# Architecture
This document is for an engineer, human or otherwise, who has never opened this
repository and needs to make a correct change to it without first reading
every file. It explains the layers and why they exist, the shapes the domain
is built from, how a skill sitting in a folder on disk becomes a card in the
window, where state lives and who owns writing it, which files are generated
rather than hand-written, and which invariants a change must not break even
though nothing but a test — or careful reading — would catch the break.
It does not repeat what other documents already own. `README.md` is the pitch
and the install instructions. `CLAUDE.md` holds the exact commands and a list
of mistakes already made once. `CONTRIBUTING.md` owns the git workflow,
versioning and release process. `plan.md` owns what is still undecided or
queued. This document is the only one that tries to explain the system as a
whole, in enough depth that its claims are checkable against the code that
backs them — every non-obvious statement below cites the file, and often the
symbol, it was verified against.
## The three crates, and what actually enforces the boundary between them
The workspace (`Cargo.toml`) has three members: `crates/core` (package
`skills-core`), `crates/cli` (`skills-cli`), and `src-tauri` (`skills-hub`,
the library half of the Tauri app). A fourth "layer", `src/`, is the React
frontend and is not a Rust crate at all — it talks to `src-tauri` only through
generated TypeScript bindings.
```mermaid
graph TD
TAURI["src-tauri (skills-hub) Tauri commands, State, Channel"] -->|depends on| CORE["crates/core (skills-core) pure domain — no tauri, no window, no IPC"]
CLI["crates/cli (skills-cli) terminal dev harness"] -->|depends on| CORE
TAURI -->|"generates via tauri-specta (cargo test -p skills-hub)"| BINDINGS["src/bindings.ts"]
UI["src/ — React + zustand"] -->|imports| BINDINGS
CORE -.->|"banned: deny.toml [[bans.deny]] name = tauri"| TAURICRATE["tauri crate"]
style TAURICRATE fill:#fee,stroke:#c00,stroke-dasharray: 5 5
```
`crates/core/src/lib.rs` states the rule in its module doc: the crate "knows
nothing about Tauri, about a window, or about a user interface. Everything it
touches is either a path it was handed or a value it was given." That is not
a convention held together by review. `deny.toml` bans `tauri` as a dependency
of anything in the workspace graph (`[[bans.deny]] name = "tauri"`), and
`crates/core/Cargo.toml` has no such dependency to begin with — a `cargo deny
check` run (wired into CI, see `CONTRIBUTING.md`) fails the build the moment
that stops being true, rather than merely failing a review.
`crates/cli` is the second half of the proof, not a convenience. It links
`skills-core` and nothing workspace-local beyond it (`crates/cli/Cargo.toml`),
and its own doc comment says why it exists: "It also keeps the layering
honest: this binary links `skills-core` and nothing else." If a change to the
domain accidentally required something only `src-tauri` provides — an
`AppHandle`, a window — `skills-cli` stops compiling. Use it to exercise the
scanner and the rescan pipeline against real folders without building the
whole app: `cargo run -p skills-cli -- scan`, `-- rescan
`, `-- usage
`, `-- mcp`, `-- discover `, `-- toggle on|off --dry-run`
(`crates/cli/src/main.rs`).
`src-tauri/src/lib.rs` is the adapter: "Nothing in here makes a domain
decision. It resolves the paths the platform owns, holds shared state, maps
core errors onto a serialisable shape, and adapts the core's progress callback
onto a Tauri channel." Every `#[tauri::command]` in `src-tauri/src/commands/`
follows that shape — parse input, call into `skills_core::*`, map
`CoreError` to `CommandError` (`src-tauri/src/error.rs`), touch `AppState`
just enough to keep the cached snapshot in step.
One more decision holds this apart from a typical desktop app: `$HOME` is a
parameter threaded through the domain (`paths::resolve_tool_dir`,
`scan::scan_tool`, …) rather than read from the environment inside
`crates/core`. `crates/core/src/paths.rs`'s module doc says this plainly: it
"is what makes the scanner testable against a temporary directory instead of
only against the machine it runs on." Only `src-tauri/src/lib.rs::load_state`
and `crates/cli/src/main.rs::home()` ever call `dirs::home_dir()`.
## The domain model
Everything downstream is built from a small set of shapes in
`crates/core/src/model.rs`.
- **`ItemType`** — `Skill | Agent | Command | Rule`. `ItemType::ALL` fixes the
order the UI presents them in.
- **`ToolConfig`** — one AI coding tool and where it keeps things: `paths`
(global scope), `project_paths` (per-project overrides, falling back to
stripping `~/` off the global path — see `paths::to_project_relative`),
`unconfirmed_paths` (documented but never scanned, offered as a suggestion),
plus fields for plugin bundle discovery and MCP config location. The
registry itself — the sixteen-plus shipped tools — is source code, not data:
`crates/core/src/tools.rs::default_tools()`, built with a small `Tool`
builder. Its own doc comment explains why: "several are deliberate
exceptions that look like mistakes without the reason written beside them. A
JSON file cannot hold those reasons; the compiler also cannot check it."
Tool **names, icons and brand marks are not here** — that presentation
lives in `src/toolMeta.ts` (see "Generated vs hand-written" for the
cross-check that keeps the two in step).
- **`DiscoveredItem`** — what one scan pass found on disk: `entry_id`,
`source_path` (the `SKILL.md` for a folder skill, the file itself
otherwise), `real_path` (symlinks resolved), which `tool`/`project_id`/
`plugin_id` it belongs to, `name`/`description` (read from frontmatter),
`enabled` (derived from which folder it physically sits in), `modified`.
- **`ItemMetadata`** — a `DiscoveredItem` plus everything the user said about
it: `tags`, `favorite`, `collections`, and `InstallSource` (provenance: repo,
ref, subpath, commit — set only for items installed through the app's own
Discover flow). This is the shape that crosses the IPC boundary as "the
item"; `DiscoveredItem` is largely an implementation detail of scanning.
- **`ProjectWorkspace`**, **`PluginSource`**, **`CollectionDef`**,
**`BrokenSymlink`**, **`ScanWarning`** round out the model — a folder scanned
in addition to the home directory, a plugin bundle and its items, a named
grouping the user defined, a dangling symlink, and something the scan could
not do (permission denied, unreadable, malformed) respectively.
### Identity: `entry_id`
`crates/core/src/ids.rs::entry_id` hashes `(tool_id, item_type, project_id,
plugin_id, name, stable_entry_path(source_path))` with BLAKE3, keeping a
readable 32-character slug of the name as a prefix and 16 hex digits of the
hash for uniqueness. Two things make this the identity scheme rather than an
implementation detail:
1. **It must survive being disabled.** Disabling an item moves it into a
`.skillmanager-disabled` sibling folder, which changes its path.
`ids::stable_entry_path` strips every `.skillmanager-disabled` path
component before hashing, so the id — and therefore the metadata note tied
to it — does not change when the item does.
2. **It must not truncate the path.** The Obsidian plugin this application is
derived from slugged the whole identity tuple and cut the result to 80
characters (see the module doc and the regression test
`long_paths_sharing_an_eighty_character_prefix_do_not_collide`), which for
a deeply nested path discarded the path discriminator entirely — two
different items could share one metadata note and silently overwrite each
other's tags. Hashing the full stable path has no such ceiling.
## From a folder on disk to a card in the interface
```mermaid
flowchart TD
A["tools::default_tools() + AppSettings.tool_overrides"] --> B["settings::effective_tools()"]
B --> C["rescan::perform_rescan (crates/core/src/rescan.rs)"]
C --> D["walk(): scan::scan_tool / scan_project per tool × per project, in parallel (rayon) via paths::resolve_tool_dir + scan::Walk — pairs enabled folder with its .skillmanager-disabled sibling at every depth, up to MAX_SCAN_DEPTH = 4"]
D --> E["scan::scan_all_plugins() bundle items merged into the item list"]
E --> F["scan::scan_broken_symlinks()"]
F --> G["record(): store.ensure() per item parallel — one note write each, only when the rendered note actually changed"]
G --> H["prune(): store::prune() orphan / trash, refused unless the scan was full, warning-free and found something"]
H --> I["LibrarySnapshot { items, plugins, broken_symlinks, warnings, version }"]
I --> J["src-tauri commands::library::rescan streams Progress over a Tauri Channel as it runs"]
J --> K["AppState.snapshot — cache, not the source of truth"]
K -->|"tauri-specta IPC, typed by src/bindings.ts"| L["useLibrary (src/stores/library.ts) replaces the whole snapshot object"]
L --> M["lib/library.ts::deriveLibrary(items, scope, filters) one pass: visible list + sidebar counts together"]
M --> N["components/grid/ItemGrid → Card"]
```
Walking through it: `scan::Walk` (`crates/core/src/scan/mod.rs`) recognises
exactly two shapes on disk — a folder containing `SKILL.md` (the folder is the
item) and a flat `.md` file (the file is the item) — and nothing else; a
folder that is neither is a category and is descended into, which is what
makes `skills/engineering/tdd/SKILL.md` work. `Walk::category` calls
`Walk::entries` twice per directory, once for the folder itself and once for
its `.skillmanager-disabled` sibling, and does this **recursively at every
depth**, not only at the configured root — the module doc is explicit that
"the enabled and disabled halves have to be paired at *every* level of the
walk". Frontmatter is read with a deliberately lenient parser
(`crates/core/src/frontmatter.rs`) that only looks at the first 4 KiB of a
file and never fails — it is fed files hand-written by a dozen different
tools and a truncated or malformed block is expected, not exceptional.
`rescan::perform_rescan` (`crates/core/src/rescan.rs`) is the orchestrator:
it walks every tool and every project in parallel (`rayon`, one task per
root), folds in the plugin scan and the broken-symlink scan, records every
found item into the `MetaStore` (also in parallel — each item writes its own
note file), and only then prunes. The order matters, and the doc comment says
so: "Items are recorded before anything is pruned, and pruning is handed the
evidence it needs to decide whether it is entitled to act at all." See
"Invariants" below for what that evidence is.
On the Rust/TypeScript boundary, `src-tauri/src/lib.rs::specta_builder()` is
the single list of every command (`collect_commands!`); `main` mounts it and
a test (`export_typescript_bindings`) exports it to `src/bindings.ts`. Nothing
downstream of that function needs to know Tauri exists — `src-tauri/src/commands/*`
already reduced every operation to typed Rust functions.
On the frontend, `useLibrary` (`src/stores/library.ts`) holds exactly one
`LibrarySnapshot | null` and replaces it wholesale on a scan — `patchItem`
and `removeItem` exist so a single-item command (toggle, tag, delete) can
update one row without a full rescan. `lib/library.ts::deriveLibrary` is the
one place that turns a snapshot plus the current `Scope` (exclusive — see
`src/stores/filters.ts`, "Skills" replaces "Cursor") and `Filters` (compound —
a tag survives navigating to a different tool) into what is rendered, in a
single pass, specifically so the sidebar counts cannot disagree with the grid
they describe.
### Two other flows worth knowing by name
- **Enable/disable** (`crates/core/src/toggle.rs`) moves the item's unit — a
skill's folder or a lone file, resolved by `fsunit::linkable_unit` — into or
out of `.skillmanager-disabled`. It is the one module in the domain crate
that destroys anything, and it is deliberately small: its own doc comment
says why — "kept deliberately small so that all of it can be held in mind at
once."
- **Install / update / restore** (`crates/core/src/install.rs`,
`crates/core/src/diff.rs`, `crates/core/src/git.rs`) shallow-clones a
repository with the `git` binary (not a git library — see `git.rs`'s module
doc for the three reasons), strips `.git` before anything touches disk, and
for an update or restore builds a `Review` (a diff plus a list of companion
file changes) that the caller must apply explicitly. The clone backing a
prepared review is held in `AppState.reviews`
(`src-tauri/src/state.rs::PendingReview`) rather than re-cloned when
applied — re-cloning could apply something other than what the diff showed.
Unapplied reviews are swept after fifteen minutes
(`state::REVIEW_LIFETIME`).
### The command round trip
A full rescan is not how most changes reach the window. Toggling, tagging,
favouriting, deleting — anything that acts on one item — goes through a single
Tauri command and patches the cached snapshot in place, rather than
re-scanning. `set_item_enabled` is representative of the shape every such
command follows (`src-tauri/src/commands/items.rs`,
`src/stores/library.ts::patchItem`):
```mermaid
sequenceDiagram
participant UI as React component
participant Store as useLibrary zustand store
participant B as src bindings.ts, generated
participant Cmd as set_item_enabled command
participant Core as skills_core toggle and MetaStore
participant State as AppState, Mutex-guarded
participant Other as the other webview, window or popover
UI->>B: commands.setItemEnabled(entryId, enabled)
B->>Cmd: IPC call, typed by the generated bindings
Cmd->>State: find entryId in AppState.snapshot
Cmd->>Core: toggle::set_item_enabled(item, enabled)
Core-->>Cmd: new source_path, or a CoreError
Cmd->>Core: store.ensure(item.discovered)
Core-->>Cmd: ItemMetadata
Cmd->>State: replace_in_snapshot(updated)
Cmd->>Other: emit item:changed with the updated ItemMetadata
Cmd-->>B: CommandResult, CoreError mapped to CommandError code and message
B-->>UI: result with status ok or error
UI->>Store: patchItem(updated) on ok, reportError(error) on error
```
Two things this makes explicit that the prose elsewhere does not: every
command result is a discriminated `{ status: "ok", data } | { status: "error",
error }` (checked the same way in every store — `library.ts`, `settings.ts`,
`discover.ts` all branch on `result.status === "error"` before touching
`result.data`), and the error a component sees is always the stable
`CommandError.code` produced from `CoreError::code()`
(`crates/core/src/error.rs`, `src-tauri/src/error.rs`) — never a raw Rust
error string to pattern-match on. The cached `AppState.snapshot` is updated by
the command itself (`replace_in_snapshot`) so a second command reading it
straight after sees the change; the frontend's own `patchItem` is a second,
independent update of the same fact on the other side of the IPC boundary, not
a re-fetch of it.
The `item:changed` emit is there because the caller is not the only webview.
On macOS the menubar popover toggles the same items, and a card left open in
the window would otherwise go on showing the state it had before. Both sides
listen and patch one item (`commands::items::ITEM_CHANGED`,
`src/App.tsx`, `src/components/popover/Popover.tsx`); the caller does not
depend on hearing its own event, because the command already returned the item
to it.
## Where state is held
**On the Rust side**, `src-tauri/src/state.rs::AppState` is the only place
that holds anything between commands, and every field is behind its own
`Mutex` "so that reading settings does not wait on a scan":
- `settings: Mutex` — the user's configuration, persisted by
`settings::SettingsFile` as one JSON file with a pre-write backup
(`settings.backup.json`) and quarantine-on-corruption (an unreadable
settings file is renamed aside, e.g. `settings.corrupt-.json`,
and the app starts on defaults rather than refusing to open —
`settings.rs::SettingsFile::load`/`quarantine`).
- `store: Mutex