Skip to content

Latest commit

 

History

History
653 lines (550 loc) · 38.7 KB

system.md

File metadata and controls

653 lines (550 loc) · 38.7 KB

Lumen system architecture

Status: accepted architecture baseline, 2026-10-06. Decisions are recorded in docs/decisions/; research in docs/research/. This document summarises how the pieces fit; when it disagrees with an ADR, the ADR wins and this document must be fixed.

1. Purpose

Lumen answers two questions on every device it runs on:

  1. What is consuming my storage?
  2. What can I safely remove, and why?

It answers them by collecting evidence, building relationships, and applying a deterministic safety policy. Every removal is reversible where the platform allows, and is explained.

Non-goals:

  • "Speeding up" devices or registry cleaning.
  • Deleting anything without explicit user confirmation of a specific plan.
  • Cleaning other apps' data on iOS.
  • Any action the platform does not support (see platforms).

2. Product loop

DISCOVER → SCAN → COLLECT EVIDENCE → BUILD RELATIONSHIPS → CLASSIFY
        → (optional) JEV JUDGMENT → SAFETY POLICY → EXPLAIN
        → USER CONFIRMS PLAN → QUARANTINE → VERIFY → RETAIN → FINALIZE | ROLLBACK

Outcomes are KEEP, REVIEW or QUARANTINE. There is no REMOVE verdict. Permanent deletion happens only when quarantine is finalized, after retention or on explicit request.

3. Principles

Principle Mechanism
Safety over reclaimed space Hard-protection stage in the policy; unknown → KEEP/REVIEW (ADR-0014)
AI is evidence, never authority JudgeModel port, closed vocabulary, monotone-safety contract (ADR-0020)
Reversible by default Journaled same-volume quarantine (ADR-0015)
No path confusion Single handle-relative executor (ADR-0016)
Blind spots are visible Capability model and coverage reports (ADR-0008)
Honest numbers SizeFacts and reclaimable_now (ADR-0017)
Local-first, private No content upload; telemetry opt-in and content-free (ADR-0022)
Earned complexity Modular monolith (ADR-0002)

4. Context

                 ┌──────────────────────────────────────────────────────────┐
  User ─────────▶│ Lumen UI (Tauri webview / browser dashboard / Expo app)  │
                 └───────────────┬──────────────────────────────────────────┘
                                 │ view models, plan IDs (ADR-0023)
                 ┌───────────────▼──────────────────────────────────────────┐
                 │ Lumen core (Rust): application use cases                 │
                 │  scan · evidence · graph · policy · plan · quarantine    │
                 └──┬────────────┬──────────────┬───────────────┬───────────┘
                    │ ports      │              │               │ optional, user's choice
        ┌───────────▼───┐ ┌──────▼──────┐ ┌─────▼──────┐ ┌──────▼──────────────┐
        │ OS APIs       │ │ SQLite      │ │ Developer  │ │ Jev providers        │
        │ (fs, inventory│ │ index.db    │ │ tools (CLI │ │ on-device / cloud    │
        │  processes)   │ │ ledger.db   │ │ cleanup)   │ │ (metadata only)      │
        └───────────────┘ └─────────────┘ └────────────┘ └─────────────────────┘

5. Building blocks

5.1 Layers and crates

The full crate map is in ADR-0003. Crates are created only when their first code lands.

                      lumen-domain   (types, IDs, invariants, state machines)
                       ▲        ▲
              lumen-policy    lumen-graph     (pure, IO-free)
                       ▲        ▲
                    lumen-application         (use cases + ports)
        ▲            ▲            ▲             ▲              ▲
 lumen-scan   lumen-fs-exec  lumen-store-sqlite  lumen-jev   lumen-platform-*
 lumen-devkb  lumen-telemetry
        ▲            ▲            ▲             ▲              ▲
      lumen-app  ·  lumen-api  ·  lumen-ffi  ·  apps/desktop (Tauri host)  ·  lumen-cli
      lumen-helper (macOS launch daemon, ADR-0063)

Dependency rules (checked by cargo xtask lint, part of just check and CI):

  • lumen-domain, lumen-policy and lumen-graph have no IO, no async runtime, no platform code and no #[cfg(target_os)].
  • lumen-application defines ports; it depends on no adapter.
  • Adapters depend on lumen-application (and on lumen-scan for platform enumerators), never on each other, except for test support.
  • Only composition roots select platform adapters.
  • Only lumen-fs-exec may call destructive filesystem APIs.

