# Architecture

Nidhi is a single-page application with no build step required to run it, no
backend, and no network calls of its own. This document explains how the pieces
fit, and why each one is where it is.

## The shape of it

```
index.html            the landing page — static, links to play/
play/index.html       the app: loads kits/ and src/ as separate files
dist/index.html       the same app with everything inlined into one file
src/                  the code that is Nidhi's own
kits/                 vendored fleet kits, unmodified
tests/                node tests for everything in src/
tools/                build, integrity, snapshot, sync host, test runner
docs/                 these documents, and the screenshots the landing page uses
```

`play/index.html` is the readable form: sixteen `<script>` and `<link>` tags, one
per module. `dist/index.html` is the same page with those sixteen files inlined by
`tools/build.py`, for handing to someone as a single artefact. Neither is
generated by hand; edit `src/` or `play/index.html` and run the build.

## Layers

Five layers, each with one job. The rule is that a layer may only talk to the
layer below it.

| Layer | Files | Responsibility |
|---|---|---|
| **View** | `src/app.js` | DOM, events, rendering the four views. The only file that touches `document`. |
| **Domain** | `src/nidhi.js`, `src/suggest.js`, `src/cards.js`, `src/timeline.js`, `src/ledger.js`, `src/sync.js` | The rules. Pure functions over plain objects. No DOM, no storage, no network. |
| **Kits** | `kits/*.js` | Reusable machinery the fleet already built: storage, search, crypto, SM-2, case timeline, LAN room, ml. |
| **Storage** | web-kit's `Loom.storage` | IndexedDB for records, localStorage for settings. |
| **Transport** | lan-kit (optional) | A room on the local network. Only active if you start the host. |

The domain layer is the reason the test suite is fast and boring: every rule in
Nidhi can be exercised in Node with no browser, no storage and no server. If a
rule is hard to test, it is in the wrong layer.

## Why the domain is pure

`src/nidhi.js` never reads a clock, never generates a random id without being
asked, and never mutates its arguments. Time and randomness arrive as parameters:

```js
Nidhi.newRecord({ title: "x" }, { id: "r-1", clock: () => new Date("2026-11-28T06:00:00Z") })
```

That is what makes `tests/test-nidhi.js` deterministic. It is also why the merge
rules can be shared between the import path and the sync path — the same function,
called with the same inputs, gives the same answer whether the other device is a
file on a USB stick or a socket on the LAN.

## Data flow

**Writing a record**

```
editor → saveEditor() → Nidhi.touch() → validate() → put()
                                                    ├→ state.records (in memory)
                                                    ├→ Loom.storage.put() (IndexedDB)
                                                    ├→ rebuildIndex() (search-kit)
                                                    └→ state.sync.send() if connected
```

**Arriving from another device**

```
lan-kit onMessage → NidhiSync.readEnvelope() → mergeIncoming()
                                                  ├→ Nidhi.reconcile() (pure)
                                                  └→ put() for each changed record
                                                       (state.applyingRemote suppresses the echo)
```

The `applyingRemote` flag exists for one reason: without it, applying a remote
record would broadcast it straight back and the two devices would talk to each
other forever.

## The views

Four views plus sync, all rendering into the same `state.records` array:

- **Records** — the list, the folder chips, search.
- **Review** — one due card at a time (`src/cards.js`).
- **Health** — a timeline and a severity sparkline (`src/timeline.js`).
- **Money** — a posting form and three tables (`src/ledger.js`).
- **Sync** — the room, its status, and a log of what arrived.

`render()` always renders the record list, even while another view is showing.
That was a bug once: a record arriving over sync was in the vault but not in the
DOM until you switched tabs. Rendering it unconditionally costs nothing and
removes a whole class of "why isn't it there" confusion.

## Storage

One IndexedDB database (`nidhi-db`), one object store (`records`), keyed by record
id. Settings — theme, language, last sync address — live in localStorage under the
`nidhi:` prefix, via `Loom.storage.namespace("nidhi")`.

There is a small localStorage cache of the last 200 live records. It exists for
one case: the browser refuses to open IndexedDB (a private window with storage
blocked, a corrupted profile), and the app shows you what it last had instead of
an empty vault. It is a fallback, never the source of truth.

## Error handling

Every kit call that can fail is wrapped, and every failure is visible:

- `put()` catches a refused write and says so in a toast, naming the error.
- `loadAll()` falls back to the cache and tells you it did.
- `boot()` wraps the whole start-up and, if it throws, prints the message at the
  top of the page rather than leaving a blank screen.
- Dataview-style silence — a `catch` that swallows — appears nowhere. There is no
  empty `catch` block in `src/`.

## What is deliberately absent

No framework, no bundler, no npm dependency at runtime. `kits/` is vendored rather
than imported so the app works from `file://`, from a USB stick, and from a GitHub
Pages URL without a build. The cost is that updating a kit is a copy, not a
`npm update`; the benefit is that the artefact you test is the artefact you ship.

See [DATA.md](DATA.md) for the record schema, [SYNC.md](SYNC.md) for the room, and
[DEVELOPING.md](DEVELOPING.md) for how to build and test.
