# Maintenance

Maintenance controls logging, cleanup, and service restarts for CrossWatch (CW). Open **Settings → Maintenance**.

### Debug level

Use **Debug** to control log verbosity.

* **off**: warnings and important messages only.
* **on**: more detail about runs and provider calls.
* **mods**: `on`, plus provider-module debug.
* **full**: maximum detail. Use for troubleshooting. Logs get noisy.

You can change this anytime. It does not change provider data or sync results.

### Maintenance tools

<figure><img src="/files/Q8tCA5irnQW3fBWtANnE" alt=""><figcaption></figcaption></figure>

Open **Maintenance Tools** for one-click cleanup actions.

<figure><img src="/files/6eC16ePWBB4d2NrK86hQ" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
These actions are local to CW. They do not directly edit Plex/Trakt/SIMKL/Jellyfin/Emby. They can still delete local files. Back up if you are unsure.
{% endhint %}

These buttons are **local-only cleanup/reset actions**.

* They delete CW files on disk.
* The next UI load / sync run rebuilds state by reading providers again.
* The next sync may be slower and “noisier” because caches are gone.

Use these when:

* the UI shows stale info
* a cache got corrupted
* a sync keeps repeating the same actions
* stats/insights look wrong
* “currently playing” is stuck

The dialog shows:

* **Tracker root**: local tracker state and snapshots.
* **Provider cache**: provider cache and shadow files.

#### Storage locations (what CW deletes)

The UI shows the **actual resolved paths** from the API.

* **Config directory**: holds `config.json` and `state.json` (orchestrator baseline).
* **Provider cache** (`.cw_state`): provider “shadow” files, unresolved bookkeeping, `currently_watching.json`.
* **Metadata cache** (`cache/`): cached posters/artwork and metadata blobs.
* **CW tracker** (`.cw_provider/` by default): `watchlist.json`, `history.json`, `ratings.json`, plus optional `snapshots/*.json`.

{% hint style="info" %}
If paths shown in the UI differ from what you expect, trust the UI. It’s reading them from the backend.
{% endhint %}

### When to clear state or provider cache

Do **not** clear cache between normal syncs.

This is a repair step. It is not routine maintenance.

Clear **state + provider cache together** when:

* you switch a pair between **one-way** and **two-way**
* you update CrossWatch and the next plan looks wrong
* you backfill history using old dates and new items do not appear
* a run wants to remove far more items than expected

Why these cases matter:

* **Mode switch**: old baselines can use a different key shape than the new mode expects.
  * On the first two-way run, that can look like false deletions.
* **After an update**: adapter refactors can change keys, ID normalization, or episode grouping.
  * Old cache files may no longer match current provider output.
* **Historical backfill**: older watermark files can miss items added with old timestamps.
  * Current builds handle this better, but older cache files may still need one reset.
* **Unexpected mass removes**: stop immediately.
  * Restore from the provider’s own undo/history first.
  * Then reset local state before trying again.

{% hint style="warning" %}
If the first run after a config change wants to delete a lot of items, do not “see what happens”.

Stop, restore on the provider side if needed, clear local state/cache, then rerun in dry run.
{% endhint %}

#### Clear state

