# CLI Reference

On first run, the tool prompts for configuration (database path and kernel storage directory). These are saved to `~/.config/spice-kernel-db/config.toml`. All commands share a `--db` option to override the configured database path.

`spice-kernel-db` and `skd` are the same program. The examples use `skd`.

The root options come before the command: `skd [--db PATH] [-v] COMMAND ...`. `-v` is a root option only; no command has its own `-v`. `skd --help` (or `-h`) lists the commands in four groups: acquire, inspect, maintain and configure. `skd --install-completion` installs shell completion for the current shell; `--show-completion` prints it instead.


# Naming a metakernel

Every command that takes a metakernel (`show`, [check](../reference/check.md#spice_kernel_db.check), `coverage`, `rewrite`, `rm`, `which --metakernel`) resolves the argument the same way. [get](../reference/get.md#spice_kernel_db.get) resolves a name that is not a URL against the tracked metakernels first. Any of these forms names the same tracked file:

| Form | Example |
|:---|:---|
| path to the file | `~/kernels/JUICE/mk/juice_crema_5_2_v473_20260819_001.tm` |
| registry filename | `juice_crema_5_2_v473_20260819_001.tm` |
| versionless base name, with or without `.tm` | `juice_crema_5_2.tm`, `juice_crema_5_2` |
| the URL it was fetched from | `https://.../mk/juice_crema_5_2_v473_20260819_001.tm` |

Matching is case-insensitive; `--mission` narrows it to one mission. A base name matches every tracked snapshot of that metakernel, so it is unambiguous only while one is tracked. Asking for a specific version that is not tracked never lands on another version.

| Situation | Behaviour | Exit |
|:---|:---|:---|
| the name matches nothing | prints `... is not tracked locally; fetch it with spice-kernel-db get <name>` | 1 |
| the name matches several tracked metakernels | lists them and asks for one | 2 |
| no argument, at a terminal | a numbered picker over the tracked metakernels |  |
| no argument, in a script or notebook (stdin not a terminal) | prints the candidates on stderr and stops | 2 |

The same terminal rule applies to every other picker ([get](../reference/get.md#spice_kernel_db.get) with no argument, `which` with no argument, an ambiguous body name in `coverage`): a script never blocks on a prompt. Python callers get the same resolution from [KernelDB.resolve_metakernel()](../reference/KernelDB.resolve_metakernel.md#spice_kernel_db.KernelDB.resolve_metakernel).


# Several kernel roots

The configuration holds an ordered list of kernel roots: `kernel_dirs` in the `[storage]` section of `config.toml`. A root is a directory of kernels laid out as `<root>/<mission>/<type>/<file>`. The default store is one root. A second root is typically another tool's store, such as planetarypy's, or a directory of kernels you already had.

| Command | What the roots change |
|:---|:---|
| [get](../reference/get.md#spice_kernel_db.get) | Downloads into the root that already holds the metakernel (a re-fetch) or its mission; with one root, that root. When several roots could take a new mission, it lists them and asks at a terminal, and exits 2 in a script; `--download-dir` names the root explicitly. |
| [scan](../reference/scan.md#spice_kernel_db.scan) | With no directory, scans every root in turn and skips a root that does not exist, saying so. With a directory, scans just that one. `--archive` moves files into the root that holds their mission, asking the same way when none does. |
| `which`, [check](../reference/check.md#spice_kernel_db.check) | Resolve against every file the database knows, so a kernel that lives in any scanned root is found. |
| `dedup` | Plans over every location in the database, so a kernel in one root and its identical twin in another are linked. |

`dedup` keeps a copy in the `generic` mission when there is one and otherwise the first path in sort order. The order of the roots plays no part, so run `skd dedup` without `--execute` first and read the plan.

A root is only searched once it has been scanned. After `skd config add-root <dir>`, run `skd scan` to index it.

The mission of a file found under a root is the first directory below the root. A file directly in a root, or in a type directory such as `mk` or `spk`, gets its mission from the filename alone. Outside every root the mission is guessed from the path as before. A tracked metakernel keeps the mission in its registry row: [check](../reference/check.md#spice_kernel_db.check), `rewrite` and `coverage` read it from there and never guess it from the path again.

Edit the list with `skd config add-root <dir>` and `skd config remove-root <dir>` (see [`config`](#config)). From Python, use [kernel_roots()](../reference/kernel_roots.md#spice_kernel_db.kernel_roots), [add_root()](../reference/add_root.md#spice_kernel_db.add_root) and [remove_root()](../reference/remove_root.md#spice_kernel_db.remove_root) ([API](index.md#public-api)).


# Verbs at a glance

The last column says what changed with the rename in issue \#47. The old names are listed in [Renamed commands](#renamed-commands).

| Verb | Group | What it does | Since the rename |
|:---|:---|:---|:---|
| `browse [mission]` | acquire | Lists the metakernels on a mission's server. | unchanged |
| `get <mk>` | acquire | Downloads a metakernel and the kernels it needs that are missing. | also re-fetches a tracked metakernel from its source |
| `update` | acquire | Re-fetches every tracked metakernel from its source and reports what is missing; `--execute` downloads. | now walks all tracked metakernels, dry run by default |
| `ls [mission]` | inspect | Lists the tracked metakernels. | renamed |
| `show <mk>` | inspect | Registry details of a metakernel and the kernels it lists. | renamed, two commands merged |
| `which <kernel>` | inspect | Local path of a kernel, and every filename its content is known under. | renamed, two commands merged |
| `coverage <body>` | inspect | SPK coverage of a body in a metakernel. | unchanged |
| [stats](../reference/KernelDB.stats.md#spice_kernel_db.KernelDB.stats) | inspect | Database statistics, then the duplicate kernels. | now includes the duplicate report |
| `check <mk>` | inspect | Three verdicts: present, resolves, matches remote. | unchanged since \#46 |
| [doctor](../reference/KernelDB.doctor.md#spice_kernel_db.KernelDB.doctor) | inspect | Database health: poisoned rows, files gone from disk. | unchanged since \#46 |
| `scan [dir]` | maintain | Indexes every kernel file under a directory, or under every kernel root when none is given. | never prompts; directory optional since \#48 |
| `import <mk-file>` | maintain | Tracks a metakernel that is already on disk; `--unofficial` marks one assembled locally. | new |
| `rewrite <mk>` | maintain | Writes a metakernel with a local symlink tree. | unchanged |
| `rm <mk>` | maintain | Stops tracking a metakernel; the file stays. | renamed from an option |
| `clean` | maintain | Drops rows and symlinks that point at nothing. | renamed, options regrouped |
| `dedup` | maintain | Replaces duplicate kernel files with symlinks. | unchanged |
| `reset` | maintain | Deletes the database. | moved to the maintain group |
| `mission add/list/remove` | configure | Manages configured missions. | unchanged |
| `config` | configure | Shows or updates the configuration, including the kernel roots. | `add-root` and `remove-root` added (#48) |


# `browse`

Browse remote metakernels in a NAIF mission `mk/` directory, or list known directories.

``` bash
skd browse [url] [--mission NAME]
```

| Option | Description |
|----|----|
| `url` | URL to a mission's `mk/` directory, or a mission name (omit to list known directories) |
| `--mission` | Override auto-detected mission name |
| `--show-versioned` | Show versioned snapshots under each metakernel |
| `--sort {name,date}` | Row ordering. `name` (default) is alphabetical. `date` sorts by the **Latest** remote modification date ascending, so the most recently updated metakernels appear at the bottom -- handy for spotting fresh updates at a glance. |
| `--archived` | Browse the mission's `former_versions/` subdirectory instead of the live `mk/` listing. Each archived metakernel is rendered on its own row (no base-name aggregation) because archived snapshots are distinct historical files, not byte-identical copies of a current file. |
| `--filter SUBSTRING` | Case-insensitive substring filter on metakernel filenames. Particularly useful when combined with `--archived` to narrow listings of a thousand-plus entries. |

``` bash
# List all known mk/ directories (from missions table and previously acquired metakernels)
skd browse

# Browse by mission name (prefix matching, case-insensitive)
skd browse JUICE
skd browse bepi    # matches BEPICOLOMBO

# Browse by full URL
skd browse https://naif.jpl.nasa.gov/pub/naif/JUICE/kernels/mk/

# Sort by latest remote modification date (newest at the bottom)
skd browse JUICE --sort date

# Browse only the archived versions in former_versions/
skd browse JUICE --archived
skd browse JUICE --archived --sort date  # combine with sort

# Narrow a large listing with a substring filter (combinable with --archived)
skd browse JUICE --archived --filter crema_5_1
```

**Without a URL**, lists configured missions from the `missions` table:

    Configured missions

      Mission  mk/ URL
      ───────  ──────────────────────────────────────────────────────────
      JUICE    https://spiftp.esac.esa.int/data/SPICE/JUICE/kernels/mk/
      MRO      https://naif.jpl.nasa.gov/pub/naif/MRO/kernels/mk/

    Use 'spice-kernel-db browse <mission>' to scan a specific directory.
    Use 'spice-kernel-db mission add' to add another mission.

**With a URL**, fetches the Apache directory listing, parses `.tm` file entries, groups them by base name (stripping version tags like `_v461_20251127_001`), and displays a compact summary:

    Remote metakernels: JUICE (https://naif.jpl.nasa.gov/.../mk/)

      Metakernel                         Versions  Latest           Local
      ─────────────────────────────────  ────────  ──────────────── ────────
      juice_crema_5_0.tm                        1  2025-08-15 11:00 no
      juice_ops.tm                              3  2025-11-27 09:30 yes
      juice_plan.tm                             2  2026-02-02 14:00 outdated

      Total: 3 unique | 6 files | 1 locally acquired
      Run 'spice-kernel-db get <name>' to update outdated metakernels.
      Use --show-versioned to see individual snapshots.

The **Local** column shows three states:

- **yes** -- locally acquired and up to date (or scan-acquired, where remote date is unknown)
- **outdated** -- locally acquired but the remote copy has been modified since acquisition
- **no** -- not acquired locally

With `--show-versioned`, versioned snapshots are listed under each base metakernel:

      juice_ops.tm                                 2025-11-27 09:30    12K  yes
        snapshot: juice_ops_v230_20221128_001.tm   2022-11-28 10:00     8K
        snapshot: juice_ops_v461_20251127_001.tm   2025-11-27 09:30    12K


# [get](../reference/get.md#spice_kernel_db.get)

Fetch a metakernel, show which kernels are needed, and download the missing ones.

``` bash
skd get [url-or-name] [--download-dir DIR] [--mission NAME] [-y] [--force]
```

| Option | Description |
|----|----|
| `url-or-name` | A URL, a tracked metakernel, or a `.tm` filename on the configured mission's server. See the table below. **Omit to pick from the server listing** at a terminal. |
| `--download-dir` | The kernel root to download into (default: derived, see [Several kernel roots](#several-kernel-roots)) |
| `--mission` | Override auto-detected mission name (use it to disambiguate when several missions are known and you pass a filename) |
| `-y, --yes` | Skip confirmation prompt |
| `--force` | Re-download all kernels even if already on disk (skips DB lookups and remote size queries) |

What the argument means:

| Argument | What [get](../reference/get.md#spice_kernel_db.get) does |
|:---|:---|
| a URL | Fetches that file. |
| a tracked metakernel (any form in [Naming a metakernel](#naming-a-metakernel)) | Re-fetches it from its stored source URL, downloads the kernels that are missing, and re-indexes the directories the metakernel points at. |
| a `.tm` filename that is not tracked | Looks it up in the `mk/` directory of the configured mission, then under `former_versions/`. |
| nothing | At a terminal, a picker over the mission's server listing. |

``` bash
# By filename (after browsing a mission at least once)
skd get juice_ops.tm

# By filename with explicit mission (when multiple missions are known)
skd get juice_ops.tm --mission JUICE

# By full URL
skd get https://naif.jpl.nasa.gov/pub/naif/JUICE/kernels/mk/juice_ops.tm

# Auto-confirm download
skd get juice_ops.tm -y

# A tracked metakernel: fetch the newest version of what it points at
skd get juice_crema_5_2
```

When a filename is given instead of a URL, the tool looks up the mk/ directory URL from the `missions` table (configured via `mission add`). Mission names support case-insensitive prefix matching (e.g. `--mission bepi` matches `BEPICOLOMBO`).

The tool fetches the remote metakernel, resolves each kernel entry to a full URL, checks your local database, queries remote file sizes (in parallel), and displays a summary table. Kernels whose content is known under other filenames are marked `(+N aliases)`; `which <name>` shows the full trail. Downloaded kernels are stored preserving the remote subdirectory structure (e.g. `lsk/`, `spk/`, `ck/`) and automatically registered in the database.

**Metakernels without a source URL.** A metakernel added by [scan](../reference/scan.md#spice_kernel_db.scan) or `import` has no stored source URL. `get <name>` then tries the mission's `mk/` URL plus the filename. If the mission has no `mk/` URL, it fails with `This metakernel was added via scan, not downloaded.` and asks for a URL.

**A source that has gone.** When the stored source answers 403, 404 or 410, `get <name>` prints a red *Metakernel unreachable* panel with the URL, the HTTP status and the filename, and exits 2. The panel names the two ways out: `skd clean --registry` for every such row, or `skd rm <name>` for this one.

**Archived metakernels.** ESA (and some NAIF directories) rotate older versioned metakernels into a `former_versions/` subdirectory once a newer version supersedes them. When a filename you request is not present in the live `mk/` listing, [get](../reference/get.md#spice_kernel_db.get) automatically retries under `former_versions/<filename>` before failing. The kernels referenced by the older metakernel are typically still available at their original locations (ESA in particular is purely additive -- old kernel files are kept alongside new ones), so the rest of the download proceeds unchanged:

``` bash
# A 2022-era versioned metakernel -- auto-fetched from former_versions/
skd get juice_crema_2_0_ops_v200.tm --mission JUICE
```

If both the live and `former_versions/` URLs 404, the error names both attempted URLs so you can diagnose archive layouts that don't follow this convention. If the server does not answer at all, [get](../reference/get.md#spice_kernel_db.get) says so and exits 1 instead of reporting the file as missing.


# `update`

Re-fetch every tracked metakernel from its source and report what is missing. Nothing is written unless you pass `--execute`.

``` bash
skd update [--execute]
```

| Option | Description |
|----|----|
| `--execute` | Download the missing kernels. Default: report only. `--execute` is the confirmation; there is no per-metakernel prompt. |

Each metakernel re-fetches into the root that holds it (see [Several kernel roots](#several-kernel-roots)), so there is no `--download-dir`; one directory for metakernels from several roots would undo that. `get <name>` takes it for a single metakernel.

`--mission`, `-y` and `--force` are hidden from `--help` and have no effect on the walk. They exist for the deprecated one-argument form described under [Renamed commands](#renamed-commands).

``` bash
# What is missing across everything I track? Nothing is written.
skd update

# Download all of it
skd update --execute
```

For each tracked metakernel, `update` fetches it from its source URL and prints the same status table as [get](../reference/get.md#spice_kernel_db.get). A dry run stops there. With `--execute` the missing kernels are downloaded and the directories the metakernel points at are re-indexed. A summary table closes the run, one row per metakernel, with the count of missing kernels (dry run) or downloaded kernels (`--execute`). A dry run ends with the line `Dry run: pass --execute to download.`

- Alias rows, where a symlink stands next to its target, are skipped. The target is walked under its own name.
- A row with no stored source URL is fetched from the mission's `mk/` URL plus the filename. If the mission has no `mk/` URL, the row gets a note in the summary table.
- A source that answers 403, 404 or 410 gets a note in the summary table (`source gone (HTTP 404); spice-kernel-db clean --registry`) and the walk goes on. The exit code stays 0.
- A source that cannot be reached at all is noted the same way and does not stop the walk.

Use `get <name>` to update one metakernel.


# `ls`

List tracked metakernels.

``` bash
skd ls [mission]
```

| Option | Description |
|----|----|
| `mission` | Only this mission. Case-insensitive prefix, so `ju` matches `JUICE`. |

``` bash
# All tracked metakernels
skd ls

# One mission
skd ls JUICE
```

                       Tracked metakernels
    ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┓
    ┃ Mission ┃ Metakernel            ┃ Kernels ┃ Source                ┃
    ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━┩
    │ JUICE   │ juice_ops.tm          │      42 │ spiftp.esac.esa.int   │
    │ MRO     │ mro_v16.tm            │      31 │ naif.jpl.nasa.gov     │
    └─────────┴───────────────────────┴─────────┴───────────────────────┘

The **Source** column shows the host the metakernel was fetched from; it is empty for a metakernel added by [scan](../reference/scan.md#spice_kernel_db.scan) or `import`. When two tracked metakernels list the same kernels, the second carries a line `↳ identical to <first>`. With nothing tracked, `ls` prints `No tracked metakernels.` A metakernel imported with `--unofficial` carries the word `unofficial` after its name.


# `show`

Registry details of one metakernel and the kernels it lists.

``` bash
skd show [metakernel] [--mission NAME] [--type TYPE]
```

| Option | Description |
|----|----|
| `metakernel` | Any form in [Naming a metakernel](#naming-a-metakernel). **Omit to pick from the tracked metakernels** at a terminal. |
| `--mission` | Preferred mission for kernel resolution |
| `--type` | Only kernels of this type (`ck`, `spk`, `fk`, `ik`, `pck`, `lsk`, `sclk`, `dsk`). The totals stay whole. |

``` bash
# Details and kernel table
skd show juice_ops.tm

# Only the SPK kernels
skd show juice_ops.tm --type spk
```

    Metakernel: juice_ops.tm
      Mission:      JUICE
      Source:       https://spiftp.esac.esa.int/data/SPICE/JUICE/kernels/mk/juice_ops.tm
      Acquired:     2026-11-12 14:23:11.502892
      Local path:   ~/.local/share/spice-kernel-db/kernels/JUICE/mk/juice_ops.tm
    ┏━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
    ┃ Kernel       ┃ Type ┃    Size ┃ Status  ┃
    ┡━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
    │ naif0012.tls │ lsk  │  5.2 KB │ in db   │
    │ de432s.bsp   │ spk  │ 31.2 MB │ in db   │
    │ missing.bsp  │ spk  │       -- │ missing │
    └──────────────┴──────┴─────────┴─────────┘

      Total: 3 | In DB: 2 | Missing: 1

The **Source** line is absent for a metakernel added by [scan](../reference/scan.md#spice_kernel_db.scan) or `import`. A metakernel imported with `--unofficial` has the line `Official: no (assembled locally, not an archive metakernel)` below **Acquired**. **Status** is `in db` when the kernel resolves to a file in the database and `missing` otherwise.

`show` also takes a `.tm` file that is not tracked. It lists the kernels the file loads, with the type counts and the `(+N aliases)` marks, and ends with `Not tracked; spice-kernel-db import <path> tracks it.` A name that matches nothing, and is not a file, exits 1.


# `which`

Find the local path of a kernel, and every filename its content is known under.

``` bash
skd which [kernel] [--mission NAME] [--metakernel MK]
```

| Option | Description |
|----|----|
| `kernel` | A kernel filename (canonical or alias) or a SHA-256 prefix of six or more characters. **Omit to pick from the deduplicated kernels** at a terminal. |
| `--mission` | Preferred mission for resolution |
| `--metakernel` | Resolve every kernel of this metakernel instead (any form in [Naming a metakernel](#naming-a-metakernel)). One `kernel<TAB>path` line each; a kernel that does not resolve prints `kernel<TAB>NOT FOUND` on stderr and the exit code is 1. |

``` bash
skd which naif0012.tls --mission JUICE
# /data/spice/JUICE/kernels/lsk/naif0012.tls

skd which mro_sc_2024.bc --mission JUICE
# /data/spice/MRO/kernels/ck/mro_sc_2024.bc
#   ⚠ mro_sc_2024.bc: not found in [JUICE] registry, using copy from [MRO]

# By content hash prefix
skd which 3f9a1c

# Every kernel of a metakernel, for a script
skd which --metakernel juice_ops > paths.tsv
```

The first line on stdout is the local path; warnings go to stderr. A kernel that is not in the database prints `Not found: <kernel>` on stderr with a hint to run [scan](../reference/scan.md#spice_kernel_db.scan), and exits 1.

When the content is known under more than one filename, the path is followed by three tables: the content hash with the canonical name, type and size; the filenames the content is known under, with the canonical one marked; and every on-disk location, each marked as a real file, a symlink or missing. With no argument, `which` lists the deduplicated kernels, most aliases first, and lets you pick one.

> **Tip: Discover upstream aliases without deduplicating**
>
> Because identity is content-based, `which` surfaces names an *archive* (e.g. ESA) publishes the same bytes under -- revealing, for example, that a `_v13` kernel is byte-identical to `_v12`, or that two trajectory scenarios reuse the same solar-array/antenna kernels. This is a pure discovery feature: it needs **no `dedup` step** (symlinking duplicates is a separate, optional space-saving operation). See [Discovering archive-side aliases](design.md#content-identity).


# `coverage`

Check SPK body coverage in a metakernel. See the [Coverage](coverage.md) page for full details.

``` bash
skd coverage <body> [metakernel] [--mission NAME]
```

| Option | Description |
|----|----|
| `body` | NAIF body ID (e.g. `399`) or body name (e.g. `Earth`) |
| `metakernel` | Any form in [Naming a metakernel](#naming-a-metakernel). Omit to pick from the tracked metakernels at a terminal. |
| `--mission` | Mission name for preferred-mission resolution |

``` bash
# Interactive -- pick metakernel, resolve body name
skd coverage Earth

# Explicit
skd coverage 399 juice_ops.tm --mission JUICE
```

Requires the optional `spiceypy` dependency: `pip install spice-kernel-db[spice]`


# [stats](../reference/KernelDB.stats.md#spice_kernel_db.KernelDB.stats)

Print database statistics, then the duplicate kernels.

``` bash
skd stats
```

The statistics are the unique kernels, total locations, total size, number of duplicates, poisoned rows, registered missions, and a breakdown by kernel type.

A **poisoned row** is a kernel that is present on disk but flagged as superseded by content that exists nowhere. Such a kernel is re-downloaded on every `update --execute`. The count is highlighted when non-zero; `scan <directory>` on the directory holding the file repairs it.

The duplicate section lists each kernel that exists in two or more locations, largest first and at most 30, showing the paths and missions of every copy, with a total wasted space calculation. It reads `No duplicates found.` when there are none. `dedup` replaces the copies with symlinks.


# [check](../reference/check.md#spice_kernel_db.check)

Check a metakernel. Three questions, each answered on its own line with its own exit bit:

| Verdict | Question | Exit bit | Runs |
|:---|:---|:---|:---|
| present | does every kernel the metakernel lists exist on disk? | 1 | always |
| resolves | does every entry resolve through `PATH_VALUES`/`PATH_SYMBOLS` to the file the database knows (size, with `--hash` also SHA-256), with no traversal, dangling link or ambiguous name? | 2 | always |
| matches remote | does every kernel's size (with `--hash` also its SHA-256) match the server? | 4 | `--remote` |

The exit code is the sum, so a script can read it: `0` all green, `1` a kernel missing, `2` the metakernel does not resolve, `4` a kernel differs from the server, `5` missing plus differs, and so on. The output never collapses into one tick; a verdict that did not run says `not checked`. (Exit 2 is also the code for an ambiguous name or a usage error; those print their reason before any verdict runs. A config file that does not parse exits 78 from every command, so it is never read as a verdict.)

``` bash
skd check [metakernel] [--remote] [--hash] [--spice] [--json] [--mission NAME]
```

| Option | Description |
|----|----|
| `metakernel` | Any form in [Naming a metakernel](#naming-a-metakernel). **Omit to pick from the tracked metakernels** at a terminal. |
| `--remote` | Also compare each kernel's size with the server, one HEAD per kernel. The only network check. |
| `--hash` | Compare SHA-256 against the database, and with `--remote` against the server (downloads each kernel, slow). |
| `--spice` | With `--remote`, `furnsh` each local kernel and report what SPICE cannot read (requires spiceypy). |
| `--json` | The three verdicts and their evidence as JSON, nothing else on stdout. |
| `--mission` | Preferred mission for kernel resolution |

With the root option `-v`, per-file warnings are printed in full instead of the compact summary.

``` bash
# At a terminal: pick from the tracked metakernels
skd check

# Local verdicts only
skd check juice_crema_5_2

# Before an analysis run: everything, including the server
skd check juice_crema_5_2 --remote --hash

# In a script
skd check juice_crema_5_2 --json || echo "exit $?"
```

Per-entry statuses behind the *resolves* verdict (shown as a table only when something is wrong):

| Status | Verdict | Meaning |
|----|----|----|
| `OK` | -- | Verified |
| `NOT_FOUND`, `DANGLING` | present, or resolves when every kernel exists elsewhere | No file at the resolved path; `rewrite` points the metakernel at the local copies |
| `NOT_FILE` | resolves | Path exists but isn't a regular file |
| `TRAVERSAL` | resolves | Entry resolves outside every `PATH_VALUE` root |
| `SIZE_MISMATCH` | resolves | File size disagrees with the database record |
| `HASH_MISMATCH` | resolves | (`--hash`) SHA-256 disagrees with the database record |
| `AMBIGUOUS` | resolves | The resolved path is not registered and several non-superseded `kernels` rows carry its filename |
| `BAD_PATH_VALUE` | resolves | `PATH_VALUES` entry not absolute or directory missing |
| `UNREGISTERED` | none | File exists but no `kernels` row; [scan](../reference/scan.md#spice_kernel_db.scan) registers it |

The resolved path pins the file. When an entry resolves to a path the database has registered as a location (or to a symlink whose target is one), that location's size and hash are the expectation, whatever other missions or kernel roots call a file by the same name. Two stores can each hold a different `naif0012.tls` without either entry being flagged. Only an unregistered path falls back to the filename, where several active rows give `AMBIGUOUS`.

[check](../reference/check.md#spice_kernel_db.check) takes the mission of a tracked metakernel from its registry row, not from its path.

If the metakernel was fetched from a remote server, [check](../reference/check.md#spice_kernel_db.check) also says when a newer version is listed there (one directory listing, nothing downloaded).


# [doctor](../reference/KernelDB.doctor.md#spice_kernel_db.KernelDB.doctor)

Database health, nothing per metakernel.

``` bash
skd doctor [--json]
```

Reports the table counts, poisoned supersession rows (a kernel present on disk but flagged as superseded by content that exists nowhere, so every `update --execute` re-downloads it; `scan <directory>` on the directory holding the file repairs it), kernel locations whose file is gone (`clean --execute` removes them), paths registered under more than one hash and tracked metakernels whose file is gone (`rm <name>`). Exits 1 only on poisoned rows; a missing file or a path with several hashes is listed and does not change the exit code.

A path registered under more than one hash is one file with several `locations` rows, for example a 0-byte row left by an interrupted download beside the row for the real content. [check](../reference/check.md#spice_kernel_db.check) reports such a path as `SIZE_MISMATCH` against the wrong row. `scan <directory>` on the directory holding the file keeps the row that matches the file on disk and marks the other rows superseded.


# [scan](../reference/scan.md#spice_kernel_db.scan)

Recursively scan a directory and register all kernel files. With no directory, scan every configured kernel root in turn (see [Several kernel roots](#several-kernel-roots)).

``` bash
skd [-v] scan [directory] [--mission NAME] [--archive]
```

| Option | Description |
|----|----|
| `directory` | Directory to scan recursively. Default: each kernel root in the configuration. |
| `--mission` | Override auto-detected mission name |
| `--archive` | Move files into the kernel root that holds their mission (or the only root) and leave symlinks at the original locations |

With the root option `-v`, [scan](../reference/scan.md#spice_kernel_db.scan) prints each registered file. After the scan it prints the database statistics.

``` bash
# Every configured kernel root
skd scan

# Auto-detect mission from path structure
skd scan /data/spice/JUICE/kernels

# Explicit mission label
skd scan /data/spice/generic_kernels --mission generic

# Verbose output
skd -v scan /data/spice/MRO/kernels

# Import kernels from a random directory into the central archive
skd scan /tmp/downloaded_kernels --mission JUICE --archive
```

With `--archive`, each kernel file is moved into a kernel root (organized as `{root}/{mission}/{type}/{filename}`) and a symlink is left at the original location. A file already inside a configured root stays in that root; any other file goes to the root that already holds its mission, or to the only root. When a mission is held by no root, or by several, the command lists the roots and asks at a terminal, once per such mission, and exits 2 in a script; nothing moves until every file has its root (`--mission NAME` makes every scanned file that mission). This lets you import kernels from anywhere while keeping the original paths functional.

A `.tm` file that [scan](../reference/scan.md#spice_kernel_db.scan) meets is tracked as well. When it is already tracked, [scan](../reference/scan.md#spice_kernel_db.scan) keeps the mission and the `official` flag of its registry row, because a scan only guesses them. [get](../reference/get.md#spice_kernel_db.get) and `import` state them and replace the row.

[scan](../reference/scan.md#spice_kernel_db.scan) never prompts, so it is safe in a script. When it meets a mission that is not configured yet, it does one of two things:

- If the mission's directory holds a `.spice-server` marker (written by [get](../reference/get.md#spice_kernel_db.get)), the mission is configured on the spot and [scan](../reference/scan.md#spice_kernel_db.scan) says so.
- Otherwise it prints the command to run, for example `spice-kernel-db mission add JUICE --server-url <https://naif.jpl.nasa.gov/pub/naif/|https://spiftp.esac.esa.int/data/SPICE/>`, and carries on.

The missions `generic` and `unknown` are never configured.

> **Note: Note**
>
> Symlinks require filesystem support. On Windows, Developer Mode or administrator privileges are needed. If symlink creation fails, the file is still moved and registered -- only the symlink is skipped (with a warning).


# `import`

Track a metakernel that is already on disk, without downloading anything.

``` bash
skd import <metakernel-file> [--mission NAME] [--unofficial]
```

| Option | Description |
|----|----|
| `metakernel-file` | Path to the `.tm` file |
| `--mission` | Override auto-detected mission name (default: the directory below the kernel root when the file is under one, otherwise guessed from the path) |
| `--unofficial` | Mark the metakernel as assembled locally, not an archive metakernel. `ls` appends `unofficial` to its name and `show` prints `Official: no`. |

``` bash
skd import ~/spice/JUICE/mk/juice_ops.tm
# Tracked juice_ops.tm (JUICE): 40/42 kernels on disk and registered.
#   Not on disk (2):
#     $KERNELS/spk/missing_1.bsp
#     $KERNELS/spk/missing_2.bsp
#   spice-kernel-db get juice_ops.tm downloads them once the mission's server is configured.
```

`import` resolves each entry of the file through its own `PATH_VALUES` and `PATH_SYMBOLS`, registers the kernels that exist on disk, indexes the entries, and adds the registry row with no source URL. It makes no network request. After it, the metakernel works with `show`, [check](../reference/check.md#spice_kernel_db.check), `which --metakernel`, `rewrite` and `coverage`. Use [scan](../reference/scan.md#spice_kernel_db.scan) instead to register a whole directory of kernels.

The registry keeps an `official` flag for each metakernel. It is true unless `--unofficial` is given. Use `--unofficial` for a metakernel built on this machine, such as a subsetter's output or the one planetarypy assembles in `archived_kernels.py`, so that it is not mistaken for one published by an archive.


# `rewrite`

Rewrite a metakernel with a local symlink tree.

``` bash
skd rewrite [metakernel] [-o OUTPUT] [--link-root DIR] [--mission NAME]
```

| Option | Description |
|----|----|
| `metakernel` | The original metakernel: path, registry filename or base name. **Omit to pick from the tracked metakernels** at a terminal. |
| `-o, --output` | Output `.tm` path (default: `<stem>_local.tm` next to the original) |
| `--link-root` | Root for symlink tree (default: `kernels/` next to output) |
| `--mission` | Mission name for preferred-mission resolution |

``` bash
# Basic usage
skd rewrite juice_crema_5_1.tm -o juice_local.tm

# Custom symlink root
skd rewrite juice_crema_5_1.tm -o juice_local.tm \
    --link-root /data/spice/unified

# Explicit mission
skd rewrite juice_crema_5_1.tm -o juice_local.tm --mission JUICE
```


# `rm`

Stop tracking a metakernel. The `.tm` file stays on disk.

``` bash
skd rm [metakernel] [--mission NAME]
```

| Option | Description |
|----|----|
| `metakernel` | Registry filename, base name or path. **Omit to pick from the tracked metakernels** at a terminal. |
| `--mission` | Mission the name belongs to |

``` bash
skd rm juice_crema_5_1_v462_20260223_001.tm
```

`rm` deletes the registry row and the indexed entries of that metakernel. The name is matched against the registry, not against the file system, so a row whose file is gone can be removed. A name that matches nothing exits 1. Kernels stay registered; `clean` removes rows for kernels whose file is gone.


# `clean`

Drop database rows and symlinks that point at nothing. Dry run unless `--execute` is given.

``` bash
skd clean [--execute] [--locations] [--symlinks] [--registry] [--delete-files]
```

| Option | Description |
|----|----|
| `--execute` | Actually remove entries. Default: report only. |
| `--locations` | Kernel locations whose file no longer exists on disk, then kernel rows left with no location. |
| `--symlinks` | Dangling symlinks under each mission's download tree. The tree is derived from the tracked metakernels (the parent of each `mk/` directory) and walked recursively. These accumulate when an underlying kernel store moves, or after `--locations` removes a location row. |
| `--registry` | Tracked metakernels whose source URL answers 403, 404 or 410. Sends one HEAD request per row to its source URL, or to the mission's `mk/` URL plus the filename when no source URL is stored; a row with neither is noted and skipped (`rm` drops it). **The only class that contacts the server.** |
| `--delete-files` | With `--registry --execute`: also unlink the `.tm` files on disk. |

Without a class flag, `--locations` and `--symlinks` run, the two classes that need no network. With one or more class flags, only the named classes run, so the classes can be combined.

Network errors (timeouts, DNS failures) under `--registry` are **never** treated as dead. A removal would otherwise discard real state because you happened to be offline.

``` bash
# Preview stale kernel locations and dangling symlinks
skd clean

# Remove them
skd clean --execute

# Preview which tracked metakernels have lost their source
skd clean --registry

# Remove those rows and their .tm files
skd clean --registry --execute --delete-files
```


# `dedup`

Replace duplicate kernel files with symlinks.

``` bash
skd dedup [--execute] [-y]
```

| Option | Description |
|----|----|
| `--execute` | Actually replace files (default: dry run) |
| `-y, --yes` | With `--execute`: skip the confirmation prompt. Without `-y`, the dry run is shown first and you are asked to proceed. |

``` bash
# Preview (default, safe)
skd dedup

# Do it
skd dedup --execute
```

The canonical copy (the file that symlinks point to) is chosen with a preference for files in the `generic` mission.


# `reset`

Delete the database and start fresh.

``` bash
skd reset [-y]
```

| Option      | Description              |
|-------------|--------------------------|
| `-y, --yes` | Skip confirmation prompt |

``` bash
# Interactive (asks for confirmation)
skd reset

# Skip confirmation
skd reset -y
```

Deletes only the DuckDB database file. Kernel files in the configured kernel directory are **not** touched. After resetting, you can re-index existing kernels:

``` bash
skd scan ~/.local/share/spice-kernel-db/kernels
```


# `mission`

Configure missions for filename-based acquisition and browsing. Mission names are matched case-insensitively and support prefix matching -- e.g. `bepi` matches `BEPICOLOMBO`, `ju` matches `JUICE` (as long as the prefix is unambiguous).


## `mission add`

Set up a new mission. Runs interactively with no arguments; non-interactive when a name (or `--mk-dir-url`) is given.

Interactive flow:

1.  Choose a server: `[1] NASA [2] ESA`
2.  View available missions from that server (split into "with metakernels" and "no default mk/")
3.  Select one by number; or type the name of a "no default mk/" mission to consult the curated registry
4.  Configure deduplication: `Enable deduplication for this mission? [Y/n]:`
5.  Store in database

``` bash
skd mission add
```

| Option | Description |
|----|----|
| `name` (positional, optional) | Mission name. When given, prompts are skipped. |
| `--server-url <URL>` | Archive server base URL. Required with positional name unless the mission name is unambiguous on a known server. |
| `--mk-dir-url <URL>` | Override the metakernel directory URL (bypasses auto-discovery). Validated with a HEAD request. |
| `--no-dedup` | Disable deduplication for this mission. |

``` bash
# Interactive
skd mission add

# Non-interactive, explicit metakernel directory
skd mission add LRO \
  --server-url https://naif.jpl.nasa.gov/pub/naif/ \
  --mk-dir-url https://naif.jpl.nasa.gov/pub/naif/LRO/data/spice/mk/

# Non-interactive, let the tool auto-discover (curated registry + alt-path probe)
skd mission add OSIRIS-REX --server-url https://naif.jpl.nasa.gov/pub/naif/
```

When discovery finds multiple candidate metakernel directories, the command lists them and asks you to re-run with `--mk-dir-url`. When it finds none, it points at the troubleshooting docs.


### Curated metakernel registry

For missions whose metakernels live outside the default `{server}/{MISSION}/kernels/mk/` path -- typically on PDS nodes rather than NAIF -- the package ships `mission_registry.toml`, a curated list of verified alternate locations. The `mission add` flow checks this registry first, then falls back to the standard `kernels/mk/` probe.

An empirical NAIF survey found that no missions use the speculative patterns (`spice_kernels/mk/`, `data/spice/mk/`, etc.) one might expect from naming convention alone; the registry is therefore deliberately sparse and only grows through verified contributions. See `docs/troubleshooting.qmd` for the contribution format. Registry entries may use absolute URLs (PDS nodes, mission websites), not just `{server}`/`{m}` placeholders.

After setup, the command prints next steps for acquiring metakernels.


## `mission list`

Show all configured missions with their server, deduplication status, and mk/ directory URL.

``` bash
skd mission list
```

Example output:

    Configured missions:

      Mission  Server  Dedup  mk/ URL
      ───────  ──────  ─────  ──────────────────────────────
      JUICE    ESA     yes    https://spiftp.esac.esa.int/data/SPICE/JUICE/kernels/mk/
      MRO      NASA    no     https://naif.jpl.nasa.gov/pub/naif/MRO/kernels/mk/


## `mission remove`

Remove a configured mission from the database.

``` bash
skd mission remove <name>
```

| Option | Description            |
|--------|------------------------|
| `name` | Mission name to remove |

``` bash
skd mission remove MRO
```


# `config`

Show or update configuration.

``` bash
skd config [--setup]
skd config get <key>
skd config set <key> <value>
skd config add-root <dir>
skd config remove-root <dir>
```

| Option | Description |
|----|----|
| `--setup` | Re-run the interactive first-time setup |
| `get <key>` | Print one setting. The only key is `db_path`. Any other key, `kernel_dirs` included, is refused with a pointer to `add-root` and `remove-root`. |
| `set <key> <value>` | Change one setting and save it. |
| `add-root <dir>` | Append a directory to the kernel roots and save. The directory is created when missing. A directory that is already a root is not added twice. |
| `remove-root <dir>` | Remove a directory from the kernel roots and save. The last root cannot be removed. Files on disk and database rows stay as they are; `clean` drops rows whose file is gone. |

``` bash
# Show current settings
skd config

# Re-run setup (change database path, kernel directory, etc.)
skd config --setup

# Read or change one setting
skd config get db_path
skd config set db_path ~/Dropbox/spice-kernels.duckdb

# Add a second store, then index it
skd config add-root ~/planetarypy_data/spice_kernels
skd scan

# Stop using it
skd config remove-root ~/planetarypy_data/spice_kernels
```

Without arguments, prints the current configuration: config file location, database path and the kernel roots, one per line. `add-root` and `remove-root` print the same listing afterwards, and `add-root` reminds you to scan the new root.


# Renamed commands

Issue \#47 renamed most verbs. Each old name still runs. It prints `note: 'old' is now 'new'` on stderr, then runs the new command with the new command's options. The old names are hidden from `--help` and go away in 1.0.

| Old name | New name | Notes |
|:---|:---|:---|
| `list <mk>` | `show <mk>` | `--type` and `--mission` carry over. |
| `metakernels [--mission NAME]`, `mk [--mission NAME]` | `ls [mission]` |  |
| `metakernels <name>`, `mk <name>` | `show <name>` |  |
| `metakernels --remove <name>`, `mk --remove <name>` | `rm <name>` |  |
| `resolve <kernel>` | `which <kernel>` | `which` also prints the alias tables when the content has several names. |
| `resolve --metakernel <mk>` | `which --metakernel <mk>` |  |
| `aliases [name-or-hash]` | `which [kernel]` |  |
| `duplicates` | [stats](../reference/KernelDB.stats.md#spice_kernel_db.KernelDB.stats) | The duplicate report follows the statistics. |
| `prune [--execute]` | `clean --locations [--execute]` | The alias keeps the old behaviour. `clean` with no class flag also sweeps dangling symlinks. |
| `prune --metakernels`, `prune --mk` | `clean --registry` |  |
| `prune --orphan-symlinks` | `clean --symlinks` |  |
| `verify <mk>` | `check <mk>` | `--deep` is `--hash`. `--strict` has no equivalent and is ignored with a note. The database-wide report is [doctor](../reference/KernelDB.doctor.md#spice_kernel_db.KernelDB.doctor). |
| `update <name>` | `get <name>` | `update` with no argument is now the walk over all tracked metakernels. |