5.2 Ports

Port Responsibility Desktop adapters
DirEnumerator Batched directory metadata → EntryBatch with SizeFacts and access state getattrlistbulk, FileIdExtdDirectoryInfo, getdents64 + statx, std::fs fallback
CandidateVerifier Re-read a candidate by handle before it is proposed or acted on: identity, exact link count, compressed size, sharing directory handles (Windows); getattrlist with PRIVATESIZE (macOS)
ChangeFeed Persisted change streams with resume points FSEvents, USN, ReadDirectoryChangesW, inotify
InventorySource Applications, packages, processes, services, startup items per OS (bundles + pkgutil, launchd plists; Uninstall keys, MSI, AppX, Run keys, Task Scheduler, SCM)
InUseProbe Is an item open or owned by a running process? Unknown when not every process is visible, never "unused" libproc; Restart Manager
QuarantineStore Per-volume stores, manifests, retention lumen-fs-exec
Executor Plan execution by handle with identity verification lumen-fs-exec
ToolRunner Run vetted developer-tool cleanup commands as the user lumen-devkb
Store Persist scans, graph, decisions, ledger lumen-store-sqlite
JudgeModel Optional evidence from AI lumen-jev
SecretStore Credentials Lumen needs (the OpenRouter key), never in databases or logs macOS Keychain, Windows Credential Manager
Clock, IdGenerator Deterministic time and IDs in tests std / fakes

Ports for filesystem and OS inspection are synchronous. They run on plain std threads: the scanner's scoped worker threads (crates/lumen-scan/src/scheduler.rs) or the calling thread. Only model-bound ports (JudgeModel, Describer) are async; there is no async runtime, and lumen_app::block_on (crates/lumen-app/src/runtime.rs) runs their futures on the calling thread (ADR-0017 amendment).

6. Domain model

All types live in lumen-domain and are serialisable with versioned JSON Schemas (ADR-0011).

6.1 Identifiers

Identifiers are typed newtypes, never bare strings or integers:

Type Meaning
DeviceId Random per install
VolumeId Volume UUID / serial
FileIdentity (VolumeId, file_id: u128): inode or NTFS FileId
NodeId Graph node
EvidenceId BLAKE3 of the canonical evidence record
EvidenceHash Merkle root of an evidence bundle
ScanId, SnapshotId, PlanId, OperationId Lifecycle entities
PolicyVersion, PromptVersion, SchemaVersion Semantic versions

Paths are stored as raw bytes (OsString semantics) plus an escaped display form. Filesystem identity, not path text, is the key for every decision.

6.2 Core entities

Entity Key fields
Device id, platform, OS version, capabilities
Platform macos, windows, android, ios; and PlatformCapabilities
Volume id, mount points, filesystem, case and normalisation behaviour, supports no-replace rename, supports clones
FilesystemEntry identity, parent, name bytes, kind, SizeFacts, times, flags, AccessState
Application bundle / package ID, name, version, vendor, signing team, install locations, sources
Process pid, executable identity, owning application, start time
Service kind (launch agent/daemon, Windows service, scheduled task, startup entry), definition location, target executable, enabled state
Package package manager or installer, identifiers, owned paths
Artifact A classified thing worth explaining: one entry or a group (e.g. "Xcode DerivedData for project X"), with a category
Evidence Immutable fact with provenance (§7)
Relationship Typed, directed edge between nodes
CoverageReport Roots and sources observed, denied, truncated

6.3 Decision entities

CleanupCandidate is what users review:

