diff --git a/CHANGELOG.md b/CHANGELOG.md index 156e16e..f069451 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,20 +9,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Compare one explicitly selected app's verified signed App Group declaration against an exact ID without enumerating applications or treating the result as ownership or current-use proof. - Optionally inventory immediate folders in five macOS Library locations for read-only review. Ownership and data purpose remain unverified; results may overlap known locations. - Show project `node_modules` as protected, review-only storage, and exclude nested package outputs from automatic cleanup candidates. - Record desktop-generated-output cleanup results locally and expose them through `still cleanup-history`. - Add read-only home, system-volume and selected-folder scans, with size-ordered folder navigation in the Mac app. - Add a Mac Docker screen action to review and prune unused default-builder cache after a user-selected retention period. +- Offer an explicit, non-overwriting restore of remaining staged data to its recorded sibling path on macOS. A restored payload may already be incomplete. +- Allow the desktop old-file search to include recognized project build outputs when requested. +- Keep compact per-scan workspace totals and provide a timeline in the Mac app and `still review-history`. +- Show comparable Library and Docker changes in the Mac overview and link incomplete cleanup results to stage review. +- Show filename-based Library clues and allow a user to record, update, or revoke their own scoped uninstall confirmation; neither authorizes deletion. +- Compare an explicitly selected signed app's App Group declaration against one specified group ID without enumerating apps or exposing its other entitlements. ### Changed +- Start newly scanned CLI plans with every entry kept; show recommendations separately in the review TUI. Existing saved plans are unchanged. +- Record available scan-time allocated size, start-of-cleanup keep settings, and the original-path check time with cleanup history. +- Record SDK, Docker container, and builder-cache outcomes in cleanup history, including partial or unverified SDK results. +- Confirm the number and size of candidates before selecting all eligible project outputs. +- Show project-by-project counts and sizes before bulk selection, and offer a direct view of independently reviewable Cargo subfolders. +- Include all unused builder cache in the age-filtered Docker cache cleanup, with the expanded scope shown before confirmation. +- Avoid waiting for per-file open-process checks in the desktop old-file search; the results explicitly state that use was not checked. - Compare regular-file contents as well as metadata during output review on Unix. This reads selected files and can make review slower; it does not guarantee detection of every concurrent change. - Include bounded Docker CLI error details when an inspection fails. - Match Buildx cache records against Engine metadata when Buildx returns human-readable dates, and verify filter behavior before attempting an exact cache removal. ### Fixed +- Avoid rejecting a staged file solely because its metadata change time changed after staging; verify its identity and contents before removal. +- Keep stage review controls visible for long paths and allow carefully verified Cargo cache subfolders to be reviewed when target markers were lost. +- Match equivalent ordinary and extended-length Windows drive paths when applying scan scopes and glob rules, without changing apply-time authorization. +- Display recognized Docker sizes in binary units and translate known relative dates on the Japanese screen. - Inspect stopped containers with bind mounts or null labels without losing Docker metadata, while continuing to protect managed and explicitly retained containers. ## [0.2.0-beta.1] - 2026-11-16 diff --git a/Cargo.toml b/Cargo.toml index aa150d8..20c8a3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,6 @@ name = "still" version = "0.2.0-beta.1" edition = "2021" default-run = "still" -authors = ["Antigravity"] description = "Local storage explorer and review-first cleanup tool" license-file = "LICENSE" # Source-available as requested diff --git a/README.md b/README.md index 779e296..602b755 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ cargo install --path . Mac のサイドバーの **ディスク** では、ホームフォルダがあるボリュームの使用率と空き容量、その物理ディスクの読み込み・書き込み速度を確認できます。この画面を開いている間に約2秒間隔で計測します。**Docker** では、現在のローカル接続先、または指定した接続先のコンテナ・イメージ・ボリューム・ビルドキャッシュを容量順に表示します。名前・ID・状態で絞り込み、行を選ぶと参照数やマウントなどの詳細を確認できます。Docker 内のサイズは、SSD の実際の回収量と異なる場合があります。 +Mac の Docker 画面で明示的に調査した後、Docker の `version`、`info`、`system df` を読み取り専用で追加実行し、種類別の容量サマリーを端末内に追記します。接続先・daemon・Dockerの版・保存方式とカテゴリが一致する観測だけを比較し、概要画面に種類ごとの概算の増減を表示します。Dockerの表示値は丸められ、種類間で容量が重なる場合があります。足し合わせた容量やSSDの回収量として扱いません。接続名・日時・カテゴリ別サイズ・比較結果と比較用の識別子を保存し、daemon IDとソケットパスはハッシュ化します。観測履歴は自動削除しません。取得や保存に失敗した場合は画面に表示します。 + Mac は左のナビゲーションから各画面を開き、候補一覧の右側で判定理由と削除後の影響を確認できます。保留や保護の項目も名前と容量を読みやすく表示し、選択した分だけ確認画面に進みます。選択とホバーの色は短く変化し、macOS の「視差効果を減らす」が有効なら起動時に動きを抑えます。画面構成と状態の扱いは [デスクトップの UX](docs/DESKTOP_UX.md) にまとめています。 フォルダ調査中は、確認済みのファイル数・フォルダ数・論理容量・調査している場所を表示します。容量の集計後は、掃除候補の安全性確認へ切り替わります。Library の残り物の所有元推定と週次提案、Before/After の記録は [整理アルゴリズムと製品プラン](docs/CLEANUP_STRATEGY.md) にまとめています。 @@ -54,14 +56,16 @@ Mac ではホームの「_workspace を調べる」から開始できます。 概要の「容量の大きい場所を探す」では、ホーム、システム領域、または選んだフォルダを読み取り専用で走査できます。フォルダは容量順に並び、クリックで中に入り、上のフォルダやパスの表示から戻れます。別ボリュームは走査せず、権限のない項目も読めません。外付けボリュームはフォルダ選択から個別に調べてください。 -アプリの保存容量画面では、必要に応じて Library の主要な保存先の調査を選べます。CLI では `still app-storage --library` です。`Caches`、`Logs`、`Application Support`、`Containers`、`Group Containers` の直下にあるフォルダを読み取り専用で集計します。所有元・用途は未確認として表示し、リンクはたどりません。既知の保存先と重なる行があるため、表示容量を合算できません。 +アプリの保存容量画面では、必要に応じて Library の主要な保存先の調査を選べます。CLI では `still app-storage --library` です。`Caches`、`Logs`、`Application Support`、`Containers`、`Group Containers` の直下にあるフォルダを読み取り専用で集計します。ファイル名からDB・ログ・アーカイブ・バックアップに見える件数を示しますが、本文は読まず、内容や用途を確定しません。判別できない名前や未調査の項目はその旨を表示します。所有元・用途は未確認として表示し、リンクはたどりません。既知の保存先と重なる行があるため、表示容量を合算できません。 + +Macでは、Library行のフォルダ名から認識できるbundle IDについて、自分がアプリをアンインストールし確認した場所(`/Applications`、`~/Applications`、または両方)と時刻を端末内に記録できます。本人の申告であり、OSやstillによる証明ではありません。記録は更新・撤回でき、削除可否や自動選択には使いません。別の場所やユーザーは確認範囲に含まれません。 標準の Cargo `target` が保留になった場合、`debug`・`release` 直下の `incremental` と `deps` は個別に検査します。Cargo の痕跡と中身の形式を確認できたフォルダだけが選択でき、証明書・ログ・結果など判別できない項目を含むフォルダは保留になります。 別の場所に置いた Cargo 出力も、ビルド痕跡が揃えば表示します。対応するプロジェクトが確認できない場合や、Git 追跡ファイル・リンク・保護項目などがある場合は、一覧の **Status** に保留理由が出ます。削除時には内容の変化や使用中のファイルを再確認します。 言語メニューで、画面や保留理由を英語・日本語に切り替えられます。行をクリックすると、長いパスを含む理由の全文が出ます。 -**Find old files…** で、ホーム配下から更新・アクセス・作成のうち、取得できた最新の日時が指定の日数より古いファイルを容量順に探せます。対象フォルダや最小サイズを指定して、結果をパスで絞れます。ターミナルでは `still stale --older-than-days 180 --min-mib 512` を実行し、`--root` でホーム配下のフォルダを指定できます。更新日・最終アクセス日・論理サイズ・上位候補の使用中チェックを表示します。開いているプロセスが見つからなくても、不要とは限りません。隠し項目、`Library`、`node_modules` は走査対象外です。 +**Find old files…** で、ホーム配下から更新・アクセス・作成のうち、取得できた最新の日時が指定の日数より古いファイルを容量順に探せます。対象フォルダや最小サイズを指定して、結果をパスで絞れます。画面ではCLIと同じく既定で開発プロジェクトの生成物を含め、チェックを外すと確認できた生成物を除外します。画面では使用中かどうかは確認しません。ターミナルの `still stale --older-than-days 180 --min-mib 512` は上位候補の使用中チェックを試みます。`--root` でホーム配下のフォルダを指定できます。開いているプロセスが見つからなくても、不要とは限りません。隠し項目、`Library`、`node_modules` はどちらも走査対象外です。 ```sh # ソースからウィンドウを起動(macOS / Windows) @@ -98,6 +102,8 @@ Windows の MSIX は [パッケージ作成スクリプト](scripts/build-window CLI では `still app-storage`、Xcode の一覧も含めるなら `still app-storage --xcode-runtimes` を実行します。CLI は読み取り専用です。Mac アプリでは、Chrome を終了してから「既定プロファイルの HTTP キャッシュを確認…」を選べます。対象は Google Chrome の Default プロファイルの `Cache_Data` のみです。確認画面には容量・件数・再取得の影響が表示され、実行結果は `still cleanup-history` に残ります。「Library の整理で残す」は次回の調査にも反映されます。SDK の版は各管理ツールで利用状況を確認してください。Notion のローカルデータや仕事の証跡になりうるログは保護表示します。ワークスペース調査では Unity の元アセットとキャッシュ、Unreal Engine 本体、元アセット、自動保存、ログ、生成キャッシュも判別して表示します。 +「アプリと SDK の容量」では、明示的に選んだアプリ1つの署名付き App Group 宣言を、入力したIDと照合できます。CLI は `still group-link --app <アプリの絶対パス> --group ` です。署名の整合性は発行元の真正性を証明せず、選んだアプリ以外の利用元、所有元、使用中かどうかも分かりません。同時変更をすべて検出できる保証はありません。宣言を確認できない場合は未確認として扱い、照合によってデータは削除しません。 + Mac 版の **App storage… → Review Xcode & NDK versions…** では、版ごとの容量と候補/保護の理由を表示します。古いランタイムは最終利用記録、端末の状態、テスト設定を確認し、利用記録がある場合は45日を目安にします。プロジェクト設定と NDK のビルド記録は、開いているプロファイルのフォルダ、`~/_workspace`、`~/AndroidStudioProjects` を調べます。候補を選んで **Review … selected → Uninstall … selected** と進むと、再確認できた版だけを各管理ツールでアンインストールします。結果には Mac のデータボリュームの前後の空き容量と、実測した差が出ます。 Xcode の削除処理後は、利用可能ランタイムの一覧と、対象ビルドのイメージも照合します。残っている場合は **一部残存** と表示し、確認できたイメージの使用量を、データボリューム全体で実測した空き容量の差と別に示します。 @@ -128,6 +134,8 @@ still review --profile weekly ``` `--root` だけで保存すると容量調査用のプロファイルになります。初回は比較元を記録し、次回から差分を表示します。差分の `*` は一部を走査できなかったときの観測値です。`--format json` などのレポート出力は走査履歴を更新しません。 +記録されたワークスペース全体の容量推移は、Macアプリのワークスペース操作メニューにある「この場所の容量履歴…」または `still review-history --root <絶対パス>` で確認できます。CLI の週次プロファイルで記録した場合は `--profile <名前>` を追加します。各観測の論理容量、取得できた割当容量と一部未走査の有無を表示し、CLIでは `--format json` と `--limit` も指定できます。古い最新比較用データから、それ以前の履歴は復元しません。履歴は端末内に観測ごとに保存し、自動削除しないため、スキャンを重ねると件数が増えます。 + `Enter` でディレクトリを開き、`←` で親に戻ります。`/` で現在地以下を検索し、`o` で別の調査先を開きます。`s` で合計容量順、最大ファイル順、前回からの増加順を切り替えます。増加順はプロファイルの前回走査があるときに使えます。 `Tab` に Cargo、Next.js、Vite の生成物候補と、対応するソースがある CPython のバイトコードキャッシュが出ます。`package.json` の隣の `node_modules` も容量を表示しますが、ローカル変更やリンクを含む可能性があるため削除対象にはしません。`Space` で選ぶと、Git の追跡状態と配下のファイルを確認します。`D` で実際に削除する対象を確認し、`y` で実行します。削除はゴミ箱を経由しません。`--output` は再生成できる専用出力先に指定してください。Unity の `Library` は容量と保護理由を表示します。 @@ -138,7 +146,9 @@ still review --profile weekly Rust の差分コンパイル用キャッシュ全体が保留でも、完了したコンパイル単位を個別に選べます。未完了の作業域・用途不明のファイル・保護マーカーがある単位は保持し、選択後の変更や使用中のファイルは実行前に再確認します。 -デスクトップの生成物削除結果は、対象パス・結果・論理容量とボリュームの空き容量の前後値を端末内に記録します。`still cleanup-history` または `still cleanup-history --format json` で参照できます。保存に失敗した場合は結果画面に表示します。削除が未完了の場合、元のパスが残っていなくてもステージ領域に残っている可能性があります。履歴はコンテナや SDK の操作をまだ含みません。 +残存ステージ内のデータを戻す場合は、Mac アプリの **残ったステージを確認… → 復元を確認** から Finder で内容と表示された移動先を確認してください。CLI では `still stage-cleanup <ステージのパス> --cleanup-root <対象ルート>` で確認し、同じ指定に `--restore` を加えると残存する `payload` を記録された元の場所へ移動します。既存の移動先は上書きしません。ステージの記録は由来や完全性の証明ではなく、処理中に一部が削除済みの場合があります。復元後もステージの記録は残ります。 + +デスクトップの生成物削除結果は、対象パス・結果・論理容量とボリュームの空き容量の前後値を端末内に記録します。取得できた場合は、削除前のスキャン時の割当容量、開始時にそのワークスペースに適用される「残す」設定、元のパスの存在を確認した時刻も記録します。MacではSDKのアンインストール、Dockerコンテナとビルドキャッシュの整理結果も記録します。部分残存・未確認は成功と区別し、Dockerの生出力や接続先詳細は保存しません。`still cleanup-history` または `still cleanup-history --format json` で参照でき、保存失敗は結果画面に表示します。削除が未完了の場合、元のパスが残っていなくてもステージ領域に残っている可能性があります。 Macで一部残存と表示されたときは、再スキャン後にワークスペースのメニューから「残ったステージを確認…」を開きます。場所を選ぶと内容を検査し、空のフォルダ・認識できたFinderメタデータ・元の場所の記録だけであれば、確認画面から片付けられます。CLIでは `still stage-cleanup --cleanup-root <整理ルート> <ステージのパス>` が確認のみ、同じ指定に `--apply` を付けると削除します。 @@ -203,8 +213,10 @@ still scan still scan --list-scopes ``` +Windowsでは、除外ルールの照合が曖昧になるのを避けるため、走査先・ルール範囲・globに `RUNNER~1` のような既知の8.3形式に見える表記があるとスキャンを中止します。長い名前を指定してください。同形の通常名やglobも拒否する場合があり、すべての8.3形式を検出できる保証はありません。大文字小文字や他の別名、ジャンクションを使った異なる表記の同一性も解決しません。 + ### 2. Review (確認・選別) -作成された計画ファイルをTUIで開き、アイテムごとにアクションを決定します。 +作成された計画ファイルをTUIで開き、アイテムごとにアクションを決定します。推奨アクションは表示用で、初期状態ではすべて Keep です。 ```bash still tui diff --git a/README_EN.md b/README_EN.md index b9562d0..d441fa9 100644 --- a/README_EN.md +++ b/README_EN.md @@ -38,6 +38,8 @@ The initial interface is Japanese. Use the language menu in the upper right to s On the Mac, **Disk** in the header shows capacity for your home volume and separate read/write activity for the physical disks serving it. Sampling runs about every two seconds while this view is open. **Docker** lists local containers, images, volumes and build cache by reported size, with name/ID/state filtering and details for the selected row. Docker storage sizes can differ from actual SSD space recoverable. +After an explicit scan in the Mac Docker view, still runs additional read-only `version`, `info`, and `system df` commands and appends category summaries locally. The overview compares observations only when the endpoint, daemon, Docker versions, storage configuration, and category set match. Docker rounds the reported sizes, and categories may overlap; do not add them together or treat their changes as SSD space reclaimed. The record includes the context name, timestamp, sizes, comparisons, and comparison identifiers; the daemon ID and socket path are hashed. Observation history is not automatically deleted. Failures to obtain or save a comparison are shown in the app. + Workspace scans report observed file/folder counts, logical bytes and the current directory before checking candidate safety. The [cleanup algorithm and product plan](docs/CLEANUP_STRATEGY.md) describes the proposed Library ownership checks and before/after evidence. Open `still.app` on macOS or `stilll` from the Windows Start menu. Choose **Add workspace…**, sort folders by size, or search paths recursively. Choose **Save as…** to save a weekly profile. Profiles saved with `still review --save-profile` can also be opened here. @@ -52,7 +54,7 @@ When a standard Cargo `target` is held, still checks the `incremental` and `deps Relocated Cargo output appears when the scan finds build markers and compiled profiles. **Status** explains blockers such as missing project context, tracked files, symbolic links, and protected entries. The final removal check also checks for changes and files in use. -Use **Reasons** to switch blocker explanations between English and Japanese. **Find old files…** lists large files under your home folder by the latest available modification, access, or creation date, with date details and an open-file check where available. You can select a folder, change the minimum age and size, and filter the results by path. The CLI equivalent is `still stale --older-than-days 180 --min-mib 512`. Old files are shown for review; an access date or open-file check cannot prove a file is unused. +Use **Reasons** to switch blocker explanations between English and Japanese. **Find old files…** lists large files under your home folder by the latest available modification, access, or creation date. You can select a folder, change the minimum age and size, and filter the results by path. Like the CLI, the GUI includes project build output by default; turn the option off to exclude recognized build output. The GUI does not check whether files are open. The CLI, `still stale --older-than-days 180 --min-mib 512`, attempts an open-file check for the top results. An access date or open-file check cannot prove a file is unused. Local Docker review also lists unreferenced volumes as protected. To inspect completed jobs and pods from a local Kubernetes or K3s context, use `still kube --kubeconfig ~/kube-local.yaml --context my-local --namespace dev` or add the context in **Candidate sources**. Cluster inspection is read-only and requires a verified loopback HTTPS endpoint. @@ -82,10 +84,18 @@ scripts/notarize-macos-app.sh target/still-signed.app still-notary target/still- On macOS, **App storage…** measures known Android NDK, Unity, Unreal, browser cache, Slack and Teams log, and Notion data locations under your home folder. It reads metadata without opening logs or databases. The optional Xcode checkbox queries its simulator runtime inventory. Use `still app-storage` or `still app-storage --xcode-runtimes` in the terminal. The CLI inventory is read-only. In the Mac app, close Chrome and choose **Review default profile HTTP cache…** to inspect its Default profile’s `Cache_Data` directory. A separate confirmation shows the scope, size and download impact. Results are recorded in `still cleanup-history`. **Keep in Library cleanup** also applies to future scans. Workspace review also identifies protected game assets, autosaves, engine files, and caches. -The optional Library inventory, also available as `still app-storage --library`, measures immediate folders in Caches, Logs, Application Support, Containers, and Group Containers. It reports exact registered bundle ID matches where available and skips links. Shared locations and unverified owners remain review-only. Entries may overlap known locations, so their sizes must not be added together. +The Mac app also records SDK uninstall and Docker container and build-cache cleanup results in `still cleanup-history`. Partial and unverified outcomes are distinguished from success. Docker output and endpoint details are not retained; history save failures are shown with the operation result. + +The app storage screen can compare an exact App Group ID against the signed declaration of one app you explicitly select. In the CLI, use `still group-link --app --group `. Signature integrity does not prove the publisher's identity, ownership, current use, or the other apps that may use a group. Concurrent changes may not always be detected. An unverifiable declaration remains unknown; this check never removes data. + +The optional Library inventory, also available as `still app-storage --library`, measures immediate folders in Caches, Logs, Application Support, Containers, and Group Containers. It counts names that resemble databases, logs, archives, or backups without reading file contents or claiming their actual purpose; undecodable names and incomplete inspection are indicated. It reports exact registered bundle ID matches where available and skips links. Shared locations and unverified owners remain review-only. Entries may overlap known locations, so their sizes must not be added together. + +On macOS, for a bundle ID recognizable from a Library folder name, you may record your own statement that you uninstalled the app, including when and which locations you checked (`/Applications`, `~/Applications`, or both). This is your statement, not proof by the OS or still; other locations and users are outside its scope. You can update or revoke it. It never controls deletion or automatic selection. Workspace review shows `node_modules` next to a `package.json` as protected, review-only storage. When an output is selected for removal, still reads regular-file contents to compare them again; contents are not stored or transmitted. Reviewing large outputs can take time, and the checks cannot guarantee detection of every concurrent change. +To restore data left in a stage, choose **Review leftover stages… → Review restore** in the Mac app and inspect the contents in Finder and the displayed destination. In the CLI, preview with `still stage-cleanup --cleanup-root `, then add `--restore` to move the remaining `payload` to its recorded original location. An existing destination is never overwritten. The stage record does not prove origin or completeness, and some data may already have been removed. The stage record remains after restoration. + On the Mac, select **App storage… → Review Xcode & NDK versions…** to see each SDK version’s size and the reason it is available for review or protected. Review and confirm individual versions to uninstall them with their management tools. still checks the selected versions again before uninstalling and reports the actual change in free space on the Mac data volume. After an Xcode uninstall, still also checks the usable runtime inventory and disk images for the selected build. When evidence remains, it shows **Partially remaining** and reports observed image usage separately from the measured change in volume free space. @@ -102,6 +112,8 @@ still review --root ~/projects --search target --format json Save a weekly profile with `still review --save-profile weekly --cleanup-root ~/projects` and reopen it with `still review --profile weekly`. With a previous scan available, `s` can sort directories by growth. Formatted reports read the same history without updating it. +Use **This workspace's size history…** in the Mac workspace menu or `still review-history --root ` to read recorded workspace totals over time; add `--profile ` for a CLI review profile. Each observation reports logical bytes, allocated bytes when available, and whether the scan skipped entries. The CLI supports `--format json` and `--limit`. Earlier history is not reconstructed from the old latest-snapshot file. Each observation is stored locally and is not automatically deleted, so the number of records grows over time. + Press Enter to open a directory, `/` to search, or `o` to choose another root. With a cleanup root configured, Tab shows generated outputs. Space checks and selects an output. `D` opens the deletion preview, and `y` confirms permanent removal. Use `--output` to declare a dedicated reproducible script output directory. `still worktrees --help` and `still docker --help` show the options for the other cleanup sources. @@ -121,8 +133,10 @@ still scan still scan --list-scopes ``` +On Windows, scans stop when a root, rule scope, or glob resembles a known 8.3 short-name spelling such as `RUNNER~1`, because exclusions may otherwise be ambiguous. Specify long names. This check may also reject ordinary names or globs with the same form and does not guarantee detection of every 8.3 spelling. It does not resolve case differences, other aliases, or junctions. + ### 2. Review (TUI) -Open the generated plan in the TUI to decide actions for each item. +Open the generated plan in the TUI to decide actions for each item. Recommendations are informational; every item initially remains set to Keep. ```bash still tui diff --git a/docs/CLEANUP_STRATEGY.md b/docs/CLEANUP_STRATEGY.md index 050f6ce..19cdeca 100644 --- a/docs/CLEANUP_STRATEGY.md +++ b/docs/CLEANUP_STRATEGY.md @@ -64,8 +64,18 @@ SSD の使用率を見て、前週から増えた場所を開き、候補の容 Library 直下の対象5領域を明示スキャンし、同じファイルシステム上の割当容量と、通常ファイルの更新・作成・アクセス記録の最新値を集計する。フォルダ自体の更新日時も別に扱う。ファイル本文は読まない。共有コンテナ以外でディレクトリ名と登録済みアプリの bundle ID が完全一致したときだけ、対応するアプリと起動中かどうかを照合する。未登録、登録照会失敗、アンインストール確認済みは同一視しない。アクセス記録の古さは未使用の証明にしない。 +通常ファイルの名前から DB・ログ・アーカイブ・バックアップ形式の可能性を集計する。名前だけの手掛かりであり、内容・用途・削除可能性を確定しない。本人が特定の bundle ID についてアンインストールと場所の確認を申告した場合は、選択した確認範囲・日時とともに端末内に記録し、撤回・再確認できる。OSの証明や削除判断には使わない。 + +App Group は、利用者が明示的に選んだアプリ一つの署名と entitlements を調べ、指定したグループIDの宣言との完全一致を確認できる。署名の整合性は発行元の真正性や利用状況、すべての利用元の証明ではなく、同時変更も完全には検出できない。共有コンテナの所有元を自動確定したり、照合結果を削除判断に使ったりしない。 + デスクトップの明示スキャンで直前の完全観測との差を表示する。ワークスペースと Library で「残す」を選んだ場所は、次回の確認と削除直前に照合する。 +明示したワークスペース調査では、各時点のルート全体の論理容量・割当容量・部分調査の状態を端末内に記録し、Mac の操作メニューまたは `still review-history` で履歴を確認できる。フォルダごとの過去全件は保存せず、この機能の追加前の観測も遡って作らない。掃除履歴には、取得できたスキャン時の割当容量、開始時のワークスペースの保持設定、元のパスを確認した時刻を記録する。 + +SDK、Docker コンテナ、Docker ビルドキャッシュの操作も、対象・結果・測定できた空き容量を整理履歴に残す。SDK の一部残存や確認不能を区別し、残存イメージの容量を確認できた場合は併記する。Docker の生出力や接続先詳細、エラーの原文は保存しない。 + +ホームでは、プロジェクトの増加に加えて、比較可能な Library の増加と Docker の種類別容量差を別々の根拠・観測日時で示す。Docker は同じ daemon・接続先・バージョンなどの条件を満たす場合に限り、丸められた Docker の集計値を比較する。共有領域を含むカテゴリを合計せず、Mac の空き容量差とも区別する。未取得や失敗は画面に示す。 + 最初の Library 整理対象は Google Chrome の Default プロファイルの HTTP キャッシュ。登録済みの bundle ID と停止状態を確認し、固定された保存先で Chromium の索引とエントリの形式を照合する。対象と再取得の影響を表示し、承認されたディレクトリだけを再検証してステージに移す。完了または未完了の理由とボリュームの空き容量差は既存の整理履歴に記録する。ログ、DB、共有コンテナは読み取り専用とする。 配布検証では macOS のローカル署名付きバンドルに加え、Windows CI で検証用 ID の MSIX を作成し、展開した CLI と GUI のハッシュを release ビルドと照合する。Developer ID 署名・Apple 公証・別端末での確認と、この版の Store 署名・実機確認は外部配布の工程として残る。 diff --git a/docs/DESKTOP_UX.md b/docs/DESKTOP_UX.md index e4374c8..fbf08a2 100644 --- a/docs/DESKTOP_UX.md +++ b/docs/DESKTOP_UX.md @@ -95,7 +95,9 @@ The visual concept informed the sidebar, list, inspector and footer. Its sample numbers are not application data. The application deliberately uses its actual producer/blocker reason and states that open files are checked again before removal. A scan does not prove that a candidate is unused. Disk statistics and -Docker storage browsing remain read-only. Navigation cannot replace an active +Docker storage browsing are read-only; separately confirmed actions can remove +eligible containers or prune unused builder cache on the selected local daemon. +Navigation cannot replace an active cleanup job. Profiles, SDK checks, partial-removal accounting and the explicit confirmation contracts remain authoritative. diff --git a/docs/phase_2_1_fortification.md b/docs/phase_2_1_fortification.md index 88be833..4fad38f 100644 --- a/docs/phase_2_1_fortification.md +++ b/docs/phase_2_1_fortification.md @@ -7,7 +7,7 @@ Goal: "Hard Safety" — hardening the system against operational accidents. 1. **Purge Separation**: `still apply` NEVER performs permanent deletion (Purge). 2. **Validator Barrier**: No IO operations unless the plan passes validation. 3. **No Symlink Traversal**: Symlinks are never followed; they are skipped or rejected. -4. **No Network / No Telemetry**: Strict local-only operation. +4. **No Telemetry**: Scan, plan, and apply operate locally. Other workflows can explicitly request network access; for example, `--github-pr` invokes `gh` to query GitHub. 5. **Default Deny (Scope)**: Apply is rejected if paths are outside permitted scopes. ## Implementation Details diff --git a/src/cli.rs b/src/cli.rs index 49d9ca0..1372080 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -28,8 +28,13 @@ pub enum Commands { Stale(StaleArgs), #[command(about = "Review Mac app storage, SDK versions, caches, and protected data")] AppStorage(AppStorageArgs), + #[cfg(target_os = "macos")] + #[command(about = "Check one selected application's signed App Group declaration")] + GroupLink(GroupLinkArgs), #[command(about = "Read locally recorded desktop cleanup results")] CleanupHistory(CleanupHistoryArgs), + #[command(about = "Read recorded workspace scan totals over time")] + ReviewHistory(ReviewHistoryArgs), #[cfg(target_os = "macos")] #[command(about = "Review Finder metadata left in a cleanup stage")] StageCleanup(StageCleanupArgs), @@ -52,8 +57,11 @@ pub struct StageCleanupArgs { #[arg(long)] pub cleanup_root: PathBuf, /// Permanently remove the reviewed metadata and empty stage directories. - #[arg(long)] + #[arg(long, conflicts_with = "restore")] pub apply: bool, + /// Move the remaining payload back to the recorded sibling path, without overwriting it. + #[arg(long)] + pub restore: bool, } #[derive(Args, Debug)] @@ -65,6 +73,21 @@ pub struct CleanupHistoryArgs { pub format: ListFormat, } +#[derive(Args, Debug)] +pub struct ReviewHistoryArgs { + /// Workspace root from the recorded scan (absolute path). + #[arg(long)] + pub root: PathBuf, + /// Read a named review profile's history instead of the desktop workspace history. + #[arg(long)] + pub profile: Option, + /// Maximum number of recent observations to display. + #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u16).range(1..=500))] + pub limit: u16, + #[arg(long, value_enum, default_value_t = ListFormat::Text)] + pub format: ListFormat, +} + #[derive(Args, Debug)] pub struct AppStorageArgs { /// Also ask Xcode for its installed simulator runtime inventory. @@ -77,6 +100,17 @@ pub struct AppStorageArgs { pub format: ListFormat, } +#[cfg(target_os = "macos")] +#[derive(Args, Debug)] +pub struct GroupLinkArgs { + /// Explicitly selected .app bundle to inspect; its code is not launched. + #[arg(long)] + pub app: PathBuf, + /// Exact App Group identifier to compare. + #[arg(long)] + pub group: String, +} + #[derive(clap::ValueEnum, Clone, Copy, Default, Debug, Eq, PartialEq)] pub enum StaleSort { #[default] diff --git a/src/lib.rs b/src/lib.rs index 5d9c373..f7fa19d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,71 @@ pub fn launch_desktop(profile: Option) -> Result<()> { } } +fn scan_roots_to_plan( + paths: Vec, + rules: &[config::rules::Rule], + started: std::time::SystemTime, + output: &std::path::Path, + json: bool, +) -> Result<()> { + let mut entries = Vec::new(); + for path in paths { + let exists = path.exists(); + if !exists { + println!("Skipping non-existent path: {:?}", path); + } else { + println!("Scanning: {:?}", path); + } + let scanner = scan::walk::Scanner::new(path, rules.to_vec()); + // Never save a successful partial plan when a scanner returns an error. + entries.append(&mut scanner.scan()?); + } + println!("Found {} entries", entries.len()); + let plan = plan::Plan { + schema_version: "2.0".to_string(), + generated_by: "still".to_string(), + created_at: started, + entries, + }; + if json { + println!("{}", serde_json::to_string_pretty(&plan)?); + } + plan::io::save_plan(&plan, output)?; + println!("Plan saved to {:?}", output); + Ok(()) +} + +#[cfg(all(test, windows))] +mod scan_safety_tests { + use super::*; + + #[test] + fn later_root_failure_does_not_overwrite_existing_plan() -> Result<()> { + let fixture = tempfile::tempdir()?; + let root = fixture.path().canonicalize()?; + let first = root.join("first"); + let second = root.join("ambiguous~1"); + std::fs::create_dir(&first)?; + std::fs::create_dir(&second)?; + std::fs::write(first.join("found.dat"), b"fixture")?; + let scanner = scan::walk::Scanner::new(first.clone(), vec![]); + assert_eq!(scanner.scan()?.len(), 1, "first root must be scannable"); + let output = root.join("plan.json"); + std::fs::write(&output, b"original plan")?; + let error = scan_roots_to_plan( + vec![first, second], + &[], + std::time::SystemTime::now(), + &output, + true, + ) + .expect_err("a later ambiguous root must stop plan creation"); + assert!(error.to_string().contains("8.3 short name")); + assert_eq!(std::fs::read(&output)?, b"original plan"); + Ok(()) + } +} + pub fn run_cli() -> Result<()> { let cli = Cli::parse(); @@ -133,8 +198,6 @@ pub fn run_cli() -> Result<()> { } }; - let mut all_entries = Vec::new(); - // Load rules // Load rules let rules_path = if let Some(path) = &args.rules { @@ -175,34 +238,7 @@ pub fn run_cli() -> Result<()> { vec![] }; - for path in target_paths { - if !path.exists() { - println!("Skipping non-existent path: {:?}", path); - continue; - } - println!("Scanning: {:?}", path); - let scanner = scan::walk::Scanner::new(path, rules.clone()); - match scanner.scan() { - Ok(mut entries) => all_entries.append(&mut entries), - Err(e) => eprintln!("Error scanning: {}", e), - } - } - - println!("Found {} entries", all_entries.len()); - - let plan = plan::Plan { - schema_version: "2.0".to_string(), - generated_by: "still".to_string(), - created_at: start, - entries: all_entries, - }; - - if args.json { - println!("{}", serde_json::to_string_pretty(&plan)?); - } - - plan::io::save_plan(&plan, &args.out)?; - println!("Plan saved to {:?}", args.out); + scan_roots_to_plan(target_paths, &rules, start, &args.out, args.json)?; } Some(Commands::Review(args)) => review::run(args)?, Some(Commands::Gui(args)) => launch_desktop(args.profile.clone())?, @@ -212,8 +248,11 @@ pub fn run_cli() -> Result<()> { Some(Commands::Stale(args)) => review::stale::run(args)?, Some(Commands::AppStorage(args)) => review::app_storage::run(args)?, #[cfg(target_os = "macos")] + Some(Commands::GroupLink(args)) => review::app_storage::group_link::run(args)?, + #[cfg(target_os = "macos")] Some(Commands::StageCleanup(args)) => review::recover_stage(args)?, Some(Commands::CleanupHistory(args)) => review::cleanup_history::run(args)?, + Some(Commands::ReviewHistory(args)) => review::review_history(args)?, Some(Commands::Tui(args)) => { println!("Starting TUI with plan: {:?}", args.plan); let mut app = tui::app::App::new(args.plan.clone())?; diff --git a/src/review/app_storage.rs b/src/review/app_storage.rs index 8ef78db..959d086 100644 --- a/src/review/app_storage.rs +++ b/src/review/app_storage.rs @@ -1,9 +1,13 @@ +#[cfg(target_os = "macos")] +pub(crate) mod group_link; #[cfg(all(target_os = "macos", feature = "desktop"))] pub(super) mod known_cache; #[cfg(target_os = "macos")] -mod library; +pub(super) mod library; +#[cfg(all(target_os = "macos", any(test, feature = "desktop")))] +pub(super) mod observations; #[cfg(all(target_os = "macos", any(test, feature = "desktop")))] -mod observations; +pub(super) mod uninstall_assertions; #[cfg(all(target_os = "macos", feature = "desktop"))] pub(super) fn desktop_scan(xcode: bool, include_library: bool) -> anyhow::Result { @@ -65,6 +69,7 @@ pub fn run(args: &AppStorageArgs) -> Result<()> { #[cfg(target_os = "macos")] if let Some(evidence) = row.library { println!(" {}", evidence.activity_text(false)); + println!(" {}", evidence.name_hints_text(false)); } } for note in result.notes { @@ -80,10 +85,12 @@ pub(super) fn scan(_: bool, _: bool) -> Result { anyhow::bail!("App storage review is currently available on macOS") } +#[cfg(target_os = "macos")] +pub(super) use mac::command_output; #[cfg(target_os = "macos")] pub(super) use mac::scan; #[cfg(all(target_os = "macos", feature = "desktop"))] -pub(super) use mac::{command_output, runtimes, simctl_json, Runtime}; +pub(super) use mac::{runtimes, simctl_json, Runtime}; #[cfg(target_os = "macos")] mod mac { diff --git a/src/review/app_storage/group_link.rs b/src/review/app_storage/group_link.rs new file mode 100644 index 0000000..4f3f65f --- /dev/null +++ b/src/review/app_storage/group_link.rs @@ -0,0 +1,259 @@ +//! One explicitly selected app, one exact group identifier. No app enumeration. +use anyhow::{bail, ensure, Context, Result}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Declaration { + Match, + NoMatch, + NoGroups, +} + +fn valid_group(group: &str) -> bool { + !group.is_empty() && group.len() <= 1024 && !group.chars().any(char::is_control) +} + +fn parse_groups(json: &str, group: &str) -> Result { + let value: serde_json::Value = serde_json::from_str(json).context("Invalid entitlements")?; + let object = value + .as_object() + .context("Expected an entitlements dictionary")?; + let Some(groups) = object.get("com.apple.security.application-groups") else { + return Ok(Declaration::NoGroups); + }; + let groups = groups + .as_array() + .context("Invalid App Groups entitlement")?; + let groups = groups + .iter() + .map(|value| value.as_str().context("Invalid App Group identifier")) + .collect::>>()?; + Ok(if groups.contains(&group) { + Declaration::Match + } else { + Declaration::NoMatch + }) +} + +// plutil parses the platform plist format. Keep entitlement data out of logs, +// saved reports and the UI; temporary files use private OS-created handles. +fn plist_to_json(input: &[u8]) -> Result { + let mut source = tempfile::tempfile()?; + source.write_all(input)?; + source.seek(SeekFrom::Start(0))?; + let mut output = tempfile::tempfile()?; + let mut child = Command::new("/usr/bin/plutil") + .args(["-convert", "json", "-o", "-", "-"]) + .stdin(Stdio::from(source)) + .stdout(Stdio::from(output.try_clone()?)) + .stderr(Stdio::null()) + .spawn() + .context("Could not start entitlement parser")?; + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if output.metadata()?.len() > 4 * 1024 * 1024 { + let _ = child.kill(); + let _ = child.wait(); + bail!("Entitlement data is too large"); + } + if let Some(status) = child.try_wait()? { + ensure!(status.success(), "Could not parse entitlement data"); + break; + } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + bail!("Entitlement parser timed out"); + } + std::thread::sleep(Duration::from_millis(25)); + } + output.seek(SeekFrom::Start(0))?; + let mut result = String::new(); + output + .take(4 * 1024 * 1024 + 1) + .read_to_string(&mut result)?; + ensure!( + result.len() <= 4 * 1024 * 1024, + "Entitlement data is too large" + ); + Ok(result) +} + +fn verify(app: &Path) -> Result<()> { + super::command_output( + Command::new("/usr/bin/codesign") + .args(["--verify", "--strict", "--all-architectures", "--"]) + .arg(app), + Duration::from_secs(30), + ) + .context("The application's signature could not be verified")?; + Ok(()) +} + +fn main_executable(app: &Path) -> Result { + let contents = app.join("Contents"); + let executable_dir = contents.join("MacOS"); + for directory in [&contents, &executable_dir] { + let metadata = std::fs::symlink_metadata(directory)?; + ensure!( + metadata.is_dir() && !metadata.file_type().is_symlink(), + "Application layout could not be verified" + ); + } + let info = contents.join("Info.plist"); + let info_meta = std::fs::symlink_metadata(&info)?; + ensure!( + info_meta.is_file() && !info_meta.file_type().is_symlink(), + "Application metadata could not be verified" + ); + let name = super::command_output( + Command::new("/usr/bin/plutil") + .args(["-extract", "CFBundleExecutable", "raw", "-o", "-", "--"]) + .arg(&info), + Duration::from_secs(10), + ) + .context("Could not read the application executable name")?; + let name = std::ffi::OsStr::new(name.trim()); + let mut components = Path::new(name).components(); + ensure!( + matches!(components.next(), Some(std::path::Component::Normal(_))) + && components.next().is_none(), + "Invalid application executable name" + ); + let executable = executable_dir.join(name); + let metadata = std::fs::symlink_metadata(&executable)?; + ensure!( + metadata.is_file() && !metadata.file_type().is_symlink(), + "Application executable could not be verified" + ); + Ok(executable) +} + +fn file_stamp(path: &Path) -> Result<(u64, u64, i64, i64, u64)> { + use std::os::unix::fs::MetadataExt; + let meta = std::fs::symlink_metadata(path)?; + ensure!( + !meta.file_type().is_symlink(), + "Application entry changed during inspection" + ); + Ok(( + meta.dev(), + meta.ino(), + meta.ctime(), + meta.ctime_nsec(), + meta.len(), + )) +} + +pub(crate) fn inspect(app: &Path, group: &str) -> Result { + use std::os::unix::fs::MetadataExt; + ensure!(valid_group(group), "Enter a valid App Group identifier"); + ensure!( + app.is_absolute() && app.extension().is_some_and(|ext| ext == "app"), + "Select an absolute .app bundle" + ); + let metadata = std::fs::symlink_metadata(app).context("Cannot inspect selected application")?; + ensure!( + metadata.is_dir() && !metadata.file_type().is_symlink(), + "Expected a regular application bundle" + ); + let app = app.canonicalize()?; + let initial = std::fs::symlink_metadata(&app)?; + ensure!( + (metadata.dev(), metadata.ino()) == (initial.dev(), initial.ino()), + "Selected application changed during inspection" + ); + let executable = main_executable(&app)?; + let initial_executable = file_stamp(&executable)?; + let initial_info = file_stamp(&app.join("Contents/Info.plist"))?; + verify(&app)?; + let xml = super::command_output( + Command::new("/usr/bin/codesign") + .args(["-d", "--xml", "--entitlements", "-", "--"]) + .arg(&app), + Duration::from_secs(15), + ) + .context("Could not read signed entitlement data")?; + let result = if xml.trim().is_empty() { + Declaration::NoGroups + } else { + parse_groups(&plist_to_json(xml.as_bytes())?, group)? + }; + // A second check reduces the chance of reporting a changed bundle. It is + // not an atomic guarantee against concurrent modification. + verify(&app)?; + let final_metadata = std::fs::symlink_metadata(&app)?; + ensure!( + ( + initial.dev(), + initial.ino(), + initial.ctime(), + initial.ctime_nsec() + ) == ( + final_metadata.dev(), + final_metadata.ino(), + final_metadata.ctime(), + final_metadata.ctime_nsec() + ), + "Selected application changed during inspection" + ); + ensure!( + main_executable(&app)? == executable + && file_stamp(&executable)? == initial_executable + && file_stamp(&app.join("Contents/Info.plist"))? == initial_info, + "Application executable or metadata changed during inspection" + ); + Ok(result) +} + +pub(crate) fn run(args: &crate::cli::GroupLinkArgs) -> Result<()> { + let result = inspect(&args.app, &args.group)?; + println!( + "Selected app: {}\nApp Group: {}", + args.app.display(), + args.group + ); + println!( + "{}", + match result { + Declaration::Match => "The signed entitlement declares this exact group.", + Declaration::NoMatch => "The signed entitlement does not declare this exact group.", + Declaration::NoGroups => + "No App Groups entitlement was found in the selected app's signature.", + } + ); + println!("Signature integrity does not prove publisher identity. This checks one app only; it does not establish ownership, use, or all group members. Concurrent changes may not always be detected."); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact_match_and_unknown_data_are_distinct() { + let json = + r#"{"com.apple.security.application-groups":["group.test.one","group.test.two"]}"#; + assert_eq!( + parse_groups(json, "group.test.one").unwrap(), + Declaration::Match + ); + assert_eq!( + parse_groups(json, "group.test").unwrap(), + Declaration::NoMatch + ); + assert_eq!( + parse_groups("{}", "group.test").unwrap(), + Declaration::NoGroups + ); + assert!(parse_groups( + r#"{"com.apple.security.application-groups":"group.test"}"#, + "group.test" + ) + .is_err()); + assert!(parse_groups("invalid", "group.test").is_err()); + assert!(!valid_group("bad\nname")); + } +} diff --git a/src/review/app_storage/known_cache.rs b/src/review/app_storage/known_cache.rs index 30123b8..903ef5f 100644 --- a/src/review/app_storage/known_cache.rs +++ b/src/review/app_storage/known_cache.rs @@ -238,16 +238,19 @@ fn apply_in( Some(false) => None, }); Ok(cleanup_history::Record { + operation: None, version: 1, root: home.join(ROOT), started_at, completed_at: Utc::now(), available_before: before, available_after: after, + kept_paths_at_start: None, items: vec![cleanup_history::Item { path: approved.path, producer: "Google Chrome HTTP cache (Default)".to_owned(), logical_bytes: approved.logical_bytes, + scanned_allocated_bytes: Some(approved.allocated_bytes), status: if reason.is_none() { "removed" } else { @@ -256,6 +259,7 @@ fn apply_in( .to_owned(), reason, original_path_exists: exists, + original_path_checked_at: Some(Utc::now()), }], }) } diff --git a/src/review/app_storage/library.rs b/src/review/app_storage/library.rs index b1bac5f..6ecc526 100644 --- a/src/review/app_storage/library.rs +++ b/src/review/app_storage/library.rs @@ -68,6 +68,63 @@ pub(super) struct Activity { pub newest_file_accessed: Option>, pub files: u64, pub skipped: u64, + name_hints: NameHints, +} + +#[derive(Default, Debug, Serialize)] +struct NameHints { + database: u64, + log: u64, + archive: u64, + backup: u64, + undecodable: u64, +} + +impl NameHints { + fn observe(&mut self, name: &OsStr) { + let Some(name) = name.to_str().map(str::to_ascii_lowercase) else { + self.undecodable += 1; + return; + }; + let database = [ + ".db", + ".db3", + ".sqlite", + ".sqlite3", + ".realm", + ".db-wal", + ".db-shm", + ".sqlite-wal", + ".sqlite-shm", + ".sqlite3-wal", + ".sqlite3-shm", + ] + .iter() + .any(|ext| name.ends_with(ext)); + let log = name.ends_with(".log") + || name.ends_with(".log.gz") + || name.ends_with(".log.old") + || name.rsplit_once(".log.").is_some_and(|(_, suffix)| { + let digits = suffix.strip_suffix(".gz").unwrap_or(suffix); + let digits = digits.strip_prefix("old.").unwrap_or(digits); + !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) + }); + let archive = [ + ".zip", ".tar", ".tar.gz", ".tgz", ".gz", ".bz2", ".xz", ".7z", ".rar", + ] + .iter() + .any(|ext| name.ends_with(ext)); + let backup = [".bak", ".backup", ".old"] + .iter() + .any(|ext| name.ends_with(ext)) + || name.rsplit_once(".old.").is_some_and(|(_, digits)| { + !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) + }); + self.database += u64::from(database); + self.log += u64::from(log); + self.archive += u64::from(archive); + self.backup += u64::from(backup); + } } /// File observations are maxima of recorded filesystem timestamps. Access times @@ -106,6 +163,7 @@ pub(super) fn measure(path: &Path, home_device: u64) -> Result<(u64, Activity)> continue; } activity.files += 1; + activity.name_hints.observe(entry.file_name()); if metadata.nlink() == 1 || hardlinks.insert(metadata.ino()) { allocated = allocated.saturating_add(metadata.blocks().saturating_mul(512)); } @@ -132,6 +190,16 @@ pub(in crate::review) struct Evidence { } impl Evidence { + #[cfg(feature = "desktop")] + pub(in crate::review) fn bundle_id(&self) -> Option<&str> { + self.bundle_id.as_deref() + } + + #[cfg(feature = "desktop")] + pub(in crate::review) fn registered_bundle_observed(&self) -> bool { + self.installed_bundle.is_some() + } + pub(super) fn new(area: Area, name: &OsStr, activity: Activity) -> Self { let bundle_id = name .to_str() @@ -232,6 +300,40 @@ impl Evidence { observed(a.newest_file_accessed) ) } + + pub(in crate::review) fn name_hints_text(&self, japanese: bool) -> String { + let a = &self.activity; + let hints = &a.name_hints; + let mut labels = Vec::new(); + for (count, ja, en) in [ + (hints.database, "DB形式", "database-like"), + (hints.log, "ログ形式", "log-like"), + (hints.archive, "アーカイブ形式", "archive-like"), + (hints.backup, "バックアップ形式", "backup-like"), + ] { + if count > 0 { + labels.push(if japanese { + format!("{ja}の可能性 {count}件") + } else { + format!("{count} {en}") + }); + } + } + let detail = if labels.is_empty() { + if japanese { + "該当する名前は見つかりませんでした".to_owned() + } else { + "No matching names observed".to_owned() + } + } else { + labels.join(" · ") + }; + if japanese { + format!("名前からの手がかり: {detail}。名前だけの推定で、内容・用途は未確認です。種類は重複します。{}{}", if hints.undecodable > 0 { format!("文字として判別できない名前が{}件あります。", hints.undecodable) } else { String::new() }, if a.skipped > 0 { "一部を確認できていません。" } else { "" }) + } else { + format!("Filename clues: {detail}. Names alone do not establish content or purpose; categories overlap.{}{}", if hints.undecodable > 0 { format!(" Could not decode {} filename(s).", hints.undecodable) } else { String::new() }, if a.skipped > 0 { " Some entries were not inspected." } else { "" }) + } + } } pub(super) fn match_bundles(rows: &mut [super::Row]) -> Result<()> { @@ -277,6 +379,7 @@ fn apply_matches(rows: &mut [super::Row], bundles: &BTreeMap) { mod tests { use super::*; use crate::review::app_storage::Row; + use std::os::unix::ffi::OsStringExt; use std::os::unix::fs::symlink; fn row(area: Area, directory: &str) -> Row { @@ -338,4 +441,45 @@ mod tests { assert!(measure(&root, m.dev().wrapping_add(1)).is_err()); Ok(()) } + + #[test] + fn filenames_are_only_overlapping_clues_and_partial_and_undecodable_are_shown() -> Result<()> { + let fixture = tempfile::tempdir()?; + let root = fixture.path().join("Caches"); + fs::create_dir(&root)?; + for name in [ + "local.sqlite-wal", + "app.LOG.4.gz", + "warp.log.old.3", + "bundle.tar.gz", + "copy.bak", + "notes.txt", + "invalid.log..gz", + ] { + fs::write(root.join(name), b"content is not examined")?; + } + symlink(fixture.path(), root.join("external"))?; + let (_, mut activity) = measure(&root, root.metadata()?.dev())?; + // Some macOS filesystems reject non-UTF-8 names, so exercise this + // case on the classifier without relying on filesystem support. + activity + .name_hints + .observe(&std::ffi::OsString::from_vec(vec![b'x', 0xff])); + assert_eq!(activity.name_hints.database, 1); + assert_eq!(activity.name_hints.log, 2); + assert_eq!(activity.name_hints.archive, 3); + assert_eq!(activity.name_hints.backup, 2); + assert_eq!(activity.name_hints.undecodable, 1); + assert_eq!(activity.skipped, 1); + let evidence = Evidence::new(Area::Cache, OsStr::new("example"), activity); + let ja = evidence.name_hints_text(true); + assert!(ja.contains("内容・用途は未確認")); + assert!(ja.contains("種類は重複")); + assert!(ja.contains("判別できない名前が1件")); + assert!(ja.contains("一部を確認できていません")); + assert!(evidence + .name_hints_text(false) + .contains("Could not decode 1 filename(s)")); + Ok(()) + } } diff --git a/src/review/app_storage/observations.rs b/src/review/app_storage/observations.rs index c7dc7e5..01c78fd 100644 --- a/src/review/app_storage/observations.rs +++ b/src/review/app_storage/observations.rs @@ -17,6 +17,42 @@ struct Snapshot { completed: DateTime, // Library-relative labels contain the area as well as the directory name. allocated: BTreeMap, + // Added without changing v1: older snapshots simply have no saved changes. + #[serde(default)] + growth: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(in crate::review) struct Growth { + pub label: String, + pub bytes: u64, + pub previous: DateTime, +} + +#[derive(Clone, Debug)] +pub(in crate::review) struct RecentGrowth { + pub completed: DateTime, + pub rows: Vec, +} + +#[cfg(feature = "desktop")] +pub(in crate::review) fn recent_growth() -> Result> { + let dirs = crate::storage_paths::project_dirs().context("Could not locate still data")?; + recent_growth_in(dirs.data_local_dir()) +} + +fn recent_growth_in(directory: &Path) -> Result> { + let file = match File::open(directory.join("library-observation.json")) { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + let snapshot: Snapshot = serde_json::from_reader(BufReader::new(file))?; + ensure!(snapshot.version == 1, "Unknown Library history format"); + Ok(Some(RecentGrowth { + completed: snapshot.completed, + rows: snapshot.growth, + })) } #[cfg(feature = "desktop")] @@ -40,6 +76,7 @@ fn record_in(directory: &Path, report: &mut Report) -> Result<()> { version: 1, completed: Utc::now(), allocated: BTreeMap::new(), + growth: Vec::new(), }; for row in &mut report.rows { let Some(evidence) = &mut row.library else { @@ -57,9 +94,20 @@ fn record_in(directory: &Path, report: &mut Report) -> Result<()> { .and_then(|p| p.allocated.get(&row.label).map(|size| (p.completed, size))) { evidence.previous = Some((prior, i128::from(bytes) - i128::from(*size))); + if bytes > *size { + snapshot.growth.push(Growth { + label: row.label.clone(), + bytes: bytes - *size, + previous: prior, + }); + } } snapshot.allocated.insert(row.label.clone(), bytes); } + snapshot + .growth + .sort_unstable_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.label.cmp(&b.label))); + snapshot.growth.truncate(3); fs::create_dir_all(directory)?; let mut file = tempfile::NamedTempFile::new_in(directory)?; { @@ -105,6 +153,7 @@ mod tests { let mut first = scan(64, false); record_in(dir.path(), &mut first)?; assert!(first.rows[0].library.as_ref().unwrap().previous.is_none()); + assert!(recent_growth_in(dir.path())?.unwrap().rows.is_empty()); let mut smaller = scan(16, false); record_in(dir.path(), &mut smaller)?; assert_eq!( @@ -120,6 +169,7 @@ mod tests { let mut partial = scan(2, true); record_in(dir.path(), &mut partial)?; assert!(partial.rows[0].library.as_ref().unwrap().previous.is_none()); + assert!(recent_growth_in(dir.path())?.unwrap().rows.is_empty()); let mut baseline = scan(16, false); record_in(dir.path(), &mut baseline)?; assert!(baseline.rows[0] @@ -134,6 +184,50 @@ mod tests { fresh.rows[0].library.as_ref().unwrap().previous.unwrap().1, 16 ); + let latest = recent_growth_in(dir.path())?.unwrap(); + assert_eq!(latest.rows.len(), 1); + assert_eq!(latest.rows[0].label, "Library/Caches/test.app"); + assert_eq!(latest.rows[0].bytes, 16); + assert!(latest.rows[0].previous <= latest.completed); + Ok(()) + } + + #[test] + fn older_snapshots_are_read_without_inventing_a_difference() -> Result<()> { + let dir = tempfile::tempdir()?; + std::fs::write( + dir.path().join("library-observation.json"), + r#"{"version":1,"completed":"2026-01-01T00:00:00Z","allocated":{"Library/Caches/test.app":16}}"#, + )?; + assert!(recent_growth_in(dir.path())?.unwrap().rows.is_empty()); + let mut report = scan(32, false); + record_in(dir.path(), &mut report)?; + let latest = recent_growth_in(dir.path())?.unwrap(); + assert_eq!(latest.rows.len(), 1); + assert_eq!(latest.rows[0].bytes, 16); + Ok(()) + } + + #[test] + fn saved_growth_is_limited_to_largest_comparable_rows() -> Result<()> { + let dir = tempfile::tempdir()?; + let mut initial = Report::default(); + let mut next = Report::default(); + for (index, increase) in [10, 30, 20, 40].into_iter().enumerate() { + let mut old = scan(100, false).rows.pop().unwrap(); + let mut new = scan(100 + increase, false).rows.pop().unwrap(); + old.label = format!("Library/Caches/item{index}"); + new.label = old.label.clone(); + initial.rows.push(old); + next.rows.push(new); + } + record_in(dir.path(), &mut initial)?; + record_in(dir.path(), &mut next)?; + let latest = recent_growth_in(dir.path())?.unwrap(); + assert_eq!( + latest.rows.iter().map(|row| row.bytes).collect::>(), + [40, 30, 20] + ); Ok(()) } } diff --git a/src/review/app_storage/uninstall_assertions.rs b/src/review/app_storage/uninstall_assertions.rs new file mode 100644 index 0000000..a8fd4c2 --- /dev/null +++ b/src/review/app_storage/uninstall_assertions.rs @@ -0,0 +1,319 @@ +//! User-reported checks only. These records never authorize cleanup. +use anyhow::{ensure, Context, Result}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs; +use std::io::Read; +use std::path::Path; + +const MAX_BYTES: u64 = 4 * 1024 * 1024; + +fn stamp(metadata: &fs::Metadata) -> (u64, u64, u64, i64, i64, i64, i64) { + use std::os::unix::fs::MetadataExt; + ( + metadata.dev(), + metadata.ino(), + metadata.len(), + metadata.mtime(), + metadata.mtime_nsec(), + metadata.ctime(), + metadata.ctime_nsec(), + ) +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(in crate::review) enum Scope { + #[serde(rename = "system_applications")] + System, + #[serde(rename = "user_applications")] + User, + #[serde(rename = "both_applications")] + Both, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum State { + Confirmed, + Revoked, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(in crate::review) struct Record { + state: State, + pub scope: Scope, + pub confirmed_at: DateTime, + pub updated_at: DateTime, +} + +impl Record { + pub(in crate::review) fn confirmed(&self) -> bool { + self.state == State::Confirmed + } +} + +#[derive(Default, Deserialize, Serialize)] +struct Document { + version: u8, + records: BTreeMap, +} + +#[derive(Default)] +pub(in crate::review) struct Records { + records: BTreeMap, +} + +fn path() -> Result { + Ok(crate::storage_paths::project_dirs() + .context("Could not locate still data")? + .data_local_dir() + .join("user-uninstall-confirmations.json")) +} + +fn valid_id(id: &str) -> bool { + id.len() <= 255 + && id.split('.').count() >= 2 + && id.split('.').all(|part| { + !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + }) +} + +impl Records { + pub(in crate::review) fn load() -> Result { + Self::read(&path()?) + } + fn read(path: &Path) -> Result { + use std::os::unix::fs::OpenOptionsExt; + let mut file = match fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(Self::default()) + } + Err(error) => return Err(error.into()), + }; + let before = file.metadata()?; + ensure!( + before.is_file() && before.len() <= MAX_BYTES, + "Invalid or oversized uninstall confirmation file" + ); + let mut bytes = Vec::new(); + (&mut file).take(MAX_BYTES + 1).read_to_end(&mut bytes)?; + ensure!( + bytes.len() as u64 <= MAX_BYTES, + "Oversized uninstall confirmation file" + ); + let after = file.metadata()?; + let current = fs::symlink_metadata(path)?; + ensure!( + after.is_file() + && current.is_file() + && stamp(&before) == stamp(&after) + && stamp(&after) == stamp(¤t), + "Uninstall confirmation file changed while reading" + ); + let document: Document = serde_json::from_slice(&bytes)?; + ensure!( + document.version == 1 && document.records.keys().all(|id| valid_id(id)), + "Invalid uninstall confirmation file" + ); + Ok(Self { + records: document.records, + }) + } + pub(in crate::review) fn get(&self, id: &str) -> Option<&Record> { + self.records.get(id) + } + pub(in crate::review) fn entries(&self) -> impl Iterator { + self.records + .iter() + .map(|(id, record)| (id.as_str(), record)) + } + pub(in crate::review) fn confirm(id: &str, scope: Scope) -> Result { + Self::update(&path()?, id, Some(scope)) + } + pub(in crate::review) fn revoke(id: &str) -> Result { + Self::update(&path()?, id, None) + } + fn update(file: &Path, id: &str, scope: Option) -> Result { + use std::os::unix::fs::OpenOptionsExt; + ensure!(valid_id(id), "Invalid bundle ID"); + let parent = file.parent().context("No still data directory")?; + fs::create_dir_all(parent)?; + let lock = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(parent.join("user-uninstall-confirmations.lock"))?; + ensure!(lock.metadata()?.is_file(), "Invalid confirmation lock"); + lock.try_lock() + .map_err(|error| anyhow::anyhow!("Confirmation records are busy: {error}"))?; + let mut current = Self::read(file)?; + let now = Utc::now(); + if let Some(scope) = scope { + current.records.insert( + id.into(), + Record { + state: State::Confirmed, + scope, + confirmed_at: now, + updated_at: now, + }, + ); + } else { + let record = current + .records + .get_mut(id) + .context("No user confirmation to revoke")?; + ensure!( + record.confirmed(), + "The user confirmation is already revoked" + ); + record.state = State::Revoked; + record.updated_at = now; + } + let temp = tempfile::NamedTempFile::new_in(parent)?; + serde_json::to_writer( + temp.as_file(), + &Document { + version: 1, + records: current.records.clone(), + }, + )?; + ensure!( + temp.as_file().metadata()?.len() <= MAX_BYTES, + "Uninstall confirmation file would exceed the supported size" + ); + temp.as_file().sync_all()?; + temp.persist(file)?; + Ok(current) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn existing_scope_names_remain_compatible() -> Result<()> { + for (json, scope) in [ + ("\"system_applications\"", Scope::System), + ("\"user_applications\"", Scope::User), + ("\"both_applications\"", Scope::Both), + ] { + assert_eq!(serde_json::from_str::(json)?, scope); + assert_eq!(serde_json::to_string(&scope)?, json); + } + Ok(()) + } + #[test] + fn explicit_scopes_confirm_reconfirm_and_revoke_without_other_ids_changing() -> Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("confirmations.json"); + let first = Records::update(&path, "com.example.one", Some(Scope::System))?; + assert!(first.get("com.example.one").unwrap().confirmed()); + Records::update(&path, "com.example.two", Some(Scope::User))?; + let revised = Records::update(&path, "com.example.one", Some(Scope::Both))?; + assert_eq!(revised.get("com.example.one").unwrap().scope, Scope::Both); + let revoked = Records::update(&path, "com.example.one", None)?; + assert!(!revoked.get("com.example.one").unwrap().confirmed()); + assert!(revoked.get("com.example.two").unwrap().confirmed()); + assert!(!Records::read(&path)? + .get("com.example.one") + .unwrap() + .confirmed()); + assert!(Records::update(&path, "../bad", Some(Scope::Both)).is_err()); + assert!(Records::update(&path, "com.example.missing", None).is_err()); + Ok(()) + } + + #[test] + fn busy_or_invalid_records_never_overwrite_existing_data() -> Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("confirmations.json"); + Records::update(&path, "com.example.one", Some(Scope::Both))?; + let original = fs::read(&path)?; + let lock = fs::OpenOptions::new() + .read(true) + .write(true) + .open(dir.path().join("user-uninstall-confirmations.lock"))?; + lock.try_lock()?; + assert!(Records::update(&path, "com.example.two", Some(Scope::System)).is_err()); + assert_eq!(fs::read(&path)?, original); + drop(lock); + let broken = dir.path().join("broken.json"); + fs::write(&broken, b"not-json")?; + assert!(Records::update(&broken, "com.example.two", Some(Scope::User)).is_err()); + assert_eq!(fs::read(&broken)?, b"not-json"); + Ok(()) + } + + #[test] + fn rejects_symlinks_fifos_and_oversized_input_without_waiting() -> Result<()> { + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::symlink; + let dir = tempfile::tempdir()?; + let target = dir.path().join("target"); + fs::write(&target, b"{}")?; + let link = dir.path().join("link"); + symlink(&target, &link)?; + assert!(Records::read(&link).is_err()); + let pipe = dir.path().join("pipe"); + let name = std::ffi::CString::new(pipe.as_os_str().as_bytes())?; + // SAFETY: name is a live, NUL-terminated temporary path and mode is valid. + assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); + let before = std::time::Instant::now(); + assert!(Records::read(&pipe).is_err()); + assert!(before.elapsed() < std::time::Duration::from_secs(1)); + let large = dir.path().join("large"); + fs::write(&large, vec![b' '; MAX_BYTES as usize + 1])?; + assert!(Records::read(&large).is_err()); + Ok(()) + } + + #[test] + fn update_that_crosses_size_limit_preserves_existing_records() -> Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("confirmations.json"); + let record = Record { + state: State::Confirmed, + scope: Scope::Both, + confirmed_at: Utc::now(), + updated_at: Utc::now(), + }; + let id = |n: usize| format!("com.example.{n:06}.{}", "x".repeat(220)); + let empty = Document { + version: 1, + records: BTreeMap::new(), + }; + let empty_len = serde_json::to_vec(&empty)?.len(); + let sample = Document { + version: 1, + records: BTreeMap::from([(id(0), record.clone())]), + }; + let entry_cost = serde_json::to_vec(&sample)?.len() - empty_len + 1; + let count = (MAX_BYTES as usize - empty_len + 1) / entry_cost; + let records = (0..count).map(|n| (id(n), record.clone())).collect(); + let original = serde_json::to_vec(&Document { + version: 1, + records, + })?; + assert!(original.len() <= MAX_BYTES as usize); + fs::write(&path, &original)?; + let oversized_id = format!("com.example.{}", "y".repeat(243)); + assert!(valid_id(&oversized_id)); + let error = Records::update(&path, &oversized_id, Some(Scope::System)) + .err() + .context("expected size rejection")?; + assert!(format!("{error:#}").contains("exceed")); + assert_eq!(fs::read(&path)?, original); + Ok(()) + } +} diff --git a/src/review/artifacts.rs b/src/review/artifacts.rs index b37b72c..623c884 100644 --- a/src/review/artifacts.rs +++ b/src/review/artifacts.rs @@ -117,7 +117,8 @@ impl Policy { if matches!( path.file_name().and_then(|s| s.to_str()), Some("incremental" | "deps") - ) && cargo_cache::cache_root(path).is_some_and(|target| self.permits(target)) + ) && cargo_cache::cache_root(path) + .is_some_and(|target| self.permits(target) && self.has_enclosing_cargo_project(target)) { return Some(if path.ends_with("incremental") { Producer::CargoIncremental @@ -125,7 +126,9 @@ impl Policy { Producer::CargoDependencies }); } - if cargo_cache::incremental_unit(path).is_some_and(|target| self.permits(target)) { + if cargo_cache::incremental_unit(path) + .is_some_and(|target| self.permits(target) && self.has_enclosing_cargo_project(target)) + { return Some(Producer::CargoIncremental); } let parent = path.parent()?; @@ -184,7 +187,17 @@ impl Policy { let unit = path .parent() .is_some_and(|parent| parent.ends_with("incremental")); - for parent in path.ancestors().skip(1).take(if unit { 3 } else { 2 }) { + let cache = if unit { + path.parent().expect("incremental parent") + } else { + &path + }; + let target = cargo_cache::cache_root(cache).context("Cargo cache root changed")?; + for parent in path + .ancestors() + .skip(1) + .take_while(|parent| parent.starts_with(target)) + { for marker in [".still-active", ".keep", ".gitkeep", ".git"] { match fs::symlink_metadata(parent.join(marker)) { Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} @@ -341,9 +354,6 @@ pub fn file_candidates(scan: &inventory::Inventory, policy: &Policy) -> Vec Vec = std::thread::scope(|scope| { found - .chunks(found.len().div_ceil(workers)) + .chunks(found.len().div_ceil(workers).max(1)) .map(|chunk| { let inspect = &inspect; scope.spawn(move || { @@ -399,22 +409,25 @@ pub fn file_candidates(scan: &inventory::Inventory, policy: &Policy) -> Vec = files .iter() - .filter(|c| c.blocked_reason.is_some() && c.producer == Producer::Cargo) + .filter(|c| { + c.blocked_reason.is_some() + && matches!(c.producer, Producer::Cargo | Producer::CargoRelocated) + }) .map(|c| c.row.path.clone()) .collect(); - if !held_targets.is_empty() { - for row in &scan.directories { - if !matches!( - row.path.file_name().and_then(|s| s.to_str()), - Some("incremental" | "deps") - ) || !row - .path - .ancestors() - .nth(2) - .is_some_and(|p| held_targets.contains(p)) - { - continue; - } + let identified_targets: HashSet<_> = files + .iter() + .filter(|c| matches!(c.producer, Producer::Cargo | Producer::CargoRelocated)) + .map(|c| c.row.path.clone()) + .collect(); + for row in &scan.directories { + let Some(target) = cargo_cache::cache_root(&row.path) else { + continue; + }; + // A held target or one whose markers were lost can still contain + // separately reviewable compiler caches. Do not add overlapping rows + // when the whole target is already selectable. + if held_targets.contains(target) || !identified_targets.contains(target) { if let Some(producer) = policy.producer(&row.path).filter(|p| p.is_partial_cargo()) { files.push(inspect(row, producer, None)); } @@ -706,6 +719,13 @@ pub fn verify_staged(tree: &Tree, payload: &Path) -> Result<()> { // Moving the root into staging can change its ctime. actual.changed = expected.changed; } + #[cfg(unix)] + if !actual.is_dir && !expected.is_dir { + // Finder and hard-link metadata can change ctime after staging + // without changing file contents. stamp has already checked + // the file identity and watched for changes while hashing it. + actual.changed = expected.changed; + } #[cfg(target_os = "macos")] if actual != *expected && actual.is_dir @@ -973,6 +993,30 @@ fn has_dependency(project: &Path, package: &str) -> bool { mod tests { use super::*; + #[cfg(unix)] + fn change_test_file_metadata(path: &Path) -> Result<()> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let before = fs::metadata(path)?; + let original_changed = (before.ctime(), before.ctime_nsec()); + let mode = before.permissions().mode() ^ 0o100; + // Some filesystems expose coarse timestamps; wait briefly for ctime + // to advance so the test actually covers a changed ctime. + for _ in 0..210 { + fs::set_permissions(path, fs::Permissions::from_mode(mode))?; + let after = fs::metadata(path)?; + assert_ne!( + after.permissions().mode() & 0o100, + before.permissions().mode() & 0o100 + ); + if (after.ctime(), after.ctime_nsec()) != original_changed { + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + bail!("File ctime did not advance after metadata change") + } + fn fixture() -> (tempfile::TempDir, PathBuf, Policy) { let temporary = tempfile::tempdir().unwrap(); let root = temporary.path().canonicalize().unwrap(); @@ -1002,6 +1046,56 @@ mod tests { Ok(()) } + #[cfg(unix)] + #[test] + fn staged_removal_accepts_metadata_changes_but_rejects_modified_contents() -> Result<()> { + let (_temp, output, policy) = fixture(); + let prepared = policy.prepare(&output)?; + let staged = output.with_file_name("payload"); + fs::rename(&output, &staged)?; + verify_staged(&prepared.tree, &staged)?; + change_test_file_metadata(&staged.join("build.bin"))?; + filesystem::test_remove_staged(staged.parent().unwrap(), &prepared.tree)?; + assert!(!staged.exists()); + + let (_temp, output, policy) = fixture(); + let prepared = policy.prepare(&output)?; + let staged = output.with_file_name("payload"); + fs::rename(&output, &staged)?; + verify_staged(&prepared.tree, &staged)?; + let modified = fs::metadata(staged.join("build.bin"))?.modified()?; + fs::write(staged.join("build.bin"), b"different")?; + fs::File::options() + .write(true) + .open(staged.join("build.bin"))? + .set_times(fs::FileTimes::new().set_modified(modified))?; + assert!(filesystem::test_remove_staged(staged.parent().unwrap(), &prepared.tree).is_err()); + assert_eq!(fs::read(staged.join("build.bin"))?, b"different"); + Ok(()) + } + + #[cfg(unix)] + #[test] + fn staged_verification_accepts_metadata_changes_but_rejects_modified_contents() -> Result<()> { + let (_temp, output, policy) = fixture(); + let prepared = policy.prepare(&output)?; + let staged = output.with_file_name("payload"); + fs::rename(&output, &staged)?; + let file = staged.join("build.bin"); + let modified = fs::metadata(&file)?.modified()?; + change_test_file_metadata(&file)?; + verify_staged(&prepared.tree, &staged)?; + + fs::write(&file, b"different")?; + fs::File::options() + .write(true) + .open(&file)? + .set_times(fs::FileTimes::new().set_modified(modified))?; + assert!(verify_staged(&prepared.tree, &staged).is_err()); + assert_eq!(fs::read(file)?, b"different"); + Ok(()) + } + #[test] fn mutation_after_selection_invalidates_approval() { let (_temporary, output, policy) = fixture(); @@ -1099,6 +1193,88 @@ mod tests { Ok(()) } + #[test] + fn markerless_restored_target_only_exposes_strictly_verified_cache_parts() -> Result<()> { + let tmp = tempfile::tempdir()?; + let root = tmp.path().canonicalize()?; + let target = root.join("target-aarch64"); + let profile = target.join("aarch64-apple-darwin/debug"); + let deps = profile.join("deps"); + let incremental = profile.join("incremental"); + fs::create_dir_all(&deps)?; + fs::create_dir(&incremental)?; + fs::create_dir(profile.join(".fingerprint"))?; + fs::write(profile.join(".cargo-lock"), b"")?; + fs::write(root.join("Cargo.toml"), b"[workspace]")?; + fs::write(root.join(".gitignore"), b"/target-aarch64/")?; + git::check(git::run(&root, ["init", "-q"])?, "init")?; + fs::write(deps.join("demo-0123456789abcdef.d"), b"build metadata")?; + let unit = incremental.join("demo-0123456789abc"); + let session = "s-ho9wx39w3k-0u5spzg"; + let generation = format!("{session}-0xny0l54dee30tk2bxf7bttju"); + fs::create_dir_all(unit.join(&generation))?; + fs::write(unit.join(&generation).join("dep-graph.bin"), b"generated")?; + fs::write(unit.join(format!("{session}.lock")), b"")?; + let policy = Policy { + roots: vec![root.clone()], + outputs: vec![], + docker_context: None, + }; + let scan = inventory::scan(&root, 2, None)?; + let rows = file_candidates(&scan, &policy); + assert!(!rows.iter().any(|row| row.row.path == target)); + assert!( + rows.iter() + .any(|row| row.row.path == deps && row.blocked_reason.is_none()), + "deps: {:?}", + rows.iter() + .find(|row| row.row.path == deps) + .and_then(|row| row.blocked_reason.as_ref()) + .map(ToString::to_string) + ); + assert!(rows + .iter() + .any(|row| row.row.path == incremental && row.blocked_reason.is_none())); + let approved = policy.prepare(&deps)?; + let approved_unit = policy.prepare(&unit)?; + fs::write(deps.join("personal-notes.txt"), b"preserve")?; + assert!(policy.remove(&approved).is_err()); + let scan = inventory::scan(&root, 2, None)?; + assert!(file_candidates(&scan, &policy) + .iter() + .any(|row| row.row.path == deps && row.blocked_reason.is_some())); + assert!(deps.join("personal-notes.txt").is_file()); + // A target-level keep marker applies even through the triple/profile hierarchy. + fs::write(target.join(".keep"), b"preserve")?; + assert!(policy.remove(&approved_unit).is_err()); + assert!(unit.is_dir()); + Ok(()) + } + + #[test] + fn markerless_caches_require_a_real_cargo_project_and_profile_structure() -> Result<()> { + let tmp = tempfile::tempdir()?; + let root = tmp.path().canonicalize()?; + let target = root.join("target-other"); + let profile = target.join("debug"); + let deps = profile.join("deps"); + fs::create_dir_all(&deps)?; + fs::create_dir(profile.join(".fingerprint"))?; + fs::write(profile.join(".cargo-lock"), b"")?; + let policy = Policy { + roots: vec![root.clone()], + outputs: vec![], + docker_context: None, + }; + assert!(policy.producer(&deps).is_none()); + fs::write(root.join("Cargo.toml"), b"[workspace]")?; + assert_eq!(policy.producer(&deps), Some(Producer::CargoDependencies)); + // A present but unrecognized marker must not be treated as missing. + fs::write(target.join("CACHEDIR.TAG"), b"not a Cargo marker")?; + assert!(policy.producer(&deps).is_none()); + Ok(()) + } + #[test] fn finished_units_remain_reviewable_beside_an_unfinished_build() -> Result<()> { let tmp = tempfile::tempdir()?; diff --git a/src/review/artifacts/cargo_cache.rs b/src/review/artifacts/cargo_cache.rs index d387503..00a9989 100644 --- a/src/review/artifacts/cargo_cache.rs +++ b/src/review/artifacts/cargo_cache.rs @@ -4,18 +4,27 @@ use std::fs; use std::io::Read; use std::path::{Component, Path}; -/// Only recognize direct Cargo profile caches belonging to a local manifest. +/// Recognize Cargo profile caches, including profiles nested under a target triple. +/// The policy independently verifies an enclosing Cargo project. pub(super) fn cache_root(path: &Path) -> Option<&Path> { if !matches!(path.file_name()?.to_str()?, "deps" | "incremental") || !directory(path) { return None; } let profile = path.parent()?; - let target = profile.parent()?; + let parent = profile.parent()?; + let target = if parent + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains('-') && !name.starts_with("target-")) + && parent.parent().is_some_and(target_name) + { + parent.parent()? + } else { + parent + }; if !matches!(profile.file_name()?.to_str()?, "debug" | "release") - || target.file_name()? != "target" || !directory(profile) || !directory(target) - || !regular_file(&target.parent()?.join("Cargo.toml")) || !directory(&profile.join(".fingerprint")) || !regular_file(&profile.join(".cargo-lock")) { @@ -24,7 +33,14 @@ pub(super) fn cache_root(path: &Path) -> Option<&Path> { if !regular_file(&target.join(".rustc_info.json")) { let tag = target.join("CACHEDIR.TAG"); if !regular_file(&tag) { - return None; + // A failed staged removal can already have removed both markers. + // Only strictly verified subtrees are eligible in this case; the + // enclosing target itself never gains deletion authority here. + let missing = |path: &Path| matches!(fs::symlink_metadata(path), Err(err) if err.kind() == std::io::ErrorKind::NotFound); + return (target_name(target) + && missing(&target.join(".rustc_info.json")) + && missing(&tag)) + .then_some(target); } let mut header = String::new(); fs::File::open(tag) @@ -41,6 +57,12 @@ pub(super) fn cache_root(path: &Path) -> Option<&Path> { Some(target) } +fn target_name(path: &Path) -> bool { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name == "target" || name.starts_with("target-")) +} + fn crate_name(value: &str) -> bool { !value.is_empty() && value @@ -267,7 +289,8 @@ mod tests { fs::create_dir(profile.join(".fingerprint"))?; fs::write(profile.join(".cargo-lock"), "")?; fs::write(temp.path().join("Cargo.toml"), "[workspace]")?; - assert!(cache_root(&deps).is_none()); + // The policy additionally checks that the root belongs to a Cargo project. + assert_eq!(cache_root(&deps), Some(target.as_path())); fs::write(target.join(".rustc_info.json"), "{}")?; assert_eq!(cache_root(&deps), Some(target.as_path())); assert!(cache_root(&profile).is_none()); diff --git a/src/review/cleanup_history.rs b/src/review/cleanup_history.rs index 5309855..6241016 100644 --- a/src/review/cleanup_history.rs +++ b/src/review/cleanup_history.rs @@ -16,9 +16,14 @@ pub(super) struct Item { pub path: PathBuf, pub producer: String, pub logical_bytes: u64, + /// Allocated size from the earlier workspace scan, not a deletion-time measurement. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scanned_allocated_bytes: Option, pub status: String, pub reason: Option, pub original_path_exists: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub original_path_checked_at: Option>, } #[derive(Debug, Serialize, Deserialize)] @@ -29,7 +34,55 @@ pub(super) struct Record { pub completed_at: DateTime, pub available_before: Option, pub available_after: Option, + /// Workspace keep rules observed at the start; absent means not observed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kept_paths_at_start: Option>, pub items: Vec, + /// Non-filesystem operations use their own typed targets rather than fake paths. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operation: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +pub(super) struct Operation { + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retention_days: Option, + pub targets: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +pub(super) struct OperationTarget { + pub identifier: String, + pub status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remaining_image_bytes: Option, +} + +#[cfg(all(not(test), feature = "desktop", target_os = "macos"))] +pub(super) fn save_operation( + started_at: DateTime, + before: Option, + after: Option, + operation: Operation, +) -> Result<()> { + let home = directories::BaseDirs::new() + .context("Could not locate home volume")? + .home_dir() + .to_owned(); + save(&Record { + version: 1, + root: home, + started_at, + completed_at: Utc::now(), + available_before: before, + available_after: after, + kept_paths_at_start: None, + items: Vec::new(), + operation: Some(operation), + }) } fn directory() -> Result { @@ -117,11 +170,13 @@ fn last_measurement_in(directory: &Path, root: &Path) -> Result, available_after: Option, + #[serde(default)] + operation: Option, } for path in newest_paths(directory)? { let measurement: Measurement = serde_json::from_reader(BufReader::new(fs::File::open(path)?))?; - if measurement.root == root { + if measurement.root == root && measurement.operation.is_none() { anyhow::ensure!( measurement.version == 1, "Unsupported cleanup history version" @@ -148,6 +203,12 @@ pub fn run(args: &CleanupHistoryArgs) -> Result<()> { " Free bytes: {:?} → {:?} (whole-volume observation)", record.available_before, record.available_after ); + if let Some(paths) = &record.kept_paths_at_start { + println!(" Keep rules at start: {}", paths.len()); + for path in paths { + println!(" {}", path.display()); + } + } for item in record.items { println!( " {} · {} · {} logical bytes · {}", @@ -160,6 +221,30 @@ pub fn run(args: &CleanupHistoryArgs) -> Result<()> { println!(" {reason}"); } println!(" Original path exists: {:?}", item.original_path_exists); + if item.original_path_exists == Some(true) && item.status == "removed" { + println!(" The path may have been recreated after removal."); + } + if let Some(bytes) = item.scanned_allocated_bytes { + println!(" Allocated bytes from earlier scan: {bytes}"); + } + if let Some(time) = item.original_path_checked_at { + println!(" Original path checked at: {time}"); + } + } + if let Some(operation) = record.operation { + println!(" Operation: {}", operation.kind); + if let Some(days) = operation.retention_days { + println!(" Retention: {days} days"); + } + for target in operation.targets { + println!(" {} · {}", target.status, target.identifier); + if let Some(reason) = target.reason { + println!(" {reason}"); + } + if let Some(bytes) = target.remaining_image_bytes { + println!(" Remaining image bytes: {bytes}"); + } + } } } } @@ -180,14 +265,18 @@ mod tests { completed_at: Utc::now(), available_before: Some(10), available_after: Some(20), + kept_paths_at_start: Some(vec!["/tmp/project/keep".into()]), items: vec![Item { path: "/tmp/project/target".into(), producer: "Cargo".into(), logical_bytes: 42, + scanned_allocated_bytes: Some(32), status: "incomplete".into(), reason: Some("could not verify".into()), original_path_exists: None, + original_path_checked_at: Some(Utc::now()), }], + operation: None, }; save_in(dir.path(), &record)?; assert_eq!( @@ -202,7 +291,61 @@ mod tests { Some("could not verify") ); assert_eq!(records[0].items[0].original_path_exists, None); + assert_eq!(records[0].items[0].scanned_allocated_bytes, Some(32)); assert_eq!(load_from(dir.path(), 0)?.len(), 0); Ok(()) } + + #[test] + fn reads_history_written_before_optional_observation_fields() -> Result<()> { + let record: Record = serde_json::from_str( + r#"{ + "version":1,"root":"/tmp/project", + "started_at":"2026-01-01T00:00:00Z", + "completed_at":"2026-01-01T00:01:00Z", + "available_before":1,"available_after":2, + "items":[{"path":"/tmp/project/target","producer":"Cargo", + "logical_bytes":42,"status":"removed","reason":null, + "original_path_exists":false}] + }"#, + )?; + assert_eq!(record.items[0].scanned_allocated_bytes, None); + assert_eq!(record.items[0].original_path_checked_at, None); + assert!(record.kept_paths_at_start.is_none()); + assert!(record.operation.is_none()); + Ok(()) + } + + #[test] + fn operation_history_round_trips_without_confusing_workspace_measurements() -> Result<()> { + let dir = tempfile::tempdir()?; + let home = PathBuf::from("/tmp/fixture-home"); + let record = Record { + version: 1, + root: home.clone(), + started_at: Utc::now(), + completed_at: Utc::now(), + available_before: Some(10), + available_after: Some(20), + kept_paths_at_start: None, + items: Vec::new(), + operation: Some(Operation { + kind: "sdk_uninstall".into(), + retention_days: None, + targets: vec![OperationTarget { + identifier: "runtime".into(), + status: "partial".into(), + reason: Some("Runtime image remains".into()), + remaining_image_bytes: Some(100), + }], + }), + }; + save_in(dir.path(), &record)?; + let loaded = load_from(dir.path(), 1)?; + let target = &loaded[0].operation.as_ref().unwrap().targets[0]; + assert_eq!(target.status, "partial"); + assert_eq!(target.remaining_image_bytes, Some(100)); + assert!(last_measurement_in(dir.path(), &home)?.is_none()); + Ok(()) + } } diff --git a/src/review/desktop/history_ui.rs b/src/review/desktop/history_ui.rs new file mode 100644 index 0000000..b991148 --- /dev/null +++ b/src/review/desktop/history_ui.rs @@ -0,0 +1,81 @@ +use super::{display, egui, text, App, Outcome}; +use crate::review::history::{self, HistoryPoint}; +use anyhow::Result; +use std::path::PathBuf; + +const DISPLAY_LIMIT: usize = 100; + +#[derive(Default)] +pub(super) struct Panel { + pub(super) review: Option)>>, +} + +impl App { + pub(super) fn history_menu(&mut self, ui: &mut egui::Ui) { + let Some(scan) = &self.scan else { return }; + let root = scan.root.clone(); + let profile = self.profile_name.clone(); + if ui + .add_enabled( + self.job.is_none(), + egui::Button::new(text( + self.japanese_reasons, + "この場所の容量履歴…", + "This workspace's size history…", + )), + ) + .clicked() + { + ui.close(); + self.spawn( + ui.ctx(), + text( + self.japanese_reasons, + "履歴を読み込み中…", + "Loading scan history…", + ), + false, + move || { + Outcome::HistoryLoad( + history::load_timeline(&root, profile.as_deref(), DISPLAY_LIMIT) + .map(|entries| (root, entries)), + ) + }, + ); + } + } + + pub(super) fn history_dialog(&mut self, ctx: &egui::Context) { + let ja = self.japanese_reasons; + let Some(review) = &self.timeline.review else { + return; + }; + let mut close = false; + let modal = egui::Modal::new("workspace-history".into()).show(ctx, |ui| { + ui.heading(text(ja, "この場所の容量履歴", "Workspace size history")); + match review { + Ok((root, points)) => { + ui.label(display(root)); + if points.is_empty() { + ui.label(text(ja, "まだ履歴がありません。この機能の追加前の観測は含まれません。", "No history recorded yet. Observations from before this feature are not included.")); + } else { + ui.small(text(ja, "新しい順に最大100回の調査を表示します。読み取れなかった項目などを含む場合は一部未走査と表示します。", "Up to 100 scans, newest first. Partial means some entries could not be inspected or were skipped.")); + egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { + for point in points { + ui.separator(); + ui.strong(point.completed_at.with_timezone(&chrono::Local).format("%Y/%m/%d %H:%M:%S").to_string()); + ui.label(format!("{} {} · {} {}", text(ja, "論理容量", "Logical"), super::bytes(point.logical_bytes), text(ja, "割当容量", "Allocated"), point.allocated_bytes.map(super::bytes).unwrap_or_else(|| text(ja, "不明", "Unavailable").into()))); + if point.partial { ui.small(text(ja, "一部未走査", "Partial observation")); } + } + }); + } + } + Err(err) => { ui.label(text(ja, "履歴を読み込めませんでした。", "Could not load scan history.")); ui.label(format!("{err:#}")); } + } + close = ui.button(text(ja, "閉じる", "Close")).clicked(); + }); + if close || modal.should_close() { + self.timeline.review = None; + } + } +} diff --git a/src/review/desktop/home.rs b/src/review/desktop/home.rs index 77589fa..b687b7c 100644 --- a/src/review/desktop/home.rs +++ b/src/review/desktop/home.rs @@ -28,6 +28,10 @@ pub(super) struct Home { pub(super) requested_project: Option, capacity: Option<(u64, u64)>, pub(super) last_measurement: Option<(u64, u64)>, + library_growth: Option, + library_history_unavailable: bool, + docker_growth: Option, + docker_history_unavailable: bool, } fn recent_path() -> Result { @@ -45,6 +49,10 @@ impl Default for Home { .and_then(|path| serde_json::from_reader(fs::File::open(path).ok()?).ok()), capacity: None, last_measurement: None, + library_growth: None, + library_history_unavailable: false, + docker_growth: None, + docker_history_unavailable: false, }; if let Some(last) = &home.recent { home.last_measurement = super::super::cleanup_history::last_measurement(&last.root) @@ -52,11 +60,39 @@ impl Default for Home { .flatten(); } home.update_capacity(); + home.reload_library_growth(); + home.reload_docker_growth(); home } } impl Home { + pub(super) fn reload_docker_growth(&mut self) { + match super::super::docker::storage::observations::latest() { + Ok(value) => { + self.docker_growth = value; + self.docker_history_unavailable = false; + } + Err(_) => { + self.docker_growth = None; + self.docker_history_unavailable = true; + } + } + } + + pub(super) fn reload_library_growth(&mut self) { + match super::super::app_storage::observations::recent_growth() { + Ok(value) => { + self.library_growth = value; + self.library_history_unavailable = false; + } + Err(_) => { + self.library_growth = None; + self.library_history_unavailable = true; + } + } + } + pub(super) fn update_capacity(&mut self) { self.capacity = self.directory.as_ref().and_then(|dir| { let stat = rustix::fs::statvfs(dir).ok()?; @@ -98,6 +134,13 @@ impl Home { impl App { pub(super) fn show_home(&mut self, ui: &mut egui::Ui) { + let pending = self.monitor.observation_pending(); + if pending { + self.monitor.poll(ui.ctx()); + if !self.monitor.observation_pending() { + self.home.reload_docker_growth(); + } + } egui::ScrollArea::vertical().show(ui, |ui| { ui.set_max_width(820.0); ui.add_space(10.0); @@ -332,7 +375,17 @@ impl App { if ui .add_enabled( self.job.is_none(), - egui::Link::new(format!("{name} {} ›", item.label)), + egui::Link::new(format!( + "{name} {} ›", + if self.japanese_reasons { + item.label.strip_prefix("new ").map_or_else( + || item.label.clone(), + |size| format!("新規 {size}"), + ) + } else { + item.label.clone() + } + )), ) .on_hover_text(display(&item.path)) .clicked() @@ -341,6 +394,146 @@ impl App { } } } + ui.add_space(22.); + ui.strong(text( + self.japanese_reasons, + "アプリと Docker の確認", + "App storage and Docker", + )); + if let Some(library) = &self.home.library_growth { + ui.small(if self.japanese_reasons { + format!( + "Library の前回の調査: {}(割当容量)", + library + .completed + .with_timezone(&Local) + .format("%Y/%m/%d %H:%M") + ) + } else { + format!( + "Last Library scan: {} (allocated size)", + library + .completed + .with_timezone(&Local) + .format("%Y/%m/%d %H:%M") + ) + }); + if library.rows.is_empty() { + ui.small(text(self.japanese_reasons, "比較できる増加はありません。初回・部分調査では差分を表示できません。", "No comparable increases. A first or partial scan may not produce a comparison.")); + } else { + ui.small(text(self.japanese_reasons, "前回の調査で増えた場所。詳細は「アプリの容量」を開き、必要に応じて再調査してください。", "Increases at the last scan. Open app storage and scan again if needed to inspect details.")); + } + for row in &library.rows { + let previous = row.previous.with_timezone(&Local).format("%Y/%m/%d %H:%M"); + let label = if self.japanese_reasons { + format!("{} +{} ({previous} 比)", row.label, bytes(row.bytes)) + } else { + format!("{} +{} since {previous}", row.label, bytes(row.bytes)) + }; + ui.label(label); + } + } else if self.home.library_history_unavailable { + ui.small(text( + self.japanese_reasons, + "Library の前回の観測を読み込めませんでした。", + "The previous Library observation could not be read.", + )); + } else { + ui.small(text(self.japanese_reasons, "Library はまだ観測していません。明示して調査すると、比較可能な次回から増加を表示します。", "Library has not been inventoried. Comparable increases appear after a later explicit scan.")); + } + ui.horizontal(|ui| { + if super::controls::button( + ui, + text( + self.japanese_reasons, + "アプリの容量を開く", + "Open app storage", + ), + false, + self.job.is_none(), + ) + .clicked() + { + self.app_storage_selected = true; + self.navigate(super::shell::Screen::Apps); + } + if super::controls::button( + ui, + text(self.japanese_reasons, "Docker を開く", "Open Docker"), + false, + self.job.is_none(), + ) + .clicked() + { + self.navigate(super::shell::Screen::Docker); + } + }); + if self.monitor.observation_pending() { + ui.small(text( + self.japanese_reasons, + "Docker の前回比較を記録中…", + "Recording Docker comparison…", + )); + } + if self.monitor.observation_failed() { + ui.small(text(self.japanese_reasons, "Docker比較の一部を記録できませんでした。以下は以前の観測の場合があります。", "Some Docker comparisons could not be recorded. The observation below may be older.")); + } + if let Some(docker) = &self.home.docker_growth { + ui.small(format!( + "Docker {} · {}", + docker.context, + docker + .measured + .with_timezone(&Local) + .format("%Y/%m/%d %H:%M") + )); + if let Some(prior) = docker.prior { + ui.small(if self.japanese_reasons { + format!( + "{} 比(Docker表示の概算差)", + prior.with_timezone(&Local).format("%Y/%m/%d %H:%M") + ) + } else { + format!( + "Approximate change since {}", + prior.with_timezone(&Local).format("%Y/%m/%d %H:%M") + ) + }); + for (category, difference) in &docker.changes { + let label = match category.as_str() { + "Images" => text(self.japanese_reasons, "イメージ", "Images"), + "Containers" => text(self.japanese_reasons, "コンテナ", "Containers"), + "Local Volumes" => { + text(self.japanese_reasons, "ローカルボリューム", "Local volumes") + } + "Build Cache" => { + text(self.japanese_reasons, "ビルドキャッシュ", "Build cache") + } + _ => continue, + }; + let sign = if *difference < 0 { "−" } else { "+" }; + ui.label(format!( + "{label} {sign}{}", + bytes(difference.unsigned_abs() as u64) + )); + } + ui.small(text(self.japanese_reasons, "種類ごとの値には重複や丸め誤差があり、SSDの回収量ではありません。", "Category values can overlap and are rounded; these are not SSD space reclaimed.")); + } else { + ui.small(text( + self.japanese_reasons, + "比較できる以前のDocker観測はありません。", + "No comparable earlier Docker observation.", + )); + } + } else if self.home.docker_history_unavailable { + ui.small(text( + self.japanese_reasons, + "Dockerの観測履歴を読み込めませんでした。", + "Could not read Docker observation history.", + )); + } else { + ui.small(text(self.japanese_reasons, "Dockerの容量を調査すると、比較可能な次回から種類ごとの増減を表示します。", "After an explicit Docker scan, comparable changes appear by category on a later scan.")); + } if let Some(project) = requested { if self.scan.as_ref().is_some_and(|s| s.root == path) && self.projects.open_project(project.clone()) diff --git a/src/review/desktop/keep.rs b/src/review/desktop/keep.rs index 40130bb..1513fa9 100644 --- a/src/review/desktop/keep.rs +++ b/src/review/desktop/keep.rs @@ -60,6 +60,15 @@ impl KeepRules { .map(PathBuf::as_path) } + /// Snapshot only the rules that can protect this workspace or its contents. + pub(super) fn relevant_to(&self, root: &Path) -> Vec { + self.paths + .iter() + .filter(|path| path.starts_with(root) || root.starts_with(path)) + .cloned() + .collect() + } + pub(super) fn reason(&self, path: &Path) -> Option { let kept = display(self.conflict(path)?); Some(Message::new( @@ -115,6 +124,11 @@ mod tests { let kept = output.join("debug/incremental"); KeepRules::update_in(&file, &kept, true)?; let rules = KeepRules::read(&file)?; + assert_eq!( + rules.relevant_to(Path::new("/workspace/demo")), + vec![kept.clone()] + ); + assert!(rules.relevant_to(Path::new("/workspace/other")).is_empty()); for path in [output, kept.as_path(), &kept.join("part")] { assert_eq!(rules.conflict(path), Some(kept.as_path())); } diff --git a/src/review/desktop/library_ui.rs b/src/review/desktop/library_ui.rs index c52a2dc..e19fbac 100644 --- a/src/review/desktop/library_ui.rs +++ b/src/review/desktop/library_ui.rs @@ -10,6 +10,8 @@ impl App { let mut review_sdk = false; #[cfg(target_os = "macos")] let mut cache_action = None; + #[cfg(target_os = "macos")] + let mut group_check = None; let render = |ui: &mut egui::Ui| { if !as_page { ui.set_width((ctx.content_rect().width() - 80.0).clamp(590.0, 920.0)); @@ -29,6 +31,12 @@ impl App { "所有元と再生成方法を確認できたキャッシュは、内容を確認してから整理できます。", "Review an eligible cache separately before removing it.", )); + #[cfg(target_os = "macos")] + { + group_check = self.library_panel.group_ui(ui, busy, self.japanese_reasons); + self.library_panel + .assertion_overview(ui, busy, self.japanese_reasons); + } ui.add_enabled_ui(!busy, |ui| { ui.checkbox( &mut self.xcode_runtimes, @@ -93,35 +101,56 @@ impl App { size_basis(row.size_basis, self.japanese_reasons) ); #[cfg(target_os = "macos")] - let title = format!( - "{title}{}", - self.library_panel.marker(row, index, self.japanese_reasons) - ); + let access = self.library_panel.access(row, index); + #[cfg(target_os = "macos")] + let title = + format!("{title}{}", access.label(self.japanese_reasons)); let header = egui::CollapsingHeader::new(title).id_salt(( row.path.as_deref(), &row.label, index, )); - header.show(ui, |ui| { - if let Some(path) = &row.path { - ui.label(path); - } - ui.label(row.reason.text(self.japanese_reasons)); + ui.horizontal(|ui| { #[cfg(target_os = "macos")] - { - if let Some(evidence) = &row.library { - ui.small(evidence.activity_text(self.japanese_reasons)); + if access.is_locked() { + let (rect, _) = ui.allocate_exact_size( + egui::vec2(14.0, 14.0), + egui::Sense::hover(), + ); + icons::paint(ui, rect, icons::Icon::Lock, MUTED); + } + header.show(ui, |ui| { + if let Some(path) = &row.path { + ui.label(path); } - if let Some(action) = self.library_panel.row( - ui, - row, - index, - busy, - self.japanese_reasons, - ) { - cache_action = Some(action); + ui.label(row.reason.text(self.japanese_reasons)); + #[cfg(target_os = "macos")] + { + if let Some(evidence) = &row.library { + ui.small( + evidence.activity_text(self.japanese_reasons), + ); + ui.small( + evidence.name_hints_text(self.japanese_reasons), + ); + self.library_panel.uninstall_row( + ui, + evidence, + busy, + self.japanese_reasons, + ); + } + if let Some(action) = self.library_panel.row( + ui, + row, + index, + busy, + self.japanese_reasons, + ) { + cache_action = Some(action); + } } - } + }); }); ui.separator(); } @@ -171,6 +200,23 @@ impl App { if let Some(action) = cache_action { self.cache_action(ctx, action); } + #[cfg(target_os = "macos")] + self.library_panel + .uninstall_modal(ctx, self.japanese_reasons); + #[cfg(target_os = "macos")] + if let Some((app, group)) = group_check { + self.library_panel.group_result = None; + self.spawn( + ctx, + text( + self.japanese_reasons, + "アプリの署名と宣言を確認中…", + "Checking the app signature and declaration…", + ), + false, + move || Outcome::GroupLink(app_storage::group_link::inspect(&app, &group)), + ); + } if start { self.app_storage = None; #[cfg(target_os = "macos")] @@ -199,7 +245,13 @@ pub(super) use mac::{Panel, SavedReceipt}; #[cfg(target_os = "macos")] mod mac { use super::*; - use crate::review::{app_storage::known_cache, cleanup_history}; + use crate::review::{ + app_storage::{ + known_cache, + uninstall_assertions::{Records, Scope}, + }, + cleanup_history, + }; use keep::KeepRules; #[derive(Default)] @@ -209,6 +261,33 @@ mod mac { settings_error: Option, pub(in crate::review::desktop) review: Option>, pub(in crate::review::desktop) receipt: Option>, + group_app: Option, + group_id: String, + pub(in crate::review::desktop) group_result: + Option>, + assertions: Option>, + observed_registered_ids: std::collections::BTreeSet, + assertion_draft: Option, + assertion_error: Option, + } + + struct AssertionDraft { + id: String, + registered: bool, + scope: Option, + acknowledged: bool, + } + + fn scope_text(scope: Scope, ja: bool) -> &'static str { + match scope { + Scope::System => text(ja, "/Applications のみ", "/Applications only"), + Scope::User => text(ja, "~/Applications のみ", "~/Applications only"), + Scope::Both => text( + ja, + "/Applications と ~/Applications", + "/Applications and ~/Applications", + ), + } } pub(in crate::review::desktop) struct SavedReceipt { @@ -221,9 +300,138 @@ mod mac { Review(PathBuf), } + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(super) enum Access { + Reviewable, + Kept, + Unavailable, + ReadOnly, + } + + impl Access { + pub(super) fn is_locked(self) -> bool { + self != Self::Reviewable + } + pub(super) fn label(self, ja: bool) -> &'static str { + match self { + Self::Reviewable => text(ja, " · HTTP キャッシュを確認", " · Review HTTP cache"), + Self::Kept => text(ja, " · 残す設定", " · Kept"), + Self::Unavailable => text(ja, " · 確認保留", " · Review unavailable"), + Self::ReadOnly => { + text(ja, " · この画面では閲覧のみ", " · View only on this screen") + } + } + } + } + impl Panel { + fn overview_draft(&self, id: String) -> AssertionDraft { + AssertionDraft { + registered: self.observed_registered_ids.contains(&id), + id, + scope: None, + acknowledged: false, + } + } + + pub(super) fn assertion_overview(&mut self, ui: &mut egui::Ui, busy: bool, ja: bool) { + if self.assertions.is_none() { + self.assertions = Some(Records::load()); + } + let mut revoke: Option = None; + let mut update: Option = None; + let mut reload = false; + ui.collapsing(text(ja, "自分のアンインストール確認記録", "Your uninstall confirmation records"), |ui| { + ui.small(text(ja, "本人の申告です。OSの検出とは別で、削除可否には使いません。", "Your statements are separate from OS detection and never control deletion.")); + match &self.assertions { + Some(Ok(records)) => { + if records.entries().next().is_none() { ui.small(text(ja, "記録はありません。", "No records.")); } + for (id, record) in records.entries() { + let date = record.updated_at.with_timezone(&chrono::Local).format("%Y/%m/%d %H:%M"); + ui.label(format!("{id} · {} · {} · {date}", scope_text(record.scope, ja), if record.confirmed() { text(ja, "本人確認済み", "Confirmed by you") } else { text(ja, "撤回済み", "Revoked") })); + ui.horizontal(|ui| { + if ui.add_enabled(!busy, egui::Button::new(text(ja, "再確認…", "Confirm again…"))).clicked() { update = Some(id.to_owned()); } + if record.confirmed() && ui.add_enabled(!busy, egui::Button::new(text(ja, "撤回", "Revoke"))).clicked() { revoke = Some(id.to_owned()); } + }); + } + } + Some(Err(error)) => { ui.label(format!("{} · {error:#}", text(ja, "確認記録を読み込めません", "Could not read confirmations"))); } + None => {} + } + reload = ui.add_enabled(!busy, egui::Button::new(text(ja, "記録を再読み込み", "Reload records"))).clicked(); + if let Some(error) = &self.assertion_error { ui.label(format!("{} · {error}", text(ja, "記録を更新できません", "Could not update confirmation"))); } + }); + if reload { + self.assertions = Some(Records::load()); + } + if let Some(id) = revoke { + match Records::revoke(&id) { + Ok(records) => { + self.assertions = Some(Ok(records)); + self.assertion_error = None; + } + Err(error) => self.assertion_error = Some(format!("{error:#}")), + } + } + if let Some(id) = update { + self.assertion_draft = Some(self.overview_draft(id)); + self.assertion_error = None; + } + } + + pub(super) fn group_ui( + &mut self, + ui: &mut egui::Ui, + busy: bool, + ja: bool, + ) -> Option<(PathBuf, String)> { + let mut check = false; + ui.collapsing(text(ja, "選んだアプリの App Group 宣言を照合…", "Check an app's App Group declaration…"), |ui| { + ui.label(text(ja, "アプリ1つの署名付き宣言と指定したIDを完全一致で照合します。", "Compare one selected app's signed declaration with an exact group ID.")); + ui.small(text(ja, "署名の整合性は発行元の真正性を証明しません。他の利用元や使用中かどうかも分かりません。同時変更をすべて検出できる保証はありません。", "Signature integrity does not prove publisher identity, other group members, or whether the group is in use. Concurrent changes may not always be detected.")); + ui.add_enabled_ui(!busy, |ui| { + if ui.button(text(ja, "アプリを選ぶ…", "Choose app…")).clicked() { + if let Some(path) = rfd::FileDialog::new().add_filter("Application", &["app"]).pick_file() { + self.group_app = Some(path); + self.group_result = None; + } + } + if let Some(path) = &self.group_app { ui.small(display(path)); } + ui.horizontal(|ui| { + ui.label(text(ja, "App Group ID", "App Group ID")); + if ui.text_edit_singleline(&mut self.group_id).changed() { self.group_result = None; } + }); + check = ui.add_enabled(self.group_app.is_some() && !self.group_id.is_empty(), egui::Button::new(text(ja, "宣言を照合", "Check declaration"))).clicked(); + }); + if let Some(result) = &self.group_result { + use app_storage::group_link::Declaration; + match result { + Ok(Declaration::Match) => { ui.label(text(ja, "このアプリの署名付き宣言に、指定IDの完全一致があります。", "The app's signed declaration contains the exact ID.")); } + Ok(Declaration::NoMatch) => { ui.label(text(ja, "このアプリの署名付き宣言に、指定IDはありません。", "The app's signed declaration does not contain the ID.")); } + Ok(Declaration::NoGroups) => { ui.label(text(ja, "このアプリの署名に App Groups の宣言はありません。", "The app signature has no App Groups declaration.")); } + Err(error) => { ui.label(text(ja, "宣言を確認できませんでした。", "The declaration could not be verified.")); ui.small(format!("{error:#}")); } + } + } + }); + check.then(|| (self.group_app.clone().unwrap(), self.group_id.clone())) + } + pub(in crate::review::desktop) fn scanned(&mut self, result: &Result) { self.load_kept(); + self.assertions = Some(Records::load()); + self.observed_registered_ids = result + .as_ref() + .ok() + .into_iter() + .flat_map(|report| report.rows.iter()) + .filter_map(|row| { + let evidence = row.library.as_ref()?; + evidence + .registered_bundle_observed() + .then(|| evidence.bundle_id().map(str::to_owned)) + .flatten() + }) + .collect(); self.cache_row = result.as_ref().ok().and_then(|report| { report.rows.iter().enumerate().find_map(|(index, row)| { @@ -232,6 +440,157 @@ mod mac { }); } + pub(super) fn uninstall_row( + &mut self, + ui: &mut egui::Ui, + evidence: &app_storage::library::Evidence, + busy: bool, + ja: bool, + ) { + let Some(id) = evidence.bundle_id() else { + return; + }; + ui.add_space(6.); + ui.label(text( + ja, + "アンインストールについての自分の確認", + "Your uninstall confirmation", + )); + let mut revoke = false; + match &self.assertions { + Some(Ok(records)) => match records.get(id) { + Some(record) => { + let timestamp = record + .updated_at + .with_timezone(&chrono::Local) + .format("%Y/%m/%d %H:%M"); + let scope = scope_text(record.scope, ja); + ui.small(if ja { + format!( + "{} · {scope} · {timestamp}", + if record.confirmed() { + "本人が確認済みとして記録" + } else { + "本人が確認記録を撤回" + } + ) + } else { + format!( + "{} · {scope} · {timestamp}", + if record.confirmed() { + "Confirmed by you" + } else { + "Confirmation revoked by you" + } + ) + }); + if record.confirmed() { + revoke = ui + .add_enabled( + !busy, + egui::Button::new(text( + ja, + "この確認を撤回", + "Revoke confirmation", + )), + ) + .clicked(); + } + } + None => { + ui.small(text( + ja, + "本人の確認記録はありません。", + "No confirmation from you is recorded.", + )); + } + }, + Some(Err(error)) => { + ui.small(format!( + "{} · {error:#}", + text( + ja, + "確認記録を読み込めません", + "Could not read confirmations" + ) + )); + return; + } + None => return, + } + if revoke { + match Records::revoke(id) { + Ok(records) => { + self.assertions = Some(Ok(records)); + self.assertion_error = None; + } + Err(error) => self.assertion_error = Some(format!("{error:#}")), + } + } + if ui + .add_enabled( + !busy, + egui::Button::new(text( + ja, + "自分の確認を記録・更新…", + "Record or update your confirmation…", + )), + ) + .clicked() + { + self.assertion_draft = Some(AssertionDraft { + id: id.into(), + registered: evidence.registered_bundle_observed(), + scope: None, + acknowledged: false, + }); + self.assertion_error = None; + } + if let Some(error) = &self.assertion_error { + ui.small(format!( + "{} · {error}", + text(ja, "記録を更新できません", "Could not update confirmation") + )); + } + } + + pub(super) fn uninstall_modal(&mut self, ctx: &egui::Context, ja: bool) { + let Some(draft) = &mut self.assertion_draft else { + return; + }; + let mut save = false; + let mut close = false; + let modal = egui::Modal::new("uninstall-user-confirmation".into()).show(ctx, |ui| { + ui.heading(text(ja, "自分の確認を記録", "Record your confirmation")); + ui.label(format!("Bundle ID: {}", draft.id)); + ui.label(text(ja, "フォルダ名から推定したIDです。対象のアプリとIDを自分で確かめてください。", "This ID comes from the folder name. Verify the app and ID yourself.")); + ui.small(text(ja, "この確認記録からOS登録の有無は分かりません。", "This confirmation does not establish OS registration status.")); + if draft.registered { ui.label(text(ja, "注意: 今回の調査では、このIDの登録済みアプリも観測しています。", "Note: this scan also observed a registered app with this ID.")); } + ui.label(text(ja, "確認した場所を選んでください。ほかの場所は確認範囲に含みません。", "Choose the locations you checked; other locations are outside this record.")); + for scope in [Scope::System, Scope::User, Scope::Both] { + ui.radio_value(&mut draft.scope, Some(scope), scope_text(scope, ja)); + } + ui.checkbox(&mut draft.acknowledged, text(ja, "このIDのアプリを自分でアンインストールし、選んだ場所を確認しました。", "I uninstalled the app with this ID and checked the selected locations.")); + ui.small(text(ja, "本人の申告として日時と範囲を保存します。OSやstillによる証明ではなく、削除可否や自動選択には使いません。", "This records your statement with its time and scope. It is not proof by the OS or still and never controls deletion or automatic selection.")); + ui.horizontal(|ui| { + close = ui.button(text(ja, "キャンセル", "Cancel")).clicked(); + save = ui.add_enabled(draft.scope.is_some() && draft.acknowledged, egui::Button::new(text(ja, "確認を記録", "Record confirmation"))).clicked(); + }); + }); + if save { + let draft = self.assertion_draft.take().expect("open confirmation"); + match Records::confirm(&draft.id, draft.scope.expect("scope selected")) { + Ok(records) => { + self.assertions = Some(Ok(records)); + self.assertion_error = None; + } + Err(error) => self.assertion_error = Some(format!("{error:#}")), + } + } else if close || modal.should_close() { + self.assertion_draft = None; + } + } + fn target(&self, index: usize) -> Option<&Path> { self.cache_row .as_ref() @@ -239,16 +598,8 @@ mod mac { .map(|(_, path)| path.as_path()) } - pub(super) fn marker( - &self, - row: &app_storage::Row, - index: usize, - ja: bool, - ) -> &'static str { + pub(super) fn access(&self, row: &app_storage::Row, index: usize) -> Access { let candidate = self.target(index); - if candidate.is_none() && row.library.is_none() { - return ""; - } let path = candidate.or(row.native_path.as_deref()); if path.is_some_and(|path| { self.kept @@ -256,11 +607,15 @@ mod mac { .and_then(|r| r.as_ref().ok()) .is_some_and(|rules| rules.conflict(path).is_some()) }) { - text(ja, " · 残す設定", " · Kept") + Access::Kept } else if candidate.is_some() { - text(ja, " · HTTP キャッシュを確認", " · Review HTTP cache") + if matches!(self.kept, Some(Ok(_))) { + Access::Reviewable + } else { + Access::Unavailable + } } else { - "" + Access::ReadOnly } } @@ -503,6 +858,43 @@ mod mac { } } } + + #[cfg(test)] + mod confirmation_tests { + use super::{Access, Panel}; + use crate::review::{app_storage::Row, desktop::keep::KeepRules, message::Message}; + + #[test] + fn access_marks_only_available_cache_as_reviewable() { + let row = Row { + label: "Chrome".into(), + path: None, + native_path: None, + size_bytes: Some(10), + size_basis: "allocated", + partial: false, + reason: Message::new("example", "例"), + library: None, + }; + let mut panel = Panel::default(); + assert_eq!(panel.access(&row, 0), Access::ReadOnly); + panel.cache_row = Some((0, "/tmp/example".into())); + assert_eq!(panel.access(&row, 0), Access::Unavailable); + panel.kept = Some(Ok(KeepRules::default())); + assert_eq!(panel.access(&row, 0), Access::Reviewable); + assert!(!panel.access(&row, 0).is_locked()); + assert!(panel.access(&row, 1).is_locked()); + } + #[test] + fn overview_reconfirmation_warns_for_observed_registered_id() { + let mut panel = Panel::default(); + panel + .observed_registered_ids + .insert("com.example.app".into()); + assert!(panel.overview_draft("com.example.app".into()).registered); + assert!(!panel.overview_draft("com.example.other".into()).registered); + } + } } #[cfg(all(test, target_os = "macos"))] diff --git a/src/review/desktop/mod.rs b/src/review/desktop/mod.rs index 5af164b..292090b 100644 --- a/src/review/desktop/mod.rs +++ b/src/review/desktop/mod.rs @@ -2,6 +2,8 @@ mod controls; mod folder_index; mod help; #[cfg(target_os = "macos")] +mod history_ui; +#[cfg(target_os = "macos")] mod home; mod icons; mod instance; @@ -299,13 +301,21 @@ struct TableRow { enum Outcome { Scan(Result), #[cfg(target_os = "macos")] + HistoryLoad(Result<(PathBuf, Vec)>), + #[cfg(target_os = "macos")] StageReview(Result), #[cfg(target_os = "macos")] + StageRestoreReview(Result), + #[cfg(target_os = "macos")] + StageRestore(Result<()>), + #[cfg(target_os = "macos")] StageRemoval(Result<()>), Search(Result), Stale(Result), AppStorage(Result), #[cfg(target_os = "macos")] + GroupLink(Result), + #[cfg(target_os = "macos")] CachePrepared(Result), #[cfg(target_os = "macos")] CacheFinished(Result), @@ -339,6 +349,7 @@ struct StaleFiles { root: Option, days: u16, mib: u64, + include_outputs: bool, query: String, report: Option, error: String, @@ -351,6 +362,7 @@ impl Default for StaleFiles { root: None, days: 90, mib: 100, + include_outputs: true, query: String::new(), report: None, error: String::new(), @@ -394,6 +406,8 @@ struct App { confirmation_page: usize, #[cfg(target_os = "macos")] stages: stage_recovery::Panel, + #[cfg(target_os = "macos")] + timeline: history_ui::Panel, job: Option, save_as: Option, status: String, @@ -552,6 +566,8 @@ impl App { self.app_storage = Some(result); } #[cfg(target_os = "macos")] + Outcome::GroupLink(result) => self.library_panel.group_result = Some(result), + #[cfg(target_os = "macos")] Outcome::CachePrepared(result) => self.library_panel.review = Some(result), #[cfg(target_os = "macos")] Outcome::CacheFinished(result) => { @@ -578,8 +594,25 @@ impl App { } } #[cfg(target_os = "macos")] + Outcome::HistoryLoad(result) => self.timeline.review = Some(result), + #[cfg(target_os = "macos")] Outcome::StageReview(result) => self.stages.review = Some(result), #[cfg(target_os = "macos")] + Outcome::StageRestoreReview(result) => self.stages.restore = Some(result), + #[cfg(target_os = "macos")] + Outcome::StageRestore(result) => match result { + Ok(()) => { + self.refresh(ctx, false); + self.status = text( + self.japanese_reasons, + "残存データを復元しました。ステージの記録は残っています。", + "Restored remaining data. The stage record remains.", + ) + .into(); + } + Err(error) => self.status = format!("{error:#}"), + }, + #[cfg(target_os = "macos")] Outcome::StageRemoval(result) => match result { Ok(()) => { self.refresh(ctx, false); @@ -820,7 +853,10 @@ impl App { path: Some(row.path.clone()), folder: row.is_dir, size: bytes(size), - change: delta.map_or_else(|| "—".into(), |delta| delta.label()), + change: delta.map_or_else( + || "—".into(), + |delta| delta.localized_label(self.japanese_reasons), + ), order: if self.sort == Sort::Change { delta.map(|d| d.signed_bytes()) } else { @@ -1047,6 +1083,8 @@ impl App { } fn toolbar_actions(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + #[cfg(target_os = "macos")] + self.history_menu(ui); #[cfg(target_os = "macos")] self.stage_menu(ui); if ui @@ -1865,6 +1903,8 @@ impl App { } fn dialogs(&mut self, ctx: &egui::Context) { + #[cfg(target_os = "macos")] + self.history_dialog(ctx); #[cfg(target_os = "macos")] self.stage_dialog(ctx); #[cfg(target_os = "macos")] @@ -2299,6 +2339,11 @@ impl eframe::App for App { mod tests { use super::*; + #[test] + fn old_file_search_includes_build_outputs_by_default() { + assert!(StaleFiles::default().include_outputs); + } + #[test] fn folder_browse_orders_files_and_directories_and_can_enter() -> anyhow::Result<()> { let temp = tempfile::tempdir()?; diff --git a/src/review/desktop/monitor.rs b/src/review/desktop/monitor.rs index a3dfe93..653ad07 100644 --- a/src/review/desktop/monitor.rs +++ b/src/review/desktop/monitor.rs @@ -32,6 +32,8 @@ pub(super) struct Panel { context_job: Option>>>, contexts: Option>>, docker_job: Option>>, + observation_jobs: Vec>>, + observation_result: Option>, docker: Option>>, marked: BTreeSet, review: Option, @@ -238,7 +240,15 @@ impl Panel { self.reset_disk(); } - fn poll(&mut self, ctx: &egui::Context) { + pub(super) fn observation_pending(&self) -> bool { + !self.observation_jobs.is_empty() + } + + pub(super) fn observation_failed(&self) -> bool { + self.observation_result.as_ref().is_some_and(Result::is_err) + } + + pub(super) fn poll(&mut self, ctx: &egui::Context) { if let Some(job) = &self.disk_job { match job.try_recv() { Ok(result) => { @@ -299,7 +309,26 @@ impl Panel { Err(mpsc::TryRecvError::Empty) => {} } } - if self.disk_job.is_some() || self.docker_job.is_some() { + let mut pending = Vec::new(); + for job in self.observation_jobs.drain(..) { + let result = match job.try_recv() { + Ok(result) => Some(result), + Err(mpsc::TryRecvError::Disconnected) => { + Some(Err(anyhow::anyhow!("Docker observation interrupted"))) + } + Err(mpsc::TryRecvError::Empty) => { + pending.push(job); + None + } + }; + if let Some(result) = result { + if result.is_err() || self.observation_result.is_none() { + self.observation_result = Some(result); + } + } + } + self.observation_jobs = pending; + if self.disk_job.is_some() || self.docker_job.is_some() || self.observation_pending() { ctx.request_repaint_after(Duration::from_millis(100)); } } @@ -350,10 +379,24 @@ impl Panel { self.selected = None; let context = self.context.clone(); let (tx, rx) = mpsc::channel(); + let (observation_tx, observation_rx) = mpsc::channel(); self.docker_job = Some(rx); + self.observation_jobs.push(observation_rx); + self.observation_result = None; let ctx = ctx.clone(); std::thread::spawn(move || { - let _ = tx.send(storage::inspect(&context)); + let result = storage::inspect(&context); + let request = result + .as_ref() + .ok() + .and_then(|report| report.observation_request()); + let _ = tx.send(result); + ctx.request_repaint(); + if let Some(request) = request { + let _ = observation_tx.send(request.record()); + } else { + let _ = observation_tx.send(Err(anyhow::anyhow!("Docker inventory unavailable"))); + } ctx.request_repaint(); }); } diff --git a/src/review/desktop/monitor/docker_ui.rs b/src/review/desktop/monitor/docker_ui.rs index d1b5bfe..633e65e 100644 --- a/src/review/desktop/monitor/docker_ui.rs +++ b/src/review/desktop/monitor/docker_ui.rs @@ -45,6 +45,50 @@ fn date(value: Option>, japanese: bool) -> String { .unwrap_or_else(|| text(japanese, "不明", "Unknown").into()) } +fn docker_size(value: &str) -> String { + storage::size_bytes(value) + .map(bytes) + .unwrap_or_else(|| value.to_owned()) +} + +fn relative_time(value: &str, japanese: bool) -> String { + if !japanese { + return value.to_owned(); + } + if value == "Just now" || value == "just now" { + return "たった今".into(); + } + if let Some(translated) = match value.to_ascii_lowercase().as_str() { + "less than a second ago" => Some("1秒未満前"), + "about a minute ago" => Some("約1分前"), + "about an hour ago" => Some("約1時間前"), + "about a day ago" => Some("約1日前"), + "about a week ago" => Some("約1週間前"), + "about a month ago" => Some("約1か月前"), + "about a year ago" => Some("約1年前"), + _ => None, + } { + return translated.into(); + } + let parts: Vec<_> = value.split_whitespace().collect(); + if let [number, unit, "ago"] = parts.as_slice() { + if number.parse::().is_ok() { + let unit = match *unit { + "second" | "seconds" => "秒", + "minute" | "minutes" => "分", + "hour" | "hours" => "時間", + "day" | "days" => "日", + "week" | "weeks" => "週間", + "month" | "months" => "か月", + "year" | "years" => "年", + _ => return value.to_owned(), + }; + return format!("{number}{unit}前"); + } + } + value.to_owned() +} + fn name(item: &storage::Resource) -> String { if item.name.trim().is_empty() { item.id.chars().take(12).collect() @@ -218,8 +262,8 @@ fn cache_output_table(ui: &mut egui::Ui, output: &str, parsed: &ParsedOutput, ja } else { text(japanese, "いいえ", "No") }); - ui.label(&row.size); - ui.label(&row.last_accessed); + ui.label(docker_size(&row.size)); + ui.label(relative_time(&row.last_accessed, japanese)); ui.end_row(); } }); @@ -228,8 +272,9 @@ fn cache_output_table(ui: &mut egui::Ui, output: &str, parsed: &ParsedOutput, ja } if let Some(total) = &total { ui.label(format!( - "{}: {total}", - text(japanese, "Docker の報告容量", "Docker reported") + "{}: {}", + text(japanese, "Docker の報告容量", "Docker reported"), + docker_size(total) )); } if *unrecognized || (rows.is_empty() && total.is_none() && !output.trim().is_empty()) { @@ -385,6 +430,16 @@ impl Panel { if let Some(result) = &self.cache_receipt { let receipt = &result.raw; ui.group(|ui| { + if let Some(error) = &receipt.history_error { + ui.label(format!( + "{} · {error}", + text( + japanese, + "整理履歴を保存できませんでした", + "Could not save cleanup history" + ) + )); + } ui.horizontal(|ui| { ui.strong(text( japanese, @@ -460,6 +515,18 @@ impl Panel { if !self.docker_error.is_empty() { ui.label(RichText::new(&self.docker_error).color(Color32::from_rgb(170, 50, 42))); } + if self.observation_pending() && self.docker_job.is_none() { + ui.small(text( + japanese, + "容量の前回比較を記録中…", + "Recording storage comparison…", + )); + } + if let Some(Err(error)) = &self.observation_result { + ui.label(format!("{} · {error:#}", text(japanese, + "前回比較を記録できませんでした。概要には以前の記録が残る場合があります", + "Could not record the comparison. The overview may still show an older observation"))); + } let Some(result) = &self.docker else { if !busy { ui.add_space(28.0); @@ -543,7 +610,7 @@ impl Panel { action = Action::ReviewCache; } }); - ui.small(text(japanese, "Docker の接続先にある該当キャッシュをまとめて整理します。正確な対象と回収量は事前に確定できません。", "Docker selects matching cache on this connection. Exact items and reclaimed space cannot be determined in advance.")); + ui.small(text(japanese, "Docker の既定ビルダーが対象を判定します。使用中などの理由で行が残ることがあり、表示容量と回収量も一致するとは限りません。", "Docker's default builder selects the records. Some may remain, for example if in use, and reported size may differ from reclaimed space.")); } let previous = (self.query.clone(), self.filter, self.sort, self.age_days); ui.add_enabled_ui(!busy, |ui| { @@ -920,7 +987,7 @@ fn rows( &item .estimated_bytes .map(bytes) - .unwrap_or_else(|| item.size.clone()), + .unwrap_or_else(|| docker_size(&item.size)), 15.0, super::super::INK, Align::Max, @@ -936,12 +1003,12 @@ fn rows( if item.last_used.is_empty() { text(japanese, "不明", "Unknown").to_owned() } else { - item.last_used.clone() + relative_time(&item.last_used, japanese) } } else if !item.mounts.is_empty() { item.mounts.clone() } else { - item.shared_size.clone() + docker_size(&item.shared_size) }, 13.0, MUTED, @@ -994,7 +1061,7 @@ fn inspector( name(item) }; ui.label(RichText::new(title).size(19.0).strong()); - ui.label(RichText::new(&item.size).size(24.0)); + ui.label(RichText::new(docker_size(&item.size)).size(24.0)); ui.small(if kind == storage::Kind::Container { text(japanese, "コンテナの書込層", "Container writable layer") } else { @@ -1040,9 +1107,9 @@ fn inspector( ui.label(format!( "{} {} · {} {}", text(japanese, "共有", "Shared"), - item.shared_size, + docker_size(&item.shared_size), text(japanese, "固有", "Unique"), - item.unique_size + docker_size(&item.unique_size) )); } ui.add_space(12.0); @@ -1093,6 +1160,16 @@ fn show_receipt( names: &std::collections::BTreeMap, japanese: bool, ) { + if let Some(error) = &receipt.history_error { + ui.label(format!( + "{} · {error}", + text( + japanese, + "整理履歴を保存できませんでした", + "Could not save cleanup history" + ) + )); + } egui::Frame::NONE .stroke(Stroke::new(1.0_f32, LINE)) .corner_radius(9) @@ -1228,7 +1305,7 @@ impl App { ui.set_width(520.0); ui.heading(text(japanese, "ビルドキャッシュを整理しますか?", "Clean up build cache?")); ui.strong(format!("{}: {}", text(japanese, "接続先", "Context"), review.context)); - ui.label(if japanese { format!("この Docker の既定ビルダーで、{} 日以上未使用のキャッシュを Docker の基準でまとめて削除します。", review.days) } else { format!("Docker will prune unused cache older than {} days from this daemon's default builder.", review.days) }); + ui.label(if japanese { format!("この Docker の既定ビルダーで、{} 日以上未使用のキャッシュを Docker の基準で削除します。通常は残る内部・フロントエンドのキャッシュも対象です。", review.days) } else { format!("Docker will prune unused cache older than {} days from this daemon's default builder, including internal and frontend cache.", review.days) }); ui.label(text(japanese, "対象の全件や回収量は事前に確定できません。次のビルドは遅くなり、キャッシュマウント内のデータが失われる場合があります。ゴミ箱には入りません。", "Exact records and reclaimed space are unknown in advance. Later builds may be slower and cache-mount data may be lost. This bypasses Trash.")); ui.horizontal(|ui| { cancel = controls::button(ui, text(japanese, "キャンセル", "Cancel"), false, self.job.is_none()).clicked(); @@ -1270,7 +1347,7 @@ impl App { ui.label(text(japanese,"コンテナ内の書込データと Docker 管理ログが失われます。マウント先・ボリューム・イメージは残します。","Container writable data and Docker-managed logs will be lost. Mounts, volumes and images remain.")); ui.add_space(12.0); egui::ScrollArea::vertical().max_height(280.0).show(ui,|ui| { - for item in &review.items { ui.strong(name(item)); ui.small(&item.id); ui.label(format!("{} · {} {}",item.size,text(japanese,"最終停止/作成","Stopped / created"),date(activity(item),japanese))); ui.label(item.reason.text(japanese)); ui.add_space(6.0); ui.separator(); } + for item in &review.items { ui.strong(name(item)); ui.small(&item.id); ui.label(format!("{} · {} {}",docker_size(&item.size),text(japanese,"最終停止/作成","Stopped / created"),date(activity(item),japanese))); ui.label(item.reason.text(japanese)); ui.add_space(6.0); ui.separator(); } }); ui.add_space(12.0); ui.horizontal(|ui| { @@ -1307,6 +1384,17 @@ impl App { mod tests { use super::*; + #[test] + fn docker_display_converts_known_values_and_preserves_unknown_values() { + assert_eq!(docker_size("2GB"), bytes(2_000_000_000)); + assert_eq!(docker_size("unknown"), "unknown"); + assert_eq!(relative_time("2 months ago", true), "2か月前"); + assert_eq!(relative_time("1 hour ago", true), "1時間前"); + assert_eq!(relative_time("About an hour ago", true), "約1時間前"); + assert_eq!(relative_time("2 months ago", false), "2 months ago"); + assert_eq!(relative_time("unknown format", true), "unknown format"); + } + #[test] fn cache_cleanup_output_preserves_rows_and_unknown_details() { let text = "ID RECLAIMABLE SIZE LAST ACCESSED\nabc123* true 4.227MB 2 months ago\ndef456 false 0B 9 days ago\nTotal: 4.227MB\n"; diff --git a/src/review/desktop/old_files.rs b/src/review/desktop/old_files.rs index 52e332d..edbf3e6 100644 --- a/src/review/desktop/old_files.rs +++ b/src/review/desktop/old_files.rs @@ -20,8 +20,8 @@ impl App { )); ui.label(text( self.japanese_reasons, - "ホーム内の古い大容量ファイルを探します。開発プロジェクトの生成物はワークスペースで確認できます。", - "Find old personal files in your home folder. Review project build output in Workspace.", + "ホーム内の古い大容量ファイルを探します。使用中かどうかは確認しません。", + "Find old large files in your home folder. Open processes are not checked.", )); #[cfg(target_os = "macos")] if as_page @@ -80,6 +80,24 @@ impl App { state.error.clear(); } }); + if ui + .checkbox( + &mut state.include_outputs, + text( + self.japanese_reasons, + "開発プロジェクトの生成物を含める", + "Include project build output", + ), + ) + .changed() + { + state.report = None; + } + ui.small(text( + self.japanese_reasons, + "隠し項目、Library、node_modules は常に対象外です。", + "Hidden items, Library, and node_modules are always excluded.", + )); ui.horizontal(|ui| { ui.label(text( self.japanese_reasons, @@ -268,7 +286,13 @@ impl App { self.show_stale_files = false; } if start { - let (root, days, mib, sort) = (state.root.clone(), state.days, state.mib, state.sort); + let (root, days, mib, sort, include_outputs) = ( + state.root.clone(), + state.days, + state.mib, + state.sort, + state.include_outputs, + ); state.report = None; state.error.clear(); state.query.clear(); @@ -280,7 +304,15 @@ impl App { "Looking for old files…", ), false, - move || Outcome::Stale(stale::scan_personal(root.as_deref(), days, mib, sort)), + move || { + Outcome::Stale(stale::scan_personal( + root.as_deref(), + days, + mib, + sort, + include_outputs, + )) + }, ); } #[cfg(target_os = "macos")] diff --git a/src/review/desktop/projects.rs b/src/review/desktop/projects.rs index c454603..4a5a433 100644 --- a/src/review/desktop/projects.rs +++ b/src/review/desktop/projects.rs @@ -71,6 +71,7 @@ pub(super) struct Projects { focused: Option, query: String, by_candidate: bool, + confirm_bulk: bool, pub(super) active: bool, } @@ -135,7 +136,7 @@ fn candidate_header(ui: &mut egui::Ui, japanese: bool) { let status_width = if width >= 460. { 92. } else { 64. }; let name_width = (width - super::controls::HEIGHT - - 82. + - 110. - status_width - 3. * header.spacing().item_spacing.x) .max(40.); @@ -149,7 +150,7 @@ fn candidate_header(ui: &mut egui::Ui, japanese: bool) { ); for (label, width, align) in [ (text(japanese, "項目", "Item"), name_width, Align::Min), - (text(japanese, "サイズ", "Size"), 82., Align::Max), + (text(japanese, "サイズ", "Size"), 110., Align::Max), (text(japanese, "状態", "Status"), status_width, Align::Min), ] { super::controls::cell(ui, width, 28., align, |ui| { @@ -162,6 +163,7 @@ fn candidate_header(ui: &mut egui::Ui, japanese: bool) { #[derive(Default)] struct InspectorActions { inspect: Option, + show_parts: Option, finder_error: Option, keep: Option<(PathBuf, bool)>, } @@ -199,6 +201,9 @@ fn candidate_inspector( if let Some(count) = project.reviewable_cargo_parts.get(path) { ui.label(if japanese { format!("全体の削除は保留です。下位の {count} 件は個別に確認できます。") } else { format!("Whole-target removal is on hold. {count} subfolders can be reviewed individually.") }); + if super::controls::button(ui, text(japanese, "この下の候補を表示", "Show candidates inside"), false, true).clicked() { + actions.show_parts = Some(path.clone()); + } } } else { ui.label(text(japanese, "確認できる掃除候補です。", "Available for cleanup review.")); @@ -240,6 +245,20 @@ fn candidate_inspector( } impl Projects { + fn bulk_breakdown(&self) -> Vec<(&Project, usize)> { + self.rows + .iter() + .filter_map(|project| { + let count = self + .bulk_paths + .range(project.path.clone()..) + .take_while(|path| path.starts_with(&project.path)) + .count(); + (count > 0).then_some((project, count)) + }) + .collect() + } + pub(super) fn from_scan(scan: &Scan) -> Self { let mut projects: BTreeMap<_, _> = scan .directories @@ -538,7 +557,7 @@ impl App { let status_width = if width >= 460. { 92. } else { 64. }; let name_width = (width - super::controls::HEIGHT - - 82. + - 110. - status_width - 3. * row.spacing().item_spacing.x) .max(40.); @@ -614,10 +633,10 @@ impl App { }, ); ui.allocate_ui_with_layout( - egui::vec2(82., 42.), + egui::vec2(110., 42.), egui::Layout::right_to_left(Align::Center), |ui| { - ui.set_width(82.); + ui.set_width(110.); super::controls::label( ui, &bytes(c.row.usage.size()), @@ -765,6 +784,11 @@ impl App { if let Some(error) = actions.finder_error { self.status = error; } + if let Some(path) = actions.show_parts { + self.projects.query = display(&path); + self.projects.focused = None; + ui.ctx().request_repaint(); + } if !missing.is_empty() { let scan = self.scan.as_mut().unwrap(); scan.files.retain(|c| !missing.contains(&c.row.path)); @@ -832,7 +856,7 @@ impl App { "Largest increase since last scan" ), name(&p.path), - delta.label() + delta.localized_label(self.japanese_reasons) )) .color(ACCENT), ); @@ -871,7 +895,7 @@ impl App { ) .clicked() { - self.marked.clone_from(&self.projects.bulk_paths); + self.projects.confirm_bulk = true; } } else { if ui @@ -894,6 +918,52 @@ impl App { .clicked(); } }); + ui.small(text( + japanese, + "選択だけでは削除されません。確認画面で内容を確認できます。", + "Selecting items does not delete them. Review the details on the next screen.", + )); + if self.projects.confirm_bulk { + let mut select = false; + let mut cancel = false; + let dialog = egui::Modal::new(egui::Id::new("confirm-project-bulk-selection")) + .frame(super::modal_frame(ui.ctx())) + .show(ui.ctx(), |ui| { + ui.set_width((ui.ctx().content_rect().width() - 64.0).clamp(200.0, 720.0)); + ui.heading(text(japanese, "掃除候補をまとめて選択しますか?", "Select all cleanup candidates?")); + ui.label(if japanese { + format!("全プロジェクトの {} 件 · 見込み {}", self.projects.bulk_paths.len(), bytes(self.projects.reclaim)) + } else { + format!("{} items across projects · estimated {}", self.projects.bulk_paths.len(), bytes(self.projects.reclaim)) + }); + ui.label(text(japanese, "この操作では削除されません。プロジェクトを開いて個別に選ぶこともできます。", "This only selects items; nothing is deleted. You can also open a project to select items individually.")); + let breakdown = self.projects.bulk_breakdown(); + ui.strong(text(japanese, "プロジェクトごとの内訳", "By project")); + egui::ScrollArea::vertical().id_salt("bulk-project-breakdown").max_height(220.0) + .show_rows(ui, 30.0, breakdown.len(), |ui, range| { + for index in range { + let (project, count) = breakdown[index]; + let line = if japanese { + format!("{} · {} 件 · {}", name(&project.path), count, bytes(project.reclaim)) + } else { + format!("{} · {} items · {}", name(&project.path), count, bytes(project.reclaim)) + }; + ui.add(egui::Label::new(line).truncate()).on_hover_text(display(&project.path)); + } + }); + ui.add_space(12.); + ui.horizontal(|ui| { + cancel = super::controls::button(ui, text(japanese, "キャンセル", "Cancel"), false, true).clicked(); + select = super::controls::button(ui, text(japanese, "選択する", "Select items"), true, self.job.is_none()).clicked(); + }); + }); + if cancel || dialog.should_close() || select { + self.projects.confirm_bulk = false; + } + if select { + self.marked.clone_from(&self.projects.bulk_paths); + } + } if review { let policy = scan.policy.clone(); let paths = self.marked.iter().cloned().collect(); @@ -961,8 +1031,8 @@ impl App { - 16. - 4. * ui.spacing().item_spacing.x) .max(1.); - let column = (available * 0.20).clamp(1., 106.); - let delta_width = (available * 0.22).clamp(1., 132.); + let column = (available * 0.22).clamp(1., 130.); + let delta_width = (available * 0.23).clamp(1., 150.); let widths = [ available - 2. * column - delta_width, column, @@ -1037,7 +1107,10 @@ impl App { for (i, label) in [ bytes(p.size), bytes(p.reclaim), - p.delta.map_or_else(|| "—".into(), |d| d.label()), + p.delta.map_or_else( + || "—".into(), + |d| d.localized_label(self.japanese_reasons), + ), ] .into_iter() .enumerate() @@ -1138,6 +1211,14 @@ mod tests { 1 ); assert_eq!(projects.reclaim, 55); + assert_eq!( + projects + .bulk_breakdown() + .iter() + .map(|(project, count)| (project.path.clone(), *count, project.reclaim)) + .collect::>(), + vec![(root.join("a"), 1, 15), (root.join("b"), 1, 40)] + ); assert_eq!( projects.bulk_paths, BTreeSet::from([ diff --git a/src/review/desktop/scan.rs b/src/review/desktop/scan.rs index eb0c159..c1d3eee 100644 --- a/src/review/desktop/scan.rs +++ b/src/review/desktop/scan.rs @@ -275,6 +275,12 @@ impl Confirmation { pub fn remove(self, root: &Path) -> CleanupReceipt { let started_at = chrono::Utc::now(); + #[cfg(target_os = "macos")] + let kept_paths_at_start = super::keep::KeepRules::load() + .ok() + .map(|rules| rules.relevant_to(root)); + #[cfg(not(target_os = "macos"))] + let kept_paths_at_start = None; let before = super::super::filesystem::available(root); let outcomes = run_in_pairs(&self.items, |item| { let result = self @@ -290,8 +296,9 @@ impl Confirmation { let items = self .items .iter() + .zip(&self.totals) .zip(&outcomes) - .map(|(item, (_, result))| { + .map(|((item, summary), (_, result))| { let original_path_exists = match std::fs::symlink_metadata(&item.path) { Ok(_) => Some(true), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Some(false), @@ -301,6 +308,7 @@ impl Confirmation { path: item.path.clone(), producer: item.producer.reason().to_owned(), logical_bytes: item.logical_bytes(), + scanned_allocated_bytes: summary.scanned_allocated, status: if result.is_ok() { "removed" } else { @@ -309,16 +317,19 @@ impl Confirmation { .into(), reason: result.as_ref().err().map(ToString::to_string), original_path_exists, + original_path_checked_at: Some(chrono::Utc::now()), } }) .collect(); let record = cleanup_history::Record { + operation: None, version: 1, root: root.to_owned(), started_at, completed_at: chrono::Utc::now(), available_before: before, available_after: after, + kept_paths_at_start, items, }; #[cfg(not(test))] diff --git a/src/review/desktop/sdk.rs b/src/review/desktop/sdk.rs index 9f2dd8e..3067eea 100644 --- a/src/review/desktop/sdk.rs +++ b/src/review/desktop/sdk.rs @@ -380,16 +380,24 @@ fn sdk_rows( row.set_clip_rect(row.clip_rect().intersect(rect)); let mut checked = marked.contains(&item.target); if cell(&mut row, HEIGHT, HEIGHT, egui::Align::Min, |ui| { - ui.add_enabled( - enabled && item.selectable, - egui::Checkbox::without_text(&mut checked), + if item.selectable { + ui.add_enabled(enabled, egui::Checkbox::without_text(&mut checked)) + } else { + let (rect, response) = + ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); + super::icons::paint(ui, rect, super::icons::Icon::Lock, MUTED); + response + } + }) + .on_hover_text(if item.selectable { + text( + japanese, + "アンインストールの確認に含める", + "Include in uninstall review", ) + } else { + text(japanese, "保護された項目", "Protected item") }) - .on_hover_text(text( - japanese, - "アンインストールの確認に含める", - "Include in uninstall review", - )) .changed() { if checked { @@ -588,6 +596,16 @@ fn show_receipt(ui: &mut egui::Ui, result: &Result, japanese: bool) { ui.label(format!("{error:#}")); } Ok(receipt) => { + if let Some(error) = &receipt.history_error { + ui.label(format!( + "{} · {error}", + text( + japanese, + "整理履歴を保存できませんでした", + "Could not save cleanup history" + ) + )); + } ui.label( RichText::new(text( japanese, diff --git a/src/review/desktop/shell.rs b/src/review/desktop/shell.rs index c08e0e3..ba2d986 100644 --- a/src/review/desktop/shell.rs +++ b/src/review/desktop/shell.rs @@ -105,6 +105,7 @@ impl App { if self.screen == screen { return; } + self.status.clear(); self.monitor.close(); self.sdk.open = screen == Screen::Apps; match screen { @@ -115,7 +116,11 @@ impl App { self.monitor.context = self.profile.docker_context.clone().unwrap_or_default(); } } - Screen::Overview => self.home.update_capacity(), + Screen::Overview => { + self.home.update_capacity(); + self.home.reload_library_growth(); + self.home.reload_docker_growth(); + } Screen::Apps => self.sdk.open = true, _ => {} } @@ -397,7 +402,24 @@ impl App { ui.add_space(12.0); } if !self.status.is_empty() { - ui.label(RichText::new(&self.status).color(egui::Color32::from_rgb(160, 50, 40))); + let success = self.status + == text( + self.japanese_reasons, + "ステージを片付けました。", + "Removed the reviewed stage.", + ) + || self.status + == text( + self.japanese_reasons, + "残存データを復元しました。ステージの記録は残っています。", + "Restored remaining data. The stage record remains.", + ); + let color = if success { + ACCENT + } else { + egui::Color32::from_rgb(160, 50, 40) + }; + ui.label(RichText::new(&self.status).color(color)); ui.add_space(10.0); } } @@ -405,6 +427,7 @@ impl App { fn cleanup_result(&mut self, ui: &mut egui::Ui) { if let Some(receipt) = &self.cleanup_receipt { let mut dismiss = false; + let mut review_stages = false; let actual = match (receipt.before, receipt.after) { (Some(before), Some(after)) => format!( "{}{}", @@ -456,6 +479,24 @@ impl App { receipt.held ) }); + if receipt.held > 0 { + ui.small(text( + self.japanese_reasons, + "元の場所に残っていない場合も、ステージにデータが残っている可能性があります。", + "Data may remain in a stage even if it is no longer at the original location.", + )); + review_stages = ui + .add_enabled( + self.job.is_none() + && self.scan.as_ref().is_some_and(|scan| !scan.policy.roots.is_empty()), + egui::Button::new(text( + self.japanese_reasons, + "残ったステージを確認…", + "Review leftover stages…", + )), + ) + .clicked(); + } ui.collapsing( text( self.japanese_reasons, @@ -482,6 +523,9 @@ impl App { if dismiss { self.cleanup_receipt = None; } + if review_stages { + self.open_stage_list(); + } ui.add_space(12.0); } } diff --git a/src/review/desktop/stage_recovery.rs b/src/review/desktop/stage_recovery.rs index 8f3feff..9a85606 100644 --- a/src/review/desktop/stage_recovery.rs +++ b/src/review/desktop/stage_recovery.rs @@ -1,5 +1,5 @@ use super::{display, egui, text, App, Outcome, Scan}; -use crate::review::filesystem::recovery::ReviewedStage; +use crate::review::filesystem::recovery::{RestoreStage, ReviewedStage}; use anyhow::Result; use std::path::PathBuf; @@ -7,6 +7,7 @@ use std::path::PathBuf; pub(super) struct Panel { locations: Option>, pub(super) review: Option>, + pub(super) restore: Option>, } fn locations(scan: &Scan) -> Vec<(PathBuf, PathBuf)> { @@ -31,6 +32,14 @@ fn locations(scan: &Scan) -> Vec<(PathBuf, PathBuf)> { } impl App { + pub(super) fn open_stage_list(&mut self) { + if let Some(scan) = &self.scan { + if !scan.policy.roots.is_empty() { + self.stages.locations = Some(locations(scan)); + } + } + } + pub(super) fn stage_menu(&mut self, ui: &mut egui::Ui) { let Some(scan) = &self.scan else { return }; if scan.policy.roots.is_empty() { @@ -44,7 +53,7 @@ impl App { )) .clicked() { - self.stages.locations = Some(locations(scan)); + self.open_stage_list(); ui.close(); } } @@ -55,6 +64,7 @@ impl App { let mut selected = None; let mut close = false; let modal = egui::Modal::new("stage-list".into()).show(ctx, |ui| { + ui.set_width((ctx.content_rect().width() - 64.0).clamp(200.0, 720.0)); ui.heading(text(ja, "残ったステージ", "Leftover stages")); if paths.is_empty() { ui.label(text( @@ -65,16 +75,29 @@ impl App { } else { ui.label(text( ja, - "確認する場所を選んでください。", - "Choose a stage to inspect.", + "今回のスキャンで見つかった場所です。確認するステージを選んでください。", + "These stages were found in the last scan. Choose one to inspect.", )); egui::ScrollArea::vertical() .max_height(300.0) .show(ui, |ui| { for (root, path) in paths { - if ui.button(display(path)).clicked() { - selected = Some((root.clone(), path.clone())); - } + ui.vertical(|ui| { + ui.add(egui::Label::new(display(path)).wrap()); + ui.horizontal_wrapped(|ui| { + if ui.button(text(ja, "後片付け", "Clean up")).clicked() + { + selected = Some((root.clone(), path.clone(), false)); + } + if ui + .button(text(ja, "復元を確認", "Review restore")) + .clicked() + { + selected = Some((root.clone(), path.clone(), true)); + } + }); + ui.separator(); + }); } }); } @@ -83,19 +106,63 @@ impl App { if close || modal.should_close() || selected.is_some() { self.stages.locations = None; } - if let Some((root, path)) = selected { + if let Some((root, path, restore)) = selected { self.spawn( ctx, text(ja, "残存ファイルを確認中…", "Inspecting stage…"), false, - move || Outcome::StageReview(ReviewedStage::inspect(&root, &path)), + move || { + if restore { + Outcome::StageRestoreReview(RestoreStage::inspect(&root, &path)) + } else { + Outcome::StageReview(ReviewedStage::inspect(&root, &path)) + } + }, ); } } + if let Some(review) = &self.stages.restore { + let mut restore = false; + let mut close = false; + let mut finder_error = None; + let modal = egui::Modal::new("stage-restore".into()).show(ctx, |ui| { + ui.set_width((ctx.content_rect().width() - 64.0).clamp(200.0, 720.0)); + ui.heading(text(ja, "残存データの復元", "Restore remaining data")); + match review { + Ok(stage) => { + ui.label(format!("{}: {}", text(ja, "移動元", "From"), display(&stage.path.join("payload")))); + ui.label(format!("{}: {}", text(ja, "記録された移動先", "Recorded destination"), display(&stage.original))); + ui.label(text(ja, "記録は由来や完全性の証明ではありません。整理中に一部が削除済みの可能性があります。内容と移動先を確認してください。既存の移動先は上書きしません。", "The record does not prove origin or completeness; some data may already have been removed. Check the contents and destination. An existing destination will not be overwritten.")); + if ui.button(text(ja, "残存データを Finder で開く", "Open remaining data in Finder")).clicked() { + finder_error = super::open_in_finder(&stage.path.join("payload")).err(); + } + restore = ui.button(text(ja, "残存データをこの場所に復元", "Restore remaining data here")).clicked(); + } + Err(err) => { ui.label(format!("{err:#}")); } + } + close = ui.button(text(ja, "閉じる", "Close")).clicked(); + }); + if let Some(error) = finder_error { + self.status = format!("{error:#}"); + } + if restore { + if let Some(Ok(review)) = self.stages.restore.take() { + self.spawn( + ctx, + text(ja, "復元中…", "Restoring…"), + true, + move || Outcome::StageRestore(review.restore()), + ); + } + } else if close || modal.should_close() { + self.stages.restore = None; + } + } if let Some(review) = &self.stages.review { let mut remove = false; let mut close = false; let modal = egui::Modal::new("stage-review".into()).show(ctx, |ui| { + ui.set_width((ctx.content_rect().width() - 64.0).clamp(200.0, 720.0)); ui.heading(text(ja, "ステージの後片付け", "Stage cleanup")); match review { Ok(stage) => { @@ -105,7 +172,8 @@ impl App { } Err(err) => { ui.label(text(ja, "後片付けを保留しました。", "Stage cleanup is on hold.")); - ui.label(format!("{err:#}")); + ui.label(text(ja, "ステージに残った内容を安全に片付けられるか確認できませんでした。", "Could not verify that the remaining contents are safe to clean up.")); + ui.collapsing(text(ja, "詳細", "Details"), |ui| { ui.label(format!("{err:#}")); }); } } close = ui.button(text(ja, "閉じる", "Close")).clicked(); diff --git a/src/review/docker/storage.rs b/src/review/docker/storage.rs index b0e3c26..6a9deb8 100644 --- a/src/review/docker/storage.rs +++ b/src/review/docker/storage.rs @@ -4,6 +4,7 @@ use crate::review::message::Message; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; mod actions; +pub(crate) mod observations; pub(crate) use actions::{Receipt, Review}; use serde::Deserialize; use std::time::Duration; @@ -76,6 +77,7 @@ pub(crate) struct CacheCleanupResult { pub result: Result, pub before: Option, pub after: Option, + pub history_error: Option, } impl CacheCleanup { @@ -95,6 +97,7 @@ impl CacheCleanup { } pub fn apply(self) -> CacheCleanupResult { + let started = Utc::now(); let free = || { directories::BaseDirs::new() .and_then(|d| crate::review::filesystem::available(d.home_dir())) @@ -111,21 +114,54 @@ impl CacheCleanup { Ok(()) }, || { - let filter = format!("until={}h", u64::from(self.days) * 24); - command_output(command_on(&self.endpoint).args(["builder", "prune", "--force", "--filter", &filter]), Duration::from_secs(300)) + command_output(&mut cache_prune_command(&self.endpoint, self.days), Duration::from_secs(300)) .context("Docker cache cleanup did not complete; some records may already have been removed") }, ); - CacheCleanupResult { + let receipt = CacheCleanupResult { context: self.context, days: self.days, result, before, after: free(), + history_error: None, + }; + #[cfg(not(test))] + let mut receipt = receipt; + #[cfg(not(test))] + { + let target = super::super::cleanup_history::OperationTarget { + identifier: "default builder cache".into(), + status: if receipt.result.is_ok() { "completed" } else { "unverified" }.into(), + reason: receipt.result.as_ref().err().map(|_| "Cleanup did not complete or could not be verified; details were not retained".into()), + remaining_image_bytes: None, + }; + receipt.history_error = super::super::cleanup_history::save_operation( + started, + receipt.before, + receipt.after, + super::super::cleanup_history::Operation { + kind: "docker_builder_cache_cleanup".into(), + retention_days: Some(receipt.days), + targets: vec![target], + }, + ) + .err() + .map(|error| format!("{error:#}")); } + #[cfg(test)] + let _ = started; + receipt } } +fn cache_prune_command(endpoint: &str, days: u16) -> std::process::Command { + let filter = format!("until={}h", u64::from(days) * 24); + let mut command = command_on(endpoint); + command.args(["builder", "prune", "--all", "--force", "--filter", &filter]); + command +} + fn checked_cache_cleanup( verify: impl FnOnce() -> Result<()>, run: impl FnOnce() -> Result, @@ -201,11 +237,31 @@ pub(crate) fn inspect(context: &str) -> Result { Duration::from_secs(30), ) .context("Docker の容量を取得できませんでした。Docker Desktop または Colima と接続先を確認してください")?; - let mut report = parse(context, &response)?; + let mut report = parse(context.clone(), &response)?; actions::enrich(&mut report, pin)?; Ok(report) } +pub(crate) struct ObservationRequest { + context: String, + pin: actions::Pin, +} + +impl Report { + pub(crate) fn observation_request(&self) -> Option { + self.daemon.as_ref().map(|pin| ObservationRequest { + context: self.context.clone(), + pin: pin.clone(), + }) + } +} + +impl ObservationRequest { + pub(crate) fn record(self) -> Result<()> { + observations::measure_and_record(&self.pin.endpoint, &self.context, &self.pin) + } +} + fn parse(context: String, json: &str) -> Result { let response: Response = serde_json::from_str(json)?; let groups = [ @@ -305,6 +361,24 @@ mod tests { Ok(()) } + #[test] + fn cache_cleanup_includes_all_unused_cache_with_the_selected_age() { + let command = cache_prune_command("unix:///tmp/docker.sock", 7); + let args: Vec<_> = command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + assert!(args.windows(6).any(|args| args + == [ + "builder", + "prune", + "--all", + "--force", + "--filter", + "until=168h" + ])); + } + #[test] fn cache_cleanup_never_runs_if_connection_verification_fails() { let called = std::cell::Cell::new(false); diff --git a/src/review/docker/storage/actions.rs b/src/review/docker/storage/actions.rs index e1dff5d..245f0df 100644 --- a/src/review/docker/storage/actions.rs +++ b/src/review/docker/storage/actions.rs @@ -7,7 +7,7 @@ const PROJECTION: &str = r#"{"id":{{json .Id}},"name":{{json .Name}},"image":{{j #[derive(Clone, Debug, PartialEq, Eq)] pub(super) struct Pin { - endpoint: String, + pub(super) endpoint: String, id: String, } #[cfg_attr(test, derive(serde::Serialize))] @@ -370,6 +370,7 @@ pub(crate) struct Receipt { pub before: Option, pub after: Option, pub estimated_bytes: Option, + pub history_error: Option, } impl Review { pub fn prepare(report: &Report, selection: &BTreeSet) -> Result { @@ -423,7 +424,33 @@ impl Review { }) } pub fn apply(self) -> Receipt { - self.apply_with(&Docker) + let started = Utc::now(); + let receipt = self.apply_with(&Docker); + #[cfg(not(test))] + let mut receipt = receipt; + #[cfg(not(test))] + { + let targets = receipt.outcomes.iter().map(|(id, result)| super::super::super::cleanup_history::OperationTarget { + identifier: id.clone(), status: if result.is_ok() { "removed" } else { "unverified" }.into(), + reason: result.as_ref().err().map(|_| "Operation failed or removal could not be verified; details were not retained".into()), + remaining_image_bytes: None, + }).collect(); + receipt.history_error = super::super::super::cleanup_history::save_operation( + started, + receipt.before, + receipt.after, + super::super::super::cleanup_history::Operation { + kind: "docker_container_removal".into(), + retention_days: None, + targets, + }, + ) + .err() + .map(|error| format!("{error:#}")); + } + #[cfg(test)] + let _ = started; + receipt } fn apply_with(self, backend: &impl Backend) -> Receipt { let before = backend.free(); @@ -463,6 +490,7 @@ impl Review { before, after: backend.free(), estimated_bytes, + history_error: None, } } } diff --git a/src/review/docker/storage/observations.rs b/src/review/docker/storage/observations.rs new file mode 100644 index 0000000..72488d2 --- /dev/null +++ b/src/review/docker/storage/observations.rs @@ -0,0 +1,363 @@ +//! Append-only, read-only Docker summary observations. Category totals are +//! kept separate: shared layers and VM storage make a summed total misleading. +use super::{actions, command_on, size_bytes}; +use crate::review::app_storage::command_output; +use anyhow::{ensure, Context, Result}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufRead, BufReader, Read, Seek, Write}; +use std::path::Path; +use std::time::Duration; + +const LINE_LIMIT: usize = 64 * 1024; +const CATEGORIES: [&str; 4] = ["Images", "Containers", "Local Volumes", "Build Cache"]; + +#[derive(Clone, Deserialize, Serialize)] +pub(in crate::review) struct Observation { + pub context: String, + pub measured: DateTime, + pub prior: Option>, + pub values: BTreeMap, + pub changes: BTreeMap, + identity: String, + versions: String, +} + +#[derive(Deserialize, Serialize)] +struct LatestCache { + log_len: u64, + observation: Observation, +} + +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct SummaryRow { + #[serde(rename = "Type")] + category: String, + size: String, +} + +fn parse_summary(output: &str) -> Result> { + let mut rows = BTreeMap::new(); + for line in output.lines().filter(|line| !line.trim().is_empty()) { + let row: SummaryRow = serde_json::from_str(line)?; + ensure!( + CATEGORIES.contains(&row.category.as_str()), + "Unknown Docker category" + ); + let value = size_bytes(&row.size).context("Docker size unavailable")?; + ensure!( + rows.insert(row.category, value).is_none(), + "Duplicate Docker category" + ); + } + ensure!(rows.len() == CATEGORIES.len(), "Incomplete Docker summary"); + Ok(rows) +} + +fn versions(endpoint: &str) -> Result { + let value = command_output( + command_on(endpoint).args([ + "version", + "--format", + "{{json .Client.Version}} {{json .Server.Version}} {{json .Server.APIVersion}}", + ]), + Duration::from_secs(10), + )?; + let parts = value + .split_whitespace() + .map(serde_json::from_str::) + .collect::, _>>()?; + ensure!( + parts.len() == 3 && parts.iter().all(|part| !part.is_empty()), + "Docker version unavailable" + ); + let info = command_output( + command_on(endpoint).args([ + "info", + "--format", + "{{json .Driver}}\n{{json .DockerRootDir}}", + ]), + Duration::from_secs(10), + )?; + let info = info + .lines() + .map(serde_json::from_str::) + .collect::, _>>()?; + ensure!( + info.len() == 2 && info.iter().all(|part| !part.is_empty()), + "Docker storage configuration unavailable" + ); + // Keep configuration paths local but out of the observation history. + Ok(format!( + "{:x}", + Sha256::digest(format!("{parts:?}{info:?}").as_bytes()) + )) +} + +pub(super) fn measure_and_record(endpoint: &str, context: &str, pin: &actions::Pin) -> Result<()> { + let first_version = versions(endpoint)?; + ensure!( + &actions::capture(endpoint)? == pin, + "Docker daemon changed before summary" + ); + let measured = Utc::now(); + let output = command_output( + command_on(endpoint).args(["system", "df", "--format", "{{json .}}"]), + Duration::from_secs(30), + )?; + let values = parse_summary(&output)?; + ensure!( + &actions::capture(endpoint)? == pin && versions(endpoint)? == first_version, + "Docker daemon or version changed during summary" + ); + // A digest is sufficient for equality and avoids persisting the daemon ID or socket path. + let identity = format!("{:x}", Sha256::digest(format!("{pin:?}").as_bytes())); + let dirs = crate::storage_paths::project_dirs().context("Could not locate still data")?; + let event = Observation { + context: context.into(), + measured, + prior: None, + values, + changes: BTreeMap::new(), + identity, + versions: first_version, + }; + append(dirs.data_local_dir(), event) +} + +fn read_latest(file: &mut File, identity: Option<&str>) -> Result> { + let mut latest = None; + let mut reader = BufReader::new(file); + loop { + let mut line = Vec::new(); + let count = reader + .by_ref() + .take(LINE_LIMIT as u64 + 1) + .read_until(b'\n', &mut line)?; + if count == 0 { + break; + } + ensure!( + count <= LINE_LIMIT && line.last() == Some(&b'\n'), + "Invalid Docker observation record" + ); + let item: Observation = serde_json::from_slice(&line)?; + if identity.is_none_or(|id| item.identity == id) + && latest + .as_ref() + .is_none_or(|current: &Observation| current.measured < item.measured) + { + latest = Some(item); + } + } + Ok(latest) +} + +fn append(directory: &Path, mut event: Observation) -> Result<()> { + use std::os::unix::fs::OpenOptionsExt; + fs::create_dir_all(directory)?; + let mut file = OpenOptions::new() + .read(true) + .append(true) + .create(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(directory.join("docker-observations.jsonl"))?; + ensure!( + file.metadata()?.is_file(), + "Docker history is not a regular file" + ); + file.try_lock() + .map_err(|error| anyhow::anyhow!("Docker history is busy: {error}"))?; + let previous = read_latest(&mut file, Some(&event.identity))?; + file.rewind()?; + let last = read_latest(&mut file, None)?; + if let Some(previous) = &previous { + if previous.measured < event.measured + && previous.versions == event.versions + && previous.values.keys().eq(event.values.keys()) + { + event.prior = Some(previous.measured); + event.changes = event + .values + .iter() + .map(|(key, value)| { + ( + key.clone(), + i128::from(*value) - i128::from(previous.values[key]), + ) + }) + .collect(); + } + } + let mut line = serde_json::to_vec(&event)?; + line.push(b'\n'); + file.write_all(&line)?; + file.sync_data()?; + let log_len = file.metadata()?.len(); + // The append-only log is authoritative; the bounded latest cache keeps + // rendering the home screen independent of the length of that log. + let latest = last + .filter(|value| value.measured > event.measured) + .unwrap_or(event); + let mut cache = tempfile::NamedTempFile::new_in(directory)?; + serde_json::to_writer( + cache.as_file_mut(), + &LatestCache { + log_len, + observation: latest, + }, + )?; + cache.as_file().sync_all()?; + cache.persist(directory.join("docker-observation-latest.json"))?; + Ok(()) +} + +pub(in crate::review) fn latest() -> Result> { + let dirs = crate::storage_paths::project_dirs().context("Could not locate still data")?; + latest_in(dirs.data_local_dir()) +} + +fn latest_in(directory: &Path) -> Result> { + use std::os::unix::fs::OpenOptionsExt; + let path = directory.join("docker-observation-latest.json"); + let mut file = match OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + ensure!( + !directory.join("docker-observations.jsonl").exists(), + "Docker observation cache is missing" + ); + return Ok(None); + } + Err(error) => return Err(error.into()), + }; + let metadata = file.metadata()?; + ensure!( + metadata.is_file() && metadata.len() <= LINE_LIMIT as u64, + "Invalid Docker observation cache" + ); + let mut data = String::new(); + file.read_to_string(&mut data)?; + let cache: LatestCache = serde_json::from_str(&data)?; + let log = fs::metadata(directory.join("docker-observations.jsonl"))?; + ensure!( + log.len() == cache.log_len, + "Docker observation cache is out of date" + ); + Ok(Some(cache.observation)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn event(id: &str, version: &str, value: u64) -> Observation { + Observation { + context: "test".into(), + measured: Utc::now(), + prior: None, + values: CATEGORIES + .iter() + .map(|name| ((*name).into(), value)) + .collect(), + changes: BTreeMap::new(), + identity: id.into(), + versions: version.into(), + } + } + + #[test] + fn rejects_missing_duplicate_and_unknown_sizes() { + let good = "{\"Type\":\"Images\",\"Size\":\"1GB\"}\n{\"Type\":\"Containers\",\"Size\":\"1MB\"}\n{\"Type\":\"Local Volumes\",\"Size\":\"0B\"}\n{\"Type\":\"Build Cache\",\"Size\":\"2MB\"}\n"; + assert_eq!(parse_summary(good).unwrap().len(), 4); + assert!(parse_summary(good.replace("2MB", "N/A").as_str()).is_err()); + assert!(parse_summary(good.replace("Build Cache", "Other").as_str()).is_err()); + assert!(parse_summary(good.replace("Build Cache", "Images").as_str()).is_err()); + assert!( + parse_summary(good.lines().take(3).collect::>().join("\n").as_str()).is_err() + ); + } + + #[test] + fn records_only_comparable_daemon_and_version_without_discarding_history() -> Result<()> { + let dir = tempfile::tempdir()?; + append(dir.path(), event("daemon-a", "v1", 10))?; + append(dir.path(), event("daemon-b", "v1", 99))?; + append(dir.path(), event("daemon-a", "v1", 15))?; + append(dir.path(), event("daemon-a", "v2", 25))?; + let mut file = File::open(dir.path().join("docker-observations.jsonl"))?; + let events = BufReader::new(&mut file) + .lines() + .map(|line| -> Result { Ok(serde_json::from_str(&line?)?) }) + .collect::>>()?; + assert_eq!(events.len(), 4); + assert!(events[0].prior.is_none()); + assert!(events[1].prior.is_none()); + assert!(events[2].prior.is_some()); + assert_eq!(events[2].changes["Images"], 5); + assert!(events[3].prior.is_none()); + Ok(()) + } + + #[test] + fn late_completion_does_not_replace_newer_observation_or_baseline() -> Result<()> { + let dir = tempfile::tempdir()?; + let base = Utc::now(); + let mut newer = event("daemon", "v1", 20); + newer.measured = base + chrono::TimeDelta::seconds(2); + append(dir.path(), newer)?; + let mut older = event("daemon", "v1", 10); + older.measured = base + chrono::TimeDelta::seconds(1); + append(dir.path(), older)?; + let latest = latest_in(dir.path())?.unwrap(); + assert_eq!(latest.values["Images"], 20); + let mut subsequent = event("daemon", "v1", 30); + subsequent.measured = base + chrono::TimeDelta::seconds(3); + append(dir.path(), subsequent)?; + let latest = latest_in(dir.path())?.unwrap(); + assert_eq!(latest.changes["Images"], 10); + assert_eq!(latest.prior, Some(base + chrono::TimeDelta::seconds(2))); + Ok(()) + } + + #[test] + fn stale_or_missing_cache_is_not_displayed_as_latest() -> Result<()> { + let dir = tempfile::tempdir()?; + assert!(latest_in(dir.path())?.is_none()); + append(dir.path(), event("daemon", "v1", 20))?; + let mut log = OpenOptions::new() + .append(true) + .open(dir.path().join("docker-observations.jsonl"))?; + let mut line = serde_json::to_vec(&event("daemon", "v1", 30))?; + line.push(b'\n'); + log.write_all(&line)?; + assert!(latest_in(dir.path()).is_err()); + let other = tempfile::tempdir()?; + std::fs::write(other.path().join("docker-observations.jsonl"), &line)?; + assert!(latest_in(other.path()).is_err()); + Ok(()) + } + + #[test] + fn busy_history_fails_without_waiting() -> Result<()> { + let dir = tempfile::tempdir()?; + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(dir.path().join("docker-observations.jsonl"))?; + file.try_lock()?; + let started = std::time::Instant::now(); + assert!(append(dir.path(), event("daemon", "v1", 20)).is_err()); + assert!(started.elapsed() < Duration::from_secs(1)); + Ok(()) + } +} diff --git a/src/review/filesystem.rs b/src/review/filesystem.rs index 6786d7c..62ead0f 100644 --- a/src/review/filesystem.rs +++ b/src/review/filesystem.rs @@ -298,7 +298,6 @@ pub fn remove_output(path: &Path, tree: &artifacts::Tree) -> Result<()> { Path::new(""), tree, flags, - &mut std::collections::HashSet::new(), )?; Ok::<(), anyhow::Error>(()) })(); @@ -337,7 +336,6 @@ fn remove_tree( relative: &Path, tree: &artifacts::Tree, flags: rustix::fs::OFlags, - unlinked: &mut std::collections::HashSet, ) -> Result<()> { use rustix::fs::{self, AtFlags, FileType, Mode, OFlags}; use std::os::unix::ffi::OsStrExt; @@ -379,14 +377,7 @@ fn remove_tree( finder::remove_metadata(&directory, &child)?; continue; } - remove_tree( - &directory, - &child, - &relative.join(&child), - tree, - flags, - unlinked, - )?; + remove_tree(&directory, &child, &relative.join(&child), tree, flags)?; } #[cfg(target_os = "macos")] finder::finish(parent, name, &directory)?; @@ -397,12 +388,10 @@ fn remove_tree( stat.st_mtime as u64, stat.st_mtime_nsec as u32, )); - // Unlinking one name changes ctime for the other names of the same inode. - let changed = (stat.st_ctime as i64, stat.st_ctime_nsec as i64); - if stat.st_size as u64 != expected.len - || modified != Some(expected.modified) - || (changed != expected.changed && !unlinked.contains(&expected.identity)) - { + // Metadata changes after staging (including unlinking another hard link) + // can change ctime without changing the reviewed file contents. Compare + // the bytes below and still detect changes while that comparison runs. + if stat.st_size as u64 != expected.len || modified != Some(expected.modified) { bail!("Staged file was modified: {relative:?}"); } let file = fs::openat( @@ -434,15 +423,20 @@ fn remove_tree( bail!("Staged file changed during inspection: {relative:?}"); } fs::unlinkat(parent, name, AtFlags::empty())?; - if stat.st_nlink > 1 { - unlinked.insert(expected.identity); - } } else { bail!("Unsupported staged entry: {relative:?}"); } Ok(()) } +#[cfg(all(test, unix))] +pub(super) fn test_remove_staged(parent: &Path, tree: &artifacts::Tree) -> Result<()> { + use rustix::fs::{self, Mode, OFlags}; + let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC; + let parent = fs::open(parent, flags, Mode::empty())?; + remove_tree(&parent, "payload".as_ref(), Path::new(""), tree, flags) +} + #[cfg(windows)] fn open_windows(path: &Path, allow_move: bool, read_contents: bool) -> Result { use std::os::windows::fs::OpenOptionsExt; diff --git a/src/review/filesystem/recovery.rs b/src/review/filesystem/recovery.rs index 870f1da..a24a986 100644 --- a/src/review/filesystem/recovery.rs +++ b/src/review/filesystem/recovery.rs @@ -9,6 +9,7 @@ use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; use std::io::Read; use std::path::Path; +use std::path::PathBuf; #[derive(Debug, PartialEq, Eq)] enum Entry { @@ -124,6 +125,90 @@ impl Stage { } } +/// The stage record is user-controlled evidence, not proof of provenance or completeness. +pub(crate) struct RestoreStage { + root: PathBuf, + pub(crate) path: PathBuf, + pub(crate) original: PathBuf, + stage_id: Identity, + payload_id: Identity, + note: Entry, +} + +impl RestoreStage { + pub(crate) fn inspect(root: &Path, path: &Path) -> Result { + let path = inventory::safe_dir(path)?; + let stage = Stage::open(root, &path)?; + let mut note = + finder::open_regular(&stage.dir, OsStr::new("original-path.txt"), 16 * 1024)?; + let mut value = String::new(); + (&mut note).take(16 * 1024 + 1).read_to_string(&mut value)?; + let original = PathBuf::from( + value + .strip_suffix('\n') + .context("Unrecognized stage note")?, + ); + ensure!( + original.parent() == path.parent() + && original.file_name().is_some() + && !artifacts::protected(&original) + && inventory::display(&original) == original.to_string_lossy(), + "Original path in stage note does not name an unprotected sibling" + ); + let payload = fs::openat(&stage.dir, "payload", finder::DIRECTORY, Mode::empty())?; + let payload_stat = fs::fstat(&payload)?; + ensure!( + payload_stat.st_dev == fs::fstat(&stage.dir)?.st_dev, + "Payload crosses a filesystem boundary" + ); + Ok(Self { + root: inventory::safe_dir(root)?, + path, + original, + stage_id: stat_identity(&fs::fstat(&stage.dir)?), + payload_id: stat_identity(&payload_stat), + note: Entry::file(&fs::fstat(note)?), + }) + } + + pub(crate) fn restore(self) -> Result<()> { + super::ensure_not_open(&self.path)?; + let current = Self::inspect(&self.root, &self.path)?; + ensure!( + current.stage_id == self.stage_id + && current.payload_id == self.payload_id + && current.note == self.note + && current.original == self.original, + "Stage or recorded destination changed during review" + ); + let stage = Stage::open(&self.root, &self.path)?; + ensure!( + stat_identity(&fs::fstat(&stage.dir)?) == self.stage_id, + "Stage changed during review" + ); + let payload = fs::openat(&stage.dir, "payload", finder::DIRECTORY, Mode::empty())?; + ensure!( + stat_identity(&fs::fstat(&payload)?) == self.payload_id, + "Payload changed during review" + ); + let payload_path_stat = fs::statat(&stage.dir, "payload", AtFlags::SYMLINK_NOFOLLOW)?; + ensure!( + FileType::from_raw_mode(payload_path_stat.st_mode) == FileType::Directory + && stat_identity(&payload_path_stat) == self.payload_id, + "Payload path changed during review" + ); + fs::renameat_with( + &stage.dir, + "payload", + &stage.parent, + self.original.file_name().context("Missing destination")?, + fs::RenameFlags::NOREPLACE, + ) + .context("Could not restore payload without overwriting the destination")?; + Ok(()) + } +} + fn inspect_directory( parent: &OwnedFd, name: &OsStr, @@ -226,13 +311,32 @@ pub(crate) fn run(args: &crate::cli::StageCleanupArgs) -> Result<()> { } fn run_review(args: &crate::cli::StageCleanupArgs) -> Result<()> { - let review = ReviewedStage::inspect(&args.cleanup_root, &args.stage)?; + if args.restore { + let review = RestoreStage::inspect(&args.cleanup_root, &args.stage)?; + println!("Stage record is not proof of origin or completeness. Moving remaining payload from {} to {}.", inventory::display(&review.path), inventory::display(&review.original)); + review.restore()?; + println!("Restored remaining payload; the stage and its note remain for review."); + return Ok(()); + } + let review = match ReviewedStage::inspect(&args.cleanup_root, &args.stage) { + Ok(review) => review, + Err(metadata_error) if !args.apply => { + let restore = RestoreStage::inspect(&args.cleanup_root, &args.stage) + .context(format!("Metadata cleanup unavailable: {metadata_error:#}"))?; + println!("Remaining payload: {}\nRecorded destination: {}\nThe stage record does not prove origin or completeness. Verify both paths and contents before running with --restore; an existing destination will not be overwritten.", inventory::display(&restore.path.join("payload")), inventory::display(&restore.original)); + return Ok(()); + } + Err(error) => return Err(error), + }; let label = inventory::display(&review.path); if args.apply { review.remove()?; println!("Removed metadata-only stage: {label}"); } else { println!("Metadata-only stage: {label}\nRun this command with --apply to remove it."); + if let Ok(restore) = RestoreStage::inspect(&args.cleanup_root, &args.stage) { + println!("Alternatively, inspect {} and recorded destination {} before using --restore. The record does not prove origin or completeness; an existing destination will not be overwritten.", inventory::display(&restore.path.join("payload")), inventory::display(&restore.original)); + } } Ok(()) } @@ -270,6 +374,7 @@ mod tests { stage, cleanup_root: root, apply: false, + restore: false, }, )) } @@ -321,7 +426,8 @@ mod tests { "symlink" => symlink(&outside, &candidate)?, _ => fs::hard_link(&outside, &candidate)?, } - assert!(run_review(&args).is_err()); + assert!(ReviewedStage::inspect(&args.cleanup_root, &args.stage).is_err()); + run_review(&args)?; // Previewing restore must not remove anything. assert!(outside.is_file()); } Ok(()) @@ -338,4 +444,56 @@ mod tests { assert!(run_review(&args).is_err()); Ok(()) } + + #[test] + fn restores_remaining_payload_without_deleting_stage_note() -> Result<()> { + let (_fixture, payload, args) = fixture()?; + fs::write(payload.join("remaining.txt"), b"remaining")?; + let review = RestoreStage::inspect(&args.cleanup_root, &args.stage)?; + let destination = review.original.clone(); + review.restore()?; + assert_eq!(fs::read(destination.join("remaining.txt"))?, b"remaining"); + assert!(args.stage.join("original-path.txt").is_file()); + assert!(!payload.exists()); + Ok(()) + } + + #[test] + fn restore_refuses_existing_destination_and_changed_note() -> Result<()> { + let (_fixture, payload, args) = fixture()?; + fs::write(payload.join("remaining.txt"), b"remaining")?; + let review = RestoreStage::inspect(&args.cleanup_root, &args.stage)?; + fs::create_dir(&review.original)?; + fs::write(review.original.join("existing.txt"), b"existing")?; + assert!(review.restore().is_err()); + assert_eq!( + fs::read(args.cleanup_root.join("target/existing.txt"))?, + b"existing" + ); + assert_eq!(fs::read(payload.join("remaining.txt"))?, b"remaining"); + let review = RestoreStage::inspect(&args.cleanup_root, &args.stage)?; + fs::write( + args.stage.join("original-path.txt"), + format!("{}\n", args.cleanup_root.join("different").display()), + )?; + assert!(review.restore().is_err()); + assert!(payload.exists()); + Ok(()) + } + + #[test] + fn restore_rejects_replaced_payload_and_non_sibling_destination() -> Result<()> { + let (_fixture, payload, args) = fixture()?; + let review = RestoreStage::inspect(&args.cleanup_root, &args.stage)?; + fs::rename(&payload, args.stage.join("preserved-payload"))?; + fs::create_dir(&payload)?; + assert!(review.restore().is_err()); + assert!(args + .stage + .join("preserved-payload/debug/deps/.DS_Store") + .exists()); + fs::write(args.stage.join("original-path.txt"), "/tmp/other\n")?; + assert!(RestoreStage::inspect(&args.cleanup_root, &args.stage).is_err()); + Ok(()) + } } diff --git a/src/review/history.rs b/src/review/history.rs index aa0baf0..d5a7c57 100644 --- a/src/review/history.rs +++ b/src/review/history.rs @@ -164,8 +164,13 @@ impl Delta { } pub fn label(self) -> String { + self.localized_label(false) + } + + pub fn localized_label(self, japanese: bool) -> String { let size = bytes(self.bytes); let label = match self.direction { + Direction::New if japanese => format!("新規 {size}"), Direction::New => format!("new {size}"), Direction::Up => format!("+{size}"), Direction::Down => format!("-{size}"), @@ -233,7 +238,6 @@ impl History { Self::in_directory(&format!("profile-{name}")) } - #[cfg(all(feature = "desktop", target_os = "macos"))] pub fn workspace() -> Result { Self::in_directory("workspace") } @@ -299,14 +303,105 @@ impl History { if let Some(current) = read::(&path)? { current.header.verify(root)?; if current.header.completed_at > snapshot.header.completed_at { - return Ok(()); + return self.save_inventory_summary(root, inventory, snapshot.header.completed_at) + .context("A newer latest scan was retained, but this scan's long-term summary could not be saved"); } } temp.persist(&path) .with_context(|| format!("Could not save scan history at {path:?}"))?; + // Keep one compact root total per explicit observation, rather than + // archiving every directory in each full snapshot. The existing latest + // snapshot remains usable even if this separate history write fails. + self.save_inventory_summary(root, inventory, snapshot.header.completed_at) + .context("Latest scan saved, but its long-term summary could not be saved")?; Ok(()) } + fn save_inventory_summary( + &self, + root: &Path, + inventory: &inventory::Inventory, + completed_at: DateTime, + ) -> Result<()> { + let root_row = inventory + .directories + .iter() + .find(|row| row.path == root) + .context("Scan did not contain a root total")?; + let summary = ScanSummary { + header: SnapshotHeader { + version: VERSION, + root: NativePath::from(root.as_os_str()), + completed_at, + }, + total: Observed::from(&root_row.usage), + }; + self.save_summary(root, &summary) + } + + fn series_dir(&self, root: &Path) -> PathBuf { + let snapshot = self.snapshot_path(root); + self.directory + .join("series") + .join(snapshot.file_stem().expect("snapshot name")) + } + + fn save_summary(&self, root: &Path, summary: &ScanSummary) -> Result<()> { + let dir = self.series_dir(root); + fs::create_dir_all(&dir)?; + let mut temp = NamedTempFile::new_in(&dir)?; + serde_json::to_writer(&mut temp, summary)?; + temp.write_all(b"\n")?; + temp.as_file().sync_all()?; + let filename = format!( + "{}-{}.json", + summary.header.completed_at.format("%Y%m%dT%H%M%S%9fZ"), + uuid::Uuid::new_v4() + ); + temp.persist_noclobber(dir.join(filename))?; + Ok(()) + } + + fn summaries(&self, root: &Path, limit: usize) -> Result> { + use std::cmp::Reverse; + use std::collections::BinaryHeap; + if limit == 0 { + return Ok(Vec::new()); + } + let dir = self.series_dir(root); + let entries = match fs::read_dir(&dir) { + Ok(entries) => entries, + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + // Keep only the newest requested paths even after years of scans. + let mut paths = BinaryHeap::new(); + for entry in entries { + let entry = entry?; + if entry.file_type()?.is_file() + && entry.path().extension().is_some_and(|ext| ext == "json") + { + let path = entry.path(); + if paths.len() < limit { + paths.push(Reverse(path)); + } else if paths.peek().is_some_and(|oldest| path > oldest.0) { + paths.pop(); + paths.push(Reverse(path)); + } + } + } + paths + .into_sorted_vec() + .into_iter() + .map(|path| path.0) + .map(|path| { + let summary: ScanSummary = read(&path)?.context("Scan summary disappeared")?; + summary.header.verify(root)?; + Ok(summary) + }) + .collect() + } + fn snapshot_path(&self, root: &Path) -> PathBuf { // A stable FNV-1a key keeps filenames short. The stored root is checked before use. let hash = root @@ -320,6 +415,90 @@ impl History { } } +#[derive(Deserialize, Serialize)] +struct ScanSummary { + header: SnapshotHeader, + total: Observed, +} + +#[cfg(all(feature = "desktop", target_os = "macos"))] +pub(super) struct HistoryPoint { + pub completed_at: DateTime, + pub logical_bytes: u64, + pub allocated_bytes: Option, + pub partial: bool, +} + +#[cfg(all(feature = "desktop", target_os = "macos"))] +pub(super) fn load_timeline( + root: &Path, + profile: Option<&str>, + limit: usize, +) -> Result> { + let store = match profile { + Some(name) => History::open(name)?, + None => History::workspace()?, + }; + store.timeline(root, limit) +} + +#[cfg(all(feature = "desktop", target_os = "macos"))] +impl History { + fn timeline(&self, root: &Path, limit: usize) -> Result> { + Ok(self + .summaries(root, limit)? + .into_iter() + .map(|entry| HistoryPoint { + completed_at: entry.header.completed_at, + logical_bytes: entry.total.logical_bytes, + allocated_bytes: entry.total.allocated_bytes, + partial: entry.total.partial, + }) + .collect()) + } +} + +pub(crate) fn run(args: &crate::cli::ReviewHistoryArgs) -> Result<()> { + use crate::cli::ListFormat; + anyhow::ensure!(args.root.is_absolute(), "Root must be an absolute path"); + // A removed workspace can still be inspected by its original absolute path. + let root = match args.root.canonicalize() { + Ok(root) => root, + Err(err) if err.kind() == io::ErrorKind::NotFound => args.root.clone(), + Err(err) => return Err(err.into()), + }; + let history = match &args.profile { + Some(name) => History::open(name)?, + None => History::workspace()?, + }; + let records = history.summaries(&root, usize::from(args.limit))?; + match args.format { + ListFormat::Json => println!("{}", serde_json::to_string_pretty(&records)?), + ListFormat::Text => { + if records.is_empty() { + println!("No recorded scan totals for this root. Earlier snapshots are not reconstructed."); + } + for record in records { + println!( + "{} · logical {} bytes · allocated {} · {}", + record.header.completed_at, + record.total.logical_bytes, + record + .total + .allocated_bytes + .map_or_else(|| "unavailable".to_owned(), |n| format!("{n} bytes")), + if record.total.partial { + "partial scan" + } else { + "complete scan" + } + ); + } + } + } + Ok(()) +} + fn read(path: &Path) -> Result> { let file = match File::open(path) { Ok(file) => file, @@ -338,6 +517,19 @@ mod tests { use super::*; use crate::review::inventory::{Inventory, Row, Usage}; + #[test] + fn new_growth_label_respects_language_and_partial_status() { + let delta = Delta { + direction: Direction::New, + bytes: 1024, + partial: true, + basis: Basis::Logical, + }; + assert!(delta.localized_label(true).starts_with("新規 ")); + assert!(delta.localized_label(true).ends_with('*')); + assert!(delta.label().starts_with("new ")); + } + fn row(path: PathBuf, logical: u64, allocated: Option, skipped: u64) -> Row { Row { path, @@ -351,6 +543,171 @@ mod tests { } } + #[test] + fn compact_series_keeps_independent_roots_partial_status_and_limit() -> Result<()> { + let temp = tempfile::tempdir()?; + let history = History { + directory: temp.path().join("snapshots"), + }; + let first = temp.path().join("first"); + let second = temp.path().join("second"); + assert!(history.summaries(&first, 20)?.is_empty()); + let inventory = |root: &Path, size, allocated, skipped| Inventory { + directories: vec![row(root.to_owned(), size, allocated, skipped)], + matches: Vec::new(), + omitted_matches: 0, + cargo_marker_dirs: Default::default(), + }; + history.record(&first, &inventory(&first, 50, Some(100), 0))?; + history.record(&second, &inventory(&second, 1000, Some(2048), 0))?; + history.record(&first, &inventory(&first, 70, None, 2))?; + let first_records = history.summaries(&first, 20)?; + assert_eq!(first_records.len(), 2); + assert_eq!(first_records[0].total.logical_bytes, 70); + assert!(first_records[0].total.allocated_bytes.is_none()); + assert!(first_records[0].total.partial); + assert_eq!(first_records[1].total.allocated_bytes, Some(100)); + assert!(!first_records[1].total.partial); + assert_eq!(history.summaries(&first, 1)?.len(), 1); + assert_eq!(history.summaries(&second, 20)?[0].total.logical_bytes, 1000); + #[cfg(all(feature = "desktop", target_os = "macos"))] + { + let points = history.timeline(&first, 100)?; + assert_eq!(points.len(), 2); + assert_eq!(points[0].logical_bytes, 70); + assert_eq!(points[0].allocated_bytes, None); + assert!(points[0].partial); + assert_eq!(points[1].allocated_bytes, Some(100)); + assert!(!points[1].partial); + assert!(history + .timeline(&temp.path().join("missing"), 100)? + .is_empty()); + } + assert_eq!( + history + .previous(&first)? + .unwrap() + .delta(&row(first.clone(), 75, None, 0)) + .unwrap() + .signed_bytes(), + 5 + ); + Ok(()) + } + + #[test] + fn series_uses_fixed_precision_chronological_order_and_rejects_wrong_root() -> Result<()> { + let temp = tempfile::tempdir()?; + let history = History { + directory: temp.path().join("snapshots"), + }; + let root = temp.path().join("root"); + let summary = |when: &str, name: &Path, bytes| ScanSummary { + header: SnapshotHeader { + version: VERSION, + root: NativePath::from(name.as_os_str()), + completed_at: when.parse().unwrap(), + }, + total: Observed { + logical_bytes: bytes, + allocated_bytes: None, + partial: false, + }, + }; + history.save_summary(&root, &summary("2026-01-01T00:00:00.123Z", &root, 1))?; + history.save_summary(&root, &summary("2026-01-01T00:00:00.123001Z", &root, 2))?; + assert_eq!(history.summaries(&root, 2)?[0].total.logical_bytes, 2); + history.save_summary(&root, &summary("2026-01-01T00:00:00.123Z", &root, 1))?; + assert_eq!(history.summaries(&root, 10)?.len(), 3); + history.save_summary( + &root, + &summary("2027-01-01T00:00:00Z", &temp.path().join("other"), 3), + )?; + assert!(history.summaries(&root, 1).is_err()); + #[cfg(all(feature = "desktop", target_os = "macos"))] + assert!(history.timeline(&root, 1).is_err()); + Ok(()) + } + + #[test] + fn older_observation_keeps_latest_snapshot_and_records_its_total() -> Result<()> { + let temp = tempfile::tempdir()?; + let history = History { + directory: temp.path().join("snapshots"), + }; + let root = temp.path().join("root"); + let inventory = |size| Inventory { + directories: vec![row(root.clone(), size, Some(size), 0)], + matches: Vec::new(), + omitted_matches: 0, + cargo_marker_dirs: Default::default(), + }; + history.record(&root, &inventory(50))?; + let path = history.snapshot_path(&root); + let mut latest: serde_json::Value = serde_json::from_reader(File::open(&path)?)?; + latest["header"]["completed_at"] = serde_json::json!("2099-01-01T00:00:00Z"); + fs::write(path, serde_json::to_vec(&latest)?)?; + history.record(&root, &inventory(80))?; + assert_eq!(history.summaries(&root, 10)?.len(), 2); + assert_eq!( + history + .previous(&root)? + .unwrap() + .delta(&row(root.clone(), 55, Some(55), 0)) + .unwrap() + .signed_bytes(), + 5 + ); + Ok(()) + } + + #[test] + fn summary_failure_reports_error_but_keeps_latest_snapshot() -> Result<()> { + let temp = tempfile::tempdir()?; + let history = History { + directory: temp.path().join("snapshots"), + }; + let root = temp.path().join("root"); + fs::create_dir_all(&history.directory)?; + fs::write(history.directory.join("series"), b"not a directory")?; + let inventory = Inventory { + directories: vec![row(root.clone(), 50, Some(100), 0)], + matches: Vec::new(), + omitted_matches: 0, + cargo_marker_dirs: Default::default(), + }; + let err = history.record(&root, &inventory).unwrap_err(); + assert!(format!("{err:#}").contains("long-term summary")); + assert!(history.previous(&root)?.is_some()); + Ok(()) + } + + #[test] + fn old_snapshot_remains_readable_without_inventing_series() -> Result<()> { + let temp = tempfile::tempdir()?; + let history = History { + directory: temp.path().join("snapshots"), + }; + let root = temp.path().join("root"); + let rows = vec![row(root.clone(), 50, Some(100), 0)]; + let snapshot = SnapshotOutput { + header: SnapshotHeader { + version: VERSION, + root: NativePath::from(root.as_os_str()), + completed_at: Utc::now(), + }, + directories: DirectoryObservations { + root: &root, + rows: &rows, + }, + }; + fs::create_dir_all(&history.directory)?; + serde_json::to_writer(File::create(history.snapshot_path(&root))?, &snapshot)?; + assert!(history.previous(&root)?.is_some()); + assert!(history.summaries(&root, 20)?.is_empty()); + Ok(()) + } + #[test] fn updates_only_the_scanned_root_and_preserves_loaded_base() -> Result<()> { let temp = tempfile::tempdir()?; @@ -419,7 +776,10 @@ mod tests { history.record( temp.path(), &Inventory { - directories: vec![row(odd_path.clone(), 3, None, 0)], + directories: vec![ + row(temp.path().to_owned(), 3, None, 0), + row(odd_path.clone(), 3, None, 0), + ], matches: Vec::new(), omitted_matches: 0, cargo_marker_dirs: Default::default(), diff --git a/src/review/mod.rs b/src/review/mod.rs index 18d50bb..b1c68a6 100644 --- a/src/review/mod.rs +++ b/src/review/mod.rs @@ -10,6 +10,7 @@ mod filesystem; pub(crate) use filesystem::recovery::run as recover_stage; mod git; mod history; +pub(crate) use history::run as review_history; mod inventory; pub mod kube; mod message; diff --git a/src/review/sdk_cleanup.rs b/src/review/sdk_cleanup.rs index bbeacfa..aee9e0e 100644 --- a/src/review/sdk_cleanup.rs +++ b/src/review/sdk_cleanup.rs @@ -68,8 +68,127 @@ impl Review { } pub fn apply(self) -> Result { - let machine = Machine::open(&self.roots)?; - apply_selection(self, &machine) + let started = Utc::now(); + let identifiers: Vec<_> = self + .items + .iter() + .map(|item| history_identifier(&item.target)) + .collect(); + let result = Machine::open(&self.roots).and_then(|machine| apply_selection(self, &machine)); + let receipt = match result { + Ok(receipt) => receipt, + Err(error) => { + #[cfg(not(test))] + { + let targets = identifiers + .iter() + .map(|identifier| super::cleanup_history::OperationTarget { + identifier: identifier.clone(), + status: "held".into(), + reason: Some("Preflight failed; no uninstall was started".into()), + remaining_image_bytes: None, + }) + .collect(); + if let Err(history_error) = super::cleanup_history::save_operation( + started, + None, + None, + super::cleanup_history::Operation { + kind: "sdk_uninstall".into(), + retention_days: None, + targets, + }, + ) { + return Err(error.context(format!( + "Could not save cleanup history: {history_error:#}" + ))); + } + } + return Err(error); + } + }; + #[cfg(not(test))] + let mut receipt = receipt; + #[cfg(not(test))] + { + let targets = history_targets(&identifiers, &receipt.results); + receipt.history_error = super::cleanup_history::save_operation( + started, + Some(receipt.before), + receipt.after.as_ref().ok().copied(), + super::cleanup_history::Operation { + kind: "sdk_uninstall".into(), + retention_days: None, + targets, + }, + ) + .err() + .map(|error| format!("{error:#}")); + } + #[cfg(test)] + let _ = (started, identifiers); + Ok(receipt) + } +} + +fn history_targets( + identifiers: &[String], + results: &[(String, Result)], +) -> Vec { + identifiers + .iter() + .zip(results) + .map(|(identifier, (_, result))| { + use super::cleanup_history::OperationTarget; + let (status, reason, remaining_image_bytes) = match result { + Ok(Removal::Removed) => ("removed", None, None), + Ok(Removal::Partial { image_bytes }) => ( + "partial", + Some("Runtime registration, path, or image remains".into()), + *image_bytes, + ), + Ok(Removal::Unverified) => ( + "unverified", + Some("Removal could not be verified".into()), + None, + ), + Err(error) => { + let reason = match error.to_string().as_str() { + "Skipped because the previous removal was not confirmed" => { + "Skipped because the previous removal was not confirmed" + } + "Use or installation changed after review" => { + "Use or installation changed after review" + } + _ => "Operation failed or was held; details were not retained", + }; + ("unverified", Some(reason.into()), None) + } + }; + OperationTarget { + identifier: identifier.clone(), + status: status.into(), + reason, + remaining_image_bytes, + } + }) + .collect() +} + +fn history_identifier(target: &Target) -> String { + let safe = |value: &str| { + value.len() <= 80 + && value + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_')) + }; + match target { + Target::Runtime { image, .. } => format!("Xcode runtime image {image}"), + Target::ResidualRuntime { build, .. } if safe(build) => { + format!("Xcode runtime build {build}") + } + Target::Ndk { version, .. } if safe(version) => format!("Android NDK {version}"), + _ => "SDK version (identifier unavailable)".into(), } } @@ -77,6 +196,7 @@ pub(super) struct Receipt { pub before: u64, pub after: Result, pub results: Vec<(String, Result)>, + pub history_error: Option, } #[derive(Debug, PartialEq, Eq)] @@ -126,6 +246,7 @@ fn apply_selection(review: Review, machine: &impl Backend) -> Result { before, after: machine.free(), results, + history_error: None, }) } @@ -1015,6 +1136,37 @@ fn missing(error: &anyhow::Error) -> bool { #[cfg(test)] mod tests { use super::*; + + #[test] + fn history_keeps_partial_and_unverified_results_without_error_contents() -> Result<()> { + let ids = vec!["one".into(), "two".into(), "three".into(), "four".into()]; + let results = vec![ + ("ignored".into(), Ok(Removal::Removed)), + ( + "ignored".into(), + Ok(Removal::Partial { + image_bytes: Some(123), + }), + ), + ("ignored".into(), Ok(Removal::Unverified)), + ("ignored".into(), Err(anyhow::anyhow!("secret-detail"))), + ]; + let targets = history_targets(&ids, &results); + assert_eq!( + targets + .iter() + .map(|target| target.status.as_str()) + .collect::>(), + ["removed", "partial", "unverified", "unverified"] + ); + assert_eq!(targets[1].remaining_image_bytes, Some(123)); + assert_eq!( + targets[1].reason.as_deref(), + Some("Runtime registration, path, or image remains") + ); + assert!(!serde_json::to_string(&targets)?.contains("secret-detail")); + Ok(()) + } use std::cell::RefCell; use std::collections::VecDeque; diff --git a/src/review/stale.rs b/src/review/stale.rs index 5d0605a..79bae94 100644 --- a/src/review/stale.rs +++ b/src/review/stale.rs @@ -102,13 +102,19 @@ struct Matches { unknown_age: usize, } +#[derive(Clone, Copy)] +enum ScanMode { + Cli, + Personal { include_outputs: bool }, +} + pub(super) fn scan( root: Option<&Path>, older_than_days: u16, min_mib: u64, sort: StaleSort, ) -> Result { - scan_scope(root, older_than_days, min_mib, sort, false) + scan_scope(root, older_than_days, min_mib, sort, ScanMode::Cli) } #[cfg(all(feature = "desktop", any(target_os = "windows", target_os = "macos")))] @@ -117,8 +123,15 @@ pub(super) fn scan_personal( days: u16, min_mib: u64, sort: StaleSort, + include_outputs: bool, ) -> Result { - scan_scope(root, days, min_mib, sort, true) + scan_scope( + root, + days, + min_mib, + sort, + ScanMode::Personal { include_outputs }, + ) } fn scan_scope( @@ -126,19 +139,12 @@ fn scan_scope( older_than_days: u16, min_mib: u64, sort: StaleSort, - personal: bool, + mode: ScanMode, ) -> Result { let home = directories::BaseDirs::new().context("Could not locate your home directory")?; let home = home.home_dir().canonicalize()?; let cutoff = SystemTime::now() - Duration::from_secs(u64::from(older_than_days) * 86_400); - scan_under( - &home, - root.unwrap_or(&home), - cutoff, - min_mib, - sort, - personal, - ) + scan_under(&home, root.unwrap_or(&home), cutoff, min_mib, sort, mode) } fn scan_under( @@ -147,13 +153,19 @@ fn scan_under( cutoff: SystemTime, min_mib: u64, sort: StaleSort, - personal: bool, + mode: ScanMode, ) -> Result { + let exclude_outputs = matches!( + mode, + ScanMode::Personal { + include_outputs: false + } + ); let root = inventory::home_scan_dir(home, root)?; if root.strip_prefix(home)?.iter().any(excluded) { bail!("Choose a folder under your home directory outside hidden or Library directories"); } - if personal + if exclude_outputs && root .ancestors() .take_while(|p| *p != home) @@ -172,13 +184,7 @@ fn scan_under( .standard_filters(false) .follow_links(false) .same_file_system(true) - .filter_entry(move |entry| { - entry.path() == scan_root - || !(excluded(entry.file_name()) - || (personal - && entry.file_type().is_some_and(|kind| kind.is_dir()) - && build_output(entry.path()))) - }); + .filter_entry(move |entry| entry.path() == scan_root || !excluded(entry.file_name())); walker.build_parallel().run(|| { let matches = &matches; Box::new(move |item| { @@ -192,6 +198,16 @@ fn scan_under( { return WalkState::Skip; } + // Marker checks can block on filesystem metadata. Perform them on + // the distributed directory workers rather than serially while a + // parent directory is scheduling all of its children. + if exclude_outputs + && entry.depth() != 0 + && entry.file_type().is_some_and(|kind| kind.is_dir()) + && build_output(entry.path()) + { + return WalkState::Skip; + } if !entry.file_type().is_some_and(|kind| kind.is_file()) { return WalkState::Continue; } @@ -246,11 +262,17 @@ fn scan_under( unknown_age, } = matches.into_inner().unwrap(); let ranked = ranked.map(BinaryHeap::into_sorted_vec); - let open_states: HashMap<_, _> = ranked[sort as usize] - .iter() - .take(20) - .map(|(_, _, _, path, _)| (path.clone(), open_state(path.clone()))) - .collect(); + // A separate lsof per candidate delays results. The GUI reports that + // open state was unchecked instead of waiting for those calls. + let open_states: HashMap<_, _> = if matches!(mode, ScanMode::Personal { .. }) { + HashMap::new() + } else { + ranked[sort as usize] + .iter() + .take(20) + .map(|(_, _, _, path, _)| (path.clone(), open_state(path.clone()))) + .collect() + }; let mut alternate_orders = ranked.map(|rows| { rows.into_iter() .map(|(_, Reverse(size), activity, path, dates)| Candidate { @@ -391,20 +413,37 @@ mod tests { fn personal_scan_skips_confirmed_project_outputs_but_keeps_other_targets() -> Result<()> { let tmp = tempfile::tempdir()?; let home = tmp.path().canonicalize()?; - for path in ["docs/target", "crate/target", "web/dist"] { + for path in [ + "docs/target", + "crate/target", + "web/dist", + ".hidden", + "node_modules", + "Library", + ] { fs::create_dir_all(home.join(path))?; fs::write(home.join(path).join("old.bin"), b"data")?; } fs::write(home.join("crate/Cargo.toml"), b"")?; fs::write(home.join("web/package.json"), b"{}")?; let cutoff = SystemTime::now() + Duration::from_secs(60); - let report = scan_under(&home, &home, cutoff, 0, StaleSort::Size, true)?; + let report = scan_under( + &home, + &home, + cutoff, + 0, + StaleSort::Size, + ScanMode::Personal { + include_outputs: false, + }, + )?; let files: Vec<_> = report .candidates .iter() .filter(|row| row.path.ends_with("old.bin")) .collect(); assert_eq!(files.len(), 1); + assert_eq!(files[0].open_state, "not_checked"); assert!(Path::new(&files[0].path).ends_with("docs/target/old.bin")); assert!(scan_under( &home, @@ -412,9 +451,48 @@ mod tests { cutoff, 0, StaleSort::Size, - true + ScanMode::Personal { + include_outputs: false + } ) .is_err()); + let included = scan_under( + &home, + &home, + cutoff, + 0, + StaleSort::Size, + ScanMode::Personal { + include_outputs: true, + }, + )?; + let files: Vec<_> = included + .candidates + .iter() + .filter(|row| row.path.ends_with("old.bin")) + .collect(); + assert_eq!(files.len(), 3); + assert!(files.iter().all(|row| row.open_state == "not_checked")); + let cli = scan_under(&home, &home, cutoff, 0, StaleSort::Size, ScanMode::Cli)?; + let included_paths: std::collections::BTreeSet<_> = included + .candidates + .iter() + .map(|row| row.path.as_str()) + .collect(); + let cli_paths: std::collections::BTreeSet<_> = + cli.candidates.iter().map(|row| row.path.as_str()).collect(); + assert_eq!(included_paths, cli_paths); + let selected = scan_under( + &home, + &home.join("crate/target"), + cutoff, + 0, + StaleSort::Size, + ScanMode::Personal { + include_outputs: true, + }, + )?; + assert_eq!(selected.candidates.len(), 1); Ok(()) } @@ -433,7 +511,7 @@ mod tests { SystemTime::now() + Duration::from_secs(60), 0, StaleSort::Size, - false, + ScanMode::Cli, )?; assert_eq!(report.omitted, 1); assert_eq!(report.candidates[0].logical_bytes, 101); @@ -479,17 +557,17 @@ mod tests { file.set_times(fs::FileTimes::new().set_accessed(new))?; } } - let report = scan_under(&home, &home, cutoff, 1, StaleSort::Size, false)?; + let report = scan_under(&home, &home, cutoff, 1, StaleSort::Size, ScanMode::Cli)?; let sizes: Vec<_> = report.candidates.iter().map(|r| r.logical_bytes).collect(); assert_eq!(sizes, [3 * 1024 * 1024, 2 * 1024 * 1024]); - assert!(scan_under(&home, tmp.path(), cutoff, 1, StaleSort::Size, false).is_err()); + assert!(scan_under(&home, tmp.path(), cutoff, 1, StaleSort::Size, ScanMode::Cli).is_err()); assert!(scan_under( &home, &home.join("Library"), cutoff, 1, StaleSort::Size, - false + ScanMode::Cli ) .is_err()); assert_eq!(meaningful_date(Ok(UNIX_EPOCH)), None); diff --git a/src/scan/tests.rs b/src/scan/tests.rs index aab9406..e0b738e 100644 --- a/src/scan/tests.rs +++ b/src/scan/tests.rs @@ -4,6 +4,157 @@ use crate::scan::walk::recommend; use std::path::PathBuf; use std::time::{Duration, SystemTime}; +#[cfg(windows)] +#[test] +fn equivalent_windows_drive_prefixes_remain_confined_to_ordinary_components() { + use crate::scan::walk::scope_contains; + use std::path::Path; + let check = |path: &str, scope: &str| scope_contains(Path::new(path), Path::new(scope)); + assert!(check(r"C:\work\project\target.dat", r"\\?\C:\work\project")); + assert!(check(r"\\?\C:\work\project\target.dat", r"C:\work\project")); + assert!(!check( + r"C:\work\project-other\target.dat", + r"\\?\C:\work\project" + )); + assert!(!check( + r"D:\work\project\target.dat", + r"\\?\C:\work\project" + )); + assert!(!check( + r"C:\work\project\..\private", + r"\\?\C:\work\project" + )); + assert!(!check(r"C:\work\project.\data", r"\\?\C:\work\project.")); + assert!(!check(r"C:\work\CON\data", r"\\?\C:\work\CON")); + assert!(!check(r"C:\work\CON .txt", r"\\?\C:\work")); + assert!(!check(r"C:\work\file:stream", r"\\?\C:\work")); + assert!(!check(r"work\project\target.dat", r"\\?\C:\work\project")); + assert!(!check(r"\\server\share\data", r"\\?\UNC\server\share")); + assert!(!check(r"\\.\PhysicalDrive0\data", r"\\?\C:\")); + assert!(!check(r"C:work\project", r"\\?\C:\work")); +} + +#[cfg(windows)] +#[test] +fn glob_matches_equivalent_drive_paths_without_expanding_unsafe_paths() { + use crate::scan::walk::glob_matches; + use std::path::Path; + let ordinary = globset::Glob::new(r"C:\work\project\*.txt") + .unwrap() + .compile_matcher(); + let verbatim = globset::Glob::new(r"\\?\C:\work\project\*.txt") + .unwrap() + .compile_matcher(); + assert!(glob_matches( + Path::new(r"\\?\C:\work\project\file.txt"), + |path| ordinary.is_match(path) + )); + assert!(glob_matches( + Path::new(r"C:\work\project\file.txt"), + |path| verbatim.is_match(path) + )); + assert!(!glob_matches( + Path::new(r"\\?\C:\work\project-other\file.txt"), + |path| ordinary.is_match(path) + )); + assert!(!glob_matches( + Path::new(r"\\?\C:\work\project\file.txt:stream"), + |path| ordinary.is_match(path) + )); + assert!(!glob_matches( + Path::new(r"\\?\UNC\host\share\file.txt"), + |path| ordinary.is_match(path) + )); +} + +#[cfg(windows)] +#[test] +fn canonical_scope_applies_recommendation_and_excludes_to_ordinary_scan() -> anyhow::Result<()> { + use crate::scan::walk::Scanner; + let temp = tempfile::tempdir()?; + let canonical_root = temp.path().canonicalize()?; + // Change only the prefix: temp_dir itself can contain RUNNER~1 on CI. + let ordinary_root = PathBuf::from( + canonical_root + .to_str() + .unwrap() + .strip_prefix(r"\\?\") + .unwrap(), + ); + std::fs::write(ordinary_root.join("candidate.txt"), b"candidate")?; + std::fs::create_dir(ordinary_root.join("skip"))?; + std::fs::write(ordinary_root.join("skip").join("secret.txt"), b"secret")?; + let mut rule = make_rule( + "matching scope", + canonical_root.to_str().unwrap(), + None, + None, + ); + rule.excludes = Some(vec![format!(r"{}\skip*", canonical_root.display())]); + rule.includes = Some(vec![format!(r"{}\candidate*", canonical_root.display())]); + let candidate_path = ordinary_root.join("candidate.txt"); + assert!( + crate::scan::walk::scope_contains(&candidate_path, &canonical_root), + "scope comparison failed: base={ordinary_root:?}, scope={canonical_root:?}, candidate={candidate_path:?}" + ); + let include_pattern = &rule.includes.as_ref().unwrap()[0]; + let include = globset::Glob::new(include_pattern)?.compile_matcher(); + assert!( + crate::scan::walk::glob_matches(&candidate_path, |path| include.is_match(path)), + "include comparison failed: base={ordinary_root:?}, scope={canonical_root:?}, candidate={candidate_path:?}, pattern={include_pattern:?}" + ); + let excluded_path = ordinary_root.join("skip"); + let exclude_pattern = &rule.excludes.as_ref().unwrap()[0]; + let exclude = globset::Glob::new(exclude_pattern)?.compile_matcher(); + assert!( + crate::scan::walk::glob_matches(&excluded_path, |path| exclude.is_match(path)), + "exclude comparison failed: base={ordinary_root:?}, scope={canonical_root:?}, excluded={excluded_path:?}, pattern={exclude_pattern:?}" + ); + let entries = Scanner::new(ordinary_root, vec![rule]).scan()?; + let candidate = entries + .iter() + .find(|entry| entry.path.ends_with("candidate.txt")) + .unwrap(); + assert_eq!( + candidate.recommended_action, + ActionType::Quarantine, + "candidate={:?}, rule_scope={canonical_root:?}, reason={}", + candidate.path, + candidate.reason + ); + assert_eq!(candidate.selected_action, ActionType::Keep); + assert!(!entries.iter().any(|entry| entry.path.ends_with("skip"))); + Ok(()) +} + +#[cfg(windows)] +#[test] +fn scanner_rejects_known_short_names_in_root_scopes_and_globs() { + use crate::scan::walk::Scanner; + let ordinary = PathBuf::from(r"C:\normal\workspace"); + let short = PathBuf::from(r"C:\Users\RUNNER~1\workspace"); + let message = |result: Result, crate::error::AppError>| { + let error = result.expect_err("short spelling must be rejected"); + assert!(error.to_string().contains("8.3 short name")); + }; + message(Scanner::new(short, vec![]).scan()); + message( + Scanner::new( + ordinary.clone(), + vec![make_rule("short", r"C:\RUNNER~1", None, None)], + ) + .scan(), + ); + for pattern in [r"C:\RUNNER~1\private*", r"**\RUNNER~[1-9]\**"] { + let mut rule = make_rule("glob", r"C:\normal", None, None); + rule.excludes = Some(vec![pattern.to_owned()]); + message(Scanner::new(ordinary.clone(), vec![rule]).scan()); + let mut rule = make_rule("include", r"C:\normal", None, None); + rule.includes = Some(vec![pattern.to_owned()]); + message(Scanner::new(ordinary.clone(), vec![rule]).scan()); + } +} + // Helper to create a basic rule fn make_rule(name: &str, scope: &str, older: Option, size: Option) -> Rule { Rule { diff --git a/src/scan/walk.rs b/src/scan/walk.rs index 9375170..907c966 100644 --- a/src/scan/walk.rs +++ b/src/scan/walk.rs @@ -27,6 +27,116 @@ use crate::scan::classify::determine_entry_type; use crate::config::rules::{expand_path, Rule}; use globset::{Glob, GlobSetBuilder}; +// Detect common DOS 8.3 spellings, including glob patterns that could match +// them. This is deliberately conservative and is not a complete 8.3 detector. +#[cfg(windows)] +fn looks_like_short_name(value: &str) -> bool { + value.as_bytes().windows(2).any(|pair| { + pair[0] == b'~' && (pair[1].is_ascii_digit() || matches!(pair[1], b'[' | b'?' | b'*')) + }) +} + +#[cfg(windows)] +fn reject_ambiguous_short_names(base: &Path, rules: &[Rule]) -> Result<(), AppError> { + let root_has_short_name = looks_like_short_name(&base.to_string_lossy()); + let rule_has_short_name = rules.iter().any(|rule| { + rule.scopes.iter().any(|scope| { + expand_path(scope).is_ok_and(|path| looks_like_short_name(&path.to_string_lossy())) + }) || rule + .includes + .iter() + .chain(rule.excludes.iter()) + .flatten() + .any(|pattern| looks_like_short_name(pattern)) + }); + if root_has_short_name || rule_has_short_name { + return Err(AppError::Scan("A scan path, rule scope, or glob resembles a Windows 8.3 short name. Use the long spelling so exclusions can be checked safely.".into())); + } + Ok(()) +} + +/// Compare scopes lexically. On Windows, a canonicalized local path may have a +/// verbatim drive prefix while the same path from current_dir does not. Only +/// bridge those spellings when every component has ordinary Win32 semantics; +/// do not resolve links or change the apply-time authorization checks. +#[cfg(not(windows))] +pub(crate) fn scope_contains(path: &Path, scope: &Path) -> bool { + path.starts_with(scope) +} + +#[cfg(windows)] +pub(crate) fn scope_contains(path: &Path, scope: &Path) -> bool { + path.starts_with(scope) + || match (alternate_windows_path(path), alternate_windows_path(scope)) { + (Some(_), Some(alternate_scope)) => path.starts_with(alternate_scope), + _ => false, + } +} + +#[cfg(windows)] +fn alternate_windows_path(path: &Path) -> Option { + use std::path::{Component, Prefix}; + let mut components = path.components(); + let Component::Prefix(prefix) = components.next()? else { + return None; + }; + let mut alternative = match prefix.kind() { + Prefix::Disk(drive) => PathBuf::from(format!(r"\\?\{}:\", drive as char)), + Prefix::VerbatimDisk(drive) => PathBuf::from(format!(r"{}:\", drive as char)), + _ => return None, + }; + if components.next()? != Component::RootDir { + return None; + } + for component in components { + let Component::Normal(name) = component else { + return None; + }; + let name_text = name.to_str()?; + if name_text.ends_with(['.', ' ']) + || name_text + .chars() + .any(|ch| ch.is_control() || "<>:\"/\\|?*".contains(ch)) + { + return None; + } + let stem = name_text + .split('.') + .next() + .unwrap_or_default() + .trim_end_matches(' ') + .to_ascii_uppercase(); + if matches!( + stem.as_str(), + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" + ) { + return None; + } + for prefix in ["COM", "LPT"] { + if let Some(suffix) = stem.strip_prefix(prefix) { + if matches!( + suffix, + "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" + ) { + return None; + } + } + } + alternative.push(name); + } + Some(alternative) +} + +#[cfg(not(windows))] +pub(crate) fn glob_matches(path: &Path, matches: impl Fn(&Path) -> bool) -> bool { + matches(path) +} + +#[cfg(windows)] +pub(crate) fn glob_matches(path: &Path, matches: impl Fn(&Path) -> bool) -> bool { + matches(path) || alternate_windows_path(path).is_some_and(|alternative| matches(&alternative)) +} + pub struct Scanner { base_path: PathBuf, rules: Vec, @@ -53,6 +163,8 @@ impl Scanner { } pub fn scan(&self) -> Result, AppError> { + #[cfg(windows)] + reject_ambiguous_short_names(&self.base_path, &self.rules)?; if !self.base_path.exists() { return Ok(vec![]); } @@ -65,7 +177,7 @@ impl Scanner { let applies = rule.scopes.iter().any(|s| { if let Ok(sp) = expand_path(s) { // Rule applies if we are scanning inside the scope, or the scope is inside what we are scanning - self.base_path.starts_with(&sp) || sp.starts_with(&self.base_path) + scope_contains(&self.base_path, &sp) || scope_contains(&sp, &self.base_path) } else { false } @@ -97,7 +209,7 @@ impl Scanner { .follow_links(false) .filter_entry(move |entry| { if let Some(set) = &exclude_set { - if set.is_match(entry.path()) { + if glob_matches(entry.path(), |path| set.is_match(path)) { return false; } } @@ -174,7 +286,8 @@ impl Scanner { origin: PlanOrigin::Scan, recommended_action, reason, - selected_action: recommended_action, + // Recommendations are informational until the user explicitly selects an action. + selected_action: ActionType::Keep, }); } @@ -202,7 +315,7 @@ pub(crate) fn recommend( // Check scope let in_scope = rule.scopes.iter().any(|s| { if let Ok(sp) = expand_path(s) { - path.starts_with(&sp) + scope_contains(path, &sp) } else { false } @@ -217,7 +330,8 @@ pub(crate) fn recommend( let mut matched_exclude = false; for pattern in excludes { if let Ok(glob) = Glob::new(pattern) { - if glob.compile_matcher().is_match(path) { + let matcher = glob.compile_matcher(); + if glob_matches(path, |path| matcher.is_match(path)) { matched_exclude = true; break; } @@ -233,7 +347,8 @@ pub(crate) fn recommend( let mut matched_include = false; for pattern in includes { if let Ok(glob) = Glob::new(pattern) { - if glob.compile_matcher().is_match(path) { + let matcher = glob.compile_matcher(); + if glob_matches(path, |path| matcher.is_match(path)) { matched_include = true; break; } diff --git a/src/tui/render.rs b/src/tui/render.rs index c5f77bb..e1eef00 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -122,6 +122,7 @@ fn render_details(f: &mut Frame, state: &AppState, area: Rect) { Span::raw("Reason: "), Span::styled(&entry.reason, Style::default().fg(Color::Magenta)), ]), + Line::from(format!("Recommended: {:?}", entry.recommended_action)), Line::from(""), Line::from(vec![ Span::raw("Action: "), diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 649ed8f..584c57a 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -15,6 +15,15 @@ fn run_still(args: &[&str], cwd: Option<&std::path::Path>) -> std::process::Outp #[test] fn test_workflow_scan_plan_apply_dryrun() { + // Use a long-spelled temp directory on Windows; the runner's TEMP may be + // an 8.3 alias, which is intentionally rejected for rule-based scanning. + #[cfg(windows)] + let temp = { + let canonical = std::env::temp_dir().canonicalize().unwrap(); + let long = canonical.to_str().unwrap().strip_prefix(r"\\?\").unwrap(); + tempfile::tempdir_in(long).unwrap() + }; + #[cfg(not(windows))] let temp = TempDir::new().unwrap(); let root = temp.path().canonicalize().unwrap(); let root = root.as_path(); // Keep it as Path @@ -68,13 +77,34 @@ recommended_action = "Trash" "Plan missing target file" ); - // Simulate User Action: Change selected_action from Keep to Trash - // (In reality, TUI does this. For test, we edit the JSON) - let plan_modified = plan_content.replace( - r#""selected_action": "Keep""#, - r#""selected_action": "Trash""#, + // A recommendation must not select an action without the user's review. + let mut plan: serde_json::Value = serde_json::from_str(&plan_content).unwrap(); + let entries = plan["entries"].as_array_mut().unwrap(); + assert!(entries + .iter() + .all(|entry| entry["selected_action"] == "Keep")); + // Windows may report the working directory without the extended-length + // prefix returned by canonicalize. Compare the resolved files, not their + // platform-dependent string spellings. + let target_canonical = target_file.canonicalize().unwrap(); + let matching: Vec<_> = entries + .iter() + .enumerate() + .filter_map(|(index, entry)| { + let path = std::path::Path::new(entry["path"].as_str()?); + (path.canonicalize().ok().as_ref() == Some(&target_canonical)).then_some(index) + }) + .collect(); + assert_eq!( + matching.len(), + 1, + "Expected exactly one target file in the plan" ); - fs::write(&plan_path, plan_modified).unwrap(); + let target = &mut entries[matching[0]]; + assert_eq!(target["recommended_action"], "Trash"); + // Simulate explicitly selecting only this item in the TUI. + target["selected_action"] = serde_json::json!("Trash"); + fs::write(&plan_path, serde_json::to_vec_pretty(&plan).unwrap()).unwrap(); // 2. Apply --dry-run // We need --allow-outside-scope because temp dir is not in ~/Library @@ -101,7 +131,7 @@ recommended_action = "Trash" println!("Modified Plan: {}", fs::read_to_string(&plan_path).unwrap()); } assert!(stdout.contains("(Dry Run)")); - assert!(stdout.contains("Trash: 2 items")); + assert!(stdout.contains("Trash: 1 items")); assert!( target_file.exists(), @@ -109,6 +139,41 @@ recommended_action = "Trash" ); } +#[cfg(windows)] +#[test] +fn scan_rejects_ambiguous_short_name_without_overwriting_plan() { + let temp = TempDir::new().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let ambiguous = root.join("fixture~1"); + fs::create_dir(&ambiguous).unwrap(); + fs::write(ambiguous.join("candidate.dat"), vec![0u8; 200]).unwrap(); + let rules = root.join("rules.toml"); + fs::write( + &rules, + format!( + "[[rules]]\nname = \"fixture\"\nscopes = [{:?}]\nmin_size_bytes = 1\nrecommended_action = \"Trash\"\n", + root.to_str().unwrap() + ), + ).unwrap(); + let plan = root.join("existing-plan.json"); + fs::write(&plan, b"existing plan must remain").unwrap(); + let output = run_still( + &[ + "scan", + "--scope", + "custom", + "--rules", + rules.to_str().unwrap(), + "--out", + plan.to_str().unwrap(), + ], + Some(&ambiguous), + ); + assert!(!output.status.success(), "ambiguous scan should fail"); + assert!(String::from_utf8_lossy(&output.stderr).contains("8.3 short name")); + assert_eq!(fs::read(plan).unwrap(), b"existing plan must remain"); +} + #[test] fn test_safety_reject_purge_in_plan() { let temp = TempDir::new().unwrap();