From d5c7d087b66ca99d1f5ad863f6036e235b152b3e Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Sat, 14 Nov 2026 16:41:04 +0100 Subject: [PATCH 1/8] Design: AutomationPolicy for the scheduled safe clean (M01-13) --- docs/architecture/M01-13_DESIGN.md | 251 +++++++++++++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 docs/architecture/M01-13_DESIGN.md diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md new file mode 100644 index 0000000..b8f05bd --- /dev/null +++ b/docs/architecture/M01-13_DESIGN.md @@ -0,0 +1,251 @@ +# M01-13 — `AutomationPolicy` for the scheduled safe clean (design) + +Status: revision 1, **for review** (no code in this PR). Base: `main` at 800c3cd. Closes RISK-017; implements +ARCHITECTURE_V2 §3a and D-011. + +Why a design first: this changes what is deleted with nobody present and what counts as an approval, so +`.claude/CLAUDE.md` makes it a reviewed design before code (like M01-04C_DESIGN.md). It is **safety-critical** +(approval + permanent delete); the implementation PRs need the user's approval and `SAFETY-CRITICAL APPROVED`. + +## 1. Today (audited at 800c3cd) + +- **The scheduled clean does not use the executor.** `AutomationModel.tick` → `runClean(automatic: true)` → + `AutoClean.run` (`MacCleaner/Automation.swift`) → `Scanner.plan/measure/finalize` → `AutoClean.select` → + `Cleaner.run` (old direct path). No plan digest, no identity snapshot, no approval, no ledger. +- **Its scope is "everything recommended, minus exceptions".** `AutoClean.select` keeps every `CleanTarget` that is + `recommended`, `isCleanable`, not `.trash`, a file/folder action, and allowed by `SafetyGuard`/`ProtectedPaths`; + `narrowed` then drops non-allow-listed `~/.cache` tools, `DiagnosticReports` and running apps' caches. So **any new + recommended target added to `Scanner.plan()` joins the unattended clean automatically** — that is RISK-017. +- **"On" is one boolean.** `auto.weekly` (UserDefaults). It stores no scope, no version, no time of consent. Turning + it on shows no list of what will be deleted. +- **History says nothing about who approved.** `CleanupRecord` (`History.swift`) has title, bytes, outcome, + measured free change; the run is one row "Scheduled Safe Clean", no item list, no approver. +- **The executor already has a `.standingPolicy(id:version:)` approver**, and the ledger already refuses a policy + approval for any entry that isn't `safeRegenerable` + `permanentDelete` + file targets + (`CleanupPlan.swift:401`, `outsidePolicyScope`; tests `CleanupContractTests.swift:264`, `CleanupExecutorTests.swift:345`). + But nothing creates one, and the ledger knows nothing about **which** policy, its categories, its version, or + whether it is enabled. Any caller can pass any id/version string. +- Caches are not on the executor yet (M01-06). The `CleanTarget` → `CleanupCandidate` builder for caches does not exist. +- CLI and MCP never run the scheduled clean; `AutomationModel` exists only in the GUI process. + +## 2. Goals (from the roadmap row) and non-goals + +Acceptance: (a) scheduled runs only under an **explicit, versioned, revocable** policy; (b) **a code change that adds +a category does not widen an enabled policy**; (c) runs recorded with `approvedBy: .standingPolicy`. + +Non-goals: new categories or a wider scope (v1 = exactly today's effective scope, frozen); scheduled **scans**; +a rewrite of the schedule/catch-up logic (`AutoSchedule` is unchanged); moving the interactive caches clean onto +the executor (M01-06); the JSONL history store (later persistence task). + +## 3. Design + +### 3a. Model (MacCleanerCore, pure, no I/O) + +``` +AutomationPolicy { id: String ("safe-clean"), version: Int, scope: AutomationScope } +AutomationScope { rules: [ScopeRule] } // an ALLOW-list; nothing outside it is ever admitted +ScopeRule { name, selector: IDSelector, roots: [PathRoot], excludedNames: Set, + skipIfAppRunning: Bool, shapes: Set } +IDSelector = .exact(Set) | .prefix(String) // candidate.id +TargetShape = .file | .directoryContents // never .command, never .tree +AutomationScope.digest: String // SHA-256, length-prefixed, like CleanupPlan.digest +AutomationPolicy.admits(candidate:disposition:) -> Admission // .admitted | .refused(Reason) +``` + +`admits` is true only when **all** hold: `risk == .safeRegenerable`; `recommended`; disposition `.permanentDelete`; +module `"caches"`; every target is a `.file`/`.directoryContents` (no `.command`, `.tree`); a rule's selector matches +the id; **every** target path is inside one of the rule's roots (after the plan's resolved identity path), none under +an `excludedNames` component; a candidate matching no rule is `.refused(.outsideScope)`. Rules are an allow-list: +there is no "everything except". + +### 3b. Versioned, frozen catalog (what "does not widen" means) + +`AutomationCatalog.versions: [Int: AutomationPolicy]` is code. **A published version's scope never changes.** +v1 reproduces today's effective scope exactly (from `AutoClean.select` + `narrowed`): + +| v1 rule | selector | roots | notes | +|---|---|---|---| +| fixed dev caches | `.exact` of the static recommended ids in `Scanner.plan()` at 800c3cd (Xcode `xcode.derived/previews/simcaches/cache`, `npm`, `yarn`, `pnpm`, `bun`, `brew`, `pods`, `pip`, `cargo.*`, `go.modcache`, `gem.specs`, `bundler`, `nuget.http`, `hex`, `cabal`, `composer`, `jetbrains.*`, …) | each id's own folder under home | the exact list is generated once from `Scanner.plan()` during 13-1 and pinned by the golden test (§6); items with `recommended: false` (maven, ivy, nuget, conda, cocoapods repos, simulators, archives, Gradle distributions) are **not** in it | +| device support | `.prefix("xcode.ds.")` | `~/Library/Developer/Xcode/* DeviceSupport` | | +| editor caches | `.prefix("editor.")` | `~/Library/Application Support//{Cache,CachedData,logs…}` | | +| `~/.cache` tools | `.exact` of `cache.` for the 12 names in `autoDotCache` | `~/.cache/` | model caches (huggingface, torch) stay manual | +| app caches | `.prefix("appcache.")`, `.prefix("container.")`, `.prefix("web.")` | `~/Library/{Caches,Containers/*/Data/Library/Caches,…}` | `skipIfAppRunning` | +| logs | `.exact("logs.user")` | `~/Library/Logs` | `excludedNames: ["DiagnosticReports"]` | + +(Prefix rules are bounded by their roots and shapes, not only by the id: a new code path inventing an `appcache.*` +id outside `~/Library/Caches` is still refused.) + +**Adding a category = adding `v2`** (a new entry; `v1` untouched). The Scanner/executor gaining a recommended target +changes nothing for an enabled v1 policy because v1 is an allow-list of ids and roots, not a filter over "recommended". +A mistake in a shipped version is fixed by **retiring** it (a `revoked: Bool` flag on the catalog entry, §3d), never by editing it. + +### 3c. Consent record (what is stored) + +Stored: `{ policyId, grantedVersion, grantedScopeDigest, grantedAt, source: .user | .migrated }`, and +`revokedAt?`. Written only by `AutomationConsentStore` (app target), called only from the Settings › Automation +toggle's confirmation. **The scope itself is never read from storage.** At each run the app looks up +`catalog[grantedVersion]`, recomputes its digest and requires it to equal `grantedScopeDigest`; any mismatch, +unknown version or retired version → **fail closed**: the run does not happen, the policy shows "paused", the user +is notified once. (This catches a bad downgrade/edit of the app's own code and a corrupted store. It is not a defense +against another process running as the user rewriting the store; see §8.) + +**Granting** is explicit: turning the schedule on (or re-enabling) opens a sheet that lists the categories and +folders of the version being granted ("Mac Cleaner will delete these caches without asking each time"), plus what +is never touched (Trash, Downloads, anything protected, commands, review items), with an **Enable** button. The +schedule (frequency/time) is not part of the policy; changing it needs no new consent (`armedAt` behaviour unchanged). + +**When a newer catalog version exists** (an app update added a category): the enabled policy **keeps running its granted +version** — the new category is not added — and Settings shows "A newer scope is available: *review*". Reviewing +shows the diff against the granted version; the user can enable it (new consent record) or ignore it. Alternative +(pause until reviewed) is Open question 1. + +**Revoking** (toggle off, or "Revoke"): writes `revokedAt`, cancels an in-flight run (§3e), and the schedule never +runs again until a new grant. Re-enabling is a new consent record, never an un-revoke. + +### 3d. Executor and ledger changes (`MacCleanerFeatures` / `Core`, safety-critical) + +- New `CleanupExecutor.approve(_ plan:, under policy: AutomationPolicy, lifetime:)`: for **every** entry calls + `policy.admits`; if any entry is refused, throws `IssueRefusal.outsidePolicyScope(candidateID:)` and issues nothing. + It then issues `.standingPolicy(id: policy.id, version: policy.version)`. The approval is single-use, bound to the + plan digest, short-lived (default 10 min, well under `maxLifetime`), per process, as for every approval. +- The free-form `approve(_, by: .standingPolicy(...))` is **refused** from then on (`IssueRefusal.useAutomationPolicy`), + so no caller can mint a policy approval with an invented id/version or without `admits`. The ledger's existing generic + check stays as a second line. +- `AutomationPolicy` has no public initializer outside `AutomationCatalog` (like `CleanupApproval`), so app code + can't construct a wider policy; it can only fetch `AutomationCatalog.policy(version:)`. +- "Enabled" and "revoked" are app state, not Core: the **scheduled runner** is the only caller and checks consent + before calling `approve`. To make revocation stop a run between items, the runner passes the executor's existing + `precondition` closure that reads a lock-protected `PolicyGate` (set on revoke); it returns a reason, the executor + skips every later item untouched (existing `preconditionFailed` behaviour). Task cancellation also stops the run + (existing `.cancelled`). +- Running-app skip moves from select time to **execution time**: the same `precondition` re-checks "is the app that + owns this folder running?" right before each item (`skipIfAppRunning`). + +### 3e. The scheduled run (app target) + +1. `tick` finds the schedule due (unchanged) and consent valid (§3c); otherwise stops (paused/revoked/off). +2. Plan: scan targets as today (`Scanner.plan/measure/finalize`), build `CleanupCandidate`s through the **caches + builder** (`.removeContents` → `.directoryContents(folder, kids)`, `.removeItem(s)` → `.file`, identities + snapshotted now), keep only candidates `policy.admits`; build a `CleanupPlan` of those, disposition + `.permanentDelete`. +3. `executor.approve(plan, under: policy)` → `execute(plan, approval:, precondition:, progress:)`. Same guards as an + interactive run: protection, identity revalidation, nothing followed through links; anything changed, protected + or added after the snapshot is skipped and reported. The snapshot is taken seconds before the run, so the + review-to-run window is far smaller than interactive. +4. Record (§3f), notify, `check()`, `refreshNextRun()` as today. + +### 3f. History + +`CleanupRecord` gains two **optional, backward-compatible** fields: `approvedBy: ApprovalRecord?` +(`{ kind: "standingPolicy", policyId, version }`; also `userInApp`, … later) and `items: [RecordItem]?` +(path, outcome per item: removed / skipped(reason) / failed). The scheduled run's row is titled "Scheduled Safe +Clean", `outcome: .deleted`, and lists **every** item, as §3a of ARCHITECTURE_V2 requires. A skipped item +(changed, protected, app running) is listed as skipped, not counted as freed. Freed bytes are the estimate plus +`measuredFreeChange`, as in 04c. Old records decode unchanged (nil). When the JSONL history store lands, the same +fields move with it. + +### 3g. The CLI and MCP cannot create or widen a policy + +By construction: no consent-store write API outside the Settings sheet's code path; `AutomationModel` and the +scheduler exist only in the GUI process; the ledger is per-process, so an approval made in the app can never be +redeemed by a CLI/MCP process; MCP/CLI have no tool that runs the scheduled clean or edits consent. +Enforced by `scripts/check-approval-sites.sh` (extended in 13-2): `.standingPolicy` / `approve(_:under:)` only in the +package and the one runner file; `AutomationConsentStore.grant` only from the Settings sheet file and the self-test; +`AutomationCatalog` lookup only from those; nothing under the MCP/CLI files. + +## 4. Safety walk-through + +| Situation | Result | +|---|---| +| New recommended cache added to `Scanner.plan()` | not in v1's ids/roots → `outsideScope`, not planned | +| App update adds a category as v2 | enabled v1 keeps running v1; v2 needs a new reviewed grant | +| `grantedScopeDigest` ≠ catalog digest, version unknown or retired | no run, "paused", one notification | +| A folder swapped for a symlink / replaced / newly protected between snapshot and delete | executor revalidation skips it (as interactive) | +| App owning a cache starts after the snapshot | `precondition` skips it | +| User turns it off mid-run | `PolicyGate` + cancellation stop before the next item; earlier items stay deleted, reported | +| A command / review / user-data / Trash item reaches the plan | `admits` refuses; ledger's generic check refuses again | +| Any other caller asks for `.standingPolicy` | refused (`useAutomationPolicy`) | +| Two runs for one slot, or run right after enabling | unchanged `isDue`/`armedAt` rules | +| Mac asleep at the slot | catch-up on wake, unchanged | + +## 5. Migration of existing installs + +Users with `auto.weekly == true` have no consent record. **Recommended:** fail closed — the schedule stays configured +but is *paused*; one notification ("Scheduled clean needs your OK again — see what it covers") and Settings shows the +scope sheet; **Enable** records a consent with `source: .user`. Cost: cleans stop until the user acts once. Alternative: +auto-grant v1 with `source: .migrated` because v1 equals what they already had (Open question 2). `auto.weekly` +remains the schedule's on/off switch for backward compatibility; consent is a separate, additional condition. + +## 6. Tests + +Package (Swift Testing), no real home: `AutomationPolicyTests` in Core, executor tests in Features. + +- **Scope:** every v1 rule admits its cases and refuses `.command`, `.tree`, `.trash`/`.overwriteThenDelete` + dispositions, non-`safeRegenerable`, non-`recommended`, a path outside its root, an `excludedNames` component + (`DiagnosticReports`), an empty target list. +- **Golden digest:** v1's `digest` and its rule list are pinned in the test; changing v1 in place fails the test + ("bump the version instead"). A second test asserts versions are append-only (every `n` in `1...max` exists). +- **Does not widen:** a synthetic catalog with v1 and v2 (v2 adds a category) → a v2-only candidate is refused under v1; + a candidate added to a fake scanner list that is "recommended" but not in v1 is refused. +- **Approval path:** `approve(under:)` throws, issuing nothing, if one entry is out of scope; success yields + `.standingPolicy(id:version:)` bound to the digest, single-use, expires; `approve(by: .standingPolicy)` is refused; + a ledger with an out-of-scope entry still refuses. +- **Execution:** a plan under the policy deletes the admitted real temp files; a swapped/replaced/protected item is + skipped; `precondition` stops mid-run on revocation and skips the rest untouched; running-app precondition skips. +- **Consent (app, self-test with a temp home):** grant stores version + digest; digest mismatch / unknown / retired + → paused, nothing deleted; revoke → no run; re-enable = new record; migration pauses an old `auto.weekly`; + history row has `approvedBy` and lists every item incl. skipped; old records still decode. +- **Sites:** `check-approval-sites.sh` extended and its own cases (a stray `.standingPolicy` fails it). +- The existing `AutoClean.select/narrowed` self-test checks (`SelfTest.swift:294–314, 552–553, 1098–1111`) are + ported to the package's scope tests (same cases, same expectations) before `AutoClean.select` is deleted; none is + dropped without an equivalent (the 04c method). + +## 7. Staging (each its own reviewed PR; dependencies, not roadmap order) + +| Stage | What | Level | Safety-critical | +|---|---|---|---| +| **13-1** | Core `AutomationPolicy`/`Scope`/catalog v1/`admits`; `approve(under:)` + refusing the free-form policy approver; package tests incl. golden digest. **App unchanged, unused.** | Senior | **yes** | +| **13-2** | App: consent store + Settings sheet, scheduled runner on the executor, history fields, migration, sites script; remove `AutoClean.run/select/narrowed`, `Cleaner.run` use from the scheduled path. **Needs the caches candidate builder from M01-06** (or that builder is built here for the scheduled subset only — Open question 3). | Senior | **yes** | +| 13-3 | Docs: ARCHITECTURE_V2 §3a, SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS (D-011 follow-up). | Junior | no | + +13-1 depends on nothing unmerged (the ledger and executor exist). 13-2 depends on 13-1 and on M01-06's caches builder. +Hotspots 13-2 will touch: `check-approval-sites.sh`, `SelfTest.swift`, and `SelfTestSupport.swift` — it must not run +alongside another task touching them (`worktree.sh overlap`). M01-04d currently edits `ci.yml`, three architecture docs and the +warnings baseline; 13-3 must wait for it to merge to avoid editing the same docs. + +## 8. Trade-offs and limits + +1. **Frozen versions in code** cost a little growth per scope change; the benefit is that "enabled" can never mean + "whatever the latest code does". +2. **Running the old scope after an update** means a user who never reviews keeps v1 forever (safe, possibly stale). +3. **The consent store is ordinary user-writable storage.** A process running as the user can edit it (or the old + `auto.weekly` key) — but such a process can already delete the user's files directly. The policy defends against + code drift, the app's own CLI/MCP, and mistakes, not against other malware as the user. The digest check also makes a + hand-edited "version 2" or scope fail closed. +4. **Permanent delete with no review.** That is the point of a standing policy; hence the narrow, frozen, + regenerable-only scope, revalidation, full item listing and an easy off switch. There is no undo for caches; reported + honestly as "deleted", never "restorable". +5. **No per-run byte cap** in v1. A run can delete many GB of regenerable caches (same as today). A cap with "stop and + ask" is cheap to add later; it is deliberately not part of this change. +6. **Duplicate work if 13-2 builds the caches candidate builder before M01-06.** Avoided by sequencing (Open question 3). +7. **One executor per process:** the scheduled run and an interactive Trash/Shred wait for each other. Acceptable for + an infrequent background run (same note as 04c); revisit in 04d-style cleanup if it shows. +8. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had + open after the last check. + +## 9. Open questions for the reviewer + +1. **After an update adds a scope version**, an enabled policy should: **(A, recommended)** keep running the granted + version and offer a review; or (B) pause until re-enabled (matches ARCHITECTURE_V2's "must re-enable"; stricter, + but a Mac stops cleaning after every scope-adding update). ARCHITECTURE_V2 §3a wording ("the user must re-enable it + after seeing the new scope") fits A only for the *new* scope; this design updates that sentence if A is chosen. +2. **Existing users:** pause (recommended) or auto-grant v1 as `.migrated`? +3. **Sequencing:** wait for M01-06 (caches onto the executor) before 13-2 (recommended), or build the + `CleanTarget` → `CleanupCandidate` builder here for the scheduled subset only? +4. **"Run safe clean now" button** (Settings): today a confirm alert then `AutoClean.run`. Recommended: it is a + person-started run, so it opens the normal review sheet with the policy-scope items preselected and is approved + `.userInApp`, not `.standingPolicy`. Alternative: keep an alert but record `.userInApp`. +5. **History:** is adding `approvedBy` and `items` to `history.json` now acceptable, or should the scheduled run wait + for the JSONL session store? +6. **Scope drift on `skipIfAppRunning`:** acceptable that "running" is judged by `NSWorkspace` bundle id/name/executable + keys as today (best effort, not a lock)? From 62d1c50c5e5289fd15b4c650a9c2c4b1b9aba6c1 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Sun, 15 Nov 2026 18:09:37 +0100 Subject: [PATCH 2/8] M01-13 design: record review decisions --- docs/architecture/M01-13_DESIGN.md | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index b8f05bd..c5af519 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -1,6 +1,6 @@ # M01-13 — `AutomationPolicy` for the scheduled safe clean (design) -Status: revision 1, **for review** (no code in this PR). Base: `main` at 800c3cd. Closes RISK-017; implements +Status: revision 2, **for review** (no code in this PR); open questions answered with the recommended options (§9). Base: `main` at 800c3cd. Closes RISK-017; implements ARCHITECTURE_V2 §3a and D-011. Why a design first: this changes what is deleted with nobody present and what counts as an approval, so @@ -233,19 +233,13 @@ warnings baseline; 13-3 must wait for it to merge to avoid editing the same docs 8. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had open after the last check. -## 9. Open questions for the reviewer - -1. **After an update adds a scope version**, an enabled policy should: **(A, recommended)** keep running the granted - version and offer a review; or (B) pause until re-enabled (matches ARCHITECTURE_V2's "must re-enable"; stricter, - but a Mac stops cleaning after every scope-adding update). ARCHITECTURE_V2 §3a wording ("the user must re-enable it - after seeing the new scope") fits A only for the *new* scope; this design updates that sentence if A is chosen. -2. **Existing users:** pause (recommended) or auto-grant v1 as `.migrated`? -3. **Sequencing:** wait for M01-06 (caches onto the executor) before 13-2 (recommended), or build the - `CleanTarget` → `CleanupCandidate` builder here for the scheduled subset only? -4. **"Run safe clean now" button** (Settings): today a confirm alert then `AutoClean.run`. Recommended: it is a - person-started run, so it opens the normal review sheet with the policy-scope items preselected and is approved - `.userInApp`, not `.standingPolicy`. Alternative: keep an alert but record `.userInApp`. -5. **History:** is adding `approvedBy` and `items` to `history.json` now acceptable, or should the scheduled run wait - for the JSONL session store? -6. **Scope drift on `skipIfAppRunning`:** acceptable that "running" is judged by `NSWorkspace` bundle id/name/executable - keys as today (best effort, not a lock)? +## 9. Decisions (the reviewer chose the recommended option for each) + +1. **After an update adds a scope version:** an enabled policy keeps running its granted version and offers a review of the + new one (A). 13-3 updates ARCHITECTURE_V2 §3a: "must re-enable" applies to the *new* scope only. +2. **Existing installs:** paused until the user enables the policy once (fail closed), with one notification. +3. **Sequencing:** 13-2 waits for M01-06's caches candidate builder; this task does not build a second one. +4. **"Run safe clean now":** opens the normal review sheet with the policy-scope items preselected, approved `.userInApp`, + never `.standingPolicy`. +5. **History:** `approvedBy` and `items` are added to `history.json` now as optional fields; they move with the JSONL store later. +6. **Running-app check:** best effort by `NSWorkspace` bundle id, name and executable keys, as today; re-checked per item at execution time. From 0d7e73a7b2b8ac6c1efa86315cd58d173fb05837 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Mon, 16 Nov 2026 00:33:32 +0100 Subject: [PATCH 3/8] M01-13 design: revision 4 (review findings, byte cap, gate chain, history) --- docs/architecture/M01-13_DESIGN.md | 515 ++++++++++++++++++++--------- 1 file changed, 354 insertions(+), 161 deletions(-) diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index c5af519..d05ac1f 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -1,6 +1,7 @@ # M01-13 — `AutomationPolicy` for the scheduled safe clean (design) -Status: revision 2, **for review** (no code in this PR); open questions answered with the recommended options (§9). Base: `main` at 800c3cd. Closes RISK-017; implements +Status: revision 4, **for review** (no code in this PR). §9 records the reviewer's decisions; §10 answers their five +follow-up findings and the `mc-reviewer` findings (revision 3 was reviewed; revision 4 answers that review). Base: `main` at 800c3cd. Closes RISK-017; implements ARCHITECTURE_V2 §3a and D-011. Why a design first: this changes what is deleted with nobody present and what counts as an approval, so @@ -16,7 +17,7 @@ Why a design first: this changes what is deleted with nobody present and what co `recommended`, `isCleanable`, not `.trash`, a file/folder action, and allowed by `SafetyGuard`/`ProtectedPaths`; `narrowed` then drops non-allow-listed `~/.cache` tools, `DiagnosticReports` and running apps' caches. So **any new recommended target added to `Scanner.plan()` joins the unattended clean automatically** — that is RISK-017. -- **"On" is one boolean.** `auto.weekly` (UserDefaults). It stores no scope, no version, no time of consent. Turning +- **"On" is one boolean.** `auto.weeklyClean` (`AutoKeys.weekly`, UserDefaults). It stores no scope, no version, no time of consent. Turning it on shows no list of what will be deleted. - **History says nothing about who approved.** `CleanupRecord` (`History.swift`) has title, bytes, outcome, measured free change; the run is one row "Scheduled Safe Clean", no item list, no approver. @@ -39,207 +40,399 @@ the executor (M01-06); the JSONL history store (later persistence task). ## 3. Design -### 3a. Model (MacCleanerCore, pure, no I/O) +### 3a. Model (MacCleanerCore, pure, no I/O, no reference to app code) ``` -AutomationPolicy { id: String ("safe-clean"), version: Int, scope: AutomationScope } -AutomationScope { rules: [ScopeRule] } // an ALLOW-list; nothing outside it is ever admitted -ScopeRule { name, selector: IDSelector, roots: [PathRoot], excludedNames: Set, - skipIfAppRunning: Bool, shapes: Set } -IDSelector = .exact(Set) | .prefix(String) // candidate.id -TargetShape = .file | .directoryContents // never .command, never .tree -AutomationScope.digest: String // SHA-256, length-prefixed, like CleanupPlan.digest -AutomationPolicy.admits(candidate:disposition:) -> Admission // .admitted | .refused(Reason) +AutomationPolicy { id: String ("safe-clean"), version: Int, scope: AutomationScope, retired: Bool } +AutomationScope { rules: [ScopeRule], maxBytesPerRun: Int64 } // an ALLOW-list; nothing outside it is admitted +ScopeRule = .item(PathPattern) // the matched path itself is removed (a file or a whole folder) + | .contentsOf(PathPattern) // each reviewed entry of the matched folder is removed; the folder stays + each with excluded: [Exclusion], skipIfAppRunning: Bool +PathPattern = [Component] +Component = .literal(String) + | .oneOf(Set) + | .anyOne(excludingNames: Set, excludingPrefixes: [String], excludingExtensions: Set) + // exactly one path component; never "", ".", ".."; patterns have a fixed depth +AutomationScope.digest // SHA-256, length-prefixed, like CleanupPlan.digest +AutomationPolicy.admits(entry:, homeDevice:, tightening:) -> Admission // .admitted | .refused(Reason) ``` -`admits` is true only when **all** hold: `risk == .safeRegenerable`; `recommended`; disposition `.permanentDelete`; -module `"caches"`; every target is a `.file`/`.directoryContents` (no `.command`, `.tree`); a rule's selector matches -the id; **every** target path is inside one of the rule's roots (after the plan's resolved identity path), none under -an `excludedNames` component; a candidate matching no rule is `.refused(.outsideScope)`. Rules are an allow-list: -there is no "everything except". +**What authorizes and what can only refuse.** *Permission to delete comes only from a path matching a rule.* The +candidate's id, title and name never admit anything. Builder-supplied signals can only **refuse**: `risk` and `module` are +checked as conditions (a candidate that isn't `safeRegenerable` in module `"caches"` is refused, and both are in the +plan digest and re-checked by the ledger), and `tightening` is an input the app may add to over time, which can only add +refusals: a candidate the current scanner marks `recommended: false` (e.g. Spotify's offline-music cache), a name the +scanner's review list or "claimed" list has grown to include, and protected paths. **Tightening never widens**: with an +empty `tightening` the scope is exactly what v1 says, and every input removes admissions. This also lets a later safety +fix (a new review-only app) take effect under frozen v1 without a new version. + +`admits` is true only when **all** hold: `risk == .safeRegenerable`; module `"caches"`; disposition `.permanentDelete`; every +target is `.file` or `.directoryContents` (never `.command`, `.tree`); every target path matches a rule: a `.file` target's +path against an `.item` pattern, and for a `.directoryContents` target **the folder against a `.contentsOf` pattern and every +reviewed entry's path against the same rule's exclusions** (so `DiagnosticReports` inside a contents rule is refused); no path +has an excluded component; the target's device equals `homeDevice` (passed in; the function does no I/O); and `tightening` +refuses nothing. Anything else is `.refused(.outsideScope)`. There is no "everything except". + +**Letter case.** Literal and `oneOf` components of **allow** patterns match **exactly** on the resolved path (a look-alike +differing in case is not admitted, even on a case-insensitive volume); **exclusions are compared case-folded** (an +exclusion also catches a look-alike). Both fail toward refusing, as in SAFETY_MODEL §2a. + +**v1 never references app or Core constants** (`SafetyGuard.*`, `PermanentDeleteRules.*`, `Scanner.claimedLibraryCaches`, +`Scanner.reviewAppCaches`, `AutoClean.autoDotCache`): their values at 800c3cd are **copied as literals** into the +catalog (13-1). A regression test pins this (§6). 13-1 also checks that **every v1 rule is a subset of the executor's own +permanent-delete allow-list** (`PermanentDeleteRules`), so the scope can't name a place the executor would refuse anyway. ### 3b. Versioned, frozen catalog (what "does not widen" means) -`AutomationCatalog.versions: [Int: AutomationPolicy]` is code. **A published version's scope never changes.** -v1 reproduces today's effective scope exactly (from `AutoClean.select` + `narrowed`): +`AutomationCatalog.versions: [Int: AutomationPolicy]` is code. **A published version's scope never changes.** v1 reproduces +today's effective scope (`AutoClean.select` + `narrowed` over what `Scanner.plan()` produces at 800c3cd), plus the byte cap +(3c). Where v1 differs from today it is **narrower** and says so. `~` = home. + +| v1 rule | pattern | exclusions / notes | +|---|---|---| +| fixed dev caches | the 29 exact paths in **Appendix A** (item or contents, as `Scanner` gives them) | the 9 `recommended: false` statics (archives, Gradle wrapper, Maven, Ivy, NuGet packages, CocoaPods repos, conda) are **not** in it | +| device support | `.contentsOf(~/Library/Developer/Xcode/ DeviceSupport)` | | +| editor caches | `.item(~/Library/Application Support//)` | editor folder list copied as literals in 13-1 (golden) | +| `~/.cache` tools | `.item(~/.cache/)` | model caches (huggingface, torch) and `uv` (kept by default) stay manual | +| app caches | `.item(~/Library/Caches/)` | excluded: prefix `.`, prefix `com.apple.`, the names Scanner "claims" (`Yarn`, `Homebrew`, `CocoaPods`, `pip`, `JetBrains`, `com.apple.dt.Xcode`, `io.github.wahdanz.maccleaner`, `local.maccleaner`), and **`com.spotify.client`** (review-only today, "offline music"); `skipIfAppRunning` | +| sandboxed app caches | `.contentsOf(~/Library/Containers//Data/Library/Caches)` | container name excluded when prefix `.` or `com.apple.`; `skipIfAppRunning` | +| web / Electron caches | `.item(~/Library/Application Support//<0..3 × anyOne>/)` and the same prefix + `Service Worker/`; written out as the explicit fixed-depth patterns for 0, 1, 2 and 3 intermediate folders (Scanner's `collectWebCaches` visits depths 0–3) | top folder excluded: prefix `.`, prefix `com.apple.`, the editor folders, `MobileSync`, `CallHistoryDB`, `AddressBook`; intermediates exclude the extensions `app`, `bundle`, `framework`, `plugin` and links; `skipIfAppRunning` | +| logs | `.item(~/Library/Logs/)` | excluded: `JetBrains` (its own rule), prefix `com.apple.`, **`DiagnosticReports`** (crash reports are kept); matches Scanner, which hands `.removeItems(children of Logs)` after the same filter; loose files directly in `Logs` are children too | + +The "app caches" classes are a class **by shape**: the cache of any app installed later at an in-pattern path qualifies. That +is what v1 means, the consent sheet says so, and it is bounded by depth, literals, exclusions, `safeRegenerable`, +protection, `skipIfAppRunning` and the cap. Everything a *new code path* could add at a **new location** is refused. + +**Adding a category = adding `v2`** (a new entry; `v1` untouched). A mistake in a shipped version is fixed by +**retiring** it (`retired: true`: the policy pauses until the user grants a newer version), never by editing it. +`tightening` handles the opposite case, a *safety fix*, without a new consent. + +### 3c. Unattended byte cap + +Nobody reviews the run, so v1 has a cap: **`maxBytesPerRun = 20 GB`** (a proposal for the reviewer to confirm before 13-1; +frozen with v1 and in the scope digest; a different number is a new version). The cap is on **freed bytes as the executor +reports them**, the same measure as the history row: hard-linked content counts 0 (nothing is freed), allocated size is +used for estimates. + +- **Planning:** admitted units are taken **smallest estimate first** (ties by path), a greedy fill while the running + estimate stays within the cap; the rest are **not planned** and are listed as `deferred (over the run limit)`. Smallest-first + maximizes what the run can clean and doesn't let one rule or path order starve the others week after week. +- **Deferral granularity:** a unit is a **candidate's `.file` target** for item rules (one `~/.cache/pip` folder, one app's cache) + and **one reviewed entry** for contents rules (each entry of DerivedData is its own removal in the executor). +- **A single item bigger than the cap is never cleaned by the schedule.** It is listed each run as "larger than the run + limit, clean it from the app" rather than half-run. This is accepted (8.5). +- **Execution:** the gate counts freed bytes per entry across the run. At the cap the gate stops the run (3d): the entry + being removed finishes or is kept per the stop rule, and every later unit is `skipped(runLimit)`. Estimates are logical, the stop is on measured + removal, so a low estimate can't run past it by more than the one entry in progress. +- It only narrows today's behaviour (today there is none). Notification and history say so when it triggers. + +### 3d. Stored consent, policy approval and execution: one chain -| v1 rule | selector | roots | notes | -|---|---|---|---| -| fixed dev caches | `.exact` of the static recommended ids in `Scanner.plan()` at 800c3cd (Xcode `xcode.derived/previews/simcaches/cache`, `npm`, `yarn`, `pnpm`, `bun`, `brew`, `pods`, `pip`, `cargo.*`, `go.modcache`, `gem.specs`, `bundler`, `nuget.http`, `hex`, `cabal`, `composer`, `jetbrains.*`, …) | each id's own folder under home | the exact list is generated once from `Scanner.plan()` during 13-1 and pinned by the golden test (§6); items with `recommended: false` (maven, ivy, nuget, conda, cocoapods repos, simulators, archives, Gradle distributions) are **not** in it | -| device support | `.prefix("xcode.ds.")` | `~/Library/Developer/Xcode/* DeviceSupport` | | -| editor caches | `.prefix("editor.")` | `~/Library/Application Support//{Cache,CachedData,logs…}` | | -| `~/.cache` tools | `.exact` of `cache.` for the 12 names in `autoDotCache` | `~/.cache/` | model caches (huggingface, torch) stay manual | -| app caches | `.prefix("appcache.")`, `.prefix("container.")`, `.prefix("web.")` | `~/Library/{Caches,Containers/*/Data/Library/Caches,…}` | `skipIfAppRunning` | -| logs | `.exact("logs.user")` | `~/Library/Logs` | `excludedNames: ["DiagnosticReports"]` | - -(Prefix rules are bounded by their roots and shapes, not only by the id: a new code path inventing an `appcache.*` -id outside `~/Library/Caches` is still refused.) - -**Adding a category = adding `v2`** (a new entry; `v1` untouched). The Scanner/executor gaining a recommended target -changes nothing for an enabled v1 policy because v1 is an allow-list of ids and roots, not a filter over "recommended". -A mistake in a shipped version is fixed by **retiring** it (a `revoked: Bool` flag on the catalog entry, §3d), never by editing it. - -### 3c. Consent record (what is stored) - -Stored: `{ policyId, grantedVersion, grantedScopeDigest, grantedAt, source: .user | .migrated }`, and -`revokedAt?`. Written only by `AutomationConsentStore` (app target), called only from the Settings › Automation -toggle's confirmation. **The scope itself is never read from storage.** At each run the app looks up -`catalog[grantedVersion]`, recomputes its digest and requires it to equal `grantedScopeDigest`; any mismatch, -unknown version or retired version → **fail closed**: the run does not happen, the policy shows "paused", the user -is notified once. (This catches a bad downgrade/edit of the app's own code and a corrupted store. It is not a defense -against another process running as the user rewriting the store; see §8.) - -**Granting** is explicit: turning the schedule on (or re-enabling) opens a sheet that lists the categories and -folders of the version being granted ("Mac Cleaner will delete these caches without asking each time"), plus what -is never touched (Trash, Downloads, anything protected, commands, review items), with an **Enable** button. The -schedule (frequency/time) is not part of the policy; changing it needs no new consent (`armedAt` behaviour unchanged). - -**When a newer catalog version exists** (an app update added a category): the enabled policy **keeps running its granted -version** — the new category is not added — and Settings shows "A newer scope is available: *review*". Reviewing -shows the diff against the granted version; the user can enable it (new consent record) or ignore it. Alternative -(pause until reviewed) is Open question 1. - -**Revoking** (toggle off, or "Revoke"): writes `revokedAt`, cancels an in-flight run (§3e), and the schedule never -runs again until a new grant. Re-enabling is a new consent record, never an un-revoke. - -### 3d. Executor and ledger changes (`MacCleanerFeatures` / `Core`, safety-critical) - -- New `CleanupExecutor.approve(_ plan:, under policy: AutomationPolicy, lifetime:)`: for **every** entry calls - `policy.admits`; if any entry is refused, throws `IssueRefusal.outsidePolicyScope(candidateID:)` and issues nothing. - It then issues `.standingPolicy(id: policy.id, version: policy.version)`. The approval is single-use, bound to the - plan digest, short-lived (default 10 min, well under `maxLifetime`), per process, as for every approval. -- The free-form `approve(_, by: .standingPolicy(...))` is **refused** from then on (`IssueRefusal.useAutomationPolicy`), - so no caller can mint a policy approval with an invented id/version or without `admits`. The ledger's existing generic - check stays as a second line. -- `AutomationPolicy` has no public initializer outside `AutomationCatalog` (like `CleanupApproval`), so app code - can't construct a wider policy; it can only fetch `AutomationCatalog.policy(version:)`. -- "Enabled" and "revoked" are app state, not Core: the **scheduled runner** is the only caller and checks consent - before calling `approve`. To make revocation stop a run between items, the runner passes the executor's existing - `precondition` closure that reads a lock-protected `PolicyGate` (set on revoke); it returns a reason, the executor - skips every later item untouched (existing `preconditionFailed` behaviour). Task cancellation also stops the run - (existing `.cancelled`). -- Running-app skip moves from select time to **execution time**: the same `precondition` re-checks "is the app that - owns this folder running?" right before each item (`skipIfAppRunning`). +``` +stored consent --validate--> ValidatedPolicy + PolicyGate --approve(under:gate:)--> GatedApproval --execute--> per-entry stop + (data) (Core) (made together, at run start) (executor) (one-shot) (executor) (PolicyGate) +``` + +What enforces it, stated honestly: **access control plus the sites script**, not the type system alone. `ValidatedPolicy`, +`PolicyGate` and `GatedApproval` have initializers that are `package`-internal to MacCleanerKit (like `CleanupApproval`), so +app code can only obtain them through `AutomationConsent.validate`, `approve(under:gate:)`, and the catalog. But +`AutomationConsent` is an ordinary Codable value and `validate` is public, so an app file that builds a consent +with the current catalog digest gets a `ValidatedPolicy`. **That is stopped by `check-approval-sites.sh`** (3g), which is the +same kind of boundary as the existing approval-site check, and by review; the digest check catches +accidents and a stale or corrupted store, not code written to forge it (8.3). + +- **`AutomationConsent`** (stored): `{ policyId, grantedVersion, grantedScopeDigest, grantedAt, source: .user, revokedAt? }`. + The scope is never read from storage. Written only by `AutomationConsentStore` (app target), only from the Settings + sheet's Enable and Revoke. +- **`validate(in: catalog, now:)`** fails closed (`.revoked`, `.unknownVersion`, `.retired`, `.digestMismatch`, + `.grantedInTheFuture`) and returns the `ValidatedPolicy` **and creates its `PolicyGate`**. **The gate is created and + registered at validation, i.e. at the start of a run** (3e step 2), before the minutes-long scan and measure. The app's + `AutomationGateRegistry` (main actor) holds the live gate. A Revoke at any later moment (during scan, during + planning, during execution) flips it synchronously, no actor hop, before `revokedAt` is persisted. `approve` refuses an + inactive gate, so a revoke during the scan means nothing is approved or deleted. +- **`CleanupExecutor.approve(_ plan:, under:, gate:)`** calls `admits` for **every** entry and refuses the whole plan with + `outsidePolicyScope(candidateID:)` if one is out (the runner filters first, 3e), then issues `.standingPolicy(id:version:)` + bound to the plan digest, single-use, lifetime 10 minutes. The executor records the issued nonce **in an executor-held map + `nonce → gate`** and returns a `GatedApproval`. +- **The old entry points can't bypass it.** The public `execute(plan, approval:)` refuses any approval whose approver is + `.standingPolicy`, or whose nonce is in the gated map, with `Refusal.gateRequired`. The gated overload + `execute(plan, gated:)` looks the gate up. The free-form `approve(_, by: .standingPolicy(...))` is refused + (`IssueRefusal.useAutomationPolicy`). +- **The gate is a new input to the run loop.** Today `halt()` reads only the cancellation state and the `stopped` reason + (`CleanupExecutor.swift` `execute`), and `precondition` runs only after an item's protection check. 13-1 adds the gate to + `halt()` (so it is read before every target, including the first) and passes it down. +- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `@Sendable (Int64) -> String?` + `stop` parameter (nil for interactive runs, behaviour unchanged), called by the Platform before **each entry** with the bytes + freed so far in this item. The gate is also asked **before the item is moved into its staging folder**, so a revoke before + an item starts leaves it in place (`LocalFileSystem.remove` renames the item into staging before it visits any entry, so + without this check the item's path would be absent for the whole walk). A non-nil reason is treated like a refused + `protection` for the rest of the walk: **fail closed**; the entries not visited are kept, the folders holding them are kept and + put back with the existing machinery (the put-back already works for a non-empty folder), and the item is `.partiallyDone`. + After a revoke at most the one entry being removed completes. + - **Name retaken during the walk.** If an app recreates the item's path while the walk runs, the put-back's + `RENAME_EXCL` fails and the remainder stays in the staging folder (`~/Library/Caches/.…`). That is already how the + Platform reports it (`KeptEntry.Reason.stagingLeftBehind` with the path). Unattended, it is therefore reported in history as a kept entry with its path, and 13-1 tests it. + - **Size of the report.** A stop doesn't list every unvisited leaf: one `KeptEntry` per folder whose remaining contents + weren't visited, with the count of entries not visited in its text. + - **New Core cases (13-1):** `KeptEntry.Reason.stopped(String)`, `SkipReason.revoked`, `SkipReason.runLimit` (instead of + parsing `preconditionFailed(String)` for history), plus the `stop` parameter on every `CleanupFileSystem` conformer + (fakes included). Every exhaustive `switch` over these in Core, Features and the app changes in the same PR. +- `precondition` is kept for the per-item running-app check (3e). ### 3e. The scheduled run (app target) -1. `tick` finds the schedule due (unchanged) and consent valid (§3c); otherwise stops (paused/revoked/off). -2. Plan: scan targets as today (`Scanner.plan/measure/finalize`), build `CleanupCandidate`s through the **caches - builder** (`.removeContents` → `.directoryContents(folder, kids)`, `.removeItem(s)` → `.file`, identities - snapshotted now), keep only candidates `policy.admits`; build a `CleanupPlan` of those, disposition - `.permanentDelete`. -3. `executor.approve(plan, under: policy)` → `execute(plan, approval:, precondition:, progress:)`. Same guards as an - interactive run: protection, identity revalidation, nothing followed through links; anything changed, protected - or added after the snapshot is skipped and reported. The snapshot is taken seconds before the run, so the - review-to-run window is far smaller than interactive. -4. Record (§3f), notify, `check()`, `refreshNextRun()` as today. - -### 3f. History - -`CleanupRecord` gains two **optional, backward-compatible** fields: `approvedBy: ApprovalRecord?` -(`{ kind: "standingPolicy", policyId, version }`; also `userInApp`, … later) and `items: [RecordItem]?` -(path, outcome per item: removed / skipped(reason) / failed). The scheduled run's row is titled "Scheduled Safe -Clean", `outcome: .deleted`, and lists **every** item, as §3a of ARCHITECTURE_V2 requires. A skipped item -(changed, protected, app running) is listed as skipped, not counted as freed. Freed bytes are the estimate plus -`measuredFreeChange`, as in 04c. Old records decode unchanged (nil). When the JSONL history store lands, the same -fields move with it. +1. `tick` finds the schedule due (unchanged `isDue`/`armedAt`) and `auto.weeklyClean` on; otherwise stops. +2. **Validate the stored consent and create the gate** (3d). On `Invalid`: no scan, no deletion, one "Not run" history row for + this slot (below) and one notification per reason. +3. Plan: scan as today (`Scanner.plan/measure/finalize`), build `CleanupCandidate`s through the caches builder (M01-06; + `.removeContents` → `.directoryContents`, `.removeItem(s)` → `.file`, `.webCachesIn` → the `.removeItems` it becomes + after `measure`, the merged `appcache.small` candidate → one `.file` per path; identities snapshotted now). **Filter per + target before `approve`**: a target the policy doesn't admit is dropped from its candidate and recorded as + `skipped(outsideScope)`; a candidate left with no targets isn't planned. This is a behaviour change from + `Cleaner.run`, where a `.removeItems` list was all-or-nothing: it is now per path, which is narrower or equal. Then apply the byte cap (3c) and + build the plan, disposition `.permanentDelete`. Check the gate is still active right before `approve`. +4. `approve(under:gate:)` then `execute(plan, gated:)`: protection, identity revalidation, nothing followed through links; a changed, + protected or added-after-snapshot item is skipped and reported. The snapshot is seconds old. +5. **Running apps, fail conservative.** `skipIfAppRunning` rules skip an item when **any** of these holds: the owning app + can't be determined from the path; the running-app list can't be read (the whole class is skipped); a running app's bundle + id, name or executable name equals the folder name, starts with `.`, or the folder name starts with `.` + (helper processes `com.x.app.helper` count). Asked again before each item (`precondition`), not only at planning. + Best effort, not a lock (8.8). +6. Record (3f), notify with **measured** results, `check()`, `refreshNextRun()`. + +**Paused or refused runs.** A run that doesn't start writes at most **one "Not run" row per scheduled slot**: the runner stores +the slot it last reported (`auto.policyReportedSlot`, the `lastSlot` date) because a paused run doesn't set `lastRun` and +`tick` fires every 5 minutes. + +**Turning `auto.weeklyClean` off and on.** Off **revokes** the consent (writes `revokedAt`, flips the live gate). On does not +re-arm the old consent: it opens the Enable sheet, and the result is a new consent record. The Settings toggle is therefore no +longer bound directly to the key (today `AutomationSettings` binds `@AppStorage(AutoKeys.weekly)`, `Automation.swift:380`); the key remains the +schedule's on/off switch and is set only together with a valid consent. This is ARCHITECTURE_V2 §3a "never runs again until turned back on". + +**Run safe clean now** (decision §9.4). Today `AutomationSettings` (`Automation.swift:446`) and the menu-bar popover +(`MenuBarPopover.swift:123`) call `runClean(automatic: false)` → `AutoClean.run` after a plain confirm alert. 13-2 replaces both +with the normal review sheet, policy-scope items preselected, approved `.userInApp`; `runClean(automatic:)` and `AutoClean.run` +are then deleted. It has its own stage entry and self-test (§6, §7). + +### 3f. History: every state the run can end in + +`CleanupRecord` gains **optional, backward-compatible** fields (old records decode unchanged; `history.json`, shared file lock as today): + +- `approvedBy: ApprovalRecord?` = `{ kind: "standingPolicy", policyId, version }` (later also the other approvers). +- `runStatus: String?` and `statusDetail: String?`. A **string**, not an enum with payloads: an older build or the CLI/MCP + reading a status it doesn't know shows it as text and doesn't drop the record. Values: `running`, `completed`, `partial`, + `cancelled`, `stoppedRevoked`, `stoppedRunLimit`, `failed`, `notRun`, `interrupted`. +- `items: [RecordItem]?` and `itemCounts: [String: Int]?`. **What is listed:** every candidate/unit that was **not removed** + (skipped with its reason, kept entries with their reason and path, failed, permission denied, deferred over the run limit, + outside scope) is listed **individually**, and each **removed** candidate is one row with its entry count and bytes. Exact + counts per result are always stored. Item results: `removed`, `partiallyDone`, `skipped(changed | protected | appRunning | + missing | addedAfterReview | cancelled | revoked | runLimit | outsideScope | preconditionFailed)`, `deferred(overRunLimit)`, + `permissionDenied`, `failed`. +- `bytes` = the sum over `removed` and `partiallyDone` freed bytes, **never the planned size** (today `AutoClean.run` adds a + target's whole planned size whenever `Cleaner.run` returns no error, which overstates a run that skipped anything). + `measuredFreeChange` stays a separate measurement. +- `outcome` is `.deleted` only when something was permanently removed; a `notRun` or fully skipped row has `outcome == nil` + and 0 bytes (so `totalDeleted` is unaffected). + +**Why not every removed entry:** `history.json` keeps the last 300 records (`History.swift`, `insert`) and rewrites the whole +file under the lock on each add, and the CLI and MCP decode it. A record listing 10,000 entries could mean millions of +entries rewritten per add. Hence: candidate rows plus every exception, exact counts for the rest. **This narrows ARCHITECTURE_V2 +§3a "listing every item" to "every candidate and every item that was not removed"**; 13-3 changes that sentence, and it is +decision §9.7 for the reviewer. If a run has more than 500 non-removed items, the first 500 are listed and the rest are in +`itemCounts` with the text `N more not listed` (explicit, never silent). + +**A run that dies.** The record is created at the start with `runStatus: running` (written under the file lock before the scan) +and replaced at the end. If the app quits, crashes or the Mac sleeps in between, the next launch shows that row as +`interrupted: per-item results unknown`; per-item journaling is not added (limit 8.11). The row is never counted as freed. + +A cancelled or revoked run lists what was removed and what was left; skipped items are never counted as freed. The +notification is made from the same data ("Freed 3.2 GB; 4 items skipped" / "Stopped: you turned the policy off after 1.1 GB"). ### 3g. The CLI and MCP cannot create or widen a policy -By construction: no consent-store write API outside the Settings sheet's code path; `AutomationModel` and the -scheduler exist only in the GUI process; the ledger is per-process, so an approval made in the app can never be -redeemed by a CLI/MCP process; MCP/CLI have no tool that runs the scheduled clean or edits consent. -Enforced by `scripts/check-approval-sites.sh` (extended in 13-2): `.standingPolicy` / `approve(_:under:)` only in the -package and the one runner file; `AutomationConsentStore.grant` only from the Settings sheet file and the self-test; -`AutomationCatalog` lookup only from those; nothing under the MCP/CLI files. +By construction: no consent-store write API outside the Settings sheet's code path; `AutomationModel` and the scheduler exist +only in the GUI process; the ledger, executor map and gate are per-process, so nothing made in the app can be redeemed in a +CLI/MCP process; MCP/CLI have no tool that runs the scheduled clean or edits consent. Enforced by `scripts/check-approval-sites.sh` +(extended in 13-2; this file is a hotspot, see §7): `.standingPolicy`, `approve(_:under:`, `execute(_:gated:`, `PolicyGate` and +`AutomationConsent.validate` only in the package and the one runner file; `AutomationConsentStore` writes only from the Settings +sheet file and the self-test; nothing under the MCP/CLI files; no `AutomationConsent(` initializer call outside the store and the self-test. ## 4. Safety walk-through | Situation | Result | |---|---| -| New recommended cache added to `Scanner.plan()` | not in v1's ids/roots → `outsideScope`, not planned | +| New recommended cache at a new path in `Scanner.plan()` | matches no rule → `outsideScope`, dropped, listed | +| New candidate named `appcache.x` / `web.x` / `xcode.ds.x` at an unexpected path or depth | refused: ids never admit | +| `Spotify` / `com.apple.*` / claimed / `MobileSync` / `CallHistoryDB` / `AddressBook` / `DiagnosticReports` | refused by v1's own exclusions | +| The scanner later marks another app cache review-only | `tightening` refuses it under v1 with no new consent | +| `SafetyGuard`/`PermanentDeleteRules`/`Scanner` lists edited elsewhere | v1 holds literal copies; admissions unchanged (they can only tighten) | | App update adds a category as v2 | enabled v1 keeps running v1; v2 needs a new reviewed grant | -| `grantedScopeDigest` ≠ catalog digest, version unknown or retired | no run, "paused", one notification | -| A folder swapped for a symlink / replaced / newly protected between snapshot and delete | executor revalidation skips it (as interactive) | -| App owning a cache starts after the snapshot | `precondition` skips it | -| User turns it off mid-run | `PolicyGate` + cancellation stop before the next item; earlier items stay deleted, reported | +| Stored digest ≠ catalog digest, version unknown, retired or revoked | no run, "paused", reason shown, one row per slot | +| Folder swapped for a symlink / replaced / newly protected between snapshot and delete | executor revalidation skips it | +| App owning a cache starts after the snapshot, or can't be identified | skipped (`precondition`; unknown owner fails conservative) | +| User turns it off during the scan, before an item, or inside one huge folder | gate refuses `approve`, or stops before the item / next entry; rest kept and reported | +| Estimate too low, or caches are huge | stop at 20 GB freed; remaining units deferred and listed | +| One path of a merged candidate is out of scope | that path dropped and listed; the others run | | A command / review / user-data / Trash item reaches the plan | `admits` refuses; ledger's generic check refuses again | -| Any other caller asks for `.standingPolicy` | refused (`useAutomationPolicy`) | -| Two runs for one slot, or run right after enabling | unchanged `isDue`/`armedAt` rules | +| Another caller asks for `.standingPolicy`, or runs one without the gate | refused (`useAutomationPolicy`, `gateRequired`) | +| App quits mid-run | row shows `interrupted`; nothing counted as freed | +| Two runs for one slot, or a run right after enabling | unchanged `isDue`/`armedAt` rules | | Mac asleep at the slot | catch-up on wake, unchanged | ## 5. Migration of existing installs -Users with `auto.weekly == true` have no consent record. **Recommended:** fail closed — the schedule stays configured -but is *paused*; one notification ("Scheduled clean needs your OK again — see what it covers") and Settings shows the -scope sheet; **Enable** records a consent with `source: .user`. Cost: cleans stop until the user acts once. Alternative: -auto-grant v1 with `source: .migrated` because v1 equals what they already had (Open question 2). `auto.weekly` -remains the schedule's on/off switch for backward compatibility; consent is a separate, additional condition. +Users with `auto.weeklyClean == true` have no consent record. Decision (§9.2): **paused until they enable the policy**. The +schedule stays configured but does not run; one notification ("Scheduled clean needs your OK again — see what it covers"); +Settings shows the scope sheet; **Enable** records a consent. `auto.weeklyClean` remains the schedule's on/off switch for +backward compatibility; a valid consent is a separate, additional condition. Until then a paused run writes at most one +"Not run: needs your OK" row per slot (3e). ## 6. Tests -Package (Swift Testing), no real home: `AutomationPolicyTests` in Core, executor tests in Features. - -- **Scope:** every v1 rule admits its cases and refuses `.command`, `.tree`, `.trash`/`.overwriteThenDelete` - dispositions, non-`safeRegenerable`, non-`recommended`, a path outside its root, an `excludedNames` component - (`DiagnosticReports`), an empty target list. -- **Golden digest:** v1's `digest` and its rule list are pinned in the test; changing v1 in place fails the test - ("bump the version instead"). A second test asserts versions are append-only (every `n` in `1...max` exists). -- **Does not widen:** a synthetic catalog with v1 and v2 (v2 adds a category) → a v2-only candidate is refused under v1; - a candidate added to a fake scanner list that is "recommended" but not in v1 is refused. -- **Approval path:** `approve(under:)` throws, issuing nothing, if one entry is out of scope; success yields - `.standingPolicy(id:version:)` bound to the digest, single-use, expires; `approve(by: .standingPolicy)` is refused; - a ledger with an out-of-scope entry still refuses. -- **Execution:** a plan under the policy deletes the admitted real temp files; a swapped/replaced/protected item is - skipped; `precondition` stops mid-run on revocation and skips the rest untouched; running-app precondition skips. -- **Consent (app, self-test with a temp home):** grant stores version + digest; digest mismatch / unknown / retired - → paused, nothing deleted; revoke → no run; re-enable = new record; migration pauses an old `auto.weekly`; - history row has `approvedBy` and lists every item incl. skipped; old records still decode. -- **Sites:** `check-approval-sites.sh` extended and its own cases (a stray `.standingPolicy` fails it). -- The existing `AutoClean.select/narrowed` self-test checks (`SelfTest.swift:294–314, 552–553, 1098–1111`) are - ported to the package's scope tests (same cases, same expectations) before `AutoClean.select` is deleted; none is - dropped without an equivalent (the 04c method). +Package (Swift Testing), real temp directories only, never the real home: `AutomationPolicyTests` in Core, executor and +Platform tests in Features/Platform. + +- **Scope, per rule:** admits its cases; refuses `.command`, `.tree`, non-`permanentDelete` dispositions, non-`safeRegenerable`, + a path outside its pattern, one level too deep or too shallow, a link, another volume, an empty target list, a letter-case look-alike. +- **Every exclusion is its own test:** `com.spotify.client`, `com.apple.*`, a dot-name, each claimed name, `MobileSync` / + `CallHistoryDB` / `AddressBook` as an Application Support top folder, `com.apple.*` and `JetBrains` under `Logs`, + `DiagnosticReports` as a child of `Logs` **and** as a reviewed entry of a `.contentsOf` target, an `app`/`bundle`/`framework`/`plugin` intermediate. +- **Web caches:** `Application Support//Cache` (depth 0) through `/a/b/c/Cache` (depth 3) admitted, depth 4 refused; + `Service Worker/CacheStorage` and `ScriptCache` admitted at each depth; `Service Worker/Other` refused; every `webCacheNames` literal. +- **Frozen scope / the prefix finding:** (1) golden: v1's `digest` and rule list are pinned; changing v1 in place fails + ("bump the version instead"); versions are append-only. (2) Candidates named `appcache.x` at `~/Library/Caches/Foo/Bar` (too + deep), `container.x` outside `Containers//Data/Library/Caches`, `web.x` not at a web-cache name, `xcode.ds.x` at a new + folder, and `newcat.x` at a new path are all refused. (3) A candidate at an in-pattern path with an unknown id **is** admitted + (documents that ids are not authority). (4) A synthetic catalog `v1 + v2`: a v2-only candidate is refused under v1. (5) A test edits + the literal lists the app edits (a fake editor list or claimed list gains an entry) and shows v1's digest and admissions don't + change. (6) **Tightening only narrows:** with `tightening` empty the admissions equal the golden set; adding any tightening only + removes admissions (checked over the golden cases); a `recommended: false` candidate is refused. (7) Every v1 rule path is + permitted by `PermanentDeleteRules` (v1 ⊆ executor allow-list). +- **Chain:** `validate` fails closed for revoked / unknown / retired / digest mismatch / future grant, and creates the gate; + `approve(under:gate:)` throws and issues nothing if one entry is out of scope **or the gate is inactive**; `approve(by: .standingPolicy)` is + refused; `execute(plan, approval:)` with a `.standingPolicy` approval or a gated nonce is refused (`gateRequired`); single-use + and expiry as for any approval; the gate is read before the **first** target. The sites script rejects a stray consent + initializer, `validate`, `.standingPolicy` and `PolicyGate`. +- **Revocation and cap inside long work (real temp trees):** revoke **before the first item** (the item is still in place, not + in staging); revoke **during the scan** (nothing approved); revoke after N entries of one folder with thousands of entries: no entry past + N+1 removed, unvisited folders kept and put back, one `KeptEntry` per folder with the count, item `.partiallyDone` with + `stopped`; **the item's name retaken during the walk**: remainder reported as `stagingLeftBehind` with its path. The same for the + byte cap (low estimate), hard-linked content counted as 0 freed, smallest-first planning, over-cap candidates deferred and + listed, a single item over the cap never partly run. Interactive removal with `stop: nil` behaves as before (existing tests unchanged and green). +- **New Core cases:** `KeptEntry.Reason.stopped`, `SkipReason.revoked`, `SkipReason.runLimit` are produced, and every exhaustive + switch compiles and is tested (Core, Features, app). +- **Scheduled-run mapping (app self-test, temp home):** the merged `appcache.small` candidate with one out-of-pattern path: that + path dropped and listed, the others run; `.removeItems` → `.file` per path; `.webCachesIn` → the `.removeItems` produced after + `measure`; logs as `.removeItems` of children. +- **History (self-test):** rows for completed, partial (kept entries), cancelled, stoppedRevoked, stoppedRunLimit, failed, notRun, + interrupted (a `running` row left behind); `bytes` = freed only; a 0-byte run is still recorded with `outcome == nil`; skipped, + kept and deferred items are listed with reasons; counts match; more than 500 exceptions → explicit "N more not listed"; old + records decode; an unknown `runStatus` string decodes and shows; the notification text comes from the same data. +- **Running apps:** unknown owner skipped; unreadable running list skips the class; a helper-process bundle id skips its app; + asked again per item. +- **Consent and toggle:** grant stores version + digest; Revoke flips the live gate and persists `revokedAt`; **turning + `auto.weeklyClean` off then on** leaves it paused until a new Enable and never re-arms the old consent; an old + `auto.weeklyClean == true` install with no consent is paused with one notification and one row per slot (not per 5-minute tick). +- **Run safe clean now:** opens the review sheet with policy-scope items preselected, approves `.userInApp`, records `userInApp` + (never `.standingPolicy`); both call sites (Settings, menu-bar popover) use it; `AutoClean.run` is gone. +- **Ported checks:** the `AutoClean.select/narrowed` self-test checks (`SelfTest.swift:294, 304, 551–553, 1098–1111`; lines 313–326 + are `AutoSchedule` tests and stay) are ported to the package scope tests (same cases, same expectations) before + `AutoClean.select` is deleted; none dropped without an equivalent (the 04c method). ## 7. Staging (each its own reviewed PR; dependencies, not roadmap order) | Stage | What | Level | Safety-critical | |---|---|---|---| -| **13-1** | Core `AutomationPolicy`/`Scope`/catalog v1/`admits`; `approve(under:)` + refusing the free-form policy approver; package tests incl. golden digest. **App unchanged, unused.** | Senior | **yes** | -| **13-2** | App: consent store + Settings sheet, scheduled runner on the executor, history fields, migration, sites script; remove `AutoClean.run/select/narrowed`, `Cleaner.run` use from the scheduled path. **Needs the caches candidate builder from M01-06** (or that builder is built here for the scheduled subset only — Open question 3). | Senior | **yes** | -| 13-3 | Docs: ARCHITECTURE_V2 §3a, SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS (D-011 follow-up). | Junior | no | +| **13-1** | Core: `AutomationPolicy`/scope/patterns/catalog v1 (literals + Appendix A, golden file), `tightening`, `ValidatedPolicy`, `PolicyGate`, `AutomationConsent.validate`; executor `approve(under:gate:)`, nonce→gate map, `execute(_, gated:)`, `gateRequired`, `useAutomationPolicy`, gate in `halt()`; new `KeptEntry.Reason.stopped`, `SkipReason.revoked/.runLimit`; `CleanupFileSystem.remove(stop:)`, Platform walk and the pre-staging check, all conformers; package tests above. **App unchanged, unused** (the new enum cases' exhaustive switches in the app get the minimal update). | Senior | **yes** | +| **13-2** | App: consent store + Settings sheet (toggle revokes/enables), gate registry, scheduled runner on the executor with the per-target filter and cap, history fields (`running` row, statuses, items, counts), migration and per-slot "Not run" row, **"Run safe clean now" through the review sheet** (Settings + menu-bar popover), sites script, self-tests; remove `AutoClean.run/select/narrowed`, `runClean(automatic:)` and the scheduled path's `Cleaner.run` use. **Waits for M01-06's caches candidate builder** (decision §9.3). | Senior | **yes** | +| 13-3 | Docs: ARCHITECTURE_V2 §3a ("must re-enable" applies to the *new* scope; "listing every item" becomes "every candidate and every item not removed"), SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS. | Junior | no | -13-1 depends on nothing unmerged (the ledger and executor exist). 13-2 depends on 13-1 and on M01-06's caches builder. -Hotspots 13-2 will touch: `check-approval-sites.sh`, `SelfTest.swift`, and `SelfTestSupport.swift` — it must not run -alongside another task touching them (`worktree.sh overlap`). M01-04d currently edits `ci.yml`, three architecture docs and the -warnings baseline; 13-3 must wait for it to merge to avoid editing the same docs. +13-1 depends on nothing unmerged (the ledger, executor and Platform exist). 13-2 depends on 13-1 and M01-06. Hotspots 13-2 touches: +`check-approval-sites.sh`, `SelfTest.swift`, `SelfTestSupport.swift`; 13-1 touches the executor, Platform and `CleanupFileSystem` +conformers that M01-06 may also touch (not yet checked: conformer count and overlap, to be done with `worktree.sh overlap` at planning). 13-3 waits for M01-04d to merge. +**No stage starts until this revision is approved and `SAFETY-CRITICAL APPROVED` is given.** ## 8. Trade-offs and limits -1. **Frozen versions in code** cost a little growth per scope change; the benefit is that "enabled" can never mean - "whatever the latest code does". +1. **Frozen versions in code** cost a little growth per scope change; "enabled" can never mean "whatever the latest code does". `tightening` and retirement cover safety fixes. 2. **Running the old scope after an update** means a user who never reviews keeps v1 forever (safe, possibly stale). -3. **The consent store is ordinary user-writable storage.** A process running as the user can edit it (or the old - `auto.weekly` key) — but such a process can already delete the user's files directly. The policy defends against - code drift, the app's own CLI/MCP, and mistakes, not against other malware as the user. The digest check also makes a - hand-edited "version 2" or scope fail closed. -4. **Permanent delete with no review.** That is the point of a standing policy; hence the narrow, frozen, - regenerable-only scope, revalidation, full item listing and an easy off switch. There is no undo for caches; reported - honestly as "deleted", never "restorable". -5. **No per-run byte cap** in v1. A run can delete many GB of regenerable caches (same as today). A cap with "stop and - ask" is cheap to add later; it is deliberately not part of this change. -6. **Duplicate work if 13-2 builds the caches candidate builder before M01-06.** Avoided by sequencing (Open question 3). -7. **One executor per process:** the scheduled run and an interactive Trash/Shred wait for each other. Acceptable for - an infrequent background run (same note as 04c); revisit in 04d-style cleanup if it shows. -8. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had - open after the last check. - -## 9. Decisions (the reviewer chose the recommended option for each) +3. **Forgery:** the consent store is ordinary user-writable storage, and `AutomationConsent`/`validate` are callable from app code. The digest check catches a stale or corrupted store and a mismatched version, not code written to forge a consent. That code (and any process running as the user, which can already delete your files) is out of the policy's reach; app code is held by access control, `check-approval-sites.sh` and review. +4. **Classes by shape stay open in membership.** v1 admits the cache of any app installed later at an in-pattern path. Bounded by depth, literals, exclusions, protection, running-app skip and the cap, and stated in the consent sheet. +5. **The 20 GB cap** can defer a cleanup to the next run or a manual clean, and **a single item bigger than the cap is never cleaned by the schedule**. It never deletes more than today, only less. +6. **A stop mid-folder leaves a partly deleted folder** (kept entries stay, reported). If the name was retaken, the remainder stays in a hidden staging folder, reported with its path. No undo for permanently deleted entries. +7. **`CleanupFileSystem.remove` changes** (new `stop` parameter, new Core enum cases) touch the shared executor/Platform, safety-critical, and may overlap with M01-06; sequenced in 13-1 with tests before anything uses it. +8. **Running-app detection is best effort**, not a lock: an app can start between the check and the delete. Unknown or unreadable cases skip. +9. **One executor per process:** the scheduled run and an interactive Trash/Shred wait for each other. Acceptable for an infrequent background run. +10. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had open after the last check. +11. **A run that dies** leaves an `interrupted` row without per-item results; no per-item journal in this change. +12. **Per-path filtering** replaces `Cleaner.run`'s all-or-nothing `.removeItems` handling: narrower or equal, and shown in the record. + +## 9. Decisions (the reviewer's answers) 1. **After an update adds a scope version:** an enabled policy keeps running its granted version and offers a review of the new one (A). 13-3 updates ARCHITECTURE_V2 §3a: "must re-enable" applies to the *new* scope only. -2. **Existing installs:** paused until the user enables the policy once (fail closed), with one notification. +2. **Existing installs:** paused until the user grants the new policy (fail closed), with one notification. 3. **Sequencing:** 13-2 waits for M01-06's caches candidate builder; this task does not build a second one. 4. **"Run safe clean now":** opens the normal review sheet with the policy-scope items preselected, approved `.userInApp`, never `.standingPolicy`. 5. **History:** `approvedBy` and `items` are added to `history.json` now as optional fields; they move with the JSONL store later. -6. **Running-app check:** best effort by `NSWorkspace` bundle id, name and executable keys, as today; re-checked per item at execution time. +6. **Running-app check:** best-effort detection is accepted, provided uncertain cases fail conservatively (skip): unknown owner, unreadable list, helper-process ids (§3e.5); re-checked per item. +7. **History detail:** the record lists every candidate and every item that was not removed, with exact counts for the rest, instead of + every removed entry (§3f). This narrows ARCHITECTURE_V2 §3a "listing every item". *Raised by the design review; open for the reviewer's decision.* +8. **The 20 GB cap value** (§3c) is a proposal. *Open for the reviewer's decision before 13-1.* + +## Appendix A. v1 fixed dev caches (the 29 exact paths) + +Generated from `Scanner.plan()` at 800c3cd: every `dir(...)` target with `recommended: true` (the 9 `recommended: false` statics +are excluded). Paths are relative to `~`. 13-1 turns this into the golden file; this table is the list under review. + +| shape | path | | shape | path | +|---|---|---|---|---| +| contents | `Library/Developer/Xcode/DerivedData` | | item | `.npm/_cacache` | +| contents | `Library/Developer/Xcode/UserData/Previews` | | item | `Library/Caches/Yarn` | +| contents | `Library/Developer/CoreSimulator/Caches` | | item | `Library/pnpm/store` | +| item | `Library/Caches/com.apple.dt.Xcode` | | item | `.bun/install/cache` | +| item | `.gradle/caches` | | item | `Library/Caches/Homebrew` | +| item | `.gradle/daemon` | | item | `Library/Caches/CocoaPods` | +| item | `.android/cache` | | item | `Library/Caches/pip` | +| item | `.pub-cache/hosted` | | contents | `.cargo/registry` | +| item | `.pub-cache/git` | | contents | `.cargo/git` | +| item | `.dartServer` | | contents | `go/pkg/mod` | +| contents | `.gem/specs` | | contents | `.bundle/cache` | +| contents | `.local/share/NuGet` | | contents | `.hex/packages` | +| contents | `.cabal/packages` | | contents | `.composer/cache` | +| item | `Library/Caches/JetBrains` | | item | `Library/Logs/JetBrains` | + +Not in this table, handled by their own v1 rules: device support (5 literal OS folders), editor caches, the 12 `~/.cache` tools, +app / sandboxed / web caches and logs (§3b). (The Xcode device-support folders are listed there, not here.) + +## 10. Responses to the review findings + +**The user's five required fixes** + +| # | Finding | Resolution (where) | +|---|---|---| +| 1 | Prefix rules could admit new candidates under v1 | Ids never admit; allow-rules are fixed-depth path patterns with literal copies of every list; builder signals can only refuse (`tightening`); regression tests (§3a, §3b, §6 "Frozen scope") | +| 2 | Boundary between consent, approval and execution; revocation inside long cleanup | One chain: `validate` (+ gate at run start) → `approve(under:gate:)` → `GatedApproval` → `execute(gated:)`; nonce→gate map, old entry points refuse; gate in `halt()` and a per-entry `stop` in `remove`, plus a check before the staging move (§3d, §6) | +| 3 | No byte cap | 20 GB frozen in v1: smallest-first planning, measured-freed stop, deferral listed (§3c; value is open decision §9.8) | +| 4 | History accuracy | Status string, freed-only bytes, every candidate and every exception listed, 0-byte and not-run rows, `running`/`interrupted` row, nil outcome when nothing was deleted (§3f) | +| 5 | `auto.weekly` → `auto.weeklyClean` | Corrected everywhere; the Today section names `AutoKeys.weekly` | + +**`mc-reviewer` findings on revision 3** (REQUEST CHANGES; each verified against the code before acting) + +| # | Finding | Resolution | +|---|---|---| +| B1 | App-cache and logs rules were wider than today (`com.apple.*`, claimed names, Spotify, App Support exclusions, Logs) | **Confirmed** (`Scanner.swift:144–181`). Exclusions copied into v1 as literals; Spotify excluded; logs as `.item(Logs/)` with its filters; tests per exclusion (§3b, §6) | +| B2 | Web-cache pattern too narrow (depth, Service Worker) | **Confirmed** (`collectWebCaches` depth < 4). Explicit patterns for 0–3 intermediates and the Service Worker shapes (§3b, §6) | +| B3 | Chain over-claimed; gated vs ungated `execute`; `halt()` claim wrong; gate timing | **Confirmed.** Wording corrected to "access control plus the sites script"; nonce→gate map and `gateRequired`; gate added to `halt()`; gate created at validation (§3d, §3e) | +| S4 | `stop` hook incompletely specified (staging rename, retaken name, new enum cases, report size, `@Sendable`) | All adopted (§3d, §7, §8.6, §8.7) | +| S5 | Cap semantics (oversized item, ordering, granularity, hard links) | Smallest-first, defined units, measured freed, oversized item stated as never cleaned by the schedule (§3c, §8.5) | +| S6 | `admits` entry checks, "reads only paths" over-claim, home device, letter case | Per-entry exclusion check, claim reworded, `homeDevice` input, case rule stated (§3a) | +| S7 | History: crash mid-run, 300-record rewrite cost, unknown-tolerant status, `.deleted` on notRun | `running`/`interrupted` row, exceptions + counts (flagged as decision §9.7), string status, nil outcome (§3f) | +| S8 | Run now, off/on, paused-slot key, all-or-nothing behaviour change | Run now stage and tests; off revokes, on re-grants; `auto.policyReportedSlot`; per-path filter before `approve` with tests (§3e, §6, §7, §8.12) | +| S9 | Fixed list ended in "…" | Full list in Appendix A (29 paths) | +| N | SelfTest line citations; weak digest claim; duplicate precondition text; unrelated branch diff | Citations fixed (§6); claim softened (§8.3); duplicate removed; the extra files in the reviewer's diff came from a stale local `main`; against `origin/main` this PR changes **only** `M01-13_DESIGN.md` (`git diff origin/main...HEAD`) | + +Not checked by the reviewer and still to do before 13-1: the `CleanupFileSystem` conformer count and overlap with M01-06; +`Staging` prefix interaction with later scans; `package`-init feasibility across Features/Platform. Whether to ask for an Opus +review (`mc-safety-architect`) of this design before 13-1 is the user's call; it has not been requested. From fdc9ae7ea4d1d13ff66ab9444676d0a38b75f890 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Mon, 16 Nov 2026 00:41:13 +0100 Subject: [PATCH 4/8] =?UTF-8?q?M01-13=20design:=20strict=20byte=20cap,=20u?= =?UTF-8?q?nknown=20results=20after=20a=20crash,=20consent=20wording;=20AR?= =?UTF-8?q?CHITECTURE=5FV2=20=C2=A73a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture/ARCHITECTURE_V2.md | 13 +++-- docs/architecture/M01-13_DESIGN.md | 72 ++++++++++++++++------------ 2 files changed, 51 insertions(+), 34 deletions(-) diff --git a/docs/architecture/ARCHITECTURE_V2.md b/docs/architecture/ARCHITECTURE_V2.md index 947167e..a7ff682 100644 --- a/docs/architecture/ARCHITECTURE_V2.md +++ b/docs/architecture/ARCHITECTURE_V2.md @@ -100,11 +100,18 @@ separate **`AutomationPolicy`**, which the user turns on explicitly in Settings (today: `AutoClean.select` / `AutoClean.narrowed` — tool caches, logs except crash reports, caches of apps that are not running). Never command targets (simulators, Docker, `tmutil`), never review-required or potential-user-data items, never Trash-only items, never anything privileged. -* **Versioned:** the policy records which categories it covers. A new app version that adds a category does not - extend an existing policy; the user must re-enable it after seeing the new scope. +* **Versioned:** the policy is a frozen scope in code (an allow-list of path patterns). A new app version that adds a + category is a **new version**; an enabled policy keeps running the version the user granted and the user must grant the new + one after seeing its scope. New *locations* and *categories* always need new consent; a new *member* of an already-permitted + path class (a newly installed app's cache folder) does not, and the Enable sheet says so. Details: `M01-13_DESIGN.md`. +* **Capped:** one run frees at most the version's byte budget (20 GB in v1), enforced by charging each entry before it is removed. * **Same executor, same guards:** protection, exclusions and identity revalidation apply exactly as in an interactive run; anything changed or protected is skipped. -* **Recorded:** each run is a history session with `approvedBy: .standingPolicy`, listing every item. +* **Recorded:** each run is a history session with `approvedBy: .standingPolicy`. It lists every candidate (rule, path, final + status) and every item that was **not** removed (skipped, kept, failed, deferred, each with its reason), plus exact counts of + successful, skipped, failed and deferred units; successfully removed entries are counted, not listed one by one. More than 500 + exceptions are truncated with a visible count. A run that dies is `interrupted` with its freed bytes **unknown** (at least the + confirmed amount), never recorded as 0. * **Revocable:** turning it off cancels future runs; it never runs again until turned back on. * The CLI and MCP cannot create or widen a policy. diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index d05ac1f..da1ef36 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -100,30 +100,36 @@ today's effective scope (`AutoClean.select` + `narrowed` over what `Scanner.plan | logs | `.item(~/Library/Logs/)` | excluded: `JetBrains` (its own rule), prefix `com.apple.`, **`DiagnosticReports`** (crash reports are kept); matches Scanner, which hands `.removeItems(children of Logs)` after the same filter; loose files directly in `Logs` are children too | The "app caches" classes are a class **by shape**: the cache of any app installed later at an in-pattern path qualifies. That -is what v1 means, the consent sheet says so, and it is bounded by depth, literals, exclusions, `safeRegenerable`, +is what v1 means. **The scope guarantee, stated precisely: new *locations* and new *categories* always need new consent; a new *member* of an already-permitted path class (a newly installed app's cache folder) does not.** The Enable sheet must say so in plain words ("This also covers the caches of apps you install later, in the same folders") next to the list of folders; the sheet's text is part of the versioned scope (changing it is a new version) and 13-2 has a self-test that the sheet shows it. The class is bounded by depth, literals, exclusions, `safeRegenerable`, protection, `skipIfAppRunning` and the cap. Everything a *new code path* could add at a **new location** is refused. **Adding a category = adding `v2`** (a new entry; `v1` untouched). A mistake in a shipped version is fixed by **retiring** it (`retired: true`: the policy pauses until the user grants a newer version), never by editing it. `tightening` handles the opposite case, a *safety fix*, without a new consent. -### 3c. Unattended byte cap - -Nobody reviews the run, so v1 has a cap: **`maxBytesPerRun = 20 GB`** (a proposal for the reviewer to confirm before 13-1; -frozen with v1 and in the scope digest; a different number is a new version). The cap is on **freed bytes as the executor -reports them**, the same measure as the history row: hard-linked content counts 0 (nothing is freed), allocated size is -used for estimates. - -- **Planning:** admitted units are taken **smallest estimate first** (ties by path), a greedy fill while the running - estimate stays within the cap; the rest are **not planned** and are listed as `deferred (over the run limit)`. Smallest-first - maximizes what the run can clean and doesn't let one rule or path order starve the others week after week. +### 3c. Unattended byte cap (a strict limit) + +Nobody reviews the run, so v1 has a cap: **`maxBytesPerRun = 20 GB`** (approved by the reviewer as v1's budget; frozen with v1 +and in the scope digest; a different number is a new version). It is a **strict limit on what the run may free**, enforced by +**charging before removing**, not a planning estimate: + +- **The charge** for a file is its **allocated size**, taken from the entry's identity, **whether or not it is hard-linked** (a + hard-linked file frees nothing but is still charged, so charged ≥ freed always). Folders and links charge 0. +- **`stop` gets the next entry's charge.** The Platform walk calls `stop(chargedSoFarInItem, nextEntryCharge)` before each entry; + the gate refuses an entry when `charged + nextEntryCharge > maxBytesPerRun`, and updates its run total as entries are removed. + A refused entry is kept like any stopped entry (3d). So the run **cannot free more than 20 GB**, whatever the planning estimate + said; the overshoot is zero by construction. (A file that grew after its identity was captured fails the identity check and is + skipped, not removed.) +- **Planning** still uses estimates, to choose what to attempt: admitted units are taken **smallest estimate first** (ties by + path), a greedy fill while the running estimate stays within the cap; the rest are **not planned** and listed as + `deferred (over the run limit)`. Smallest-first maximizes what the run can clean and doesn't let one rule or path order starve + the others week after week. - **Deferral granularity:** a unit is a **candidate's `.file` target** for item rules (one `~/.cache/pip` folder, one app's cache) and **one reviewed entry** for contents rules (each entry of DerivedData is its own removal in the executor). -- **A single item bigger than the cap is never cleaned by the schedule.** It is listed each run as "larger than the run - limit, clean it from the app" rather than half-run. This is accepted (8.5). -- **Execution:** the gate counts freed bytes per entry across the run. At the cap the gate stops the run (3d): the entry - being removed finishes or is kept per the stop rule, and every later unit is `skipped(runLimit)`. Estimates are logical, the stop is on measured - removal, so a low estimate can't run past it by more than the one entry in progress. +- **A single item bigger than the cap:** not planned when its estimate says so, and listed each run as "larger than the run limit, + clean it from the app". If the estimate was wrong, the strict charge stops the walk at the cap and the item is `.partiallyDone` + (kept entries reported). So "never cleaned by the schedule" holds for items known to be over the cap; an item of unknown size + can be partly cleaned, never beyond the cap. - It only narrows today's behaviour (today there is none). Notification and history say so when it triggers. ### 3d. Stored consent, policy approval and execution: one chain @@ -161,9 +167,9 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). - **The gate is a new input to the run loop.** Today `halt()` reads only the cancellation state and the `stopped` reason (`CleanupExecutor.swift` `execute`), and `precondition` runs only after an item's protection check. 13-1 adds the gate to `halt()` (so it is read before every target, including the first) and passes it down. -- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `@Sendable (Int64) -> String?` +- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `@Sendable (_ chargedSoFarInItem: Int64, _ nextEntryCharge: Int64) -> String?` `stop` parameter (nil for interactive runs, behaviour unchanged), called by the Platform before **each entry** with the bytes - freed so far in this item. The gate is also asked **before the item is moved into its staging folder**, so a revoke before + charged so far in this item and the next entry's charge (3c). The gate is also asked **before the item is moved into its staging folder**, so a revoke before an item starts leaves it in place (`LocalFileSystem.remove` renames the item into staging before it visits any entry, so without this check the item's path would be absent for the whole walk). A non-nil reason is treated like a refused `protection` for the rest of the walk: **fail closed**; the entries not visited are kept, the folders holding them are kept and @@ -222,13 +228,13 @@ are then deleted. It has its own stage entry and self-test (§6, §7). - `runStatus: String?` and `statusDetail: String?`. A **string**, not an enum with payloads: an older build or the CLI/MCP reading a status it doesn't know shows it as text and doesn't drop the record. Values: `running`, `completed`, `partial`, `cancelled`, `stoppedRevoked`, `stoppedRunLimit`, `failed`, `notRun`, `interrupted`. -- `items: [RecordItem]?` and `itemCounts: [String: Int]?`. **What is listed:** every candidate/unit that was **not removed** +- `items: [RecordItem]?` and `itemCounts: [String: Int]?`. **What is listed:** **every candidate with its identity (rule, path), scope (policy id, version) and final status**, and every unit that was **not removed** (skipped with its reason, kept entries with their reason and path, failed, permission denied, deferred over the run limit, outside scope) is listed **individually**, and each **removed** candidate is one row with its entry count and bytes. Exact - counts per result are always stored. Item results: `removed`, `partiallyDone`, `skipped(changed | protected | appRunning | + counts of successful, skipped, failed and deferred units are always stored. Item results: `removed`, `partiallyDone`, `skipped(changed | protected | appRunning | missing | addedAfterReview | cancelled | revoked | runLimit | outsideScope | preconditionFailed)`, `deferred(overRunLimit)`, `permissionDenied`, `failed`. -- `bytes` = the sum over `removed` and `partiallyDone` freed bytes, **never the planned size** (today `AutoClean.run` adds a +- `bytes` = the sum over `removed` and `partiallyDone` freed bytes **when the result is known** (`bytesKnown: true`), **never the planned size** (today `AutoClean.run` adds a target's whole planned size whenever `Cleaner.run` returns no error, which overstates a run that skipped anything). `measuredFreeChange` stays a separate measurement. - `outcome` is `.deleted` only when something was permanently removed; a `notRun` or fully skipped row has `outcome == nil` @@ -241,9 +247,13 @@ entries rewritten per add. Hence: candidate rows plus every exception, exact cou decision §9.7 for the reviewer. If a run has more than 500 non-removed items, the first 500 are listed and the rest are in `itemCounts` with the text `N more not listed` (explicit, never silent). -**A run that dies.** The record is created at the start with `runStatus: running` (written under the file lock before the scan) -and replaced at the end. If the app quits, crashes or the Mac sleeps in between, the next launch shows that row as -`interrupted: per-item results unknown`; per-item journaling is not added (limit 8.11). The row is never counted as freed. +**A run that dies: unknown is not zero.** The record is created at the start with `runStatus: running` (under the file lock, +before the scan), carries `bytesKnown: false`, and is **checkpointed after each candidate finishes** with the progress confirmed +so far (`confirmedBytes`, `confirmedItems`, same lock). At the end it is replaced by the final record (`bytesKnown: true`). If the +app quits, crashes or the Mac sleeps in between, the next launch shows the row as `interrupted`: "at least *confirmedBytes* freed; +the rest is **unknown**". It is **not** shown as "0 freed", and `totalDeleted` counts only `confirmedBytes`, labelled "at least". +A completed run that removed nothing is a **confirmed zero** (`bytesKnown: true`, `bytes: 0`); the two are never merged. There is +no per-item journal (8.11): what survives a crash is progress to the last finished candidate. A cancelled or revoked run lists what was removed and what was left; skipped items are never counted as freed. The notification is made from the same data ("Freed 3.2 GB; 4 items skipped" / "Stopped: you turned the policy off after 1.1 GB"). @@ -275,7 +285,7 @@ sheet file and the self-test; nothing under the MCP/CLI files; no `AutomationCon | One path of a merged candidate is out of scope | that path dropped and listed; the others run | | A command / review / user-data / Trash item reaches the plan | `admits` refuses; ledger's generic check refuses again | | Another caller asks for `.standingPolicy`, or runs one without the gate | refused (`useAutomationPolicy`, `gateRequired`) | -| App quits mid-run | row shows `interrupted`; nothing counted as freed | +| App quits mid-run | row shows `interrupted`; freed bytes **unknown** (at least the confirmed amount), never 0 | | Two runs for one slot, or a run right after enabling | unchanged `isDue`/`armedAt` rules | | Mac asleep at the slot | catch-up on wake, unchanged | @@ -317,7 +327,7 @@ Platform tests in Features/Platform. in staging); revoke **during the scan** (nothing approved); revoke after N entries of one folder with thousands of entries: no entry past N+1 removed, unvisited folders kept and put back, one `KeptEntry` per folder with the count, item `.partiallyDone` with `stopped`; **the item's name retaken during the walk**: remainder reported as `stagingLeftBehind` with its path. The same for the - byte cap (low estimate), hard-linked content counted as 0 freed, smallest-first planning, over-cap candidates deferred and + byte cap: a low estimate **never frees more than the cap** (the next entry is refused when `charged + next > cap`, tested at the boundary), hard-linked files are charged (not 0), smallest-first planning, over-cap candidates deferred and listed, a single item over the cap never partly run. Interactive removal with `stop: nil` behaves as before (existing tests unchanged and green). - **New Core cases:** `KeptEntry.Reason.stopped`, `SkipReason.revoked`, `SkipReason.runLimit` are produced, and every exhaustive switch compiles and is tested (Core, Features, app). @@ -325,7 +335,7 @@ Platform tests in Features/Platform. path dropped and listed, the others run; `.removeItems` → `.file` per path; `.webCachesIn` → the `.removeItems` produced after `measure`; logs as `.removeItems` of children. - **History (self-test):** rows for completed, partial (kept entries), cancelled, stoppedRevoked, stoppedRunLimit, failed, notRun, - interrupted (a `running` row left behind); `bytes` = freed only; a 0-byte run is still recorded with `outcome == nil`; skipped, + interrupted (a `running` row left behind): shown as unknown with the checkpointed minimum, never as 0, and counted in `totalDeleted` only for the confirmed part; `bytes` = freed only; a 0-byte run is still recorded with `outcome == nil`; skipped, kept and deferred items are listed with reasons; counts match; more than 500 exceptions → explicit "N more not listed"; old records decode; an unknown `runStatus` string decodes and shows; the notification text comes from the same data. - **Running apps:** unknown owner skipped; unreadable running list skips the class; a helper-process bundle id skips its app; @@ -364,7 +374,7 @@ conformers that M01-06 may also touch (not yet checked: conformer count and over 8. **Running-app detection is best effort**, not a lock: an app can start between the check and the delete. Unknown or unreadable cases skip. 9. **One executor per process:** the scheduled run and an interactive Trash/Shred wait for each other. Acceptable for an infrequent background run. 10. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had open after the last check. -11. **A run that dies** leaves an `interrupted` row without per-item results; no per-item journal in this change. +11. **A run that dies** leaves an `interrupted` row with `bytesKnown: false` and the progress confirmed at the last checkpoint (per candidate); no per-item journal in this change. 12. **Per-path filtering** replaces `Cleaner.run`'s all-or-nothing `.removeItems` handling: narrower or equal, and shown in the record. ## 9. Decisions (the reviewer's answers) @@ -379,7 +389,7 @@ conformers that M01-06 may also touch (not yet checked: conformer count and over 6. **Running-app check:** best-effort detection is accepted, provided uncertain cases fail conservatively (skip): unknown owner, unreadable list, helper-process ids (§3e.5); re-checked per item. 7. **History detail:** the record lists every candidate and every item that was not removed, with exact counts for the rest, instead of every removed entry (§3f). This narrows ARCHITECTURE_V2 §3a "listing every item". *Raised by the design review; open for the reviewer's decision.* -8. **The 20 GB cap value** (§3c) is a proposal. *Open for the reviewer's decision before 13-1.* +8. **The 20 GB cap value** (§3c) is a proposal. **APPROVED** by the reviewer as v1's budget; the semantics are a strict limit (§3c). ## Appendix A. v1 fixed dev caches (the 29 exact paths) @@ -414,8 +424,8 @@ app / sandboxed / web caches and logs (§3b). (The Xcode device-support folders |---|---|---| | 1 | Prefix rules could admit new candidates under v1 | Ids never admit; allow-rules are fixed-depth path patterns with literal copies of every list; builder signals can only refuse (`tightening`); regression tests (§3a, §3b, §6 "Frozen scope") | | 2 | Boundary between consent, approval and execution; revocation inside long cleanup | One chain: `validate` (+ gate at run start) → `approve(under:gate:)` → `GatedApproval` → `execute(gated:)`; nonce→gate map, old entry points refuse; gate in `halt()` and a per-entry `stop` in `remove`, plus a check before the staging move (§3d, §6) | -| 3 | No byte cap | 20 GB frozen in v1: smallest-first planning, measured-freed stop, deferral listed (§3c; value is open decision §9.8) | -| 4 | History accuracy | Status string, freed-only bytes, every candidate and every exception listed, 0-byte and not-run rows, `running`/`interrupted` row, nil outcome when nothing was deleted (§3f) | +| 3 | No byte cap | 20 GB frozen in v1: smallest-first planning, measured-freed stop, deferral listed (§3c; strict, charge-before-remove; value approved §9.8) | +| 4 | History accuracy | Status string, freed-only bytes, every candidate and every exception listed, 0-byte and not-run rows, `running`/`interrupted` row with unknown (not zero) bytes and per-candidate checkpoints, nil outcome when nothing was deleted (§3f) | | 5 | `auto.weekly` → `auto.weeklyClean` | Corrected everywhere; the Today section names `AutoKeys.weekly` | **`mc-reviewer` findings on revision 3** (REQUEST CHANGES; each verified against the code before acting) From 23c875f4b85dc448652a25249c5a884272137731 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Mon, 16 Nov 2026 00:50:34 +0100 Subject: [PATCH 5/8] M01-13 design: revision 5 (Opus safety review: charge accounting, work folders, one-shot gate, durable checkpoint, sequencing) --- docs/architecture/M01-13_DESIGN.md | 197 +++++++++++++++++++++-------- 1 file changed, 141 insertions(+), 56 deletions(-) diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index da1ef36..11e40e1 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -70,11 +70,11 @@ fix (a new review-only app) take effect under frozen v1 without a new version. target is `.file` or `.directoryContents` (never `.command`, `.tree`); every target path matches a rule: a `.file` target's path against an `.item` pattern, and for a `.directoryContents` target **the folder against a `.contentsOf` pattern and every reviewed entry's path against the same rule's exclusions** (so `DiagnosticReports` inside a contents rule is refused); no path -has an excluded component; the target's device equals `homeDevice` (passed in; the function does no I/O); and `tightening` +has an excluded component; the target's device equals `homeDevice` and the home prefix (both passed in; the function does no I/O); and `tightening` refuses nothing. Anything else is `.refused(.outsideScope)`. There is no "everything except". **Letter case.** Literal and `oneOf` components of **allow** patterns match **exactly** on the resolved path (a look-alike -differing in case is not admitted, even on a case-insensitive volume); **exclusions are compared case-folded** (an +differing in case is not admitted, even on a case-insensitive volume); **exclusions are compared case-folded** (`lowercased()`, locale-independent; Unicode normalization is left to the volume, which APFS ignores) (an exclusion also catches a look-alike). Both fail toward refusing, as in SAFETY_MODEL §2a. **v1 never references app or Core constants** (`SafetyGuard.*`, `PermanentDeleteRules.*`, `Scanner.claimedLibraryCaches`, @@ -90,14 +90,14 @@ today's effective scope (`AutoClean.select` + `narrowed` over what `Scanner.plan | v1 rule | pattern | exclusions / notes | |---|---|---| -| fixed dev caches | the 29 exact paths in **Appendix A** (item or contents, as `Scanner` gives them) | the 9 `recommended: false` statics (archives, Gradle wrapper, Maven, Ivy, NuGet packages, CocoaPods repos, conda) are **not** in it | -| device support | `.contentsOf(~/Library/Developer/Xcode/ DeviceSupport)` | | +| fixed dev caches | the 28 exact paths in **Appendix A** (item or contents, as `Scanner` gives them) | the `recommended: false` statics (archives, Gradle wrapper, Maven, Ivy, NuGet packages, CocoaPods repos, the 6 conda folders: 12 paths) are **not** in it | +| device support | `.contentsOf(~/Library/Developer/Xcode/)` | | | editor caches | `.item(~/Library/Application Support//)` | editor folder list copied as literals in 13-1 (golden) | | `~/.cache` tools | `.item(~/.cache/)` | model caches (huggingface, torch) and `uv` (kept by default) stay manual | | app caches | `.item(~/Library/Caches/)` | excluded: prefix `.`, prefix `com.apple.`, the names Scanner "claims" (`Yarn`, `Homebrew`, `CocoaPods`, `pip`, `JetBrains`, `com.apple.dt.Xcode`, `io.github.wahdanz.maccleaner`, `local.maccleaner`), and **`com.spotify.client`** (review-only today, "offline music"); `skipIfAppRunning` | | sandboxed app caches | `.contentsOf(~/Library/Containers//Data/Library/Caches)` | container name excluded when prefix `.` or `com.apple.`; `skipIfAppRunning` | -| web / Electron caches | `.item(~/Library/Application Support//<0..3 × anyOne>/)` and the same prefix + `Service Worker/`; written out as the explicit fixed-depth patterns for 0, 1, 2 and 3 intermediate folders (Scanner's `collectWebCaches` visits depths 0–3) | top folder excluded: prefix `.`, prefix `com.apple.`, the editor folders, `MobileSync`, `CallHistoryDB`, `AddressBook`; intermediates exclude the extensions `app`, `bundle`, `framework`, `plugin` and links; `skipIfAppRunning` | -| logs | `.item(~/Library/Logs/)` | excluded: `JetBrains` (its own rule), prefix `com.apple.`, **`DiagnosticReports`** (crash reports are kept); matches Scanner, which hands `.removeItems(children of Logs)` after the same filter; loose files directly in `Logs` are children too | +| web / Electron caches | `.item(~/Library/Application Support//<0..3 × anyOne>/)` and the same prefix + `Service Worker/`; written out as the explicit fixed-depth patterns for 0, 1, 2 and 3 intermediate folders (Scanner's `collectWebCaches` visits depths 0–3) | top folder excluded: prefix `.`, prefix `com.apple.`, the editor folders, `MobileSync`, `CallHistoryDB`, `AddressBook`; intermediates exclude the extensions `app`, `bundle`, `framework`, `plugin`, links and **dot-prefixed folders** (today's walk skips hidden folders); `skipIfAppRunning` | +| logs | `.item(~/Library/Logs/)` | excluded: `JetBrains` (its own rule), prefix `com.apple.`, **prefix `.` (so never a work folder; narrower than today)**, **`DiagnosticReports`** (crash reports are kept); matches Scanner, which hands `.removeItems(children of Logs)` after the same filter; loose files directly in `Logs` are children too | The "app caches" classes are a class **by shape**: the cache of any app installed later at an in-pattern path qualifies. That is what v1 means. **The scope guarantee, stated precisely: new *locations* and new *categories* always need new consent; a new *member* of an already-permitted path class (a newly installed app's cache folder) does not.** The Enable sheet must say so in plain words ("This also covers the caches of apps you install later, in the same folders") next to the list of folders; the sheet's text is part of the versioned scope (changing it is a new version) and 13-2 has a self-test that the sheet shows it. The class is bounded by depth, literals, exclusions, `safeRegenerable`, @@ -107,30 +107,35 @@ protection, `skipIfAppRunning` and the cap. Everything a *new code path* could a **retiring** it (`retired: true`: the policy pauses until the user grants a newer version), never by editing it. `tightening` handles the opposite case, a *safety fix*, without a new consent. -### 3c. Unattended byte cap (a strict limit) - -Nobody reviews the run, so v1 has a cap: **`maxBytesPerRun = 20 GB`** (approved by the reviewer as v1's budget; frozen with v1 -and in the scope digest; a different number is a new version). It is a **strict limit on what the run may free**, enforced by -**charging before removing**, not a planning estimate: - -- **The charge** for a file is its **allocated size**, taken from the entry's identity, **whether or not it is hard-linked** (a - hard-linked file frees nothing but is still charged, so charged ≥ freed always). Folders and links charge 0. -- **`stop` gets the next entry's charge.** The Platform walk calls `stop(chargedSoFarInItem, nextEntryCharge)` before each entry; - the gate refuses an entry when `charged + nextEntryCharge > maxBytesPerRun`, and updates its run total as entries are removed. - A refused entry is kept like any stopped entry (3d). So the run **cannot free more than 20 GB**, whatever the planning estimate - said; the overshoot is zero by construction. (A file that grew after its identity was captured fails the identity check and is - skipped, not removed.) -- **Planning** still uses estimates, to choose what to attempt: admitted units are taken **smallest estimate first** (ties by - path), a greedy fill while the running estimate stays within the cap; the rest are **not planned** and listed as - `deferred (over the run limit)`. Smallest-first maximizes what the run can clean and doesn't let one rule or path order starve - the others week after week. -- **Deferral granularity:** a unit is a **candidate's `.file` target** for item rules (one `~/.cache/pip` folder, one app's cache) - and **one reviewed entry** for contents rules (each entry of DerivedData is its own removal in the executor). -- **A single item bigger than the cap:** not planned when its estimate says so, and listed each run as "larger than the run limit, - clean it from the app". If the estimate was wrong, the strict charge stops the walk at the cap and the item is `.partiallyDone` - (kept entries reported). So "never cleaned by the schedule" holds for items known to be over the cap; an item of unknown size - can be partly cleaned, never beyond the cap. -- It only narrows today's behaviour (today there is none). Notification and history say so when it triggers. +### 3c. Unattended byte cap (a strict limit on the run's accounted charge) + +Nobody reviews the run, so v1 has a cap: **`maxBytesPerRun = 20 GB`** (approved by the reviewer as v1's budget; frozen with +v1 and in the scope digest; a different number is a new version). It is enforced by **charging before removing**, and the +guarantee is stated precisely: **the run's accounted charge never exceeds the cap.** The disk's real change can still differ +(a file can grow between the `fstatat` and the `unlinkat`; APFS clones and snapshots change what is actually freed), which is +why history reports **confirmed freed bytes separately** from the charge (3f). + +- **What is charged.** *Every* entry the walk removes is charged its `st_blocks * 512` from the walk's own fresh `fstatat` + (the item's `FileIdentity` has only a logical size, and nested entries have no captured identity): files whatever their link + count, and also folders and links. (`LocalFileSystem.freed` adds a folder's and a link's own blocks to the freed total, so charging them 0 + would let freed exceed charged.) Hard-linked files are charged although unlinking them frees nothing: the charge is + conservative by design. +- **Where the check runs.** The Platform calls `stop(nextEntryCharge)` **immediately before every `unlinkat` and `rmdir`** in the + walk, and for an item that is a plain file (no walk) right before its unlink, using the stat taken in staging, putting the file + back if refused. The gate **adds each charge it approves**, without being told the outcome, so it needs no report from the + executor and no per-item counter. It refuses when `charged + next > maxBytesPerRun` (or revoked). A refusal stops the rest of + the walk (parent loops included); **after a stop no further folder is `rmdir`'d**; the unvisited entries and the folders + holding them are kept (3d). +- **Planning** uses estimates to choose what to attempt: admitted units smallest-estimate first (ties by path), greedy fill within + the cap; the rest are **not planned** and listed as `deferred (over the run limit)` (this stops one rule or path order from starving + the others every week). +- **Per-item pre-check.** Right before each item the runner re-measures its allocated size (a fresh walk) against the remaining + budget and **defers the item if it doesn't fit**, instead of starting something the cap would cut. The per-entry stop is only the + backstop for a size that changed in between. So an item known to exceed the cap is never started; an item that grew + can still end `.partiallyDone`. **A stop mid-item (cap or revoke) leaves a partly cleaned folder; for package caches (Gradle, + pnpm, Go module cache) that can break builds until they are rebuilt**, and the record and the notification say which items were partly cleaned. +- **Deferral granularity:** a unit is a candidate's `.file` target for item rules and **one reviewed entry** for contents rules. +- It only narrows today's behaviour (today there is none). ### 3d. Stored consent, policy approval and execution: one chain @@ -139,8 +144,8 @@ stored consent --validate--> ValidatedPolicy + PolicyGate --approve(under:gate:) (data) (Core) (made together, at run start) (executor) (one-shot) (executor) (PolicyGate) ``` -What enforces it, stated honestly: **access control plus the sites script**, not the type system alone. `ValidatedPolicy`, -`PolicyGate` and `GatedApproval` have initializers that are `package`-internal to MacCleanerKit (like `CleanupApproval`), so +What enforces it, stated honestly: **access control plus the sites script**, not the type system alone. `AutomationPolicy`, `AutomationScope`, `AutomationCatalog`, `ValidatedPolicy`, +`PolicyGate` and `GatedApproval` have initializers that are `package`-level (the precedent is `ApprovalLedger`; `CleanupApproval.init` is `internal`), so app code can only obtain them through `AutomationConsent.validate`, `approve(under:gate:)`, and the catalog. But `AutomationConsent` is an ordinary Codable value and `validate` is public, so an app file that builds a consent with the current catalog digest gets a `ValidatedPolicy`. **That is stopped by `check-approval-sites.sh`** (3g), which is the @@ -150,11 +155,11 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). - **`AutomationConsent`** (stored): `{ policyId, grantedVersion, grantedScopeDigest, grantedAt, source: .user, revokedAt? }`. The scope is never read from storage. Written only by `AutomationConsentStore` (app target), only from the Settings sheet's Enable and Revoke. -- **`validate(in: catalog, now:)`** fails closed (`.revoked`, `.unknownVersion`, `.retired`, `.digestMismatch`, +- **`AutomationConsent.validate(now:)`** checks against the **built-in** `AutomationCatalog` only (a `package` overload taking a catalog exists for tests; app code can't make a wider catalog or policy). It fails closed (`.revoked`, `.unknownVersion`, `.retired`, `.digestMismatch`, `.grantedInTheFuture`) and returns the `ValidatedPolicy` **and creates its `PolicyGate`**. **The gate is created and - registered at validation, i.e. at the start of a run** (3e step 2), before the minutes-long scan and measure. The app's - `AutomationGateRegistry` (main actor) holds the live gate. A Revoke at any later moment (during scan, during - planning, during execution) flips it synchronously, no actor hop, before `revokedAt` is persisted. `approve` refuses an + registered at validation, i.e. at the start of a run** (3e step 2), before the minutes-long scan and measure. The gate is **one-shot**: it is consumed by `approve` (one approval per gate) and closed when `execute` finishes, and validation and gate registration happen in the same main-actor turn. The `ValidatedPolicy` carries the `tightening` captured at run start, so `approve` can't be handed a weaker one. The app's + `AutomationGateRegistry` (main actor) holds every outstanding gate. A Revoke at any later moment (during scan, during + planning, during execution) flips **all outstanding gates** synchronously, no actor hop, before `revokedAt` is persisted. `approve` refuses an inactive gate, so a revoke during the scan means nothing is approved or deleted. - **`CleanupExecutor.approve(_ plan:, under:, gate:)`** calls `admits` for **every** entry and refuses the whole plan with `outsidePolicyScope(candidateID:)` if one is out (the runner filters first, 3e), then issues `.standingPolicy(id:version:)` @@ -167,15 +172,15 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). - **The gate is a new input to the run loop.** Today `halt()` reads only the cancellation state and the `stopped` reason (`CleanupExecutor.swift` `execute`), and `precondition` runs only after an item's protection check. 13-1 adds the gate to `halt()` (so it is read before every target, including the first) and passes it down. -- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `@Sendable (_ chargedSoFarInItem: Int64, _ nextEntryCharge: Int64) -> String?` - `stop` parameter (nil for interactive runs, behaviour unchanged), called by the Platform before **each entry** with the bytes - charged so far in this item and the next entry's charge (3c). The gate is also asked **before the item is moved into its staging folder**, so a revoke before +- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `@Sendable (_ nextEntryCharge: Int64) -> String?` + `stop` parameter, **which is the protocol requirement with no default implementation**; the old two-argument form remains only as an extension that forwards `stop: nil` (so existing calls compile and interactive behaviour is unchanged, while a conformer can never silently ignore `stop`), called by the Platform before **each entry** with the + next entry's charge (3c). The gate is also asked **before the item is moved into its staging folder**, so a revoke before an item starts leaves it in place (`LocalFileSystem.remove` renames the item into staging before it visits any entry, so without this check the item's path would be absent for the whole walk). A non-nil reason is treated like a refused `protection` for the rest of the walk: **fail closed**; the entries not visited are kept, the folders holding them are kept and put back with the existing machinery (the put-back already works for a non-empty folder), and the item is `.partiallyDone`. After a revoke at most the one entry being removed completes. - - **Name retaken during the walk.** If an app recreates the item's path while the walk runs, the put-back's + - **Put-back failures outside the walk** (a mismatch, a protection refusal, or the single-file stop) throw a `PlatformError`, which the executor reports as `.failed(text)`, not as `stagingLeftBehind`; history maps both to "work folder left behind, at ". **Name retaken during the walk.** If an app recreates the item's path while the walk runs, the put-back's `RENAME_EXCL` fails and the remainder stays in the staging folder (`~/Library/Caches/.…`). That is already how the Platform reports it (`KeptEntry.Reason.stagingLeftBehind` with the path). Unattended, it is therefore reported in history as a kept entry with its path, and 13-1 tests it. - **Size of the report.** A stop doesn't list every unvisited leaf: one `KeptEntry` per folder whose remaining contents @@ -185,6 +190,31 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). (fakes included). Every exhaustive `switch` over these in Core, Features and the app changes in the same PR. - `precondition` is kept for the per-item running-app check (3e). +### 3d-2. Leftover work folders (`.maccleaner-rm-`) + +A leftover is the **remainder of an approved item**: after a stop whose put-back failed (the name was retaken), or after a crash or +SIGKILL mid-walk (then the whole unvisited item is still inside). It can hold entries that were kept because they changed after +review or became protected, and its original name is recorded nowhere on disk (slot `item`), so path-based protection +(`UserProtection`) can no longer be applied to it. Today `LocalFileSystem.entries` hides the prefix, but the executor handles every +*reviewed* entry (`CleanupExecutor.contents`), `Scanner.children` lists hidden files, and `PermanentDeleteRules` doesn't refuse the +prefix: a leftover in `~/Library/Logs`, or inside a contents-rule folder, could be deleted by the next unattended run. + +- **Central exclusion.** The prefix becomes a public Core constant (`CleanupWorkFolder.prefix`, today `LocalFileSystem.stagingPrefix`). + It is filtered in **every** discovery layer: `Scanner.children`, `Scanner.plan/measure` (so a folder's shown size excludes it), + the M01-06 candidate builder (an entry with the prefix is never a candidate or reviewed entry), and `LocalFileSystem.entries` (already). + Interactive and unattended scans alike, so `~/.cache/.maccleaner-rm-X` is no longer offered as a recommended candidate. +- **Second check in `admits`.** A path with **any component** starting with the prefix (case-folded) is refused, so a future builder + that forgets the filter still can't get one admitted. (The v1 logs rule also excludes dot-prefixed names, which is narrower + than today; web-cache intermediates exclude dot-prefixed folders, as today's `.skipsHiddenFiles` walk does.) +- **Never silently skipped, never silently deleted.** The runner records, in the `running` checkpoint, the item being worked on + (original path and work-folder path); kept entries already carry the work-folder path. **At launch and before each scheduled run** + the app lists the known parents for leftovers and reports "work folders left behind" with their paths (history, notification and a + Settings row). **Recovery is reviewed and never permanent deletion** (protection can't be re-verified): *Put Back* (`RENAME_EXCL` to the + original name, if it is free and the original path is known) or *Move to Trash*, each after the person sees the folder. + 13-1 (Core): the constant and the `admits` refusal. 13-2: the central filter in the app's scan, detection and reporting. **A + separate stage, 13-2b, does the review UI** (Put Back / Move to Trash), because it is its own approval boundary. +- A third-party folder that happens to use the prefix is never cleaned: a safe failure. + ### 3e. The scheduled run (app target) 1. `tick` finds the schedule due (unchanged `isDue`/`armedAt`) and `auto.weeklyClean` on; otherwise stops. @@ -198,7 +228,7 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). `Cleaner.run`, where a `.removeItems` list was all-or-nothing: it is now per path, which is narrower or equal. Then apply the byte cap (3c) and build the plan, disposition `.permanentDelete`. Check the gate is still active right before `approve`. 4. `approve(under:gate:)` then `execute(plan, gated:)`: protection, identity revalidation, nothing followed through links; a changed, - protected or added-after-snapshot item is skipped and reported. The snapshot is seconds old. + protected or added-after-snapshot item is skipped and reported. The snapshot is seconds old; what actually protects against entries that appeared or changed since is the executor's creation/change-time cutoff and per-entry identity checks, not the age of the snapshot. 5. **Running apps, fail conservative.** `skipIfAppRunning` rules skip an item when **any** of these holds: the owning app can't be determined from the path; the running-app list can't be read (the whole class is skipped); a running app's bundle id, name or executable name equals the folder name, starts with `.`, or the folder name starts with `.` @@ -206,6 +236,11 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). Best effort, not a lock (8.8). 6. Record (3f), notify with **measured** results, `check()`, `refreshNextRun()`. +**A crashed slot is spent.** `lastRun` is written only after a run (`Automation.swift:314–316`), so a crash before it would make `isDue` fire +again on relaunch, and a crash loop could free the cap again at each launch. The runner therefore persists the slot as **attempted** +(`auto.policyAttemptedSlot`) **before any deletion**, together with the `running` row, so the cap is **per slot**; a crashed slot +doesn't retry until the next one. + **Paused or refused runs.** A run that doesn't start writes at most **one "Not run" row per scheduled slot**: the runner stores the slot it last reported (`auto.policyReportedSlot`, the `lastSlot` date) because a paused run doesn't set `lastRun` and `tick` fires every 5 minutes. @@ -247,9 +282,11 @@ entries rewritten per add. Hence: candidate rows plus every exception, exact cou decision §9.7 for the reviewer. If a run has more than 500 non-removed items, the first 500 are listed and the rest are in `itemCounts` with the text `N more not listed` (explicit, never silent). +**Durability of the checkpoint.** `SharedFile.update` today writes with `Data.write(.atomic)` (no `fsync`, and it writes even if the lock wasn't taken), and `read` returns `[]` on a decode error, so a checkpoint into a corrupt file would overwrite every record. 13-2 therefore gives history a **dedicated durable write**: temp file, `F_FULLFSYNC`, `rename`, `fsync` of the folder, all **under the lock and failing closed** (`commit`, not `update`); it refuses to write when the file is *unreadable* (distinct from *missing*); and if a checkpoint can't be committed it returns a stop reason from `onItemFinished`, so the run halts **before the next candidate**. The checkpoint is written when the **last target of a candidate** finishes (`onItemFinished` fires per target, synchronously, before the next). Cost: a rewrite of up to 300 records plus a full sync per candidate, tens of ms each. History also needs a new API for **0-byte rows and replace-by-id** (`HistoryStore.add` drops `bytes <= 0` and records are immutable), and the `running` row stores the **PID and boot session** so a second GUI instance mid-run isn't mistaken for a dead one. The candidate list itself is bounded: the first 300 candidate rows are listed and the rest are in `itemCounts`, with `N more not listed`. Sleep doesn't interrupt a run; only a quit or crash does. + **A run that dies: unknown is not zero.** The record is created at the start with `runStatus: running` (under the file lock, before the scan), carries `bytesKnown: false`, and is **checkpointed after each candidate finishes** with the progress confirmed -so far (`confirmedBytes`, `confirmedItems`, same lock). At the end it is replaced by the final record (`bytesKnown: true`). If the +so far (`confirmedBytes` = **freed as the file system reported it**, `confirmedItems`, same lock; separate from the charge, which is only the budget). At the end it is replaced by the final record (`bytesKnown: true`). If the app quits, crashes or the Mac sleeps in between, the next launch shows the row as `interrupted`: "at least *confirmedBytes* freed; the rest is **unknown**". It is **not** shown as "0 freed", and `totalDeleted` counts only `confirmedBytes`, labelled "at least". A completed run that removed nothing is a **confirmed zero** (`bytesKnown: true`, `bytes: 0`); the two are never merged. There is @@ -327,8 +364,22 @@ Platform tests in Features/Platform. in staging); revoke **during the scan** (nothing approved); revoke after N entries of one folder with thousands of entries: no entry past N+1 removed, unvisited folders kept and put back, one `KeptEntry` per folder with the count, item `.partiallyDone` with `stopped`; **the item's name retaken during the walk**: remainder reported as `stagingLeftBehind` with its path. The same for the - byte cap: a low estimate **never frees more than the cap** (the next entry is refused when `charged + next > cap`, tested at the boundary), hard-linked files are charged (not 0), smallest-first planning, over-cap candidates deferred and - listed, a single item over the cap never partly run. Interactive removal with `stop: nil` behaves as before (existing tests unchanged and green). + byte cap: a low estimate **never frees more than the cap** (the next entry is refused when `charged + next > cap`, tested at the boundary), hard-linked files, folders and links are charged (charged ≥ freed is asserted over real trees, including folder/link blocks), smallest-first planning, over-cap candidates deferred and + listed, a an item the pre-check finds over the remaining budget is deferred and never started (a grown item can still end `.partiallyDone`, tested). Interactive removal with `stop: nil` behaves as before (existing tests unchanged and green). +- **Charge accounting:** over real trees with nested folders, links and hard-linked files, the sum of charges is ≥ the freed bytes the + Platform reports; the single-file item path calls `stop` and puts the file back when refused; no `rmdir` after a stop; `stop` + is called before **every** unlink/rmdir (a counting fake); a conformer can't compile without implementing `stop`; the two-argument + forwarding form passes `nil`. +- **Gate:** one-shot (a second `approve` with the same gate is refused); Revoke flips every outstanding gate; a gate kept from an + earlier run can't be reused; `tightening` captured at validation can't be replaced at `approve`; `validate(now:)` can't use a + caller's catalog outside tests (the `package` overload is not visible to the app). +- **Work folders:** `admits` refuses any path component with the prefix, in any case; the Scanner and the builder never list one; + a leftover inside `~/Library/Logs`, inside a contents folder (DerivedData), and in `~/.cache` is never planned or deleted; the + checkpoint records the item in progress; detection finds a leftover left by a stop with a retaken name and by a simulated kill + mid-walk, and reports it without touching it. +- **Crashed slot:** the attempted-slot marker is written before any deletion; a relaunch after a crash does not re-run the slot. +- **Durable checkpoint:** a failed commit stops the run before the next candidate; an unreadable `history.json` is never overwritten; + replace-by-id and a 0-byte row work; a `running` row with another live PID isn't shown as interrupted. - **New Core cases:** `KeptEntry.Reason.stopped`, `SkipReason.revoked`, `SkipReason.runLimit` are produced, and every exhaustive switch compiles and is tested (Core, Features, app). - **Scheduled-run mapping (app self-test, temp home):** the merged `appcache.small` candidate with one out-of-pattern path: that @@ -353,14 +404,20 @@ Platform tests in Features/Platform. | Stage | What | Level | Safety-critical | |---|---|---|---| -| **13-1** | Core: `AutomationPolicy`/scope/patterns/catalog v1 (literals + Appendix A, golden file), `tightening`, `ValidatedPolicy`, `PolicyGate`, `AutomationConsent.validate`; executor `approve(under:gate:)`, nonce→gate map, `execute(_, gated:)`, `gateRequired`, `useAutomationPolicy`, gate in `halt()`; new `KeptEntry.Reason.stopped`, `SkipReason.revoked/.runLimit`; `CleanupFileSystem.remove(stop:)`, Platform walk and the pre-staging check, all conformers; package tests above. **App unchanged, unused** (the new enum cases' exhaustive switches in the app get the minimal update). | Senior | **yes** | -| **13-2** | App: consent store + Settings sheet (toggle revokes/enables), gate registry, scheduled runner on the executor with the per-target filter and cap, history fields (`running` row, statuses, items, counts), migration and per-slot "Not run" row, **"Run safe clean now" through the review sheet** (Settings + menu-bar popover), sites script, self-tests; remove `AutoClean.run/select/narrowed`, `runClean(automatic:)` and the scheduled path's `Cleaner.run` use. **Waits for M01-06's caches candidate builder** (decision §9.3). | Senior | **yes** | -| 13-3 | Docs: ARCHITECTURE_V2 §3a ("must re-enable" applies to the *new* scope; "listing every item" becomes "every candidate and every item not removed"), SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS. | Junior | no | - -13-1 depends on nothing unmerged (the ledger, executor and Platform exist). 13-2 depends on 13-1 and M01-06. Hotspots 13-2 touches: -`check-approval-sites.sh`, `SelfTest.swift`, `SelfTestSupport.swift`; 13-1 touches the executor, Platform and `CleanupFileSystem` -conformers that M01-06 may also touch (not yet checked: conformer count and overlap, to be done with `worktree.sh overlap` at planning). 13-3 waits for M01-04d to merge. -**No stage starts until this revision is approved and `SAFETY-CRITICAL APPROVED` is given.** +| **13-1** | Core: `AutomationPolicy`/scope/patterns/catalog v1 (literals + Appendix A, golden file; `package` initializers), `tightening`, `ValidatedPolicy`, one-shot `PolicyGate`, `AutomationConsent.validate(now:)`; the public work-folder prefix constant and the `admits` refusal; executor `approve(under:gate:)`, nonce→gate map, `execute(_, gated:)`, `gateRequired`, `useAutomationPolicy`, gate in `halt()`; new `KeptEntry.Reason.stopped`, `SkipReason.revoked/.runLimit`; `CleanupFileSystem.remove(stop:)` as the requirement (+ forwarding extension), the Platform walk's per-unlink/rmdir charge check, the single-file and pre-staging checks, both conformers (`LocalFileSystem`, test `FakeFS`); package tests above, including rewriting `CleanupExecutorTests.swift:346` (it calls the now-refused `approve(by: .standingPolicy)`). **App unchanged, unused**: `AutoClean.run` keeps deleting unattended without a gate until 13-2, so RISK-017 stays open until then. | Senior | **yes** | +| **13-2** | App: consent store + Settings sheet (toggle revokes/enables), gate registry, scheduled runner on the executor with the per-target filter, cap, per-item pre-check and attempted-slot marker; central work-folder filter in `Scanner`; leftover detection and reporting; history fields, durable checkpoint, 0-byte/replace-by-id API, `SharedFile` fixes, migration and per-slot "Not run" row; **"Run safe clean now" through the review sheet** (Settings + menu-bar popover); sites script (allow the runner's `CleanupExecutor(`); self-tests; remove `AutoClean.run/select/narrowed`, `runClean(automatic:)` and the scheduled path's `Cleaner.run`. **Waits for M01-06's caches candidate builder.** | Senior | **yes** | +| **13-2b** | Review UI for leftover work folders: Put Back (`RENAME_EXCL`) or Move to Trash after review, never permanent delete. | Senior | **yes** (approval boundary) | +| 13-3 | Docs: ARCHITECTURE_V2 (remaining §3a/§5 wording), SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS. | Junior | no | + +**Sequencing with M01-06 (checked).** `CleanupFileSystem` has two conformers (`LocalFileSystem`, the test `FakeFS`); `ProtectionChecking` has three +(`AppProtection`, `AppOwnedTrash.OneFolder`, the test `Protected`) and this design doesn't change that protocol; the only production +caller of `remove` is `CleanupExecutor.swift:212`. M01-06 will edit `LocalFileSystem.removeContents`, the same walk 13-1 changes, and +it must also add something `Cleaner.run` does today and the executor does not: **`makeOwnerWritable` for read-only folders** (the Go +module cache, `go/pkg/mod`, is read-only, so its v1 entries would fail with `EACCES` on every run until then; a chmod also changes +ctime, which interacts with the change-time cutoff). That chmod is its own safety-critical change. So **13-1 and M01-06 can't run in +parallel**: recommended order is 13-1 first (a contract change M01-06 should build on), then M01-06 rebased on it with the chmod as a separate +reviewed stage, then 13-2. Hotspots 13-2 touches: `check-approval-sites.sh`, `SelfTest.swift`, `SelfTestSupport.swift`, `SharedFile.swift`. +13-3 waits for M01-04d to merge. **No stage starts until this revision is approved and `SAFETY-CRITICAL APPROVED` is given.** ## 8. Trade-offs and limits @@ -372,7 +429,7 @@ conformers that M01-06 may also touch (not yet checked: conformer count and over 6. **A stop mid-folder leaves a partly deleted folder** (kept entries stay, reported). If the name was retaken, the remainder stays in a hidden staging folder, reported with its path. No undo for permanently deleted entries. 7. **`CleanupFileSystem.remove` changes** (new `stop` parameter, new Core enum cases) touch the shared executor/Platform, safety-critical, and may overlap with M01-06; sequenced in 13-1 with tests before anything uses it. 8. **Running-app detection is best effort**, not a lock: an app can start between the check and the delete. Unknown or unreadable cases skip. -9. **One executor per process:** the scheduled run and an interactive Trash/Shred wait for each other. Acceptable for an infrequent background run. +9. **Several executors per process:** `ApprovedTrash` has one, `AppOwnedTrash` makes one per move, and the runner makes its own (so `check-approval-sites.sh`'s `CleanupExecutor(` rule must allow the runner's file). A scheduled and an interactive run therefore do **not** wait for each other; concurrent runs are safe because of `RENAME_EXCL` and the identity checks. The nonce→gate map and `gateRequired` live per executor instance, which is fine because a gated approval is made and used by the same one. 10. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had open after the last check. 11. **A run that dies** leaves an `interrupted` row with `bytesKnown: false` and the progress confirmed at the last checkpoint (per candidate); no per-item journal in this change. 12. **Per-path filtering** replaces `Cleaner.run`'s all-or-nothing `.removeItems` handling: narrower or equal, and shown in the record. @@ -391,9 +448,9 @@ conformers that M01-06 may also touch (not yet checked: conformer count and over every removed entry (§3f). This narrows ARCHITECTURE_V2 §3a "listing every item". *Raised by the design review; open for the reviewer's decision.* 8. **The 20 GB cap value** (§3c) is a proposal. **APPROVED** by the reviewer as v1's budget; the semantics are a strict limit (§3c). -## Appendix A. v1 fixed dev caches (the 29 exact paths) +## Appendix A. v1 fixed dev caches (the 28 exact paths) -Generated from `Scanner.plan()` at 800c3cd: every `dir(...)` target with `recommended: true` (the 9 `recommended: false` statics +Generated from `Scanner.plan()` at 800c3cd: every `dir(...)` target with `recommended: true` (the 12 `recommended: false` static paths are excluded). Paths are relative to `~`. 13-1 turns this into the golden file; this table is the list under review. | shape | path | | shape | path | @@ -440,9 +497,37 @@ app / sandboxed / web caches and logs (§3b). (The Xcode device-support folders | S6 | `admits` entry checks, "reads only paths" over-claim, home device, letter case | Per-entry exclusion check, claim reworded, `homeDevice` input, case rule stated (§3a) | | S7 | History: crash mid-run, 300-record rewrite cost, unknown-tolerant status, `.deleted` on notRun | `running`/`interrupted` row, exceptions + counts (flagged as decision §9.7), string status, nil outcome (§3f) | | S8 | Run now, off/on, paused-slot key, all-or-nothing behaviour change | Run now stage and tests; off revokes, on re-grants; `auto.policyReportedSlot`; per-path filter before `approve` with tests (§3e, §6, §7, §8.12) | -| S9 | Fixed list ended in "…" | Full list in Appendix A (29 paths) | +| S9 | Fixed list ended in "…" | Full list in Appendix A (28 paths) | | N | SelfTest line citations; weak digest claim; duplicate precondition text; unrelated branch diff | Citations fixed (§6); claim softened (§8.3); duplicate removed; the extra files in the reviewer's diff came from a stale local `main`; against `origin/main` this PR changes **only** `M01-13_DESIGN.md` (`git diff origin/main...HEAD`) | Not checked by the reviewer and still to do before 13-1: the `CleanupFileSystem` conformer count and overlap with M01-06; `Staging` prefix interaction with later scans; `package`-init feasibility across Features/Platform. Whether to ask for an Opus review (`mc-safety-architect`) of this design before 13-1 is the user's call; it has not been requested. + +## 11. Responses to the Opus safety review (`mc-safety-architect`, on fdc9ae7: REQUEST CHANGES) + +Each claim was checked against the code before acting (`LocalFileSystem.freed` counts folder and link blocks; `Scanner.children` lists +hidden files; the executor handles every reviewed entry whatever `entries` returned). + +| # | Finding | Resolution | +|---|---|---| +| B1 | "charged ≥ freed" and "overshoot zero" false: folders/links freed but charged 0; no allocated size in identities; plain-file items have no walk; gate never told about removals | **Confirmed.** Charge every entry `st_blocks*512` from the walk's `fstatat`; `stop(nextCharge)` before every unlink/rmdir incl. the single-file path; the gate adds each approved charge; wording now "accounted charge never exceeds the cap", charge and freed reported separately (§3c) | +| B2 | Leftover `.maccleaner-rm-*` folders could be admitted and deleted unattended; protection can't be re-applied | **Confirmed.** Central exclusion in every discovery layer, a second refusal in `admits`, never silently skipped or deleted, reviewed recovery that is never permanent delete, own stage 13-2b (§3d-2, §7) | +| S1 | Catalog forgeable via `validate(in:)` | `validate(now:)` uses the built-in catalog; policy/scope/catalog initializers `package` (§3d) | +| S2 | Gate not one-shot | One-shot, consumed at `approve`, all outstanding gates flipped on revoke (§3d) | +| S3 | Crash re-runs the slot | Attempted-slot marker before any deletion; the cap is per slot (§3e) | +| S4 | Contradiction on over-cap items; partial package caches | Per-item pre-check + backstop; partial-cache risk documented (§3c, §6) | +| S5 | "One executor per process" false | Corrected (§8.9) | +| S6 | `stop` could be silently ignored via a default | The requirement takes `stop`; the two-argument form is a forwarding extension (§3d) | +| S7 | Web-cache rule wider (hidden intermediates) | Dot-prefixed intermediates excluded (§3b) | +| S8 | History durability | Dedicated durable write, fail-closed commit, unreadable-vs-missing, stop on failed checkpoint (§3f) | +| S9 | M01-06 overlap; Go module cache read-only | Checked; sequencing and the chmod stage (§7) | +| S10 | `tightening` a free runner parameter | Captured in `ValidatedPolicy` at validation (§3d) | +| N | Appendix counts (28 / 12), DeviceSupport notation, case-folding, sleep, pre-walk put-back failures, rmdir after stop, 0-byte rows, interrupted detection by PID/boot, candidate list bound, `ApprovalLedger` precedent | All applied (§3a, §3b, §3c, §3d, §3f, Appendix A) | + +**Decisions the reviewer asked of the user**, with the recommendation applied in this revision (change on request): +1. *Partial deletes at the cap:* per-item pre-check plus the per-entry backstop (recommended). +2. *Leftover recovery:* reviewed Put Back or Move to Trash, never permanent delete, in its own stage 13-2b (recommended). +3. *A crashed slot is spent* (recommended). +4. *Sequencing:* 13-1, then M01-06 with the chmod as its own stage, then 13-2 (recommended). +5. §9.7 (history lists exceptions and counts) is already approved by the user. From edd0e57ee7875cb068130e6581de1b08bbd1c155 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Mon, 16 Nov 2026 03:33:07 +0100 Subject: [PATCH 6/8] M01-13 design: revision 6 (transition safety 13-0, reserved vs freed, durable slot marker, chmod requirements) --- docs/architecture/M01-13_DESIGN.md | 103 +++++++++++++++++++++++++---- 1 file changed, 89 insertions(+), 14 deletions(-) diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index 11e40e1..79cca9c 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -120,12 +120,18 @@ why history reports **confirmed freed bytes separately** from the charge (3f). count, and also folders and links. (`LocalFileSystem.freed` adds a folder's and a link's own blocks to the freed total, so charging them 0 would let freed exceed charged.) Hard-linked files are charged although unlinking them frees nothing: the charge is conservative by design. -- **Where the check runs.** The Platform calls `stop(nextEntryCharge)` **immediately before every `unlinkat` and `rmdir`** in the +- **Where the check runs.** The Platform calls `control.reserve(charge)` **immediately before every `unlinkat` and `rmdir`** in the walk, and for an item that is a plain file (no walk) right before its unlink, using the stat taken in staging, putting the file - back if refused. The gate **adds each charge it approves**, without being told the outcome, so it needs no report from the - executor and no per-item counter. It refuses when `charged + next > maxBytesPerRun` (or revoked). A refusal stops the rest of + back if refused. The gate **adds each charge it approves to its reserved total**; it needs no report of successes from the executor. It refuses when `charged + next > maxBytesPerRun` (or revoked). A refusal stops the rest of the walk (parent loops included); **after a stop no further folder is `rmdir`'d**; the unvisited entries and the folders holding them are kept (3d). +- **Reserved is not freed.** The gate tracks **`reserved`** (charges approved, the budget) and history separately records **`freed`** (what + the file system reported removed). A charge is **kept when the unlink succeeds, and also when it is not known to have failed**. + An entry whose `unlinkat`/`rmdir` **returned an error** (the entry is still there, nothing freed) is **released** by the Platform + through `control.release(charge)`, so a run full of failures (the read-only Go module cache before M01-06's chmod, a locked file) + can't spend the budget on nothing. Charging an entry whose unlink failed and not releasing it would also be safe (conservative), + but would let failures starve a run; `release` is allowed **only** for a syscall that reported failure, so `freed ≤ reserved` still holds. Tests: + success keeps the reservation, a failed unlink releases it, a skipped-by-stop entry never reserves, and `freed ≤ reserved` over real trees. - **Planning** uses estimates to choose what to attempt: admitted units smallest-estimate first (ties by path), greedy fill within the cap; the rest are **not planned** and listed as `deferred (over the run limit)` (this stops one rule or path order from starving the others every week). @@ -172,8 +178,8 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). - **The gate is a new input to the run loop.** Today `halt()` reads only the cancellation state and the `stopped` reason (`CleanupExecutor.swift` `execute`), and `precondition` runs only after an item's protection check. 13-1 adds the gate to `halt()` (so it is read before every target, including the first) and passes it down. -- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `@Sendable (_ nextEntryCharge: Int64) -> String?` - `stop` parameter, **which is the protocol requirement with no default implementation**; the old two-argument form remains only as an extension that forwards `stop: nil` (so existing calls compile and interactive behaviour is unchanged, while a conformer can never silently ignore `stop`), called by the Platform before **each entry** with the +- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `control: RemovalControl?` parameter (a `Sendable` struct of two closures: `reserve(charge) -> String?`, the + stop check, and `release(charge)`, 3c), **which is the protocol requirement with no default implementation**; the old two-argument form remains only as an extension that forwards `control: nil` (so existing calls compile and interactive behaviour is unchanged, while a conformer can never silently ignore it). The Platform calls `reserve` before **each entry** with the next entry's charge (3c). The gate is also asked **before the item is moved into its staging folder**, so a revoke before an item starts leaves it in place (`LocalFileSystem.remove` renames the item into staging before it visits any entry, so without this check the item's path would be absent for the whole walk). A non-nil reason is treated like a refused @@ -186,7 +192,7 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). - **Size of the report.** A stop doesn't list every unvisited leaf: one `KeptEntry` per folder whose remaining contents weren't visited, with the count of entries not visited in its text. - **New Core cases (13-1):** `KeptEntry.Reason.stopped(String)`, `SkipReason.revoked`, `SkipReason.runLimit` (instead of - parsing `preconditionFailed(String)` for history), plus the `stop` parameter on every `CleanupFileSystem` conformer + parsing `preconditionFailed(String)` for history), plus the `control` parameter on every `CleanupFileSystem` conformer (fakes included). Every exhaustive `switch` over these in Core, Features and the app changes in the same PR. - `precondition` is kept for the per-item running-app check (3e). @@ -238,8 +244,14 @@ prefix: a leftover in `~/Library/Logs`, or inside a contents-rule folder, could **A crashed slot is spent.** `lastRun` is written only after a run (`Automation.swift:314–316`), so a crash before it would make `isDue` fire again on relaunch, and a crash loop could free the cap again at each launch. The runner therefore persists the slot as **attempted** -(`auto.policyAttemptedSlot`) **before any deletion**, together with the `running` row, so the cap is **per slot**; a crashed slot -doesn't retry until the next one. +**before any deletion**, together with the `running` row, so the cap is **per slot**; a crashed slot doesn't retry until the next one. +`UserDefaults` is **not** durable against a crash (writes are flushed later), so the marker is not a `UserDefaults` key: it lives in +the history's `running` row and in a small `AutomationState` file, written together with the **dedicated durable write** (3f: +temp file, `F_FULLFSYNC`, `rename`, `fsync` of the folder, under the lock, `commit`, failing closed). **The order is fixed: validate, +create the gate, durably commit the marker and the `running` row, and only then `approve` and `execute`. If the commit fails, no +run starts** (a "Not run: couldn't record the attempt" row is tried, and the slot stays unspent only if nothing destructive could +have happened). Tests: a counting file system shows zero removals when the commit fails; a simulated kill right after the commit +leaves the slot spent on relaunch; the marker is read from the durable file, not from `UserDefaults`. **Paused or refused runs.** A run that doesn't start writes at most **one "Not run" row per scheduled slot**: the runner stores the slot it last reported (`auto.policyReportedSlot`, the `lastSlot` date) because a paused run doesn't set `lastRun` and @@ -365,10 +377,10 @@ Platform tests in Features/Platform. N+1 removed, unvisited folders kept and put back, one `KeptEntry` per folder with the count, item `.partiallyDone` with `stopped`; **the item's name retaken during the walk**: remainder reported as `stagingLeftBehind` with its path. The same for the byte cap: a low estimate **never frees more than the cap** (the next entry is refused when `charged + next > cap`, tested at the boundary), hard-linked files, folders and links are charged (charged ≥ freed is asserted over real trees, including folder/link blocks), smallest-first planning, over-cap candidates deferred and - listed, a an item the pre-check finds over the remaining budget is deferred and never started (a grown item can still end `.partiallyDone`, tested). Interactive removal with `stop: nil` behaves as before (existing tests unchanged and green). + listed; an item the pre-check finds over the remaining budget is deferred and never started (a grown item can still end `.partiallyDone`, tested). Interactive removal with `control: nil` behaves as before (existing tests unchanged and green). - **Charge accounting:** over real trees with nested folders, links and hard-linked files, the sum of charges is ≥ the freed bytes the - Platform reports; the single-file item path calls `stop` and puts the file back when refused; no `rmdir` after a stop; `stop` - is called before **every** unlink/rmdir (a counting fake); a conformer can't compile without implementing `stop`; the two-argument + Platform reports; the single-file item path calls `reserve` and puts the file back when refused; no `rmdir` after a stop; `reserve` + is called before **every** unlink/rmdir (a counting fake); a conformer can't compile without implementing `control`; the two-argument forwarding form passes `nil`. - **Gate:** one-shot (a second `approve` with the same gate is refused); Revoke flips every outstanding gate; a gate kept from an earlier run can't be reused; `tightening` captured at validation can't be replaced at `approve`; `validate(now:)` can't use a @@ -404,18 +416,27 @@ Platform tests in Features/Platform. | Stage | What | Level | Safety-critical | |---|---|---|---| +| **13-0** | **Interim guard for the legacy scheduled clean** (app, small): the work-folder prefix is refused by `Scanner.children` and by `AutoClean.select` (any path component, case-folded), with self-tests that a planted `.maccleaner-rm-X` in `Logs`, a contents folder and `~/.cache` is never planned or deleted by the legacy path. No behaviour change otherwise. Independent of 13-1; ships first. | Senior | **yes** (it changes what the unattended clean may delete) | | **13-1** | Core: `AutomationPolicy`/scope/patterns/catalog v1 (literals + Appendix A, golden file; `package` initializers), `tightening`, `ValidatedPolicy`, one-shot `PolicyGate`, `AutomationConsent.validate(now:)`; the public work-folder prefix constant and the `admits` refusal; executor `approve(under:gate:)`, nonce→gate map, `execute(_, gated:)`, `gateRequired`, `useAutomationPolicy`, gate in `halt()`; new `KeptEntry.Reason.stopped`, `SkipReason.revoked/.runLimit`; `CleanupFileSystem.remove(stop:)` as the requirement (+ forwarding extension), the Platform walk's per-unlink/rmdir charge check, the single-file and pre-staging checks, both conformers (`LocalFileSystem`, test `FakeFS`); package tests above, including rewriting `CleanupExecutorTests.swift:346` (it calls the now-refused `approve(by: .standingPolicy)`). **App unchanged, unused**: `AutoClean.run` keeps deleting unattended without a gate until 13-2, so RISK-017 stays open until then. | Senior | **yes** | | **13-2** | App: consent store + Settings sheet (toggle revokes/enables), gate registry, scheduled runner on the executor with the per-target filter, cap, per-item pre-check and attempted-slot marker; central work-folder filter in `Scanner`; leftover detection and reporting; history fields, durable checkpoint, 0-byte/replace-by-id API, `SharedFile` fixes, migration and per-slot "Not run" row; **"Run safe clean now" through the review sheet** (Settings + menu-bar popover); sites script (allow the runner's `CleanupExecutor(`); self-tests; remove `AutoClean.run/select/narrowed`, `runClean(automatic:)` and the scheduled path's `Cleaner.run`. **Waits for M01-06's caches candidate builder.** | Senior | **yes** | | **13-2b** | Review UI for leftover work folders: Put Back (`RENAME_EXCL`) or Move to Trash after review, never permanent delete. | Senior | **yes** (approval boundary) | | 13-3 | Docs: ARCHITECTURE_V2 (remaining §3a/§5 wording), SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS. | Junior | no | +**Release safety (RISK-017 stays open until 13-2).** Between the merge of 13-1 and the merge of 13-2 the legacy `AutoClean.run` still +deletes unattended with no gate, as it does today. Rules for any release cut from `main` in that window: (1) **13-0 must be in it**, so +the legacy path can't consume a leftover work folder (a risk that exists today, because `Scanner.children` lists hidden files and `remove` +can leave a leftover); (2) 13-2 is preferably in the same release as the first M01-06 module that changes what the scheduled path +lists, otherwise the legacy path is unchanged; (3) the release notes say the scheduled clean still runs under the old rules. The stricter +alternative is to **disable the legacy scheduled clean** in any release before 13-2 (a kill switch that turns `AutoSchedule` off with a +notification); it costs users their scheduled cleans until 13-2 and is **not** recommended, but it is the user's call (§12). + **Sequencing with M01-06 (checked).** `CleanupFileSystem` has two conformers (`LocalFileSystem`, the test `FakeFS`); `ProtectionChecking` has three (`AppProtection`, `AppOwnedTrash.OneFolder`, the test `Protected`) and this design doesn't change that protocol; the only production caller of `remove` is `CleanupExecutor.swift:212`. M01-06 will edit `LocalFileSystem.removeContents`, the same walk 13-1 changes, and it must also add something `Cleaner.run` does today and the executor does not: **`makeOwnerWritable` for read-only folders** (the Go module cache, `go/pkg/mod`, is read-only, so its v1 entries would fail with `EACCES` on every run until then; a chmod also changes -ctime, which interacts with the change-time cutoff). That chmod is its own safety-critical change. So **13-1 and M01-06 can't run in -parallel**: recommended order is 13-1 first (a contract change M01-06 should build on), then M01-06 rebased on it with the chmod as a separate +ctime, which interacts with the change-time cutoff). That chmod is its own safety-critical change, with the requirements of §13. So **13-1 and M01-06 can't run in +parallel**: recommended order is 13-0 and 13-1 first (a contract change M01-06 should build on), then M01-06 rebased on it with the chmod as a separate reviewed stage, then 13-2. Hotspots 13-2 touches: `check-approval-sites.sh`, `SelfTest.swift`, `SelfTestSupport.swift`, `SharedFile.swift`. 13-3 waits for M01-04d to merge. **No stage starts until this revision is approved and `SAFETY-CRITICAL APPROVED` is given.** @@ -445,7 +466,7 @@ reviewed stage, then 13-2. Hotspots 13-2 touches: `check-approval-sites.sh`, `Se 5. **History:** `approvedBy` and `items` are added to `history.json` now as optional fields; they move with the JSONL store later. 6. **Running-app check:** best-effort detection is accepted, provided uncertain cases fail conservatively (skip): unknown owner, unreadable list, helper-process ids (§3e.5); re-checked per item. 7. **History detail:** the record lists every candidate and every item that was not removed, with exact counts for the rest, instead of - every removed entry (§3f). This narrows ARCHITECTURE_V2 §3a "listing every item". *Raised by the design review; open for the reviewer's decision.* + every removed entry (§3f). This narrows ARCHITECTURE_V2 §3a "listing every item" (updated in this PR). **APPROVED** by the reviewer, on condition that the record keeps every candidate's identity, scope and final status, exact counts, and explicit exceptions with a visible truncation count (§3f). 8. **The 20 GB cap value** (§3c) is a proposal. **APPROVED** by the reviewer as v1's budget; the semantics are a strict limit (§3c). ## Appendix A. v1 fixed dev caches (the 28 exact paths) @@ -531,3 +552,57 @@ hidden files; the executor handles every reviewed entry whatever `entries` retur 3. *A crashed slot is spent* (recommended). 4. *Sequencing:* 13-1, then M01-06 with the chmod as its own stage, then 13-2 (recommended). 5. §9.7 (history lists exceptions and counts) is already approved by the user. + +## 12. Decisions confirmed by the reviewer on revision 5 + +1. Per-item budget pre-check plus per-entry enforcement of the 20 GB accounted-charge limit: **APPROVED**. +2. Leftover work folders: reviewed Put Back or Move to Trash, implemented separately (13-2b): **APPROVED**. +3. A crashed scheduled slot counts as spent: **APPROVED**. +4. Order 13-1 → M01-06 → 13-2: **CONDITIONALLY APPROVED**, with the release-safety constraint (§7). This revision adds 13-0 and the + release rules to meet it. Still the user's call: **interim guard (13-0 + release rules, recommended) or disabling the legacy + scheduled clean in releases before 13-2**. + +## 13. Requirements for M01-06's read-only-folder handling (`makeOwnerWritable` successor) + +Today `Cleaner.run` calls `makeOwnerWritable` (`Scanner.swift:406`), which adds owner-write bits to a path's folder tree with +path-based `setAttributes`, before deleting. The executor has no equivalent. The permission change is a **safety-critical change of its +own** (a separate reviewed stage in M01-06) and must meet these requirements; 13-1 doesn't implement it, it only reserves the +hook (`control` is asked before it). + +1. **Only on an approved, revalidated item, inside the staging folder.** It runs after protection, the precondition/gate and the + identity check for that item have passed, and after the item was moved into its private staging folder, so the path can't be swapped. +2. **No path-based chmod.** It uses an open directory fd with `fchmod` (or `fchmodat(..., AT_SYMLINK_NOFOLLOW)` on a fd opened with + `O_NOFOLLOW`), never `setAttributes(atPath:)`. A link is never followed and its target's mode never changes. +3. **Only adds owner bits, only on directories, only ones we own.** `mode |= 0o700` on a directory whose `st_uid == geteuid()`; never removes + a bit, never changes files, links or another owner's folders, never `chown`, never clears flags (`chflags`): an immutable/`uchg` entry + is kept and reported. +4. **Within the item and the home volume.** Never above the item, never across a device boundary, never into a mount. +5. **Protection and the gate first.** `protection(path)` is asked before each directory's chmod; for an unattended run `control.reserve` + is asked first too, so a revoked run **never starts a permission change** and a stopped run changes no more. +6. **Original modes are recorded and restored.** Each directory's original mode is recorded before it is changed. If the walk stops + (revoke, cap, protection, failure, cancellation), every directory that **remains** (kept, or put back) gets its original mode back; + a restore that fails is reported (`KeptEntry` text and a warning), never ignored. Directories that are deleted need no restore. +7. **The change-time cutoff isn't tripped by our own chmod** (chmod updates ctime): the "changed after review" check for an entry is made + on a stat taken **before** that entry's chmod, and our chmod is excluded from it by ordering (check, then chmod, then delete, per entry); + the cutoff for the rest of the tree is unchanged. +8. **Interrupted cleanup** (crash/SIGKILL mid-walk) can leave directories with the extra owner bits inside a leftover work folder; that + folder is reported as a leftover (3d-2) and its recovery is reviewed, so the extra bits are never a surprise on a folder the person keeps. +9. **Fail closed.** If a chmod or a restore fails, the directory and what it holds are kept and reported; there is no escalation (no + `sudo`, no retry with a broader change). + +Regression tests (M01-06, real temp trees): a read-only tree is removed; only directories we own change, never files or links; a directory +**replaced by a symlink between the identity check and the chmod** is not followed and the target's mode is unchanged; a protected entry +is not chmod'd; a foreign-owned directory is not chmod'd and is kept; a hard-linked file's mode is unchanged; an immutable (`uchg`) +entry is kept; a stop mid-walk (revoke and cap) leaves every remaining directory at its **original mode** and reports a failed +restore; nothing outside the approved item changes; a revoked unattended run makes **no** chmod; the cutoff isn't tripped by our own chmod and a +genuinely changed entry still is; a chmod failure keeps the directory and doesn't retry broader. + +## 14. Responses to the revision-5 conditions + +| Condition | Resolution | +|---|---| +| Transition safety: legacy unattended path until 13-2; leftovers must not be consumed by it | New stage **13-0** (interim guard in `Scanner.children` and `AutoClean.select`), release rules in §7, and the alternative of disabling the legacy clean offered (§12.4) | +| Reserved vs successful removals | `reserved` vs `freed` tracked and recorded separately; charging a failed unlink is conservative, and `release` only for a syscall that reported failure so failures can't starve a run (§3c) | +| Attempted-slot marker durable before destructive execution | Not `UserDefaults`; durable file + `running` row, fixed order (commit, then `approve`), fail closed, tests (§3e) | +| `makeOwnerWritable` safety requirements and tests | §13 | +| §9.7 approved | Marked approved with its conditions (§9.7) | From 276d329be936f5ce573485a07aea51b5df9a2283 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Mon, 16 Nov 2026 03:36:39 +0100 Subject: [PATCH 7/8] M01-13 design: revision 7 (13-0 at Cleaner.remove, durable marker order and isDue feed, reserve stickiness, chmod restore/lazy/ACL) --- docs/architecture/M01-13_DESIGN.md | 71 +++++++++++++++++++----------- 1 file changed, 45 insertions(+), 26 deletions(-) diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index 79cca9c..8ff0ff6 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -122,7 +122,7 @@ why history reports **confirmed freed bytes separately** from the charge (3f). conservative by design. - **Where the check runs.** The Platform calls `control.reserve(charge)` **immediately before every `unlinkat` and `rmdir`** in the walk, and for an item that is a plain file (no walk) right before its unlink, using the stat taken in staging, putting the file - back if refused. The gate **adds each charge it approves to its reserved total**; it needs no report of successes from the executor. It refuses when `charged + next > maxBytesPerRun` (or revoked). A refusal stops the rest of + back if refused. The gate **adds each charge it approves to its `reserved` total** (the "charged" figure above is this same total); it needs no report of successes from the executor. It refuses when `charged + next > maxBytesPerRun` (or revoked). A refusal stops the rest of the walk (parent loops included); **after a stop no further folder is `rmdir`'d**; the unvisited entries and the folders holding them are kept (3d). - **Reserved is not freed.** The gate tracks **`reserved`** (charges approved, the budget) and history separately records **`freed`** (what @@ -130,7 +130,8 @@ why history reports **confirmed freed bytes separately** from the charge (3f). An entry whose `unlinkat`/`rmdir` **returned an error** (the entry is still there, nothing freed) is **released** by the Platform through `control.release(charge)`, so a run full of failures (the read-only Go module cache before M01-06's chmod, a locked file) can't spend the budget on nothing. Charging an entry whose unlink failed and not releasing it would also be safe (conservative), - but would let failures starve a run; `release` is allowed **only** for a syscall that reported failure, so `freed ≤ reserved` still holds. Tests: + but would let failures starve a run; `release` is allowed **only** for a syscall that reported failure, so `freed ≤ reserved` still holds. The gate **can't verify** that condition: it rests on the Platform's code at each site (`LocalFileSystem.swift` unlink/rmdir/single-file) and its tests, and the gate clamps `reserved` at zero. + **Stickiness:** once `reserve` refuses (cap or revoke) it **keeps refusing for the rest of the run**, so a smaller later entry or a parent loop can't slip through; the recursive `removeContents` has no abort path today, so 13-1 adds a stop flag that unwinds without further `rmdir`. **Thread safety:** the gate is lock-protected (`execute` is sequential, but a revoke arrives from the main actor while `reserve`/`release` run). **`freed`** is the Platform's pre-unlink stat estimate (`freed(s)`), as reported today; the confirmed figure is `measuredFreeChange`. Tests: success keeps the reservation, a failed unlink releases it, a skipped-by-stop entry never reserves, and `freed ≤ reserved` over real trees. - **Planning** uses estimates to choose what to attempt: admitted units smallest-estimate first (ties by path), greedy fill within the cap; the rest are **not planned** and listed as `deferred (over the run limit)` (this stops one rule or path order from starving @@ -178,8 +179,7 @@ accidents and a stale or corrupted store, not code written to forge it (8.3). - **The gate is a new input to the run loop.** Today `halt()` reads only the cancellation state and the `stopped` reason (`CleanupExecutor.swift` `execute`), and `precondition` runs only after an item's protection check. 13-1 adds the gate to `halt()` (so it is read before every target, including the first) and passes it down. -- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `control: RemovalControl?` parameter (a `Sendable` struct of two closures: `reserve(charge) -> String?`, the - stop check, and `release(charge)`, 3c), **which is the protocol requirement with no default implementation**; the old two-argument form remains only as an extension that forwards `control: nil` (so existing calls compile and interactive behaviour is unchanged, while a conformer can never silently ignore it). The Platform calls `reserve` before **each entry** with the +- **Revocation and the cap inside a long deletion.** `CleanupFileSystem.remove` gains a `control: RemovalControl?` parameter (a `Sendable` struct of two closures: `reserve(charge) -> String?`, which is also the stop check (a revoke or the cap makes it refuse; a chmod step asks `reserve(0)`), and `release(charge)`, 3c), **which is the protocol requirement with no default implementation**; the old two-argument form remains only as an extension that forwards `control: nil` (so existing calls compile and interactive behaviour is unchanged, while a conformer can never silently ignore it). The Platform calls `reserve` before **each entry** with the next entry's charge (3c). The gate is also asked **before the item is moved into its staging folder**, so a revoke before an item starts leaves it in place (`LocalFileSystem.remove` renames the item into staging before it visits any entry, so without this check the item's path would be absent for the whole walk). A non-nil reason is treated like a refused @@ -203,7 +203,7 @@ SIGKILL mid-walk (then the whole unvisited item is still inside). It can hold en review or became protected, and its original name is recorded nowhere on disk (slot `item`), so path-based protection (`UserProtection`) can no longer be applied to it. Today `LocalFileSystem.entries` hides the prefix, but the executor handles every *reviewed* entry (`CleanupExecutor.contents`), `Scanner.children` lists hidden files, and `PermanentDeleteRules` doesn't refuse the -prefix: a leftover in `~/Library/Logs`, or inside a contents-rule folder, could be deleted by the next unattended run. +prefix: a leftover that is a child of `~/Library/Logs` (hidden names aren't filtered there), or a kid of a `.removeContents` folder (which `Cleaner.run` lists with hidden files), could be deleted by the next unattended run. Not consumable at the top level today: `Library/Caches`, `Containers` and `Application Support` skip names starting with `.`, and `narrowed` drops any `~/.cache` child outside `autoDotCache`, so `~/.cache/.maccleaner-rm-X` is only **offered in the interactive list** as a recommended candidate. A work folder is created in the item's **own parent**, not a fixed folder, so the list of places is the parents of everything the run removes. - **Central exclusion.** The prefix becomes a public Core constant (`CleanupWorkFolder.prefix`, today `LocalFileSystem.stagingPrefix`). It is filtered in **every** discovery layer: `Scanner.children`, `Scanner.plan/measure` (so a folder's shown size excludes it), @@ -216,7 +216,7 @@ prefix: a leftover in `~/Library/Logs`, or inside a contents-rule folder, could (original path and work-folder path); kept entries already carry the work-folder path. **At launch and before each scheduled run** the app lists the known parents for leftovers and reports "work folders left behind" with their paths (history, notification and a Settings row). **Recovery is reviewed and never permanent deletion** (protection can't be re-verified): *Put Back* (`RENAME_EXCL` to the - original name, if it is free and the original path is known) or *Move to Trash*, each after the person sees the folder. + original name, if it is free and the original path is known) or *Move to Trash*, each after the person sees the folder. A leftover from a crash can contain directories with raised owner bits (§13.8); the Put Back row says so and offers to restore a mode only when the original is known, it never restores the folder silently. 13-1 (Core): the constant and the `admits` refusal. 13-2: the central filter in the app's scan, detection and reporting. **A separate stage, 13-2b, does the review UI** (Put Back / Move to Trash), because it is its own approval boundary. - A third-party folder that happens to use the prefix is never cleaned: a safe failure. @@ -244,14 +244,29 @@ prefix: a leftover in `~/Library/Logs`, or inside a contents-rule folder, could **A crashed slot is spent.** `lastRun` is written only after a run (`Automation.swift:314–316`), so a crash before it would make `isDue` fire again on relaunch, and a crash loop could free the cap again at each launch. The runner therefore persists the slot as **attempted** -**before any deletion**, together with the `running` row, so the cap is **per slot**; a crashed slot doesn't retry until the next one. -`UserDefaults` is **not** durable against a crash (writes are flushed later), so the marker is not a `UserDefaults` key: it lives in -the history's `running` row and in a small `AutomationState` file, written together with the **dedicated durable write** (3f: -temp file, `F_FULLFSYNC`, `rename`, `fsync` of the folder, under the lock, `commit`, failing closed). **The order is fixed: validate, -create the gate, durably commit the marker and the `running` row, and only then `approve` and `execute`. If the commit fails, no -run starts** (a "Not run: couldn't record the attempt" row is tried, and the slot stays unspent only if nothing destructive could -have happened). Tests: a counting file system shows zero removals when the commit fails; a simulated kill right after the commit -leaves the slot spent on relaunch; the marker is read from the durable file, not from `UserDefaults`. +**before any deletion**, so the cap is **per slot**; a crashed slot doesn't retry until the next one. + +- **`UserDefaults` is not durable against a crash**, so the marker is not a `UserDefaults` key. The **authoritative** store is a small + `AutomationState` file (`{ attemptedSlot, lastRunDate }`), written with the **dedicated durable write** (3f: temp file, `F_FULLFSYNC`, + `rename`, `fsync` of the folder, under the lock, `commit`, failing closed). The `running` history row is a second write and is + **informational**: two files can't be committed atomically, so the order is fixed. +- **Order:** validate and create the gate → durably commit the **marker** → commit the `running` row → scan, plan, pre-check → `approve` + → `execute`. Nothing destructive precedes the marker. The scan therefore comes **after** the marker (a crash during a long scan also + spends the slot, which is accepted). +- **A commit that fails is treated as possibly durable** (a `rename` can succeed and the directory `fsync` then fail), so **the slot is spent + whenever a commit was attempted**, and the process also remembers it in memory: **no run starts, no retry this slot, no retry every + 5-minute tick**. If the marker is committed and the `running` row's commit fails, the run does not start either (a failed row is not + worth a deletion without a record). A "Not run: couldn't record the attempt" row is tried, best effort. +- **`isDue` is fed from the durable file.** `isDue` only reads `lastRun` (`Automation.swift:67–70`), and the model's `lastRun` comes from + `UserDefaults`, so after a crash it would fire the slot again whatever the marker says. The `lastRun` given to `isDue` is therefore + **`max(UserDefaults lastRun, the marker's attemptedSlot)`, read from the durable file at launch and at each tick**. +- **`approve` can't run before the commit:** the gate has a **`committed` latch** that the runner sets only after both writes, and + `approve(under:gate:)` refuses an uncommitted gate (the counting-file-system test is then a second line, not the only one). +- `F_FULLFSYNC` can fail with `ENOTSUP` on some volumes; fail-closed then means the scheduled clean never runs there. **Accepted**, and + reported as "Not run: this volume can't make the record durable". +- **Tests:** zero removals (counting file system) when the marker commit or the row commit fails; a simulated kill right after the + commit leaves the slot spent on relaunch and `isDue` false for it; a failing commit doesn't re-attempt on the next tick; the + `lastRun` fed to `isDue` is the max; `approve` refuses an uncommitted gate; the marker is read from the durable file, not `UserDefaults`. **Paused or refused runs.** A run that doesn't start writes at most **one "Not run" row per scheduled slot**: the runner stores the slot it last reported (`auto.policyReportedSlot`, the `lastSlot` date) because a paused run doesn't set `lastRun` and @@ -296,8 +311,7 @@ decision §9.7 for the reviewer. If a run has more than 500 non-removed items, t **Durability of the checkpoint.** `SharedFile.update` today writes with `Data.write(.atomic)` (no `fsync`, and it writes even if the lock wasn't taken), and `read` returns `[]` on a decode error, so a checkpoint into a corrupt file would overwrite every record. 13-2 therefore gives history a **dedicated durable write**: temp file, `F_FULLFSYNC`, `rename`, `fsync` of the folder, all **under the lock and failing closed** (`commit`, not `update`); it refuses to write when the file is *unreadable* (distinct from *missing*); and if a checkpoint can't be committed it returns a stop reason from `onItemFinished`, so the run halts **before the next candidate**. The checkpoint is written when the **last target of a candidate** finishes (`onItemFinished` fires per target, synchronously, before the next). Cost: a rewrite of up to 300 records plus a full sync per candidate, tens of ms each. History also needs a new API for **0-byte rows and replace-by-id** (`HistoryStore.add` drops `bytes <= 0` and records are immutable), and the `running` row stores the **PID and boot session** so a second GUI instance mid-run isn't mistaken for a dead one. The candidate list itself is bounded: the first 300 candidate rows are listed and the rest are in `itemCounts`, with `N more not listed`. Sleep doesn't interrupt a run; only a quit or crash does. -**A run that dies: unknown is not zero.** The record is created at the start with `runStatus: running` (under the file lock, -before the scan), carries `bytesKnown: false`, and is **checkpointed after each candidate finishes** with the progress confirmed +**A run that dies: unknown is not zero.** The record is created at the start with `runStatus: running` (under the file lock, right after the durable marker (3e) and before the scan), carries `bytesKnown: false`, and is **checkpointed after each candidate finishes** with the progress confirmed so far (`confirmedBytes` = **freed as the file system reported it**, `confirmedItems`, same lock; separate from the charge, which is only the budget). At the end it is replaced by the final record (`bytesKnown: true`). If the app quits, crashes or the Mac sleeps in between, the next launch shows the row as `interrupted`: "at least *confirmedBytes* freed; the rest is **unknown**". It is **not** shown as "0 freed", and `totalDeleted` counts only `confirmedBytes`, labelled "at least". @@ -416,8 +430,8 @@ Platform tests in Features/Platform. | Stage | What | Level | Safety-critical | |---|---|---|---| -| **13-0** | **Interim guard for the legacy scheduled clean** (app, small): the work-folder prefix is refused by `Scanner.children` and by `AutoClean.select` (any path component, case-folded), with self-tests that a planted `.maccleaner-rm-X` in `Logs`, a contents folder and `~/.cache` is never planned or deleted by the legacy path. No behaviour change otherwise. Independent of 13-1; ships first. | Senior | **yes** (it changes what the unattended clean may delete) | -| **13-1** | Core: `AutomationPolicy`/scope/patterns/catalog v1 (literals + Appendix A, golden file; `package` initializers), `tightening`, `ValidatedPolicy`, one-shot `PolicyGate`, `AutomationConsent.validate(now:)`; the public work-folder prefix constant and the `admits` refusal; executor `approve(under:gate:)`, nonce→gate map, `execute(_, gated:)`, `gateRequired`, `useAutomationPolicy`, gate in `halt()`; new `KeptEntry.Reason.stopped`, `SkipReason.revoked/.runLimit`; `CleanupFileSystem.remove(stop:)` as the requirement (+ forwarding extension), the Platform walk's per-unlink/rmdir charge check, the single-file and pre-staging checks, both conformers (`LocalFileSystem`, test `FakeFS`); package tests above, including rewriting `CleanupExecutorTests.swift:346` (it calls the now-refused `approve(by: .standingPolicy)`). **App unchanged, unused**: `AutoClean.run` keeps deleting unattended without a gate until 13-2, so RISK-017 stays open until then. | Senior | **yes** | +| **13-0** | **Interim guard for the legacy scheduled clean** (app, small): the work-folder prefix is refused at the legacy path's **single choke point, `Cleaner.remove`** (`Scanner.swift`, every deletion of the legacy path goes through it, including each kid of a `.removeContents` folder that `Cleaner.run` lists itself with `contentsOfDirectory`, hidden files included): it skips any path whose **last component** starts with the prefix (case-folded) and reports it, and `SafetyGuard.isAllowed` also refuses such a path. `Scanner.children` and `AutoClean.select` keep a second layer (any path component, case-folded) so the item isn't even planned or sized. Self-tests: a planted `.maccleaner-rm-X` as a kid of a contents folder, as a child of `Logs`, and in `~/.cache` (interactive list only) is never planned or deleted. **Limit, stated plainly:** a leftover nested *inside* a tree that the legacy path removes recursively with `fm.removeItem` can't be spared without replacing that call; that is no worse than what the legacy path deletes today, and it is why the wording is "never a top-level target or contents kid", not "never". Also covers the MCP `clean_caches` tool, which shares `Scanner.plan` and `Cleaner.run`. No behaviour change otherwise. Independent of 13-1; ships first. | Senior | **yes** (it changes what the unattended clean may delete) | +| **13-1** | Core: `AutomationPolicy`/scope/patterns/catalog v1 (literals + Appendix A, golden file; `package` initializers), `tightening`, `ValidatedPolicy`, one-shot `PolicyGate`, `AutomationConsent.validate(now:)`; the public work-folder prefix constant and the `admits` refusal; executor `approve(under:gate:)`, nonce→gate map, `execute(_, gated:)`, `gateRequired`, `useAutomationPolicy`, gate in `halt()`; new `KeptEntry.Reason.stopped`, `SkipReason.revoked/.runLimit`; `CleanupFileSystem.remove(control:)` as the requirement (+ forwarding extension), the Platform walk's per-unlink/rmdir charge check, the single-file and pre-staging checks, both conformers (`LocalFileSystem`, test `FakeFS`); package tests above, including rewriting `CleanupExecutorTests.swift:346` (it calls the now-refused `approve(by: .standingPolicy)`). **App unchanged, unused**: `AutoClean.run` keeps deleting unattended without a gate until 13-2, so RISK-017 stays open until then. | Senior | **yes** | | **13-2** | App: consent store + Settings sheet (toggle revokes/enables), gate registry, scheduled runner on the executor with the per-target filter, cap, per-item pre-check and attempted-slot marker; central work-folder filter in `Scanner`; leftover detection and reporting; history fields, durable checkpoint, 0-byte/replace-by-id API, `SharedFile` fixes, migration and per-slot "Not run" row; **"Run safe clean now" through the review sheet** (Settings + menu-bar popover); sites script (allow the runner's `CleanupExecutor(`); self-tests; remove `AutoClean.run/select/narrowed`, `runClean(automatic:)` and the scheduled path's `Cleaner.run`. **Waits for M01-06's caches candidate builder.** | Senior | **yes** | | **13-2b** | Review UI for leftover work folders: Put Back (`RENAME_EXCL`) or Move to Trash after review, never permanent delete. | Senior | **yes** (approval boundary) | | 13-3 | Docs: ARCHITECTURE_V2 (remaining §3a/§5 wording), SAFETY_MODEL, RISK_REGISTER (close RISK-017), CURRENT_STATE, MIGRATION_PLAN, DECISIONS. | Junior | no | @@ -426,7 +440,7 @@ Platform tests in Features/Platform. deletes unattended with no gate, as it does today. Rules for any release cut from `main` in that window: (1) **13-0 must be in it**, so the legacy path can't consume a leftover work folder (a risk that exists today, because `Scanner.children` lists hidden files and `remove` can leave a leftover); (2) 13-2 is preferably in the same release as the first M01-06 module that changes what the scheduled path -lists, otherwise the legacy path is unchanged; (3) the release notes say the scheduled clean still runs under the old rules. The stricter +lists, otherwise the legacy path is unchanged; (3) the release notes say the scheduled clean still runs under the old rules, **including that the 20 GB cap, the gate and revocation do not exist before 13-2 and that "Run safe clean now" is the same unreviewed `AutoClean.run`** (`Automation.swift:446`, `MenuBarPopover.swift:123`). The stricter alternative is to **disable the legacy scheduled clean** in any release before 13-2 (a kill switch that turns `AutoSchedule` off with a notification); it costs users their scheduled cleans until 13-2 and is **not** recommended, but it is the user's call (§12). @@ -448,7 +462,7 @@ reviewed stage, then 13-2. Hotspots 13-2 touches: `check-approval-sites.sh`, `Se 4. **Classes by shape stay open in membership.** v1 admits the cache of any app installed later at an in-pattern path. Bounded by depth, literals, exclusions, protection, running-app skip and the cap, and stated in the consent sheet. 5. **The 20 GB cap** can defer a cleanup to the next run or a manual clean, and **a single item bigger than the cap is never cleaned by the schedule**. It never deletes more than today, only less. 6. **A stop mid-folder leaves a partly deleted folder** (kept entries stay, reported). If the name was retaken, the remainder stays in a hidden staging folder, reported with its path. No undo for permanently deleted entries. -7. **`CleanupFileSystem.remove` changes** (new `stop` parameter, new Core enum cases) touch the shared executor/Platform, safety-critical, and may overlap with M01-06; sequenced in 13-1 with tests before anything uses it. +7. **`CleanupFileSystem.remove` changes** (new `control` parameter, new Core enum cases) touch the shared executor/Platform, safety-critical, and may overlap with M01-06; sequenced in 13-1 with tests before anything uses it. 8. **Running-app detection is best effort**, not a lock: an app can start between the check and the delete. Unknown or unreadable cases skip. 9. **Several executors per process:** `ApprovedTrash` has one, `AppOwnedTrash` makes one per move, and the runner makes its own (so `check-approval-sites.sh`'s `CleanupExecutor(` rule must allow the runner's file). A scheduled and an interactive run therefore do **not** wait for each other; concurrent runs are safe because of `RENAME_EXCL` and the identity checks. The nonce→gate map and `gateRequired` live per executor instance, which is fine because a gated approval is made and used by the same one. 10. **Unchanged limits (SAFETY_MODEL.md):** macOS has no "delete only if unchanged"; a process can write to a file it had open after the last check. @@ -525,7 +539,9 @@ Not checked by the reviewer and still to do before 13-1: the `CleanupFileSystem` `Staging` prefix interaction with later scans; `package`-init feasibility across Features/Platform. Whether to ask for an Opus review (`mc-safety-architect`) of this design before 13-1 is the user's call; it has not been requested. -## 11. Responses to the Opus safety review (`mc-safety-architect`, on fdc9ae7: REQUEST CHANGES) +## 11. Responses to the Opus safety review + +(These tables are historical: they use the older name `stop` for what revision 6 calls `control` (`reserve`/`release`).) (`mc-safety-architect`, on fdc9ae7: REQUEST CHANGES) Each claim was checked against the code before acting (`LocalFileSystem.freed` counts folder and link blocks; `Scanner.children` lists hidden files; the executor handles every reviewed entry whatever `entries` returned). @@ -579,18 +595,21 @@ hook (`control` is asked before it). 4. **Within the item and the home volume.** Never above the item, never across a device boundary, never into a mount. 5. **Protection and the gate first.** `protection(path)` is asked before each directory's chmod; for an unattended run `control.reserve` is asked first too, so a revoked run **never starts a permission change** and a stopped run changes no more. -6. **Original modes are recorded and restored.** Each directory's original mode is recorded before it is changed. If the walk stops - (revoke, cap, protection, failure, cancellation), every directory that **remains** (kept, or put back) gets its original mode back; - a restore that fails is reported (`KeptEntry` text and a warning), never ignored. Directories that are deleted need no restore. +6. **Original modes are recorded and restored.** Each directory's full original mode (`st_mode & 07777`, not only the owner bits) is recorded before it is changed. Every directory that **remains** after the walk gets it back: on a stop (revoke, cap, protection, failure, cancellation) **and on normal completion** (a folder kept as `.notEmpty`, `.protected` or `.changedAfterReview`). The restore runs **while that directory's fd is still open, in the unwinding frame, and before the put-back or the root's rename** (the recursion closes fds and the put-back moves the folder); a restore that fails is reported (`KeptEntry` text and a warning), never ignored. Directories that are deleted need no restore. 7. **The change-time cutoff isn't tripped by our own chmod** (chmod updates ctime): the "changed after review" check for an entry is made on a stat taken **before** that entry's chmod, and our chmod is excluded from it by ordering (check, then chmod, then delete, per entry); the cutoff for the rest of the tree is unchanged. 8. **Interrupted cleanup** (crash/SIGKILL mid-walk) can leave directories with the extra owner bits inside a leftover work folder; that folder is reported as a leftover (3d-2) and its recovery is reviewed, so the extra bits are never a surprise on a folder the person keeps. -9. **Fail closed.** If a chmod or a restore fails, the directory and what it holds are kept and reported; there is no escalation (no +9. **Lazy, and narrower than the legacy path on purpose.** Today `Cleaner.remove` calls `makeOwnerWritable` only after a first `removeItem` + fails (`Scanner.swift:437–441`); the successor does the same: **a chmod happens only for a directory whose removal failed with + `EACCES`/`EPERM`**. `fchmod` needs an open fd, so a directory with no owner read/execute bit (for example mode 000 or 300) can't be opened + and is **kept and reported, with no path-based fallback** (the Go module cache, 0555, works). **ACLs are never touched** (no + `chmod -N`, no `acl_set`): a deny-delete ACL entry still blocks deletion, and the directory is kept. +10. **Fail closed.** If a chmod or a restore fails, the directory and what it holds are kept and reported; there is no escalation (no `sudo`, no retry with a broader change). -Regression tests (M01-06, real temp trees): a read-only tree is removed; only directories we own change, never files or links; a directory +Regression tests (M01-06, real temp trees; the listed ones plus restore on normal completion for kept directories, restore before put-back and in the name-retaken-in-staging case, a mode-000 directory kept and reported with no fallback, a deny-delete ACL kept and untouched, `fchmod` `EPERM` on a `uchg` directory, and a simulated crash leaves raised bits only inside the staging folder): a read-only tree is removed; only directories we own change, never files or links; a directory **replaced by a symlink between the identity check and the chmod** is not followed and the target's mode is unchanged; a protected entry is not chmod'd; a foreign-owned directory is not chmod'd and is kept; a hard-linked file's mode is unchanged; an immutable (`uchg`) entry is kept; a stop mid-walk (revoke and cap) leaves every remaining directory at its **original mode** and reports a failed From 6643e255d59d572a87033da2e130df330e3df7d1 Mon Sep 17 00:00:00 2001 From: WahdanZ Date: Mon, 16 Nov 2026 03:37:14 +0100 Subject: [PATCH 8/8] M01-13 design: wording fixes from the revision-7 re-check --- docs/architecture/M01-13_DESIGN.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/architecture/M01-13_DESIGN.md b/docs/architecture/M01-13_DESIGN.md index 8ff0ff6..4c2fe11 100644 --- a/docs/architecture/M01-13_DESIGN.md +++ b/docs/architecture/M01-13_DESIGN.md @@ -223,7 +223,7 @@ prefix: a leftover that is a child of `~/Library/Logs` (hidden names aren't filt ### 3e. The scheduled run (app target) -1. `tick` finds the schedule due (unchanged `isDue`/`armedAt`) and `auto.weeklyClean` on; otherwise stops. +1. `tick` finds the schedule due (unchanged `isDue`/`armedAt` (with `lastRun` fed from the marker, §3e)) and `auto.weeklyClean` on; otherwise stops. 2. **Validate the stored consent and create the gate** (3d). On `Invalid`: no scan, no deletion, one "Not run" history row for this slot (below) and one notification per reason. 3. Plan: scan as today (`Scanner.plan/measure/finalize`), build `CleanupCandidate`s through the caches builder (M01-06; @@ -344,12 +344,12 @@ sheet file and the self-test; nothing under the MCP/CLI files; no `AutomationCon | Folder swapped for a symlink / replaced / newly protected between snapshot and delete | executor revalidation skips it | | App owning a cache starts after the snapshot, or can't be identified | skipped (`precondition`; unknown owner fails conservative) | | User turns it off during the scan, before an item, or inside one huge folder | gate refuses `approve`, or stops before the item / next entry; rest kept and reported | -| Estimate too low, or caches are huge | stop at 20 GB freed; remaining units deferred and listed | +| Estimate too low, or caches are huge | stop at the 20 GB accounted charge; remaining units deferred and listed | | One path of a merged candidate is out of scope | that path dropped and listed; the others run | | A command / review / user-data / Trash item reaches the plan | `admits` refuses; ledger's generic check refuses again | | Another caller asks for `.standingPolicy`, or runs one without the gate | refused (`useAutomationPolicy`, `gateRequired`) | | App quits mid-run | row shows `interrupted`; freed bytes **unknown** (at least the confirmed amount), never 0 | -| Two runs for one slot, or a run right after enabling | unchanged `isDue`/`armedAt` rules | +| Two runs for one slot, or a run right after enabling | unchanged `isDue`/`armedAt` (with `lastRun` fed from the marker, §3e) rules | | Mac asleep at the slot | catch-up on wake, unchanged | ## 5. Migration of existing installs @@ -510,6 +510,8 @@ app / sandboxed / web caches and logs (§3b). (The Xcode device-support folders ## 10. Responses to the review findings +(§10 and §11 are historical: they use the older name `stop` for what revision 6 calls `control` (`reserve`/`release`).) + **The user's five required fixes** | # | Finding | Resolution (where) | @@ -539,9 +541,7 @@ Not checked by the reviewer and still to do before 13-1: the `CleanupFileSystem` `Staging` prefix interaction with later scans; `package`-init feasibility across Features/Platform. Whether to ask for an Opus review (`mc-safety-architect`) of this design before 13-1 is the user's call; it has not been requested. -## 11. Responses to the Opus safety review - -(These tables are historical: they use the older name `stop` for what revision 6 calls `control` (`reserve`/`release`).) (`mc-safety-architect`, on fdc9ae7: REQUEST CHANGES) +## 11. Responses to the Opus safety review (`mc-safety-architect`, on fdc9ae7: REQUEST CHANGES) Each claim was checked against the code before acting (`LocalFileSystem.freed` counts folder and link blocks; `Scanner.children` lists hidden files; the executor handles every reviewed entry whatever `entries` returned).