CleanupCandidate
 ├── target            Artifact ref (+ FileIdentity set)
 ├── size              SizeFacts aggregate (logical, allocated, reclaimable_now, after_snapshots)
 ├── category          e.g. app_cache, developer_build_output, log, duplicate, orphaned_service
 ├── evidence[]        EvidenceId list
 ├── relationships[]   edges used by the explanation
 ├── regeneratable     Yes | No | Unknown (with evidence)
 ├── currently_in_use  Yes | No | Unknown
 ├── protected         bool + protection rule id
 ├── risk              Low | Medium | High | Critical + factors
 ├── confidence        rule-based confidence; Jev calibrated confidence kept separately
 ├── policy_decision   PolicyDecision
 └── reversible        Reversible(mechanism) | Irreversible(reason)
  • PolicyDecision: verdict, policy_version, evidence_hash, fired rules (each with the evidence IDs it used), Jev effect, explanation.
  • AIJudgment: the validated Judgment plus its JevTrace (model, model version, prompt version, policy version, schema versions, evidence hash, timestamp, decision, confidence).
  • Recommendation: the user-facing projection of a decision, with explanation and available actions.
  • CleanupAction: one of QuarantineMove, ToolCommand, MediaTrash, PhotoLibraryDelete, CloudEvict, OpenSystemSettings, ArchiveApp. Each declares its reversibility.
  • CleanupPlan: an ordered set of actions bound to a PlanId, with a plan hash, the decisions it relies on, and expected identities. Each item records who chose it (Chooser::Policy for a proposed item, Chooser::Person for a review item the person chose), and the hash (lumen.plan/2) covers that (ADR-0051). A log or temporary item also binds the newest change shown for it (scratch_change, ADR-0070); other items omit the field, preserving existing plan bytes and hashes. Just before such an item moves, its subtree is listed again and its newest change read again; the item stays where it is when that change is later than the bound, cannot be read completely, or the plan has no bound.

6.4 State machines

Scan:

Created → Running ⇄ Paused → Completed | Cancelled | Failed(partial results kept)

Quarantine item (ADR-0015):

Planned → Journaled → Moved → Verified → Retained → Restored | Finalized
   └─────────── Failed(reason): original untouched or restorable ──────────┘

Plan:

Draft → Proposed → Confirmed(user, token) → Executing → Completed | PartiallyCompleted
      → RolledBack (optional)

Invariants (property-tested):

  • An item cannot reach Moved without a durable Journaled record.
  • Finalized is reachable only from Retained.
  • A plan cannot be Executing without Confirmed.
  • REVIEW items are never part of a confirmed plan unless the user individually chose them; a chosen item is confirmed only while it is still REVIEW (or QUARANTINE) for the same rules, and is never finalized when retention ends (ADR-0051).

7. Evidence graph

See ADR-0013 and evidence-graph.md for the full model. The graph is a typed property graph stored in index.db (nodes, edges and evidence tables) with an in-memory adjacency index per analysis.

Example chains:

Application ─creates→ CacheDirectory ─opened_by→ Process ─launched_by→ LaunchAgent
Docker Desktop ─stored_in→ VM disk image ─contains→ images ─contains→ layers
Uninstall entry ─installed_by→ MSI product ─owns→ InstallLocation ─contains→ entries

Every evidence record carries its source adapter and API, the observation time, and a coverage reference. Bundles for policy and Jev are canonically serialised, and their Merkle root (EvidenceHash) is recorded with every decision.

8. Safety policy

See ADR-0014. The stages run in order: hard protections → eligibility → classification → Jev (monotone) → user confirmation. The policy is IO-free and versioned; decisions are reproducible from (policy_version, evidence_hash).

lumen-policy implements the stages. A hard protection ends evaluation with KEEP. Protected locations are kept with everything below them (protect.location.<id>), and so is every folder that holds one (protect.contains-system, -sensitive or -cloud, by the most critical kind held): moving ~/Library would move the keychains inside it (FS-3). Eligibility rules cap the verdict: an item the platform cannot quarantine, or a link or special file, is at most REVIEW, and an item whose removal would free no space now (eligible.frees-nothing: empty, or shared with hard links, clones or snapshots) is KEEP. Classification takes the most cautious proposal, so only a classification rule can make an item a quarantine candidate. When no rule recognises an item, it is REVIEW (default.review) if it is at least 100 MB or its size is unknown, and KEEP (default.keep-small) if it is smaller. A validated Jev judgment can then only demote a quarantine proposal to REVIEW (jev.demote); it never touches KEEP or REVIEW.

REVIEW is kept for items a person can act on (ADR-0039): an application's own data, settings or documents are kept (classify.app-state), while orphaned application data, whose owner every inventory says is gone, is reviewed (classify.orphan). Items with a tool's own cleanup command stay REVIEW, and the interface lists them on their own, with the command (ADR-0035).

An item directly inside the user's log folder (macOS ~/Library/Logs) or temporary folder (Windows) is REVIEW (classify.scratch), never proposed (ADR-0070). Age only keeps: it is KEEP when it changed within 7 days (temporary) or 30 days (logs) (classify.scratch-recent), when its age is unknown (classify.scratch-age-unknown), or when it is or holds a crash or diagnostic report (classify.scratch-report).

