Bladeren bron

Add cluster thumbnail rendering support

Render thumbnails for cluster:/ files on nodes that hold the content, cache the results locally by content hash, and avoid writing .metadata/.cache into the cluster namespace. This also adds cleanup for legacy thumbnail folders, updates cluster storage/filesystem metadata plumbing and tests, ignores the new system cache directory, and documents the cluster architecture in a new whitepaper.
Toby Chui 2 maanden geleden
bovenliggende
commit
5e0f3b0a5f

+ 1 - 0
.gitignore

@@ -53,3 +53,4 @@ src/system/telegram_conf.json
 src/system/git/
 /.kilo
 /reference
+/src/system/cache

+ 1276 - 0
docs/ArozOS-Cluster-Whitepaper.md

@@ -0,0 +1,1276 @@
+# ArozOS Cluster: Technical White Paper
+
+**Many independent ArozOS nodes presented as one logical computer**
+
+| | |
+|---|---|
+| Document | ArozOS Cluster technical white paper |
+| Applies to | ArozOS v3.0.4 branch (cluster Phases 1 to 9 complete) |
+| Audience | Developers, integrators and administrators |
+| Source of truth | `src/mod/cluster/README.md`, `src/mod/cluster/TASKS.md`, the Go packages under `src/mod/cluster/` |
+| License | ArozOS is GPLv3; this document follows the project license |
+
+---
+
+## Contents
+
+1. Executive summary
+2. Design goals and non-goals
+3. Architecture overview
+4. Identifiers and addressing
+5. ACN: the node-to-node protocol
+6. Membership, joining and node states
+7. Identity (single sign-on across nodes)
+8. The metadata store (ACMS)
+9. Storage and the `cluster:/` drive
+10. Replication
+11. The event bus
+12. Jobs, map/reduce and the job contract
+13. Scheduling
+14. Developer interfaces: AGI, HTTP and Go
+15. Worked examples
+16. Minimum dependencies and requirements
+17. Limits and maximum capabilities
+18. Security model
+19. Operations and administration
+20. Developer guide: extending the cluster
+21. Known constraints and pitfalls
+22. Appendix A: endpoint reference
+23. Appendix B: tunables and constants
+24. Appendix C: glossary
+
+---
+
+## 1. Executive summary
+
+The ArozOS cluster lets several independent ArozOS installations, which may
+run on different hardware, operating systems and CPU architectures, act as a
+single logical computer. A cluster provides four unified services:
+
+- **One namespace.** A `cluster:/` drive appears in File Manager, WebDAV,
+  media serving and every AGI library on every member. Files stay whole files
+  inside ordinary folders that nodes contribute; a replicated metadata index
+  says which nodes hold which copies.
+- **One identity.** A user logs in on any member with the same credentials.
+  Logins are forwarded to an *identity origin* node, with a replicated account
+  directory as fallback when the origin is unreachable.
+- **One compute pool.** AGI job scripts are submitted once and run on the
+  best node for them, chosen by capability (for example `ffmpeg` or `nvidia`),
+  data locality and load. Map/reduce spreads work across the nodes that
+  already hold the data.
+- **One API.** The AGI `cluster` library, an event bus with script hooks and
+  a WebSocket feed, and admin HTTP endpoints hide node selection, routing,
+  retries and replication from applications.
+
+Every node keeps working as a normal standalone ArozOS when the cluster, or
+any other member, is unreachable. The whole feature ships inside the single
+ArozOS binary, adds no external service (no etcd, no ZooKeeper, no database
+server), requires no quorum, and works with as few as two nodes, including
+nodes behind NAT or Cloudflare.
+
+---
+
+## 2. Design goals and non-goals
+
+### 2.1 Goals
+
+1. **Heterogeneous nodes.** An x86 server, a Raspberry Pi and a Windows
+   workstation must be able to cooperate. Nothing assumes a shared OS,
+   architecture, installed tools or hardware.
+2. **Autonomy.** A node is always a complete ArozOS. Losing the cluster
+   degrades only the cluster features.
+3. **Whole files.** Files are never split into blocks across nodes. Any copy
+   is a normal file that can be read with ordinary tools, and the index can
+   always be rebuilt by scanning the real files.
+4. **Small clusters first.** Two-node clusters must work, including failover.
+   This rules out majority-quorum consensus.
+5. **Internet friendly.** Nodes may sit behind NAT, reverse proxies or
+   Cloudflare. All transfers fit within Cloudflare request and idle limits.
+6. **A stable application API.** Applications use AGI (the ArozOS JavaScript
+   Gateway Interface) and never talk to node addresses.
+7. **Portability.** Pure Go, no CGO requirement, no platform tools in shared
+   code, build-tagged syscalls.
+
+### 2.2 Non-goals
+
+- A Hadoop/Ceph-style block file system or erasure coding.
+- Strong linearizable consistency (no Raft or Paxos). Metadata converges
+  last-writer-wins, serialised by a leader lease.
+- Large-scale clusters. Heartbeats are a full mesh; the design targets
+  households, labs and small offices, not hundreds of nodes.
+- Running native binaries as jobs. Jobs are AGI scripts, because node
+  architectures differ; native work is reached through AGI libraries (for
+  example `ffmpeg`) on nodes that have the tool.
+
+---
+
+## 3. Architecture overview
+
+### 3.1 Layers
+
+```
++---------------------------------------------------------------+
+|  Applications: File Manager, WebDAV, Photo, Movie, AGI apps   |
++---------------------------------------------------------------+
+|  AGI "cluster" library  |  cluster:/ drive  |  /system/cluster |
++---------------------------------------------------------------+
+|  jobs (+ map/reduce)  |  events  |  replication  |  storage   |
++---------------------------------------------------------------+
+|            scheduling (one weighted scorer for all)            |
++---------------------------------------------------------------+
+|  metadata store (ACMS): leader lease + replicated log         |
++---------------------------------------------------------------+
+|  identity (AID)       |  membership (agent, gossip, health)   |
++---------------------------------------------------------------+
+|  ACN: Ed25519 signed HTTP, direct / tunnel / relay routing    |
++---------------------------------------------------------------+
+|  HTTP(S) on the normal ArozOS port, under /cluster/acn/*      |
++---------------------------------------------------------------+
+```
+
+### 3.2 Packages
+
+All cluster code lives under `src/mod/cluster/` (module path
+`imuslab.com/arozos`).
+
+| Package | Role |
+|---|---|
+| `acn/` | ArozOS Cluster Node protocol: node keys, signed requests, replay protection, routing, WebSocket reverse tunnel |
+| `capability/` | Portable detection of OS, arch, cores, RAM, tools and CPU flags; requirement matching; cross-platform `DiskUsage` |
+| `membership/` | The cluster agent: create, join, leave, gossip of node records, heartbeats, node states, latency, cluster settings, admin endpoints |
+| `identity/` | Forward authentication to the identity origin, account directory mirror, password write-back, signed user assertions |
+| `metadata/` | Replicated namespace index (files, copies, volumes, policies, settings, jobs), leader lease, replicated log, snapshots, write-behind persistence |
+| `storage/` | Contributed volumes, placement, chunked verified transfers, reads and writes for the drive, reconcile, copy primitives |
+| `replication/` | Leader-side planner and per-node worker keeping every file at its policy's copy count |
+| `events/` | Publish/subscribe with cluster-wide fan-out and de-duplication, AGI hooks, WebSocket feed |
+| `jobs/` | Replicated job records, leader-side scheduler, per-node execution, leases, cancellation, map/reduce |
+| `scheduling/` | The single placement scorer used by jobs, writes and replication |
+| `wakeonlan/` | Wake-on-LAN packets for offline LAN neighbours |
+
+Related code outside the package:
+
+| File | Role |
+|---|---|
+| `src/cluster.go` | Core wiring (`ClusterInit`, `clusterStartAgent`), drive mount/unmount, AGI provider, event hooks, master-node resolver, shutdown |
+| `src/cluster.jobs.go` | Job executor adapter to the AGI gateway, job submit handler, `sched/explain` |
+| `src/cluster.fsinfo.go` | Cluster tab of the File Manager properties dialog |
+| `src/mod/filesystem/abstractions/clusterfs/` | The `cluster:/` file system abstraction |
+| `src/mod/agi/agi.cluster.go` | The AGI `cluster` library |
+| `src/main.router.go` | Mounts `/cluster/acn/*` before the session check |
+| `src/web/SystemAO/cluster/` | Cluster Settings, Cluster Info and Cluster Jobs pages |
+| `src/web/SystemAO/locale/cluster.json` | UI and server message translations |
+| `examples/clusters_jobs/` | Runnable job examples |
+
+### 3.3 Start-up order
+
+`ClusterInit` (called from `src/startup.go`) runs `clusterStartAgent` unless
+`-disable_cluster` is set. Services are created in dependency order, and each
+is optional: if one fails to start, the services below it are skipped and the
+failure is logged under the `Cluster` title.
+
+```
+membership.NewManager      (system/cluster.db, system/cluster/node.key)
+  -> identity.New           (hooks authAgent.ForwardAuth)
+  -> metadata.New
+       -> scheduling.New
+       -> storage.New       (mounts cluster:/ via clusterSyncDrive)
+            -> events.New   (file / replica / disk-full events)
+            -> jobs.New     (user routes, "Cluster Jobs" page)
+            -> AGI ClusterLibRegister()
+            -> replication.New (nightly verify task)
+```
+
+AGI starts before the cluster, so the `cluster` library is registered late
+through `AGIGateway.ClusterLibRegister()` once the provider exists.
+`ClusterShutdown` closes the services in reverse order so heartbeats and
+tunnels stop cleanly.
+
+---
+
+## 4. Identifiers and addressing
+
+Nothing in the cluster is addressed by a name. Names are operator-set and
+every fresh install is called `My ArOZ`, so two nodes can share a name. Only
+the IDs below are unique.
+
+| Thing | Identifier | Origin | Unique within |
+|---|---|---|---|
+| Cluster | `ClusterInfo.ID` (UUID v4) | `CreateCluster`, carried in join tokens | everywhere |
+| Node | `NodeRecord.ID` = device UUID | `system/dev.uuid` or the `-uuid` flag | the cluster |
+| Node identity | Ed25519 key pair | `system/cluster/node.key` | everywhere |
+| Node name | `NodeRecord.Name` | `-hostname`, default `My ArOZ` | **not unique** |
+| Drive on a node | `FileSystemHandler.UUID` (`user`, `s1`, ...) | node storage config | **that node only** |
+| Volume | `Volume.ID` (UUID v4) | `AddVolume` | everywhere |
+| Volume location | `NodeID` + `FshUUID` + `Subpath` | `AddVolume` (duplicates refused) | everywhere |
+| File | `FileRecord.ID` (UUID v4), keyed by `Path` | first write of the path | the cluster |
+| Copy | `VolumeID` (+ `NodeID`) in the record | placement / replication | per file |
+| Job | `Job.ID` (UUID v4) | job submit | the cluster |
+
+Because a drive UUID only means something on one node, every physical
+location the cluster displays is written **node first**:
+
+```
+<node uuid>:<drive uuid>/<path on that drive>
+3f7a...c1:user/cluster/photos/a.jpg
+```
+
+> **Warning: cloned installs.** Copying `system/dev.uuid` to a second host
+> gives both the same node ID and their membership records merge into one.
+> Delete `system/dev.uuid` and `system/cluster/` on a clone before it joins.
+
+---
+
+## 5. ACN: the node-to-node protocol
+
+### 5.1 Signed requests
+
+Every node owns an Ed25519 key pair (`acn.LoadOrCreateNodeKey`). The public
+key travels in the node's membership record. Every ACN request carries:
+
+```
+X-Aroz-Node:      <sender node UUID>
+X-Aroz-Cluster:   <cluster UUID>
+X-Aroz-Timestamp: <unix seconds>
+X-Aroz-Nonce:     <random hex>
+X-Aroz-Signature: base64(Ed25519(
+                    METHOD \n target \n cluster \n node \n
+                    ts \n nonce \n sha256(body)))
+```
+
+The receiver checks, in order: the sender is a known member, the cluster ID
+matches, the timestamp is within **plus or minus 5 minutes**, the nonce is
+unseen, and the signature verifies. Only after all checks pass is the nonce
+recorded, so junk requests cannot poison the replay cache. Signed bodies are
+capped at 64 MB.
+
+ACN is mounted at `/cluster/acn/*` in `src/main.router.go` **before** the
+user-session check, because nodes authenticate with signatures rather than
+cookies. `cluster` is therefore a reserved subservice path.
+
+### 5.2 Routing
+
+Callers use `acn.Transport.Do` / `DoJSON(ctx, nodeID, method, path, in, out)`
+and never deal with addresses. The transport picks the route:
+
+1. **Tunnel**: the peer has a live tunnel terminating on this node.
+2. **Direct**: the peer advertises a URL (behind Cloudflare is fine).
+3. **Relay**: the peer is tunnelled to another member `via`; the request
+   goes to `https://<via>/cluster/acn/relay/<peer>/cluster/acn/<path>` and
+   the tunnel host forwards it. The signature covers the *original* path, so
+   the relay and the final node verify the same signature.
+
+```
+      A (public URL)        B (public URL)        C (behind NAT)
+          |                      |                      |
+          |---- direct HTTPS --->|                      |
+          |                      |<==== WebSocket ======|  C tunnels to B
+          |-- relay/C/... ------>|==== frame ==========>|  A reaches C via B
+```
+
+### 5.3 Reverse tunnel
+
+A node without a public URL opens one WebSocket to a reachable member
+(`GET /cluster/acn/tunnel`, signed). Requests are multiplexed as binary
+frames `[kind][header length][header JSON][body]`, executed against the
+node's own ACN handler and answered on the same socket.
+
+- Both ends ping every **30 s** (read timeout 90 s), so Cloudflare's 100 s
+  idle limit never trips.
+- The client reconnects with backoff and re-picks a host: the admin's
+  preferred host, otherwise the healthiest reachable member.
+- Frames are capped at **16 MB**; file transfers use 4 MiB chunks, well under
+  Cloudflare's 100 MB request limit.
+- A NAT-only node still appears online everywhere, because its tunnel host
+  learns its `LastSeen` and gossips it.
+
+---
+
+## 6. Membership, joining and node states
+
+### 6.1 Node records and gossip
+
+Each node owns one `NodeRecord` (ID, name, public key, advertised URL, tunnel
+host, version, capabilities, admin state) with an `Updated` version stamp.
+Records travel with every heartbeat and merge **last-writer-wins** per record,
+so membership converges without a master.
+
+- A node is authoritative for its own record; others may only change its
+  admin state or remove it.
+- Removed nodes remain as **tombstones for 7 days** so the removal
+  propagates to members that were offline.
+- Heartbeats go to every peer every **15 s** (full mesh).
+- Versions come from `nextVersion(prev)`, strictly greater than the previous
+  value; one millisecond is not unique, so never compare with `>=`.
+
+### 6.2 Computed node states
+
+Liveness is computed locally, not gossiped:
+
+| State | Meaning |
+|---|---|
+| `ONLINE` | heard from within 45 s |
+| `DEGRADED` | online, but CPU or RAM at or above 97 %, or disk at or below 2 % free |
+| `UNKNOWN` | silent for 45 s to 3 min |
+| `OFFLINE` | silent for more than 3 min |
+| `MAINTENANCE` / `DRAINING` | set by an admin, overrides the above |
+
+### 6.3 Capability manifests
+
+Every node publishes a `capability.Manifest` in its record:
+
+```go
+type Manifest struct {
+    OS, Arch   string          // runtime.GOOS / GOARCH
+    CPUCores   int
+    TotalRAM   int64           // bytes, 0 when unknown
+    Hostname   string
+    Features   map[string]bool
+    GoVersion  string
+    DetectedAt int64
+}
+```
+
+Detected features:
+
+| Feature | Detected by |
+|---|---|
+| `ffmpeg`, `ffprobe`, `docker`, `git`, `python3`, `node` | executable found on `PATH` |
+| `nvidia` (and then `cuda`, `gpu`) | `nvidia-smi` found on `PATH` |
+| `avx`, `avx2`, `avx512` | `golang.org/x/sys/cpu` (x86) |
+| `neon` | `golang.org/x/sys/cpu` (ARM64 ASIMD) |
+| `64bit` | architecture name ends in `64` |
+
+Jobs express `capability.Requirements` (`features`, `minRam`, `minCores`,
+`os`, `arch`); `Manifest.Satisfies` returns the first unmet requirement as a
+human-readable reason, which is what a queued job shows.
+
+### 6.4 Creating and joining
+
+1. On a member **that has an advertised URL**, an admin generates a join
+   token in System Settings > Cluster Settings. The token is
+   `aroz-join:<base64 JSON>` and embeds the cluster ID, the issuer's URL and a
+   secret; only the secret's SHA-256 is stored. Tokens expire (default
+   24 hours) and can be listed and revoked.
+2. The admin pastes the token on the new node. It POSTs its record to the
+   issuer's `/cluster/acn/join`, receives the cluster info and member list,
+   and starts heartbeating. A node without a URL tunnels to the issuer
+   immediately.
+3. The issuer pushes the new member list to everyone else.
+
+Leaving (`/system/cluster/leave`) notifies peers, wipes every table
+registered with `membership.RegisterClusterTable` and unmounts `cluster:/`.
+An admin can also remove a node, which sends it `/cluster/acn/evict`.
+
+---
+
+## 7. Identity (single sign-on across nodes)
+
+One member can be made the **identity origin** (System Settings > Cluster >
+Identity). The choice is a cluster-wide setting replicated by gossip
+(`ClusterInfo.IdentityOrigin`, last-writer-wins on `SettingsVersion`).
+
+On every other member the auth agent's `ForwardAuth` hook runs before the
+local password table:
+
+1. **Forward auth.** The member sends the username and the SHA-512 hash of
+   the typed password to the origin (`POST /cluster/acn/auth/verify`,
+   signed). The origin compares in constant time and answers with the user's
+   group names. The clear-text password never leaves the member.
+2. **Mirror.** On success the member creates or updates the account locally
+   (hash plus the groups that exist on that node, matched by name) and opens
+   a normal local session.
+3. **Fallback.** If the origin is *unreachable*, the local table decides.
+   Members pull the origin's directory (`GET /cluster/acn/auth/directory`)
+   at boot, every 5 minutes and when the origin setting changes. If the
+   origin is reachable and says the password is wrong, the login is rejected
+   with no fallback.
+4. **Write-back.** Password changes of mirrored accounts are forwarded to the
+   origin (`POST /cluster/acn/auth/setpassword`). Core code that changes a
+   password must call `clusterNotifyPasswordChanged` after writing the hash.
+
+Rules: only mirrored accounts are ever touched; a pre-existing local account
+with the same name is left alone ("local only"); accounts whose groups do not
+exist on a member are skipped and listed. **Permission groups are
+node-specific**, so create the same groups on every node.
+
+### 7.1 Signed user assertions
+
+Node A can act on node B for a logged-in user without contacting the origin:
+
+```
+token  = base64url(payload) "." base64url(Ed25519 signature)
+header = X-Aroz-User: <token>
+```
+
+`identity.Issue(username, ttl)` creates it (default lifetime 5 minutes),
+`Attach(req, username)` sets the header and `FromRequest(r)` verifies it
+against the issuer's published node key, returning
+`*identity.Assertion{User, Groups, Issuer}`.
+
+---
+
+## 8. The metadata store (ACMS)
+
+The ArozOS Cluster Metadata Store is the replicated index of the namespace.
+File contents never pass through it.
+
+### 8.1 Record kinds
+
+| Kind | Type | Key fields |
+|---|---|---|
+| file | `FileRecord` | `ID`, `Path`, `IsDir`, `Size`, `ModTime`, `Checksum` (SHA-256), `Owner`, `Primary`, `Locations[]`, `Replicas`, `Removed`, `Version` |
+| volume | `Volume` | `ID`, `NodeID`, `Name`, `FshUUID`, `Subpath`, `Capacity`, `Free`, `ReadOnly`, `Evacuating`, `LowSpace`, `Removed` |
+| policy | `Policy` | `Folder` (top level, e.g. `/photos`), `Replicas` |
+| setting | `Setting` | `Key` (e.g. `scheduling.weights`), `Value` (JSON) |
+| job | `Job` | `ID`, `Owner`, `Node`, `Status`, `Body` (full job record) |
+
+A copy of a file is a `Location{VolumeID, NodeID, State, Checksum, Updated}`
+with a state of `pending`, `writing`, `committed`, `verified`, `stale` or
+`failed`. A copy is *healthy* when `committed` or `verified`.
+
+### 8.2 Consistency model
+
+Every record carries a `Version` from `membership.NextVersion` and merges
+**last-writer-wins** on every node. There is deliberately no Raft: the store
+converges without a majority, and correctness can always be restored by
+rescanning the real files (storage reconcile).
+
+- **Leader lease** (`lease.go`). The eligible member that joined first
+  (ties by ID) claims a **30 s** lease with a higher term when no live lease
+  exists and renews it every **10 s**. Every member accepts a lease with a
+  higher term. No quorum is needed, so a two-node cluster fails over.
+  `IsLeader()` / `Leader()` serialise decisions: placement, replication
+  planning and job scheduling.
+- **Replicated log** (`log.go`). `Submit(kind, record)` applies locally at
+  once; the leader assigns a sequence number and pushes the entry to online
+  peers (`meta/append`). Followers submit through the leader (`meta/submit`)
+  or queue in `meta_pending` until one is reachable. Gaps are filled with
+  `meta/log?after=N`; a compacted range, a new term or a fresh follower
+  (`applied == 0`) triggers a full `meta/snapshot`.
+- **Write-behind persistence** (`persist.go`). Reads come from memory. A
+  change updates memory under the store lock and queues a disk write; writes
+  are coalesced per key and committed in one `database.WriteBatch`
+  transaction every **50 ms**. A crash loses at most one flush interval of
+  this node's disk copy, which catch-up restores like any other gap.
+
+> **Rule.** Never add a synchronous disk write inside the store lock. A write
+> burst would starve lease renewal and the leader would lose its lease.
+
+Read API: `Stat`, `ListDir`, `Glob`, `Volumes`, `PolicyFor`. Write API:
+`Submit(kind, record)`. New tables go through
+`membership.RegisterClusterTable` so they are wiped on leave.
+
+---
+
+## 9. Storage and the `cluster:/` drive
+
+### 9.1 Volumes
+
+An admin contributes a folder of a local drive as a **volume**
+(`storage/volume/add`, e.g. `user:/cluster`). Files in the namespace are
+ordinary files inside those folders. A rescan (`storage/rescan`, and
+automatically every 30 minutes) adopts files placed there by other means and
+flags copies that vanished or changed as `stale`. Volume capacity and free
+space are refreshed every 60 s.
+
+### 9.2 The drive
+
+When a node is in a cluster **and the cluster has at least one volume**, the
+core mounts a `Cluster` drive (`cluster:/`, public hierarchy, buffered) into
+the base storage pool (`clusterSyncDrive` in `src/cluster.go`, re-checked on
+every membership change and volume record change). File Manager, WebDAV,
+media serving and AGI `filelib` then use it like any other drive. Without a
+cluster or a volume the drive is unmounted, so nightly tasks and scanners do
+not see it.
+
+### 9.3 Write path
+
+```
+client write
+  -> spool locally while hashing (SHA-256)
+  -> ask leader for placement (scheduling scorer; local volume first,
+     then existing primary, then most free space)
+  -> copy bytes: local rename-in-place, or chunked upload to the target
+  -> publish FileRecord with a committed Location
+```
+
+The namespace never shows a half-written file: the record is published only
+after the bytes are in place. Replication then brings the file up to its
+policy's copy count.
+
+### 9.4 Read path
+
+A read opens a local healthy copy when there is one; otherwise it streams
+from an online node through the chunked protocol while verifying the
+checksum.
+
+### 9.5 Chunked transfer protocol
+
+| Endpoint | Purpose |
+|---|---|
+| `store/place` | ask the leader where a new file should go |
+| `store/begin` | open an upload session (resumable) |
+| `store/chunk` | one signed chunk, per-chunk SHA-256 |
+| `store/commit` | whole-file SHA-256 check, rename `.part-<session>` into place |
+| `store/abort` | discard a session |
+| `store/read` | ranged, chunked read |
+| `store/stat`, `store/list`, `store/checksum` | inspect copies |
+| `store/mkdir`, `store/rename`, `store/delete` | namespace operations on a volume |
+
+Chunks are **4 MiB** (maximum 8 MiB) and sessions expire after 30 minutes of
+inactivity.
+
+### 9.6 Space guard and maintenance
+
+- **Nearly full volumes.** Below **5 %** free a volume becomes read only and
+  `LowSpace`, stops taking new files and emits a `node.diskfull` event; it
+  recovers above **7 %**. The cluster setting `storage.autoReadOnly`
+  (Cluster Settings > Storage) turns this off. Read-only set by an admin is
+  never touched by the guard.
+- **Nightly maintenance on the master node only.** Every member sees the same
+  files on `cluster:/`, so trash expiry and version-history cleanup of a
+  shared drive run only on the **master node** (the metadata leader):
+  register such tasks with `nightly.TaskOption{MasterNodeOnly: true}`;
+  `nightlyShouldMaintainFsh` answers per file system handler. A standalone
+  host is its own master, so nothing changes for a single node.
+- **Where is my file?** The abstraction implements
+  `arozfs.StorageInfoProvider`, so the File Manager properties dialog shows a
+  Cluster tab with every copy, its node and volume (node-first path), state,
+  replica policy and checksum (`/system/file_system/getStorageInfo` ->
+  `src/cluster.fsinfo.go`).
+
+---
+
+## 10. Replication
+
+The replication manager keeps every file at the copy count its folder policy
+(or the record's own `Replicas`) asks for, on **different nodes**.
+
+### 10.1 Planner (metadata leader, every 60 s and on demand)
+
+| Situation | Action |
+|---|---|
+| fewer healthy copies than wanted | one pull task to a node without a copy; an existing stale copy is repaired in place |
+| more copies than wanted | drop the copy on the fullest non-primary volume, only when the rest are healthy |
+| copy on an *evacuating* volume or a `DRAINING` node | re-create elsewhere, then drop |
+| node `OFFLINE` for more than 10 minutes | mark its healthy copies `stale` (never deleted; reconcile restores them when it returns) |
+
+Limits: 4 tasks in flight per node, 16 in total, 4 workers per node. A file
+that fails backs off exponentially and is left alone for an hour after 5
+attempts. Tasks are ephemeral (in memory with a 50-entry history): a new
+leader simply plans again within one interval.
+
+### 10.2 Worker
+
+The target node pulls the bytes with the chunked protocol
+(`storage.Service.PullCopy`), verifies the checksum, publishes a `verified`
+location and reports to the leader, renewing a **30 s** task lease every
+**10 s**.
+
+### 10.3 Verification and evacuation
+
+- A nightly pass re-checksums up to **1 GB** of this node's copies, least
+  recently checked first, and downgrades mismatches to `stale`.
+  "Verify this node" runs it on demand (`repl/verify`).
+- `storage/volume/evacuate` marks a volume read only; the planner moves
+  everything off it and the volume is retired when nothing references it.
+  `volume/remove` refuses a volume that holds the only copy of a file.
+
+Replica counts range from **1 to 16** (policy) and 0 to 16 per file, where 0
+means "use the folder policy".
+
+---
+
+## 11. The event bus
+
+`events.Bus` provides publish/subscribe with cluster-wide fan-out
+(`/cluster/acn/events/publish`, batched every 200 ms) and de-duplication by
+event ID over a 10-minute window.
+
+```go
+type Event struct {
+    ID, Type, Node, Path, FileID, User string
+    Time int64
+    Data json.RawMessage
+}
+```
+
+| Event type | Raised when |
+|---|---|
+| `file.created`, `file.removed`, `file.renamed` | the storage layer writes, removes or renames a file (`renamed` carries `{"from": ...}`) |
+| `replica.verified`, `replica.stale` | a copy is verified or downgraded (`{"volume": ...}`) |
+| `node.joined`, `node.left`, `node.online`, `node.offline` | computed locally by every node from membership |
+| `node.diskfull` | a volume crosses the 5 % free guard |
+| `job.completed`, `job.failed` | a job reaches a terminal state |
+| `app.*` | custom events from `cluster.emit` (payload under 64 KB) |
+
+Consumers:
+
+- **AGI hooks.** `cluster.on(types, scriptVpath)` registers a persistent
+  hook (table `event_hooks`) that runs the script as its owner, with at most
+  4 hook runs at a time per node. The script reads the event with
+  `postPara("event")` (JSON). Types accept wildcards such as `file.*`.
+- **WebSocket feed.** Any logged-in user can subscribe at
+  `/system/cluster/events/ws`.
+- **Go.** `bus.Publish(events.Event{...})` from core code.
+
+---
+
+## 12. Jobs, map/reduce and the job contract
+
+### 12.1 Model
+
+A job is an AGI script that defines `run(job)`. The script **source is
+captured at submit time** and stored in one replicated record
+(`jobs.Record{Spec, State}`, metadata kind `job`), so any node answers status
+queries locally and a new leader resumes scheduling. Because it is
+JavaScript executed by the Otto VM inside ArozOS, the same job runs on x86,
+ARM, Windows, Linux or macOS nodes.
+
+```
+submit (any node) -> record queued -> leader schedules every 3 s
+  -> jobs/run to chosen node -> VM runs as the owner
+  -> lease renew every 10 s -> jobs/done -> record succeeded/failed
+```
+
+Statuses: `queued`, `scheduled`, `running`, `succeeded`, `failed`,
+`cancelled`. Kinds: `run`, `map`, `reduce`, `mapreduce`.
+
+### 12.2 The job contract
+
+```javascript
+function setup(ctx) {        // optional, runs once before run(); ctx = {node}
+}
+
+function run(job) {  // job = {id, name, kind, args, inputs, node, owner}
+    job.log("text");         // appended to the job log (last 200 lines)
+    job.progress(0.5);       // 0..1
+    if (job.cancelled()) {}  // poll for cancellation
+    job.abortIfCancelled();  // throws when the job was cancelled
+    return { ok: true };     // JSON-serialisable; becomes the job output
+}
+```
+
+- Normal AGI libraries (`filelib`, `imagelib`, `ffmpeg`, ...) work inside a
+  job and see `cluster:/`.
+- **Use absolute paths** (`cluster:/...`, `user:/...`). A job has no script
+  folder of its own, so relative paths are not resolved.
+- The job runs **as the submitting user** on the chosen node. The owner must
+  have an account there; with an identity origin configured, accounts are
+  mirrored automatically.
+
+### 12.3 Spec fields
+
+| Field (AGI / HTTP form) | Meaning | Default |
+|---|---|---|
+| `name` | display name | script name |
+| `script` | vpath of the `.agi` file (relative to the launcher in AGI) | required |
+| `args` | JSON passed as `job.args` | none |
+| `inputs` | files the job reads; nodes holding them are preferred | none |
+| `features` | required capabilities, e.g. `["ffmpeg"]` | none |
+| `nodes` | allowed node IDs; others are ineligible | any node |
+| `timeout` | seconds | 3600 |
+| `priority` (HTTP) | higher runs first | 0 |
+| `cores` (HTTP) | minimum CPU cores | none |
+| `dataset`, `partitionMax` / `partition` | map/reduce only | 50 files |
+
+`MaxAttempts` defaults to 3: when a running node goes silent the leader
+requeues the job, and fails it after the last attempt.
+
+### 12.4 Execution guarantees
+
+- **Parallelism.** At most `runtime.NumCPU()` jobs run per node; the rest
+  wait.
+- **Dispatch once.** Scheduling passes are serialised, and a node accepts each
+  job once even if a hand-over is repeated. Temporary refusals (a tunnel
+  still connecting, the leader not yet known) are retried. Only "the owner
+  has no account here" or "this node cannot run jobs" block that node from
+  that job for good (`State.Blocked`).
+- **Timeouts and cancellation.** `agi.Gateway.ExecuteJobScript` hands back a
+  stopper; a timeout or `cancel` interrupts the VM within about a second.
+- **Pinning.** `nodes: [id]` sends a job to a specific member; one pinned job
+  per member runs something everywhere (see `hello_world`).
+- **Retention.** Finished records are kept for 72 hours.
+- **Queued with a reason.** A job no node can take stays queued, and
+  `state.reason` explains why (for example no online node has ffmpeg).
+
+### 12.5 Map/reduce
+
+A job with a `dataset` glob becomes a map/reduce parent. The leader
+coordinates it and never assigns the parent to a node.
+
+1. The glob is expanded over the namespace (`metadata.Glob`: `*` within a
+   folder, `**` across folders, `?` one character).
+2. Files are grouped by the node that already holds a healthy copy and split
+   into partitions of `partitionMax` files (default 50); one **map** child is
+   submitted per partition, so map work runs where the bytes are.
+3. When all map children succeed, emitted pairs are grouped by key and a
+   single **reduce** child is submitted; its output becomes the parent's.
+4. A failed child fails the parent and cancels the rest. A dataset with an
+   unreachable file fails and names it; an empty dataset succeeds with an
+   empty result. Grouped map output is capped at **8 MB**.
+
+```javascript
+function mapper(files, emit) {        // files = paths of this partition
+    files.forEach(function (f) { emit(f.split(".").pop(), 1); });
+}
+function reducer(key, values) {       // called once per key
+    return values.length;
+}
+```
+
+Mapper paths are namespace paths such as `/photos/a.jpg`; prefix them with
+`cluster:` to open them with `filelib`. Children inherit the parent's `nodes`
+restriction.
+
+---
+
+## 13. Scheduling
+
+Three layers must answer "which node?": the job scheduler, write placement
+and the replication planner. They all call one scorer in `scheduling/`, which
+scores each candidate from 0 to 1:
+
+| Factor | Default weight | Measured as |
+|---|---|---|
+| data locality | 0.45 | share of the input bytes already on the node |
+| free CPU | 0.20 | `1 - cpuUsage` from the health report |
+| free memory | 0.10 | `1 - ramUsed / ramTotal` |
+| free disk | 0.05 | largest free fraction among the node's volumes |
+| queue depth | 0.10 | penalty, saturating at 8 queued items |
+| network distance | 0.05 | penalty from heartbeat RTT, saturating at 1000 ms |
+| health | 0.05 | penalty when `DEGRADED` |
+| wanted features | 0.10 | optional capabilities a job prefers |
+| site diversity | 0.05 | distance of a new copy from existing copies |
+
+- **Weights** are one replicated setting (`scheduling.weights`), each 0 to 1,
+  edited on the Cluster Settings page or through `sched/weights`
+  (`reset=true` restores defaults). Missing weights read back as the shipped
+  defaults, so old records stay valid.
+- **Eligibility.** The caller supplies the hard rule (capability match,
+  usable state, a volume with room). The scorer holds `DEGRADED` nodes back
+  whenever a healthy eligible node exists, sorts ineligible nodes last and
+  keeps their reason, so an empty result is explained rather than silent.
+- **Latency** is the heartbeat round trip smoothed with an EWMA (alpha 0.3);
+  the local node reports 0 and a never-heard peer reports -1.
+- **Site diversity** is only computed with three or more nodes and more than
+  one possible target. The planner pulls each member's latency vector over
+  `GET /cluster/acn/latency` and caches the matrix for two minutes; a
+  candidate's diversity is its distance to the nearest existing copy, as a
+  fraction of one second.
+- **Explanations.** Every score carries its factors;
+  `/system/cluster/sched/explain?job=<id>` re-runs the ranking for a job and
+  returns every candidate with its factors and reasons.
+
+---
+
+## 14. Developer interfaces
+
+### 14.1 AGI `cluster` library
+
+Load with `requirelib("cluster")`. File access on `cluster:/` needs no
+special library: `filelib` and every other library see the mounted drive.
+
+| Function | Returns | Notes |
+|---|---|---|
+| `cluster.inCluster()` | bool | |
+| `cluster.self()` | object | this node: id, name, state, capabilities, health |
+| `cluster.nodes()` | array | every member with state, platform, load |
+| `cluster.status()` | object | cluster info, identity origin, leader, volumes, storage, replication |
+| `cluster.stat(path)` | object | record with size, checksum, `locations[]`; needs read permission |
+| `cluster.list(path)` | array | records of a directory's children |
+| `cluster.setReplicas(path, n)` | bool | admin; 0 to 16, 0 = folder policy |
+| `cluster.policy(folder, n)` | bool | admin; top-level folder such as `/photos` |
+| `cluster.on(types, scriptVpath)` | string | hook id; string or array, `file.*` wildcards |
+| `cluster.off(hookId)` / `cluster.hooks()` | bool / array | |
+| `cluster.emit(type, data)` | bool | `app.` prefix added; payload under 64 KB |
+| `cluster.jobs.submit(spec)` | string | job id |
+| `cluster.jobs.mapreduce(spec)` | string | `{name, script, dataset, partitionMax, features, timeout}` |
+| `cluster.jobs.status(id)` | object | `{spec, state}` |
+| `cluster.jobs.list()` | array | own jobs |
+| `cluster.jobs.cancel(id)` | bool | |
+| `cluster.jobs.wait(id, timeoutSec)` | object | blocks in Go; throws if not finished in time |
+
+Users see and cancel only their own jobs; administrators see all.
+
+### 14.2 HTTP endpoints for browsers
+
+All go through the permission router (`prout.NewModuleRouter`):
+
+- **Admin only** (`System Setting` module, admin): `/system/cluster/*`
+  status, create, join, leave, tokens, nodes, identity, metadata, storage,
+  replication and scheduling. See Appendix A.
+- **Logged-in users** (`Tasks Scheduler` module permission):
+  `/system/cluster/jobs/{submit,status,get,cancel}`.
+- **Logged-in users**: `/system/cluster/events/ws` (WebSocket) and
+  `/system/cluster/events/hooks`.
+
+### 14.3 Go building blocks
+
+| Need | Use |
+|---|---|
+| Signed request to a member | `clusterManager.Transport().DoJSON(ctx, nodeID, method, path, in, out)` |
+| New signed node endpoint | `clusterManager.Server().HandleFunc(acn.BasePath+"/x", func(w, r, sender *acn.SignedIdentity, body []byte))` |
+| Members and their state | `clusterManager.NodeViews()` (`State`, `Local`, `Capabilities`, `Health`, `LatencyMs`, ...) |
+| Own IDs | `clusterManager.NodeID()`, `Cluster()`, `InCluster()` |
+| Cluster-scoped storage | `clusterManager.DB()` (`system/cluster.db`) + `membership.RegisterClusterTable(name)` |
+| React to setting changes | chain `OnClusterChange` / `OnMembershipChange` (keep the previous callback) |
+| Namespace | `clusterMetadata.Submit`, `Stat`, `ListDir`, `Glob`, `Volumes`, `PolicyFor`, `IsLeader` |
+| Placement | `clusterScheduling` (`Rank`, `Best`) |
+| Capabilities | `capability.Manifest.Satisfies(capability.Requirements)`, `capability.DiskUsage(path)` |
+| Cross-node user | `clusterIdentity.Issue`, `Attach`, `FromRequest` |
+| Events | `clusterEvents.Publish(events.Event{...})` |
+| Master-only nightly work | `nightly.TaskOption{MasterNodeOnly: true}` |
+
+---
+
+## 15. Worked examples
+
+The folder `examples/clusters_jobs/` contains three runnable pairs. Each has
+a **launcher** (`<name>.agi`, run like any AGI script, for example from the
+Serverless tool, Code Studio or `/system/ajgi/interface?script=<path>`) and a
+**job** (`<name>.job.agi`, captured at submit time). Keep both files in the
+same folder: the launcher refers to its job by a relative path.
+
+| Example | Shows |
+|---|---|
+| `hello_world/` | one job pinned to every usable node with `nodes`; each replies with its name, platform, capabilities and health |
+| `list_files/` | one job walks `cluster:/` with `filelib` and totals files per extension |
+| `ffmpeg_convert/` | converts `cluster:/demo.mp4` to WebM on a node with `ffmpeg`, preferring one that already holds the video |
+
+### 15.1 Run on every node (launcher)
+
+```javascript
+requirelib("cluster");
+
+var nodes = cluster.nodes(), ids = [];
+for (var i = 0; i < nodes.length; i++) {
+    var n = nodes[i];
+    if (n.state !== "ONLINE" && n.state !== "DEGRADED") continue;
+    ids.push(cluster.jobs.submit({
+        name: "Hello World on " + n.name,
+        script: "hello_world.job.agi",
+        nodes: [n.id],             // this node and nowhere else
+        timeout: 60
+    }));
+}
+var replies = [];
+for (var j = 0; j < ids.length; j++) {
+    var rec;
+    try { rec = cluster.jobs.wait(ids[j], 60); }
+    catch (e) { rec = cluster.jobs.status(ids[j]); }
+    if (rec.state.status === "succeeded") replies.push(rec.state.output);
+}
+sendJSONResp(JSON.stringify(replies));
+```
+
+### 15.2 The matching job
+
+```javascript
+requirelib("cluster");
+
+function run(job) {
+    var me = cluster.self();
+    job.log("Hello World from " + me.name);
+    return {
+        message: "Hello World from " + me.name,
+        os: me.capabilities.os,
+        arch: me.capabilities.arch,
+        cpuUsage: me.health.cpuUsage,
+        runAs: job.owner
+    };
+}
+```
+
+### 15.3 Capability and locality (ffmpeg)
+
+```javascript
+requirelib("cluster");
+var id = cluster.jobs.submit({
+    name: "Convert demo.mp4 to WEBM",
+    script: "ffmpeg_convert.job.agi",
+    args: { input: "cluster:/demo.mp4", output: "cluster:/demo.webm" },
+    inputs: ["cluster:/demo.mp4"],  // prefer a node holding the video
+    features: ["ffmpeg"],           // only nodes with ffmpeg
+    timeout: 3600
+});
+```
+
+```javascript
+requirelib("filelib");
+function run(job) {
+    if (!requirelib("ffmpeg")) throw new Error("no ffmpeg on this node");
+    job.progress(0.05);
+    if (!ffmpeg.convert(job.args.input, job.args.output)) {
+        throw new Error("conversion failed");
+    }
+    job.progress(1);
+    return { output: job.args.output,
+             bytes: filelib.filesize(job.args.output),
+             node: job.node };
+}
+```
+
+### 15.4 Map/reduce: count files per extension
+
+```javascript
+requirelib("cluster");
+var id = cluster.jobs.mapreduce({
+    name: "Extensions in /photos",
+    script: "user:/jobs/ext_count.agi",
+    dataset: "/photos/**",
+    partitionMax: 100
+});
+var rec = cluster.jobs.wait(id, 600);
+sendJSONResp(JSON.stringify(rec.state.output));  // {"jpg": 812, ...}
+```
+
+```javascript
+// user:/jobs/ext_count.agi
+function mapper(files, emit) {
+    files.forEach(function (f) { emit(f.split(".").pop(), 1); });
+}
+function reducer(key, values) { return values.length; }
+```
+
+### 15.5 React to new files (event hook)
+
+```javascript
+requirelib("cluster");
+var hookId = cluster.on(["file.created"], "user:/hooks/on_new_file.agi");
+```
+
+```javascript
+// user:/hooks/on_new_file.agi
+requirelib("cluster");
+var ev = JSON.parse(postPara("event"));  // {id, type, node, path, ...}
+if (ev.path.match(/\.jpg$/i)) {
+    cluster.emit("photos.uploaded", { path: ev.path });  // -> app.photos...
+}
+```
+
+### 15.6 Inspect copies and set replicas
+
+```javascript
+requirelib("cluster");
+var rec = cluster.stat("cluster:/photos/a.jpg");
+var where = rec.locations.map(function (l) {
+    return l.nodeId + " (" + l.state + ")";
+});
+cluster.policy("/photos", 2);                 // admin: 2 copies for /photos
+cluster.setReplicas("cluster:/photos/a.jpg", 3); // admin: this file, 3
+sendResp(where.join(", "));
+```
+
+### 15.7 Submitting over HTTP
+
+```bash
+curl -b cookies.txt -X POST \
+  https://node-a.example.com/system/cluster/jobs/submit \
+  -d script=user:/jobs/hello.job.agi -d name=Hello \
+  -d features=ffmpeg -d timeout=600 -d 'args={"x":1}'
+```
+
+List fields (`inputs`, `features`, `nodes`) accept a comma-separated list;
+`inputs` also accepts a JSON array.
+
+---
+
+## 16. Minimum dependencies and requirements
+
+### 16.1 Software
+
+| Requirement | Detail |
+|---|---|
+| ArozOS binary | This branch or later on **every** member; the cluster is built in. No separate service, database or agent is installed. |
+| Build toolchain | Go 1.25 (`go.mod`); `CGO_ENABLED=0` builds are supported. |
+| Go modules used by the cluster | `github.com/gorilla/websocket` (BSD-2), `github.com/satori/go.uuid` (MIT), `github.com/boltdb/bolt` (MIT, through `mod/database`), `golang.org/x/sys` (BSD-3), `github.com/robertkrimen/otto` (MIT, AGI) and the Go standard library (Ed25519, SHA-256). All already in ArozOS; the cluster added no new module. |
+| External tools | **None required.** `ffmpeg`, `docker`, `nvidia-smi`, `git`, `python3`, `node` only advertise optional capabilities that jobs may ask for. |
+| Platforms | Every ArozOS target: Linux amd64/386/arm/arm64/mipsle/riscv64, macOS, Windows. Syscalls are build-tagged (`capability/diskusage_*.go`). |
+
+### 16.2 Cluster topology
+
+| Requirement | Detail |
+|---|---|
+| Minimum members | **1** to create a cluster (and mount `cluster:/` once it has a volume); **2** for replication and failover; **3** for the site-diversity factor. |
+| At least one reachable member | A member with an advertised URL must exist to issue join tokens and host tunnels. Other members may be NAT-only. |
+| Unique node IDs | Each host needs its own `system/dev.uuid` (or `-uuid`). |
+| Clock synchronisation | Clocks within **plus or minus 5 minutes** (signature window and assertion lifetime). Use NTP. |
+| Network | HTTP(S) to the normal ArozOS port. No extra ports, multicast or VPN. WebSockets must pass through any proxy for tunnels. Cloudflare is supported. |
+| At least one volume | Required before `cluster:/` appears. |
+| Accounts | For jobs, the owner must exist on the executing node: configure an identity origin, or create accounts manually. Create the **same permission groups** on every node. |
+| Disk | Room for the contributed volume plus the spool (`-tmp` folder) for files in transit; a volume is read-only below 5 % free. |
+| HTTPS | Strongly recommended in production: the account directory carries password hashes. |
+
+### 16.3 Enabling and disabling
+
+The cluster agent is available by default. Start with `-disable_cluster` to
+turn it off completely: no agent, no `cluster:/`, no cluster tabs, and
+`/cluster/acn/*` answers 404. The older mDNS Neighbourhood page is separate
+and governed by `-allow_mdns`. Relevant flags: `-uuid`, `-hostname`,
+`-port`, `-tmp`, `-disable_cluster`.
+
+---
+
+## 17. Limits and maximum capabilities
+
+| Area | Limit | Value |
+|---|---|---|
+| Cluster size | no hard cap; full-mesh heartbeats every 15 s make traffic grow with the square of the node count | designed for small clusters (households, labs, small offices) |
+| Replicas | per folder policy | 1 to 16 |
+| Replicas | per file | 0 to 16 (0 = policy) |
+| File size | no fixed maximum; bound by the target volume | transferred in 4 MiB chunks |
+| Chunk | default / maximum | 4 MiB / 8 MiB |
+| Upload session | idle expiry | 30 minutes |
+| Signed request body | maximum | 64 MB |
+| Tunnel frame | maximum | 16 MB |
+| Clock skew | tolerated | plus or minus 5 minutes |
+| Jobs per node | concurrent | `runtime.NumCPU()` |
+| Job timeout | default | 3600 s |
+| Job attempts | default | 3 |
+| Job log | kept | last 200 lines |
+| Job records | retention after finishing | 72 hours |
+| Map/reduce | partition size default | 50 files |
+| Map/reduce | grouped map output | 8 MB |
+| Scheduling pass | interval | 3 s |
+| Replication | tasks in flight | 4 per node, 16 total |
+| Replication | retries | 5, then pause 1 hour |
+| Verification | nightly budget | 1 GB per node |
+| Custom event payload | maximum | 64 KB |
+| Hook scripts | concurrent per node | 4 |
+| Join token | default lifetime | 24 hours |
+| User assertion | lifetime | 5 minutes |
+
+**What a cluster can do at its best:**
+
+- Present one `cluster:/` namespace, readable and writable from every member
+  and every app, with files transparently fetched from whichever node holds
+  them.
+- Keep up to 16 verified copies of each file on distinct nodes, repair and
+  re-verify them automatically, spread second copies across sites, and move
+  data off retiring disks without downtime.
+- Survive the loss of any node, including the leader and the identity
+  origin, with two-node failover and no quorum.
+- Run AGI jobs on any architecture, placed by capability, data locality and
+  load, with progress, logs, cancellation, retries and explanations; run a
+  job on every node at once; and run map/reduce where the data lives.
+- Connect nodes across the Internet, behind NAT or Cloudflare, over the
+  normal HTTPS port.
+
+---
+
+## 18. Security model
+
+| Concern | Mechanism |
+|---|---|
+| Node authentication | Ed25519 signature over method, target, cluster, node, timestamp, nonce and body hash |
+| Replay | per-request nonce, spent only after full verification; 5-minute clock window |
+| Cross-cluster confusion | `X-Aroz-Cluster` must match |
+| Relayed requests | signature covers the original path; both relay and target verify |
+| Joining | one-time secret in the token, stored as SHA-256, expiring and revocable |
+| Passwords | only SHA-512 hashes are forwarded; constant-time comparison at the origin |
+| Acting for a user across nodes | signed, short-lived `X-Aroz-User` assertions |
+| Browser endpoints | permission router; admin-only for cluster control |
+| Jobs | run as the owner through the AGI sandbox, with the owner's permissions on the executing node |
+| Data integrity | per-chunk and whole-file SHA-256, verified copies, nightly re-checksums |
+| State isolation | `system/cluster.db`, never `ao.db`; cluster tables wiped on leave |
+
+Operational advice: run members behind HTTPS; protect `system/cluster/node.key`
+like a private key; revoke unused join tokens; keep clocks synchronised; and
+do not clone a system folder without deleting `dev.uuid` and `cluster/`.
+
+---
+
+## 19. Operations and administration
+
+Three System Settings tabs in the **Cluster** group (localized in en-us,
+zh-tw, zh-hk, zh-cn, ja-jp, ko-kr):
+
+| Tab | Page | Contents |
+|---|---|---|
+| Cluster Settings | `SystemAO/cluster/cluster.html` | node name and URL, create/join/leave, join tokens, identity origin, volumes and the nearly-full toggle, replica policies, maintenance and draining, scheduling weights |
+| Cluster Info | `SystemAO/cluster/clusterinfo.html` | reachability, platform, health, cluster summary, namespace state, node table with probes, replication tools, score preview, latency matrix, job explainer |
+| Cluster Jobs | `SystemAO/cluster/jobs.html` | submit, follow and cancel jobs (users see their own) |
+
+**Typical setup**
+
+1. On node A (reachable URL): Cluster Settings > set the advertised URL >
+   Create cluster.
+2. Add a volume, for example `user:/cluster`. `cluster:/` now appears.
+3. Generate a join token, paste it on node B (and C, ...).
+4. Choose an identity origin and create the same permission groups on each
+   node.
+5. Set replica policies, for example `/photos` = 2.
+6. Watch Cluster Info for node states, replication health and scores.
+
+**Maintenance**
+
+- Set a node to `MAINTENANCE` before rebooting it, or `DRAINING` to move its
+  copies away while it still serves reads.
+- Evacuate a volume before removing a disk.
+- Use "Verify this node" after suspected disk problems.
+- For a live two-node test on one machine, see TASKS.md section 0.5: two
+  isolated copies of `system/`, separate ports, `-uuid` and `-hostname`,
+  `-allow_mdns=false -allow_ssdp=false`.
+
+---
+
+## 20. Developer guide: extending the cluster
+
+### 20.1 Repository rules that apply
+
+1. Log only through `logger.PrintAndLog("Cluster", message, err)`.
+2. Every package under `src/mod/` ships tests; new exported functions are
+   covered (table-driven, `t.TempDir()`, `t.Fatalf`).
+3. New dependencies must be MIT, BSD, Apache-2.0, MPL-2.0 or ISC.
+4. Browser endpoints go through `prout.NewModuleRouter`; node-to-node
+   endpoints through `acn.Server.HandleFunc` (signed, mounted under
+   `/cluster/acn/`).
+5. Stay portable: no hardcoded OS paths, no `exec.Command` in shared code,
+   build tags for OS-specific code.
+6. No emoji in code or UI; use Semantic UI icons or SVG.
+7. Add user-facing strings and server messages to
+   `src/web/SystemAO/locale/cluster.json` (`CL.t` for labels, `CL.tr` for
+   server messages via `msg/<text>` and `msgp/<template>` entries).
+
+### 20.2 Adding a replicated feature
+
+1. Pick a record kind: reuse `metadata.KindSetting` for configuration, or add
+   a kind with a `Version` field that merges last-writer-wins.
+2. Write with `Submit(kind, record)`; never write the disk directly under a
+   lock.
+3. Serialise decisions on the leader (`IsLeader()`); make tasks ephemeral so
+   a new leader can re-plan.
+4. Use `scheduling` for any "which node" choice so weights and explanations
+   stay consistent.
+5. Publish events for anything scripts may want to react to.
+6. Register any new table with `membership.RegisterClusterTable`.
+
+### 20.3 Testing multi-node logic
+
+Follow `identity/identity_test.go`: create N `membership.NewManager` instances
+with `t.TempDir()` databases, serve each with
+`httptest.NewServer(m.ACNHandler())`, set URLs with `m.UpdateConfig`, create a
+cluster on one, `NewJoinToken` + `JoinCluster` the others, and poll with
+`waitFor(...)` (5 s deadline); never sleep fixed durations. Timing constants
+are variables so tests can shorten them in `init()`. Close managers in
+`t.Cleanup`.
+
+```bash
+cd src
+go build ./... && go vet ./mod/cluster/...
+go test -timeout 300s -count=3 ./mod/cluster/...
+sh ../scripts/check-conventions.sh --diff origin/master
+```
+
+---
+
+## 21. Known constraints and pitfalls
+
+- **No `-race` for Bolt-backed packages.** `boltdb/bolt` panics under
+  checkptr; only `acn` can run with `-race`.
+- **Two ArozOS instances cannot share `src/`** (Bolt lock on `ao.db`).
+- **Page scripts must not declare `var status`**: it shadows `window.status`.
+  Use names such as `clusterStatus`.
+- **`go mod tidy` pulls in modules imported by user files** under
+  `src/files/`; revert unrelated `go.mod` additions.
+- **CRLF files.** If an edit produces a whole-file diff, normalise with
+  `sed -i 's/\r$//' <file>`.
+- **Windows temp-dir cleanup** fails if a test leaves a Bolt DB open.
+- **Relative paths in jobs** do not resolve; use `cluster:/` or `user:/`.
+- **Groups are per node.** A mirrored account only gets groups that exist on
+  that node.
+- **Eventual consistency.** Two writers of the same path on different nodes
+  resolve last-writer-wins; applications needing stronger guarantees should
+  coordinate through a job or the leader.
+- **Map output lives in the job record**, so keep emitted values small
+  (8 MB cap).
+
+---
+
+## 22. Appendix A: endpoint reference
+
+### A.1 Signed node-to-node endpoints (`/cluster/acn/...`)
+
+| Group | Endpoints |
+|---|---|
+| Transport | `GET hello` (unsigned probe), `POST ping`, `GET tunnel`, `* relay/{node}/...`, `GET latency` |
+| Membership | `POST join` (join token), `POST heartbeat`, `GET members`, `POST members/sync`, `POST leave`, `POST evict` |
+| Identity | `POST auth/verify`, `GET auth/directory`, `POST auth/setpassword` |
+| Metadata | `meta/lease`, `meta/append`, `meta/submit`, `meta/log`, `meta/snapshot`, `meta/stat` |
+| Storage | `store/place`, `store/begin`, `store/chunk`, `store/commit`, `store/abort`, `store/read`, `store/stat`, `store/list`, `store/checksum`, `store/mkdir`, `store/rename`, `store/delete` |
+| Replication | `repl/pull`, `repl/lease`, `repl/done`, `repl/plan` |
+| Events | `events/publish` |
+| Jobs | `jobs/run`, `jobs/done`, `jobs/submit` |
+
+### A.2 Browser endpoints (`/system/cluster/...`)
+
+| Group | Endpoints | Access |
+|---|---|---|
+| Agent | `status`, `create`, `join`, `leave`, `config`, `testurl`, `nodes`, `capabilities`, `node/remove`, `node/state`, `node/probe` | admin |
+| Tokens | `token/new`, `token/list`, `token/revoke` | admin |
+| Identity | `identity/status`, `identity/origin`, `identity/sync` | admin |
+| Metadata | `meta/status`, `meta/ls`, `meta/stat`, `meta/policy/list`, `meta/policy/set` | admin |
+| Storage | `storage/status`, `storage/volume/add`, `storage/volume/remove`, `storage/volume/readonly`, `storage/volume/evacuate`, `storage/volume/evacuate/cancel`, `storage/volume/evacuate/status`, `storage/rescan`, `storage/autoreadonly` | admin |
+| Replication | `repl/status`, `repl/plan`, `repl/verify` | admin |
+| Scheduling | `sched/status`, `sched/weights`, `sched/explain?job=<id>` | admin |
+| Jobs | `jobs/submit`, `jobs/status`, `jobs/get`, `jobs/cancel` | user (own jobs) |
+| Events | `events/ws`, `events/hooks` | user |
+| Neighbourhood (mDNS) | `scan`, `record`, `wol` | user, only with `-allow_mdns` |
+
+---
+
+## 23. Appendix B: tunables and constants
+
+| Constant | Value | Package |
+|---|---|---|
+| `HeartbeatInterval` | 15 s | membership |
+| `OnlineWindow` / `OfflineWindow` | 45 s / 3 min | membership |
+| `TombstoneTTL` | 7 days | membership |
+| `LatencyMatrixTTL` | 2 min | membership |
+| `MaxClockSkew` | 5 min | acn |
+| `MaxSignedBody` | 64 MB | acn |
+| `TunnelPingInterval` / `TunnelReadTimeout` | 30 s / 90 s | acn |
+| `TunnelMaxFrame` | 16 MB | acn |
+| `DefaultRequestTimeout` | 60 s | acn |
+| `DefaultAssertionTTL` | 5 min | identity |
+| `DefaultSyncInterval` | 5 min | identity |
+| Leader lease / renew | 30 s / 10 s | metadata |
+| `FlushInterval` | 50 ms | metadata |
+| `ChunkSize` / `MaxChunkSize` | 4 MiB / 8 MiB | storage |
+| `SessionTTL` | 30 min | storage |
+| Refresh / reconcile | 60 s / 30 min | storage |
+| Low-space guard | 5 % on, 7 % off | storage |
+| Plan interval | 60 s | replication |
+| In flight per node / total / workers | 4 / 16 / 4 | replication |
+| Max attempts | 5 | replication |
+| Offline-to-stale | 10 min | replication |
+| Schedule interval | 3 s | jobs |
+| Task lease / renew | 30 s / 10 s | jobs |
+| Max parallel | NumCPU | jobs |
+| Retention | 72 h | jobs |
+| Default timeout / attempts | 3600 s / 3 | jobs |
+| Log lines | 200 | jobs |
+| Batch interval / dedup window | 200 ms / 10 min | events |
+| Concurrent hook runs | 4 | events |
+
+---
+
+## 24. Appendix C: glossary
+
+| Term | Meaning |
+|---|---|
+| Node | one ArozOS installation |
+| Member | a node that is in the cluster |
+| Leader / master node | the member holding the metadata lease; serialises placement, replication, scheduling and shared nightly maintenance |
+| Identity origin | the member that owns the account table |
+| Volume | a folder a node contributes to the cluster namespace |
+| Record | one entry in the metadata store |
+| Copy / location | one physical copy of a file on a volume |
+| Policy | desired replica count for a top-level folder |
+| ACN | ArozOS Cluster Node protocol |
+| ACMS | ArozOS Cluster Metadata Store |
+| AID | ArozOS Identity |
+| AGI | ArOZ Online JavaScript Gateway Interface (the server-side JavaScript runtime) |
+| Tunnel | a WebSocket a NAT-only node keeps open to a reachable member |
+| Relay | forwarding a request to a tunnelled node through its tunnel host |

+ 1327 - 0
docs/ArozOS-Cluster-Whitepaper.pdf

@@ -0,0 +1,1327 @@
+ArozOS Cluster
+Technical White Paper
+
+Many independent ArozOS nodes presented as one logical computer
+
+Applies to  ArozOS v3.0.4 branch, cluster Phases 1 to 9
+Audience
+Sources     Developers, integrators and administrators
+
+Date        src/mod/cluster/README.md, TASKS.md, the Go
+            packages under src/mod/cluster/,
+            examples/clusters_jobs/
+
+            2026-09-21
+
+ArozOS is free software released under the GNU General Public License v3. The Markdown source of this document is docs/ArozOS-
+Cluster-Whitepaper.md.
+Contents
+
+  1. Executive summary
+  2. Design goals and non-goals
+  3. Architecture overview
+  4. Identifiers and addressing
+  5. ACN: the node-to-node protocol
+  6. Membership, joining and node states
+  7. Identity (single sign-on across nodes)
+  8. The metadata store (ACMS)
+  9. Storage and the cluster:/ drive
+10. Replication
+11. The event bus
+12. Jobs, map/reduce and the job contract
+13. Scheduling
+14. Developer interfaces: AGI, HTTP and Go
+15. Worked examples
+16. Minimum dependencies and requirements
+17. Limits and maximum capabilities
+18. Security model
+19. Operations and administration
+20. Developer guide: extending the cluster
+21. Known constraints and pitfalls
+22. Appendix A: endpoint reference
+23. Appendix B: tunables and constants
+24. Appendix C: glossary
+
+ArozOS Cluster Technical White Paper         Page 2 of 33
+1. Executive summary
+
+The ArozOS cluster lets several independent ArozOS installations, which may run on different hardware, operating
+systems and CPU architectures, act as a single logical computer. A cluster provides four unified services:
+
+     One namespace. A cluster:/ drive appears in File Manager, WebDAV, media serving and every AGI library
+     on every member. Files stay whole files inside ordinary folders that nodes contribute; a replicated metadata
+     index says which nodes hold which copies.
+     One identity. A user logs in on any member with the same credentials. Logins are forwarded to an identity
+     origin node, with a replicated account directory as fallback when the origin is unreachable.
+     One compute pool. AGI job scripts are submitted once and run on the best node for them, chosen by
+     capability (for example ffmpeg or nvidia ), data locality and load. Map/reduce spreads work across the nodes
+     that already hold the data.
+     One API. The AGI cluster library, an event bus with script hooks and a WebSocket feed, and admin HTTP
+     endpoints hide node selection, routing, retries and replication from applications.
+
+Every node keeps working as a normal standalone ArozOS when the cluster, or any other member, is unreachable.
+The whole feature ships inside the single ArozOS binary, adds no external service (no etcd, no ZooKeeper, no
+database server), requires no quorum, and works with as few as two nodes, including nodes behind NAT or
+Cloudflare.
+
+ArozOS Cluster Technical White Paper  Page 3 of 33
+2. Design goals and non-goals
+
+2.1 Goals
+
+  1. Heterogeneous nodes. An x86 server, a Raspberry Pi and a Windows workstation must be able to cooperate.
+     Nothing assumes a shared OS, architecture, installed tools or hardware.
+
+  2. Autonomy. A node is always a complete ArozOS. Losing the cluster degrades only the cluster features.
+  3. Whole files. Files are never split into blocks across nodes. Any copy is a normal file that can be read with
+
+     ordinary tools, and the index can always be rebuilt by scanning the real files.
+  4. Small clusters first. Two-node clusters must work, including failover. This rules out majority-quorum
+
+     consensus.
+  5. Internet friendly. Nodes may sit behind NAT, reverse proxies or Cloudflare. All transfers fit within Cloudflare
+
+     request and idle limits.
+  6. A stable application API. Applications use AGI (the ArozOS JavaScript Gateway Interface) and never talk to
+
+     node addresses.
+  7. Portability. Pure Go, no CGO requirement, no platform tools in shared code, build-tagged syscalls.
+
+2.2 Non-goals
+
+     A Hadoop/Ceph-style block file system or erasure coding.
+     Strong linearizable consistency (no Raft or Paxos). Metadata converges last-writer-wins, serialised by a leader
+     lease.
+     Large-scale clusters. Heartbeats are a full mesh; the design targets households, labs and small offices, not
+     hundreds of nodes.
+     Running native binaries as jobs. Jobs are AGI scripts, because node architectures differ; native work is reached
+     through AGI libraries (for example ffmpeg ) on nodes that have the tool.
+
+ArozOS Cluster Technical White Paper  Page 4 of 33
+3. Architecture overview
+
+3.1 Layers
+
++---------------------------------------------------------------+
+
+| Applications: File Manager, WebDAV, Photo, Movie, AGI apps |
+
++---------------------------------------------------------------+
+
+| AGI "cluster" library | cluster:/ drive | /system/cluster |
+
++---------------------------------------------------------------+
+
+| jobs (+ map/reduce) | events | replication | storage |
+
++---------------------------------------------------------------+
+
+|            scheduling (one weighted scorer for all)      |
+
++---------------------------------------------------------------+
+
+| metadata store (ACMS): leader lease + replicated log     |
+
++---------------------------------------------------------------+
+
+| identity (AID)    | membership (agent, gossip, health) |
+
++---------------------------------------------------------------+
+
+| ACN: Ed25519 signed HTTP, direct / tunnel / relay routing |
+
++---------------------------------------------------------------+
+
+| HTTP(S) on the normal ArozOS port, under /cluster/acn/*  |
+
++---------------------------------------------------------------+
+
+3.2 Packages
+
+All cluster code lives under src/mod/cluster/ (module path imuslab.com/arozos ).
+
+Package       Role
+
+acn/          ArozOS Cluster Node protocol: node keys, signed requests, replay protection, routing, WebSocket reverse
+              tunnel
+
+capability/   Portable detection of OS, arch, cores, RAM, tools and CPU flags; requirement matching; cross-platform
+              DiskUsage
+
+membership/   The cluster agent: create, join, leave, gossip of node records, heartbeats, node states, latency, cluster settings,
+              admin endpoints
+
+identity/     Forward authentication to the identity origin, account directory mirror, password write-back, signed user
+              assertions
+
+metadata/     Replicated namespace index (files, copies, volumes, policies, settings, jobs), leader lease, replicated log,
+              snapshots, write-behind persistence
+
+storage/      Contributed volumes, placement, chunked verified transfers, reads and writes for the drive, reconcile, copy
+              primitives
+
+replication/ Leader-side planner and per-node worker keeping every file at its policy's copy count
+
+events/       Publish/subscribe with cluster-wide fan-out and de-duplication, AGI hooks, WebSocket feed
+
+jobs/         Replicated job records, leader-side scheduler, per-node execution, leases, cancellation, map/reduce
+
+scheduling/ The single placement scorer used by jobs, writes and replication
+
+wakeonlan/ Wake-on-LAN packets for offline LAN neighbours
+
+Related code outside the package:     Role
+
+ File                                 Core wiring ( ClusterInit , clusterStartAgent ), drive mount/unmount,
+  src/cluster.go                      AGI provider, event hooks, master-node resolver, shutdown
+
+ArozOS Cluster Technical White Paper                                                                               Page 5 of 33
+File                                  Role
+
+src/cluster.jobs.go                   Job executor adapter to the AGI gateway, job submit handler,
+                                      sched/explain
+
+src/cluster.fsinfo.go                 Cluster tab of the File Manager properties dialog
+
+src/mod/filesystem/abstractions/clusterfs/ The cluster:/ file system abstraction
+
+src/mod/agi/agi.cluster.go            The AGI cluster library
+
+src/main.router.go                    Mounts /cluster/acn/* before the session check
+
+src/web/SystemAO/cluster/             Cluster Settings, Cluster Info and Cluster Jobs pages
+
+src/web/SystemAO/locale/cluster.json  UI and server message translations
+
+examples/clusters_jobs/               Runnable job examples
+
+3.3 Start-up order
+
+ClusterInit (called from src/startup.go ) runs clusterStartAgent unless -disable_cluster is set. Services are
+created in dependency order, and each is optional: if one fails to start, the services below it are skipped and the
+failure is logged under the Cluster title.
+
+membership.NewManager                 (system/cluster.db, system/cluster/node.key)
+
+-> identity.New                       (hooks authAgent.ForwardAuth)
+
+-> metadata.New
+
+      -> scheduling.New
+
+      -> storage.New                  (mounts cluster:/ via clusterSyncDrive)
+
+      -> events.New (file / replica / disk-full events)
+
+      -> jobs.New                     (user routes, "Cluster Jobs" page)
+
+      -> AGI ClusterLibRegister()
+
+      -> replication.New (nightly verify task)
+
+AGI starts before the cluster, so the cluster library is registered late through AGIGateway.ClusterLibRegister()
+once the provider exists. ClusterShutdown closes the services in reverse order so heartbeats and tunnels stop
+cleanly.
+
+ArozOS Cluster Technical White Paper                                                                Page 6 of 33
+4. Identifiers and addressing
+
+Nothing in the cluster is addressed by a name. Names are operator-set and every fresh install is called My ArOZ , so
+two nodes can share a name. Only the IDs below are unique.
+
+Thing          Identifier                                  Origin                                  Unique within
+                                                           CreateCluster , carried in join tokens  everywhere
+Cluster        ClusterInfo.ID (UUID v4)                    system/dev.uuid or the -uuid flag       the cluster
+                                                           system/cluster/node.key                 everywhere
+Node           NodeRecord.ID = device UUID                 -hostname , default My ArOZ             not unique
+                                                           node storage config                     that node only
+Node identity  Ed25519 key pair                            AddVolume                               everywhere
+                                                           AddVolume (duplicates refused)          everywhere
+Node name      NodeRecord.Name                             first write of the path                 the cluster
+                                                           placement / replication                 per file
+Drive on a node FileSystemHandler.UUID ( user , s1 , ...)  job submit                              the cluster
+
+Volume         Volume.ID (UUID v4)
+
+Volume location NodeID + FshUUID + Subpath
+
+File           FileRecord.ID (UUID v4), keyed by Path
+
+Copy           VolumeID (+ NodeID ) in the record
+
+Job            Job.ID (UUID v4)
+
+Because a drive UUID only means something on one node, every physical location the cluster displays is written
+node first:
+
+   <node uuid>:<drive uuid>/<path on that drive>
+   3f7a...c1:user/cluster/photos/a.jpg
+
+Warning: cloned installs. Copying system/dev.uuid to a second host gives both the same node ID and their
+membership records merge into one. Delete system/dev.uuid and system/cluster/ on a clone before it
+joins.
+
+ArozOS Cluster Technical White Paper                                                               Page 7 of 33
+5. ACN: the node-to-node protocol
+
+5.1 Signed requests
+
+Every node owns an Ed25519 key pair ( acn.LoadOrCreateNodeKey ). The public key travels in the node's
+membership record. Every ACN request carries:
+
+X-Aroz-Node:   <sender node UUID>
+
+X-Aroz-Cluster: <cluster UUID>
+
+X-Aroz-Timestamp: <unix seconds>
+
+X-Aroz-Nonce:  <random hex>
+
+X-Aroz-Signature: base64(Ed25519(
+
+               METHOD \n target \n cluster \n node \n
+
+               ts \n nonce \n sha256(body)))
+
+The receiver checks, in order: the sender is a known member, the cluster ID matches, the timestamp is within plus
+or minus 5 minutes, the nonce is unseen, and the signature verifies. Only after all checks pass is the nonce
+recorded, so junk requests cannot poison the replay cache. Signed bodies are capped at 64 MB.
+
+ACN is mounted at /cluster/acn/* in src/main.router.go before the user-session check, because nodes
+authenticate with signatures rather than cookies. cluster is therefore a reserved subservice path.
+
+5.2 Routing
+
+Callers use acn.Transport.Do / DoJSON(ctx, nodeID, method, path, in, out) and never deal with addresses. The
+transport picks the route:
+
+  1. Tunnel: the peer has a live tunnel terminating on this node.
+  2. Direct: the peer advertises a URL (behind Cloudflare is fine).
+  3. Relay: the peer is tunnelled to another member via ; the request goes to
+
+      https://<via>/cluster/acn/relay/<peer>/cluster/acn/<path> and the tunnel host forwards it. The signature
+     covers the original path, so the relay and the final node verify the same signature.
+
+A (public URL)                        B (public URL)  C (behind NAT)
+
+|                                     |               |
+
+|---- direct HTTPS --->|                              |
+
+|                                     |<==== WebSocket ======| C tunnels to B
+
+|-- relay/C/... ------>|==== frame ==========>| A reaches C via B
+
+5.3 Reverse tunnel
+
+A node without a public URL opens one WebSocket to a reachable member ( GET /cluster/acn/tunnel , signed).
+Requests are multiplexed as binary frames [kind][header length][header JSON][body] , executed against the
+node's own ACN handler and answered on the same socket.
+
+     Both ends ping every 30 s (read timeout 90 s), so Cloudflare's 100 s idle limit never trips.
+     The client reconnects with backoff and re-picks a host: the admin's preferred host, otherwise the healthiest
+     reachable member.
+     Frames are capped at 16 MB; file transfers use 4 MiB chunks, well under Cloudflare's 100 MB request limit.
+     A NAT-only node still appears online everywhere, because its tunnel host learns its LastSeen and gossips it.
+
+ArozOS Cluster Technical White Paper                                                                   Page 8 of 33
+6. Membership, joining and node states
+
+6.1 Node records and gossip
+
+Each node owns one NodeRecord (ID, name, public key, advertised URL, tunnel host, version, capabilities, admin
+state) with an Updated version stamp. Records travel with every heartbeat and merge last-writer-wins per record,
+so membership converges without a master.
+
+     A node is authoritative for its own record; others may only change its admin state or remove it.
+     Removed nodes remain as tombstones for 7 days so the removal propagates to members that were offline.
+     Heartbeats go to every peer every 15 s (full mesh).
+     Versions come from nextVersion(prev) , strictly greater than the previous value; one millisecond is not unique,
+     so never compare with >= .
+
+6.2 Computed node states
+
+Liveness is computed locally, not gossiped:
+
+State                                 Meaning
+ONLINE                                heard from within 45 s
+DEGRADED                              online, but CPU or RAM at or above 97 %, or disk at or below 2 % free
+UNKNOWN                               silent for 45 s to 3 min
+OFFLINE                               silent for more than 3 min
+MAINTENANCE / DRAINING                set by an admin, overrides the above
+
+6.3 Capability manifests
+
+Every node publishes a capability.Manifest in its record:
+
+type Manifest struct {
+
+   OS, Arch string                    // runtime.GOOS / GOARCH
+
+   CPUCores int
+
+   TotalRAM int64                     // bytes, 0 when unknown
+
+   Hostname string
+
+   Features map[string]bool
+
+   GoVersion string
+
+   DetectedAt int64
+
+}
+
+Detected features:                                              Detected by
+                                                                executable found on PATH
+ Feature                                                        nvidia-smi found on PATH
+  ffmpeg , ffprobe , docker , git , python3 , node              golang.org/x/sys/cpu (x86)
+  nvidia (and then cuda , gpu )                                 golang.org/x/sys/cpu (ARM64 ASIMD)
+  avx , avx2 , avx512                                           architecture name ends in 64
+  neon
+  64bit
+
+ArozOS Cluster Technical White Paper                                                                         Page 9 of 33
+Jobs express capability.Requirements ( features , minRam , minCores , os , arch ); Manifest.Satisfies returns the
+first unmet requirement as a human-readable reason, which is what a queued job shows.
+
+6.4 Creating and joining
+
+  1. On a member that has an advertised URL, an admin generates a join token in System Settings > Cluster
+     Settings. The token is aroz-join:<base64 JSON> and embeds the cluster ID, the issuer's URL and a secret; only
+     the secret's SHA-256 is stored. Tokens expire (default 24 hours) and can be listed and revoked.
+
+  2. The admin pastes the token on the new node. It POSTs its record to the issuer's /cluster/acn/join , receives
+     the cluster info and member list, and starts heartbeating. A node without a URL tunnels to the issuer
+     immediately.
+
+  3. The issuer pushes the new member list to everyone else.
+
+Leaving ( /system/cluster/leave ) notifies peers, wipes every table registered with
+membership.RegisterClusterTable and unmounts cluster:/ . An admin can also remove a node, which sends it
+/cluster/acn/evict .
+
+ArozOS Cluster Technical White Paper  Page 10 of 33
+7. Identity (single sign-on across nodes)
+
+One member can be made the identity origin (System Settings > Cluster > Identity). The choice is a cluster-wide
+setting replicated by gossip ( ClusterInfo.IdentityOrigin , last-writer-wins on SettingsVersion ).
+
+On every other member the auth agent's ForwardAuth hook runs before the local password table:
+
+  1. Forward auth. The member sends the username and the SHA-512 hash of the typed password to the origin
+     ( POST /cluster/acn/auth/verify , signed). The origin compares in constant time and answers with the user's
+     group names. The clear-text password never leaves the member.
+
+  2. Mirror. On success the member creates or updates the account locally (hash plus the groups that exist on that
+     node, matched by name) and opens a normal local session.
+
+  3. Fallback. If the origin is unreachable, the local table decides. Members pull the origin's directory ( GET
+      /cluster/acn/auth/directory ) at boot, every 5 minutes and when the origin setting changes. If the origin is
+     reachable and says the password is wrong, the login is rejected with no fallback.
+
+  4. Write-back. Password changes of mirrored accounts are forwarded to the origin ( POST
+      /cluster/acn/auth/setpassword ). Core code that changes a password must call
+      clusterNotifyPasswordChanged after writing the hash.
+
+Rules: only mirrored accounts are ever touched; a pre-existing local account with the same name is left alone
+("local only"); accounts whose groups do not exist on a member are skipped and listed. Permission groups are
+node-specific, so create the same groups on every node.
+
+7.1 Signed user assertions
+
+Node A can act on node B for a logged-in user without contacting the origin:
+
+   token = base64url(payload) "." base64url(Ed25519 signature)
+   header = X-Aroz-User: <token>
+
+identity.Issue(username, ttl) creates it (default lifetime 5 minutes), Attach(req, username) sets the header and
+FromRequest(r) verifies it against the issuer's published node key, returning *identity.Assertion{User, Groups,
+Issuer} .
+
+ArozOS Cluster Technical White Paper  Page 11 of 33
+8. The metadata store (ACMS)
+
+The ArozOS Cluster Metadata Store is the replicated index of the namespace. File contents never pass through it.
+
+8.1 Record kinds
+
+Kind Type         Key fields
+
+file  FileRecord ID , Path , IsDir , Size , ModTime , Checksum (SHA-256), Owner , Primary , Locations[] , Replicas ,
+
+                  Removed , Version
+
+volume Volume     ID , NodeID , Name , FshUUID , Subpath , Capacity , Free , ReadOnly , Evacuating , LowSpace ,
+                  Removed
+
+policy Policy     Folder (top level, e.g. /photos ), Replicas
+
+setting Setting   Key (e.g. scheduling.weights ), Value (JSON)
+
+job   Job         ID , Owner , Node , Status , Body (full job record)
+
+A copy of a file is a Location{VolumeID, NodeID, State, Checksum, Updated} with a state of pending , writing ,
+committed , verified , stale or failed . A copy is healthy when committed or verified .
+
+8.2 Consistency model
+
+Every record carries a Version from membership.NextVersion and merges last-writer-wins on every node. There is
+deliberately no Raft: the store converges without a majority, and correctness can always be restored by rescanning
+the real files (storage reconcile).
+
+     Leader lease ( lease.go ). The eligible member that joined first (ties by ID) claims a 30 s lease with a higher
+     term when no live lease exists and renews it every 10 s. Every member accepts a lease with a higher term. No
+     quorum is needed, so a two-node cluster fails over. IsLeader() / Leader() serialise decisions: placement,
+     replication planning and job scheduling.
+     Replicated log ( log.go ). Submit(kind, record) applies locally at once; the leader assigns a sequence number
+     and pushes the entry to online peers ( meta/append ). Followers submit through the leader ( meta/submit ) or
+     queue in meta_pending until one is reachable. Gaps are filled with meta/log?after=N ; a compacted range, a
+     new term or a fresh follower ( applied == 0 ) triggers a full meta/snapshot .
+     Write-behind persistence ( persist.go ). Reads come from memory. A change updates memory under the
+     store lock and queues a disk write; writes are coalesced per key and committed in one database.WriteBatch
+     transaction every 50 ms. A crash loses at most one flush interval of this node's disk copy, which catch-up
+     restores like any other gap.
+
+Rule. Never add a synchronous disk write inside the store lock. A write burst would starve lease renewal and
+the leader would lose its lease.
+
+Read API: Stat , ListDir , Glob , Volumes , PolicyFor . Write API: Submit(kind, record) . New tables go through
+membership.RegisterClusterTable so they are wiped on leave.
+
+ArozOS Cluster Technical White Paper                                   Page 12 of 33
+9. Storage and the cluster:/ drive
+
+9.1 Volumes
+
+An admin contributes a folder of a local drive as a volume ( storage/volume/add , e.g. user:/cluster ). Files in the
+namespace are ordinary files inside those folders. A rescan ( storage/rescan , and automatically every 30 minutes)
+adopts files placed there by other means and flags copies that vanished or changed as stale . Volume capacity
+and free space are refreshed every 60 s.
+
+9.2 The drive
+
+When a node is in a cluster and the cluster has at least one volume, the core mounts a Cluster drive
+( cluster:/ , public hierarchy, buffered) into the base storage pool ( clusterSyncDrive in src/cluster.go , re-
+checked on every membership change and volume record change). File Manager, WebDAV, media serving and AGI
+filelib then use it like any other drive. Without a cluster or a volume the drive is unmounted, so nightly tasks
+and scanners do not see it.
+
+9.3 Write path
+
+   client write
+       -> spool locally while hashing (SHA-256)
+       -> ask leader for placement (scheduling scorer; local volume first,
+            then existing primary, then most free space)
+       -> copy bytes: local rename-in-place, or chunked upload to the target
+       -> publish FileRecord with a committed Location
+
+The namespace never shows a half-written file: the record is published only after the bytes are in place. Replication
+then brings the file up to its policy's copy count.
+
+9.4 Read path
+
+A read opens a local healthy copy when there is one; otherwise it streams from an online node through the
+chunked protocol while verifying the checksum.
+
+9.5 Chunked transfer protocol                Purpose
+                                             ask the leader where a new file should go
+ Endpoint                                    open an upload session (resumable)
+  store/place                                one signed chunk, per-chunk SHA-256
+  store/begin                                whole-file SHA-256 check, rename .part-<session> into place
+  store/chunk                                discard a session
+  store/commit                               ranged, chunked read
+  store/abort                                inspect copies
+  store/read                                 namespace operations on a volume
+  store/stat , store/list , store/checksum
+  store/mkdir , store/rename , store/delete
+
+Chunks are 4 MiB (maximum 8 MiB) and sessions expire after 30 minutes of inactivity.
+
+ArozOS Cluster Technical White Paper                                                  Page 13 of 33
+9.6 Space guard and maintenance
+
+     Nearly full volumes. Below 5 % free a volume becomes read only and LowSpace , stops taking new files and
+     emits a node.diskfull event; it recovers above 7 %. The cluster setting storage.autoReadOnly (Cluster
+     Settings > Storage) turns this off. Read-only set by an admin is never touched by the guard.
+     Nightly maintenance on the master node only. Every member sees the same files on cluster:/ , so trash
+     expiry and version-history cleanup of a shared drive run only on the master node (the metadata leader):
+     register such tasks with nightly.TaskOption{MasterNodeOnly: true} ; nightlyShouldMaintainFsh answers per
+     file system handler. A standalone host is its own master, so nothing changes for a single node.
+     Where is my file? The abstraction implements arozfs.StorageInfoProvider , so the File Manager properties
+     dialog shows a Cluster tab with every copy, its node and volume (node-first path), state, replica policy and
+     checksum ( /system/file_system/getStorageInfo -> src/cluster.fsinfo.go ).
+
+ArozOS Cluster Technical White Paper  Page 14 of 33
+10. Replication
+
+The replication manager keeps every file at the copy count its folder policy (or the record's own Replicas ) asks
+for, on different nodes.
+
+10.1 Planner (metadata leader, every 60 s and on demand)
+
+Situation                                   Action
+fewer healthy copies than wanted            one pull task to a node without a copy; an existing stale copy is repaired in
+                                            place
+more copies than wanted                     drop the copy on the fullest non-primary volume, only when the rest are
+                                            healthy
+copy on an evacuating volume or a DRAINING  re-create elsewhere, then drop
+node
+node OFFLINE for more than 10 minutes       mark its healthy copies stale (never deleted; reconcile restores them when
+                                            it returns)
+
+Limits: 4 tasks in flight per node, 16 in total, 4 workers per node. A file that fails backs off exponentially and is left
+alone for an hour after 5 attempts. Tasks are ephemeral (in memory with a 50-entry history): a new leader simply
+plans again within one interval.
+
+10.2 Worker
+
+The target node pulls the bytes with the chunked protocol ( storage.Service.PullCopy ), verifies the checksum,
+publishes a verified location and reports to the leader, renewing a 30 s task lease every 10 s.
+
+10.3 Verification and evacuation
+
+     A nightly pass re-checksums up to 1 GB of this node's copies, least recently checked first, and downgrades
+     mismatches to stale . "Verify this node" runs it on demand ( repl/verify ).
+      storage/volume/evacuate marks a volume read only; the planner moves everything off it and the volume is
+     retired when nothing references it. volume/remove refuses a volume that holds the only copy of a file.
+
+Replica counts range from 1 to 16 (policy) and 0 to 16 per file, where 0 means "use the folder policy".
+
+ArozOS Cluster Technical White Paper                      Page 15 of 33
+11. The event bus
+
+events.Bus provides publish/subscribe with cluster-wide fan-out ( /cluster/acn/events/publish , batched every
+200 ms) and de-duplication by event ID over a 10-minute window.
+
+   type Event struct {
+          ID, Type, Node, Path, FileID, User string
+          Time int64
+          Data json.RawMessage
+
+   }
+
+Event type                                  Raised when
+file.created , file.removed , file.renamed  the storage layer writes, removes or renames a file ( renamed carries
+                                            {"from": ...} )
+replica.verified , replica.stale            a copy is verified or downgraded ( {"volume": ...} )
+node.joined , node.left , node.online ,     computed locally by every node from membership
+node.offline
+node.diskfull                               a volume crosses the 5 % free guard
+job.completed , job.failed                  a job reaches a terminal state
+app.*                                       custom events from cluster.emit (payload under 64 KB)
+
+Consumers:
+
+     AGI hooks. cluster.on(types, scriptVpath) registers a persistent hook (table event_hooks ) that runs the
+     script as its owner, with at most 4 hook runs at a time per node. The script reads the event with
+      postPara("event") (JSON). Types accept wildcards such as file.* .
+     WebSocket feed. Any logged-in user can subscribe at /system/cluster/events/ws .
+     Go. bus.Publish(events.Event{...}) from core code.
+
+ArozOS Cluster Technical White Paper        Page 16 of 33
+12. Jobs, map/reduce and the job contract
+
+12.1 Model
+
+A job is an AGI script that defines run(job) . The script source is captured at submit time and stored in one
+replicated record ( jobs.Record{Spec, State} , metadata kind job ), so any node answers status queries locally and
+a new leader resumes scheduling. Because it is JavaScript executed by the Otto VM inside ArozOS, the same job
+runs on x86, ARM, Windows, Linux or macOS nodes.
+
+   submit (any node) -> record queued -> leader schedules every 3 s
+       -> jobs/run to chosen node -> VM runs as the owner
+       -> lease renew every 10 s -> jobs/done -> record succeeded/failed
+
+Statuses: queued , scheduled , running , succeeded , failed , cancelled . Kinds: run , map , reduce , mapreduce .
+
+12.2 The job contract
+
+function setup(ctx) {                 // optional, runs once before run(); ctx = {node}
+}
+
+function run(job) { // job = {id, name, kind, args, inputs, node, owner}
+
+   job.log("text");                   // appended to the job log (last 200 lines)
+
+   job.progress(0.5);                 // 0..1
+
+   if (job.cancelled()) {} // poll for cancellation
+
+   job.abortIfCancelled(); // throws when the job was cancelled
+
+   return { ok: true };               // JSON-serialisable; becomes the job output
+
+}
+
+   Normal AGI libraries ( filelib , imagelib , ffmpeg , ...) work inside a job and see cluster:/ .
+   Use absolute paths ( cluster:/... , user:/... ). A job has no script folder of its own, so relative paths are not
+   resolved.
+   The job runs as the submitting user on the chosen node. The owner must have an account there; with an
+   identity origin configured, accounts are mirrored automatically.
+
+12.3 Spec fields                               Meaning                                                   Default
+                                               display name                                              script name
+ Field (AGI / HTTP form)                       vpath of the .agi file (relative to the launcher in AGI)  required
+  name                                         JSON passed as job.args                                   none
+  script                                       files the job reads; nodes holding them are preferred     none
+  args                                         required capabilities, e.g. ["ffmpeg"]                    none
+  inputs                                       allowed node IDs; others are ineligible                   any node
+  features                                     seconds                                                   3600
+  nodes                                        higher runs first                                         0
+  timeout                                      minimum CPU cores                                         none
+  priority (HTTP)                              map/reduce only                                           50 files
+  cores (HTTP)
+  dataset , partitionMax / partition
+
+ArozOS Cluster Technical White Paper                                                                     Page 17 of 33
+MaxAttempts defaults to 3: when a running node goes silent the leader requeues the job, and fails it after the last
+attempt.
+
+12.4 Execution guarantees
+
+     Parallelism. At most runtime.NumCPU() jobs run per node; the rest wait.
+     Dispatch once. Scheduling passes are serialised, and a node accepts each job once even if a hand-over is
+     repeated. Temporary refusals (a tunnel still connecting, the leader not yet known) are retried. Only "the owner
+     has no account here" or "this node cannot run jobs" block that node from that job for good ( State.Blocked ).
+     Timeouts and cancellation. agi.Gateway.ExecuteJobScript hands back a stopper; a timeout or cancel
+     interrupts the VM within about a second.
+     Pinning. nodes: [id] sends a job to a specific member; one pinned job per member runs something
+     everywhere (see hello_world ).
+     Retention. Finished records are kept for 72 hours.
+     Queued with a reason. A job no node can take stays queued, and state.reason explains why (for example
+     no online node has ffmpeg).
+
+12.5 Map/reduce
+
+A job with a dataset glob becomes a map/reduce parent. The leader coordinates it and never assigns the parent
+to a node.
+
+  1. The glob is expanded over the namespace ( metadata.Glob : * within a folder, ** across folders, ? one
+     character).
+
+  2. Files are grouped by the node that already holds a healthy copy and split into partitions of partitionMax files
+     (default 50); one map child is submitted per partition, so map work runs where the bytes are.
+
+  3. When all map children succeed, emitted pairs are grouped by key and a single reduce child is submitted; its
+     output becomes the parent's.
+
+  4. A failed child fails the parent and cancels the rest. A dataset with an unreachable file fails and names it; an
+     empty dataset succeeds with an empty result. Grouped map output is capped at 8 MB.
+
+function mapper(files, emit) {        // files = paths of this partition
+
+   files.forEach(function (f) { emit(f.split(".").pop(), 1); });
+
+}
+
+function reducer(key, values) {       // called once per key
+
+   return values.length;
+
+}
+
+Mapper paths are namespace paths such as /photos/a.jpg ; prefix them with cluster: to open them with
+filelib . Children inherit the parent's nodes restriction.
+
+ArozOS Cluster Technical White Paper                                      Page 18 of 33
+13. Scheduling
+
+Three layers must answer "which node?": the job scheduler, write placement and the replication planner. They all
+call one scorer in scheduling/ , which scores each candidate from 0 to 1:
+
+Factor            Default weight      Measured as
+data locality     0.45                share of the input bytes already on the node
+free CPU          0.20                1 - cpuUsage from the health report
+free memory       0.10                1 - ramUsed / ramTotal
+free disk         0.05                largest free fraction among the node's volumes
+queue depth       0.10                penalty, saturating at 8 queued items
+network distance  0.05                penalty from heartbeat RTT, saturating at 1000 ms
+health            0.05                penalty when DEGRADED
+wanted features   0.10                optional capabilities a job prefers
+site diversity    0.05                distance of a new copy from existing copies
+
+Weights are one replicated setting ( scheduling.weights ), each 0 to 1, edited on the Cluster Settings page or
+through sched/weights ( reset=true restores defaults). Missing weights read back as the shipped defaults, so
+old records stay valid.
+Eligibility. The caller supplies the hard rule (capability match, usable state, a volume with room). The scorer
+holds DEGRADED nodes back whenever a healthy eligible node exists, sorts ineligible nodes last and keeps their
+reason, so an empty result is explained rather than silent.
+Latency is the heartbeat round trip smoothed with an EWMA (alpha 0.3); the local node reports 0 and a never-
+heard peer reports -1.
+Site diversity is only computed with three or more nodes and more than one possible target. The planner
+pulls each member's latency vector over GET /cluster/acn/latency and caches the matrix for two minutes; a
+candidate's diversity is its distance to the nearest existing copy, as a fraction of one second.
+Explanations. Every score carries its factors; /system/cluster/sched/explain?job=<id> re-runs the ranking for
+a job and returns every candidate with its factors and reasons.
+
+ArozOS Cluster Technical White Paper                                                     Page 19 of 33
+14. Developer interfaces
+
+14.1 AGI cluster library
+
+Load with requirelib("cluster") . File access on cluster:/ needs no special library: filelib and every other
+library see the mounted drive.
+
+Function                               Returns       Notes
+cluster.inCluster()
+cluster.self()                         bool
+cluster.nodes()
+cluster.status()                       object        this node: id, name, state, capabilities, health
+cluster.stat(path)
+cluster.list(path)                     array         every member with state, platform, load
+cluster.setReplicas(path, n)
+cluster.policy(folder, n)              object        cluster info, identity origin, leader, volumes, storage, replication
+cluster.on(types, scriptVpath)
+cluster.off(hookId) / cluster.hooks()  object        record with size, checksum, locations[] ; needs read permission
+cluster.emit(type, data)
+cluster.jobs.submit(spec)              array         records of a directory's children
+cluster.jobs.mapreduce(spec)
+cluster.jobs.status(id)                bool          admin; 0 to 16, 0 = folder policy
+cluster.jobs.list()
+cluster.jobs.cancel(id)                bool          admin; top-level folder such as /photos
+cluster.jobs.wait(id, timeoutSec)
+                                       string        hook id; string or array, file.* wildcards
+
+                                       bool / array
+
+                                       bool          app. prefix added; payload under 64 KB
+
+                                       string        job id
+
+                                       string        {name, script, dataset, partitionMax, features, timeout}
+
+                                       object        {spec, state}
+
+                                       array         own jobs
+
+                                       bool
+
+                                       object        blocks in Go; throws if not finished in time
+
+Users see and cancel only their own jobs; administrators see all.
+
+14.2 HTTP endpoints for browsers
+
+All go through the permission router ( prout.NewModuleRouter ):
+
+     Admin only ( System Setting module, admin): /system/cluster/* status, create, join, leave, tokens, nodes,
+     identity, metadata, storage, replication and scheduling. See Appendix A.
+     Logged-in users ( Tasks Scheduler module permission): /system/cluster/jobs/{submit,status,get,cancel} .
+     Logged-in users: /system/cluster/events/ws (WebSocket) and /system/cluster/events/hooks .
+
+14.3 Go building blocks
+
+Need                 Use
+                     clusterManager.Transport().DoJSON(ctx, nodeID, method, path, in, out)
+Signed request to a
+member               clusterManager.Server().HandleFunc(acn.BasePath+"/x", func(w, r, sender
+                     *acn.SignedIdentity, body []byte))
+New signed node
+endpoint
+
+ArozOS Cluster Technical White Paper                                                                   Page 20 of 33
+Need                 Use
+Members and their    clusterManager.NodeViews() ( State , Local , Capabilities , Health , LatencyMs , ...)
+state
+Own IDs              clusterManager.NodeID() , Cluster() , InCluster()
+Cluster-scoped       clusterManager.DB() ( system/cluster.db ) + membership.RegisterClusterTable(name)
+storage
+React to setting     chain OnClusterChange / OnMembershipChange (keep the previous callback)
+changes
+Namespace            clusterMetadata.Submit , Stat , ListDir , Glob , Volumes , PolicyFor , IsLeader
+                     clusterScheduling ( Rank , Best )
+Placement            capability.Manifest.Satisfies(capability.Requirements) , capability.DiskUsage(path)
+Capabilities         clusterIdentity.Issue , Attach , FromRequest
+                     clusterEvents.Publish(events.Event{...})
+Cross-node user      nightly.TaskOption{MasterNodeOnly: true}
+Events
+
+Master-only nightly
+work
+
+ArozOS Cluster Technical White Paper  Page 21 of 33
+15. Worked examples
+
+The folder examples/clusters_jobs/ contains three runnable pairs. Each has a launcher ( <name>.agi , run like any
+AGI script, for example from the Serverless tool, Code Studio or /system/ajgi/interface?script=<path> ) and a job
+( <name>.job.agi , captured at submit time). Keep both files in the same folder: the launcher refers to its job by a
+relative path.
+
+Example       Shows
+
+hello_world/  one job pinned to every usable node with nodes ; each replies with its name, platform, capabilities and
+              health
+
+list_files/   one job walks cluster:/ with filelib and totals files per extension
+
+ffmpeg_convert/ converts cluster:/demo.mp4 to WebM on a node with ffmpeg , preferring one that already holds the
+                           video
+
+15.1 Run on every node (launcher)
+
+requirelib("cluster");
+
+var nodes = cluster.nodes(), ids = [];
+
+for (var i = 0; i < nodes.length; i++) {
+
+   var n = nodes[i];
+
+   if (n.state !== "ONLINE" && n.state !== "DEGRADED") continue;
+
+   ids.push(cluster.jobs.submit({
+
+         name: "Hello World on " + n.name,
+
+         script: "hello_world.job.agi",
+
+         nodes: [n.id],               // this node and nowhere else
+
+         timeout: 60
+
+   }));
+
+}
+
+var replies = [];
+
+for (var j = 0; j < ids.length; j++) {
+
+   var rec;
+
+   try { rec = cluster.jobs.wait(ids[j], 60); }
+
+   catch (e) { rec = cluster.jobs.status(ids[j]); }
+
+   if (rec.state.status === "succeeded") replies.push(rec.state.output);
+
+}
+
+sendJSONResp(JSON.stringify(replies));
+
+15.2 The matching job
+
+   requirelib("cluster");
+
+   function run(job) {
+          var me = cluster.self();
+          job.log("Hello World from " + me.name);
+          return {
+                 message: "Hello World from " + me.name,
+                 os: me.capabilities.os,
+                 arch: me.capabilities.arch,
+                 cpuUsage: me.health.cpuUsage,
+                 runAs: job.owner
+          };
+
+   }
+
+ArozOS Cluster Technical White Paper                                               Page 22 of 33
+15.3 Capability and locality (ffmpeg)
+
+requirelib("cluster");
+
+var id = cluster.jobs.submit({
+
+     name: "Convert demo.mp4 to WEBM",
+
+     script: "ffmpeg_convert.job.agi",
+
+     args: { input: "cluster:/demo.mp4", output: "cluster:/demo.webm" },
+
+     inputs: ["cluster:/demo.mp4"], // prefer a node holding the video
+
+     features: ["ffmpeg"],            // only nodes with ffmpeg
+
+     timeout: 3600
+
+});
+
+requirelib("filelib");
+function run(job) {
+
+      if (!requirelib("ffmpeg")) throw new Error("no ffmpeg on this node");
+      job.progress(0.05);
+      if (!ffmpeg.convert(job.args.input, job.args.output)) {
+
+             throw new Error("conversion failed");
+      }
+      job.progress(1);
+      return { output: job.args.output,
+
+                     bytes: filelib.filesize(job.args.output),
+                     node: job.node };
+}
+
+15.4 Map/reduce: count files per extension
+
+requirelib("cluster");                           // {"jpg": 812, ...}
+var id = cluster.jobs.mapreduce({
+
+      name: "Extensions in /photos",
+      script: "user:/jobs/ext_count.agi",
+      dataset: "/photos/**",
+      partitionMax: 100
+});
+var rec = cluster.jobs.wait(id, 600);
+sendJSONResp(JSON.stringify(rec.state.output));
+
+// user:/jobs/ext_count.agi
+function mapper(files, emit) {
+
+      files.forEach(function (f) { emit(f.split(".").pop(), 1); });
+}
+function reducer(key, values) { return values.length; }
+
+15.5 React to new files (event hook)
+
+   requirelib("cluster");
+   var hookId = cluster.on(["file.created"], "user:/hooks/on_new_file.agi");
+
+// user:/hooks/on_new_file.agi
+requirelib("cluster");
+var ev = JSON.parse(postPara("event")); // {id, type, node, path, ...}
+if (ev.path.match(/\.jpg$/i)) {
+
+      cluster.emit("photos.uploaded", { path: ev.path }); // -> app.photos...
+}
+
+ArozOS Cluster Technical White Paper                                           Page 23 of 33
+15.6 Inspect copies and set replicas
+
+requirelib("cluster");
+
+var rec = cluster.stat("cluster:/photos/a.jpg");
+
+var where = rec.locations.map(function (l) {
+
+     return l.nodeId + " (" + l.state + ")";
+
+});
+
+cluster.policy("/photos", 2);                 // admin: 2 copies for /photos
+
+cluster.setReplicas("cluster:/photos/a.jpg", 3); // admin: this file, 3
+
+sendResp(where.join(", "));
+
+15.7 Submitting over HTTP
+
+   curl -b cookies.txt -X POST \
+       https://node-a.example.com/system/cluster/jobs/submit \
+       -d script=user:/jobs/hello.job.agi -d name=Hello \
+       -d features=ffmpeg -d timeout=600 -d 'args={"x":1}'
+
+List fields ( inputs , features , nodes ) accept a comma-separated list; inputs also accepts a JSON array.
+
+ArozOS Cluster Technical White Paper                                                                        Page 24 of 33
+16. Minimum dependencies and requirements
+
+16.1 Software
+
+Requirement      Detail
+
+ArozOS binary    This branch or later on every member; the cluster is built in. No separate service, database or agent is
+                 installed.
+
+Build toolchain  Go 1.25 ( go.mod ); CGO_ENABLED=0 builds are supported.
+
+Go modules used  github.com/gorilla/websocket (BSD-2), github.com/satori/go.uuid (MIT), github.com/boltdb/bolt
+by the cluster   (MIT, through mod/database ), golang.org/x/sys (BSD-3), github.com/robertkrimen/otto (MIT, AGI)
+                 and the Go standard library (Ed25519, SHA-256). All already in ArozOS; the cluster added no new module.
+
+External tools   None required. ffmpeg , docker , nvidia-smi , git , python3 , node only advertise optional capabilities
+                 that jobs may ask for.
+
+Platforms        Every ArozOS target: Linux amd64/386/arm/arm64/mipsle/riscv64, macOS, Windows. Syscalls are build-
+                 tagged ( capability/diskusage_*.go ).
+
+16.2 Cluster topology
+
+Requirement              Detail
+Minimum members
+                         1 to create a cluster (and mount cluster:/ once it has a volume); 2 for replication and failover; 3
+At least one reachable   for the site-diversity factor.
+member
+Unique node IDs          A member with an advertised URL must exist to issue join tokens and host tunnels. Other members
+Clock synchronisation    may be NAT-only.
+Network
+                         Each host needs its own system/dev.uuid (or -uuid ).
+At least one volume
+Accounts                 Clocks within plus or minus 5 minutes (signature window and assertion lifetime). Use NTP.
+
+Disk                     HTTP(S) to the normal ArozOS port. No extra ports, multicast or VPN. WebSockets must pass
+                         through any proxy for tunnels. Cloudflare is supported.
+HTTPS
+                         Required before cluster:/ appears.
+
+                         For jobs, the owner must exist on the executing node: configure an identity origin, or create
+                         accounts manually. Create the same permission groups on every node.
+
+                         Room for the contributed volume plus the spool ( -tmp folder) for files in transit; a volume is read-
+                         only below 5 % free.
+
+                         Strongly recommended in production: the account directory carries password hashes.
+
+16.3 Enabling and disabling
+
+The cluster agent is available by default. Start with -disable_cluster to turn it off completely: no agent, no
+cluster:/ , no cluster tabs, and /cluster/acn/* answers 404. The older mDNS Neighbourhood page is separate
+and governed by -allow_mdns . Relevant flags: -uuid , -hostname , -port , -tmp , -disable_cluster .
+
+ArozOS Cluster Technical White Paper                                      Page 25 of 33
+17. Limits and maximum capabilities
+
+Area             Limit                                                      Value
+Cluster size     no hard cap; full-mesh heartbeats every 15 s make traffic  designed for small clusters (households,
+                 grow with the square of the node count                     labs, small offices)
+Replicas         per folder policy                                          1 to 16
+Replicas         per file                                                   0 to 16 (0 = policy)
+File size        no fixed maximum; bound by the target volume               transferred in 4 MiB chunks
+Chunk            default / maximum                                          4 MiB / 8 MiB
+Upload session   idle expiry                                                30 minutes
+Signed request   maximum                                                    64 MB
+body
+Tunnel frame     maximum                                                    16 MB
+Clock skew       tolerated                                                  plus or minus 5 minutes
+Jobs per node    concurrent                                                 runtime.NumCPU()
+Job timeout      default                                                    3600 s
+Job attempts     default                                                    3
+Job log          kept                                                       last 200 lines
+Job records      retention after finishing                                  72 hours
+Map/reduce       partition size default                                     50 files
+Map/reduce       grouped map output                                         8 MB
+Scheduling pass  interval                                                   3s
+Replication      tasks in flight                                            4 per node, 16 total
+Replication      retries                                                    5, then pause 1 hour
+Verification     nightly budget                                             1 GB per node
+Custom event     maximum                                                    64 KB
+payload
+Hook scripts     concurrent per node                                        4
+Join token       default lifetime                                           24 hours
+User assertion   lifetime                                                   5 minutes
+
+What a cluster can do at its best:
+
+     Present one cluster:/ namespace, readable and writable from every member and every app, with files
+     transparently fetched from whichever node holds them.
+     Keep up to 16 verified copies of each file on distinct nodes, repair and re-verify them automatically, spread
+     second copies across sites, and move data off retiring disks without downtime.
+     Survive the loss of any node, including the leader and the identity origin, with two-node failover and no
+     quorum.
+     Run AGI jobs on any architecture, placed by capability, data locality and load, with progress, logs, cancellation,
+     retries and explanations; run a job on every node at once; and run map/reduce where the data lives.
+     Connect nodes across the Internet, behind NAT or Cloudflare, over the normal HTTPS port.
+
+ArozOS Cluster Technical White Paper                                        Page 26 of 33
+18. Security model
+
+Concern                               Mechanism
+Node authentication                   Ed25519 signature over method, target, cluster, node, timestamp, nonce and body hash
+Replay                                per-request nonce, spent only after full verification; 5-minute clock window
+Cross-cluster confusion               X-Aroz-Cluster must match
+Relayed requests                      signature covers the original path; both relay and target verify
+Joining                               one-time secret in the token, stored as SHA-256, expiring and revocable
+Passwords                             only SHA-512 hashes are forwarded; constant-time comparison at the origin
+Acting for a user across              signed, short-lived X-Aroz-User assertions
+nodes
+Browser endpoints                     permission router; admin-only for cluster control
+Jobs                                  run as the owner through the AGI sandbox, with the owner's permissions on the executing
+                                      node
+Data integrity                        per-chunk and whole-file SHA-256, verified copies, nightly re-checksums
+State isolation                       system/cluster.db , never ao.db ; cluster tables wiped on leave
+
+Operational advice: run members behind HTTPS; protect system/cluster/node.key like a private key; revoke
+unused join tokens; keep clocks synchronised; and do not clone a system folder without deleting dev.uuid and
+cluster/ .
+
+ArozOS Cluster Technical White Paper  Page 27 of 33
+19. Operations and administration
+
+Three System Settings tabs in the Cluster group (localized in en-us, zh-tw, zh-hk, zh-cn, ja-jp, ko-kr):
+
+Tab       Page                               Contents
+Cluster
+Settings  SystemAO/cluster/cluster.html      node name and URL, create/join/leave, join tokens, identity origin,
+                                             volumes and the nearly-full toggle, replica policies, maintenance and
+Cluster                                      draining, scheduling weights
+Info
+          SystemAO/cluster/clusterinfo.html  reachability, platform, health, cluster summary, namespace state, node
+Cluster                                      table with probes, replication tools, score preview, latency matrix, job
+Jobs                                         explainer
+
+          SystemAO/cluster/jobs.html         submit, follow and cancel jobs (users see their own)
+
+Typical setup
+
+  1. On node A (reachable URL): Cluster Settings > set the advertised URL > Create cluster.
+  2. Add a volume, for example user:/cluster . cluster:/ now appears.
+  3. Generate a join token, paste it on node B (and C, ...).
+  4. Choose an identity origin and create the same permission groups on each node.
+  5. Set replica policies, for example /photos = 2.
+  6. Watch Cluster Info for node states, replication health and scores.
+
+Maintenance
+
+     Set a node to MAINTENANCE before rebooting it, or DRAINING to move its copies away while it still serves reads.
+     Evacuate a volume before removing a disk.
+     Use "Verify this node" after suspected disk problems.
+     For a live two-node test on one machine, see TASKS.md section 0.5: two isolated copies of system/ , separate
+     ports, -uuid and -hostname , -allow_mdns=false -allow_ssdp=false .
+
+ArozOS Cluster Technical White Paper                                                                      Page 28 of 33
+20. Developer guide: extending the cluster
+
+20.1 Repository rules that apply
+
+  1. Log only through logger.PrintAndLog("Cluster", message, err) .
+  2. Every package under src/mod/ ships tests; new exported functions are covered (table-driven, t.TempDir() ,
+
+      t.Fatalf ).
+  3. New dependencies must be MIT, BSD, Apache-2.0, MPL-2.0 or ISC.
+  4. Browser endpoints go through prout.NewModuleRouter ; node-to-node endpoints through
+
+      acn.Server.HandleFunc (signed, mounted under /cluster/acn/ ).
+  5. Stay portable: no hardcoded OS paths, no exec.Command in shared code, build tags for OS-specific code.
+  6. No emoji in code or UI; use Semantic UI icons or SVG.
+  7. Add user-facing strings and server messages to src/web/SystemAO/locale/cluster.json ( CL.t for labels,
+
+      CL.tr for server messages via msg/<text> and msgp/<template> entries).
+
+20.2 Adding a replicated feature
+
+  1. Pick a record kind: reuse metadata.KindSetting for configuration, or add a kind with a Version field that
+     merges last-writer-wins.
+
+  2. Write with Submit(kind, record) ; never write the disk directly under a lock.
+  3. Serialise decisions on the leader ( IsLeader() ); make tasks ephemeral so a new leader can re-plan.
+  4. Use scheduling for any "which node" choice so weights and explanations stay consistent.
+  5. Publish events for anything scripts may want to react to.
+  6. Register any new table with membership.RegisterClusterTable .
+
+20.3 Testing multi-node logic
+
+Follow identity/identity_test.go : create N membership.NewManager instances with t.TempDir() databases, serve
+each with httptest.NewServer(m.ACNHandler()) , set URLs with m.UpdateConfig , create a cluster on one,
+NewJoinToken + JoinCluster the others, and poll with waitFor(...) (5 s deadline); never sleep fixed durations.
+Timing constants are variables so tests can shorten them in init() . Close managers in t.Cleanup .
+
+   cd src
+   go build ./... && go vet ./mod/cluster/...
+   go test -timeout 300s -count=3 ./mod/cluster/...
+   sh ../scripts/check-conventions.sh --diff origin/master
+
+ArozOS Cluster Technical White Paper  Page 29 of 33
+21. Known constraints and pitfalls
+
+     No -race for Bolt-backed packages. boltdb/bolt panics under checkptr; only acn can run with -race .
+     Two ArozOS instances cannot share src/ (Bolt lock on ao.db ).
+     Page scripts must not declare var status : it shadows window.status . Use names such as clusterStatus .
+      go mod tidy pulls in modules imported by user files under src/files/ ; revert unrelated go.mod additions.
+     CRLF files. If an edit produces a whole-file diff, normalise with sed -i 's/\r$//' <file> .
+     Windows temp-dir cleanup fails if a test leaves a Bolt DB open.
+     Relative paths in jobs do not resolve; use cluster:/ or user:/ .
+     Groups are per node. A mirrored account only gets groups that exist on that node.
+     Eventual consistency. Two writers of the same path on different nodes resolve last-writer-wins; applications
+     needing stronger guarantees should coordinate through a job or the leader.
+     Map output lives in the job record, so keep emitted values small (8 MB cap).
+
+ArozOS Cluster Technical White Paper  Page 30 of 33
+22. Appendix A: endpoint reference
+
+A.1 Signed node-to-node endpoints ( /cluster/acn/... )
+
+Group      Endpoints
+
+Transport  GET hello (unsigned probe), POST ping , GET tunnel , * relay/{node}/... , GET latency
+
+Membership POST join (join token), POST heartbeat , GET members , POST members/sync , POST leave , POST evict
+
+Identity   POST auth/verify , GET auth/directory , POST auth/setpassword
+
+Metadata   meta/lease , meta/append , meta/submit , meta/log , meta/snapshot , meta/stat
+
+Storage    store/place , store/begin , store/chunk , store/commit , store/abort , store/read , store/stat ,
+           store/list , store/checksum , store/mkdir , store/rename , store/delete
+
+Replication repl/pull , repl/lease , repl/done , repl/plan
+
+Events     events/publish
+
+Jobs       jobs/run , jobs/done , jobs/submit
+
+A.2 Browser endpoints ( /system/cluster/... )
+
+Group          Endpoints                                                                          Access
+Agent          status , create , join , leave , config , testurl , nodes , capabilities ,         admin
+               node/remove , node/state , node/probe
+Tokens         token/new , token/list , token/revoke                                              admin
+Identity       identity/status , identity/origin , identity/sync                                  admin
+Metadata       meta/status , meta/ls , meta/stat , meta/policy/list , meta/policy/set             admin
+Storage        storage/status , storage/volume/add , storage/volume/remove ,                      admin
+               storage/volume/readonly , storage/volume/evacuate ,
+Replication    storage/volume/evacuate/cancel , storage/volume/evacuate/status ,                  admin
+Scheduling     storage/rescan , storage/autoreadonly                                              admin
+Jobs           repl/status , repl/plan , repl/verify                                              user (own jobs)
+Events         sched/status , sched/weights , sched/explain?job=<id>                              user
+Neighbourhood  jobs/submit , jobs/status , jobs/get , jobs/cancel                                 user, only with
+(mDNS)         events/ws , events/hooks                                                           -allow_mdns
+               scan , record , wol
+
+ArozOS Cluster Technical White Paper                                                                         Page 31 of 33
+23. Appendix B: tunables and constants
+
+Constant                                Value            Package
+HeartbeatInterval                       15 s             membership
+OnlineWindow / OfflineWindow            45 s / 3 min     membership
+TombstoneTTL                            7 days           membership
+LatencyMatrixTTL                        2 min            membership
+MaxClockSkew                            5 min            acn
+MaxSignedBody                           64 MB            acn
+TunnelPingInterval / TunnelReadTimeout  30 s / 90 s      acn
+TunnelMaxFrame                          16 MB            acn
+DefaultRequestTimeout                   60 s             acn
+DefaultAssertionTTL                     5 min            identity
+DefaultSyncInterval                     5 min            identity
+Leader lease / renew                    30 s / 10 s      metadata
+FlushInterval                           50 ms            metadata
+ChunkSize / MaxChunkSize                4 MiB / 8 MiB    storage
+SessionTTL                              30 min           storage
+Refresh / reconcile                     60 s / 30 min    storage
+Low-space guard                         5 % on, 7 % off  storage
+Plan interval                           60 s             replication
+In flight per node / total / workers    4 / 16 / 4       replication
+Max attempts                            5                replication
+Offline-to-stale                        10 min           replication
+Schedule interval                       3s               jobs
+Task lease / renew                      30 s / 10 s      jobs
+Max parallel                            NumCPU           jobs
+Retention                               72 h             jobs
+Default timeout / attempts              3600 s / 3       jobs
+Log lines                               200              jobs
+Batch interval / dedup window           200 ms / 10 min  events
+Concurrent hook runs                    4                events
+
+ArozOS Cluster Technical White Paper                     Page 32 of 33
+24. Appendix C: glossary
+
+Term             Meaning
+Node             one ArozOS installation
+Member           a node that is in the cluster
+Leader / master  the member holding the metadata lease; serialises placement, replication, scheduling and shared nightly
+node             maintenance
+Identity origin  the member that owns the account table
+Volume           a folder a node contributes to the cluster namespace
+Record           one entry in the metadata store
+Copy / location  one physical copy of a file on a volume
+Policy           desired replica count for a top-level folder
+ACN              ArozOS Cluster Node protocol
+ACMS             ArozOS Cluster Metadata Store
+AID              ArozOS Identity
+AGI              ArOZ Online JavaScript Gateway Interface (the server-side JavaScript runtime)
+Tunnel           a WebSocket a NAT-only node keeps open to a reachable member
+Relay            forwarding a request to a tunnelled node through its tunnel host
+
+ArozOS Cluster Technical White Paper  Page 33 of 33
+

+ 9 - 5
src/cluster.go

@@ -377,6 +377,7 @@ func clusterMountDrive() {
 		return
 	}
 	systemWideLogger.PrintAndLog("Cluster", "cluster:/ mounted for all users", nil)
+	go clusterRemoveThumbnailFolders()
 }
 
 func clusterUnmountDrive() {
@@ -545,17 +546,20 @@ func clusterStartAgent() {
 
 			//Storage: volumes, chunked transfer and the cluster:/ drive
 			sto, err := storage.New(storage.Option{
-				Membership: clusterManager,
-				Metadata:   clusterMetadata,
-				Scheduler:  clusterScheduling,
-				TmpDir:     *tmp_directory,
-				LocalRoots: clusterLocalRoots,
+				Membership:  clusterManager,
+				Metadata:    clusterMetadata,
+				Scheduler:   clusterScheduling,
+				TmpDir:      *tmp_directory,
+				LocalRoots:  clusterLocalRoots,
+				Thumbnailer: clusterRenderThumbnail,
 			})
 			if err != nil {
 				systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster storage: "+err.Error(), err)
 			} else {
 				clusterStorage = sto
 				clusterStorage.RegisterAdminRoutes(registerAdmin)
+				//Empty thumbnail folders earlier builds left in cluster:/
+				nightlyManager.RegisterNightlyTask(func() { clusterRemoveThumbnailFolders() })
 				prevChange := clusterManager.OnMembershipChange
 				clusterManager.OnMembershipChange = func(in bool) {
 					if prevChange != nil {

+ 116 - 0
src/cluster.thumbnail.go

@@ -0,0 +1,116 @@
+package main
+
+/*
+	Thumbnails of cluster:/ files
+
+	cluster:/ is a buffered drive, so the ordinary renderers cannot open its
+	files, and a .metadata/.cache folder inside it would be a real cluster
+	file that gets placed and replicated like any other. Instead the drive
+	implements arozfs.ThumbnailRenderer through the backend below:
+
+	- the key of a thumbnail is the SHA-256 of the file from its metadata
+	  record, so the cache on this host is keyed by content and a changed
+	  file never shows an old thumbnail
+	- the image is rendered by a node holding a copy, this node first
+	  (mod/cluster/storage/thumbnail.go), with metadata.RenderLocalFile on
+	  that node's own copy; only the thumbnail crosses the network
+
+	Earlier builds created empty .metadata/.cache folders in the namespace
+	while trying to render. clusterRemoveThumbnailFolders removes them.
+*/
+
+import (
+	"context"
+	"errors"
+	"path"
+	"strconv"
+	"time"
+
+	"imuslab.com/arozos/mod/filesystem/arozfs"
+	"imuslab.com/arozos/mod/filesystem/metadata"
+)
+
+const (
+	//clusterThumbnailTimeout bounds one thumbnail request, the frame grab of
+	//a video on a slow holder included
+	clusterThumbnailTimeout = 90 * time.Second
+	//thumbnailCacheMaxAge is how long an unused thumbnail is kept on this host
+	thumbnailCacheMaxAge = 30 * 24 * time.Hour
+)
+
+// ThumbnailKey identifies the content of a namespace file. It completes the
+// clusterfs.ThumbnailBackend interface.
+func (b *clusterBackend) ThumbnailKey(logical string) (string, error) {
+	if clusterMetadata == nil {
+		return "", errors.New("this node is not in a cluster")
+	}
+	rec, err := clusterMetadata.Stat(logical)
+	if err != nil {
+		return "", err
+	}
+	if rec.IsDir {
+		return "", arozfs.ErrNoThumbnail
+	}
+	return clusterThumbnailKey(rec.Checksum, rec.ID, rec.Size, rec.ModTime), nil
+}
+
+// clusterThumbnailKey is the checksum of the file when it has one. A record
+// still being written has none yet, and is keyed by its identity instead.
+func clusterThumbnailKey(checksum string, fileID string, size int64, modTime int64) string {
+	if checksum != "" {
+		return "cluster-sha256:" + checksum
+	}
+	return "cluster-file:" + fileID + ":" + strconv.FormatInt(size, 10) + ":" + strconv.FormatInt(modTime, 10)
+}
+
+// RenderThumbnail has a node holding a copy render the thumbnail. It
+// completes the clusterfs.ThumbnailBackend interface.
+func (b *clusterBackend) RenderThumbnail(logical string) ([]byte, error) {
+	ctx, cancel := context.WithTimeout(context.Background(), clusterThumbnailTimeout)
+	defer cancel()
+	return b.s.Thumbnail(ctx, logical, metadata.ThumbnailFeature(logical))
+}
+
+// clusterRenderThumbnail renders a copy on one of this node's volumes, for
+// this node or for another member asking it.
+func clusterRenderThumbnail(osPath string) ([]byte, error) {
+	return metadata.RenderLocalFile(osPath)
+}
+
+// clusterRemoveThumbnailFolders removes the empty .metadata/.cache folders an
+// earlier build left in the namespace, and the .metadata folder around one
+// when nothing else (a trash folder, say) is in it. Only the master node does
+// it, so the members do not race each other over the same records.
+func clusterRemoveThumbnailFolders() int {
+	if clusterStorage == nil || clusterMetadata == nil || !clusterManager.InCluster() || !clusterMetadata.IsLeader() {
+		return 0
+	}
+	removed := 0
+	for _, rec := range clusterMetadata.ListSubtree("/") {
+		if !clusterIsThumbnailFolder(rec.Path, rec.IsDir) {
+			continue
+		}
+		if len(clusterMetadata.ListSubtree(rec.Path)) > 0 {
+			//Something was put in there; leave it alone
+			continue
+		}
+		if clusterStorage.Remove(rec.Path, false) != nil {
+			continue
+		}
+		removed++
+		parent := path.Dir(rec.Path)
+		if children, err := clusterMetadata.ListDir(parent); err == nil && len(children) == 0 {
+			clusterStorage.Remove(parent, false)
+		}
+	}
+	if removed > 0 {
+		systemWideLogger.PrintAndLog("Cluster", "Removed "+strconv.Itoa(removed)+" unused thumbnail folder(s) from cluster:/", nil)
+	}
+	return removed
+}
+
+// clusterIsThumbnailFolder reports whether a namespace path is a
+// .metadata/.cache folder.
+func clusterIsThumbnailFolder(p string, isDir bool) bool {
+	return isDir && path.Base(p) == ".cache" && path.Base(path.Dir(p)) == ".metadata"
+}

+ 45 - 0
src/cluster.thumbnail_test.go

@@ -0,0 +1,45 @@
+package main
+
+import "testing"
+
+func TestClusterThumbnailKey(t *testing.T) {
+	testcases := []struct {
+		name     string
+		checksum string
+		id       string
+		size     int64
+		modTime  int64
+		want     string
+	}{
+		{"committed file uses its checksum", "abc123", "f1", 10, 100, "cluster-sha256:abc123"},
+		{"same content elsewhere shares the key", "abc123", "f2", 10, 999, "cluster-sha256:abc123"},
+		{"file being written uses its identity", "", "f1", 10, 100, "cluster-file:f1:10:100"},
+		{"a new write changes the key", "", "f1", 11, 101, "cluster-file:f1:11:101"},
+	}
+	for _, tc := range testcases {
+		if got := clusterThumbnailKey(tc.checksum, tc.id, tc.size, tc.modTime); got != tc.want {
+			t.Errorf("%s: got %q, wanted %q", tc.name, got, tc.want)
+		}
+	}
+}
+
+func TestClusterIsThumbnailFolder(t *testing.T) {
+	testcases := []struct {
+		path  string
+		isDir bool
+		want  bool
+	}{
+		{"/.metadata/.cache", true, true},
+		{"/photos/.metadata/.cache", true, true},
+		{"/photos/.metadata/.cache", false, false},
+		{"/photos/.metadata", true, false},
+		{"/photos/.metadata/.trash", true, false},
+		{"/photos/.cache", true, false},
+		{"/photos/.metadata/.cache/x.jpg", false, false},
+	}
+	for _, tc := range testcases {
+		if got := clusterIsThumbnailFolder(tc.path, tc.isDir); got != tc.want {
+			t.Errorf("clusterIsThumbnailFolder(%q, %v) = %v, wanted %v", tc.path, tc.isDir, got, tc.want)
+		}
+	}
+}

+ 8 - 0
src/file_system.go

@@ -235,6 +235,14 @@ func FileSystemInit() {
 	//Create a RenderHandler for caching thumbnails
 	thumbRenderHandler = metadata.NewRenderHandler()
 
+	//Thumbnails of drives that render them where the file is stored (e.g.
+	//cluster:/) are kept on this host, outside the drive and outside tmp:/
+	//(whose files are cleared after a day)
+	metadata.SetExternalCacheDir(filepath.Join("system", "cache", "thumbnails"))
+	nightlyManager.RegisterNightlyTask(func() {
+		metadata.PruneExternalCache(thumbnailCacheMaxAge)
+	})
+
 	/*
 		Share Related Registering
 

+ 9 - 0
src/mod/cluster/README.md

@@ -293,6 +293,15 @@ every membership change and every volume record change.
   (`/system/file_system/getStorageInfo` → `src/cluster.fsinfo.go`). The shape
   is generic: any abstraction that can explain where its files live gets the
   same tab.
+- **Thumbnails**: the abstraction implements `arozfs.ThumbnailRenderer`. A
+  thumbnail is rendered by a node holding a copy (this node first, then the
+  nearest online holder whose capability manifest has the tool the format
+  needs, e.g. ffmpeg for video) through the signed `store/thumbnail`
+  endpoint (`storage/thumbnail.go`), which runs `metadata.RenderLocalFile`
+  on that node's own copy, so only the image crosses the network. The asking
+  host keeps it in `system/cache/thumbnails`, keyed by the file's SHA-256, so
+  no `.metadata/.cache` folder is ever written into the namespace; unused
+  thumbnails are pruned after 30 days (`src/cluster.thumbnail.go`).
 
 Admin API: `/system/cluster/storage/{status,volume/add,volume/remove,volume/readonly,rescan,autoreadonly}`.
 

+ 8 - 1
src/mod/cluster/storage/service.go

@@ -69,7 +69,10 @@ type Option struct {
 	TmpDir    string
 	// LocalRoots maps local (non network, non buffered) file system handler
 	// UUIDs to their real root paths. Provided by the core.
-	LocalRoots        func() map[string]string
+	LocalRoots func() map[string]string
+	// Thumbnailer renders the thumbnail of a file on one of this node's
+	// volumes, given its OS path (thumbnail.go). Nil: this node renders none.
+	Thumbnailer       func(osPath string) ([]byte, error)
 	RefreshInterval   time.Duration
 	ReconcileInterval time.Duration
 }
@@ -85,6 +88,9 @@ type Service struct {
 	sessMu   sync.Mutex
 	sessions map[string]*session
 
+	//thumbSem bounds the thumbnails rendered at once
+	thumbSem chan struct{}
+
 	stop chan struct{}
 	wg   sync.WaitGroup
 	once sync.Once
@@ -129,6 +135,7 @@ func New(opt Option) (*Service, error) {
 		client:   &Client{Transport: opt.Membership.Transport()},
 		opt:      opt,
 		sessions: map[string]*session{},
+		thumbSem: make(chan struct{}, ThumbnailConcurrency),
 		stop:     make(chan struct{}),
 	}
 	s.registerACNHandlers()

+ 14 - 2
src/mod/cluster/storage/storage_test.go

@@ -11,6 +11,7 @@ import (
 	"net/http/httptest"
 	"os"
 	"path/filepath"
+	"sync/atomic"
 	"testing"
 	"time"
 
@@ -31,6 +32,9 @@ type testNode struct {
 	svc  *Service
 	srv  *httptest.Server
 	root string //local drive root exposed as fsh "disk"
+	//thumb holds the func(osPath string) ([]byte, error) the node renders
+	//thumbnails with; empty means the node has no renderer
+	thumb *atomic.Value
 }
 
 func newTestNode(t *testing.T, id string) *testNode {
@@ -52,9 +56,17 @@ func newTestNode(t *testing.T, id string) *testNode {
 	}
 	root := filepath.Join(dir, "disk")
 	os.MkdirAll(root, 0755)
+	thumb := &atomic.Value{}
 	svc, err := New(Option{
 		Membership: m, Metadata: meta, TmpDir: filepath.Join(dir, "tmp"),
-		LocalRoots:      func() map[string]string { return map[string]string{"disk": root} },
+		LocalRoots: func() map[string]string { return map[string]string{"disk": root} },
+		Thumbnailer: func(osPath string) ([]byte, error) {
+			render, ok := thumb.Load().(func(string) ([]byte, error))
+			if !ok {
+				return nil, ErrNoThumbnailer
+			}
+			return render(osPath)
+		},
 		RefreshInterval: time.Hour, ReconcileInterval: time.Hour,
 	})
 	if err != nil {
@@ -64,7 +76,7 @@ func newTestNode(t *testing.T, id string) *testNode {
 	cfg := m.Config()
 	cfg.AdvertiseURL = srv.URL
 	m.UpdateConfig(cfg)
-	n := &testNode{id: id, m: m, meta: meta, svc: svc, srv: srv, root: root}
+	n := &testNode{id: id, m: m, meta: meta, svc: svc, srv: srv, root: root, thumb: thumb}
 	t.Cleanup(func() {
 		svc.Close()
 		meta.Close()

+ 238 - 0
src/mod/cluster/storage/thumbnail.go

@@ -0,0 +1,238 @@
+package storage
+
+/*
+	Thumbnails rendered where the file is
+
+	A thumbnail of a cluster:/ file is rendered by a node that holds a copy
+	of it, from the copy on its own volume, and only the small image crosses
+	the network. The node asking picks the holder:
+
+	- this node, when it holds a healthy copy: nothing is sent at all
+	- otherwise the online holders, nearest (lowest measured round trip)
+	  first, skipping those that lack a tool the format needs (ffmpeg for
+	  video) according to their capability manifest
+
+	A file that has no thumbnail (arozfs.ErrNoThumbnail) has none on any
+	copy, so that answer ends the search; any other failure moves on to the
+	next holder. The bytes of the file itself are never pulled for this.
+
+		POST store/thumbnail  {VolumeID, Path} -> {Image}
+
+	Rendering itself is not this package's business: the core passes
+	Option.Thumbnailer, which runs the ordinary renderers on an OS path.
+*/
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"net/http"
+	"os"
+	"sort"
+
+	"imuslab.com/arozos/mod/cluster/acn"
+	"imuslab.com/arozos/mod/cluster/metadata"
+	"imuslab.com/arozos/mod/filesystem/arozfs"
+)
+
+const (
+	pathThumbnail = acn.BasePath + "/store/thumbnail"
+
+	// ThumbnailConcurrency is how many thumbnails one node renders at once,
+	// for itself and for the nodes asking it together.
+	ThumbnailConcurrency = 2
+	// MaxThumbnailBytes is the largest thumbnail a node sends or accepts.
+	MaxThumbnailBytes = ChunkSize
+)
+
+var (
+	// ErrNoThumbnailer is returned by a node that was started without a
+	// thumbnail renderer.
+	ErrNoThumbnailer = errors.New("this node does not render thumbnails")
+	// ErrNoThumbnailHolder is returned when no online node holding a copy
+	// can render the thumbnail (e.g. none of them has ffmpeg for a video).
+	ErrNoThumbnailHolder = errors.New("no online node holding a copy can render this thumbnail")
+)
+
+type ThumbnailRequest struct {
+	VolumeID string `json:"volumeId"`
+	Path     string `json:"path"`
+}
+
+type ThumbnailResponse struct {
+	Image []byte `json:"image"`
+}
+
+// Thumbnail returns the thumbnail of a namespace file, rendered by a node
+// holding a copy. feature names a tool the renderer needs ("" for none).
+func (s *Service) Thumbnail(ctx context.Context, logical string, feature string) ([]byte, error) {
+	if !s.Ready() {
+		return nil, metadata.ErrNotInCluster
+	}
+	rec, err := s.meta.Stat(logical)
+	if err != nil {
+		return nil, os.ErrNotExist
+	}
+	if rec.IsDir {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	locs := s.orderedLocations(rec)
+	if len(locs) == 0 {
+		return nil, ErrNoHealthyCopy
+	}
+	candidates := s.thumbnailCandidates(locs, feature)
+	if len(candidates) == 0 {
+		return nil, ErrNoThumbnailHolder
+	}
+
+	var lastErr error = ErrNoThumbnailHolder
+	for _, loc := range candidates {
+		var data []byte
+		if loc.NodeID == s.m.NodeID() {
+			data, err = s.renderLocalThumbnail(ctx, loc.VolumeID, rec.Path)
+		} else {
+			data, err = s.remoteThumbnail(ctx, loc, rec.Path)
+		}
+		if err == nil {
+			return data, nil
+		}
+		if errors.Is(err, arozfs.ErrNoThumbnail) || ctx.Err() != nil {
+			return nil, err
+		}
+		lastErr = err
+	}
+	return nil, lastErr
+}
+
+// thumbnailCandidates orders the copies to ask for a thumbnail: this node
+// first, then the other holders nearest first, leaving out the nodes that
+// lack the feature. One entry per node, as a node renders any of its copies.
+func (s *Service) thumbnailCandidates(locs []metadata.Location, feature string) []metadata.Location {
+	views := map[string]struct {
+		latency float64
+		capable bool
+	}{}
+	for _, n := range s.m.NodeViews() {
+		capable := feature == "" || n.Capabilities.Has(feature)
+		views[n.ID] = struct {
+			latency float64
+			capable bool
+		}{n.LatencyMs, capable}
+	}
+
+	me := s.m.NodeID()
+	seen := map[string]bool{}
+	local := []metadata.Location{}
+	remote := []metadata.Location{}
+	for _, loc := range locs {
+		if seen[loc.NodeID] {
+			continue
+		}
+		view, known := views[loc.NodeID]
+		if !known || !view.capable {
+			continue
+		}
+		seen[loc.NodeID] = true
+		if loc.NodeID == me {
+			local = append(local, loc)
+		} else {
+			remote = append(remote, loc)
+		}
+	}
+
+	//Nearest first; a node never measured (-1) goes after the measured ones
+	sort.SliceStable(remote, func(i, j int) bool {
+		a, b := views[remote[i].NodeID].latency, views[remote[j].NodeID].latency
+		if (a < 0) != (b < 0) {
+			return b < 0
+		}
+		return a < b
+	})
+	return append(local, remote...)
+}
+
+// renderLocalThumbnail renders the copy on one of this node's volumes.
+func (s *Service) renderLocalThumbnail(ctx context.Context, volumeID string, logical string) ([]byte, error) {
+	if s.opt.Thumbnailer == nil {
+		return nil, ErrNoThumbnailer
+	}
+	_, real, err := s.localVolumePath(volumeID, logical)
+	if err != nil {
+		return nil, err
+	}
+	info, err := os.Stat(real)
+	if err != nil {
+		return nil, os.ErrNotExist
+	}
+	if info.IsDir() {
+		return nil, arozfs.ErrNoThumbnail
+	}
+
+	select {
+	case s.thumbSem <- struct{}{}:
+		defer func() { <-s.thumbSem }()
+	case <-ctx.Done():
+		return nil, ctx.Err()
+	}
+
+	data, err := s.opt.Thumbnailer(real)
+	if err != nil {
+		return nil, err
+	}
+	if len(data) == 0 {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	if len(data) > MaxThumbnailBytes {
+		return nil, errors.New("thumbnail too large")
+	}
+	return data, nil
+}
+
+// remoteThumbnail asks the node holding loc to render the thumbnail.
+func (s *Service) remoteThumbnail(ctx context.Context, loc metadata.Location, logical string) ([]byte, error) {
+	resp, err := s.client.Transport.DoJSON2(ctx, loc.NodeID, http.MethodPost, pathThumbnail,
+		ThumbnailRequest{VolumeID: loc.VolumeID, Path: logical})
+	if err != nil {
+		return nil, err
+	}
+	if resp.Status == http.StatusUnprocessableEntity {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	if err := resp.Error(); err != nil {
+		return nil, err
+	}
+	var out ThumbnailResponse
+	if err := json.Unmarshal(resp.Body, &out); err != nil {
+		return nil, err
+	}
+	if len(out.Image) == 0 {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	if len(out.Image) > MaxThumbnailBytes {
+		return nil, errors.New("thumbnail too large")
+	}
+	return out.Image, nil
+}
+
+// handleThumbnail renders a thumbnail of a copy on this node for another one.
+func (s *Service) handleThumbnail(w http.ResponseWriter, r *http.Request, sender *acn.SignedIdentity, body []byte) {
+	var req ThumbnailRequest
+	if err := json.Unmarshal(body, &req); err != nil {
+		acn.WriteError(w, http.StatusBadRequest, "invalid request")
+		return
+	}
+	data, err := s.renderLocalThumbnail(r.Context(), req.VolumeID, req.Path)
+	if err != nil {
+		switch {
+		case errors.Is(err, arozfs.ErrNoThumbnail):
+			//The content has no thumbnail: the asking node stops looking
+			acn.WriteError(w, http.StatusUnprocessableEntity, err.Error())
+		case errors.Is(err, ErrNoThumbnailer):
+			acn.WriteError(w, http.StatusNotImplemented, err.Error())
+		default:
+			acn.WriteError(w, statusFor(err), err.Error())
+		}
+		return
+	}
+	acn.WriteJSON(w, ThumbnailResponse{Image: data})
+}

+ 126 - 0
src/mod/cluster/storage/thumbnail_test.go

@@ -0,0 +1,126 @@
+package storage
+
+import (
+	"bytes"
+	"context"
+	"errors"
+	"os"
+	"path/filepath"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"imuslab.com/arozos/mod/filesystem/arozfs"
+)
+
+// countingRenderer renders "thumb:<file name>" and counts its calls. Files
+// named none.* have no thumbnail.
+func countingRenderer(calls *int32) func(string) ([]byte, error) {
+	return func(osPath string) ([]byte, error) {
+		atomic.AddInt32(calls, 1)
+		if _, err := os.Stat(osPath); err != nil {
+			return nil, err
+		}
+		name := filepath.Base(osPath)
+		if name == "none.png" {
+			return nil, arozfs.ErrNoThumbnail
+		}
+		return []byte("thumb:" + name), nil
+	}
+}
+
+func TestThumbnailRenderedByHolder(t *testing.T) {
+	a, b := cluster2(t)
+	var aCalls, bCalls int32
+	a.thumb.Store(countingRenderer(&aCalls))
+	b.thumb.Store(countingRenderer(&bCalls))
+
+	for _, p := range []string{"/pics/a.png", "/pics/none.png"} {
+		if err := a.svc.Write(p, bytes.NewReader([]byte("image")), ""); err != nil {
+			t.Fatalf("write %s: %v", p, err)
+		}
+	}
+	if err := a.svc.Mkdir("/pics/sub", ""); err != nil {
+		t.Fatalf("mkdir: %v", err)
+	}
+	waitFor(t, "b to see the files", 5*time.Second, func() bool {
+		_, err := b.meta.Stat("/pics/none.png")
+		return err == nil
+	})
+
+	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+	defer cancel()
+
+	testcases := []struct {
+		name     string
+		node     *testNode
+		path     string
+		want     string
+		wantErr  error
+		aRenders int32
+		bRenders int32
+	}{
+		//The holder renders its own copy without any request
+		{name: "local copy", node: a, path: "/pics/a.png", want: "thumb:a.png", aRenders: 1},
+		//b holds no copy: a renders it and only the image comes back
+		{name: "remote copy", node: b, path: "/pics/a.png", want: "thumb:a.png", aRenders: 2},
+		//No thumbnail is an answer about the content and comes back as such
+		{name: "no thumbnail remote", node: b, path: "/pics/none.png", wantErr: arozfs.ErrNoThumbnail, aRenders: 3},
+		{name: "no thumbnail local", node: a, path: "/pics/none.png", wantErr: arozfs.ErrNoThumbnail, aRenders: 4},
+		//Folders and missing files never reach a renderer
+		{name: "folder", node: b, path: "/pics/sub", wantErr: arozfs.ErrNoThumbnail, aRenders: 4},
+		{name: "missing", node: b, path: "/pics/missing.png", wantErr: os.ErrNotExist, aRenders: 4},
+	}
+	for _, tc := range testcases {
+		data, err := tc.node.svc.Thumbnail(ctx, tc.path, "")
+		if tc.wantErr != nil {
+			if !errors.Is(err, tc.wantErr) {
+				t.Errorf("%s: expected %v, got %v (%q)", tc.name, tc.wantErr, err, data)
+			}
+		} else if err != nil || string(data) != tc.want {
+			t.Errorf("%s: got %q, %v; wanted %q", tc.name, data, err, tc.want)
+		}
+		if got := atomic.LoadInt32(&aCalls); got != tc.aRenders {
+			t.Errorf("%s: a rendered %d times in total, wanted %d", tc.name, got, tc.aRenders)
+		}
+		if got := atomic.LoadInt32(&bCalls); got != tc.bRenders {
+			t.Errorf("%s: b rendered %d times in total, wanted %d", tc.name, got, tc.bRenders)
+		}
+	}
+}
+
+func TestThumbnailHolderLimits(t *testing.T) {
+	a, b := cluster2(t)
+	if err := a.svc.Write("/v/clip.mp4", bytes.NewReader([]byte("video")), ""); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+	waitFor(t, "b to see the file", 5*time.Second, func() bool {
+		_, err := b.meta.Stat("/v/clip.mp4")
+		return err == nil
+	})
+	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+	defer cancel()
+
+	//The only holder has no renderer: a failure, but not "no thumbnail",
+	//since another node could still render it later
+	_, err := b.svc.Thumbnail(ctx, "/v/clip.mp4", "")
+	if err == nil || errors.Is(err, arozfs.ErrNoThumbnail) {
+		t.Errorf("a holder without a renderer should fail with a retryable error, got %v", err)
+	}
+
+	//A holder that lacks the tool the format needs is not asked at all
+	var calls int32
+	a.thumb.Store(countingRenderer(&calls))
+	if _, err := b.svc.Thumbnail(ctx, "/v/clip.mp4", "no-such-feature"); !errors.Is(err, ErrNoThumbnailHolder) {
+		t.Errorf("expected ErrNoThumbnailHolder, got %v", err)
+	}
+	if atomic.LoadInt32(&calls) != 0 {
+		t.Errorf("a holder without the feature was asked to render")
+	}
+
+	//An oversized thumbnail is refused rather than passed on
+	a.thumb.Store(func(string) ([]byte, error) { return make([]byte, MaxThumbnailBytes+1), nil })
+	if _, err := a.svc.Thumbnail(ctx, "/v/clip.mp4", ""); err == nil {
+		t.Error("an oversized thumbnail should be refused")
+	}
+}

+ 2 - 0
src/mod/cluster/storage/transfer_server.go

@@ -14,6 +14,7 @@ package storage
 		GET  store/list?volume=&path=
 		POST store/checksum   {VolumeID, Path}
 		POST store/place      {Size, Path, PreferNode, PreferVolume} (leader only)
+		POST store/thumbnail  {VolumeID, Path} -> {Image}   (thumbnail.go)
 */
 
 import (
@@ -128,6 +129,7 @@ func (s *Service) registerACNHandlers() {
 	srv.HandleFunc(pathList, s.handleList)
 	srv.HandleFunc(pathChecksum, s.handleChecksum)
 	srv.HandleFunc(pathPlace, s.handlePlace)
+	srv.HandleFunc(pathThumbnail, s.handleThumbnail)
 }
 
 // localVolumePath resolves a request onto a local volume path.

+ 26 - 0
src/mod/filesystem/abstractions/clusterfs/clusterfs.go

@@ -53,6 +53,14 @@ type InfoBackend interface {
 	StorageInfo(logical string) (arozfs.StorageInfo, error)
 }
 
+// ThumbnailBackend is an optional Backend extension: a backend that
+// implements it has thumbnails rendered by a node holding a copy of the file,
+// which makes the abstraction an arozfs.ThumbnailRenderer.
+type ThumbnailBackend interface {
+	ThumbnailKey(logical string) (string, error)
+	RenderThumbnail(logical string) ([]byte, error)
+}
+
 var errUnsupported = errors.New("filesystem type not supported")
 
 var errNoStorageInfo = errors.New("storage info not available")
@@ -300,6 +308,24 @@ func (c *ClusterFileSystem) StorageInfo(p string) (arozfs.StorageInfo, error) {
 	return backend.StorageInfo(normalize(p))
 }
 
+// ThumbnailKey identifies the content of a file for the thumbnail cache.
+func (c *ClusterFileSystem) ThumbnailKey(p string) (string, error) {
+	backend, ok := c.backend.(ThumbnailBackend)
+	if !ok {
+		return "", arozfs.ErrNoThumbnail
+	}
+	return backend.ThumbnailKey(normalize(p))
+}
+
+// RenderThumbnail has a node holding a copy of the file render its thumbnail.
+func (c *ClusterFileSystem) RenderThumbnail(p string) ([]byte, error) {
+	backend, ok := c.backend.(ThumbnailBackend)
+	if !ok {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	return backend.RenderThumbnail(normalize(p))
+}
+
 func (c *ClusterFileSystem) Heartbeat() error {
 	if !c.backend.Ready() {
 		return errors.New("cluster storage not ready")

+ 73 - 0
src/mod/filesystem/abstractions/clusterfs/clusterfs_test.go

@@ -307,3 +307,76 @@ func TestStorageInfoErrors(t *testing.T) {
 		t.Error("Expected an error from a backend that does not report storage info")
 	}
 }
+
+// thumbBackend is a fakeBackend whose files have thumbnails.
+type thumbBackend struct {
+	*fakeBackend
+	keys map[string]string
+	last string
+}
+
+func (b *thumbBackend) ThumbnailKey(logical string) (string, error) {
+	b.last = logical
+	key, ok := b.keys[logical]
+	if !ok {
+		return "", errors.New("no such record")
+	}
+	return key, nil
+}
+
+func (b *thumbBackend) RenderThumbnail(logical string) ([]byte, error) {
+	b.last = logical
+	if _, ok := b.keys[logical]; !ok {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	return []byte("image of " + logical), nil
+}
+
+func TestThumbnailFromBackend(t *testing.T) {
+	backend := &thumbBackend{fakeBackend: newFake(), keys: map[string]string{"/v/a.mp4": "sha-a"}}
+	var c interface{} = New("cluster", backend)
+	r, ok := c.(arozfs.ThumbnailRenderer)
+	if !ok {
+		t.Fatal("ClusterFileSystem should be an arozfs.ThumbnailRenderer")
+	}
+
+	testcases := []struct {
+		given   string
+		wantKey string
+		wantErr bool
+	}{
+		{"cluster:/v/a.mp4", "sha-a", false},
+		{"/v/a.mp4", "sha-a", false},
+		{"v/a.mp4", "sha-a", false},
+		{"/v/missing.mp4", "", true},
+	}
+	for _, tc := range testcases {
+		key, err := r.ThumbnailKey(tc.given)
+		if (err != nil) != tc.wantErr || key != tc.wantKey {
+			t.Errorf("ThumbnailKey(%q) = %q, %v; wanted %q (error %v)", tc.given, key, err, tc.wantKey, tc.wantErr)
+		}
+		data, err := r.RenderThumbnail(tc.given)
+		if tc.wantErr {
+			if !errors.Is(err, arozfs.ErrNoThumbnail) {
+				t.Errorf("RenderThumbnail(%q) should report ErrNoThumbnail, got %v", tc.given, err)
+			}
+			continue
+		}
+		if err != nil || string(data) != "image of /v/a.mp4" {
+			t.Errorf("RenderThumbnail(%q) = %q, %v", tc.given, data, err)
+		}
+		if backend.last != "/v/a.mp4" {
+			t.Errorf("RenderThumbnail(%q) asked the backend for %q", tc.given, backend.last)
+		}
+	}
+}
+
+func TestThumbnailWithoutBackendSupport(t *testing.T) {
+	c := New("cluster", newFake())
+	if _, err := c.ThumbnailKey("/v/a.mp4"); !errors.Is(err, arozfs.ErrNoThumbnail) {
+		t.Errorf("ThumbnailKey on a plain backend should report ErrNoThumbnail, got %v", err)
+	}
+	if _, err := c.RenderThumbnail("/v/a.mp4"); !errors.Is(err, arozfs.ErrNoThumbnail) {
+		t.Errorf("RenderThumbnail on a plain backend should report ErrNoThumbnail, got %v", err)
+	}
+}

+ 38 - 0
src/mod/filesystem/arozfs/thumbnail.go

@@ -0,0 +1,38 @@
+package arozfs
+
+import "errors"
+
+/*
+	Thumbnails of files that are not on this host
+
+	The thumbnail renderer (mod/filesystem/metadata) works on files it can
+	open, and keeps each thumbnail in a .metadata/.cache folder next to the
+	file. Neither works on a drive whose files live somewhere else: reading
+	a whole video over the network to take one frame is wasteful, and
+	writing the cache back into the drive turns a throwaway image into a
+	file that drive has to store (and, on cluster:/, replicate).
+
+	A file system abstraction that can have a thumbnail made where the file
+	is stored implements ThumbnailRenderer. The renderer then asks it for
+	the image, and keeps the result in a cache on this host, keyed by what
+	ThumbnailKey reports rather than by path, so the cache never lives in
+	the drive itself. Abstractions that cannot are left out and keep the
+	usual behaviour.
+*/
+
+// ErrNoThumbnail is returned by RenderThumbnail when the file has no
+// thumbnail to give (an unsupported format, or audio without cover art). It
+// is a property of the content, so asking again will not change the answer.
+var ErrNoThumbnail = errors.New("no thumbnail for this file")
+
+// ThumbnailRenderer is implemented by file system abstractions that can have
+// a thumbnail rendered by whatever holds the file.
+type ThumbnailRenderer interface {
+	// ThumbnailKey identifies the content of a file. Two calls return the
+	// same key only while the content is the same, so a cached thumbnail
+	// found under the key is still current.
+	ThumbnailKey(realpath string) (string, error)
+
+	// RenderThumbnail returns the encoded (JPEG or PNG) thumbnail of a file.
+	RenderThumbnail(realpath string) ([]byte, error)
+}

+ 280 - 0
src/mod/filesystem/metadata/external.go

@@ -0,0 +1,280 @@
+package metadata
+
+/*
+	Thumbnails of drives that render them where the file is stored
+
+	A drive whose abstraction implements arozfs.ThumbnailRenderer (cluster:/
+	for now) does not get a .metadata/.cache folder: the thumbnail is made by
+	whatever holds the file, and the result is kept in a cache folder on this
+	host, named after the key the abstraction gives for the content. The key
+	changes with the content, so a cached thumbnail never goes stale; old
+	ones are removed by PruneExternalCache once nobody has looked at them for
+	a while.
+
+	RenderLocalFile is the other half: it runs the ordinary renderers on a
+	file this host can open by its OS path, which is what the holder of a
+	copy does when another host asks it for a thumbnail.
+*/
+
+import (
+	"crypto/sha256"
+	"encoding/base64"
+	"encoding/hex"
+	"errors"
+	"os"
+	"path/filepath"
+	"strings"
+	"sync"
+	"time"
+
+	"imuslab.com/arozos/mod/filesystem"
+	"imuslab.com/arozos/mod/filesystem/abstractions/localfs"
+	"imuslab.com/arozos/mod/filesystem/arozfs"
+)
+
+const (
+	//externalFailureTTL is how long a file with no thumbnail is not asked
+	//for again, so a folder that is opened repeatedly does not send the same
+	//failing request to another host every time. A failure that may pass (a
+	//holder offline, a timeout) is retried sooner.
+	externalFailureTTL      = 10 * time.Minute
+	externalRetryFailureTTL = time.Minute
+	//externalRenderWait bounds how long a second request for a thumbnail
+	//that is being rendered waits for the first one.
+	externalRenderWait = 2 * time.Minute
+	//MaxThumbnailSize is the largest thumbnail accepted from a renderer.
+	MaxThumbnailSize = 4 << 20
+)
+
+var (
+	externalCacheMu  sync.RWMutex
+	externalCacheDir = filepath.Join(os.TempDir(), "arozos-thumbnails")
+)
+
+// SetExternalCacheDir sets the folder that keeps the thumbnails of drives
+// implementing arozfs.ThumbnailRenderer.
+func SetExternalCacheDir(dir string) {
+	externalCacheMu.Lock()
+	defer externalCacheMu.Unlock()
+	externalCacheDir = filepath.Clean(dir)
+}
+
+// ExternalCacheDir returns the folder set by SetExternalCacheDir.
+func ExternalCacheDir() string {
+	externalCacheMu.RLock()
+	defer externalCacheMu.RUnlock()
+	return externalCacheDir
+}
+
+// thumbnailRendererOf returns the renderer of a drive, if it has one.
+func thumbnailRendererOf(fsh *filesystem.FileSystemHandler) (arozfs.ThumbnailRenderer, bool) {
+	if fsh == nil || fsh.FileSystemAbstraction == nil {
+		return nil, false
+	}
+	r, ok := fsh.FileSystemAbstraction.(arozfs.ThumbnailRenderer)
+	return r, ok
+}
+
+// externalCachePath is where the thumbnail for a content key is kept. The key
+// is hashed so that whatever characters an abstraction puts in it, the file
+// name is safe, and the first two characters spread the files over folders.
+func externalCachePath(key string) string {
+	sum := sha256.Sum256([]byte(key))
+	name := hex.EncodeToString(sum[:])
+	return filepath.Join(ExternalCacheDir(), name[:2], name+".thumb")
+}
+
+// externalCacheFile returns the cache path of a file and whether the
+// thumbnail is there.
+func externalCacheFile(r arozfs.ThumbnailRenderer, rpath string) (string, bool) {
+	if !ThumbnailSupported(rpath) {
+		return "", false
+	}
+	key, err := r.ThumbnailKey(rpath)
+	if err != nil || key == "" {
+		return "", false
+	}
+	cachePath := externalCachePath(key)
+	info, err := os.Stat(cachePath)
+	return cachePath, err == nil && !info.IsDir()
+}
+
+// renderFlight is one thumbnail being rendered, which other requests for
+// the same content wait for instead of rendering it again.
+type renderFlight struct {
+	done chan struct{}
+	data []byte
+	err  error
+}
+
+// loadExternalCache is LoadCache for a drive implementing ThumbnailRenderer.
+func (rh *RenderHandler) loadExternalCache(r arozfs.ThumbnailRenderer, rpath string, generateOnly bool) (string, error) {
+	if !ThumbnailSupported(rpath) {
+		return "", errors.New("no supported format")
+	}
+	key, err := r.ThumbnailKey(rpath)
+	if err != nil {
+		return "", err
+	}
+	if key == "" {
+		return "", errors.New("no content key for this file")
+	}
+	cachePath := externalCachePath(key)
+
+	if data, err := os.ReadFile(cachePath); err == nil {
+		//Refresh the time so the pruning keeps thumbnails that are in use
+		now := time.Now()
+		os.Chtimes(cachePath, now, now)
+		if generateOnly {
+			return "", nil
+		}
+		return base64.StdEncoding.EncodeToString(data), nil
+	}
+
+	if until, ok := rh.externalFailures.Load(key); ok {
+		if time.Now().Before(until.(time.Time)) {
+			return "", errors.New("thumbnail rendering failed recently")
+		}
+		rh.externalFailures.Delete(key)
+	}
+
+	data, err := rh.renderExternal(r, rpath, key, cachePath)
+	if err != nil {
+		return "", err
+	}
+	if generateOnly {
+		return "", nil
+	}
+	return base64.StdEncoding.EncodeToString(data), nil
+}
+
+// renderExternal asks the drive for a thumbnail and keeps it, making sure
+// one piece of content is rendered once however many requests want it.
+func (rh *RenderHandler) renderExternal(r arozfs.ThumbnailRenderer, rpath string, key string, cachePath string) ([]byte, error) {
+	flight := &renderFlight{done: make(chan struct{})}
+	if existing, loaded := rh.externalFlights.LoadOrStore(key, flight); loaded {
+		other := existing.(*renderFlight)
+		select {
+		case <-other.done:
+			return other.data, other.err
+		case <-time.After(externalRenderWait):
+			return nil, errors.New("timed out waiting for the thumbnail")
+		}
+	}
+	defer func() {
+		close(flight.done)
+		rh.externalFlights.Delete(key)
+	}()
+
+	data, err := r.RenderThumbnail(rpath)
+	if err == nil && len(data) == 0 {
+		err = arozfs.ErrNoThumbnail
+	}
+	if err == nil && len(data) > MaxThumbnailSize {
+		err = errors.New("thumbnail too large")
+	}
+	if err != nil {
+		ttl := externalRetryFailureTTL
+		if errors.Is(err, arozfs.ErrNoThumbnail) {
+			ttl = externalFailureTTL
+		}
+		rh.externalFailures.Store(key, time.Now().Add(ttl))
+		flight.err = err
+		return nil, err
+	}
+	//A failed write only means the thumbnail is not kept for next time
+	writeFileAtomic(cachePath, data)
+	flight.data = data
+	return data, nil
+}
+
+// writeFileAtomic writes to a temporary file next to path and renames it in
+// place, so a reader never sees half a thumbnail.
+func writeFileAtomic(path string, data []byte) error {
+	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+		return err
+	}
+	tmp, err := os.CreateTemp(filepath.Dir(path), ".render-*")
+	if err != nil {
+		return err
+	}
+	tmpName := tmp.Name()
+	if _, err := tmp.Write(data); err != nil {
+		tmp.Close()
+		os.Remove(tmpName)
+		return err
+	}
+	if err := tmp.Close(); err != nil {
+		os.Remove(tmpName)
+		return err
+	}
+	if err := os.Rename(tmpName, path); err != nil {
+		os.Remove(tmpName)
+		return err
+	}
+	return nil
+}
+
+// PruneExternalCache removes the kept thumbnails that have not been used for
+// maxAge, and returns how many it removed.
+func PruneExternalCache(maxAge time.Duration) int {
+	root := ExternalCacheDir()
+	cutoff := time.Now().Add(-maxAge)
+	removed := 0
+	filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
+		if err != nil || info.IsDir() {
+			return nil
+		}
+		if info.ModTime().Before(cutoff) {
+			if os.Remove(p) == nil {
+				removed++
+			}
+		}
+		return nil
+	})
+	return removed
+}
+
+// RenderLocalFile renders the thumbnail of a file this host can open by its OS
+// path and returns the encoded image. The renderers write their output into a
+// scratch folder, never next to the file.
+func RenderLocalFile(osPath string) ([]byte, error) {
+	info, err := os.Stat(osPath)
+	if err != nil {
+		return nil, err
+	}
+	if info.IsDir() || !ThumbnailSupported(osPath) {
+		return nil, arozfs.ErrNoThumbnail
+	}
+
+	scratch, err := os.MkdirTemp("", "arozos-thumb-")
+	if err != nil {
+		return nil, err
+	}
+	defer os.RemoveAll(scratch)
+
+	dir := filepath.Dir(osPath)
+	fsh := &filesystem.FileSystemHandler{
+		Name:                  "thumbnail",
+		UUID:                  "thumbnail",
+		Path:                  dir,
+		Hierarchy:             "public",
+		ReadOnly:              true,
+		InitiationTime:        time.Now().Unix(),
+		FileSystemAbstraction: localfs.NewLocalFileSystemAbstraction("thumbnail", dir, "public", true),
+		Filesystem:            "ext4",
+	}
+	cacheFolder := filepath.ToSlash(scratch)
+	if !strings.HasSuffix(cacheFolder, "/") {
+		cacheFolder += "/"
+	}
+
+	encoded, err := renderThumbnail(fsh, cacheFolder, filepath.ToSlash(osPath), false)
+	if err != nil {
+		return nil, err
+	}
+	if encoded == "" {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	return base64.StdEncoding.DecodeString(encoded)
+}

+ 298 - 0
src/mod/filesystem/metadata/external_test.go

@@ -0,0 +1,298 @@
+package metadata
+
+import (
+	"bytes"
+	"encoding/base64"
+	"errors"
+	"image/jpeg"
+	"os"
+	"path/filepath"
+	"sync"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"imuslab.com/arozos/mod/filesystem"
+	"imuslab.com/arozos/mod/filesystem/abstractions/localfs"
+	"imuslab.com/arozos/mod/filesystem/arozfs"
+)
+
+// renderingFS is a local abstraction that also renders thumbnails itself,
+// the way cluster:/ does, and counts how often it is asked to.
+type renderingFS struct {
+	localfs.LocalFileSystemAbstraction
+	keys   map[string]string //path -> content key
+	images map[string][]byte //path -> thumbnail, missing = ErrNoThumbnail
+	delay  time.Duration
+	calls  int32
+}
+
+func (r *renderingFS) ThumbnailKey(p string) (string, error) {
+	key, ok := r.keys[p]
+	if !ok {
+		return "", os.ErrNotExist
+	}
+	return key, nil
+}
+
+func (r *renderingFS) RenderThumbnail(p string) ([]byte, error) {
+	atomic.AddInt32(&r.calls, 1)
+	time.Sleep(r.delay)
+	img, ok := r.images[p]
+	if !ok {
+		return nil, arozfs.ErrNoThumbnail
+	}
+	return img, nil
+}
+
+// newRenderingFSH returns a drive backed by renderingFS, with the external
+// cache in a temporary folder for the length of the test.
+func newRenderingFSH(t *testing.T) (*filesystem.FileSystemHandler, *renderingFS, string) {
+	t.Helper()
+	dir := t.TempDir()
+	previous := ExternalCacheDir()
+	SetExternalCacheDir(filepath.Join(t.TempDir(), "thumbs"))
+	t.Cleanup(func() { SetExternalCacheDir(previous) })
+
+	abs := &renderingFS{
+		LocalFileSystemAbstraction: localfs.NewLocalFileSystemAbstraction("REMOTE", dir+"/", "public", false),
+		keys:                       map[string]string{},
+		images:                     map[string][]byte{},
+	}
+	fsh := &filesystem.FileSystemHandler{
+		Name:                  "remote",
+		UUID:                  "REMOTE",
+		Path:                  dir + "/",
+		Hierarchy:             "public",
+		RequireBuffer:         true,
+		InitiationTime:        time.Now().Unix(),
+		FileSystemAbstraction: abs,
+		Filesystem:            "cluster",
+	}
+	return fsh, abs, dir
+}
+
+func TestThumbnailSupportedAndFeature(t *testing.T) {
+	testcases := []struct {
+		name      string
+		supported bool
+		feature   string
+	}{
+		{"photo.JPG", true, ""},
+		{"photo.webp", true, ""},
+		{"raw.CR2", true, ""},
+		{"song.mp3", true, ""},
+		{"clip.mp4", true, "ffmpeg"},
+		{"clip.MKV", true, "ffmpeg"},
+		{"model.stl", true, ""},
+		{"print.gcode", true, ""},
+		{"art.psd", true, ""},
+		{"logo.svg", true, ""},
+		{"notes.txt", false, ""},
+		{"noextension", false, ""},
+	}
+	for _, tc := range testcases {
+		if got := ThumbnailSupported(tc.name); got != tc.supported {
+			t.Errorf("ThumbnailSupported(%q) = %v, wanted %v", tc.name, got, tc.supported)
+		}
+		if got := ThumbnailFeature(tc.name); got != tc.feature {
+			t.Errorf("ThumbnailFeature(%q) = %q, wanted %q", tc.name, got, tc.feature)
+		}
+	}
+}
+
+func TestRenderLocalFile(t *testing.T) {
+	dir := t.TempDir()
+	png := createSmallPNG(t, dir, "pic.png")
+	txt := filepath.Join(dir, "notes.txt")
+	os.WriteFile(txt, []byte("hello"), 0644)
+
+	data, err := RenderLocalFile(png)
+	if err != nil {
+		t.Fatalf("RenderLocalFile(png) failed: %v", err)
+	}
+	img, err := jpeg.Decode(bytes.NewReader(data))
+	if err != nil {
+		t.Fatalf("thumbnail is not a JPEG: %v", err)
+	}
+	if b := img.Bounds(); b.Dx() != 480 || b.Dy() != 480 {
+		t.Errorf("thumbnail is %dx%d, wanted 480x480", b.Dx(), b.Dy())
+	}
+
+	//The renderers work in a scratch folder, never next to the file
+	if _, err := os.Stat(filepath.Join(dir, ".metadata")); !os.IsNotExist(err) {
+		t.Errorf("RenderLocalFile left a .metadata folder next to the file")
+	}
+
+	testcases := []struct {
+		name   string
+		path   string
+		noThmb bool
+	}{
+		{"unsupported format", txt, true},
+		{"folder", dir, true},
+		{"missing file", filepath.Join(dir, "missing.png"), false},
+	}
+	for _, tc := range testcases {
+		_, err := RenderLocalFile(tc.path)
+		if err == nil {
+			t.Errorf("%s: expected an error", tc.name)
+			continue
+		}
+		if errors.Is(err, arozfs.ErrNoThumbnail) != tc.noThmb {
+			t.Errorf("%s: ErrNoThumbnail = %v, wanted %v (%v)", tc.name, !tc.noThmb, tc.noThmb, err)
+		}
+	}
+}
+
+func TestLoadCacheFromRenderingDrive(t *testing.T) {
+	fsh, abs, dir := newRenderingFSH(t)
+	rh := NewRenderHandler()
+	file := filepath.ToSlash(filepath.Join(dir, "clip.mp4"))
+	abs.keys[file] = "sha-1"
+	abs.images[file] = []byte("frame one")
+
+	//First load renders, the second is served from this host's cache
+	for i := 0; i < 2; i++ {
+		got, err := rh.LoadCache(fsh, file, false)
+		if err != nil {
+			t.Fatalf("LoadCache #%d failed: %v", i+1, err)
+		}
+		if decoded, _ := base64.StdEncoding.DecodeString(got); string(decoded) != "frame one" {
+			t.Errorf("LoadCache #%d returned %q", i+1, decoded)
+		}
+	}
+	if abs.calls != 1 {
+		t.Errorf("rendered %d times, wanted once", abs.calls)
+	}
+	if !CacheExists(fsh, file) {
+		t.Error("CacheExists should see the kept thumbnail")
+	}
+
+	//Nothing is written into the drive
+	if _, err := os.Stat(filepath.Join(dir, ".metadata")); !os.IsNotExist(err) {
+		t.Error("a .metadata folder was created inside the drive")
+	}
+
+	//New content, new key: rendered again rather than served stale
+	abs.keys[file] = "sha-2"
+	abs.images[file] = []byte("frame two")
+	if CacheExists(fsh, file) {
+		t.Error("CacheExists should not match a thumbnail of the old content")
+	}
+	got, err := rh.LoadCache(fsh, file, false)
+	if decoded, _ := base64.StdEncoding.DecodeString(got); err != nil || string(decoded) != "frame two" {
+		t.Errorf("after a content change got %q, %v", decoded, err)
+	}
+
+	//Cache path and removal do not apply to a drive cached by content
+	if _, err := GetCacheFilePath(fsh, file); err == nil {
+		t.Error("GetCacheFilePath should not hand out a host path for this drive")
+	}
+	if err := RemoveCache(fsh, file); err != nil {
+		t.Errorf("RemoveCache should be a no-op, got %v", err)
+	}
+
+	//generateOnly renders but returns nothing
+	other := filepath.ToSlash(filepath.Join(dir, "b.jpg"))
+	abs.keys[other] = "sha-b"
+	abs.images[other] = []byte("b")
+	if got, err := rh.LoadCache(fsh, other, true); err != nil || got != "" {
+		t.Errorf("generateOnly returned %q, %v", got, err)
+	}
+	if !CacheExists(fsh, other) {
+		t.Error("generateOnly should still keep the thumbnail")
+	}
+}
+
+func TestLoadCacheRenderingDriveFailures(t *testing.T) {
+	fsh, abs, dir := newRenderingFSH(t)
+	rh := NewRenderHandler()
+
+	//Unsupported formats and folders never reach the renderer
+	notes := filepath.ToSlash(filepath.Join(dir, "notes.txt"))
+	abs.keys[notes] = "sha-notes"
+	if _, err := rh.LoadCache(fsh, notes, false); err == nil {
+		t.Error("expected an error for an unsupported format")
+	}
+
+	//A file with no thumbnail is not asked for again straight away
+	song := filepath.ToSlash(filepath.Join(dir, "song.mp3"))
+	abs.keys[song] = "sha-song"
+	for i := 0; i < 3; i++ {
+		if _, err := rh.LoadCache(fsh, song, false); err == nil {
+			t.Errorf("LoadCache #%d of a file without thumbnail should fail", i+1)
+		}
+	}
+	if abs.calls != 1 {
+		t.Errorf("renderer asked %d times, wanted once", abs.calls)
+	}
+
+	//A file the drive has no key for fails without rendering
+	if _, err := rh.LoadCache(fsh, filepath.ToSlash(filepath.Join(dir, "gone.png")), false); err == nil {
+		t.Error("expected an error for a file without a content key")
+	}
+	if abs.calls != 1 {
+		t.Errorf("renderer asked %d times, wanted once", abs.calls)
+	}
+}
+
+func TestLoadCacheRenderingDriveRendersOnce(t *testing.T) {
+	fsh, abs, dir := newRenderingFSH(t)
+	abs.delay = 200 * time.Millisecond
+	rh := NewRenderHandler()
+	file := filepath.ToSlash(filepath.Join(dir, "clip.mp4"))
+	abs.keys[file] = "sha-1"
+	abs.images[file] = []byte("frame")
+
+	//Several viewers opening the same folder wait for one render
+	var wg sync.WaitGroup
+	errs := make(chan error, 5)
+	for i := 0; i < 5; i++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			got, err := rh.LoadCache(fsh, file, false)
+			if err == nil && got == "" {
+				err = errors.New("empty thumbnail")
+			}
+			errs <- err
+		}()
+	}
+	wg.Wait()
+	close(errs)
+	for err := range errs {
+		if err != nil {
+			t.Errorf("concurrent LoadCache failed: %v", err)
+		}
+	}
+	if n := atomic.LoadInt32(&abs.calls); n != 1 {
+		t.Errorf("rendered %d times for concurrent requests, wanted once", n)
+	}
+}
+
+func TestPruneExternalCache(t *testing.T) {
+	previous := ExternalCacheDir()
+	SetExternalCacheDir(t.TempDir())
+	t.Cleanup(func() { SetExternalCacheDir(previous) })
+
+	oldPath := externalCachePath("old")
+	newPath := externalCachePath("new")
+	for _, p := range []string{oldPath, newPath} {
+		if err := writeFileAtomic(p, []byte("x")); err != nil {
+			t.Fatalf("writeFileAtomic: %v", err)
+		}
+	}
+	past := time.Now().Add(-48 * time.Hour)
+	os.Chtimes(oldPath, past, past)
+
+	if removed := PruneExternalCache(24 * time.Hour); removed != 1 {
+		t.Errorf("PruneExternalCache removed %d files, wanted 1", removed)
+	}
+	if _, err := os.Stat(oldPath); !os.IsNotExist(err) {
+		t.Error("the unused thumbnail was kept")
+	}
+	if _, err := os.Stat(newPath); err != nil {
+		t.Errorf("a recent thumbnail was removed: %v", err)
+	}
+}

+ 88 - 60
src/mod/filesystem/metadata/metadata.go

@@ -39,6 +39,10 @@ func IsRawImageFile(filePath string) bool {
 type RenderHandler struct {
 	renderingFiles  sync.Map
 	renderingFolder sync.Map
+
+	//Drives that render thumbnails where the file is stored (external.go)
+	externalFlights  sync.Map //content key -> *renderFlight
+	externalFailures sync.Map //content key -> time until it is tried again
 }
 
 // Create a new RenderHandler
@@ -64,6 +68,11 @@ func (rh *RenderHandler) BuildCacheForFolder(fsh *filesystem.FileSystemHandler,
 		rh.LoadCache(fsh, filepath.Join(rpath, fi.Name()), true)
 	}
 
+	if _, ok := thumbnailRendererOf(fsh); ok {
+		//This drive has no cache folder of its own
+		return nil
+	}
+
 	//Check if the cache folder has file. If not, remove it
 	cachedFiles, _ := fshAbs.ReadDir(filepath.ToSlash(filepath.Join(filepath.Clean(rpath), "/.metadata/.cache/")))
 	if len(cachedFiles) == 0 {
@@ -86,6 +95,11 @@ func (rh *RenderHandler) LoadCacheAsBytes(fsh *filesystem.FileSystemHandler, vpa
 
 // Try to load a cache from file. If not exists, generate it now
 func (rh *RenderHandler) LoadCache(fsh *filesystem.FileSystemHandler, rpath string, generateOnly bool) (string, error) {
+	if r, ok := thumbnailRendererOf(fsh); ok {
+		//Rendered where the file is stored and cached on this host
+		return rh.loadExternalCache(r, rpath, generateOnly)
+	}
+
 	//Create a cache folder
 	fshAbs := fsh.FileSystemAbstraction
 	cacheFolder := filepath.ToSlash(filepath.Join(filepath.Clean(filepath.Dir(rpath)), "/.metadata/.cache/") + "/")
@@ -148,81 +162,82 @@ func (rh *RenderHandler) checkCacheNeeded(fsh *filesystem.FileSystemHandler, rpa
 	return true, "", nil
 }
 
-func (rh *RenderHandler) generateCache(fsh *filesystem.FileSystemHandler, cacheFolder string, rpath string, generateOnly bool) (string, error) {
-	//Cache image not exists. Set this file to busy
-	rh.renderingFiles.Store(rpath, "busy")
-
-	//That object not exists. Generate cache image
+// Formats with a thumbnail renderer, by the extension of the file
+var (
 	//Audio formats that might contains id4 thumbnail
-	id4Formats := []string{".mp3", ".ogg", ".flac"}
-	if utils.StringInArray(id4Formats, strings.ToLower(filepath.Ext(rpath))) {
-		img, err := generateThumbnailForAudio(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
-	}
-
-	//Generate resized image for images
-	imageFormats := []string{".png", ".jpeg", ".jpg", ".webp"}
-	if utils.StringInArray(imageFormats, strings.ToLower(filepath.Ext(rpath))) {
-		img, err := generateThumbnailForImage(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
-	}
-
-	//RAW image formats (Sony, Canon, Nikon, etc.)
-	if IsRawImageFile(rpath) {
-		img, err := generateThumbnailForRAW(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
-	}
-
+	audioThumbnailFormats = []string{".mp3", ".ogg", ".flac"}
+	imageThumbnailFormats = []string{".png", ".jpeg", ".jpg", ".webp"}
 	//Video formats, extract from the 5 sec mark
-	vidFormats := []string{".mkv", ".mp4", ".webm", ".ogv", ".avi", ".rmvb"}
-	if utils.StringInArray(vidFormats, strings.ToLower(filepath.Ext(rpath))) {
-		img, err := generateThumbnailForVideo(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
-	}
+	videoThumbnailFormats = []string{".mkv", ".mp4", ".webm", ".ogv", ".avi", ".rmvb"}
+	modelThumbnailFormats = []string{".stl", ".obj"}
+	//Sliced G-code, which carries a slicer generated preview in its header
+	gcodeThumbnailFormats = []string{".gcode", ".gco"}
+)
 
-	//3D Model Formats
-	modelFormats := []string{".stl", ".obj"}
-	if utils.StringInArray(modelFormats, strings.ToLower(filepath.Ext(rpath))) {
-		img, err := generateThumbnailForModel(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
+// ThumbnailSupported reports whether a file of this name has a thumbnail
+// renderer. Folders are not covered: their preview is built from the
+// thumbnails of the files inside them.
+func ThumbnailSupported(filename string) bool {
+	ext := strings.ToLower(filepath.Ext(filename))
+	for _, formats := range [][]string{audioThumbnailFormats, imageThumbnailFormats,
+		videoThumbnailFormats, modelThumbnailFormats, gcodeThumbnailFormats} {
+		if utils.StringInArray(formats, ext) {
+			return true
+		}
 	}
+	return IsRawImageFile(filename) || ext == ".psd" || ext == ".svg"
+}
 
-	//Sliced G-code, which carries a slicer generated preview in its header
-	gcodeFormats := []string{".gcode", ".gco"}
-	if utils.StringInArray(gcodeFormats, strings.ToLower(filepath.Ext(rpath))) {
-		img, err := generateThumbnailForGcode(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
+// ThumbnailFeature names the host tool a thumbnail of this file needs, or ""
+// when the built in renderers are enough. It uses the feature names of the
+// cluster capability manifests.
+func ThumbnailFeature(filename string) string {
+	if utils.StringInArray(videoThumbnailFormats, strings.ToLower(filepath.Ext(filename))) {
+		return "ffmpeg"
 	}
+	return ""
+}
 
-	//Photoshop file
-	if strings.ToLower(filepath.Ext(rpath)) == ".psd" {
-		img, err := generateThumbnailForPSD(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
-	}
+func (rh *RenderHandler) generateCache(fsh *filesystem.FileSystemHandler, cacheFolder string, rpath string, generateOnly bool) (string, error) {
+	//Cache image not exists. Set this file to busy
+	rh.renderingFiles.Store(rpath, "busy")
+	defer rh.renderingFiles.Delete(rpath)
+	return renderThumbnail(fsh, cacheFolder, rpath, generateOnly)
+}
 
-	//SVG file
-	if strings.ToLower(filepath.Ext(rpath)) == ".svg" {
-		img, err := generateThumbnailForSVG(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
+// renderThumbnail picks the renderer for a file and writes its thumbnail into
+// cacheFolder, which ends with a slash.
+func renderThumbnail(fsh *filesystem.FileSystemHandler, cacheFolder string, rpath string, generateOnly bool) (string, error) {
+	ext := strings.ToLower(filepath.Ext(rpath))
+	switch {
+	case utils.StringInArray(audioThumbnailFormats, ext):
+		return generateThumbnailForAudio(fsh, cacheFolder, rpath, generateOnly)
+	case utils.StringInArray(imageThumbnailFormats, ext):
+		//Generate resized image for images
+		return generateThumbnailForImage(fsh, cacheFolder, rpath, generateOnly)
+	case IsRawImageFile(rpath):
+		//RAW image formats (Sony, Canon, Nikon, etc.)
+		return generateThumbnailForRAW(fsh, cacheFolder, rpath, generateOnly)
+	case utils.StringInArray(videoThumbnailFormats, ext):
+		return generateThumbnailForVideo(fsh, cacheFolder, rpath, generateOnly)
+	case utils.StringInArray(modelThumbnailFormats, ext):
+		//3D Model Formats
+		return generateThumbnailForModel(fsh, cacheFolder, rpath, generateOnly)
+	case utils.StringInArray(gcodeThumbnailFormats, ext):
+		return generateThumbnailForGcode(fsh, cacheFolder, rpath, generateOnly)
+	case ext == ".psd":
+		//Photoshop file
+		return generateThumbnailForPSD(fsh, cacheFolder, rpath, generateOnly)
+	case ext == ".svg":
+		return generateThumbnailForSVG(fsh, cacheFolder, rpath, generateOnly)
 	}
 
 	//Folder preview renderer
 	if fsh.FileSystemAbstraction.IsDir(rpath) && len(filepath.Base(rpath)) > 0 && filepath.Base(rpath)[:1] != "." {
-		img, err := generateThumbnailForFolder(fsh, cacheFolder, rpath, generateOnly)
-		rh.renderingFiles.Delete(rpath)
-		return img, err
+		return generateThumbnailForFolder(fsh, cacheFolder, rpath, generateOnly)
 	}
 
 	//Other filters
-	rh.renderingFiles.Delete(rpath)
 	return "", errors.New("no supported format")
 }
 
@@ -380,12 +395,20 @@ func (rh *RenderHandler) HandleLoadCache(w http.ResponseWriter, r *http.Request,
 
 // Check if the cache for a file exists
 func CacheExists(fsh *filesystem.FileSystemHandler, file string) bool {
+	if r, ok := thumbnailRendererOf(fsh); ok {
+		_, found := externalCacheFile(r, file)
+		return found
+	}
 	cacheFolder := filepath.ToSlash(filepath.Join(filepath.Clean(filepath.Dir(file)), "/.metadata/.cache/") + "/")
 	return fsh.FileSystemAbstraction.FileExists(cacheFolder+filepath.Base(file)+".jpg") || fsh.FileSystemAbstraction.FileExists(cacheFolder+filepath.Base(file)+".png")
 }
 
 // Get cache path for this file, given realpath
 func GetCacheFilePath(fsh *filesystem.FileSystemHandler, file string) (string, error) {
+	if _, ok := thumbnailRendererOf(fsh); ok {
+		//The path is on this host, not on the drive, so no fsh can read it
+		return "", errors.New("thumbnail of this drive is not kept on the drive")
+	}
 	if CacheExists(fsh, file) {
 		fshAbs := fsh.FileSystemAbstraction
 		cacheFolder := filepath.ToSlash(filepath.Join(filepath.Clean(filepath.Dir(file)), "/.metadata/.cache/") + "/")
@@ -403,6 +426,11 @@ func GetCacheFilePath(fsh *filesystem.FileSystemHandler, file string) (string, e
 
 // Remove cache if exists, given realpath
 func RemoveCache(fsh *filesystem.FileSystemHandler, file string) error {
+	if _, ok := thumbnailRendererOf(fsh); ok {
+		//Cached by content, so a moved or changed file never finds a stale
+		//thumbnail; unused ones are pruned instead
+		return nil
+	}
 	if CacheExists(fsh, file) {
 		cachePath, err := GetCacheFilePath(fsh, file)
 		if err != nil {