![image](https://github.com/user-attachments/assets/e64da9af-acd5-4ad6-8ad1-9d516832d434)

**What it does**

* Deletes `/config/state.json`.
* Forces a full rebuild on the next run.

Best for:

* bad or stuck sync plans
* relearning after big provider-side changes
* switching a pair between **one-way** and **two-way** when planning looks wrong

Does not:

* remove items from Plex/Trakt/SIMKL/Jellyfin/Emby
* delete CW tracker snapshots

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/clear-state`
* **Deletes:** `CONFIG_DIR/state.json`
* **Why you’d use it:** force a clean baseline diff after a sync loop.

</details>

#### Clear provider cache

![image](https://github.com/user-attachments/assets/41551b64-c212-4c03-86a7-a41ff37bb83d)

**What it does**

* Removes files in the provider cache directory (shown in the UI).
* Forces provider health and unresolved refetch.

Best for:

* provider health/unresolved counts that never change
* CW reusing obviously old provider data
* clearing tombstones, watermarks, and provider-side index cache files after a bad plan
* pairing with **Clear state** for the safest sync reset

Does not:

* change any provider libraries or history

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/clear-cache`
* **Deletes:** all **top-level files** under `CW_STATE_DIR` (not nested directories).
* The UI may list `*.json`, but cleanup removes any top-level file.

</details>

#### What each reset clears

Use this when you are cleaning files manually, or when you want to know what the UI buttons are rebuilding.

**Clear state** removes:

* `state.json`
  * clears provider baselines
  * clears old mode-transition memory

**Clear provider cache** typically removes files under `.cw_state/`, including:

* `tombstones.json`
  * clears deletion memory that can block re-adds or drive removes
* `*.flap.json`
  * clears previous snapshot/failure tracking
* `*.index.*.json` and `*.cache.*.json`
  * clears provider-specific index caches
* `*.watermarks.*.json`
  * forces a full refetch instead of delta

#### Safest full reset

For the cleanest rebuild:

1. Run **Clear state**
2. Run **Clear provider cache**
3. Rerun with **Dry run** first
4. Start with one pair and one feature if you are debugging

If you are cleaning files by hand, deleting `state.json` plus everything in `.cw_state/` is the safest full reset.

The next run will be slower. It will rebuild from live provider data instead of old local cache.

{% hint style="info" %}
Routine delta caching, watermarks, and tombstones are correct in steady state.

Only clear them when you are fixing a bad plan or recovering from a major change.
{% endhint %}

#### Remove metadata cache

![image](https://github.com/user-attachments/assets/c68eff65-d82b-4ef0-8ad2-4228cbe404ec)

**What it does**

* Deletes cached artwork and metadata under `/config/cache`.
* Forces a re-fetch when items are processed or viewed.
* Can free disk space.

Best for:

* wrong, corrupt, or outdated posters/artwork
* visual glitches caused by stale cached images
* large caches you want to prune

Does not:

* delete movies/shows or change provider libraries
* touch tracker state files or `/config/.cw_state`

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/clear-metadata-cache`
* **Deletes:** everything inside `CACHE_DIR` (files + directories).

</details>

#### Clear CW tracker

![image](https://github.com/user-attachments/assets/a2629f57-b0e4-493e-860c-4a62489a035b)

The CW tracker is a local backup of:

* Watchlist
* History
* Ratings

You will see two checkboxes:

* **Tracker state files**: removes current tracker state.
* **All snapshots**: removes tracker snapshots.

You can select one or both. If both are unchecked, nothing runs.

**What it does**

* **Tracker state files**: clears local tracker state files.
* **All snapshots**: deletes tracker snapshot backups.

Best for:

* forcing a clean tracker rebuild from live providers
* deleting old snapshots you no longer need

Does not:

* touch provider libraries or watch history
* modify `/config/state.json` (orchestrator state)

This deletes local container files. Typical names are `watchlist.json`, `history.json`, and `ratings.json`.

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/crosswatch-tracker/clear`
* **Body:**

```json
{
  "clear_state": true,
  "clear_snapshots": false
}
```

* If `clear_state=true`: deletes `TRACKER_ROOT/*.json`
* If `clear_snapshots=true`: deletes `TRACKER_ROOT/snapshots/*.json`

</details>

#### Reset statistics

![image](https://github.com/user-attachments/assets/53a55680-1900-4370-b663-6ae20738d5d7)

**What it does**

* Clears stats + insights caches (and related report files).
* Next stats/insights load will rebuild from refreshed state.

Best for:

* obviously wrong or stale Dashboard numbers
* after large cleanups, to refresh reports

Does not:

* change provider data or tracker snapshots

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/reset-stats`
* **Default behavior (UI sends `{}`):** purges stats file + state file + reports + insights caches.
* **Optional body fields:**

```json
{
  "recalc": false,
  "purge_file": true,
  "purge_state": true,
  "purge_reports": true,
  "purge_insights": true
}
```

Notes:

* This is analytics cleanup. It should not affect provider data.
* If `recalc=true`, it tries to refresh stats from current `state.json` after purging.

</details>

#### Reset currently playing

![image](https://github.com/user-attachments/assets/0cb4d80b-f4ce-4b19-a96c-041058d61746)

**What it does**

* Clears `currently_watching.json`.
* Removes stuck "currently playing" entries.

Best for:

* UI shows something playing when nothing is playing

Does not:

* remove watched history from any provider

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/reset-currently-watching`
* **Deletes:** `CW_STATE_DIR/currently_watching.json`

</details>

### Restart CW

The **Restart CrossWatch** button restarts the CW service (container/app) from inside the UI.

* Restarts the backend to reload config and code.
* Avoid restarting during an active sync run.
* Your settings and provider connections are not reset.

{% hint style="warning" %}
This is a hard restart. It’s not graceful. Don’t press it mid-sync unless you like chaos.
{% endhint %}

<details>

<summary>Advanced: API details</summary>

* **Endpoint:** `POST /api/maintenance/restart`
* Behavior: schedules a hard process exit (`os._exit(0)`) after \~0.75s.
* Your supervisor (Docker restart policy / systemd / etc.) should bring it back.

</details>

### Advanced: status endpoints

Use these to inspect what CW sees on disk.

* `GET /api/maintenance/provider-cache`
  * returns whether it exists, root path, and `*.json` file list (name/size/mtime)
* `GET /api/maintenance/crosswatch-tracker`
  * returns resolved tracker root, tracker `*.json`, snapshot `*.json`, and counts

### Advanced: “Clean Everything” order

The UI runs these **in order** (after confirmation):

1. `POST /api/maintenance/clear-state`
2. `POST /api/maintenance/clear-cache`
3. `POST /api/maintenance/clear-metadata-cache`
4. `POST /api/maintenance/crosswatch-tracker/clear` with:

```json
{ "clear_state": true, "clear_snapshots": true }
```

5. `POST /api/maintenance/reset-stats` with `{}` (defaults to full purge)
6. `POST /api/maintenance/reset-currently-watching`

If you clicked this by accident, you basically chose “rebuild everything from scratch”.

### Advanced: troubleshooting notes

* If “Reset statistics” doesn’t fully clear insights:
  * some caches are best-effort imports; missing modules simply won’t be cleared
  * file patterns are broad on purpose; it cleans “insight-ish” JSON across config/cache/state folders
* If something still looks wrong after a full clean:
  * the problem is likely provider data or mapping logic (not local cache)

<details>

<summary>Advanced: response format</summary>

Most endpoints return JSON like:

* `ok: true` on success
* `ok: false` + `error` on failure
* some include `before` / `after` scans and `removed` lists

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.crosswatch.app/crosswatch/maintenance.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