A known artifact inside an application's state is decided on its own (ADR-0040): a knowledge-base match nested in a candidate identified only as app state (such as an Electron app's Cache in its Application Support folder) is its own candidate, and the app's folder is kept for the rest of it, sized without the nested candidates.

Large folders that no evidence names become candidates too (ADR-0051): after a scan, at most 30 directories of at least 1 GiB, at the level where their size is spread out, fully listed, and never inside, around or equal to another candidate (evidence graph). Their only extra fact, LargeUnrecognised, is one no rule reads, so the policy decides them as any unrecognised item: default.review, or KEEP when a protection fires. They are never proposed for quarantine.

Security software stays list-only (ADR-0060 rule 4): an item with an OwningSecuritySoftware fact, a positive platform observation that its owner is security software (never a name or an AI answer), is kept as a hard protection (protect.security-software). On macOS, an item gets it when it already carries an installed app's OwningApplication and one of that app's bundles has the Endpoint Security entitlement in its signature, read with codesign (lumen_application::security_owners); an unreadable signature adds nothing. Windows has no producer yet.

Application usage counts only towards caution (ADR-0059):

  • an item whose owning application is running is kept (protect.app-running). On macOS, an application runs when a process's executable lies inside one of its bundles. That is read from the assessment's one read of the process table, and read again when a plan is confirmed or an item is checked again;
  • application data whose owner any source finds installed is not orphaned;
  • when an application was last opened (ApplicationLastOpened) and when a project last changed (ProjectActivity) are shown and never decided on.

None of these facts is sent to AI review.

Some verdicts rest on what Lumen did not know at assessment time, and a person can ask for those items to be checked again (ADR-0058). lumen_application::reassess::gaps maps fired rules to the gaps a read-only check may answer:

  • in use, partly visible or unknown, or kept because its application runs → asked live again;
  • not read, or not observed → its subtree listed again;
  • an old observation → observed again;
  • default.review or classify.orphan → the inventories read again.

Every other rule is a decision, and anything AI review changed is never re-decided. reassess decides the item again with the unchanged policy and no judge, only while its path still names the scanned object. It records the earlier verdict and rules and the evidence the new decision added. reassess_all takes at most 500 items and stops when cancelled. lumen_app::reassess runs the checks:

  • it loads the scan's evidence again, with the inventories read now;
  • it lists an unread or stale item again from the filesystem, read-only, for at most 30 s, after which the rest stays unlisted and kept;
  • it asks the live in-use probe, never the assessment's snapshot.

9. Explainability

Every Recommendation answers, from evidence (or states "unknown" with the reason):

Question Source
What is this? category + knowledge-base entry + node type
Why does it exist? / What created it? created_by, owned_by, installed_by edges
Is anything using it? opened_by, running processes, launches edges, in-use probe
Can it be regenerated? knowledge base, vendor-declared cache evidence
How much space does it use? SizeFacts: logical, allocated, reclaimable now, after snapshots
What happens if I remove it? knowledge-base consequence text + regeneration cost
Can I undo it? CleanupAction reversibility + retention window
Why did Lumen recommend this? fired rules with evidence, Jev effect, coverage caveats

Explanations are generated from templates, never from AI free text. A Jev rationale, if present, is shown separately and labelled as AI-generated.

REVIEW candidates also expose a review-reasons/1 descriptor: stable typed categories for unknown ownership, shared resources, possible user data, uncertain space, tool-required cleanup and AI caution. Every REVIEW has a category; KEEP and QUARANTINE have none. These categories are derived after evaluation, never fed back into policy or plans. Fired rules and localized explanations, with their supporting facts, remain the explanation shown to people. The view accepts future category strings so an older UI can retain its existing rule-text fallback. active_process and stale_evidence are reserved descriptive codes, emitted only when the relevant evidence supports them; active use still invokes the existing KEEP protection.

An item kept only because a running process uses it (protect.in-use) also says what quitting would allow (ADR-0039, 2026-10-31 amendment): assessment evaluates its input once more, by the policy alone, with the fresh in-use fact replaced by "not in use" (both No and Partial). When both would be QUARANTINE, Assessed.free_when_closed names the processes the probe reported (CandidateView.free_when_closed, escaped like paths), and lumen assess and the clean-up page say which apps to quit and scan again. The verdict stays KEEP; the counterfactual is never stored, planned, confirmed or sent to Jev.

10. Scanning

