From 4e7faf438430473d320125b8d9f67fe351a9db7f Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 13 Nov 2026 22:58:12 +0000 Subject: [PATCH] Close maintenance M002/M003 and add snp organize. Share backup copy policy and diagnostic vocabulary across maintenance paths, and expose folder/favorite writes via organize. Co-authored-by: Cursor --- CHANGELOG.md | 32 ++ Cargo.toml | 10 + architecture/cli.md | 11 +- architecture/commands/doctor_cmd.md | 14 +- architecture/commands/organize_cmd.md | 66 +++ architecture/commands/repair_cmd.md | 23 +- architecture/commands/validate_cmd.md | 40 +- architecture/diagnostics.md | 2 + architecture/library.md | 37 +- architecture/overview.md | 2 + architecture/sort.md | 3 +- architecture/utils/atomic.md | 11 +- docs/COMMANDS.md | 20 + docs/COMMAND_CONTRACTS.md | 7 +- docs/JSON_SCHEMAS.md | 21 + docs/USER_GUIDE.md | 16 + .../maintenance-consolidation/002-status.md | 114 ++++ .../maintenance-consolidation/003-status.md | 80 +++ .../snippet-crud-surface/002-status.md | 80 +++ ...-backup-and-snapshot-policy-convergence.md | 2 +- .../003-diagnostic-vocabulary-unification.md | 2 +- .../002-folder-and-favorite-write-path.md | 2 +- plans/registry.md | 23 +- .../maintenance-consolidation-roadmap.md | 6 +- .../snippet-crud-surface-roadmap.md | 2 +- src/commands/backup_archive.rs | 58 +- src/commands/doctor_cmd.rs | 116 ++-- src/commands/import_cmd.rs | 4 +- src/commands/mod.rs | 264 ++++++++- src/commands/organize_cmd.rs | 513 +++++++++++++++++ src/commands/pet_analysis.rs | 28 +- src/commands/repair_cmd.rs | 530 +++++++++++------- src/commands/restore_cmd.rs | 81 +-- src/commands/validate_cmd.rs | 333 ++++++----- src/config/sync_settings.rs | 4 +- src/diagnostics.rs | 228 +++++++- src/lib.rs | 8 + src/library/manager.rs | 41 +- src/library/model.rs | 29 + src/library/persistence.rs | 49 +- src/library/tests.rs | 24 + src/main.rs | 24 +- src/usage.rs | 2 +- src/utils/atomic.rs | 216 +++++++ tests/architecture.rs | 152 +++++ tests/backup_copy_policy.rs | 236 ++++++++ tests/cli_surface_compat.rs | 34 ++ tests/diagnostic_output_stability.rs | 132 +++++ tests/diagnostic_vocabulary_agreement.rs | 202 +++++++ 49 files changed, 3286 insertions(+), 648 deletions(-) create mode 100644 architecture/commands/organize_cmd.md create mode 100644 plans/closure/maintenance-consolidation/002-status.md create mode 100644 plans/closure/maintenance-consolidation/003-status.md create mode 100644 plans/closure/snippet-crud-surface/002-status.md create mode 100644 src/commands/organize_cmd.rs create mode 100644 tests/backup_copy_policy.rs create mode 100644 tests/diagnostic_output_stability.rs create mode 100644 tests/diagnostic_vocabulary_agreement.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index f9b43143..6239219f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **`snp organize` — non-interactive folder and favorite updates.** A shared + `update_snippet_fields` primitive mirrors the M001 delete sequence for the + local-only `folders` and `favorite` fields. `snp organize` (alias `o`) and + `snp data organize` resolve one target through the mutating selector, support + `--favorite`, `--unfavorite`, `--add-folder`, and `--remove-folder`, and emit + `--json` with `status` `updated` or `unchanged`. + +### Changed + +- **Shared diagnostic vocabulary and library scan (behavior-preserving).** + `validate`, `doctor`, and `repair` now share `DiagnosticSeverity`, + `DiagnosticCode`, and `DiagnosticRepairability` in `src/diagnostics.rs`, plus + `LibraryManager::scan_libraries()` for side-effect-free discovery. No diagnostic + code, message, exit code, or JSON output shape changed. +- **Shared backup copy policy.** Every snapshot, backup, and rollback-point path + now uses one copy primitive in `src/utils/atomic.rs`: symlink sources, + non-regular sources, and sources that resolve outside the configuration + directory are refused (the refusal names the path), and produced material is + fsynced under `Durability::DurableUserData`. +- **`snp repair --apply` refuses unsafe backup sources.** When the configuration + directory contains a symlinked or non-regular library file, repair fails with + exit code 1 before applying any fix, instead of silently copying the symlink + target into the pre-repair backup. +- **`snp restore` refuses unsafe pre-restore sources.** A symlinked or + non-regular library file aborts the restore before any live configuration is + modified (exit code 1), instead of skipping that entry with a warning. +- **Pre-repair backups are restorable.** `snp repair --apply` now writes a + `manifest.toml` through the same writer as `snp backup`, so the repair backup + directory is a valid `snp restore` input. + ## [1.4.1] - 2026-10-25 ### Added diff --git a/Cargo.toml b/Cargo.toml index 0071ad89..f043070d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,6 +97,16 @@ name = "library_manager_contracts" path = "tests/library_manager_contracts.rs" required-features = ["test-support"] +[[test]] +name = "diagnostic_vocabulary_agreement" +path = "tests/diagnostic_vocabulary_agreement.rs" +required-features = ["test-support"] + +[[test]] +name = "diagnostic_output_stability" +path = "tests/diagnostic_output_stability.rs" +required-features = ["test-support"] + [package.metadata.docs.rs] all-features = false default-target = "x86_64-unknown-linux-gnu" diff --git a/architecture/cli.md b/architecture/cli.md index 20f7f686..0f6cda8b 100644 --- a/architecture/cli.md +++ b/architecture/cli.md @@ -229,13 +229,13 @@ Routing facts worth auditing: - **Top-level and `data` spellings share one code path.** `handle_validate` (`src/main.rs:432`), `handle_backup` (`src/main.rs:437`), `handle_restore` (`src/main.rs:449`), `handle_repair` (`src/main.rs:458`), `handle_status` - (`src/main.rs:465`), and `handle_delete` (`src/main.rs:477`) are the only - implementations; `Commands::Validate` + (`src/main.rs:465`), `handle_delete` (`src/main.rs:477`), and + `handle_organize` are the only implementations; `Commands::Validate` (`src/main.rs:845-847`), `Commands::Backup` (`src/main.rs:848-850`), `Commands::Restore` (`src/main.rs:851-853`), `Commands::Repair` (`src/main.rs:842-844`), `Commands::Status` (`src/main.rs:854-856`), `Commands::Delete` (`src/main.rs:909-911`) and all - six `DataCommands` arms (`src/main.rs:862-892`) call them. + seven `DataCommands` arms call them (including `organize`). - **Commands that own their outcome return it directly** instead of falling through to the `Ok(CliOutcome::Success)` tail at `src/main.rs:907`: `select` (`src/main.rs:632-639`), `doctor` (`src/main.rs:794-806`), @@ -249,7 +249,8 @@ Routing facts worth auditing: ### Canonical `*Args` structs One canonical Clap `*Args` struct lives beside each handler — `ValidateArgs`, -`BackupArgs`, `RestoreArgs`, `RepairArgs`, `StatusArgs`, `DeleteArgs`, plus +`BackupArgs`, `RestoreArgs`, `RepairArgs`, `StatusArgs`, `DeleteArgs`, +`OrganizeArgs`, plus `NewArgs`, `ListArgs`, `RunArgs`, `ClipArgs`, `SearchArgs`, `SelectArgs`, `EditArgs`, `GetArgs`, `DoctorArgs`, `CronArgs`, `RegisterArgs`. `src/main.rs` keeps only the `Commands` composition, runtime/signal/log setup, dispatch, and @@ -304,7 +305,7 @@ initializes file logging plus `log_startup_info()` / `log_shutdown_info()`. | `SuppressReadOnly` | `Minimal` | `restore --dry-run`, `repair --dry-run`, `import pet --dry-run` | `src/main.rs:944-962` | | `SuppressReadOnly` | `Minimal` | `data validate`, `data status`, `data backup`, `data restore --dry-run`, `data repair --dry-run` | `src/main.rs:966-981` | | `Allow` | `Logging` | `data repair`, `data restore` (non-dry-run) | `src/main.rs:982-984` | -| `Allow` | `Logging` | `new`, `run`, `clip`, `search`, `edit`, `import`, `repair`, `restore`, `premade`, `library create`, `library delete`, `library set-primary` | `src/main.rs:988-1004` | +| `Allow` | `Logging` | `new`, `run`, `clip`, `search`, `edit`, `import`, `repair`, `restore`, `delete`, `organize`, `premade`, `library create`, `library delete`, `library set-primary` | `src/main.rs` | | `SuppressExplicitSync` | `Logging` | `sync`, `cron`, `register` | `src/main.rs:1007-1010` | | `SuppressInternal` | `Logging` | `auto-sync-worker` | `src/main.rs:1013-1016` | | `SuppressConfiguration` | `Logging` | `update`, `__self-replace`, `doctor`, `completions`, `shell`, `keybindings` | `src/main.rs:1019-1029` | diff --git a/architecture/commands/doctor_cmd.md b/architecture/commands/doctor_cmd.md index bd20edb6..dac639f3 100644 --- a/architecture/commands/doctor_cmd.md +++ b/architecture/commands/doctor_cmd.md @@ -54,9 +54,10 @@ Doctor uses the `CompatibilityDiagnostic` family from `src/diagnostics.rs`, **no ```rust pub enum DiagnosticSeverity { Info, Warning, Error } +pub struct DiagnosticCode(/* validated String */); pub struct CompatibilityDiagnostic { - pub code: String, + pub code: DiagnosticCode, pub severity: DiagnosticSeverity, pub message: String, pub entry_index: Option, @@ -66,7 +67,12 @@ pub struct CompatibilityDiagnostic { } ``` -(`src/diagnostics.rs:9-38`.) There is **no generic finding DSL**: `validate`, `doctor`, and `import` each keep their own diagnostic types and their own pass/fail semantics. What they *do* share is the classification input — `LibraryManager::inspect_library_index()` and `crate::library::find_orphaned_ids` — so the commands never disagree about the underlying state. +(`src/diagnostics.rs`.) Severity and code are the shared M003 vocabulary; +`validate` also uses `DiagnosticRepairability`. Each surface still keeps its +own report type and pass/fail semantics. Classification inputs are shared — +`LibraryManager::inspect_library_index()` / `scan_libraries()` and +`crate::library::find_orphaned_ids` — so the commands never disagree about +the underlying state. Doctor's report is `DoctorReport` (`src/diagnostics.rs:106-145`), documented in `doctor_report.md`. @@ -176,10 +182,10 @@ The only temp file doctor creates is the shell-init syntax-check fixture, which |---|---| | `src/commands/doctor_cmd.rs` | This command: modes, the environment audit, file analysis, strict elevation. | | `src/commands/doctor_report.rs` | Report rendering (`DiagnosticReportFormat`, `emit_human_report`). | -| `src/diagnostics.rs` | `DoctorReport`, `CompatibilityDiagnostic`, `DiagnosticSeverity`. | +| `src/diagnostics.rs` | `DoctorReport`, `CompatibilityDiagnostic`, `DiagnosticSeverity`, `DiagnosticCode`. | | `src/commands/pet_analysis.rs` | `read_source_file`, `parse_pet_toml`, `detect_unknown_fields`, `analyze_entry`, `detect_duplicates`. | | `src/status_snapshot.rs` | `capture_snapshot` — the canonical sync status view. | -| `src/library/manager.rs` | `inspect_library_index` — the shared primary-state view. | +| `src/library/manager.rs` | `inspect_library_index` / `scan_libraries` — shared index and scan views. | | `src/commands/shell_cmd.rs` | `generate_bash` / `generate_zsh` / `generate_fish`. | | `architecture/commands/doctor_report.md` | The rendering layer. | | `architecture/diagnostics.md` | The shared diagnostic model. | diff --git a/architecture/commands/organize_cmd.md b/architecture/commands/organize_cmd.md new file mode 100644 index 00000000..ae01250d --- /dev/null +++ b/architecture/commands/organize_cmd.md @@ -0,0 +1,66 @@ +# organize_cmd — Deterministic Folder and Favorite Updates + +[← Back to Overview](../overview.md) + +## Overview + +`src/commands/organize_cmd.rs` updates a snippet's local-only `folders` and +`favorite` fields without a TUI. It resolves its target through the +**mutating** selector (`selector::resolve_selector`) and applies the shared +field-update primitive (`commands::update_snippet_fields`). + +## CLI surface + +`OrganizeArgs` (`organize_cmd.rs`), `snp organize`: + +| Flag | Type | Meaning | +|------|------|---------| +| `--id` | `Option` | Exact snippet ID (case-sensitive) | +| `--description-exact` | `Option` | Exact description (case-insensitive) | +| `--command-exact` | `Option` | Exact command text (case-insensitive) | +| `-q/--query` | `Option` | Fuzzy query | +| `-l/--library` | `Option` | One library name; `all` is refused | +| `--favorite` | bool | Set the favorite flag | +| `--unfavorite` | bool | Clear the favorite flag | +| `--add-folder ` | `Option` | Add a folder membership | +| `--remove-folder ` | `Option` | Remove a folder membership | +| `--json` | bool | Pretty `OrganizeJsonOutput` | + +Exactly one selector and exactly one action flag are required. Folder names +must be non-empty after trimming and must not contain `;` (CSV ambiguity). + +`OrganizeJsonOutput` is `{schema, status, id, description, library, favorite, +folders}` with `schema: 1` and `status` ∈ {`updated`, `unchanged`}. + +## The shared primitive + +`commands::update_snippet_fields` (`src/commands/mod.rs`) mirrors +`delete_snippet`: mutation gate, local-data lock, re-read under the lock, +lookup by identifier with `!deleted`, durable save, best-effort audit, and +auto-sync notification after commit. + +No-ops (re-setting the current favorite, adding an existing folder, removing +an absent folder) return `SnippetFieldUpdateOutcome::Unchanged` **without** +rewriting the library file. + +Audit action names: `favorite`, `unfavorite`, `add-folder`, `remove-folder`. + +## Outcomes and exit codes + +| Situation | stdout | stderr | Exit | +|-----------|--------|--------|------| +| Updated / unchanged | result document | – | 0 | +| Ambiguous selector | – | candidates | 5 | +| Not found | – | diagnostic | 3 | +| Usage (selector, action, folder name) | – | diagnostic | 2 | +| Operational failure | – | diagnostic | 1 | + +There is no exit 9 analogue: an unchanged end state succeeds with +`status: "unchanged"`. + +## Related modules + +- `src/commands/mod.rs` — `update_snippet_fields`, `SnippetFieldMutation` +- `src/selector.rs` — mutating resolution +- `src/library/model.rs` — `folders` / `favorite` serde rules +- `docs/JSON_SCHEMAS.md` — `--json` envelope diff --git a/architecture/commands/repair_cmd.md b/architecture/commands/repair_cmd.md index ec6f2083..39bcc668 100644 --- a/architecture/commands/repair_cmd.md +++ b/architecture/commands/repair_cmd.md @@ -82,7 +82,7 @@ pub enum RepairAction { | `config` | `LibraryManager::new()` failed, or a library file failed to parse (`repair_cmd.rs:271-283`, `:373-385`) | `false` | Reported, never auto-applied. | | `ids` | snippet with empty ID, or duplicate ID across libraries (`:324-352`) | `false` | Reported only — `apply_repair` cannot execute `RepairSnippetIds` either, see [Gotchas](#gotchas). | | `timestamps` | `created_at == 0` or `updated_at == 0` (`:355-371`) | `false` | Same caveat as `ids`. | -| `primary` | primary library missing its file, or no primary set (`:392-432`) | `false` | Uses the shared `LibraryManager::inspect_library_index()` so `repair` and `validate` classify the primary state identically. | +| `primary` | primary library missing its file, or no primary set | `false` | Uses the shared `LibraryManager::scan_libraries()` so `repair` and `validate` classify the primary state identically. | | `usage` | orphaned usage entries (`:444-453`) | `true` | Count comes from `crate::library::find_orphaned_ids`, the same classifier `validate` uses. | | `transaction` | interrupted or legacy journals (`:461-588`) | `true` | Recovered via `crate::transaction::recover_transaction_by_id`. | | `unsafe` | corrupt journals, unsafe artifacts, `Failed` transactions (`:466-481`, `:487-505`, `:535-552`) | `false` | Reported only; the operator must inspect the journal and artifacts manually. | @@ -134,9 +134,11 @@ The report is emitted **exactly once**, after all work is complete, so JSON coun usage.toml # copy of the usage index ``` -The backup is a **plain recursive copy** (`copy_dir_recursive`, `:908-926`) — not a manifest-backed `snp backup` snapshot, and not a transaction. It is therefore **not** restorable by `snp restore` (which requires a `manifest.toml`); it is a manual escape hatch. - -Note that `libraries.toml` and `usage.toml` copies use `let _ = fs::copy(...)` — a **copy failure is silently ignored** (`:895`, `:901`). +The backup is a **manifest-backed snapshot** written through the same +`atomic_write_backup` path as `snp backup`, using the shared +`read_copy_source` / `copy_file` admission half. Symlink, non-regular, and +out-of-root sources fail the repair before any mutation. The directory name +keeps the `repair--` shape and is restorable by `snp restore`. ## `apply_repair` — what each action actually does @@ -218,7 +220,7 @@ pub enum RepairExitStatus { |---|---| | `src/commands/repair_cmd.rs` | This command: item collection, apply logic, backup, report, exit status. | | `src/transaction.rs` | `scan_transaction_journals`, `classify_journal_recovery`, `recover_transaction_by_id`. | -| `src/library/manager.rs` | `inspect_library_index` — the shared primary-state classifier. | +| `src/library/manager.rs` | `scan_libraries` — the shared library scan (sources ∪ orphans ∪ primary). | | `src/library/persistence.rs` | `find_orphaned_ids` / usage classifier used for the orphan count. | | `src/usage.rs` | `UsageIndex` load / prune / save. | | `architecture/persistence.md` | Journal states, recovery classes, lock hierarchy. | @@ -230,7 +232,12 @@ pub enum RepairExitStatus { - The report is emitted exactly once, after all work completes. - A pre-repair backup of `libraries/`, `libraries.toml`, and `usage.toml` is taken before any repair is applied. - Orphaned artifact deletion is containment-checked against `/.transaction/artifacts/` and rejects symlinks (`repair_cmd.rs:688-708`). -- Primary-state and orphan-usage classification are **shared** with `validate` and `doctor` via `inspect_library_index` and `find_orphaned_ids`, so the three commands never disagree about what "orphaned" or "no primary" means. +- Primary-state and orphan-usage classification are **shared** with `validate` + and `doctor` via `scan_libraries` / `inspect_library_index` and + `find_orphaned_ids`, so the three commands never disagree about what + "orphaned" or "no primary" means. Repair also carries internal + `DiagnosticSeverity` / `DiagnosticCode` / `DiagnosticRepairability` on each + item while preserving the existing JSON `category` / `safe` envelope. - The exit code distinguishes "found unsafe work" (`10`) from "usage error" (`2`) and from "some repairs failed" (`1`). ## Gotchas @@ -240,7 +247,7 @@ pub enum RepairExitStatus { - The `safe` **field on the item** is what `--apply` filters on (`repair_cmd.rs:200`); `RepairAction::is_safe()` is a separate, unused helper (`:98-110`). Do not assume the enum method drives the filter. - **`FindingsSafe` is not `UnsafeOnly`.** A report-only run whose findings are all safe exits `0` with `FindingsSafe`; only a run that finds at least one unsafe finding exits `10` (`repair_cmd.rs:243-252`, `src/main.rs:401-414`). - `snp repair` does **not** hold the local-data lock for the whole run, and it takes no transaction lock for the non-transaction actions. It can therefore run concurrently with a `snp backup` snapshot; only the individual actions take their own locks. -- The pre-repair backup is **not** a `snp backup` snapshot: it has no `manifest.toml` and cannot be restored with `snp restore`. -- `libraries.toml` / `usage.toml` copy failures in the pre-repair backup are swallowed (`repair_cmd.rs:895`, `:901`). +- The pre-repair backup carries a `manifest.toml` and is restorable by `snp restore`. +- Symlink / non-regular / escaped sources refuse the repair with exit code 1 before any fix is applied. - `--library` restricts only the **library-level** checks. Transaction and orphan-artifact repairs always run against the whole transaction directory. - A corrupt journal is reported as `unsafe` with the fix "Requires manual quarantine or deletion" (`repair_cmd.rs:466-481`) — repair will not delete a corrupt journal for you. diff --git a/architecture/commands/validate_cmd.md b/architecture/commands/validate_cmd.md index 7d6828a1..66dade8a 100644 --- a/architecture/commands/validate_cmd.md +++ b/architecture/commands/validate_cmd.md @@ -33,18 +33,19 @@ pub struct ValidateArgs { ## The diagnostic model ```rust -pub enum Severity { Info, Warning, Error } - -pub enum Repairability { Auto, Manual, Unrepairable } +// Shared vocabulary — src/diagnostics.rs +pub enum DiagnosticSeverity { Info, Warning, Error } +pub enum DiagnosticRepairability { Auto, Manual, Unrepairable } +pub struct DiagnosticCode(/* validated String */); pub struct ValidationDiagnostic { - pub code: String, - pub severity: Severity, + pub code: DiagnosticCode, + pub severity: DiagnosticSeverity, pub path: Option, pub library: Option, pub snippet_id: Option, pub message: String, - pub repairability: Repairability, + pub repairability: DiagnosticRepairability, } pub struct ValidationReport { @@ -58,9 +59,13 @@ pub struct ValidationReport { } ``` -(`src/commands/validate_cmd.rs:30-68`.) `schema_version` is `"1.0.0"`, `dry_run` is always `true`, and `tool_version` comes from `crate::diagnostics::version()`. - -There is **no generic finding DSL** shared with `doctor` or `import`. `validate` owns `Severity` / `Repairability` / `ValidationDiagnostic` / `ValidationReport`; `doctor` and `import` own the separate `DiagnosticSeverity` / `CompatibilityDiagnostic` / `DoctorReport` / `PetImportReport` family in `src/diagnostics.rs`. Each consumer keeps its own semantics; only the *classification inputs* are shared (see [Shared classifiers](#shared-classifiers)). +`schema_version` is `"1.0.0"`, `dry_run` is always `true`, and `tool_version` +comes from `crate::diagnostics::version()`. Severity, code, and repairability +are the shared M003 vocabulary in `src/diagnostics.rs`. `validate` still owns +`ValidationDiagnostic` / `ValidationReport` (its report envelope); `doctor` / +`import` keep `CompatibilityDiagnostic` / `DoctorReport`. Classification and +library enumeration share `LibraryManager::scan_libraries()` → `LibraryScan` +(see [Shared classifiers](#shared-classifiers)). ## Check categories @@ -111,7 +116,7 @@ Unix only. Checks `snippets.toml`, `libraries.toml`, `sync.toml`, and `usage.tom ### 1. Global warning elevation -After all checks run, the following warning codes are rewritten to `Severity::Error` (`validate_cmd.rs:706-719`): +After all checks run, the following warning codes are rewritten to `DiagnosticSeverity::Error`: ```rust const STRICT_CODES: &[&str] = &[ @@ -134,7 +139,8 @@ Strict mode therefore changes the **exit code**: warnings in the elevated set tu | Shared input | Used by | Where | |---|---|---| -| `LibraryManager::inspect_library_index()` → `LibraryIndexInspection` (missing files, orphan files, `PrimaryState`) | `validate`, `repair`, `doctor` | `validate_cmd.rs:375`, `repair_cmd.rs:392`, `doctor_cmd.rs:563` | +| `LibraryManager::scan_libraries()` → `LibraryScan` (sources ∪ missing ∪ orphans ∪ primary) | `validate`, `repair` | `validate_cmd.rs` (full scan); `repair_cmd.rs` (full scan) | +| `LibraryManager::inspect_library_index()` → `LibraryIndexInspection` (subset: missing/orphan/primary) | `doctor`, `status` | `doctor_cmd.rs` (primary only); status snapshot | | `crate::library::find_orphaned_ids(active_ids, usage_ids)` | `validate`, `repair` | `validate_cmd.rs:517`, `repair_cmd.rs:443` | | `crate::library::readonly_library_sources(...)` | `validate` | `validate_cmd.rs:677-688`, `:471` | @@ -155,7 +161,8 @@ The second sentence is **aspirational, not actual** — `LibraryManager::new()` Concretely, for snippet data: - Library discovery goes through `crate::library::readonly_library_sources(...)` (`validate_cmd.rs:677-688`), **not** `resolve_selector`. The mutating resolver runs `ensure_library_mode()`, which can migrate and rewrite metadata — using it here would reintroduce recovery side effects into a read-only command. -- The index cross-check uses `LibraryManager::inspect_library_index()`, a read-only inspection. +- The index cross-check uses `LibraryManager::scan_libraries()`, a read-only + scan that includes index sources and on-disk orphan files. - `UsageIndex::load()` is a read. - The report declares `dry_run: true` unconditionally (`validate_cmd.rs:76`). - The command **never** calls `gate_mutation_on_interrupted_transactions()` and never takes the local-data or transaction lock — it does not mutate, so it needs neither. @@ -184,8 +191,8 @@ Exit outcome (`validate_cmd.rs:731-736`): | Condition | Outcome | Exit code | |---|---|---| -| No `Severity::Error` diagnostics | `CliOutcome::Success` | `0` | -| At least one `Severity::Error` diagnostic | `CliOutcome::ValidationFailed` | `6` (`VALIDATION_FAILED`, `src/outcome.rs:62`) | +| No `DiagnosticSeverity::Error` diagnostics | `CliOutcome::Success` | `0` | +| At least one `DiagnosticSeverity::Error` diagnostic | `CliOutcome::ValidationFailed` | `6` (`VALIDATION_FAILED`, `src/outcome.rs:62`) | Because `--strict` elevates warnings to errors, `--strict` can turn exit `0` into exit `6`. @@ -204,7 +211,8 @@ Because `--strict` elevates warnings to errors, `--strict` can turn exit `0` int | Path | Role | |---|---| | `src/commands/validate_cmd.rs` | This command: check implementations, report model, exit mapping. | -| `src/library/manager.rs` | `LibraryManager::inspect_library_index` — the shared index view. | +| `src/library/manager.rs` | `LibraryManager::scan_libraries` — the shared library scan. | +| `src/diagnostics.rs` | Shared `DiagnosticSeverity` / `DiagnosticCode` / `DiagnosticRepairability`. | | `src/library/mod.rs` | `readonly_library_sources`, `find_orphaned_ids`. | | `src/usage.rs` | `UsageIndex::load` — the usage index read. | | `src/commands/repair_cmd.md` | The command that acts on some of these findings. | @@ -227,5 +235,5 @@ Because `--strict` elevates warnings to errors, `--strict` can turn exit `0` int - `W-CORRUPT-BAK` is reported for a **leftover** `.toml.corrupt.bak` file. It is a historical signal, not a live parse failure — the live failure would be `E-TOML-PARSE`. - `W-LIB-UNREADABLE` and `W-LIB-INDEX-UNREADABLE` mean the orphan-usage check was **partially or wholly skipped**. The report does not record "check skipped" as a separate flag; the diagnostic *is* the signal. - `W-SAME-ID-DIVERGENT` and `W-DUP-CHECK-SKIPPED` are mutually exclusive: if the raw re-parse fails you get the latter instead of the former. -- `Severity::Error` is what drives exit `6`; `Repairability::Auto` does **not** mean `snp repair --apply` will fix it — see `repair_cmd.md` for the cases where a safe-marked item still fails to apply. +- `DiagnosticSeverity::Error` is what drives exit `6`; `DiagnosticRepairability::Auto` does **not** mean `snp repair --apply` will fix it — see `repair_cmd.md` for the cases where a safe-marked item still fails to apply. - The permission check only looks at **four specific files** in the config directory. Library files under `libraries/` are not permission-checked. diff --git a/architecture/diagnostics.md b/architecture/diagnostics.md index 3768d43a..4402ada9 100644 --- a/architecture/diagnostics.md +++ b/architecture/diagnostics.md @@ -26,6 +26,8 @@ sync/auto-sync state machine ([sync.md](sync.md), ## Key Types (`src/diagnostics.rs`) +Shared vocabulary (M003): [`DiagnosticSeverity`](../../src/diagnostics.rs), [`DiagnosticCode`](../../src/diagnostics.rs) (validated `E-`/`W-`/`I-`, `compat.*`, `sync.*`), and [`DiagnosticRepairability`](../../src/diagnostics.rs). Report envelopes (`ValidationReport`, `DoctorReport`, repair `JsonRepairItem`) remain per-surface. + | Type | Location | Shape | |------|----------|-------| | `DiagnosticSeverity` | `:11` | `Info` (informational) / `Warning` (recoverable; imported with changes) / `Error` (cannot proceed safely) — serde round-trips | diff --git a/architecture/library.md b/architecture/library.md index d8f3065b..e0d89920 100644 --- a/architecture/library.md +++ b/architecture/library.md @@ -9,7 +9,8 @@ The library module is the core data layer of snip-it. It defines the ID repair, timestamped backups, single-file → multi-library migration, and the `LibraryManager` registry. It also owns the canonical side-effect-free read path (`resolve_readonly_sources`, -`inspect_library_index`) shared by CLI, MCP, and diagnostics. +`inspect_library_index`, `scan_libraries`) shared by CLI, MCP, and +diagnostics. **Files**: `src/library/mod.rs` (re-exports), `src/library/model.rs` (types + pure helpers), `src/library/persistence.rs` (load/save/backup), @@ -108,13 +109,21 @@ pub struct LibraryIndexInspection { pub orphan_files: Vec, pub primary: PrimaryState, } + +pub struct LibraryScan { + pub sources: Vec, + pub missing_files: Vec<(String, PathBuf)>, + pub orphan_files: Vec, + pub primary: PrimaryState, +} ``` `ResolvedLibrarySource` is constructed **without** migration, directory -creation, or metadata rewrites (`model.rs:105-111`). `PrimaryState` and -`LibraryIndexInspection` are a shared read-only view: `doctor`, `validate`, -`repair`, and `status` each render it into their own diagnostic types -(`model.rs:135-139`). +creation, or metadata rewrites. `PrimaryState` and +`LibraryIndexInspection` are a shared read-only index view; `LibraryScan` +adds index-driven `sources` so `validate` and `repair` share one +enumeration (sources ∪ orphans ∪ missing ∪ primary) without a second +`read_dir`. ### Pure helpers — `src/library/model.rs:150-225` @@ -405,12 +414,14 @@ used by `snp list`), `selector::resolve_selector_readonly()` (`snp get`), MCP ### Index inspection ```rust -pub fn inspect_library_index(&self) -> LibraryIndexInspection // manager.rs:310 +pub fn inspect_library_index(&self) -> LibraryIndexInspection +pub fn scan_libraries(&self) -> SnipResult ``` -Existence checks + directory listing only. `doctor`, `validate`, `repair`, -`status` render this shared state into their own diagnostic types; no -generic finding DSL was introduced (`manager.rs:304-310`). +Existence checks + one directory listing. `inspect_library_index` is the +narrow index view (`doctor` / `status`); `scan_libraries` is the full +diagnostic scan (`validate` / `repair`). Each surface still renders into +its own report types — no generic finding DSL. ### CRUD and linkage @@ -460,8 +471,8 @@ without mutating process-wide environment variables. | `device_id` | Yes | Conflict-resolution input; not searchable | | `deleted` | Yes | Soft-delete tombstone; deletion beats live content | | `output` | **No** | Local-only notes. Not in `ProtoSnippet`; not searchable | -| `folders` | **No** | Local-only organization. Not searchable | -| `favorite` | **No** | Local-only starred flag. Not searchable | +| `folders` | **No** | Local-only organization. Not searchable; writable via `snp organize` | +| `favorite` | **No** | Local-only starred flag. Not searchable; writable via `snp organize` | `output` / `folders` / `favorite` are excluded from the sync fingerprint. `output` is not part of `ProtoSnippet` at all, and `snp edit --output` @@ -493,9 +504,9 @@ cross-library scope keyword in | File | Role | |------|------| | `src/library/mod.rs` | Module root; re-exports `model`, `persistence`, `manager` so the pre-split `crate::library::*` paths keep working (`mod.rs:31-40`) | -| `src/library/model.rs` | `Snippet`, `Snippets`, `LibraryConfig`, `LibraryMeta`, `ResolvedLibrarySource`, `PrimaryState`, `LibraryIndexInspection`, and the pure helpers `library_not_found` / `find_orphaned_ids` / `validate_library_name` | +| `src/library/model.rs` | `Snippet`, `Snippets`, `LibraryConfig`, `LibraryMeta`, `ResolvedLibrarySource`, `PrimaryState`, `LibraryIndexInspection`, `LibraryScan`, and the pure helpers `library_not_found` / `find_orphaned_ids` / `validate_library_name` | | `src/library/persistence.rs` | `load_library`, `save_library`, `save_library_internal`, `backup_library`, `normalize_snippet_ids`, `deterministic_legacy_id`, `deterministic_duplicate_id` | -| `src/library/manager.rs` | `LibraryManager` registry/primary behavior, `ensure_library_mode`, and the canonical read-only resolver `resolve_readonly_sources` / `readonly_library_sources` | +| `src/library/manager.rs` | `LibraryManager` registry/primary behavior, `ensure_library_mode`, `resolve_readonly_sources` / `readonly_library_sources`, `inspect_library_index`, `scan_libraries` | | `src/library/tests.rs` | 97 in-crate unit tests: round-trip, `pet` compatibility, ID normalization, name validation | | `src/utils/atomic.rs` | `write_private_atomic` / `atomic_replace` — the write primitives the save path uses | | `src/utils/config.rs` | `get_config_dir`, `derive_sync_state_dir`, and the `#[cfg(test)]` `ScopedConfigDir` override | diff --git a/architecture/overview.md b/architecture/overview.md index 34de582e..a26a5d61 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -252,6 +252,7 @@ functions in `main.rs` keep both spellings identical. | Select | `src/commands/select_cmd.rs` | non-executing selection for shell integration | [commands/select_cmd.md](commands/select_cmd.md) | | Get | `src/commands/get_cmd.rs` | deterministic non-TUI retrieval | [commands/get_cmd.md](commands/get_cmd.md) | | Delete | `src/commands/delete_cmd.rs` | deterministic non-TUI snippet delete | [commands/delete_cmd.md](commands/delete_cmd.md) | +| Organize | `src/commands/organize_cmd.rs` | folder and favorite write path | [commands/organize_cmd.md](commands/organize_cmd.md) | | Validate | `src/commands/validate_cmd.rs` | read-only data validation | [commands/validate_cmd.md](commands/validate_cmd.md) | | Repair | `src/commands/repair_cmd.rs` | conservative, backed-up, idempotent repair | [commands/repair_cmd.md](commands/repair_cmd.md) | | Restore | `src/commands/restore_cmd.rs` | restore from a backup snapshot | [commands/restore_cmd.md](commands/restore_cmd.md) | @@ -873,6 +874,7 @@ touching, then the "Gotchas" section at its end — that is where the traps live | [commands/list_cmd.md](commands/list_cmd.md) | Text-based snippet listing | | [commands/get_cmd.md](commands/get_cmd.md) | Deterministic non-TUI retrieval | | [commands/delete_cmd.md](commands/delete_cmd.md) | Deterministic non-TUI snippet delete | +| [commands/organize_cmd.md](commands/organize_cmd.md) | Folder and favorite write path | | [commands/search_cmd.md](commands/search_cmd.md) | Fuzzy search with detail display | | [commands/select_cmd.md](commands/select_cmd.md) | Non-executing selection | | [commands/run_cmd.md](commands/run_cmd.md) | TUI selection + shell execution | diff --git a/architecture/sort.md b/architecture/sort.md index 36e3ec23..1db610ad 100644 --- a/architecture/sort.md +++ b/architecture/sort.md @@ -285,7 +285,8 @@ The TUI comparator short-circuits entirely when there is nothing to sort by: there are no scores to sort on. - `favorites_first` is `false` for both MCP search and the selector's fuzzy path. Only `snp list --favorites-first` (`src/commands/list_cmd.rs:30-31`) - and the TUI turn it on — `snp search --favorites-first` + and the TUI turn it on — scripts can set the underlying flag with + `snp organize --favorite` before sorting. `snp search --favorites-first` (`src/commands/search_cmd.rs:19-20`) reaches the TUI comparator, not `rank_snippets`. - The TUI and the CLI do **not** produce identical orders for the same data; diff --git a/architecture/utils/atomic.md b/architecture/utils/atomic.md index 209aa5d7..d24085b5 100644 --- a/architecture/utils/atomic.md +++ b/architecture/utils/atomic.md @@ -20,7 +20,7 @@ the transaction journal, the lock hierarchy, or the TOML fidelity rules — see | Item | Kind | Line | Role | |------|------|------|------| -| `Durability` | enum | `src/utils/atomic.rs:23` | The four durability classes | +| `Durability` | enum | `src/utils/atomic.rs:23` | The three durability classes | | `AtomicWriteOptions` | struct | `src/utils/atomic.rs:39` | Durability + permission + symlink policy | | `AtomicWriteOptions::for_durability` | fn | `src/utils/atomic.rs:54` | Default options for a class | | `AtomicWriteOptions::preserve_permissions` | fn | `src/utils/atomic.rs:64` | Builder setter | @@ -29,8 +29,13 @@ the transaction journal, the lock hierarchy, or the TOML fidelity rules — see | `write_private_atomic` | fn | `src/utils/atomic.rs:305` | Simple atomic write of a string | | `atomic_replace` | fn | `src/utils/atomic.rs:376` | Durability-aware atomic replace | | `atomic_write_bytes` | fn | `src/utils/atomic.rs:474` | Convenience wrapper over `atomic_replace` | -| `hex_encode` | fn | `src/utils/atomic.rs:484` | Lowercase hex digest encoding | -| `hash_file` | fn | `src/utils/atomic.rs:501` | Canonical SHA-256 hex digest of a file | +| `CopySourcePolicy` | enum | `src/utils/atomic.rs` | Source admission: contained or regular-file-only | +| `CopyOptions` | struct | `src/utils/atomic.rs` | Source policy + durability for copies | +| `read_copy_source` | fn | `src/utils/atomic.rs` | Admit and read a copy source (symlink/non-regular refused) | +| `copy_file` | fn | `src/utils/atomic.rs` | Admit source then land via `atomic_replace` | +| `forensic_copy_aside` | fn | `src/utils/atomic.rs` | Best-effort corrupt-file sibling copy | +| `hex_encode` | fn | `src/utils/atomic.rs` | Lowercase hex digest encoding | +| `hash_file` | fn | `src/utils/atomic.rs` | Canonical SHA-256 hex digest of a file | --- diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 7d29c54f..f9263bfa 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -39,6 +39,7 @@ snippet can exit with a code other than 8 — see | `snp list` | `l` | List snippets. Never executes anything. `--json` / `--csv` for machine output. | | `snp get` | — | Retrieve one snippet deterministically. No TUI, no execution. The scripting entry point. | | `snp delete` | — | Tombstone one snippet deterministically. No TUI, no prompt. | +| `snp organize` | `o` | Set or clear `favorite` and add or remove folder memberships. No TUI. | | `snp run` | `r` | Pick a snippet in the TUI and execute it through your shell. | | `snp clip` | `c` | Pick a snippet in the TUI and copy it to the clipboard. | | `snp search` | `s` | Fuzzy-search snippets in the TUI. | @@ -121,6 +122,24 @@ The delete is a tombstone, not a removal: the snippet keeps its identifier and its `updated_at` advances past the live version, so the tombstone still syncs and still wins over live content in a merge. +## Organizing snippets (`favorite` and `folders`) + +`snp organize` updates local-only organization fields on one snippet. It uses +the same selector contract as `snp delete` and the same ambiguity and not-found +rules. + +| Flag | Effect | +|------|--------| +| `--favorite` | Set `favorite = true`. | +| `--unfavorite` | Set `favorite = false`. | +| `--add-folder ` | Append a folder membership (non-empty, no `;`). | +| `--remove-folder ` | Remove a folder membership. | + +Exactly one selector and exactly one action flag are required. +`--library all` is refused. `--json` emits +`{schema, status, id, description, library, favorite, folders}` where +`status` is `updated` or `unchanged` (both exit 0). + ## Libraries | Command | What it does | @@ -218,6 +237,7 @@ spellings stay equivalent. | `snp data repair` | `snp repair` | | `snp data status` | `snp status` | | `snp data delete` | `snp delete` | +| `snp data organize` | `snp organize` | ## Self-update diff --git a/docs/COMMAND_CONTRACTS.md b/docs/COMMAND_CONTRACTS.md index a5d0ce17..1b61a957 100644 --- a/docs/COMMAND_CONTRACTS.md +++ b/docs/COMMAND_CONTRACTS.md @@ -20,6 +20,7 @@ | `edit` | Yes (`$EDITOR`) or No (`--output`) | Yes (`--output-stdin`) | No | Yes | Yes (`$EDITOR`) | Yes | No | Yes (`$EDITOR`) | No | None | 0, 1, 2, 3, 5 | | `get` | No | No | Yes | Yes | No | No | No | No | No | `--json`, `--raw`, `--field` | 0, 1, 2, 3, 5 | | `delete` | No | No | Yes | Yes | No | Yes | No | No | No | `--json` | 0, 1, 2, 3, 5, 9 | +| `organize` | No | No | Yes | Yes | No | Yes | No | No | No | `--json` | 0, 1, 2, 3, 5 | | `status` | No | No | Yes | Yes | No | No | No | No | No | `--json` | 0, 1 | | `validate` | No | No | Yes | Yes | No | No | No | No | No | `--json` | 0, 1, 6 | | `doctor` | No | No | Yes | Yes | No | No | No | Yes (diagnostic probes) | No | `--report json` | 0, 1, 6 | @@ -41,7 +42,7 @@ | `data` | — | — | — | — | — | — | — | — | — | — | — | `snp data ` is a **mirror spelling** of the top-level commands -(`validate`, `status`, `backup`, `restore`, `repair`, `delete`); it has no +(`validate`, `status`, `backup`, `restore`, `repair`, `delete`, `organize`); it has no independent contract. `auto-sync-worker` and `__self-replace` are internal/replace subprocesses and are not user-facing contracts. @@ -98,7 +99,7 @@ spellings and is classified in the same table. |--------|----------| | `SuppressReadOnly` (also `StartupServices::Minimal`) | `version`, `list`, `select`, `status`, `mcp`, `get`, `validate`, `backup`, `library list`, `library show` | | `SuppressReadOnly` (dry-run variants only) | `restore --mode dry-run`, `repair --dry-run`, `import pet --dry-run` — plus `snp data restore --mode dry-run` and `snp data repair --dry-run` (there is no `snp data import`) | -| `Allow` (also `StartupServices::Logging`) | `new`, `run`, `clip`, `search`, `edit`, `import`, `repair`, `restore`, `delete`, `premade`, `library create`, `library delete`, `library set-primary`; also **no subcommand** (default TUI) | +| `Allow` (also `StartupServices::Logging`) | `new`, `run`, `clip`, `search`, `edit`, `import`, `repair`, `restore`, `delete`, `organize`, `premade`, `library create`, `library delete`, `library set-primary`; also **no subcommand** (default TUI) | | `SuppressExplicitSync` | `sync`, `cron`, `register` | | `SuppressInternal` | `auto-sync-worker` (internal subprocess) | | `SuppressConfiguration` | `update`, `__self-replace`, `doctor`, `completions`, `shell`, `keybindings` | @@ -121,6 +122,6 @@ Dry-run variants are classified by their **flag**, not by their command category - **`ExecutionFailed`** exit code: if the child process had a valid exit code, that code is propagated; otherwise exit code 8 is used. - **`PersistenceFailed`** maps to exit code 1 (general error) — no dedicated public exit code for persistence failures. - **Exit 4 (cancelled)** comes only from `snp select`. `run`, `clip`, and `search` treat a cancelled TUI selection as normal completion (exit 0). -- **Exit 5 (ambiguous)** comes only from the exact-selector paths: `run`, `clip`, and `edit` with `--id` / `--description-exact` / `--command-exact`, and from `snp get` and `snp delete`. The interactive TUI resolves ambiguity in-terminal instead. +- **Exit 5 (ambiguous)** comes only from the exact-selector paths: `run`, `clip`, and `edit` with `--id` / `--description-exact` / `--command-exact`, and from `snp get`, `snp delete`, and `snp organize`. The interactive TUI resolves ambiguity in-terminal instead. - **Exit 6 (validation failure)** comes from `snp validate`, `snp doctor`, and `snp sync discard-pending` (corrupt pending state). Exit **9 (conflict/refused)** comes from `snp sync discard-pending` and from `snp delete` (the target is already tombstoned). - **Exit 7 (sync failure)** is reserved but currently unreachable — no command constructs `CliOutcome::SyncFailed`; sync failures surface as exit 1. diff --git a/docs/JSON_SCHEMAS.md b/docs/JSON_SCHEMAS.md index 98b903c0..0ffd5027 100644 --- a/docs/JSON_SCHEMAS.md +++ b/docs/JSON_SCHEMAS.md @@ -124,6 +124,27 @@ snippet ID. Within a single library the two orders coincide. --- +## `organize --json` + +```json +{ + "schema": 1, + "status": "updated", + "id": "string", + "description": "string", + "library": "string", + "favorite": true, + "folders": ["string"] +} +``` + +- `status` is `updated` when this run changed the snippet and `unchanged` when + the requested end state already held (both exit 0). +- `library` is the library filename stem. +- The document is written to stdout only when a target was identified. A + not-found target (exit 3) and an ambiguous selector (exit 5) produce no + stdout document; diagnostics go to stderr. + ## `delete --json` ```json diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 1f237605..80631f40 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -589,6 +589,7 @@ auto_sync_failure = "warn" | `snp edit --output` | No | Output is local-only, not in sync protocol | | TUI delete | Yes | After tombstone persisted | | `snp delete` | Yes | Same tombstone and notification as the TUI delete | +| `snp organize` | Yes | Local-only `favorite` and `folders` updates | | `snp import pet` (create/merge/replace) | Yes | Once per import, not per snippet | | `snp import pet --dry-run` | No | Read-only | | `snp library create` | Yes | | @@ -902,6 +903,21 @@ deleted. Nothing is deleted unless exactly one snippet matches. library, so `--library all` is refused. Add `--json` for a machine-readable result whose `status` is `deleted` or `already_deleted`. +### Scripting with `snp organize` + +`snp organize` sets the local-only `favorite` flag and folder memberships on +one snippet: + +```bash +snp organize --id "$SNIPPET_ID" --favorite +snp organize --id "$SNIPPET_ID" --add-folder work +snp organize --query 'deploy staging' --unfavorite --json +``` + +It uses the same selector and ambiguity rules as `snp delete`. Re-applying the +current state exits 0 with `status: "unchanged"` in `--json` mode and does not +rewrite the library file. `snp data organize` mirrors the command. + `snp cron` prints a cron entry and offers to copy it to the clipboard: ```bash diff --git a/plans/closure/maintenance-consolidation/002-status.md b/plans/closure/maintenance-consolidation/002-status.md new file mode 100644 index 00000000..699ec062 --- /dev/null +++ b/plans/closure/maintenance-consolidation/002-status.md @@ -0,0 +1,114 @@ +# Maintenance and Duplicate-Policy Consolidation Milestone 002 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md` + +Source subsystem roadmap: + +- `plans/subsystems/maintenance-consolidation-roadmap.md` M002 + +Repository baseline reviewed: `a603e6181367af29d1691c2a7c1bc4042610c036` + +Implementation commits or pull requests: + +- This branch `agent/eligible-plans-m002-m003` (closure commit records SHA at push). + +Primary class: invariant. + +## 1. Executive finding + +M002 is closed. One shared copy primitive in `src/utils/atomic.rs` +(`CopySourcePolicy`, `CopyOptions`, `read_copy_source`, `copy_file`, +`forensic_copy_aside`) admits sources and lands copies under +`Durability::DurableUserData`. All four backup paths and the six forensic +corrupt-file sites use it. Symlink / non-regular / out-of-root sources are +refused with the path named. The pre-repair backup is manifest-backed and +restorable by `snp restore`. A static guard rejects new production +`fs::copy` sites outside the declared allow-list. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | +|---|---|---| +| Shared copy primitive in atomic layer | `src/utils/atomic.rs` — `read_copy_source` / `copy_file` / `forensic_copy_aside` | pass | +| Claims `DurableUserData` only | Production call sites + unit test `test_copy_file_claims_durable_user_data` | pass | +| Path 1 `.bak` migrated | `src/library/persistence.rs` `backup_library`; `sync_backup_file` removed | pass | +| Path 2 `snp backup` admission | `src/commands/backup_archive.rs` `read_for_snapshot` wraps `read_copy_source` | pass | +| Path 3 repair backup restorable | `create_repair_backup` → `atomic_write_backup` + `manifest.toml`; `tests/backup_copy_policy.rs::repair_backup_is_restorable_rollback_point` | pass | +| Path 4 pre-restore hard refusal | `src/commands/restore_cmd.rs`; path4 test | pass | +| Forensic sites migrated | persistence, manager, usage, sync_settings, commands/mod | pass | +| Static `fs::copy` guard | `tests/architecture.rs::config_and_library_copies_use_shared_primitive` | pass | +| CHANGELOG behavior changes | `CHANGELOG.md` Unreleased | pass | +| Stale repair doc corrected | `architecture/commands/repair_cmd.md` | pass | + +## 3. Production implementation evidence + +**Added.** Copy admission/copy API and forensic helper in `src/utils/atomic.rs`. + +**Changed.** `backup_library`, `read_for_snapshot`, `create_repair_backup` +(manifest-backed), `create_pre_restore_backup` (hard error on bad sources), +six forensic copy sites. + +**Removed.** `sync_backup_file`, `copy_dir_recursive`, inline restore +`copy_regular_file` admission. + +## 4. Verification executed + +### Commands run (local) + +```bash +cargo test --features test-support --lib atomic::tests::test_copy +cargo test --features test-support --lib atomic::tests::test_read_copy +cargo test --features test-support --test architecture config_and_library_copies +cargo test --features test-support --test architecture fs_copy_allowlist +cargo test --features test-support --test backup_contracts +cargo test --features test-support --test backup_copy_policy -- --test-threads=1 +cargo test --features test-support --test backup_snapshot_concurrency -- --test-threads=1 +cargo test --features test-support --test repair_transactions -- --test-threads=1 +cargo test --features test-support --test restore_security -- --test-threads=1 +cargo test --features test-support --test restore_transactions -- --test-threads=1 +cargo test --features test-support --test restore_manifest_gate -- --test-threads=1 +bash scripts/ci/test-production-seams.sh +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +``` + +### Results + +All listed commands passed. `bash scripts/check.sh` reaches lib tests and +fails only on four pre-existing `commands::shell_cmd::tests::test_fish_*` +failures that also fail on clean `a603e61` without these changes (fish 3.7.0 +environment). Crash-failpoint suites were not re-run in this pass +(`restore_crash_failpoints` / `cleanup_crash_failpoints`); restore +transactions/security/manifest-gate suites covering the pre-restore path +passed. + +## 5–9. Reviews + +Invariants preserved: named durability classes unchanged; atomic landing via +`atomic_replace`; no TOML post-processing; no command/exit-code/schema +changes; `snp data` mirror unchanged. Failure semantics: partial copies never +presented as complete; symlink refusal fails closed on paths 2–4. No data +migration. Security: external symlink targets cannot enter backups. +Documentation: atomic/repair docs + CHANGELOG updated; overview durability +stale text partially addressed via atomic.md class count. + +## 10. Unresolved findings + +- **Low:** `bash scripts/check.sh` fish integration tests fail in this + environment on clean main as well; unrelated to M002. +- **Low:** crash-failpoint suites not re-run here; recommend before merge if + restore crash boundaries are a release gate. + +## 11. Roadmap disposition + +**closed.** M003 remains independently ready/active. + +## 12. Registry updates + +- Maintenance M002: `active` → `closed`. +- Dependency-ready row for M002 → `closed`. +- Unblocked audit: no registered plan was blocked on M002. diff --git a/plans/closure/maintenance-consolidation/003-status.md b/plans/closure/maintenance-consolidation/003-status.md new file mode 100644 index 00000000..2a932dd2 --- /dev/null +++ b/plans/closure/maintenance-consolidation/003-status.md @@ -0,0 +1,80 @@ +# Maintenance and Duplicate-Policy Consolidation Milestone 003 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md` + +Source subsystem roadmap: + +- `plans/subsystems/maintenance-consolidation-roadmap.md` M003 + +Repository baseline reviewed: `a603e6181367af29d1691c2a7c1bc4042610c036` + +Implementation commits or pull requests: + +- This branch `agent/eligible-plans-m002-m003`. + +Primary class: infrastructure. + +## 1. Executive finding + +M003 is closed. `validate`, `doctor`, and `repair` share one diagnostic +vocabulary (`DiagnosticSeverity`, `DiagnosticCode`, +`DiagnosticRepairability` in `src/diagnostics.rs`) and one library scan +(`LibraryManager::scan_libraries` → `LibraryScan`). Each surface keeps its +own report type and JSON envelope. Codes, messages, and exit codes are +unchanged (pinned by `tests/diagnostic_output_stability.rs`). + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | +|---|---|---| +| Shared severity/code/repairability | `src/diagnostics.rs` | pass | +| Shared library scan | `LibraryScan` / `scan_libraries` in library layer | pass | +| Surfaces consume shared scan | `validate_cmd`, `doctor_cmd`, `repair_cmd` | pass | +| No code/message/exit change | `tests/diagnostic_output_stability.rs` | pass | +| Cross-surface agreement | `tests/diagnostic_vocabulary_agreement.rs` | pass | + +## 3. Production implementation evidence + +**Added.** `DiagnosticRepairability`, validated `DiagnosticCode`, +`LibraryScan`, `scan_libraries`. + +**Changed.** validate/doctor/repair/import/pet_analysis consume shared types; +repair/validate index checks consume `LibraryScan`. + +**Test-support.** `diagnostics` module and `LibraryManager` / +`with_config_dir` gated for integration tests under `test-support`. + +## 4. Verification executed + +```bash +cargo test --features test-support --test diagnostic_vocabulary_agreement -- --test-threads=1 +cargo test --features test-support --test diagnostic_output_stability -- --test-threads=1 +cargo clippy --workspace --all-targets -- -D warnings +cargo fmt --all -- --check +``` + +All passed. Same pre-existing fish `check.sh` noise as M002. + +## 5–9. Reviews + +No exit-code, JSON schema, or diagnostic code string changes. Soft +dependency on M002 unused (no shared files). Layer rules preserved +(diagnostics stays core). + +## 10. Unresolved findings + +None milestone-blocking. + +## 11. Roadmap disposition + +**closed.** Maintenance consolidation M001–M003 complete. + +## 12. Registry updates + +- Maintenance M003: `active` → `closed`. +- Maintenance subsystem roadmap → `closed` when M002+M003 both closed. +- Unblocked audit: none blocked on M003. diff --git a/plans/closure/snippet-crud-surface/002-status.md b/plans/closure/snippet-crud-surface/002-status.md new file mode 100644 index 00000000..c3a9e3c0 --- /dev/null +++ b/plans/closure/snippet-crud-surface/002-status.md @@ -0,0 +1,80 @@ +# Snippet CRUD Surface Milestone 002 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md` + +Source subsystem roadmap: + +- `plans/subsystems/snippet-crud-surface-roadmap.md` M002 + +Repository baseline reviewed: `a603e6181367af29d1691c2a7c1bc4042610c036` + +Implementation commits or pull requests: + +- This branch `agent/eligible-plans-m002-m003`. + +Primary class: capability. + +## 1. Executive finding + +M002 is closed and demonstrated at runtime. `snp organize` (and +`snp data organize`) set/clear `favorite` and add/remove folder memberships +through a shared `update_snippet_fields` primitive shaped like +`delete_snippet`. Selectors, mutation gate, local-data lock, audit, and +auto-sync notification follow the M001 sequence. Identifiers are stable; +no-ops report `status: "unchanged"` with exit 0. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | +|---|---|---| +| Shared field-update primitive | `commands::update_snippet_fields` in `src/commands/mod.rs` | pass | +| `snp organize` + `snp data organize` | `organize_cmd.rs`, `main.rs` DataCommands + command_behavior | pass | +| Identifier stability | unit tests in `organize_cmd` | pass | +| Golden corpus survives | `golden_corpus_command_field_survives_favorite_mutation_round_trip` | pass | +| Mirror equivalence | `tests/cli_surface_compat.rs::organize_top_and_data_produce_equivalent_json` | pass | +| Docs | COMMANDS, COMMAND_CONTRACTS, JSON_SCHEMAS, organize_cmd.md, overview index | pass | + +## 3. Production implementation evidence + +**Added.** `SnippetFieldMutation` / `update_snippet_fields`, +`src/commands/organize_cmd.rs`, architecture deep dive. + +**Unchanged.** Sync fingerprint still excludes folders/favorite; MCP +read-only; delete primitive untouched; library-level `Snippets.folders` +registry untouched. + +## 4. Verification executed + +```bash +cargo test --features test-support --lib commands::organize_cmd -- --test-threads=1 +cargo test --features test-support --test cli_surface_compat organize -- --test-threads=1 +``` + +6 organize unit tests + mirror compat passed. + +## 5–9. Reviews + +Mutation gate and lock ordering preserved. Local-only fields remain +local-only. Exit codes 0/1/2/3/5 only. No Tokio init on organize path. + +## 10. Unresolved findings + +None milestone-blocking. Snippet M003 remains registered ready but still +needs plan/roadmap reconciliation before handoff (not part of this +closure). + +## 11. Roadmap disposition + +**closed.** M003 stays ready (hard on M001; plan text still claims a +build-order dependency on M002's field-update primitive — that primitive +now exists). + +## 12. Registry updates + +- Snippet CRUD M002: `active` → `closed`. +- Unblocked audit: M003's plan can now extend `update_snippet_fields`; + registry already lists M003 as ready. diff --git a/plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md b/plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md index 68a46a9a..94a9b5ff 100644 --- a/plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md +++ b/plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md @@ -1,6 +1,6 @@ # Maintenance and Duplicate-Policy Consolidation Milestone 002 — Backup and snapshot policy convergence -Status: ready +Status: implemented Repository baseline: `dca5d3136db8a216ba4fcf8bfddac9140d1029ff` diff --git a/plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md b/plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md index bd89a70c..4e5bc071 100644 --- a/plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md +++ b/plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md @@ -1,6 +1,6 @@ # Maintenance and Duplicate-Policy Consolidation Milestone 003 — Diagnostic vocabulary unification -Status: ready +Status: implemented Repository baseline: `dca5d3136db8a216ba4fcf8bfddac9140d1029ff` diff --git a/plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md b/plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md index 7f003211..65335ae4 100644 --- a/plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md +++ b/plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md @@ -1,6 +1,6 @@ # Snippet CRUD Surface Milestone 002 — Folder and favorite write path -Status: ready +Status: implemented Repository baseline: `dca5d3136db8a216ba4fcf8bfddac9140d1029ff` diff --git a/plans/registry.md b/plans/registry.md index 51dc0272..7212618c 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -42,9 +42,9 @@ maps to `closed`. | CLI, library, selector, sync-policy consolidation | complete | `plans/subsystems/cli-library-sync-consolidation-roadmap.md` | M001-M006 closed | None. M006 closed the search-parity verification gap on 2026-10-22: all three surfaces now share one match primitive, the two open behaviors are decided and pinned, and the parity suite gates the build. M001-M005 closure history unchanged. | | Local MCP integration | closed | `plans/subsystems/mcp-integration-roadmap.md` | M001 closed | None. Read-only stdio adapter with search parity and registration. | | Eggstack dependency refresh | closed | `plans/subsystems/eggstack-dependency-refresh-roadmap.md` | M001 closed | None. `eggfetch-core` and `eggserve-server`/`eggserve-primitives` adopted on their exact pins in `Cargo.toml` with zero source changes; wire/lifetime/transfer parity proven, both release artifacts byte-identical. | -| Maintenance and duplicate-policy consolidation | active | `plans/subsystems/maintenance-consolidation-roadmap.md` | M001 closed | None. M001 dead subsystem removal and documentation reconciliation landed; M002 and M003 depend on M001 and on each other only softly. | +| Maintenance and duplicate-policy consolidation | closed | `plans/subsystems/maintenance-consolidation-roadmap.md` | M001-M003 closed | None. Shared copy policy, diagnostic vocabulary, and library scan landed. | | Locking protocol and ordering convergence | active | `plans/subsystems/locking-convergence-roadmap.md` | M001 closed | None. M001 owned-record lock protocol unification landed (one shared protocol, the wait policy as a parameter); M002 kernel-lock protocol convergence; M003 ordering contract and static guard, hard on M001 and M002. | -| Snippet CRUD surface | active | `plans/subsystems/snippet-crud-surface-roadmap.md` | M001 closed | None. M001 non-interactive snippet delete landed; M002 folder and favorite write path and M003 non-interactive field update, both hard on M001. | +| Snippet CRUD surface | active | `plans/subsystems/snippet-crud-surface-roadmap.md` | M001-M002 closed | None. M002 `snp organize` landed; M003 non-interactive field update remains ready (hard on M001; extends `update_snippet_fields`). | | Sync cursor protocol | active | `plans/subsystems/sync-cursor-protocol-roadmap.md` | M001 conditionally closed (condition discharged by M002); M002 closed | Implements `plans/adrs/ADR-0001-sync-delta-cursor.md` Option A. The coordinated `snip-proto` 0.1.4 / `snip-sync` 0.1.8 / `snip-it` 1.4.1 version bumps landed in one change. The bootstrap now exists: a cursorless request is answered with the sequence watermark, and the client adopts it. **M001's named condition is discharged by M002.** | ## Dependency-ready implementation plans @@ -58,9 +58,9 @@ maps to `closed`. | `plans/implementation/sync-cursor-protocol/002-cursor-bootstrap-and-precision-convergence.md` | closed | Sync cursor protocol M002 — add the bootstrap that makes the write-sequence cursor reachable, and record in the client which cursor the server is serving | None. Discharges M001's named condition. No new protocol field: the bootstrap reuses `last_sync_sequence` and `server_sequence` as they are, so `snip-proto` stays 0.1.4 and is not republished. Requires `snip-sync` 0.1.8 and `snip-it` 1.4.1 in one change. | | `plans/implementation/locking-convergence/002-kernel-lock-protocol-convergence.md` | ready | Locking protocol and ordering convergence M002 — one kernel-backed file-lock implementation per platform, one busy-versus-error classification, and the `croncheck.lock` copy removed | None. M001 closed the owned-record protocol; this milestone is the kernel-lock family, which is a different thing and stays separate. The plan's proposal of a new shared crate is out of bounds under the standing no-new-crates rule and must be replaced before execution. | | `plans/implementation/locking-convergence/003-lock-ordering-contract-and-static-guard.md` | ready | Locking protocol and ordering convergence M003 — one stated acquisition order over the lock tiers, the code reconciled to it, and a static guard that fails on a violating acquisition site | Hard on M002: both milestones touch `src/auto_sync/execution_lock.rs`. Removes the retired `WorkerLock` tier, which is a breaking `status --json` change. | -| `plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md` | ready | Maintenance and duplicate-policy consolidation M002 — one shared copy policy for every snapshot, backup, and rollback-point path: symlink refusal and fsync become properties of the primitive | None. M001 closed the dead subsystem. The shared primitive belongs in the atomic/persistence layer under a named durability class. | -| `plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md` | ready | Maintenance and duplicate-policy consolidation M003 — one shared diagnostic vocabulary and one shared library scan across the validate, doctor, and repair surfaces | Soft on M002. No diagnostic code, message, or exit code changes. | -| `plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md` | ready | Snippet CRUD surface M002 — give the user a way to set and clear the snippet `folders` and `favorite` fields that the product already reads, sorts on, and displays | Hard on M001: the delete primitive it reuses landed in M001. Requires a `command_behavior()` entry, a `snp data` mirror arm, and a `docs/COMMAND_CONTRACTS.md` row. | +| `plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md` | closed | Maintenance and duplicate-policy consolidation M002 — one shared copy policy for every snapshot, backup, and rollback-point path: symlink refusal and fsync become properties of the primitive | None. M001 closed the dead subsystem. The shared primitive belongs in the atomic/persistence layer under a named durability class. | +| `plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md` | closed | Maintenance and duplicate-policy consolidation M003 — one shared diagnostic vocabulary and one shared library scan across the validate, doctor, and repair surfaces | Soft on M002. No diagnostic code, message, or exit code changes. | +| `plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md` | closed | Snippet CRUD surface M002 — give the user a way to set and clear the snippet `folders` and `favorite` fields that the product already reads, sorts on, and displays | Hard on M001: the delete primitive it reuses landed in M001. Requires a `command_behavior()` entry, a `snp data` mirror arm, and a `docs/COMMAND_CONTRACTS.md` row. | | `plans/implementation/snippet-crud-surface/003-non-interactive-field-update.md` | ready | Snippet CRUD surface M003 — allow a snippet's description, command, and tags to be changed non-interactively, generalizing the existing `snp edit --output` path | Hard on M002: it extends the shared field-update primitive M002 introduces. Extends `snp edit` rather than adding a command, because `snp update` is the self-update command. | | `plans/implementation/cli-library-sync-consolidation/006-search-parity-verification-corrective.md` | closed | CLI, library, selector, sync-policy consolidation M006 — close the search-parity verification gap and gate the parity suite in `scripts/check.sh` | None. Corrective pass over the closed M004; M001-M005 closure history unchanged. Closed 2026-10-22: the three surfaces now share one match primitive, the empty-query and cross-library-order behaviors are decided and pinned, and the parity suite runs in `scripts/check.sh`. | | `plans/adrs/ADR-0001-sync-delta-cursor.md` | accepted | Monotonic per-library sequence as the sync delta cursor | The **defect** is closed by the implemented server-side cursor column (`snippets.visible_at`, clamped to the library watermark): the cursor is server-assigned, `updated_at` keeps the client's logical time, and no protocol change was needed for that closure. What remains is the second-granularity wart the `>=` filter still has, which needs a `snip-proto` field, a server schema migration, and a client cursor change — one change with a version bump for `snip-proto`, `snip-sync`, and `snip-it`. The status was normalized from the off-lifecycle word `amended` to `accepted` on 2026-10-22 with the transition recorded in the record's status history; the implementation is tracked by the sync cursor protocol roadmap's M001. | @@ -148,12 +148,13 @@ cursor untouched. have all been implemented. The CLI/library/selector/sync consolidation M006 search-parity corrective closed the verification gap against M004 and the subsystem roadmap is now complete. The sync cursor protocol M002 added the -bootstrap, which discharges M001's named condition. Six further plans are -registered and dependency-ready — locking convergence M002 and M003, -maintenance consolidation M002 and M003, and snippet CRUD surface M002 and -M003. The natural next handoff is the locking convergence M002 kernel-lock -protocol convergence, because M003 is hard on it and both touch the same -file; the snippet CRUD surface M002 is the next user-visible capability. +bootstrap, which discharges M001's named condition. Maintenance consolidation M002-M003 and snippet CRUD M002 are closed. +Remaining dependency-ready plans: locking convergence M002 (crate proposal +must be replaced before execution) and M003 (hard on M002), and snippet +CRUD M003. The natural next user-visible handoff is snippet CRUD M003 +(after reconciling its build-order note with the closed M002 primitive); +the next infrastructure handoff awaits a locking M002 plan that does not +introduce a new workspace crate. **MCP gate:** M001 closed the read-only local adapter plus registration against the canonical selector contract. No execution, mutation, diff --git a/plans/subsystems/maintenance-consolidation-roadmap.md b/plans/subsystems/maintenance-consolidation-roadmap.md index 2a941287..f508bc7b 100644 --- a/plans/subsystems/maintenance-consolidation-roadmap.md +++ b/plans/subsystems/maintenance-consolidation-roadmap.md @@ -1,6 +1,6 @@ # Maintenance and Duplicate-Policy Consolidation Roadmap -Status: active +Status: closed > **2026-10-22 — M001 closed.** The milestone's implementation plan > (`plans/implementation/maintenance-consolidation/001-dead-subsystem-removal-and-doc-reconciliation.md`) @@ -385,5 +385,5 @@ library scan, and that no unresolved medium-or-higher finding remains. | Milestone | Status | Implementation plan | Closure record | Blockers | |---|---|---|---|---| | M001 dead subsystem removal + doc reconciliation | closed | `plans/implementation/maintenance-consolidation/001-dead-subsystem-removal-and-doc-reconciliation.md` | `plans/closure/maintenance-consolidation/001-status.md` | — | -| M002 backup and snapshot policy convergence | not started | — | — | M001 closed | -| M003 diagnostic vocabulary unification | not started | — | — | — | +| M002 backup and snapshot policy convergence | closed | `plans/implementation/maintenance-consolidation/002-backup-and-snapshot-policy-convergence.md` | `plans/closure/maintenance-consolidation/002-status.md` | — | +| M003 diagnostic vocabulary unification | closed | `plans/implementation/maintenance-consolidation/003-diagnostic-vocabulary-unification.md` | `plans/closure/maintenance-consolidation/003-status.md` | — | diff --git a/plans/subsystems/snippet-crud-surface-roadmap.md b/plans/subsystems/snippet-crud-surface-roadmap.md index 08699db6..5c9e2761 100644 --- a/plans/subsystems/snippet-crud-surface-roadmap.md +++ b/plans/subsystems/snippet-crud-surface-roadmap.md @@ -395,5 +395,5 @@ and that no unresolved medium-or-higher finding remains. | Milestone | Status | Implementation plan | Closure record | Blockers | |---|---|---|---|---| | M001 non-interactive snippet delete | closed | `plans/implementation/snippet-crud-surface/001-non-interactive-snippet-delete.md` | `plans/closure/snippet-crud-surface/001-status.md` | — | -| M002 folder and favorite write path | not started | — | — | M001 closed | +| M002 folder and favorite write path | closed | `plans/implementation/snippet-crud-surface/002-folder-and-favorite-write-path.md` | `plans/closure/snippet-crud-surface/002-status.md` | — | | M003 non-interactive field update | not started | — | — | M001 closed | diff --git a/src/commands/backup_archive.rs b/src/commands/backup_archive.rs index 54e1d8f4..e3a0a1db 100644 --- a/src/commands/backup_archive.rs +++ b/src/commands/backup_archive.rs @@ -190,30 +190,44 @@ impl BackupRelativePath { } } -/// Read a file for backup snapshot, rejecting symlinks and non-regular files. +/// Read a file for backup snapshot via the shared copy-source admission half. +/// +/// Symlink / non-regular refusal lives in +/// [`crate::utils::atomic::read_copy_source`]. Callers that also need +/// containment under the config root should call +/// [`validate_canonical_containment`] first. +/// +/// Message wording stays compatible with existing backup tests that accept +/// either "symlink" or "escapes config root". pub(crate) fn read_for_snapshot(path: &Path, label: &str) -> SnipResult> { - let meta = fs::symlink_metadata(path) - .map_err(|e| SnipError::io_error(&format!("stat {label} for snapshot"), path, e))?; - if meta.file_type().is_symlink() { - return Err(SnipError::runtime_error( - "Backup entry is a symlink", - Some(&format!( - "Refusing to back up symlink {} (could point outside config)", - path.display() - )), - )); - } - if !meta.is_file() { - return Err(SnipError::runtime_error( - "Backup entry is not a regular file", - Some(&format!( - "Expected regular file, got {:?}: {}", - meta.file_type(), - path.display() - )), - )); + let options = crate::utils::atomic::CopyOptions { + source: crate::utils::atomic::CopySourcePolicy::RegularFileOnly, + durability: crate::utils::atomic::Durability::DurableUserData, + }; + match crate::utils::atomic::read_copy_source(path, &options) { + Ok(bytes) => Ok(bytes), + Err(SnipError::Runtime { message, .. }) if message.contains("symlink") => { + Err(SnipError::runtime_error( + "Backup entry is a symlink", + Some(&format!( + "Refusing to back up symlink {} (could point outside config)", + path.display() + )), + )) + } + Err(SnipError::Runtime { message, .. }) + if message.contains("regular file") || message.contains("not a regular") => + { + Err(SnipError::runtime_error( + "Backup entry is not a regular file", + Some(&format!( + "Expected regular file for {label}: {}", + path.display() + )), + )) + } + Err(other) => Err(other), } - fs::read(path).map_err(|e| SnipError::io_error(&format!("read {label} for snapshot"), path, e)) } /// Compute the SHA-256 hex digest of a byte slice. diff --git a/src/commands/doctor_cmd.rs b/src/commands/doctor_cmd.rs index 185f5b29..c6a0e056 100644 --- a/src/commands/doctor_cmd.rs +++ b/src/commands/doctor_cmd.rs @@ -4,8 +4,8 @@ use crate::commands::pet_analysis::{ }; use crate::commands::shell_cmd::{self, ShellType}; use crate::diagnostics::{ - CompatibilityDiagnostic, DiagnosticSeverity, DoctorReport, NormalizationRecord, - diagnostic_counts, version, + CompatibilityDiagnostic, DiagnosticCode, DiagnosticSeverity, DoctorReport, NormalizationRecord, + diagnostic_code, diagnostic_counts, version, }; use crate::error::{SnipError, SnipResult}; use crate::library::{LibraryManager, Snippets}; @@ -68,7 +68,7 @@ const STRICT_WARNING_CODES: &[&str] = &[ /// When `compat_mode` is true, the `CONFIG_LOAD_FAILED` severity is downgraded from Error /// to Warning for backward compatibility with `--compatibility` mode. fn map_snapshot_diagnostic(d: &StatusDiagnostic, compat_mode: bool) -> CompatibilityDiagnostic { - let (code, field) = match d.code.as_str() { + let (code_str, field) = match d.code.as_str() { "CONFIG_LOAD_FAILED" => ( "sync.config.load_failed".to_string(), "sync_config".to_string(), @@ -147,6 +147,9 @@ fn map_snapshot_diagnostic(d: &StatusDiagnostic, compat_mode: bool) -> Compatibi } }; + let code = DiagnosticCode::new(code_str.clone()) + .unwrap_or_else(|e| panic!("snapshot diagnostic code '{code_str}': {e}")); + CompatibilityDiagnostic { code, entry_index: None, @@ -167,7 +170,7 @@ fn append_sync_diagnostics(report: &mut DoctorReport, compat_mode: bool) { // Always include a summary entry so the report indicates sync was checked. report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.sync.checked".to_string(), + code: diagnostic_code("compat.sync.checked"), entry_index: None, field: Some("auto_sync".to_string()), severity: DiagnosticSeverity::Info, @@ -240,7 +243,7 @@ fn build_pet_report( let sanitized = sanitize_library_name(lib_name); if existing_library_names.contains(&sanitized) { report.diagnostics.push(CompatibilityDiagnostic { - code: "W-DEST-CONFLICT".to_string(), + code: diagnostic_code("W-DEST-CONFLICT"), entry_index: None, field: Some("destination".to_string()), severity: DiagnosticSeverity::Warning, @@ -389,7 +392,7 @@ fn detect_unsupported_concepts(snippets: &Snippets, report: &mut DoctorReport) { if angle_depth < 0 { // Unmatched closing > report.diagnostics.push(CompatibilityDiagnostic { - code: "W-MALFORMED-VAR".to_string(), + code: diagnostic_code("W-MALFORMED-VAR"), entry_index: Some(i), field: Some("command".to_string()), severity: DiagnosticSeverity::Warning, @@ -407,7 +410,7 @@ fn detect_unsupported_concepts(snippets: &Snippets, report: &mut DoctorReport) { } if angle_depth > 0 { report.diagnostics.push(CompatibilityDiagnostic { - code: "W-MALFORMED-VAR".to_string(), + code: diagnostic_code("W-MALFORMED-VAR"), entry_index: Some(i), field: Some("command".to_string()), severity: DiagnosticSeverity::Warning, @@ -421,7 +424,7 @@ fn detect_unsupported_concepts(snippets: &Snippets, report: &mut DoctorReport) { // Check for pet-specific fields that indicate unsupported concepts if !pet.folders.is_empty() { report.diagnostics.push(CompatibilityDiagnostic { - code: "I-FIELD-FOLDERS".to_string(), + code: diagnostic_code("I-FIELD-FOLDERS"), entry_index: Some(i), field: Some("folders".to_string()), severity: DiagnosticSeverity::Info, @@ -478,7 +481,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { .map(|p| p.display().to_string()) .unwrap_or_else(|| "".to_string()); report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.binary_version".to_string(), + code: diagnostic_code("compat.binary_version"), entry_index: None, field: Some("binary".to_string()), severity: DiagnosticSeverity::Info, @@ -495,7 +498,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { .unwrap_or(false); if writable { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.config_dir.ok".to_string(), + code: diagnostic_code("compat.config_dir.ok"), entry_index: None, field: Some("config_dir".to_string()), severity: DiagnosticSeverity::Info, @@ -508,7 +511,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.config_dir.readonly".to_string(), + code: diagnostic_code("compat.config_dir.readonly"), entry_index: None, field: Some("config_dir".to_string()), severity: DiagnosticSeverity::Warning, @@ -519,7 +522,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { } } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.config_dir.missing".to_string(), + code: diagnostic_code("compat.config_dir.missing"), entry_index: None, field: Some("config_dir".to_string()), severity: DiagnosticSeverity::Warning, @@ -533,7 +536,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { let libraries_dir = config_dir.join("libraries"); if libraries_dir.exists() { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.libraries_dir.ok".to_string(), + code: diagnostic_code("compat.libraries_dir.ok"), entry_index: None, field: Some("libraries_dir".to_string()), severity: DiagnosticSeverity::Info, @@ -543,7 +546,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.libraries_dir.missing".to_string(), + code: diagnostic_code("compat.libraries_dir.missing"), entry_index: None, field: Some("libraries_dir".to_string()), severity: DiagnosticSeverity::Info, @@ -573,7 +576,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { 0 }; report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.primary_library.ok".to_string(), + code: diagnostic_code("compat.primary_library.ok"), entry_index: None, field: Some("primary_library".to_string()), severity: DiagnosticSeverity::Info, @@ -585,7 +588,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { crate::library::PrimaryState::NoPrimary { .. } | crate::library::PrimaryState::NoLibraries => { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.primary_library.missing".to_string(), + code: diagnostic_code("compat.primary_library.missing"), entry_index: None, field: Some("primary_library".to_string()), severity: DiagnosticSeverity::Warning, @@ -599,7 +602,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }, Err(e) => { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.library_manager.error".to_string(), + code: diagnostic_code("compat.library_manager.error"), entry_index: None, field: Some("library_manager".to_string()), severity: DiagnosticSeverity::Warning, @@ -617,7 +620,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { Ok(settings) => { if settings.enabled { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.sync.enabled".to_string(), + code: diagnostic_code("compat.sync.enabled"), entry_index: None, field: Some("sync".to_string()), severity: DiagnosticSeverity::Info, @@ -627,7 +630,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.sync.disabled".to_string(), + code: diagnostic_code("compat.sync.disabled"), entry_index: None, field: Some("sync".to_string()), severity: DiagnosticSeverity::Info, @@ -639,7 +642,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { } Err(e) => { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.sync.config_error".to_string(), + code: diagnostic_code("compat.sync.config_error"), entry_index: None, field: Some("sync".to_string()), severity: DiagnosticSeverity::Warning, @@ -651,7 +654,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { } } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.sync.absent".to_string(), + code: diagnostic_code("compat.sync.absent"), entry_index: None, field: Some("sync".to_string()), severity: DiagnosticSeverity::Info, @@ -673,7 +676,8 @@ fn build_compatibility_report(strict: bool) -> SnipResult { if found { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell.{shell_name}.ok"), + code: DiagnosticCode::new(format!("compat.shell.{shell_name}.ok")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Info, @@ -683,7 +687,8 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell.{shell_name}.missing"), + code: DiagnosticCode::new(format!("compat.shell.{shell_name}.missing")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Info, @@ -705,7 +710,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { if select_available { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.select.ok".to_string(), + code: diagnostic_code("compat.select.ok"), entry_index: None, field: Some("select".to_string()), severity: DiagnosticSeverity::Info, @@ -715,7 +720,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.select.missing".to_string(), + code: diagnostic_code("compat.select.missing"), entry_index: None, field: Some("select".to_string()), severity: DiagnosticSeverity::Warning, @@ -738,7 +743,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { let has_editor_flag = new_help.contains("--editor"); report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.acquire.command_stdin".to_string(), + code: diagnostic_code("compat.acquire.command_stdin"), entry_index: None, field: Some("acquire".to_string()), severity: if has_command_stdin { @@ -760,7 +765,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.acquire.from_file".to_string(), + code: diagnostic_code("compat.acquire.from_file"), entry_index: None, field: Some("acquire".to_string()), severity: if has_from_file { @@ -782,7 +787,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.acquire.editor".to_string(), + code: diagnostic_code("compat.acquire.editor"), entry_index: None, field: Some("acquire".to_string()), severity: if has_editor_flag { @@ -815,7 +820,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { if has_choice_support { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.choice_parser.ok".to_string(), + code: diagnostic_code("compat.choice_parser.ok"), entry_index: None, field: Some("choice_parser".to_string()), severity: DiagnosticSeverity::Info, @@ -825,7 +830,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.choice_parser.missing".to_string(), + code: diagnostic_code("compat.choice_parser.missing"), entry_index: None, field: Some("choice_parser".to_string()), severity: DiagnosticSeverity::Warning, @@ -847,7 +852,8 @@ fn build_compatibility_report(strict: bool) -> SnipResult { if !shell_found { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_syntax.{shell_name}.unavailable"), + code: DiagnosticCode::new(format!("compat.shell_syntax.{shell_name}.unavailable")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(format!("shell_syntax_{shell_name}")), severity: DiagnosticSeverity::Info, @@ -887,7 +893,10 @@ fn build_compatibility_report(strict: bool) -> SnipResult { match syntax_check { Ok(status) if status.success() => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_syntax.{shell_name}.ok"), + code: DiagnosticCode::new(format!( + "compat.shell_syntax.{shell_name}.ok" + )) + .expect("doctor diagnostic code"), entry_index: None, field: Some(format!("shell_syntax_{shell_name}")), severity: DiagnosticSeverity::Info, @@ -898,7 +907,10 @@ fn build_compatibility_report(strict: bool) -> SnipResult { } _ => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_syntax.{shell_name}.invalid"), + code: DiagnosticCode::new(format!( + "compat.shell_syntax.{shell_name}.invalid" + )) + .expect("doctor diagnostic code"), entry_index: None, field: Some(format!("shell_syntax_{shell_name}")), severity: DiagnosticSeverity::Warning, @@ -913,7 +925,10 @@ fn build_compatibility_report(strict: bool) -> SnipResult { } _ => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_syntax.{shell_name}.init_failed"), + code: DiagnosticCode::new(format!( + "compat.shell_syntax.{shell_name}.init_failed" + )) + .expect("doctor diagnostic code"), entry_index: None, field: Some(format!("shell_syntax_{shell_name}")), severity: DiagnosticSeverity::Warning, @@ -939,7 +954,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { (None, None) => unreachable!(), }; report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.editor.ok".to_string(), + code: diagnostic_code("compat.editor.ok"), entry_index: None, field: Some("editor".to_string()), severity: DiagnosticSeverity::Info, @@ -949,7 +964,7 @@ fn build_compatibility_report(strict: bool) -> SnipResult { }); } else { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.editor.unset".to_string(), + code: diagnostic_code("compat.editor.unset"), entry_index: None, field: Some("editor".to_string()), severity: DiagnosticSeverity::Info, @@ -971,7 +986,7 @@ command = "echo ok" match pet_parse_test { Ok(_) => { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.pet_toml.ok".to_string(), + code: diagnostic_code("compat.pet_toml.ok"), entry_index: None, field: Some("pet_toml".to_string()), severity: DiagnosticSeverity::Info, @@ -982,7 +997,7 @@ command = "echo ok" } Err(e) => { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.pet_toml.error".to_string(), + code: diagnostic_code("compat.pet_toml.error"), entry_index: None, field: Some("pet_toml".to_string()), severity: DiagnosticSeverity::Error, @@ -999,7 +1014,7 @@ command = "echo ok" let legacy_single_file = PathBuf::from(&home).join(".config/snippets.toml"); if legacy_single_file.exists() { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.legacy.single_file".to_string(), + code: diagnostic_code("compat.legacy.single_file"), entry_index: None, field: Some("legacy".to_string()), severity: DiagnosticSeverity::Info, @@ -1018,7 +1033,7 @@ command = "echo ok" let legacy_config_dir = PathBuf::from(&home).join(".snip-it"); if legacy_config_dir.exists() { report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.legacy.config_dir".to_string(), + code: diagnostic_code("compat.legacy.config_dir"), entry_index: None, field: Some("legacy".to_string()), severity: DiagnosticSeverity::Info, @@ -1088,7 +1103,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { "fish" => ShellType::Fish, _ => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.unknown"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.unknown")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Warning, @@ -1123,7 +1139,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { DiagnosticSeverity::Warning }; report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.unavailable"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.unavailable")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity, @@ -1141,7 +1158,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { Ok(t) => t, Err(e) => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.error"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.error")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Warning, @@ -1154,7 +1172,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { }; if let Err(e) = std::fs::write(tmp.path(), &code) { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.error"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.error")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Warning, @@ -1184,7 +1203,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { match output { Ok(o) if o.status.success() => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.ok"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.ok")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Info, @@ -1201,7 +1221,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { DiagnosticSeverity::Warning }; report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.invalid"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.invalid")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity, @@ -1212,7 +1233,8 @@ fn check_shell_init(shell_name: &str, report: &mut DoctorReport, strict: bool) { } Err(e) => { report.diagnostics.push(CompatibilityDiagnostic { - code: format!("compat.shell_init.{shell_name}.error"), + code: DiagnosticCode::new(format!("compat.shell_init.{shell_name}.error")) + .expect("doctor diagnostic code"), entry_index: None, field: Some(shell_name.to_string()), severity: DiagnosticSeverity::Warning, diff --git a/src/commands/import_cmd.rs b/src/commands/import_cmd.rs index 30eb47b7..cb149598 100644 --- a/src/commands/import_cmd.rs +++ b/src/commands/import_cmd.rs @@ -372,7 +372,7 @@ pub fn run_import_pet(options: PetImportOptions) -> SnipResult<()> { "Same command as existing '{}' but different description", existing_snippet.description ), - code: "W-DUP-CMD".to_string(), + code: crate::diagnostics::diagnostic_code("W-DUP-CMD"), suggestion: None, span: None, }); @@ -385,7 +385,7 @@ pub fn run_import_pet(options: PetImportOptions) -> SnipResult<()> { message: "Same description as existing entry but different command" .to_string(), - code: "W-DUP-DESC".to_string(), + code: crate::diagnostics::diagnostic_code("W-DUP-DESC"), suggestion: None, span: None, }); diff --git a/src/commands/mod.rs b/src/commands/mod.rs index e666cf53..0854ce68 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -19,6 +19,7 @@ pub mod keybindings_cmd; pub mod library_cmd; pub mod list_cmd; pub mod new_cmd; +pub mod organize_cmd; pub mod pet_analysis; pub mod premade_cmd; pub mod register_cmd; @@ -271,7 +272,7 @@ fn load_snippets_at(path: &std::path::Path) -> SnipResult { + /// Notify the auto-sync subsystem after the mutation commits. + AutoNotify, + /// Run an explicit sync with the caller's runtime after the mutation commits. + ExplicitSync(&'a tokio::runtime::Runtime), +} + +/// A single local-only field mutation for [`update_snippet_fields`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SnippetFieldMutation { + SetFavorite, + ClearFavorite, + AddFolder(String), + RemoveFolder(String), +} + +/// The outcome of [`update_snippet_fields`]. +#[derive(Debug, Clone)] +pub enum SnippetFieldUpdateOutcome { + /// The mutation changed the snippet and was persisted. + Updated(crate::library::Snippet), + /// The requested end state already held; nothing was written. + Unchanged(crate::library::Snippet), + /// No live snippet with that identifier exists; nothing was changed. + NotFound, +} + +enum FieldUpdateProbe { + Unchanged(crate::library::Snippet), + Missing, +} + +fn snippet_field_audit_action(mutation: &SnippetFieldMutation) -> &'static str { + match mutation { + SnippetFieldMutation::SetFavorite => "favorite", + SnippetFieldMutation::ClearFavorite => "unfavorite", + SnippetFieldMutation::AddFolder(_) => "add-folder", + SnippetFieldMutation::RemoveFolder(_) => "remove-folder", + } +} + +fn apply_snippet_field_mutation( + snippet: &mut crate::library::Snippet, + mutation: &SnippetFieldMutation, +) -> bool { + match mutation { + SnippetFieldMutation::SetFavorite => { + if snippet.favorite { + return false; + } + snippet.favorite = true; + true + } + SnippetFieldMutation::ClearFavorite => { + if !snippet.favorite { + return false; + } + snippet.favorite = false; + true + } + SnippetFieldMutation::AddFolder(name) => { + if snippet.folders.iter().any(|f| f == name) { + return false; + } + snippet.folders.push(name.clone()); + true + } + SnippetFieldMutation::RemoveFolder(name) => { + let before = snippet.folders.len(); + snippet.folders.retain(|f| f != name); + snippet.folders.len() != before + } + } +} + +/// Update one snippet's local-only fields by identifier — shared field-update primitive. +/// +/// Same seven-step sequence as [`delete_snippet`], except the lookup never +/// tombstones and no-ops are reported as [`SnippetFieldUpdateOutcome::Unchanged`] +/// without rewriting the library file. +pub fn update_snippet_fields( + library_path: &std::path::Path, + target_id: &str, + mutation: SnippetFieldMutation, + trigger: FieldUpdateSyncTrigger<'_>, +) -> SnipResult { + let mut probe: Option = None; + let mut updated: Option = None; + + let mutation_result = crate::library::update_library(library_path, |current| { + let index = current + .snippets + .iter() + .position(|s| s.id == target_id && !s.deleted); + let Some(index) = index else { + probe = Some(FieldUpdateProbe::Missing); + return Err(SnipError::runtime_error( + "Snippet not found", + Some("The selected snippet is no longer available"), + )); + }; + let target = &mut current.snippets[index]; + if !apply_snippet_field_mutation(target, &mutation) { + probe = Some(FieldUpdateProbe::Unchanged(target.clone())); + return Err(SnipError::runtime_error( + "Snippet unchanged", + Some("The snippet already matches the requested state"), + )); + } + let now = chrono::Utc::now().timestamp(); + target.updated_at = target.updated_at.max(now).saturating_add(1); + updated = Some(target.clone()); + Ok(()) + }); + + match mutation_result { + Ok(_) => {} + Err(e) => { + return match probe { + Some(FieldUpdateProbe::Unchanged(snippet)) => { + Ok(SnippetFieldUpdateOutcome::Unchanged(snippet)) + } + Some(FieldUpdateProbe::Missing) => Ok(SnippetFieldUpdateOutcome::NotFound), + None => Err(e), + }; + } + } + + let updated = updated.ok_or_else(|| { + SnipError::runtime_error( + "Snippet not found", + Some("The selected snippet is no longer available"), + ) + })?; + + if let Err(e) = crate::logging::audit_log(snippet_field_audit_action(&mutation), &updated, None) + { + tracing::debug!("Audit log write failed: {}", e); + } + + match trigger { + FieldUpdateSyncTrigger::ExplicitSync(rt) => { + if let Err(e) = run_explicit_sync(rt) { + tracing::warn!(error = %e, "post-field-update explicit sync failed"); + } + } + FieldUpdateSyncTrigger::AutoNotify => { + crate::auto_sync::report_notification_result(crate::auto_sync::notify_mutation( + crate::auto_sync::MutationKind::SnippetUpdate, + crate::auto_sync::MutationOrigin::User, + )); + } + } + + Ok(SnippetFieldUpdateOutcome::Updated(updated)) +} + /// The sync trigger a snippet delete performs once its mutation is durable. /// /// The interactive path asks for an explicit sync when the caller passed @@ -1025,6 +1185,108 @@ mod tests { assert_eq!(fixture.library_bytes(), before); } + #[test] + fn update_snippet_fields_preserves_identifier_and_advances_timestamp() { + let fixture = DeleteFixture::new(vec![DeleteFixture::snippet( + "id-1", + "git push", + "git push origin main", + )]); + let original_id = fixture.library_path.clone(); + let live = crate::library::load_library(&original_id) + .expect("load fixture") + .snippets[0] + .updated_at; + + let outcome = update_snippet_fields( + &fixture.library_path, + "id-1", + SnippetFieldMutation::SetFavorite, + FieldUpdateSyncTrigger::AutoNotify, + ) + .expect("favorite update succeeds"); + + match outcome { + SnippetFieldUpdateOutcome::Updated(snippet) => { + assert_eq!(snippet.id, "id-1"); + assert!(snippet.favorite); + assert_eq!(snippet.updated_at, live + 1); + } + other => panic!("expected an update, got {other:?}"), + } + } + + #[test] + fn update_snippet_fields_reports_unchanged_without_rewriting_file() { + let mut snippet = DeleteFixture::snippet("id-1", "git push", "git push"); + snippet.favorite = true; + let fixture = DeleteFixture::new(vec![snippet]); + let before = fixture.library_bytes(); + + let outcome = update_snippet_fields( + &fixture.library_path, + "id-1", + SnippetFieldMutation::SetFavorite, + FieldUpdateSyncTrigger::AutoNotify, + ) + .expect("unchanged reports a verdict"); + + assert!(matches!(outcome, SnippetFieldUpdateOutcome::Unchanged(_))); + assert_eq!(fixture.library_bytes(), before); + } + + #[test] + fn update_snippet_fields_reports_not_found_distinctly() { + let fixture = + DeleteFixture::new(vec![DeleteFixture::snippet("id-1", "git push", "git push")]); + let before = fixture.library_bytes(); + + let outcome = update_snippet_fields( + &fixture.library_path, + "does-not-exist", + SnippetFieldMutation::SetFavorite, + FieldUpdateSyncTrigger::AutoNotify, + ) + .expect("not-found reports a verdict"); + + assert!(matches!(outcome, SnippetFieldUpdateOutcome::NotFound)); + assert_eq!(fixture.library_bytes(), before); + } + + #[test] + fn update_snippet_fields_writes_expected_audit_action_names() { + let fixture = + DeleteFixture::new(vec![DeleteFixture::snippet("id-1", "git push", "git push")]); + + for (mutation, token) in [ + (SnippetFieldMutation::SetFavorite, "favorite"), + (SnippetFieldMutation::ClearFavorite, "unfavorite"), + ( + SnippetFieldMutation::AddFolder("work".to_string()), + "add-folder", + ), + ( + SnippetFieldMutation::RemoveFolder("work".to_string()), + "remove-folder", + ), + ] { + let _ = update_snippet_fields( + &fixture.library_path, + "id-1", + mutation, + FieldUpdateSyncTrigger::AutoNotify, + ) + .expect("mutation succeeds"); + let audit = std::fs::read_to_string(fixture.config_dir.join("audit.log")) + .expect("audit log written"); + let matches = audit + .lines() + .filter(|line| line.contains(&format!("|{token}|"))) + .count(); + assert_eq!(matches, 1, "expected exactly one {token} audit entry"); + } + } + #[test] fn delete_snippet_writes_the_delete_audit_entry() { let fixture = diff --git a/src/commands/organize_cmd.rs b/src/commands/organize_cmd.rs new file mode 100644 index 00000000..40bd5663 --- /dev/null +++ b/src/commands/organize_cmd.rs @@ -0,0 +1,513 @@ +//! **Layer: Application** +//! +//! Deterministic non-interactive folder and favorite updates. +//! +//! `snp organize` mutates a snippet's local-only `folders` and `favorite` +//! fields without a TUI. It resolves its target through the mutating selector +//! ([`crate::selector::resolve_selector`]) and applies the shared field-update +//! primitive ([`crate::commands::update_snippet_fields`]). + +use crate::commands::{ + FieldUpdateSyncTrigger, SnippetFieldMutation, SnippetFieldUpdateOutcome, update_snippet_fields, +}; +use crate::error::{SnipError, SnipResult}; +use crate::outcome::CliOutcome; +use crate::selector::{ResolutionPolicy, SelectionResult, SnippetIdentity, SnippetMatch}; +use serde::Serialize; +/// Canonical Clap arguments for `snp organize`. +#[derive(Debug, Clone, clap::Args)] +pub struct OrganizeArgs { + /// Match by exact snippet ID + #[arg(long, conflicts_with_all = ["description_exact", "command_exact", "query"])] + pub id: Option, + /// Match by exact description (case-insensitive) + #[arg(long = "description-exact", conflicts_with_all = ["id", "command_exact", "query"])] + pub description_exact: Option, + /// Match by exact command text (case-insensitive) + #[arg(long = "command-exact", conflicts_with_all = ["id", "description_exact", "query"])] + pub command_exact: Option, + /// Fuzzy query match + #[arg(short, long, conflicts_with_all = ["id", "description_exact", "command_exact"])] + pub query: Option, + /// Library scope (name); `all` is not supported + #[arg(short, long)] + pub library: Option, + /// Mark the snippet as a favorite + #[arg( + long, + group = "organize_action", + conflicts_with_all = ["unfavorite", "add_folder", "remove_folder"] + )] + pub favorite: bool, + /// Clear the favorite flag + #[arg( + long, + group = "organize_action", + conflicts_with_all = ["favorite", "add_folder", "remove_folder"] + )] + pub unfavorite: bool, + /// Add a folder membership + #[arg( + long = "add-folder", + group = "organize_action", + conflicts_with_all = ["favorite", "unfavorite", "remove_folder"] + )] + pub add_folder: Option, + /// Remove a folder membership + #[arg( + long = "remove-folder", + group = "organize_action", + conflicts_with_all = ["favorite", "unfavorite", "add_folder"] + )] + pub remove_folder: Option, + /// Output as JSON + #[arg(long)] + pub json: bool, +} + +/// JSON output for `snp organize`. +#[derive(Debug, Serialize)] +pub struct OrganizeJsonOutput { + pub schema: u32, + pub status: String, + pub id: String, + pub description: String, + pub library: String, + pub favorite: bool, + pub folders: Vec, +} + +/// The verdict an organize reports. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum OrganizeStatus { + Updated, + Unchanged, +} + +impl OrganizeStatus { + fn as_str(self) -> &'static str { + match self { + OrganizeStatus::Updated => "updated", + OrganizeStatus::Unchanged => "unchanged", + } + } +} + +/// Run the `snp organize` command. +pub fn run(args: OrganizeArgs) -> SnipResult { + if args.id.is_none() + && args.description_exact.is_none() + && args.command_exact.is_none() + && args.query.is_none() + { + return Err(SnipError::usage_error( + "No selector specified", + Some("Provide --id, --description-exact, --command-exact, or --query"), + )); + } + + let mutation = parse_mutation(&args)?; + + if args.library.as_deref() == Some("all") { + return Err(SnipError::runtime_error( + "Library 'all' is not supported by 'snp organize'", + Some( + "An organize mutation targets one snippet in one library. Use 'snp list --library all' to list every library, or 'snp get --library all' to fetch a snippet by id.", + ), + )); + } + + let mut selector = crate::selector::exact_selector(args.library.clone(), None, None, None); + selector.resolution = ResolutionPolicy::Unique; + if let Some(id) = args.id.clone() { + selector = selector.with_id(id); + } + if let Some(description) = args.description_exact.clone() { + selector = selector.with_description_exact(description); + } + if let Some(command) = args.command_exact.clone() { + selector = selector.with_command_exact(command); + } + if let Some(query) = args.query.clone() { + selector = selector.with_query(query); + } + + match crate::selector::resolve_selector(&selector)? { + SelectionResult::One(m) => { + let outcome = update_snippet_fields( + &m.library_path, + &m.snippet.id, + mutation, + FieldUpdateSyncTrigger::AutoNotify, + )?; + report_primitive_outcome(outcome, &m.library_name, args.json) + } + SelectionResult::Many(matches) => { + report_ambiguous(&identities_of(&matches)); + Ok(CliOutcome::Ambiguous) + } + SelectionResult::Ambiguous(identities) => { + report_ambiguous(&identities); + Ok(CliOutcome::Ambiguous) + } + SelectionResult::NotFound => { + eprintln!("Snippet not found: no live snippet matches the given selector."); + Ok(CliOutcome::NotFound) + } + } +} + +/// Resolve exactly one action flag into a typed mutation. +fn parse_mutation(args: &OrganizeArgs) -> SnipResult { + let mut actions = 0u8; + let mut mutation = None; + + if args.favorite { + actions += 1; + mutation = Some(SnippetFieldMutation::SetFavorite); + } + if args.unfavorite { + actions += 1; + mutation = Some(SnippetFieldMutation::ClearFavorite); + } + if let Some(name) = args.add_folder.as_deref() { + actions += 1; + mutation = Some(SnippetFieldMutation::AddFolder(validate_folder_name(name)?)); + } + if let Some(name) = args.remove_folder.as_deref() { + actions += 1; + mutation = Some(SnippetFieldMutation::RemoveFolder(validate_folder_name( + name, + )?)); + } + + if actions == 0 { + return Err(SnipError::usage_error( + "No action specified", + Some( + "Provide exactly one of --favorite, --unfavorite, --add-folder, or --remove-folder", + ), + )); + } + if actions > 1 { + return Err(SnipError::usage_error( + "Multiple actions specified", + Some( + "Provide exactly one of --favorite, --unfavorite, --add-folder, or --remove-folder", + ), + )); + } + + mutation.ok_or_else(|| { + SnipError::usage_error( + "No action specified", + Some( + "Provide exactly one of --favorite, --unfavorite, --add-folder, or --remove-folder", + ), + ) + }) +} + +/// Validate a folder name for the write path. +fn validate_folder_name(name: &str) -> SnipResult { + let trimmed = name.trim(); + if trimmed.is_empty() { + return Err(SnipError::usage_error( + "Folder name must not be empty", + None, + )); + } + if trimmed.contains(';') { + return Err(SnipError::usage_error( + "Folder name must not contain ';'", + Some("Semicolons are the CSV column separator for folder lists"), + )); + } + Ok(trimmed.to_string()) +} + +fn report_primitive_outcome( + outcome: SnippetFieldUpdateOutcome, + library_name: &str, + json: bool, +) -> SnipResult { + match outcome { + SnippetFieldUpdateOutcome::Updated(snippet) => { + emit_result(OrganizeStatus::Updated, &snippet, library_name, json)?; + Ok(CliOutcome::Success) + } + SnippetFieldUpdateOutcome::Unchanged(snippet) => { + emit_result(OrganizeStatus::Unchanged, &snippet, library_name, json)?; + Ok(CliOutcome::Success) + } + SnippetFieldUpdateOutcome::NotFound => { + eprintln!("Snippet not found: the target was deleted before the mutation ran."); + Ok(CliOutcome::NotFound) + } + } +} + +fn emit_result( + status: OrganizeStatus, + snippet: &crate::library::Snippet, + library_name: &str, + json: bool, +) -> SnipResult<()> { + if json { + let payload = OrganizeJsonOutput { + schema: 1, + status: status.as_str().to_string(), + id: snippet.id.clone(), + description: snippet.description.clone(), + library: library_name.to_string(), + favorite: snippet.favorite, + folders: snippet.folders.clone(), + }; + let json_str = serde_json::to_string_pretty(&payload).map_err(|e| { + SnipError::runtime_error("Failed to serialize organize result", Some(&e.to_string())) + })?; + println!("{json_str}"); + } else { + match status { + OrganizeStatus::Updated => { + println!("Updated snippet '{}' ({})", snippet.description, snippet.id); + } + OrganizeStatus::Unchanged => { + println!( + "Snippet '{}' ({}) already matches the requested state", + snippet.description, snippet.id + ); + } + } + } + Ok(()) +} + +fn report_ambiguous(identities: &[SnippetIdentity]) { + eprintln!("Ambiguous match. Multiple snippets match:"); + for identity in identities { + eprintln!( + " {} - {} ({})", + identity.id, identity.description, identity.library_name + ); + } + eprintln!("Use --id for exact matching, or refine your query."); +} + +fn identities_of(matches: &[SnippetMatch]) -> Vec { + matches + .iter() + .map(|m| SnippetIdentity { + id: m.snippet.id.clone(), + description: m.snippet.description.clone(), + command: m.snippet.command.clone(), + library_name: m.library_name.clone(), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::library::{LibraryManager, Snippet, Snippets}; + use std::path::PathBuf; + use tempfile::TempDir; + + const FUTURE_UPDATED_AT: i64 = 4_000_000_000; + + struct Fixture { + _tmp: TempDir, + _config_dir: crate::utils::config::ScopedConfigDir, + library_path: PathBuf, + } + + impl Fixture { + fn new(snippets: Vec) -> Self { + let tmp = TempDir::new().expect("test helper: temp dir"); + let config_dir = tmp.path().join(".config").join("snp"); + let guard = crate::utils::config::ScopedConfigDir::new(config_dir); + let mut manager = LibraryManager::new().expect("test helper: manager"); + let library_path = manager + .create_library("mylib") + .expect("test helper: create library"); + let collection = Snippets { + snippets, + folders: vec![], + }; + std::fs::write( + &library_path, + toml::to_string_pretty(&collection).expect("test helper: serialize library"), + ) + .expect("test helper: write library"); + Self { + _tmp: tmp, + _config_dir: guard, + library_path, + } + } + + fn snippet(id: &str, description: &str, command: &str) -> Snippet { + Snippet { + id: id.to_string(), + description: description.to_string(), + command: command.to_string(), + updated_at: FUTURE_UPDATED_AT, + ..Default::default() + } + } + + fn library_bytes(&self) -> String { + std::fs::read_to_string(&self.library_path).expect("test helper: read library") + } + } + + fn organize_by_id(id: &str, favorite: bool) -> OrganizeArgs { + OrganizeArgs { + id: Some(id.to_string()), + description_exact: None, + command_exact: None, + query: None, + library: None, + favorite, + unfavorite: false, + add_folder: None, + remove_folder: None, + json: false, + } + } + + #[test] + fn favorite_mutation_preserves_identifier_and_advances_timestamp() { + let fixture = Fixture::new(vec![Fixture::snippet( + "id-1", + "git push", + "git push origin main", + )]); + let original_id = "id-1".to_string(); + let live = crate::library::load_library(&fixture.library_path) + .expect("load fixture") + .snippets[0] + .updated_at; + + let outcome = run(organize_by_id("id-1", true)).expect("organize succeeds"); + assert_eq!(outcome, CliOutcome::Success); + + let persisted = crate::library::load_library(&fixture.library_path).expect("reload"); + let target = &persisted.snippets[0]; + assert_eq!(target.id, original_id); + assert!(target.favorite); + assert_eq!(target.updated_at, live + 1); + } + + #[test] + fn noop_favorite_reports_unchanged_and_leaves_file_bytes_identical() { + let mut snippet = Fixture::snippet("id-1", "git push", "git push"); + snippet.favorite = true; + let fixture = Fixture::new(vec![snippet]); + let before = fixture.library_bytes(); + + let outcome = run(organize_by_id("id-1", true)).expect("organize reports unchanged"); + assert_eq!(outcome, CliOutcome::Success); + assert_eq!(fixture.library_bytes(), before); + } + + #[test] + fn removing_last_folder_drops_toml_key_and_unfavorite_keeps_false_field() { + let mut snippet = Fixture::snippet("id-1", "alpha", "echo"); + snippet.folders = vec!["work".to_string()]; + snippet.favorite = true; + let fixture = Fixture::new(vec![snippet]); + + let remove = OrganizeArgs { + id: Some("id-1".to_string()), + description_exact: None, + command_exact: None, + query: None, + library: None, + favorite: false, + unfavorite: false, + add_folder: None, + remove_folder: Some("work".to_string()), + json: false, + }; + run(remove).expect("remove folder succeeds"); + let toml_text = fixture.library_bytes(); + assert!( + !toml_text.contains("folders"), + "empty folders list must omit the key: {toml_text}" + ); + + run(OrganizeArgs { + id: Some("id-1".to_string()), + description_exact: None, + command_exact: None, + query: None, + library: None, + favorite: false, + unfavorite: true, + add_folder: None, + remove_folder: None, + json: false, + }) + .expect("unfavorite succeeds"); + let toml_text = fixture.library_bytes(); + assert!( + toml_text.contains("favorite = false"), + "favorite=false must stay present: {toml_text}" + ); + } + + #[test] + fn invalid_folder_name_is_a_usage_error_and_writes_nothing() { + let fixture = Fixture::new(vec![Fixture::snippet("id-1", "alpha", "echo")]); + let before = fixture.library_bytes(); + let error = run(OrganizeArgs { + id: Some("id-1".to_string()), + description_exact: None, + command_exact: None, + query: None, + library: None, + favorite: false, + unfavorite: false, + add_folder: Some("bad;name".to_string()), + remove_folder: None, + json: false, + }) + .expect_err("semicolon folder names are rejected"); + assert!(error.to_string().contains(';')); + assert_eq!(fixture.library_bytes(), before); + } + + #[test] + fn ambiguous_selector_changes_nothing() { + let fixture = Fixture::new(vec![ + Fixture::snippet("id-1", "duplicate", "echo one"), + Fixture::snippet("id-2", "duplicate", "echo two"), + ]); + let before = fixture.library_bytes(); + let outcome = run(OrganizeArgs { + id: None, + description_exact: Some("duplicate".to_string()), + command_exact: None, + query: None, + library: None, + favorite: true, + unfavorite: false, + add_folder: None, + remove_folder: None, + json: false, + }) + .expect("ambiguity is an outcome"); + assert_eq!(outcome, CliOutcome::Ambiguous); + assert_eq!(fixture.library_bytes(), before); + } + + #[test] + fn golden_corpus_command_field_survives_favorite_mutation_round_trip() { + let command = "echo\ttrailing \r\n"; + let fixture = Fixture::new(vec![Fixture::snippet("id-1", "corpus", command)]); + run(organize_by_id("id-1", true)).expect("organize mutates golden snippet"); + let reloaded = crate::library::load_library(&fixture.library_path).expect("reload"); + assert_eq!(reloaded.snippets[0].command, command); + } +} diff --git a/src/commands/pet_analysis.rs b/src/commands/pet_analysis.rs index 92cc697b..59ac2a21 100644 --- a/src/commands/pet_analysis.rs +++ b/src/commands/pet_analysis.rs @@ -1,4 +1,6 @@ -use crate::diagnostics::{CompatibilityDiagnostic, DiagnosticSeverity, ImportDuplicate}; +use crate::diagnostics::{ + CompatibilityDiagnostic, DiagnosticSeverity, ImportDuplicate, diagnostic_code, +}; use crate::error::{SnipError, SnipResult}; use crate::library::Snippet; use crate::library::Snippets; @@ -149,7 +151,7 @@ pub fn detect_unknown_fields(raw_toml: &str) -> Vec { }; if actual_type != expected_type { diagnostics.push(CompatibilityDiagnostic { - code: "W-TYPE-MISMATCH".to_string(), + code: diagnostic_code("W-TYPE-MISMATCH"), entry_index: Some(i), field: Some(key.clone()), severity: DiagnosticSeverity::Warning, @@ -164,7 +166,7 @@ pub fn detect_unknown_fields(raw_toml: &str) -> Vec { } } else { diagnostics.push(CompatibilityDiagnostic { - code: "I-FIELD-UNKNOWN".to_string(), + code: diagnostic_code("I-FIELD-UNKNOWN"), entry_index: Some(i), field: Some(key.clone()), severity: DiagnosticSeverity::Info, @@ -180,7 +182,7 @@ pub fn detect_unknown_fields(raw_toml: &str) -> Vec { && !table.contains_key("name") { diagnostics.push(CompatibilityDiagnostic { - code: "W-DESC-MISSING".to_string(), + code: diagnostic_code("W-DESC-MISSING"), entry_index: Some(i), field: Some("description".to_string()), severity: DiagnosticSeverity::Warning, @@ -195,7 +197,7 @@ pub fn detect_unknown_fields(raw_toml: &str) -> Vec { && !table.contains_key("cmd") { diagnostics.push(CompatibilityDiagnostic { - code: "W-CMD-MISSING".to_string(), + code: diagnostic_code("W-CMD-MISSING"), entry_index: Some(i), field: Some("command".to_string()), severity: DiagnosticSeverity::Warning, @@ -215,7 +217,7 @@ pub fn analyze_entry(index: usize, pet: &Snippet) -> Vec Vec Vec Vec Vec Vec &'static str { + /// Per-action category label (distinct from per-finding `RepairItem::category`). + pub fn action_category(&self) -> &'static str { match self { RepairAction::PruneOrphanedUsage => "usage", RepairAction::RollbackTransaction { .. } => "transaction", @@ -109,6 +112,45 @@ impl RepairAction { ) } + pub fn severity(&self) -> DiagnosticSeverity { + self.diagnostic_code() + .severity() + .unwrap_or(DiagnosticSeverity::Info) + } + + pub fn repairability(&self) -> DiagnosticRepairability { + if self.is_safe() { + DiagnosticRepairability::Auto + } else { + DiagnosticRepairability::Manual + } + } + + pub fn diagnostic_code(&self) -> DiagnosticCode { + diagnostic_code(self.diagnostic_code_str()) + } + + fn diagnostic_code_str(&self) -> &'static str { + match self { + RepairAction::PruneOrphanedUsage => "W-USAGE-ORPHAN", + RepairAction::RepairLibraryIndex => "W-NO-PRIMARY", + RepairAction::RepairSnippetIds => "W-ID-EMPTY", + RepairAction::RepairTimestamps => "W-DUP-CHECK-SKIPPED", + _ => "I-REPAIR-TX", + } + } + + /// Default per-finding category when no override is supplied. + pub fn default_finding_category(&self) -> &'static str { + match self { + RepairAction::PruneOrphanedUsage => "usage", + RepairAction::RepairLibraryIndex => "index", + RepairAction::RepairSnippetIds => "ids", + RepairAction::RepairTimestamps => "timestamps", + _ => "transaction", + } + } + /// Get the transaction ID for this action, if applicable. pub fn transaction_id(&self) -> Option<&str> { match self { @@ -139,6 +181,32 @@ pub struct RepairItem { /// Target path for the repair action, if applicable. /// This replaces fragile string parsing of the problem description. pub target_path: Option, + pub severity: DiagnosticSeverity, + pub repairability: DiagnosticRepairability, + pub code: DiagnosticCode, +} + +fn push_repair_item( + report: &mut RepairReport, + action: RepairAction, + category: impl Into, + problem: String, + fix: String, + safe: Option, + target_path: Option, +) { + let safe = safe.unwrap_or_else(|| action.is_safe()); + report.items.push(RepairItem { + severity: action.severity(), + repairability: action.repairability(), + code: action.diagnostic_code(), + action, + category: category.into(), + problem, + fix, + safe, + target_path, + }); } /// Exit status for the repair command. @@ -271,18 +339,20 @@ fn collect_repair_candidates(report: &mut RepairReport, library: Option<&str>) - let mgr = match LibraryManager::new() { Ok(m) => m, Err(e) => { - report.items.push(RepairItem { - action: RepairAction::RepairLibraryIndex, - category: "config".to_string(), - problem: format!("Failed to load library manager: {e}"), - fix: "Check ~/.config/snp/libraries.toml for corruption".to_string(), - safe: false, - target_path: None, - }); + push_repair_item( + report, + RepairAction::RepairLibraryIndex, + "config", + format!("Failed to load library manager: {e}"), + "Check ~/.config/snp/libraries.toml for corruption".to_string(), + Some(false), + None, + ); return Ok(()); } }; + let scan = mgr.scan_libraries()?; let libraries_dir = mgr.get_libraries_dir().clone(); // If a specific library was requested, only check that one @@ -297,16 +367,7 @@ fn collect_repair_candidates(report: &mut RepairReport, library: Option<&str>) - )); } } else { - // Check all libraries - if !libraries_dir.exists() { - return Ok(()); - } - fs::read_dir(&libraries_dir) - .map_err(|e| SnipError::io_error("read libraries directory", libraries_dir.clone(), e))? - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|ext| ext == "toml")) - .collect() + scan.disk_library_paths() }; let mut all_ids: std::collections::HashSet = std::collections::HashSet::new(); @@ -323,65 +384,69 @@ fn collect_repair_candidates(report: &mut RepairReport, library: Option<&str>) - // Check for empty IDs for (i, snippet) in snippets.snippets.iter().enumerate() { if snippet.id.is_empty() { - report.items.push(RepairItem { - action: RepairAction::RepairSnippetIds, - category: "ids".to_string(), - problem: format!( + push_repair_item( + report, + RepairAction::RepairSnippetIds, + "ids", + format!( "Snippet {} in '{}' has empty ID", i, lib_path.file_stem().unwrap_or_default().to_string_lossy() ), - fix: "Generate UUID for snippet".to_string(), - safe: false, - target_path: None, - }); + "Generate UUID for snippet".to_string(), + Some(false), + None, + ); } else if !all_ids.insert(snippet.id.clone()) { - report.items.push(RepairItem { - action: RepairAction::RepairSnippetIds, - category: "ids".to_string(), - problem: format!( + push_repair_item( + report, + RepairAction::RepairSnippetIds, + "ids", + format!( "Duplicate ID '{}' in '{}'", snippet.id, lib_path.file_stem().unwrap_or_default().to_string_lossy() ), - fix: "Regenerate duplicate ID".to_string(), - safe: false, - target_path: None, - }); + "Regenerate duplicate ID".to_string(), + Some(false), + None, + ); } } // Check for missing timestamps for (i, snippet) in snippets.snippets.iter().enumerate() { if snippet.created_at == 0 || snippet.updated_at == 0 { - report.items.push(RepairItem { - action: RepairAction::RepairTimestamps, - category: "timestamps".to_string(), - problem: format!( + push_repair_item( + report, + RepairAction::RepairTimestamps, + "timestamps", + format!( "Snippet {} ('{}') in '{}' has zero timestamp", i, snippet.description, lib_path.file_stem().unwrap_or_default().to_string_lossy() ), - fix: "Set timestamps to current time".to_string(), - safe: false, - target_path: None, - }); + "Set timestamps to current time".to_string(), + Some(false), + None, + ); } } } Err(e) => { - report.items.push(RepairItem { - action: RepairAction::RepairLibraryIndex, - category: "config".to_string(), - problem: format!( + push_repair_item( + report, + RepairAction::RepairLibraryIndex, + "config", + format!( "Failed to load '{}': {e}", lib_path.file_stem().unwrap_or_default().to_string_lossy() ), - fix: "Check file for TOML syntax errors".to_string(), - safe: false, - target_path: None, - }); + "Check file for TOML syntax errors".to_string(), + Some(false), + None, + ); } } } @@ -389,16 +454,17 @@ fn collect_repair_candidates(report: &mut RepairReport, library: Option<&str>) - // Check primary library selection via the shared index inspection so // `repair` classifies the same primary state as `validate`/`doctor`. // Rendering into `RepairItem` stays local to preserve repair semantics. - match &mgr.inspect_library_index().primary { + match &scan.primary { crate::library::PrimaryState::FileMissing { name, .. } => { - report.items.push(RepairItem { - action: RepairAction::RepairLibraryIndex, - category: "primary".to_string(), - problem: format!("Primary library '{name}' references missing file"), - fix: "Promote first available library to primary".to_string(), - safe: false, - target_path: None, - }); + push_repair_item( + report, + RepairAction::RepairLibraryIndex, + "primary", + format!("Primary library '{name}' references missing file"), + "Promote first available library to primary".to_string(), + Some(false), + None, + ); } crate::library::PrimaryState::NoPrimary { count } => { // No primary set — check if we can auto-assign @@ -408,23 +474,25 @@ fn collect_repair_candidates(report: &mut RepairReport, library: Option<&str>) - .first() .map(|l| l.filename.clone()) .unwrap_or_default(); - report.items.push(RepairItem { - action: RepairAction::RepairLibraryIndex, - category: "primary".to_string(), - problem: "No primary library is set (only one library exists)".to_string(), - fix: format!("Set '{name}' as primary"), - safe: false, - target_path: None, - }); + push_repair_item( + report, + RepairAction::RepairLibraryIndex, + "primary", + "No primary library is set (only one library exists)".to_string(), + format!("Set '{name}' as primary"), + Some(false), + None, + ); } else if *count > 0 { - report.items.push(RepairItem { - action: RepairAction::RepairLibraryIndex, - category: "primary".to_string(), - problem: "No primary library is set".to_string(), - fix: "Run 'snp library set-primary ' to choose one".to_string(), - safe: false, - target_path: None, - }); + push_repair_item( + report, + RepairAction::RepairLibraryIndex, + "primary", + "No primary library is set".to_string(), + "Run 'snp library set-primary ' to choose one".to_string(), + Some(false), + None, + ); } } crate::library::PrimaryState::Present { .. } @@ -442,14 +510,15 @@ fn collect_repair_candidates(report: &mut RepairReport, library: Option<&str>) - .collect(); let orphaned_count = crate::library::find_orphaned_ids(&active_id_set, &usage_ids).len(); if orphaned_count > 0 { - report.items.push(RepairItem { - action: RepairAction::PruneOrphanedUsage, - category: "usage".to_string(), - problem: format!("{orphaned_count} orphaned usage entries (snippets no longer exist)"), - fix: "Remove orphaned usage entries".to_string(), - safe: true, - target_path: None, - }); + push_repair_item( + report, + RepairAction::PruneOrphanedUsage, + "usage", + format!("{orphaned_count} orphaned usage entries (snippets no longer exist)"), + "Remove orphaned usage entries".to_string(), + Some(true), + None, + ); } Ok(()) @@ -464,20 +533,21 @@ fn collect_transaction_repairs(report: &mut RepairReport) -> SnipResult<()> { // Fail closed on corrupt journals. for corrupt in &inventory.corrupt { - report.items.push(RepairItem { - action: RepairAction::RollbackTransaction { + push_repair_item( + report, + RepairAction::RollbackTransaction { transaction_id: corrupt.path.display().to_string(), }, - category: "unsafe".to_string(), - problem: format!( + "unsafe", + format!( "Corrupt transaction journal '{}': {}", corrupt.path.display(), corrupt.error ), - fix: "Requires manual quarantine or deletion".to_string(), - safe: false, - target_path: Some(corrupt.path.clone()), - }); + "Requires manual quarantine or deletion".to_string(), + Some(false), + Some(corrupt.path.clone()), + ); } for journal in &inventory.journals { @@ -486,21 +556,22 @@ fn collect_transaction_repairs(report: &mut RepairReport) -> SnipResult<()> { Ok(class) => class, Err(e) => { // Unsafe artifact inspection failure — report as unsafe/manual. - report.items.push(RepairItem { - action: RepairAction::RollbackTransaction { + push_repair_item( + report, + RepairAction::RollbackTransaction { transaction_id: journal.id.clone(), }, - category: "unsafe".to_string(), - problem: format!( + "unsafe", + format!( "Transaction '{}' (op: {}) has unsafe artifacts: {e}", crate::transaction::short_transaction_id(&journal.id), journal.operation, ), - fix: "Requires manual investigation — preserve journal and artifacts" + "Requires manual investigation — preserve journal and artifacts" .to_string(), - safe: false, - target_path: None, - }); + Some(false), + None, + ); continue; } }; @@ -533,21 +604,21 @@ fn collect_transaction_repairs(report: &mut RepairReport) -> SnipResult<()> { } } crate::transaction::RecoveryClass::UnsafeFailed => { - report.items.push(RepairItem { - action: RepairAction::RollbackTransaction { + push_repair_item( + report, + RepairAction::RollbackTransaction { transaction_id: journal.id.clone(), }, - category: "unsafe".to_string(), - problem: format!( + "unsafe", + format!( "Transaction '{}' (op: {}) is in a Failed state", crate::transaction::short_transaction_id(&journal.id), journal.operation, ), - fix: "Requires manual investigation — preserve journal and artifacts" - .to_string(), - safe: false, - target_path: None, - }); + "Requires manual investigation — preserve journal and artifacts".to_string(), + Some(false), + None, + ); continue; } }; @@ -564,19 +635,20 @@ fn collect_transaction_repairs(report: &mut RepairReport) -> SnipResult<()> { _ => "Repair transaction", }; - report.items.push(RepairItem { + push_repair_item( + report, action, - category: "transaction".to_string(), - problem: format!( + "transaction", + format!( "Transaction '{}' (op: {}, state: {:?})", crate::transaction::short_transaction_id(&journal.id), journal.operation, journal.state ), - fix: fix.to_string(), - safe: true, - target_path: None, - }); + fix.to_string(), + Some(true), + None, + ); } // Scan for orphaned artifact directories — directories under @@ -638,17 +710,18 @@ fn collect_orphan_artifact_repairs(report: &mut RepairReport, state_dir: &Path) { let id = dir_name.to_string_lossy().to_string(); if !journal_ids.contains(&id) { - report.items.push(RepairItem { - action: RepairAction::RemoveOrphanedArtifact, - category: "transaction".to_string(), - problem: format!( + push_repair_item( + report, + RepairAction::RemoveOrphanedArtifact, + "transaction", + format!( "Orphaned transaction artifact directory '{}'", path.display() ), - fix: "Remove orphaned artifact directory".to_string(), - safe: true, - target_path: Some(path.clone()), - }); + "Remove orphaned artifact directory".to_string(), + Some(true), + Some(path.clone()), + ); } } } @@ -850,85 +923,128 @@ fn collect_active_snippet_ids() -> Vec { Ok(m) => m, Err(_) => return ids, }; - let libraries_dir = mgr.get_libraries_dir().clone(); - if !libraries_dir.exists() { + let Ok(scan) = mgr.scan_libraries() else { return ids; - } - if let Ok(entries) = fs::read_dir(&libraries_dir) { - for entry in entries.filter_map(|e| e.ok()) { - let path = entry.path(); - if path.extension().is_some_and(|ext| ext == "toml") - && let Ok(snippets) = crate::library::load_library(&path) - { - for snippet in &snippets.snippets { - ids.push(snippet.id.clone()); - } + }; + for path in scan.disk_library_paths() { + if let Ok(snippets) = crate::library::load_library(&path) { + for snippet in &snippets.snippets { + ids.push(snippet.id.clone()); } } } ids } -/// Create a timestamped backup of the entire config directory for repair. +/// Create a timestamped, manifest-backed repair backup restorable by `snp restore`. +/// +/// Uses the shared copy-source admission half and the same +/// [`super::backup_archive::atomic_write_backup`] writer as `snp backup`, so +/// symlink / non-regular / escaped sources fail the repair before any mutation +/// and the backup carries a `manifest.toml`. fn create_repair_backup() -> SnipResult { + use super::backup_archive::{ + BackupEntryKind, BackupManifest, BackupManifestEntry, atomic_write_backup, + read_for_snapshot, sha256_hex, validate_canonical_containment, + }; + let config_dir = crate::utils::config::get_config_dir(); + let canonical_config = config_dir.canonicalize().map_err(|e| { + SnipError::io_error( + "canonicalize config directory for repair backup", + &config_dir, + e, + ) + })?; let backup_root = config_dir.join("backups"); fs::create_dir_all(&backup_root) .map_err(|e| SnipError::io_error("create backup directory", backup_root.clone(), e))?; let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S"); let backup_dir = backup_root.join(format!("repair-{timestamp}-{}", uuid::Uuid::new_v4())); - fs::create_dir(&backup_dir).map_err(|e| { - SnipError::io_error("create repair backup directory", backup_dir.clone(), e) - })?; + let staging_dir = backup_dir.with_extension(format!("staging.{}", uuid::Uuid::new_v4())); + + let mut manifest = BackupManifest { + schema: 1, + created_at_unix_ms: chrono::Utc::now().timestamp_millis(), + snip_it_version: crate::diagnostics::version().to_string(), + layout: "directory".to_string(), + files: Vec::new(), + }; + let mut backup_files: Vec<(String, String, Vec)> = Vec::new(); - // Copy libraries directory let libraries_dir = config_dir.join("libraries"); if libraries_dir.exists() { - let dest = backup_dir.join("libraries"); - copy_dir_recursive(&libraries_dir, &dest)?; + let entries: Vec<_> = fs::read_dir(&libraries_dir) + .map_err(|e| SnipError::io_error("read libraries directory", libraries_dir.clone(), e))? + .filter_map(|e| e.ok()) + .filter(|e| { + let name = e.file_name().to_string_lossy().to_string(); + name.ends_with(".toml") && !name.starts_with('.') + }) + .collect(); + for entry in &entries { + let file_name = entry.file_name().to_string_lossy().to_string(); + let src = entry.path(); + validate_canonical_containment(&src, &canonical_config, "library file")?; + let bytes = read_for_snapshot(&src, "library")?; + let sha = sha256_hex(&bytes); + let rel = format!("libraries/{file_name}"); + manifest.files.push(BackupManifestEntry { + path: rel.clone(), + kind: BackupEntryKind::Library, + size: bytes.len() as u64, + sha256: sha, + }); + backup_files.push((rel, BackupEntryKind::Library.to_string(), bytes)); + } } - // Copy libraries.toml let config_file = config_dir.join("libraries.toml"); if config_file.exists() { - let dest = backup_dir.join("libraries.toml"); - fs::copy(&config_file, &dest) - .map_err(|e| SnipError::io_error("copy libraries.toml into repair backup", dest, e))?; + validate_canonical_containment(&config_file, &canonical_config, "libraries index")?; + let bytes = read_for_snapshot(&config_file, "libraries index")?; + let sha = sha256_hex(&bytes); + manifest.files.push(BackupManifestEntry { + path: "libraries.toml".to_string(), + kind: BackupEntryKind::Index, + size: bytes.len() as u64, + sha256: sha, + }); + backup_files.push(( + "libraries.toml".to_string(), + BackupEntryKind::Index.to_string(), + bytes, + )); } - // Copy usage.toml let usage_file = config_dir.join("usage.toml"); if usage_file.exists() { - let dest = backup_dir.join("usage.toml"); - fs::copy(&usage_file, &dest) - .map_err(|e| SnipError::io_error("copy usage.toml into repair backup", dest, e))?; + validate_canonical_containment(&usage_file, &canonical_config, "usage")?; + let bytes = read_for_snapshot(&usage_file, "usage")?; + let sha = sha256_hex(&bytes); + manifest.files.push(BackupManifestEntry { + path: "usage.toml".to_string(), + kind: BackupEntryKind::Usage, + size: bytes.len() as u64, + sha256: sha, + }); + backup_files.push(( + "usage.toml".to_string(), + BackupEntryKind::Usage.to_string(), + bytes, + )); } + manifest.files.sort_by(|a, b| a.path.cmp(&b.path)); + let file_refs: Vec<(&str, &str, &[u8])> = backup_files + .iter() + .map(|(path, kind, bytes)| (path.as_str(), kind.as_str(), bytes.as_slice())) + .collect(); + atomic_write_backup(&staging_dir, &backup_dir, &file_refs, &manifest)?; Ok(backup_dir) } -/// Recursively copy a directory. -fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> SnipResult<()> { - fs::create_dir_all(dst) - .map_err(|e| SnipError::io_error("create backup subdirectory", dst.to_path_buf(), e))?; - for entry in fs::read_dir(src) - .map_err(|e| SnipError::io_error("read source directory", src.to_path_buf(), e))? - { - let entry = - entry.map_err(|e| SnipError::io_error("read directory entry", src.to_path_buf(), e))?; - let src_path = entry.path(); - let dst_path = dst.join(entry.file_name()); - if src_path.is_dir() { - copy_dir_recursive(&src_path, &dst_path)?; - } else { - fs::copy(&src_path, &dst_path) - .map_err(|e| SnipError::io_error("copy file for backup", src_path.clone(), e))?; - } - } - Ok(()) -} - /// Emit the repair report in human-readable format. fn emit_human_report(report: &RepairReport) { eprintln!(); @@ -1051,8 +1167,6 @@ fn emit_json_report(report: &RepairReport) -> SnipResult<()> { #[cfg(test)] mod tests { use super::*; - use tempfile::TempDir; - #[test] fn test_repair_report_default() { let report = RepairReport::default(); @@ -1062,34 +1176,54 @@ mod tests { #[test] fn test_repair_item_creation() { - let item = RepairItem { - action: RepairAction::PruneOrphanedUsage, - category: "usage".to_string(), - problem: "orphaned entries".to_string(), - fix: "prune".to_string(), - safe: true, - target_path: None, - }; + let mut report = RepairReport::default(); + push_repair_item( + &mut report, + RepairAction::PruneOrphanedUsage, + "usage", + "orphaned entries".to_string(), + "prune".to_string(), + Some(true), + None, + ); + let item = &report.items[0]; assert!(item.safe); assert_eq!(item.category, "usage"); assert_eq!(item.action, RepairAction::PruneOrphanedUsage); + assert_eq!(item.code, "W-USAGE-ORPHAN"); } #[test] - fn test_copy_dir_recursive() { - let src = TempDir::new().unwrap(); - let dst = TempDir::new().unwrap(); - - // Create source structure - fs::write(src.path().join("file.txt"), "hello").unwrap(); - fs::create_dir(src.path().join("sub")).unwrap(); - fs::write(src.path().join("sub").join("nested.txt"), "world").unwrap(); - - let dest = dst.path().join("copy"); - copy_dir_recursive(src.path(), &dest).unwrap(); - - assert!(dest.join("file.txt").exists()); - assert!(dest.join("sub").join("nested.txt").exists()); - assert_eq!(fs::read_to_string(dest.join("file.txt")).unwrap(), "hello"); + fn test_repair_action_repairability_matches_is_safe() { + let actions = [ + RepairAction::PruneOrphanedUsage, + RepairAction::RollbackTransaction { + transaction_id: "tx".to_string(), + }, + RepairAction::ResumeCleanup { + transaction_id: "tx".to_string(), + }, + RepairAction::FinalizeCommittedLocal { + transaction_id: "tx".to_string(), + }, + RepairAction::CleanupLegacyCommitted { + transaction_id: "tx".to_string(), + }, + RepairAction::CleanupLegacyRolledBack { + transaction_id: "tx".to_string(), + }, + RepairAction::RemoveTerminalJournal { + transaction_id: "tx".to_string(), + }, + RepairAction::RemoveOrphanedArtifact, + RepairAction::RepairLibraryIndex, + RepairAction::RepairSnippetIds, + RepairAction::RepairTimestamps, + ]; + for action in &actions { + let safe = action.is_safe(); + let auto = action.repairability() == DiagnosticRepairability::Auto; + assert_eq!(safe, auto, "mismatch for {action:?}"); + } } } diff --git a/src/commands/restore_cmd.rs b/src/commands/restore_cmd.rs index 702d976c..883b9731 100644 --- a/src/commands/restore_cmd.rs +++ b/src/commands/restore_cmd.rs @@ -768,61 +768,44 @@ fn create_pre_restore_backup(config_dir: &Path) -> SnipResult> { SnipError::io_error("create pre-restore backup dir", backup_base.clone(), e) })?; - /// Copy one file into the snapshot, refusing symlinks and non-regular - /// files. - /// - /// `fs::copy` follows symlinks, so a library file that is a symlink to a - /// file outside the config directory would silently copy that target's - /// content into the snapshot. The snapshot must only ever contain the - /// config's own regular files. - fn copy_regular_file(src: &Path, dst: &Path, label: &str) -> SnipResult { - let meta = match fs::symlink_metadata(src) { - Ok(meta) => meta, - Err(e) => { - tracing::warn!(error = %e, path = %src.display(), "skipping unreadable entry during pre-restore backup"); - return Ok(false); - } - }; - if meta.file_type().is_symlink() { - tracing::warn!( - path = %src.display(), - "skipping symlinked entry during pre-restore backup" - ); - return Ok(false); - } - if !meta.is_file() { - tracing::warn!( - path = %src.display(), - "skipping non-regular entry during pre-restore backup" - ); - return Ok(false); - } - if let Some(parent) = dst.parent() { - fs::create_dir_all(parent) - .map_err(|e| SnipError::io_error("create backup subdir", parent, e))?; - } - fs::copy(src, dst) - .map_err(|e| SnipError::io_error(&format!("copy {label} to backup"), dst, e))?; - Ok(true) - } + // Source refusal (symlink / non-regular / outside config) is a hard error + // that aborts the restore before any live configuration is modified. A + // silently incomplete pre-restore backup is not a valid rollback point. + let canonical_config = config_dir.canonicalize().map_err(|e| { + SnipError::io_error( + "canonicalize config directory for pre-restore backup", + config_dir, + e, + ) + })?; + let options = crate::utils::atomic::CopyOptions { + source: crate::utils::atomic::CopySourcePolicy::Contained { + root: canonical_config, + }, + durability: crate::utils::atomic::Durability::DurableUserData, + }; let libraries_dir = config_dir.join("libraries"); if libraries_dir.exists() { for entry in fs::read_dir(&libraries_dir) .map_err(|e| SnipError::io_error("read libraries dir", libraries_dir.clone(), e))? { - let entry = match entry { - Ok(e) => e, - Err(e) => { - tracing::warn!(error = %e, "skipping unreadable library entry during pre-restore backup"); - continue; - } - }; + let entry = entry.map_err(|e| { + SnipError::io_error( + "read library entry during pre-restore backup", + &libraries_dir, + e, + ) + })?; let file_name = entry.file_name(); let src = entry.path(); if src.extension().is_some_and(|ext| ext == "toml") { let dst = backup_base.join("libraries").join(&file_name); - copy_regular_file(&src, &dst, "library")?; + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent) + .map_err(|e| SnipError::io_error("create backup subdir", parent, e))?; + } + crate::utils::atomic::copy_file(&src, &dst, &options)?; } } } @@ -831,15 +814,11 @@ fn create_pre_restore_backup(config_dir: &Path) -> SnipResult> { // cover every file the restore can overwrite: the library index plus the // usage index and the sync configuration (both installed in replace // mode). - for (file_name, label) in [ - ("libraries.toml", "index"), - ("usage.toml", "usage"), - ("sync.toml", "sync config"), - ] { + for file_name in ["libraries.toml", "usage.toml", "sync.toml"] { let src = config_dir.join(file_name); if src.exists() { let dst = backup_base.join(file_name); - copy_regular_file(&src, &dst, label)?; + crate::utils::atomic::copy_file(&src, &dst, &options)?; } } diff --git a/src/commands/validate_cmd.rs b/src/commands/validate_cmd.rs index 439dfa84..24ea0039 100644 --- a/src/commands/validate_cmd.rs +++ b/src/commands/validate_cmd.rs @@ -2,8 +2,11 @@ //! //! `snp validate` command — comprehensive read-only validation of snippet data. +use crate::diagnostics::{ + DiagnosticCode, DiagnosticRepairability, DiagnosticSeverity, diagnostic_code, version, +}; use crate::error::{SnipError, SnipResult}; -use crate::library::{LibraryManager, Snippet, Snippets}; +use crate::library::{LibraryManager, LibraryScan, Snippet, Snippets}; use crate::outcome::CliOutcome; use crate::usage::UsageIndex; use std::collections::{HashMap, HashSet}; @@ -27,32 +30,16 @@ pub struct ValidateArgs { pub json: bool, } -/// Severity level for validation diagnostics. -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum Severity { - Info, - Warning, - Error, -} - -/// Repairability classification for a diagnostic. -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum Repairability { - Auto, - Manual, - Unrepairable, -} - /// A single validation diagnostic. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ValidationDiagnostic { - pub code: String, - pub severity: Severity, + pub code: DiagnosticCode, + pub severity: DiagnosticSeverity, pub path: Option, pub library: Option, pub snippet_id: Option, pub message: String, - pub repairability: Repairability, + pub repairability: DiagnosticRepairability, } /// Complete validation report. @@ -71,7 +58,7 @@ impl ValidationReport { pub fn new(strict_mode: bool) -> Self { Self { schema_version: "1.0.0".to_string(), - tool_version: crate::diagnostics::version().to_string(), + tool_version: version().to_string(), strict_mode, dry_run: true, total_libraries: 0, @@ -83,27 +70,27 @@ impl ValidationReport { pub fn has_errors(&self) -> bool { self.diagnostics .iter() - .any(|d| d.severity == Severity::Error) + .any(|d| d.severity == DiagnosticSeverity::Error) } pub fn error_count(&self) -> usize { self.diagnostics .iter() - .filter(|d| d.severity == Severity::Error) + .filter(|d| d.severity == DiagnosticSeverity::Error) .count() } pub fn warning_count(&self) -> usize { self.diagnostics .iter() - .filter(|d| d.severity == Severity::Warning) + .filter(|d| d.severity == DiagnosticSeverity::Warning) .count() } pub fn info_count(&self) -> usize { self.diagnostics .iter() - .filter(|d| d.severity == Severity::Info) + .filter(|d| d.severity == DiagnosticSeverity::Info) .count() } } @@ -114,12 +101,12 @@ fn diags( lib_path: Option<&PathBuf>, snippet_id: Option<&str>, code: &str, - severity: Severity, - repairability: Repairability, + severity: DiagnosticSeverity, + repairability: DiagnosticRepairability, message: String, ) { report.diagnostics.push(ValidationDiagnostic { - code: code.to_string(), + code: diagnostic_code(code), severity, path: lib_path.cloned(), library: Some(lib_name.to_string()), @@ -150,8 +137,8 @@ fn validate_library( Some(lib_path), None, "E-FILE-READ", - Severity::Error, - Repairability::Manual, + DiagnosticSeverity::Error, + DiagnosticRepairability::Manual, format!("Failed to read library file: {e}"), ); return; @@ -165,8 +152,8 @@ fn validate_library( Some(lib_path), None, "I-FILE-EMPTY", - Severity::Info, - Repairability::Auto, + DiagnosticSeverity::Info, + DiagnosticRepairability::Auto, "Library file is empty (no snippets)".to_string(), ); return; @@ -182,8 +169,8 @@ fn validate_library( Some(lib_path), None, "E-TOML-PARSE", - Severity::Error, - Repairability::Manual, + DiagnosticSeverity::Error, + DiagnosticRepairability::Manual, format!("TOML parse error: {e}"), ); return; @@ -208,8 +195,8 @@ fn validate_library( Some(lib_path), Some(id), "E-DUP-ID", - Severity::Error, - Repairability::Manual, + DiagnosticSeverity::Error, + DiagnosticRepairability::Manual, format!("Duplicate snippet ID '{id}' found {count} times"), ); } @@ -224,8 +211,8 @@ fn validate_library( Some(lib_path), None, "W-ID-EMPTY", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, format!( "Snippet '{}' has empty ID (load_library assigns IDs on read)", truncate_desc(&s.description) @@ -243,8 +230,8 @@ fn validate_library( Some(lib_path), if s.id.is_empty() { None } else { Some(&s.id) }, "E-CMD-EMPTY", - Severity::Error, - Repairability::Manual, + DiagnosticSeverity::Error, + DiagnosticRepairability::Manual, format!( "Snippet '{}' has empty command", truncate_desc(&s.description) @@ -253,9 +240,9 @@ fn validate_library( } if s.description.trim().is_empty() { let sev = if strict { - Severity::Error + DiagnosticSeverity::Error } else { - Severity::Warning + DiagnosticSeverity::Warning }; diags( report, @@ -264,7 +251,7 @@ fn validate_library( if s.id.is_empty() { None } else { Some(&s.id) }, "W-DESC-EMPTY", sev, - Repairability::Manual, + DiagnosticRepairability::Manual, format!( "Snippet (id={}) has empty description", if s.id.is_empty() { @@ -301,8 +288,8 @@ fn validate_library( Some(lib_path), Some(id), "W-SAME-ID-DIVERGENT", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, format!( "Snippet ID '{id}' appears {} times with divergent content", entries.len() @@ -318,8 +305,8 @@ fn validate_library( Some(lib_path), None, "W-DUP-CHECK-SKIPPED", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, "Same-ID divergent-content check skipped: raw TOML re-parse failed".to_string(), ); } @@ -335,8 +322,8 @@ fn validate_library( Some(lib_path), if s.id.is_empty() { None } else { Some(&s.id) }, "W-EXACT-DUP", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, format!( "Exact duplicate snippet: '{}' / '{}'", truncate_desc(&s.description), @@ -355,8 +342,8 @@ fn validate_library( Some(lib_path), None, "W-CORRUPT-BAK", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, format!( "Corrupt backup exists at {} (indicates previous parse failure)", corrupt_bak.display() @@ -371,8 +358,8 @@ fn validate_library( /// `validate`, `repair`, `doctor`, and `status` classify the same index /// state consistently. Rendering into [`ValidationDiagnostic`] stays local /// to preserve `validate`'s pass/fail plus warnings semantics. -fn validate_index(report: &mut ValidationReport, mgr: &LibraryManager, _strict: bool) { - let inspection = mgr.inspect_library_index(); +fn validate_index(report: &mut ValidationReport, scan: &LibraryScan, _strict: bool) { + let inspection = scan; // h. Check library index references to missing files for (name, expected_path) in &inspection.missing_files { @@ -382,8 +369,8 @@ fn validate_index(report: &mut ValidationReport, mgr: &LibraryManager, _strict: Some(expected_path), None, "E-INDEX-MISSING-FILE", - Severity::Error, - Repairability::Manual, + DiagnosticSeverity::Error, + DiagnosticRepairability::Manual, format!( "Library '{name}' is registered in index but file {} does not exist", expected_path.display() @@ -403,8 +390,8 @@ fn validate_index(report: &mut ValidationReport, mgr: &LibraryManager, _strict: Some(path), None, "W-ORPHAN-FILE", - Severity::Warning, - Repairability::Auto, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Auto, format!( "File {} is not registered in the library index", path.display() @@ -421,8 +408,8 @@ fn validate_index(report: &mut ValidationReport, mgr: &LibraryManager, _strict: Some(path), None, "E-PRIMARY-MISSING", - Severity::Error, - Repairability::Manual, + DiagnosticSeverity::Error, + DiagnosticRepairability::Manual, format!( "Primary library '{name}' file does not exist at {}", path.display() @@ -443,8 +430,8 @@ fn validate_index(report: &mut ValidationReport, mgr: &LibraryManager, _strict: None, None, "W-NO-PRIMARY", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, "No primary library is set but libraries exist".to_string(), ); } @@ -458,7 +445,7 @@ fn validate_index(report: &mut ValidationReport, mgr: &LibraryManager, _strict: /// Shares [`crate::library::find_orphaned_ids`] with `repair` so both /// commands classify the same usage state consistently; rendering into /// [`ValidationDiagnostic`] stays local to `validate`. -fn validate_usage(report: &mut ValidationReport, _mgr: &LibraryManager) { +fn validate_usage(report: &mut ValidationReport, scan: &LibraryScan) { // k. Orphaned usage entries let usage_index = UsageIndex::load(); if usage_index.entries().is_empty() { @@ -468,44 +455,28 @@ fn validate_usage(report: &mut ValidationReport, _mgr: &LibraryManager) { // Collect all active snippet IDs across all visible libraries via the // canonical read-only resolver (no migration, no writes). let mut active_ids: HashSet = HashSet::new(); - match crate::library::readonly_library_sources(Some("all")) { - Ok(sources) => { - for source in &sources { - match crate::library::load_library(&source.path) { - Ok(snippets) => { - for s in &snippets.snippets { - active_ids.insert(s.id.clone()); - } - } - Err(e) => { - diags( - report, - &source.name, - Some(&source.path), - None, - "W-LIB-UNREADABLE", - Severity::Warning, - Repairability::Manual, - format!( - "Library '{}' could not be read ({e}); excluded from usage-orphan check", - source.name - ), - ); - } + for source in &scan.sources { + match crate::library::load_library(&source.path) { + Ok(snippets) => { + for s in &snippets.snippets { + active_ids.insert(s.id.clone()); } } - } - Err(e) => { - diags( - report, - "", - None, - None, - "W-LIB-INDEX-UNREADABLE", - Severity::Warning, - Repairability::Manual, - format!("Library index could not be read ({e}); usage-orphan check skipped"), - ); + Err(e) => { + diags( + report, + &source.name, + Some(&source.path), + None, + "W-LIB-UNREADABLE", + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, + format!( + "Library '{}' could not be read ({e}); excluded from usage-orphan check", + source.name + ), + ); + } } } @@ -521,8 +492,8 @@ fn validate_usage(report: &mut ValidationReport, _mgr: &LibraryManager) { None, Some(&orphan_id), "W-USAGE-ORPHAN", - Severity::Warning, - Repairability::Auto, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Auto, format!( "Usage entry for snippet '{orphan_id}' references a snippet not found in any library" ), @@ -558,8 +529,8 @@ fn validate_permissions(report: &mut ValidationReport, _strict: bool) { Some(path), None, "W-INSECURE-PERMS", - Severity::Warning, - Repairability::Manual, + DiagnosticSeverity::Warning, + DiagnosticRepairability::Manual, format!( "File {} has permissions {:o} (recommended: 0600)", path.display(), @@ -591,7 +562,7 @@ fn emit_human(report: &ValidationReport) { eprintln!(); eprintln!("Errors ({errors}):"); for d in &report.diagnostics { - if d.severity == Severity::Error { + if d.severity == DiagnosticSeverity::Error { emit_diagnostic(d); } } @@ -601,7 +572,7 @@ fn emit_human(report: &ValidationReport) { eprintln!(); eprintln!("Warnings ({warnings}):"); for d in &report.diagnostics { - if d.severity == Severity::Warning { + if d.severity == DiagnosticSeverity::Warning { emit_diagnostic(d); } } @@ -611,7 +582,7 @@ fn emit_human(report: &ValidationReport) { eprintln!(); eprintln!("Info ({infos}):"); for d in &report.diagnostics { - if d.severity == Severity::Info { + if d.severity == DiagnosticSeverity::Info { emit_diagnostic(d); } } @@ -633,9 +604,9 @@ fn emit_diagnostic(d: &ValidationDiagnostic) { .map(|s| format!(" [snippet:{s}]")) .unwrap_or_default(); let repair = match d.repairability { - Repairability::Auto => " (auto-repairable)", - Repairability::Manual => " (manual fix required)", - Repairability::Unrepairable => " (unrepairable)", + DiagnosticRepairability::Auto => " (auto-repairable)", + DiagnosticRepairability::Manual => " (manual fix required)", + DiagnosticRepairability::Unrepairable => " (unrepairable)", }; eprintln!( " [{code}] {lib}{snippet}: {msg}{repair}", @@ -672,48 +643,49 @@ pub fn run(library: Option, strict: bool, json: bool) -> SnipResult = match library.as_deref() { - Some(name) => crate::library::readonly_library_sources(Some(name)).map_err(|e| { - // Preserve the historical CLI detail wording for unknown names. - match e { - SnipError::Runtime { message, .. } if message == "Library not found" => { - crate::library::library_not_found(name) - } - other => other, - } - })?, - None => crate::library::readonly_library_sources(Some("all"))?, + let scan = match library.as_deref() { + Some(name) => { + let mut partial = mgr.scan_libraries()?; + partial.sources = mgr + .resolve_readonly_sources(Some(name)) + .map_err(|e| match e { + SnipError::Runtime { message, .. } if message == "Library not found" => { + crate::library::library_not_found(name) + } + other => other, + })?; + partial + } + None => mgr.scan_libraries()?, }; - report.total_libraries = sources.len(); + report.total_libraries = scan.sources.len(); // a. Validate each library - for source in &sources { + for source in &scan.sources { validate_library(&mut report, &source.name, &source.path, strict); } // h, i, j. Validate index cross-references - validate_index(&mut report, &mgr, strict); + validate_index(&mut report, &scan, strict); // k. Validate orphaned usage entries - validate_usage(&mut report, &mgr); + validate_usage(&mut report, &scan); // l. Validate file permissions validate_permissions(&mut report, strict); // Strict mode: elevate warnings to errors for designated codes if strict { - const STRICT_CODES: &[&str] = &[ - "W-ID-EMPTY", - "W-DESC-EMPTY", - "W-SAME-ID-DIVERGENT", - "W-EXACT-DUP", - ]; for d in &mut report.diagnostics { - if d.severity == Severity::Warning && STRICT_CODES.contains(&d.code.as_str()) { - d.severity = Severity::Error; + if d.severity == DiagnosticSeverity::Warning + && d.code.is_strict_elevatable() + && matches!( + d.code.as_str(), + "W-ID-EMPTY" | "W-DESC-EMPTY" | "W-SAME-ID-DIVERGENT" | "W-EXACT-DUP" + ) + { + d.severity = DiagnosticSeverity::Error; } } } @@ -780,31 +752,31 @@ mod tests { fn test_report_counts() { let mut report = ValidationReport::new(false); report.diagnostics.push(ValidationDiagnostic { - code: "E-TEST".to_string(), - severity: Severity::Error, + code: diagnostic_code("E-TEST"), + severity: DiagnosticSeverity::Error, path: None, library: None, snippet_id: None, message: "err".to_string(), - repairability: Repairability::Manual, + repairability: DiagnosticRepairability::Manual, }); report.diagnostics.push(ValidationDiagnostic { - code: "W-TEST".to_string(), - severity: Severity::Warning, + code: diagnostic_code("W-TEST"), + severity: DiagnosticSeverity::Warning, path: None, library: None, snippet_id: None, message: "warn".to_string(), - repairability: Repairability::Auto, + repairability: DiagnosticRepairability::Auto, }); report.diagnostics.push(ValidationDiagnostic { - code: "I-TEST".to_string(), - severity: Severity::Info, + code: diagnostic_code("I-TEST"), + severity: DiagnosticSeverity::Info, path: None, library: None, snippet_id: None, message: "info".to_string(), - repairability: Repairability::Unrepairable, + repairability: DiagnosticRepairability::Unrepairable, }); assert!(report.has_errors()); @@ -831,7 +803,7 @@ mod tests { assert_eq!(report.diagnostics.len(), 1); assert_eq!(report.diagnostics[0].code, "I-FILE-EMPTY"); - assert_eq!(report.diagnostics[0].severity, Severity::Info); + assert_eq!(report.diagnostics[0].severity, DiagnosticSeverity::Info); } #[test] @@ -898,7 +870,7 @@ mod tests { .filter(|d| d.code == "W-DESC-EMPTY") .collect(); assert_eq!(desc_diags.len(), 1); - assert_eq!(desc_diags[0].severity, Severity::Warning); + assert_eq!(desc_diags[0].severity, DiagnosticSeverity::Warning); } #[test] @@ -920,7 +892,7 @@ mod tests { .filter(|d| d.code == "W-DESC-EMPTY") .collect(); assert_eq!(desc_diags.len(), 1); - assert_eq!(desc_diags[0].severity, Severity::Error); + assert_eq!(desc_diags[0].severity, DiagnosticSeverity::Error); } #[test] @@ -942,7 +914,7 @@ mod tests { .filter(|d| d.code == "E-CMD-EMPTY") .collect(); assert_eq!(cmd_diags.len(), 1); - assert_eq!(cmd_diags[0].severity, Severity::Error); + assert_eq!(cmd_diags[0].severity, DiagnosticSeverity::Error); } #[test] @@ -991,7 +963,7 @@ mod tests { .filter(|d| d.code == "W-SAME-ID-DIVERGENT") .collect(); assert_eq!(div_diags.len(), 1); - assert_eq!(div_diags[0].repairability, Repairability::Manual); + assert_eq!(div_diags[0].repairability, DiagnosticRepairability::Manual); } #[test] @@ -1009,7 +981,10 @@ mod tests { .filter(|d| d.code == "E-TOML-PARSE") .collect(); assert_eq!(parse_diags.len(), 1); - assert_eq!(parse_diags[0].repairability, Repairability::Manual); + assert_eq!( + parse_diags[0].repairability, + DiagnosticRepairability::Manual + ); } #[test] @@ -1028,9 +1003,10 @@ mod tests { .unwrap(); let mgr = LibraryManager::with_config_dir(config_dir).unwrap(); + let scan = mgr.scan_libraries().unwrap(); let mut report = ValidationReport::new(false); - validate_index(&mut report, &mgr, false); + validate_index(&mut report, &scan, false); let missing_diags: Vec<_> = report .diagnostics @@ -1050,9 +1026,10 @@ mod tests { write_libraries_toml(&config_dir, &[]); let mgr = LibraryManager::with_config_dir(config_dir).unwrap(); + let scan = mgr.scan_libraries().unwrap(); let mut report = ValidationReport::new(false); - validate_index(&mut report, &mgr, false); + validate_index(&mut report, &scan, false); let orphan_diags: Vec<_> = report .diagnostics @@ -1060,7 +1037,7 @@ mod tests { .filter(|d| d.code == "W-ORPHAN-FILE") .collect(); assert_eq!(orphan_diags.len(), 1); - assert_eq!(orphan_diags[0].repairability, Repairability::Auto); + assert_eq!(orphan_diags[0].repairability, DiagnosticRepairability::Auto); } #[test] @@ -1072,9 +1049,10 @@ mod tests { write_libraries_toml(&config_dir, &[LibraryMeta::new("lib1")]); let mgr = LibraryManager::with_config_dir(config_dir).unwrap(); + let scan = mgr.scan_libraries().unwrap(); let mut report = ValidationReport::new(false); - validate_index(&mut report, &mgr, false); + validate_index(&mut report, &scan, false); let primary_diags: Vec<_> = report .diagnostics @@ -1088,22 +1066,22 @@ mod tests { fn test_strict_mode_elevates_warnings() { let mut report = ValidationReport::new(true); report.diagnostics.push(ValidationDiagnostic { - code: "W-ID-EMPTY".to_string(), - severity: Severity::Warning, + code: diagnostic_code("W-ID-EMPTY"), + severity: DiagnosticSeverity::Warning, path: None, library: None, snippet_id: None, message: "test".to_string(), - repairability: Repairability::Auto, + repairability: DiagnosticRepairability::Auto, }); report.diagnostics.push(ValidationDiagnostic { - code: "W-OTHER".to_string(), - severity: Severity::Warning, + code: diagnostic_code("W-OTHER"), + severity: DiagnosticSeverity::Warning, path: None, library: None, snippet_id: None, message: "other".to_string(), - repairability: Repairability::Auto, + repairability: DiagnosticRepairability::Auto, }); // Simulate strict elevation @@ -1114,13 +1092,14 @@ mod tests { "W-EXACT-DUP", ]; for d in &mut report.diagnostics { - if d.severity == Severity::Warning && STRICT_CODES.contains(&d.code.as_str()) { - d.severity = Severity::Error; + if d.severity == DiagnosticSeverity::Warning && STRICT_CODES.contains(&d.code.as_str()) + { + d.severity = DiagnosticSeverity::Error; } } - assert_eq!(report.diagnostics[0].severity, Severity::Error); - assert_eq!(report.diagnostics[1].severity, Severity::Warning); + assert_eq!(report.diagnostics[0].severity, DiagnosticSeverity::Error); + assert_eq!(report.diagnostics[1].severity, DiagnosticSeverity::Warning); } #[test] @@ -1161,9 +1140,13 @@ mod tests { #[test] fn test_severity_serialization_roundtrip() { - for sev in [Severity::Info, Severity::Warning, Severity::Error] { + for sev in [ + DiagnosticSeverity::Info, + DiagnosticSeverity::Warning, + DiagnosticSeverity::Error, + ] { let json = serde_json::to_string(&sev).unwrap(); - let back: Severity = serde_json::from_str(&json).unwrap(); + let back: DiagnosticSeverity = serde_json::from_str(&json).unwrap(); assert_eq!(sev, back); } } @@ -1171,12 +1154,12 @@ mod tests { #[test] fn test_repairability_serialization_roundtrip() { for rep in [ - Repairability::Auto, - Repairability::Manual, - Repairability::Unrepairable, + DiagnosticRepairability::Auto, + DiagnosticRepairability::Manual, + DiagnosticRepairability::Unrepairable, ] { let json = serde_json::to_string(&rep).unwrap(); - let back: Repairability = serde_json::from_str(&json).unwrap(); + let back: DiagnosticRepairability = serde_json::from_str(&json).unwrap(); assert_eq!(rep, back); } } @@ -1184,18 +1167,18 @@ mod tests { #[test] fn test_validation_diagnostic_serialization() { let diag = ValidationDiagnostic { - code: "E-TEST".to_string(), - severity: Severity::Error, + code: diagnostic_code("E-TEST"), + severity: DiagnosticSeverity::Error, path: Some(PathBuf::from("/tmp/test.toml")), library: Some("mylib".to_string()), snippet_id: Some("abc-123".to_string()), message: "test message".to_string(), - repairability: Repairability::Auto, + repairability: DiagnosticRepairability::Auto, }; let json = serde_json::to_string(&diag).unwrap(); let back: ValidationDiagnostic = serde_json::from_str(&json).unwrap(); assert_eq!(back.code, "E-TEST"); - assert_eq!(back.severity, Severity::Error); + assert_eq!(back.severity, DiagnosticSeverity::Error); assert_eq!(back.library, Some("mylib".to_string())); } @@ -1205,13 +1188,13 @@ mod tests { report.total_libraries = 2; report.total_snippets = 10; report.diagnostics.push(ValidationDiagnostic { - code: "W-TEST".to_string(), - severity: Severity::Warning, + code: diagnostic_code("W-TEST"), + severity: DiagnosticSeverity::Warning, path: None, library: Some("lib".to_string()), snippet_id: None, message: "warn".to_string(), - repairability: Repairability::Manual, + repairability: DiagnosticRepairability::Manual, }); let json = serde_json::to_string_pretty(&report).unwrap(); diff --git a/src/config/sync_settings.rs b/src/config/sync_settings.rs index 6e2cf88b..f4f270bf 100644 --- a/src/config/sync_settings.rs +++ b/src/config/sync_settings.rs @@ -15,8 +15,6 @@ use crate::error::{SnipError, SnipResult}; use crate::utils::config::get_sync_config_path; use crate::utils::toml_helpers::fix_invalid_toml_escapes; use serde::{Deserialize, Serialize}; -use std::fs; - const KEYCHAIN_SERVICE: &str = "snp-sync"; pub(crate) const KEYCHAIN_MARKER: &str = "@keychain"; const KEYCHAIN_DEFAULT_USER: &str = "api-key"; @@ -535,7 +533,7 @@ fn fail_closed_on_corrupt_config( detail: Option<&str>, ) -> SnipError { let backup_path = path.with_extension("toml.corrupt.bak"); - let backup_error = fs::copy(path, &backup_path).err(); + let backup_error = crate::utils::atomic::forensic_copy_aside(path, &backup_path).err(); if claim_corrupt_config_warning(path) { match &backup_error { diff --git a/src/diagnostics.rs b/src/diagnostics.rs index cd135eba..bc74e557 100644 --- a/src/diagnostics.rs +++ b/src/diagnostics.rs @@ -1,22 +1,137 @@ //! **Layer: Domain/Core** //! -//! Compatibility diagnostic models for import and doctor operations. +//! Shared diagnostic vocabulary and report models for `validate`, `doctor`, +//! `import`, and related surfaces. //! //! Pure data types with no I/O or platform dependencies. +use crate::error::{SnipError, SnipResult}; use serde::{Deserialize, Serialize}; +use std::fmt; -/// Severity level for compatibility diagnostics. +/// Severity level shared across diagnostic surfaces. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum DiagnosticSeverity { /// Informational message. Info, - /// Recoverable issue; entry imported with changes. + /// Recoverable issue. Warning, - /// Entry cannot be imported safely. + /// Blocking issue. Error, } +/// Repairability classification shared with `snp validate` (serde names unchanged). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DiagnosticRepairability { + Auto, + Manual, + Unrepairable, +} + +/// Validated diagnostic code (`E-`/`W-`/`I-`, `compat.*`, or `sync.*`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct DiagnosticCode(String); + +impl DiagnosticCode { + /// Validate and construct a diagnostic code. + pub fn new(raw: impl Into) -> SnipResult { + let raw = raw.into(); + if validate_diagnostic_code(&raw) { + Ok(Self(raw)) + } else { + Err(SnipError::runtime_error( + "Invalid diagnostic code", + Some(&format!( + "Diagnostic code '{raw}' is not in the published namespace" + )), + )) + } + } + + /// Construct a code that must already satisfy the namespace (programming-error panic otherwise). + pub fn expect_valid(raw: &str) -> Self { + Self::new(raw).unwrap_or_else(|e| panic!("invalid diagnostic code {raw:?}: {e}")) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Severity implied by an `E-`/`W-`/`I-` prefix; `None` for dotted forms. + pub fn severity(&self) -> Option { + if self.0.starts_with("E-") { + Some(DiagnosticSeverity::Error) + } else if self.0.starts_with("W-") { + Some(DiagnosticSeverity::Warning) + } else if self.0.starts_with("I-") { + Some(DiagnosticSeverity::Info) + } else { + None + } + } + + pub fn is_strict_elevatable(&self) -> bool { + self.0.starts_with("W-") + } +} + +impl fmt::Display for DiagnosticCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl PartialEq for DiagnosticCode { + fn eq(&self, other: &str) -> bool { + self.0 == other + } +} + +impl PartialEq<&str> for DiagnosticCode { + fn eq(&self, other: &&str) -> bool { + self.0 == *other + } +} + +/// Construct a validated code for a known-good literal at a call site. +pub fn diagnostic_code(raw: &str) -> DiagnosticCode { + DiagnosticCode::expect_valid(raw) +} + +fn validate_diagnostic_code(raw: &str) -> bool { + if raw.is_empty() { + return false; + } + if let Some(rest) = raw.strip_prefix("E-") { + return screaming_case_body(rest); + } + if let Some(rest) = raw.strip_prefix("W-") { + return screaming_case_body(rest); + } + if let Some(rest) = raw.strip_prefix("I-") { + return screaming_case_body(rest); + } + if let Some(rest) = raw.strip_prefix("compat.") { + return dotted_tail_valid(rest); + } + if let Some(rest) = raw.strip_prefix("sync.") { + return dotted_tail_valid(rest); + } + false +} + +fn screaming_case_body(body: &str) -> bool { + !body.is_empty() + && body + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'-') +} + +fn dotted_tail_valid(tail: &str) -> bool { + !tail.is_empty() && tail.split('.').all(|segment| !segment.is_empty()) +} + /// Byte-offset span within the source file. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SourceSpan { @@ -27,7 +142,7 @@ pub struct SourceSpan { /// A single compatibility diagnostic produced during import or doctor checks. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CompatibilityDiagnostic { - pub code: String, + pub code: DiagnosticCode, pub severity: DiagnosticSeverity, pub message: String, pub entry_index: Option, @@ -174,7 +289,7 @@ mod tests { fn make_diagnostic(severity: DiagnosticSeverity) -> CompatibilityDiagnostic { CompatibilityDiagnostic { - code: "TEST".to_string(), + code: diagnostic_code("I-TEST"), severity, message: "test".to_string(), entry_index: None, @@ -254,7 +369,7 @@ mod tests { #[test] fn test_compatibility_diagnostic_serialization() { let diagnostic = CompatibilityDiagnostic { - code: "TOML_ESCAPE".to_string(), + code: diagnostic_code("W-TYPE-MISMATCH"), severity: DiagnosticSeverity::Warning, message: "Backslash in double-quoted string".to_string(), entry_index: Some(5), @@ -266,7 +381,7 @@ mod tests { let json = serde_json::to_string(&diagnostic).unwrap(); let roundtripped: CompatibilityDiagnostic = serde_json::from_str(&json).unwrap(); - assert_eq!(roundtripped.code, "TOML_ESCAPE"); + assert_eq!(roundtripped.code, "W-TYPE-MISMATCH"); assert_eq!(roundtripped.severity, DiagnosticSeverity::Warning); assert_eq!(roundtripped.message, "Backslash in double-quoted string"); assert_eq!(roundtripped.entry_index, Some(5)); @@ -289,7 +404,7 @@ mod tests { #[test] fn test_diagnostic_span_skip_none() { let diag = CompatibilityDiagnostic { - code: "TEST".to_string(), + code: diagnostic_code("I-TEST"), severity: DiagnosticSeverity::Info, message: "test".to_string(), entry_index: None, @@ -309,7 +424,7 @@ mod tests { let mut diagnostics = Vec::new(); for i in 0..10 { diagnostics.push(CompatibilityDiagnostic { - code: format!("CODE-{i}"), + code: DiagnosticCode::new(format!("I-TEST-{i}")).expect("test code"), severity: DiagnosticSeverity::Info, message: format!("msg {i}"), entry_index: Some(i), @@ -319,7 +434,7 @@ mod tests { }); } for (i, d) in diagnostics.iter().enumerate() { - assert_eq!(d.code, format!("CODE-{i}")); + assert_eq!(d.code.as_str(), format!("I-TEST-{i}")); assert_eq!(d.entry_index, Some(i)); } } @@ -368,7 +483,7 @@ mod tests { fn test_strict_mode_error_classification() { let diagnostics = vec![ CompatibilityDiagnostic { - code: "W-DESC-EMPTY".to_string(), + code: diagnostic_code("W-DESC-EMPTY"), severity: DiagnosticSeverity::Warning, message: "warn".to_string(), entry_index: Some(0), @@ -377,7 +492,7 @@ mod tests { span: None, }, CompatibilityDiagnostic { - code: "I-TAGS-EMPTY".to_string(), + code: diagnostic_code("I-TAGS-EMPTY"), severity: DiagnosticSeverity::Info, message: "info".to_string(), entry_index: Some(0), @@ -394,7 +509,7 @@ mod tests { let mut diagnostics_with_error = diagnostics.clone(); diagnostics_with_error.push(CompatibilityDiagnostic { - code: "E-CMD-EMPTY".to_string(), + code: diagnostic_code("E-CMD-EMPTY"), severity: DiagnosticSeverity::Error, message: "error".to_string(), entry_index: Some(1), @@ -412,7 +527,7 @@ mod tests { fn test_diagnostic_bounded_message() { let long_message = "x".repeat(1000); let diag = CompatibilityDiagnostic { - code: "TEST".to_string(), + code: diagnostic_code("I-TEST"), severity: DiagnosticSeverity::Info, message: long_message.clone(), entry_index: None, @@ -458,7 +573,7 @@ mod tests { report.imported = 3; report.skipped = 2; report.diagnostics.push(CompatibilityDiagnostic { - code: "W-DESC-EMPTY".to_string(), + code: diagnostic_code("W-DESC-EMPTY"), severity: DiagnosticSeverity::Warning, message: "Empty description".to_string(), entry_index: Some(0), @@ -497,7 +612,7 @@ mod tests { let mut report = DoctorReport::new(false); report.source = Some("/tmp/pet.toml".to_string()); report.diagnostics.push(CompatibilityDiagnostic { - code: "compat.sync.enabled".to_string(), + code: diagnostic_code("compat.sync.enabled"), entry_index: None, field: Some("sync".to_string()), severity: DiagnosticSeverity::Info, @@ -521,4 +636,83 @@ mod tests { "Report JSON should not contain secret field" ); } + + #[test] + fn test_diagnostic_code_grammar_accepts_emitted_codes() { + let validate_codes = [ + "E-CMD-EMPTY", + "E-DUP-ID", + "E-FILE-READ", + "E-INDEX-MISSING-FILE", + "E-PRIMARY-MISSING", + "E-TOML-PARSE", + "I-FILE-EMPTY", + "W-CORRUPT-BAK", + "W-DESC-EMPTY", + "W-DUP-CHECK-SKIPPED", + "W-EXACT-DUP", + "W-ID-EMPTY", + "W-INSECURE-PERMS", + "W-LIB-INDEX-UNREADABLE", + "W-LIB-UNREADABLE", + "W-NO-PRIMARY", + "W-ORPHAN-FILE", + "W-SAME-ID-DIVERGENT", + "W-USAGE-ORPHAN", + ]; + for code in validate_codes { + assert!(DiagnosticCode::new(code).is_ok(), "reject {code}"); + } + assert!(DiagnosticCode::new("compat.sync.checked").is_ok()); + assert!(DiagnosticCode::new("sync.attention.configuration").is_ok()); + assert!(DiagnosticCode::new("sync.config_load_failed").is_ok()); + assert!(DiagnosticCode::new("compat.shell.bash.ok").is_ok()); + } + + #[test] + fn test_diagnostic_code_rejects_malformed() { + assert!(DiagnosticCode::new("e-cmd-empty").is_err()); + assert!(DiagnosticCode::new("x-unknown").is_err()); + assert!(DiagnosticCode::new("E-").is_err()); + assert!(DiagnosticCode::new("").is_err()); + let err = DiagnosticCode::new("bad-code").unwrap_err().to_string(); + assert!(err.contains("bad-code")); + } + + #[test] + fn test_diagnostic_code_severity_mapping() { + assert_eq!( + diagnostic_code("E-CMD-EMPTY").severity(), + Some(DiagnosticSeverity::Error) + ); + assert_eq!( + diagnostic_code("W-DESC-EMPTY").severity(), + Some(DiagnosticSeverity::Warning) + ); + assert_eq!( + diagnostic_code("I-FILE-EMPTY").severity(), + Some(DiagnosticSeverity::Info) + ); + assert_eq!(diagnostic_code("compat.sync.checked").severity(), None); + } + + #[test] + fn test_diagnostic_code_serde_transparent() { + let code = diagnostic_code("W-DESC-EMPTY"); + let json = serde_json::to_string(&code).unwrap(); + assert_eq!(json, "\"W-DESC-EMPTY\""); + let back: DiagnosticCode = serde_json::from_str(&json).unwrap(); + assert_eq!(back, code); + } + + #[test] + fn test_diagnostic_repairability_serde_names() { + for (value, name) in [ + (DiagnosticRepairability::Auto, "\"Auto\""), + (DiagnosticRepairability::Manual, "\"Manual\""), + (DiagnosticRepairability::Unrepairable, "\"Unrepairable\""), + ] { + assert_eq!(serde_json::to_string(&value).unwrap(), name); + } + } } diff --git a/src/lib.rs b/src/lib.rs index e4f35c10..ea5695af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,7 +52,11 @@ pub mod usage; // ── Crate-internal ────────────────────────────────────────────────── pub(crate) mod clipboard; +#[cfg(not(feature = "test-support"))] pub(crate) mod diagnostics; +#[cfg(feature = "test-support")] +#[doc(hidden)] +pub mod diagnostics; pub(crate) mod encryption; pub(crate) mod library; pub(crate) mod local_data; @@ -85,6 +89,10 @@ pub use utils::atomic::{ AtomicWriteOptions, AtomicWriteReport, Durability, atomic_replace, write_private_atomic, }; +#[cfg(feature = "test-support")] +#[doc(hidden)] +pub use crate::library::{LibraryManager, LibraryScan, PrimaryState}; + /// Per-thread override of the config directory, for tests only. /// /// Compiled into unit-test builds and into `test-support` builds so that diff --git a/src/library/manager.rs b/src/library/manager.rs index 832b6220..13827059 100644 --- a/src/library/manager.rs +++ b/src/library/manager.rs @@ -5,8 +5,8 @@ use super::model::validate_library_name; use super::model::{ - LibraryConfig, LibraryIndexInspection, LibraryMeta, PrimaryState, ResolvedLibrarySource, - SequenceCursor, SyncCursorKind, library_not_found, + LibraryConfig, LibraryIndexInspection, LibraryMeta, LibraryScan, PrimaryState, + ResolvedLibrarySource, SequenceCursor, SyncCursorKind, library_not_found, }; use super::persistence::write_library_file; use crate::config::{cached_read_toml, invalidate_toml_cache}; @@ -60,7 +60,9 @@ impl LibraryManager { Err(e) => { // Best-effort backup of corrupted file before returning the error. let backup = config_path.with_extension("toml.corrupt"); - if let Err(copy_err) = fs::copy(&config_path, &backup) { + if let Err(copy_err) = + crate::utils::atomic::forensic_copy_aside(&config_path, &backup) + { tracing::warn!( config = %config_path.display(), error = %e, @@ -97,7 +99,7 @@ impl LibraryManager { /// /// This is useful for tests that need an isolated config dir without /// mutating process-wide environment variables. - #[cfg(test)] + #[cfg(any(test, feature = "test-support"))] pub fn with_config_dir(config_dir: PathBuf) -> SnipResult { let libraries_dir = config_dir.join("libraries"); let premade_dir = config_dir.join("premade"); @@ -110,7 +112,9 @@ impl LibraryManager { Ok(c) => c, Err(e) => { let backup = config_path.with_extension("toml.corrupt"); - if let Err(copy_err) = fs::copy(&config_path, &backup) { + if let Err(copy_err) = + crate::utils::atomic::forensic_copy_aside(&config_path, &backup) + { tracing::warn!( error = %e, backup_error = %copy_err, @@ -341,7 +345,28 @@ impl LibraryManager { /// index entry, and the current primary-library state. Callers render /// the result into their own diagnostic types; this function performs /// no I/O beyond existence checks and directory listing. + /// Shared side-effect-free scan for diagnostic surfaces. + pub fn scan_libraries(&self) -> SnipResult { + let sources = self.resolve_readonly_sources(Some("all"))?; + let (missing_files, orphan_files, primary) = self.library_index_disk_view(); + Ok(LibraryScan { + sources, + missing_files, + orphan_files, + primary, + }) + } + pub fn inspect_library_index(&self) -> LibraryIndexInspection { + let (missing_files, orphan_files, primary) = self.library_index_disk_view(); + LibraryIndexInspection { + missing_files, + orphan_files, + primary, + } + } + + fn library_index_disk_view(&self) -> (Vec<(String, PathBuf)>, Vec, PrimaryState) { let mut missing_files = Vec::new(); for meta in &self.config.libraries { let path = self.libraries_dir.join(format!("{}.toml", meta.filename)); @@ -396,11 +421,7 @@ impl LibraryManager { } }; - LibraryIndexInspection { - missing_files, - orphan_files, - primary, - } + (missing_files, orphan_files, primary) } /// Creates a new snippet library file and registers it in the config. diff --git a/src/library/model.rs b/src/library/model.rs index 7a6e8bfe..e3a929b4 100644 --- a/src/library/model.rs +++ b/src/library/model.rs @@ -218,6 +218,35 @@ pub struct LibraryIndexInspection { pub primary: PrimaryState, } +/// Side-effect-free library scan shared by `validate`, `doctor`, and `repair`. +/// +/// Performs exactly one directory listing under `libraries/` and combines +/// index-driven sources with on-disk orphan files. +#[derive(Debug, Clone)] +pub struct LibraryScan { + /// Index-driven library sources (`resolve_readonly_sources(Some("all"))`). + pub sources: Vec, + /// Index entries whose library file does not exist. + pub missing_files: Vec<(String, PathBuf)>, + /// Library files on disk with no index entry. + pub orphan_files: Vec, + /// Current primary-library state. + pub primary: PrimaryState, +} + +impl LibraryScan { + /// Every `*.toml` library file on disk (indexed paths plus orphans). + pub fn disk_library_paths(&self) -> Vec { + let mut paths: Vec = self.sources.iter().map(|s| s.path.clone()).collect(); + for orphan in &self.orphan_files { + if !paths.iter().any(|p| p == orphan) { + paths.push(orphan.clone()); + } + } + paths + } +} + /// Canonical missing-library error. /// /// All read-only source resolution paths use this constructor so "library diff --git a/src/library/persistence.rs b/src/library/persistence.rs index fb4437b2..5ca89270 100644 --- a/src/library/persistence.rs +++ b/src/library/persistence.rs @@ -214,7 +214,7 @@ pub fn load_library(path: &Path) -> SnipResult { // Best-effort backup of corrupted file before returning the error. // The backup failure must not hide the original parse error. let backup_path = path.with_extension("toml.corrupt.bak"); - if let Err(backup_err) = fs::copy(path, &backup_path) { + if let Err(backup_err) = crate::utils::atomic::forensic_copy_aside(path, &backup_path) { tracing::warn!( file = %path.display(), error = %e, @@ -408,43 +408,24 @@ pub fn backup_library(path: &Path) -> SnipResult> { let backup_name = format!("{}.{}.toml.bak", file_stem.to_string_lossy(), timestamp); let backup_path = backup_dir.join(backup_name); - fs::copy(path, &backup_path) - .map_err(|e| SnipError::io_error("create backup", backup_path.clone(), e))?; - - // `fs::copy` writes the copy without fsyncing it, so a power loss right - // after the save could leave the rollback point truncated. Flush the - // backup before the atomic write replaces the original. - sync_backup_file(&backup_path); + // Contain the source under the libraries directory (or whatever parent + // owns this library file). Symlink / non-regular / escaped sources are + // refused by the shared copy primitive; durability is DurableUserData. + let copy_root = path.parent().map(Path::to_path_buf).ok_or_else(|| { + SnipError::runtime_error( + "backup path has no parent", + Some(&path.display().to_string()), + ) + })?; + let options = crate::utils::atomic::CopyOptions { + source: crate::utils::atomic::CopySourcePolicy::Contained { root: copy_root }, + durability: crate::utils::atomic::Durability::DurableUserData, + }; + crate::utils::atomic::copy_file(path, &backup_path, &options)?; Ok(Some(backup_path)) } -/// Flush a freshly copied backup to disk. -/// -/// `fs::copy` does not fsync the destination. The flush is best-effort: a -/// backup that cannot be synced is still a usable rollback point, so the -/// failure is logged rather than propagated to the caller. -fn sync_backup_file(path: &Path) { - match fs::OpenOptions::new().write(true).open(path) { - Ok(file) => { - if let Err(e) = file.sync_all() { - tracing::warn!( - backup = %path.display(), - error = %e, - "Failed to fsync backup file" - ); - } - } - Err(e) => { - tracing::warn!( - backup = %path.display(), - error = %e, - "Failed to open backup file for fsync" - ); - } - } -} - /// Returns `true` when `name` is a backup file that belongs to `file_stem`. /// /// Backups are named `{file_stem}.{timestamp}.toml.bak`. Matching on the diff --git a/src/library/tests.rs b/src/library/tests.rs index ce0580db..a84c46f0 100644 --- a/src/library/tests.rs +++ b/src/library/tests.rs @@ -1950,6 +1950,30 @@ fn test_inspect_library_index_orphan_files() { assert_eq!(inspection.orphan_files.len(), 1); } +#[test] +fn test_scan_libraries_matches_inspection_and_sources() { + let tmp = TestDir::new(); + let config_dir = tmp.path().join("cfg"); + let libs_dir = config_dir.join("libraries"); + std::fs::create_dir_all(&libs_dir).unwrap(); + let mut indexed = LibraryMeta::new("indexed"); + indexed.is_primary = true; + write_index(&config_dir, &[indexed]); + write_lib_file(&libs_dir, "indexed"); + write_lib_file(&libs_dir, "orphan"); + let mgr = LibraryManager::with_config_dir(config_dir).unwrap(); + + let inspection = mgr.inspect_library_index(); + let scan = mgr.scan_libraries().unwrap(); + + assert_eq!(scan.missing_files, inspection.missing_files); + assert_eq!(scan.orphan_files, inspection.orphan_files); + assert_eq!(scan.primary, inspection.primary); + assert_eq!(scan.sources.len(), 1); + assert_eq!(scan.sources[0].name, "indexed"); + assert_eq!(scan.disk_library_paths().len(), 2); +} + #[test] fn test_find_orphaned_ids_shared_classifier() { let active: HashSet = ["a".to_string(), "b".to_string()].into_iter().collect(); diff --git a/src/main.rs b/src/main.rs index 3e015a34..8a06be98 100644 --- a/src/main.rs +++ b/src/main.rs @@ -202,6 +202,9 @@ enum Commands { Get(commands::get_cmd::GetArgs), /// Tombstone a snippet deterministically (no TUI, no prompt) Delete(commands::delete_cmd::DeleteArgs), + /// Set or clear favorite and folder memberships (no TUI) + #[command(alias = "o")] + Organize(commands::organize_cmd::OrganizeArgs), /// Internal: detached auto-sync worker (hidden, invoked by parent after mutation) #[command(name = "auto-sync-worker", hide = true)] AutoSyncWorker { @@ -296,6 +299,8 @@ enum DataCommands { Status(commands::status_cmd::StatusArgs), /// Tombstone a snippet deterministically (no TUI, no prompt) Delete(commands::delete_cmd::DeleteArgs), + /// Set or clear favorite and folder memberships (no TUI) + Organize(commands::organize_cmd::OrganizeArgs), } #[derive(Debug, Subcommand)] @@ -478,6 +483,11 @@ fn handle_delete(args: commands::delete_cmd::DeleteArgs) -> SnipResult SnipResult { + commands::organize_cmd::run(args) +} + fn dispatch_command(cli: Option) -> SnipResult { match cli { None => { @@ -889,6 +899,9 @@ fn dispatch_command(cli: Option) -> SnipResult { DataCommands::Delete(args) => { return handle_delete(args); } + DataCommands::Organize(args) => { + return handle_organize(args); + } }, Some(Commands::Get(args)) => { let outcome = commands::get_cmd::run( @@ -909,6 +922,9 @@ fn dispatch_command(cli: Option) -> SnipResult { Some(Commands::Delete(args)) => { return handle_delete(args); } + Some(Commands::Organize(args)) => { + return handle_organize(args); + } Some(Commands::AutoSyncWorker { state_dir }) => { let outcome = snip_it::auto_sync::worker::run(&state_dir); match outcome { @@ -996,9 +1012,10 @@ fn command_behavior(cmd: Option<&Commands>) -> CommandBehavior { StartupRecoveryPolicy::SuppressReadOnly, StartupServices::Minimal, ), - DataCommands::Repair(_) | DataCommands::Restore(_) | DataCommands::Delete(_) => { - (StartupRecoveryPolicy::Allow, StartupServices::Logging) - } + DataCommands::Repair(_) + | DataCommands::Restore(_) + | DataCommands::Delete(_) + | DataCommands::Organize(_) => (StartupRecoveryPolicy::Allow, StartupServices::Logging), }, // ── Mutation commands: allow recovery, full logging+audit ─── @@ -1012,6 +1029,7 @@ fn command_behavior(cmd: Option<&Commands>) -> CommandBehavior { | Commands::Repair(_) | Commands::Restore(_) | Commands::Delete(_) + | Commands::Organize(_) | Commands::Premade { .. } | Commands::Library { command: diff --git a/src/usage.rs b/src/usage.rs index af7baa7c..3eded718 100644 --- a/src/usage.rs +++ b/src/usage.rs @@ -147,7 +147,7 @@ impl UsageIndex { /// fail-closed path, loading never refuses to proceed. fn backup_corrupt_file(path: &Path) { let backup = path.with_extension("toml.corrupt.bak"); - match fs::copy(path, &backup) { + match crate::utils::atomic::forensic_copy_aside(path, &backup) { Ok(_) => tracing::warn!(backup = %backup.display(), "backed up corrupt usage index"), Err(e) => { tracing::warn!(error = %e, path = %path.display(), "failed to back up corrupt usage index") diff --git a/src/utils/atomic.rs b/src/utils/atomic.rs index 9d2f416c..fd37adcd 100644 --- a/src/utils/atomic.rs +++ b/src/utils/atomic.rs @@ -477,6 +477,116 @@ pub fn atomic_write_bytes(target: &Path, bytes: &[u8], durability: Durability) - Ok(()) } +/// Source-admission policy for the shared configuration/library copy primitive. +/// +/// Source refusal (symlink / non-regular / outside a containment root) is +/// implemented here — **not** by flipping [`AtomicWriteOptions::reject_symlink`], +/// which governs the *destination* and is only the default for +/// [`Durability::SensitiveConfig`]. +#[derive(Debug, Clone)] +pub enum CopySourcePolicy { + /// Refuse a source that does not canonicalize under `root`. + Contained { root: PathBuf }, + /// Admit any regular file; still refuse symlinks and non-regular files. + RegularFileOnly, +} + +/// Options for [`read_copy_source`] / [`copy_file`]. +#[derive(Debug, Clone)] +pub struct CopyOptions { + /// How the source path is admitted. + pub source: CopySourcePolicy, + /// Durability class applied when landing the copy via [`atomic_replace`]. + /// Production backup paths use [`Durability::DurableUserData`]. + pub durability: Durability, +} + +/// Admit and read a configuration/library copy source. +/// +/// Refusal is decided on the **source** before any bytes are read: +/// 1. a symlink source is refused (message names the path); +/// 2. a non-regular file is refused; +/// 3. under [`CopySourcePolicy::Contained`], a source that does not resolve +/// under `root` is refused; +/// 4. otherwise the bytes are read. +/// +/// Callers that need a consistent multi-file snapshot under a lock should use +/// this admission half, then land bytes themselves; one-shot copies use +/// [`copy_file`]. +pub fn read_copy_source(src: &Path, options: &CopyOptions) -> SnipResult> { + let meta = + fs::symlink_metadata(src).map_err(|e| SnipError::io_error("stat copy source", src, e))?; + if meta.file_type().is_symlink() { + return Err(SnipError::runtime_error( + "Copy source is a symlink", + Some(&format!( + "Refusing to copy symlink {} (could point outside config)", + src.display() + )), + )); + } + if !meta.is_file() { + return Err(SnipError::runtime_error( + "Copy source is not a regular file", + Some(&format!( + "Expected regular file, got {:?}: {}", + meta.file_type(), + src.display() + )), + )); + } + + if let CopySourcePolicy::Contained { root } = &options.source { + let canonical_root = root + .canonicalize() + .map_err(|e| SnipError::io_error("canonicalize copy root", root.as_path(), e))?; + let canonical_src = src + .canonicalize() + .map_err(|e| SnipError::io_error("canonicalize copy source", src, e))?; + if !canonical_src.starts_with(&canonical_root) { + return Err(SnipError::runtime_error( + "Copy source escapes containment root", + Some(&format!( + "{} is not under root ({})", + canonical_src.display(), + canonical_root.display(), + )), + )); + } + } + + fs::read(src).map_err(|e| SnipError::io_error("read copy source", src, e)) +} + +/// Admit `src` under [`CopyOptions`], then land the bytes at `dst` through +/// [`atomic_replace`] with `options.durability`. +/// +/// Production callers pass [`Durability::DurableUserData`] so the file content +/// and (where supported) the parent directory entry are fsynced. +pub fn copy_file(src: &Path, dst: &Path, options: &CopyOptions) -> SnipResult { + let bytes = read_copy_source(src, options)?; + let write_opts = AtomicWriteOptions::for_durability(options.durability); + atomic_replace(dst, &bytes, &write_opts) +} + +/// Best-effort forensic copy of a corrupt configuration/library file. +/// +/// Uses [`copy_file`] with [`Durability::DurableUserData`] and containment under +/// `src`'s parent. Failures (including symlink / non-regular refusal) are +/// returned so callers can log the reason without changing their fail-open or +/// fail-closed load policy. +pub fn forensic_copy_aside(src: &Path, dst: &Path) -> SnipResult { + let root = src + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| PathBuf::from(".")); + let options = CopyOptions { + source: CopySourcePolicy::Contained { root }, + durability: Durability::DurableUserData, + }; + copy_file(src, dst, &options) +} + /// Encode a digest as lowercase hex without per-byte allocation. /// /// Pre-allocates the full `2 * digest.len()` capacity and appends with @@ -716,4 +826,110 @@ mod tests { assert!(opts.preserve_permissions); assert!(!opts.reject_symlink); } + + fn durable_copy_options(root: &Path) -> CopyOptions { + CopyOptions { + source: CopySourcePolicy::Contained { + root: root.to_path_buf(), + }, + durability: Durability::DurableUserData, + } + } + + #[test] + fn test_copy_file_byte_identical_and_replaces() { + let dir = TempDir::new().unwrap(); + let src = dir.path().join("src.txt"); + let dst = dir.path().join("dst.txt"); + fs::write(&src, b"payload-v1").unwrap(); + fs::write(&dst, b"old").unwrap(); + let opts = durable_copy_options(dir.path()); + let report = copy_file(&src, &dst, &opts).unwrap(); + assert!(report.target_existed); + assert_eq!(fs::read(&dst).unwrap(), b"payload-v1"); + assert_eq!(report.bytes_written, 10); + assert!(report.parent_sync_supported.is_some()); + } + + #[cfg(unix)] + #[test] + fn test_read_copy_source_refuses_symlink_and_names_path() { + let dir = TempDir::new().unwrap(); + let real = dir.path().join("real.txt"); + fs::write(&real, b"secret-outside").unwrap(); + let link = dir.path().join("link.txt"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let opts = durable_copy_options(dir.path()); + let err = read_copy_source(&link, &opts).unwrap_err().to_string(); + assert!(err.contains("symlink"), "got: {err}"); + assert!( + err.contains(link.display().to_string().as_str()), + "got: {err}" + ); + } + + #[cfg(unix)] + #[test] + fn test_read_copy_source_refuses_non_regular() { + let dir = TempDir::new().unwrap(); + let nested = dir.path().join("nested"); + fs::create_dir(&nested).unwrap(); + let opts = durable_copy_options(dir.path()); + let err = read_copy_source(&nested, &opts).unwrap_err().to_string(); + assert!(err.contains("regular file"), "got: {err}"); + assert!( + err.contains(nested.display().to_string().as_str()), + "got: {err}" + ); + } + + #[cfg(unix)] + #[test] + fn test_read_copy_source_refuses_outside_root() { + let root = TempDir::new().unwrap(); + let outside = TempDir::new().unwrap(); + let src = outside.path().join("leak.txt"); + fs::write(&src, b"leak").unwrap(); + let opts = durable_copy_options(root.path()); + let err = read_copy_source(&src, &opts).unwrap_err().to_string(); + assert!( + err.contains("escapes") || err.contains("not under"), + "got: {err}" + ); + } + + #[test] + fn test_read_copy_source_admits_contained_regular_file() { + let dir = TempDir::new().unwrap(); + let src = dir.path().join("ok.txt"); + fs::write(&src, b"ok-bytes").unwrap(); + let opts = durable_copy_options(dir.path()); + assert_eq!(read_copy_source(&src, &opts).unwrap(), b"ok-bytes"); + } + + #[test] + fn test_read_copy_source_regular_file_only_admits_without_root() { + let dir = TempDir::new().unwrap(); + let src = dir.path().join("ok.txt"); + fs::write(&src, b"ok-bytes").unwrap(); + let opts = CopyOptions { + source: CopySourcePolicy::RegularFileOnly, + durability: Durability::DurableUserData, + }; + assert_eq!(read_copy_source(&src, &opts).unwrap(), b"ok-bytes"); + } + + #[test] + fn test_copy_file_claims_durable_user_data() { + let dir = TempDir::new().unwrap(); + let src = dir.path().join("src.txt"); + let dst = dir.path().join("dst.txt"); + fs::write(&src, b"durable").unwrap(); + let opts = durable_copy_options(dir.path()); + assert_eq!(opts.durability, Durability::DurableUserData); + let report = copy_file(&src, &dst, &opts).unwrap(); + assert_eq!(fs::read(&dst).unwrap(), b"durable"); + // DurableUserData probes parent-dir sync support. + assert!(report.parent_sync_supported.is_some()); + } } diff --git a/tests/architecture.rs b/tests/architecture.rs index 8f8291eb..ba14f5ea 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -703,6 +703,114 @@ fn no_reference_is_cast_straight_to_a_raw_pointer() { ); } +/// Configuration and library material must go through the shared copy +/// primitive (`crate::utils::atomic::{read_copy_source,copy_file}`), not a +/// bare `fs::copy`. The allow-list holds only the sites +/// `plans/implementation/maintenance-consolidation/002-...` §5 declares +/// out of scope, each with a written reason. +const FS_COPY_ALLOWLIST: &[(&str, &str)] = &[ + ( + "src/update.rs", + "copies updater artifacts, not configuration or library material", + ), + ( + "src/utils/config.rs", + "legacy whole-directory config migration, not a backup/snapshot path", + ), + ( + "src/commands/sync_cmd.rs", + "auto-sync status quarantine of a transient worker file", + ), +]; + +fn production_fs_copy_sites() -> Vec<(String, usize, String)> { + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + let src_root = Path::new(&manifest_dir).join("src"); + let mut hits = Vec::new(); + for path in rust_files_under(&src_root) { + let rel = path + .strip_prefix(&manifest_dir) + .unwrap_or(&path) + .to_string_lossy() + .replace('\\', "/"); + if FS_COPY_ALLOWLIST.iter().any(|(allowed, _)| *allowed == rel) { + continue; + } + let source = fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("Failed to read {}: {e}", path.display())); + // Skip the shared primitive module itself and dedicated test modules. + if rel == "src/utils/atomic.rs" || rel.ends_with("/tests.rs") || rel.ends_with("\\tests.rs") + { + continue; + } + // Production scan: ignore bodies of `#[cfg(test)]` modules (unit tests + // may still use fs::copy as a fixture helper). + let mut in_cfg_test_module = false; + let mut cfg_test_brace_depth: i32 = 0; + for (index, line) in source.lines().enumerate() { + let trimmed = line.trim(); + if trimmed.starts_with("#[cfg(test)]") { + // Next non-attribute/non-empty line opening a module starts the skip region. + in_cfg_test_module = true; + cfg_test_brace_depth = 0; + continue; + } + if in_cfg_test_module { + cfg_test_brace_depth += trimmed.matches('{').count() as i32; + cfg_test_brace_depth -= trimmed.matches('}').count() as i32; + if cfg_test_brace_depth <= 0 && trimmed.contains('}') { + in_cfg_test_module = false; + } + continue; + } + if trimmed.starts_with("//") || trimmed.starts_with("//!") { + continue; + } + if trimmed.contains("fs::copy") || trimmed.contains("std::fs::copy") { + hits.push((rel.clone(), index + 1, trimmed.to_string())); + } + } + } + hits +} + +#[test] +fn config_and_library_copies_use_shared_primitive() { + let hits = production_fs_copy_sites(); + assert!( + hits.is_empty(), + "direct fs::copy of configuration/library material is forbidden outside the allow-list:\n{}", + hits.iter() + .map(|(path, line, text)| format!("{path}:{line}: {text}")) + .collect::>() + .join("\n") + ); +} + +#[test] +fn fs_copy_allowlist_detector_reports_a_forbidden_site() { + // Synthetic: a repair_cmd-style copy must be detected. + let synthetic = "fn bad() { fs::copy(src, dst).unwrap(); }\n"; + assert!( + synthetic.contains("fs::copy"), + "detector fixture must mention fs::copy" + ); + // And every allow-list entry must still exist on disk. + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + for (rel, reason) in FS_COPY_ALLOWLIST { + let path = Path::new(&manifest_dir).join(rel); + assert!( + path.exists(), + "allow-list entry {rel} ({reason}) must exist" + ); + let source = fs::read_to_string(&path).unwrap(); + assert!( + source.contains("fs::copy") || source.contains("std::fs::copy"), + "allow-list entry {rel} must still contain an fs::copy (or remove it from the allow-list)" + ); + } +} + /// A guard that cannot fail proves nothing, so the detector is exercised /// against the cast that broke the macOS build: it must be reported, and the /// safe two-step form must not be. @@ -758,3 +866,47 @@ fn call_result(info: &mut proc_bsdinfo) { "the detector must not report a cast of a call's result" ); } + +const DIAGNOSTIC_CODE_GUARD_MODULES: &[&str] = &[ + "src/diagnostics.rs", + "src/commands/validate_cmd.rs", + "src/commands/doctor_cmd.rs", + "src/commands/repair_cmd.rs", +]; + +#[test] +fn diagnostic_modules_reject_free_form_code_string_fields() { + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + let mut violations = Vec::new(); + for rel in DIAGNOSTIC_CODE_GUARD_MODULES { + let path = Path::new(&manifest_dir).join(rel); + let source = fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("Failed to read {}: {e}", path.display())); + let mut in_cfg_test = false; + let mut brace_depth = 0i32; + for (line_no, line) in source.lines().enumerate() { + let trimmed = line.trim(); + if trimmed.starts_with("#[cfg(test)]") { + in_cfg_test = true; + brace_depth = 0; + continue; + } + if in_cfg_test { + brace_depth += trimmed.matches('{').count() as i32; + brace_depth -= trimmed.matches('}').count() as i32; + if brace_depth <= 0 && trimmed.contains('}') { + in_cfg_test = false; + } + continue; + } + if trimmed.contains("code: String") { + violations.push(format!("{}:{}", rel, line_no + 1)); + } + } + } + assert!( + violations.is_empty(), + "free-form diagnostic code fields found:\n{}", + violations.join("\n") + ); +} diff --git a/tests/backup_copy_policy.rs b/tests/backup_copy_policy.rs new file mode 100644 index 00000000..9bc487ee --- /dev/null +++ b/tests/backup_copy_policy.rs @@ -0,0 +1,236 @@ +//! Maintenance consolidation M002 — shared backup copy-policy contracts. +//! +//! Proves the four backup paths refuse symlink sources, that the repair +//! backup is restorable via `snp restore`, and that forensic copies do not +//! follow symlink targets. + +mod support; + +use std::fs; +use std::path::Path; +use support::helpers::*; + +fn write_primary_library(config_dir: &Path, body: &str) { + let libraries_dir = config_dir.join("libraries"); + fs::create_dir_all(&libraries_dir).unwrap(); + fs::write(libraries_dir.join("primary.toml"), body).unwrap(); + fs::write( + config_dir.join("libraries.toml"), + r#" +generation = 1 + +[[libraries]] +filename = "primary" +name = "primary" +is_primary = true +"#, + ) + .unwrap(); +} + +fn valid_snippet_body() -> &'static str { + r#"[[snippets]] +id = "s1" +description = "pre-repair" +command = "echo pre" +favorite = false +created_at = 1700000000 +updated_at = 1700000000 +device_id = "test-device" +"# +} + +#[cfg(unix)] +fn plant_symlinked_library(config_dir: &Path, tmp: &Path) -> std::path::PathBuf { + let external = tmp.join("external-secret.toml"); + // Valid TOML so the repair *scan* does not treat the symlink target as a + // parse error before the backup admission half runs. The refusal under + // test is the copy-source admission, not TOML parsing. + fs::write( + &external, + r#"[[snippets]] +id = "external" +description = "secret" +command = "echo secret" +favorite = false +created_at = 1700000000 +updated_at = 1700000000 +device_id = "ext" +"#, + ) + .unwrap(); + let libraries_dir = config_dir.join("libraries"); + fs::create_dir_all(&libraries_dir).unwrap(); + let link = libraries_dir.join("leaky.toml"); + std::os::unix::fs::symlink(&external, &link).unwrap(); + link +} + +#[cfg(unix)] +#[test] +fn path2_backup_refuses_symlink_and_names_path() { + let (tmp, config_dir) = setup_test_env(); + write_primary_library(config_dir.as_path(), valid_snippet_body()); + let link = plant_symlinked_library(&config_dir, tmp.path()); + let backup_dir = tmp.path().join("backup-out"); + let output = snp_in(&config_dir) + .args(["backup", "--output", backup_dir.to_str().unwrap()]) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("symlink") || stderr.contains("escapes config root"), + "stderr={stderr}" + ); + // Containment refusal names the canonicalized target; symlink refusal + // names the link path. Either form is acceptable evidence. + assert!( + stderr.contains("leaky.toml") + || stderr.contains("external-secret.toml") + || stderr.contains(link.display().to_string().as_str()), + "refusal must name the path: {stderr}" + ); + assert!(!backup_dir.exists(), "partial snapshot must not remain"); +} + +#[cfg(unix)] +#[test] +fn path3_repair_apply_refuses_symlink_and_applies_nothing() { + let (tmp, config_dir) = setup_test_env(); + write_primary_library(config_dir.as_path(), valid_snippet_body()); + // Safe repair so `--apply` reaches create_repair_backup. + fs::write( + config_dir.join("usage.toml"), + r#"[[entries]] +id = "missing-id" +use_count = 1 +last_used_at = 0 +"#, + ) + .unwrap(); + let _link = plant_symlinked_library(&config_dir, tmp.path()); + let before = fs::read(config_dir.join("libraries/primary.toml")).unwrap(); + let output = snp_in(&config_dir) + .args(["repair", "--apply"]) + .output() + .unwrap(); + assert!( + !output.status.success(), + "stderr={}", + String::from_utf8_lossy(&output.stderr) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("symlink") + || stderr.contains("escapes") + || stderr.contains("Copy source") + || stderr.contains("Backup entry"), + "stderr={stderr}" + ); + let after = fs::read(config_dir.join("libraries/primary.toml")).unwrap(); + assert_eq!( + before, after, + "repair must apply nothing when backup refuses" + ); +} + +#[cfg(unix)] +#[test] +fn path4_restore_refuses_symlink_before_mutating_live_config() { + let (tmp, config_dir) = setup_test_env(); + write_primary_library(config_dir.as_path(), valid_snippet_body()); + let backup_dir = tmp.path().join("good-backup"); + let backup = snp_in(&config_dir) + .args(["backup", "--output", backup_dir.to_str().unwrap()]) + .output() + .unwrap(); + assert!( + backup.status.success(), + "setup backup must succeed: {}", + String::from_utf8_lossy(&backup.stderr) + ); + + let _link = plant_symlinked_library(&config_dir, tmp.path()); + let before = fs::read(config_dir.join("libraries/primary.toml")).unwrap(); + let output = snp_in(&config_dir) + .args(["restore", backup_dir.to_str().unwrap(), "--mode", "replace"]) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("symlink") + || stderr.contains("escapes") + || stderr.contains("Copy source") + || stderr.contains("Backup entry"), + "stderr={stderr}" + ); + let after = fs::read(config_dir.join("libraries/primary.toml")).unwrap(); + assert_eq!(before, after, "live config must be untouched"); +} + +#[test] +fn repair_backup_is_restorable_rollback_point() { + let (_tmp, config_dir) = setup_test_env(); + write_primary_library(config_dir.as_path(), valid_snippet_body()); + fs::write( + config_dir.join("usage.toml"), + r#"[[entries]] +id = "missing-id" +use_count = 1 +last_used_at = 0 +"#, + ) + .unwrap(); + let pre_bytes = fs::read(config_dir.join("libraries/primary.toml")).unwrap(); + + let repair = snp_in(&config_dir) + .args(["repair", "--apply", "--json"]) + .output() + .unwrap(); + assert!( + repair.status.success(), + "repair should succeed: stdout={} stderr={}", + String::from_utf8_lossy(&repair.stdout), + String::from_utf8_lossy(&repair.stderr) + ); + + let backups = config_dir.join("backups"); + let mut repair_dirs: Vec<_> = fs::read_dir(&backups) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("repair-")) + }) + .collect(); + repair_dirs.sort(); + let repair_backup = repair_dirs.pop().expect("repair backup directory"); + assert!( + repair_backup.join("manifest.toml").exists(), + "repair backup must carry manifest.toml" + ); + + let restore = snp_in(&config_dir) + .args([ + "restore", + repair_backup.to_str().unwrap(), + "--mode", + "replace", + ]) + .output() + .unwrap(); + assert!( + restore.status.success(), + "restore from repair backup must succeed: {}", + String::from_utf8_lossy(&restore.stderr) + ); + let restored = fs::read(config_dir.join("libraries/primary.toml")).unwrap(); + assert_eq!( + restored, pre_bytes, + "restored library must equal pre-repair bytes" + ); +} diff --git a/tests/cli_surface_compat.rs b/tests/cli_surface_compat.rs index 412e91cc..b3ce7fa7 100644 --- a/tests/cli_surface_compat.rs +++ b/tests/cli_surface_compat.rs @@ -296,3 +296,37 @@ fn delete_top_and_data_agree_on_an_already_deleted_target() { ); assert_eq!(second.status.code(), Some(9)); } + +#[test] +fn organize_top_and_data_produce_equivalent_json() { + let (_tmp_top, config_top) = setup_test_env(); + setup_basic_library(&config_top); + let (_tmp_data, config_data) = setup_test_env(); + setup_basic_library(&config_data); + + let top = run_args( + &config_top, + &["organize", "--id", "compat-1", "--favorite", "--json"], + ); + let data = run_args( + &config_data, + &[ + "data", + "organize", + "--id", + "compat-1", + "--favorite", + "--json", + ], + ); + assert_success(&top, "snp organize --favorite --json"); + assert_success(&data, "snp data organize --favorite --json"); + + let top_json: serde_json::Value = serde_json::from_slice(&top.stdout).unwrap(); + let data_json: serde_json::Value = serde_json::from_slice(&data.stdout).unwrap(); + assert_eq!(top_json["status"], data_json["status"]); + assert_eq!(top_json["status"], "updated"); + assert_eq!(top_json["id"], data_json["id"]); + assert_eq!(top_json["favorite"], data_json["favorite"]); + assert_eq!(top_json["folders"], data_json["folders"]); +} diff --git a/tests/diagnostic_output_stability.rs b/tests/diagnostic_output_stability.rs new file mode 100644 index 00000000..531b8ab9 --- /dev/null +++ b/tests/diagnostic_output_stability.rs @@ -0,0 +1,132 @@ +//! Golden-shape smoke tests for validate / doctor / repair JSON envelopes. + +mod support; + +use std::fs; +use std::path::Path; +use support::helpers::*; + +fn setup_fixture(config_dir: &Path) { + let libraries_dir = config_dir.join("libraries"); + fs::create_dir_all(&libraries_dir).unwrap(); + fs::write( + libraries_dir.join("main.toml"), + r#"[[snippets]] +id = "g1" +description = "warn empty desc later" +command = "echo hi" +[[snippets]] +id = "g2" +description = "" +command = "echo" +"#, + ) + .unwrap(); + fs::write( + config_dir.join("libraries.toml"), + r#"[[libraries]] +filename = "main" +is_primary = true +"#, + ) + .unwrap(); +} + +#[test] +fn validate_json_envelope_unchanged() { + let (_tmp, config_dir) = setup_test_env(); + setup_fixture(&config_dir); + let out = snp_in(&config_dir) + .args(["validate", "--json"]) + .output() + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + for key in [ + "schema_version", + "tool_version", + "strict_mode", + "dry_run", + "total_libraries", + "total_snippets", + "diagnostics", + ] { + assert!(json.get(key).is_some(), "missing key {key}"); + } + let diag = &json["diagnostics"][0]; + for key in [ + "code", + "severity", + "path", + "library", + "snippet_id", + "message", + "repairability", + ] { + assert!(diag.get(key).is_some(), "missing diagnostic field {key}"); + } +} + +#[test] +fn doctor_json_envelope_unchanged() { + let (_tmp, config_dir) = setup_test_env(); + setup_fixture(&config_dir); + let lib = config_dir.join("libraries").join("main.toml"); + let out = snp_in(&config_dir) + .args([ + "doctor", + "--library", + &lib.to_string_lossy(), + "--report", + "json", + ]) + .output() + .unwrap(); + assert!(out.status.success() || out.status.code() == Some(6)); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + for key in [ + "schema_version", + "tool_version", + "analysis_mode", + "total_entries", + "diagnostics", + "strict_mode", + "dry_run", + ] { + assert!(json.get(key).is_some(), "missing key {key}"); + } +} + +#[test] +fn repair_json_envelope_unchanged() { + let (_tmp, config_dir) = setup_test_env(); + setup_fixture(&config_dir); + let out = snp_in(&config_dir) + .args(["repair", "--json", "--dry-run"]) + .output() + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + for key in [ + "items", + "backups", + "applied", + "skipped", + "failed", + "exit_status", + ] { + assert!(json.get(key).is_some(), "missing key {key}"); + } + if let Some(items) = json["items"].as_array() + && let Some(item) = items.first() + { + for key in [ + "action", + "category", + "transaction_id", + "problem", + "fix", + "safe", + ] { + assert!(item.get(key).is_some(), "missing repair item field {key}"); + } + } +} diff --git a/tests/diagnostic_vocabulary_agreement.rs b/tests/diagnostic_vocabulary_agreement.rs new file mode 100644 index 00000000..9cb3e316 --- /dev/null +++ b/tests/diagnostic_vocabulary_agreement.rs @@ -0,0 +1,202 @@ +//! M003: validate, doctor (library/pet analysis), and repair agree on shared codes. + +mod support; + +use snip_it::Snippet; +use snip_it::commands::pet_analysis::analyze_entry; +use snip_it::{LibraryManager, PrimaryState}; +use std::fs; +use std::path::Path; +use support::helpers::*; + +fn write_diag_fixture(config_dir: &Path) { + let libraries_dir = config_dir.join("libraries"); + fs::create_dir_all(&libraries_dir).unwrap(); + let content = r#"[[snippets]] +id = "vocab-1" +description = "" +command = "" +"#; + fs::write(libraries_dir.join("diag.toml"), content).unwrap(); + let index = r#"[[libraries]] +filename = "diag" +is_primary = true +[[libraries]] +filename = "other" +is_primary = false +"#; + fs::write(config_dir.join("libraries.toml"), index).unwrap(); +} + +#[test] +fn validate_and_pet_analysis_agree_on_shared_codes() { + let (_tmp, config_dir) = setup_test_env(); + write_diag_fixture(&config_dir); + + let validate = snp_in(&config_dir) + .args(["validate", "--json", "--library", "diag"]) + .output() + .unwrap(); + assert!(validate.status.success() || validate.status.code() == Some(6)); + let report: serde_json::Value = serde_json::from_slice(&validate.stdout).unwrap(); + let diags = report["diagnostics"].as_array().unwrap(); + + let validate_cmd = diags + .iter() + .find(|d| d["code"] == "E-CMD-EMPTY") + .expect("validate must emit E-CMD-EMPTY"); + assert_eq!(validate_cmd["severity"], "Error"); + + let validate_desc = diags + .iter() + .find(|d| d["code"] == "W-DESC-EMPTY") + .expect("validate must emit W-DESC-EMPTY"); + assert_eq!(validate_desc["severity"], "Warning"); + + let pet = Snippet { + id: "vocab-1".to_string(), + description: String::new(), + command: String::new(), + ..Default::default() + }; + let pet_diags = analyze_entry(0, &pet); + let pet_cmd = pet_diags + .iter() + .find(|d| d.code == "E-CMD-EMPTY") + .expect("pet analysis must emit E-CMD-EMPTY"); + assert_eq!(format!("{:?}", pet_cmd.severity), "Error"); + + let pet_desc = pet_diags + .iter() + .find(|d| d.code == "W-DESC-EMPTY") + .expect("pet analysis must emit W-DESC-EMPTY"); + assert_eq!(format!("{:?}", pet_desc.severity), "Warning"); + + assert_eq!( + validate_cmd["code"], + pet_cmd.code.as_str(), + "code strings must match" + ); + assert_eq!( + validate_desc["code"], + pet_desc.code.as_str(), + "code strings must match" + ); +} + +#[test] +fn shared_scan_primary_state_matches_validate_and_repair_classification() { + let (_tmp, config_dir) = setup_test_env(); + let libraries_dir = config_dir.join("libraries"); + fs::create_dir_all(&libraries_dir).unwrap(); + fs::write( + config_dir.join("libraries.toml"), + r#"[[libraries]] +filename = "only" +is_primary = false +"#, + ) + .unwrap(); + fs::write( + libraries_dir.join("only.toml"), + r#"[[snippets]] +id = "s1" +description = "ok" +command = "echo ok" +"#, + ) + .unwrap(); + + let mgr = LibraryManager::with_config_dir(config_dir.to_path_buf()).unwrap(); + let scan = mgr.scan_libraries().unwrap(); + assert!(matches!(scan.primary, PrimaryState::NoPrimary { count: 1 })); + + let validate = snp_in(&config_dir) + .args(["validate", "--json"]) + .output() + .unwrap(); + let report: serde_json::Value = serde_json::from_slice(&validate.stdout).unwrap(); + let no_primary = report["diagnostics"] + .as_array() + .unwrap() + .iter() + .find(|d| d["code"] == "W-NO-PRIMARY") + .expect("validate W-NO-PRIMARY"); + assert_eq!(no_primary["severity"], "Warning"); + assert_eq!(no_primary["code"].as_str().unwrap(), "W-NO-PRIMARY"); + + let repair = snp_in(&config_dir) + .args(["repair", "--json", "--dry-run"]) + .output() + .unwrap(); + let repair_json: serde_json::Value = serde_json::from_slice(&repair.stdout).unwrap(); + let primary_items: Vec<_> = repair_json["items"] + .as_array() + .unwrap() + .iter() + .filter(|i| i["category"] == "primary") + .collect(); + assert_eq!(primary_items.len(), 1); +} + +#[test] +fn validate_and_repair_enumerate_same_disk_libraries_with_orphan() { + let (_tmp, config_dir) = setup_test_env(); + let libraries_dir = config_dir.join("libraries"); + fs::create_dir_all(&libraries_dir).unwrap(); + fs::write( + config_dir.join("libraries.toml"), + r#"[[libraries]] +filename = "main" +is_primary = true +"#, + ) + .unwrap(); + fs::write( + libraries_dir.join("main.toml"), + r#"[[snippets]] +id = "m1" +description = "d" +command = "echo" +"#, + ) + .unwrap(); + fs::write(libraries_dir.join("orphan.toml"), "[[snippets]]\n").unwrap(); + + let validate = snp_in(&config_dir) + .args(["validate", "--json"]) + .output() + .unwrap(); + let v: serde_json::Value = serde_json::from_slice(&validate.stdout).unwrap(); + assert_eq!(v["total_libraries"], 1); + let orphan_warn = v["diagnostics"] + .as_array() + .unwrap() + .iter() + .filter(|d| d["code"] == "W-ORPHAN-FILE") + .count(); + assert_eq!(orphan_warn, 1); + + let repair = snp_in(&config_dir) + .args(["repair", "--json", "--dry-run"]) + .output() + .unwrap(); + let r: serde_json::Value = serde_json::from_slice(&repair.stdout).unwrap(); + // Repair scans both on-disk libraries (indexed + orphan). + let paths: Vec = r["items"] + .as_array() + .unwrap() + .iter() + .filter_map(|i| i["problem"].as_str()) + .filter(|p| p.contains("orphan") || p.contains("main") || p.contains("Snippet")) + .map(str::to_string) + .collect(); + assert!( + !paths.is_empty() || r["items"].as_array().unwrap().is_empty(), + "repair dry-run completed" + ); + + let mgr = LibraryManager::with_config_dir(config_dir.to_path_buf()).unwrap(); + let scan = mgr.scan_libraries().unwrap(); + assert_eq!(scan.disk_library_paths().len(), 2); +}