See ADR-0017 and ADR-0018.

  • Modes: full, incremental (change feed), targeted (subtree or category), background (agent, low priority), cancel, and resume (checkpoints).
  • Pipeline: scoped std worker threads, one directory at a time from a shared queue (crates/lumen-scan/src/scheduler.rs) → bounded channel → the calling thread, which aggregates coverage and sizes and reports progress (crates/lumen-app/src/scan.rs) → bounded channel → the single index.db writer thread (crates/lumen-store-sqlite/src/writer.rs). Per-volume semaphores, priority bands and a stall watchdog are not built yet.
  • Partial failure: per-directory errors become Denied or Error nodes; the scan continues and the coverage report records them.
  • Never hydrate placeholders, never open contents during scanning, never open archives.

11. Cleanup execution

  1. The user selects candidates. The core builds a CleanupPlan, re-runs the policy on fresh evidence, and returns PlanId plus the plan hash. The plan holds every candidate the policy proposes and the review items the person chose (lumen plan --choose <PATH>): only REVIEW items without a tool command or classify.devkb-not-regenerable; any other chosen path fails the plan with the reason (ADR-0051).
  2. The user confirms. The UI sends execute_plan(plan_id, confirmation_token).
  3. Per item, the executor re-verifies identity by handle, checks the in-use gate (No, or Partial for the user's own files under ADR-0030), writes a journal intent, performs a no-replace rename into the quarantine store, verifies, and records completion. A mismatch aborts that item to REVIEW.
  4. Retention then finalization, or rollback by operation ID. Only items the policy proposed are finalized when retention ends; an item the person chose, or one whose chooser the ledger does not record, stays until the person restores it or removes it for good (ADR-0051).
  5. Tool actions (developer caches) and other irreversible actions are executed separately, after a dry run, labelled irreversible.

12. Specialised subsystems

12.1 Orphan Hunter

The Orphan Hunter finds services, startup entries, launch agents, package remnants and security modules whose owning application appears to be gone. It produces evidence cards, never deletions:

Detected third-party component.
Associated application: not found (searched: /Applications, Spotlight, LaunchServices, receipts)
Last activity: 184 days ago          System service: yes
Executable: present (unsigned)       Vendor: unknown
Coverage: complete for user scope; system scope read-only
Risk: HIGH                           Recommendation: REVIEW

Rules:

  • "Absent" requires positive evidence across all applicable sources with complete coverage.
  • Security software, kernel or system extensions, and unknown executables are always REVIEW or KEEP.
  • Actions are delegated to the OS where possible (System Settings › Login Items, StartupApproved toggles that the user confirms per item). Lumen never edits the macOS BTM database or deletes Run values or tasks.

12.2 Developer Mode

Developer Mode is driven by the lumen-devkb knowledge base (ADR-0021): Xcode DerivedData and simulators, Docker, node_modules, pnpm, npm and Yarn caches, Cargo, Gradle, CocoaPods, Next.js build output, Android build outputs, IDE caches, AI tool caches and Homebrew. The tool's own cleanup command is preferred; self-managed caches are shown as informational. Cargo project matching covers only the default debug and release intermediate deps, build and incremental directories beside a scanned regular Cargo.toml; final outputs and custom layouts remain outside that entry. A project's node_modules directory is regenerable only beside a scanned regular npm, pnpm, Yarn or Bun lockfile, and a project location never matches inside another instance of its own path, such as a package's node_modules inside node_modules (research 31). When a candidate matched an entry with a tool command, lumen assess, lumen plan and the clean-up page show it (CandidateView.tool_command, quoted for a POSIX shell when copied). In the desktop app the user can also run it, after a confirmation that it cannot be undone: run_tool_command names the entry, and the host runs that entry's command from the knowledge base without a shell (lumen_app::tools, ADR-0049). The resolved search path is also passed to the tool, so interpreters and child programs work when Lumen was opened from the Dock or Finder. Homebrew's reviewed cache command includes --prune=all --scrub so recent downloads are considered; its preview uses the same flags with --dry-run. The UI explains possible re-downloads before confirmation. Homebrew decides removal eligibility; --prune=all can also remove downloads for installed packages (scope research). Assessment resolves custom cache locations from the running process's environment, reading only variable names declared for the current platform in the knowledge base. Unset or invalid roots do not match; variables are not inferred from a terminal's configuration or collected wholesale. Matching a custom location supplies evidence, not permission to remove it: all existing policy and execution checks still apply. A tool uses the folder its variable names instead of its default one, and its command inherits Lumen's environment, so while one of an entry's variables is set the command is shown, and can be run, only with that variable's folder (KnowledgeBase::command_acts_on). An old default folder beside it still matches the entry and keeps its verdict, but is shown without the command. If the entry's variables name different folders, Lumen cannot tell which one the tool uses and shows the command with none of them.

Permanent removal and confirmed tool commands also report observed free-space changes (SpaceChangeView). Each target volume is measured at its surviving parent, with the directory identity checked around both readings. Unavailable or changed targets remain unknown; tool measurements require complete coverage of at most 64 matched targets and de-duplicate volumes. Negative changes are preserved. These are immediate observations, not proof of bytes reclaimed by Lumen: snapshots, delayed reclamation and other programs can affect them. Only aggregate byte readings enter local logs; paths and volume identifiers do not. Cleanup outcomes stay independent of measurement availability, and quarantine alone is not reported as freeing space. The shared UI shows the selected items' estimate separately from the observed change, including decreases, no change, and unavailable measurements. A batch compares the first and last reading per volume rather than adding overlapping observations; expandable details show both readings. Results persist when navigating away. Distinct volumes can share available storage (for example APFS volumes in one container), so the UI never adds their changes into a single total; it shows each volume separately (measurement rationale).

Entries are JSON files in crates/lumen-devkb/entries/, one per artifact, embedded at build time and validated on load against schemas/devkb-entry.schema.json plus rules the schema cannot express:

  • paths are relative to a known root, and never the root itself or every child of it;
  • a project location needs marker files;
  • an optional location kind restricts evidence to a real directory or regular file;
  • programs are bare names that the runner resolves from the user's PATH, then known install locations, and arguments are an argument vector, never a shell string;
  • a tool_action entry has an action, and a not_regenerable one never does;
  • sources are https URLs;
  • last_verified is a real date. A weekly scheduled job (cargo xtask devkb --max-age-days 180) fails when an entry is older than 180 days or dated in the future.

12.3 Duplicates

lumen_application::duplicates implements the bounded, cancellable grouping use case independently of metadata scanning. It collapses file identities before head/tail/full fingerprints and verifies members again before publishing groups. Groups are always REVIEW, including identical backups. Their logical redundancy does not promise physical savings: hard links are reported separately and clone or shared-block facts remain attached to each member. A Detector takes files one batch at a time, every file of a size in one batch, so a completed scan is compared from index.db one size at a time (IndexStore::same_size_files) with no limit on its file count. Readers must prevent link following and hydration; no content or fingerprint is sent to AI or telemetry.

On macOS, lumen_platform_macos::DuplicateReader supplies the fingerprints: it opens with O_NOFOLLOW_ANY and dataless materialization off, attests the handle's identity, size, modification and change times before and after reading, and hashes 4 KiB head and tail samples and then the whole file with BLAKE3 through a 64 KiB buffer. The samples use BLAKE3 rather than ADR-0019's XXH3, which avoids a second hash dependency; only the full hash establishes equality either way. A file with a resource fork never matches its scanned size and is skipped.

On Windows, lumen_platform_windows::DuplicateReader does the same with cloud placeholders exposed for its thread. It first opens the file for its attributes only and refuses reparse points, offline, recall-on-open and recall-on-access files, system files and directories, or an object that is not the scanned one. Only then does it open the file again with FILE_READ_DATA, all share modes and no backup semantics, so a file's access checks always apply. It attests that handle's volume serial, file ID, size, last-write and change times before and after reading. A junction in a parent folder can redirect an open, but the file ID then differs and the file is skipped as changed.

On Linux, lumen_platform_linux::DuplicateReader reads what lumen_scan::StdFsEnumerator listed. It opens with openat2 and RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS, so a link in any component is refused; a kernel without openat2 (before 5.6, or filtered) reads nothing. Files on FUSE filesystems, where cloud-drive clients mount and a read can download, are never read. The descriptor's st_dev, st_ino, size, modification and change times are attested before and after reading, as on macOS.

lumen duplicates <PATH>... [--json] (lumen_app::duplicates::find) runs both on folders the user names, never the whole disk by default. It lists them afresh from their real paths, skips quarantine stores like a scan, and leaves every file in a protected location unread (lumen_policy::protected_location, which fails closed when the location data or home is unknown). It prints paths and sizes for review; digests never leave the process, and nothing is chosen or removed. On Windows the roots lose canonicalize's \\?\ prefix for drive paths, as the scanner adds it itself. Other platforms report that the analysis is unsupported rather than finding nothing.

In the desktop app, the Storage page starts compare_scan after a non-partial scan finishes (ADR-0065). The host keeps that comparison, so the person can check copies to move by its ID and their places, never a path (ADR-0069). It sends only the scan ID; the host checks that it is the latest completed scan and reads its roots from the index. The comparison is a separate operation from scanning, has its own progress and cancellation, and never accepts paths from the webview. macOS, Windows and Linux use the same bounded duplicate reader.

See ADR-0019. Exact duplicates are found in stages ending in a BLAKE3 content ID. Near-duplicates are REVIEW only.

12.4 Storage forecasting

Forecasts use the history of ScanSnapshot volume totals:

  • They require at least 5 snapshots spanning at least 14 days.
  • Growth rate comes from a robust estimator (Theil–Sen) with an interval. Output is rounded ("about 3.8 GB/week", "full in about 3–5 weeks"), never shown to false precision.
  • They report "not enough data" otherwise, and flag discontinuities (large one-off changes) instead of extrapolating them.

13. Cross-cutting concerns

  • Errors: typed thiserror enums per crate with structured fields (operation, path handle, OS code); anyhow only in binaries; no silently ignored results (let _ = requires a justification comment).
  • Concurrency: std threads and bounded std::sync::mpsc channels; no async runtime. One lumen_application::CancelToken per operation (crates/lumen-application/src/cancel.rs), checked by workers between units of work; destructive steps are uninterruptible journaled units.
  • Observability: tracing with a redaction layer; local sinks; OpenTelemetry opt-in and content-free (ADR-0022).
  • Privacy: no file contents leave the device; cloud Jev is metadata-only, and off until the user chooses it on first launch (ADR-0050); content hashes stay local.
  • Persistence: index.db (rebuildable) and ledger.db (durable) (ADR-0012).
  • Security: see the threat model.

14. Failure modes

Failure Behaviour
Directory unreadable (TCC, ACL) Denied node, unknown size, coverage gap; scan continues
Change feed drops events Subtree invalidation; periodic full sweep
Identity mismatch at execution Item aborted to REVIEW, reason recorded
Crash mid-plan Journal reconciliation when the desktop app starts, before held items are listed and before each plan, under a ledger lock; each item is at its source or in quarantine, or left as it is and shown as needing the person
Ledger DB lost or corrupt Rebuild from sidecar manifests in quarantine stores
Quarantine volume unsupported Item becomes REVIEW (no copy-and-delete)
Jev unavailable or invalid Decision proceeds without Jev evidence
Name collision on restore Ask the user; never overwrite
Tool command fails Recorded; no partial claims of freed space; measured free space after

15. Testing strategy

Level What
Unit domain invariants, policy rules, size math, explanation templates
Property path normalisation, policy invariants, size aggregation, graph invariants, serialisation round-trips, quarantine and plan state machines
Integration use cases on temporary fixture filesystems with port fakes; fault injection at every executor step
Platform adapter per-OS fixtures in CI (APFS clones, hard links, placeholders, long paths, junctions)
Security symlink/junction race tests, malicious names, IPC peer rejection, injection canaries
AI evaluation golden datasets, cassette replay, calibration and safety gates (docs/ai)
End-to-end Playwright against a real core on fixture filesystems; "never touch user data" assertions
Benchmarks scan throughput, RSS, syscall counts, incremental rescan time, UI responsiveness

Destructive tests never run against the real user filesystem: they use temporary directories created by the test harness, and the executor refuses roots outside a test-provided sandbox when built with the test-sandbox feature.

16. Deviations from the initial specification

Initial suggestion Decision Why
Next.js web app Vite + React SPA Tauri needs static frontends; no server on user machines (ADR-0009)
Axios Native fetch via the generated client axios supply-chain compromise, March 2026
apps/ios, apps/android apps/mobile (Expo, both platforms) One RN app with native modules (ADR-0007)
platforms/* directories crates/lumen-platform-* + Expo Modules Platform code lives in adapters next to the ports they implement
packages/schemas schemas/ generated from Rust Rust is the single source of truth (ADR-0011)
Generic "cleanup" QUARANTINE plus labelled irreversible tool actions OS trash is not a reliable quarantine (ADR-0015)