Compare commits

..
1510 changed files with 8657 additions and 32091 deletions

5
.gitattributes vendored
View file

@ -1,5 +0,0 @@
# The ridge bake is addressed by its bytes (bake_id covers the manifest text and the tile files): public/ridge is checked out exactly as committed, whatever
# core.autocrlf says, so a Windows working tree serves the bytes its directory name was hashed from.
public/ridge/** -text
# The baker's inputs and schema are text, read the same everywhere.
scripts/ridge-bake/**/*.json text eol=lf

View file

@ -18,14 +18,10 @@ jobs:
- name: Setup node - name: Setup node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version-file: '.node-version' node-version-file: ".node-version"
package-manager-cache: false package-manager-cache: false
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Ridge asset gate
run: |
npx vitest run src/app/features/scene/ridge/ridgeAssets.test.ts
echo "ridge assets: $(find public/ridge -type f | wc -l) files, $(du -sb public/ridge | cut -f1) bytes"
- name: Build app - name: Build app
env: env:
NODE_OPTIONS: '--max_old_space_size=4096' NODE_OPTIONS: '--max_old_space_size=4096'

View file

@ -1,21 +0,0 @@
# Third-party notices
## d3-celestial (constellation lines)
The constellation line chains in `src/app/features/scene/ridge/nightSkyData.ts` are derived from
`data/constellations.lines.json` of d3-celestial, https://github.com/ofrohn/d3-celestial,
under the licence below.
```
Copyright (c) 2015, Olaf Frohn
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.```

View file

@ -26,7 +26,7 @@
"enabled": false "enabled": false
}, },
"fileZoneShare": { "fileZoneShare": {
"enabled": true "enabled": false
}, },
"push": { "push": {
"vapidPublicKey": "", "vapidPublicKey": "",

View file

@ -1,34 +0,0 @@
schema = "gamecult.idunn.target_declaration.v1"
target = "ratatoskr"
# Idunn stamps the source commit into the build environment under this name. The release is not built from source: the
# dist tarball below is built by scripts the release owner runs (build-prod-dist.sh) and enters pinned by sha256, so
# each release is a recipe commit whose pin is its provenance. The stamp the served index carries is the commit the
# tarball was built from, which is not this commit.
source_stamp_environment = "RATATOSKR_BUILD_COMMIT"
# Release dist adc64a4fb626d35ccc29bc9d4af45d5b49f1ccae: the output of build-prod-dist.sh (live config check passed), packed
# as dist/ at the top of one gzip tar. The tree carries the repo's own config.json; what is served is the operator's
# carried file, which Idunn copies beside dist/ and the vhost aliases over the tree's (a vhost without that alias would
# serve the repo config).
[[external_inputs]]
id = "dist-tarball"
url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-adc64a4f/ratatoskr-adc64a4f-dist.tar.gz"
sha256 = "17df6f8e95e11f3402bb2be67aba968c4f3b1ffc690ded9abbc858a5fa95a89a"
runner = "unpack"
destination = "release/dist.tar.gz"
[[steps]]
id = "unpack-dist"
phase = "prepare"
runner = "unpack"
argv = ["tar", "-xzf", "release/dist.tar.gz", "-C", "release"]
[[artifacts]]
id = "dist"
source_kind = "runner-output"
runner = "unpack"
source = "release/dist"
destination = "dist"
[static_release]
artifact = "dist"

View file

@ -1,291 +0,0 @@
# Files desk: Commons and per-Persona file zones, two designs compared
Status: **decided: Option A, Matrix as the single authority** (Meta, #swarm 2026-11-13 14:44Z: "Let's try matrix shaped"). Design only; no Files desk code is merged and nothing is deployed. Option B (the host service) is parked, not deleted: Eureka's branch `eureka-self/commons-host` at `a391960d` has no PR and a Soul verdict of NOT READY with fixes owed, and is woken only if Meta later wants a real file store. PR #143 (B's cut 1 in this repo) is closed unmerged. Items marked **UNKNOWN** are not verified; **Q-E** are questions for Eureka, **Q-M** for Meta.
### Eureka's answers (`/opt/commons/handoff/commons-matrix-notes-20261113.md`, read 2026-11-13; final answers folded in 2026-11-13)
- **Upload cap (Q-E1, read).** Synapse 1.164.1; the repo template `homeserver.yaml` has `max_upload_size: 50M` and the nginx vhost `client_max_body_size 50m`; the live runtime file is root-only and was not read. No per-room or per-user per-file cap exists; `media_upload_limits` is a per-user time-window quota. `GET /_matrix/client/v1/media/config` returns `m.upload.size` to an authenticated client, which is what the client reads. Raising the cap takes the config line, a Synapse restart and nginx at least as large.
- **Posting (Q-E1, read).** A Self holds no Matrix credentials, so the publisher needs its own bot account and token (a MAS compatibility token via `mas-cli`). It uploads with `POST /_matrix/media/v3/upload` and sends `m.room.message` with `msgtype` `m.file` or `m.image`. The Persona mouth sends `m.text` only today, so file events are new for it too.
- **Room (Q-E3, answered).** The Commons room is `#commons:gamecult.org` (create type `org.gamecult.file_zone`, unencrypted, membership by the estate Space, publisher bot at power level 50). Provisioning and push muting are Eureka's.
- **Cap (Q-E1, answered).** 50 MiB per file. The client reads it live from `m.upload.size`, not from this document.
- **Poster (Q-E1, answered).** The publisher posts as the owning Mind: each file appears under the Mind whose tree it came from, not under a generic bot.
- **Final marker (Q-E2, answered).** A handoff document is final when a sibling `NAME.final` holds its sha256; the publisher watches for that, posts once, and carries `org.gamecult.publish.replaces` (prior event id and sha256) on a later final version.
- **Range (Q-E4, unverified).** Whether Synapse media honours `Range` has not been checked against a live mxc. Playback therefore stays on the blob download until it is.
- **Edited-doc stale copies:** a redacted file's media persists unless purged; the publisher dedupes by sha256.
Source: Meta, #swarm 2026-11-13 14:28Z and 14:40Z; ruling `ratatoskr:ruling:persona-file-sharing-zone` (a browsable, previewing collection per Persona; the Self writes to her outbox, her Persona decides what is shared, the Self never holds Matrix credentials).
## What exists on Matrix today (the base A must fit)
Read from this repo at dev `8ba407cd`:
- **Zone = a room** whose `m.room.create` type is `org.gamecult.file_zone` (`isFileZone.ts`), or one listed in config `fileZoneRooms`. One per Mind, `#<mind>-files:<server>`, found by alias or by the carried id in the root Space's `org.gamecult.stewardships` (`mediaRoom.ts`, `MediaRow.tsx`); rendered as the Media row of each Mind's group.
- **Album = a thread root** (a text event; its `body`, or its latest `m.replace` edit, is the title); **file = a thread reply** with `msgtype` `m.audio|m.image|m.video|m.file` (`buildAlbums.ts`). A redacted event or an `m.replace` is never a file. Loose room messages are not shown.
- **Read** = `GET /rooms/{id}/threads` and `/relations/{root}/m.thread`, every page, 100 per request, at most 20 pages per endpoint (`useAlbums.ts`, `readPages.ts`; a capped read shows a note in the list). Unencrypted rooms only.
- **Write** = `sendShareSet` (`shareSet.ts`, behind `fileZoneShare.enabled`): a root, then one thread reply per file, content from `getMsgContent` with `info.sha256`.
- **Media** = authenticated Matrix media fetched to a blob (`downloadMedia` in `FileContent.tsx`): so the "media element cannot send a header" problem that Option B needed a ticket for is already solved this way, at the cost that a file is fully downloaded before it plays.
- **Receipts** = `org.gamecult.file_received` from a Mind's mouth after it fetches and verifies the sha256 (`docs/file-zone-mind-contract.md`); the mouth enforces the Mind's membership in the room.
Option A is an extension of this, not a second system.
## The two options
**A. Matrix is the only authority.** Commons is one more file-zone room; each Mind's zone is the room she already has. Audience is room membership. Upload is the ordinary Matrix upload. Folders are albums (thread roots). A small publisher service with its own Matrix account posts allowlisted handoff documents into the Commons room. The Files desk is a view over file events in those rooms.
**B. The host service.** A file host on Yggdrasil serves allowlisted directories (`GET /index`, `GET /file`, a capped `PUT`), authenticated by Matrix OpenID; the client browses it as a tree. Written out in full below the line.
| | A: Matrix only | B: host service |
| -------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| Authorities | one (Matrix: identity, audience, storage, audit) | two (Matrix for identity, the host for files and access) |
| Audience | room membership and power levels | the host derives a role from Matrix identity and enforces it again |
| Audit of writes | the event `sender`, kept by the homeserver | the host's own log |
| Overwriting someone's file | impossible: events are immutable and only the sender's own edit counts; a redaction is a steward's act | host rule, host code |
| Upload size cap | the homeserver's `m.upload.size`, global, 50 MiB (Eureka) | the host's own, chosen freely |
| Type allowlist | not enforceable by the homeserver; client-side courtesy, steward redaction | enforced by the host (sniffed) |
| What is browsable | what was posted (published or uploaded) | what is on disk under the allowlist, live |
| Mind-written handoff docs | a publisher posts them once, when final (below) | the host serves the tree |
| Per-Persona zone | the existing Media room; the Self's outbox reaches it through the mouth, as the ruling says | a `shared/` directory the host serves |
| Folders | albums; nesting by path in the album title | real directories |
| Mind fetch | unchanged (mouth, room id and event id, receipts) | a second route the mouth would need |
| Media playback | blob download, as today; no seeking before the whole file arrives | ranges and a ticket, or the same blob |
| New moving parts | a room, a publisher | a host service, OpenID verification, CORS, tickets, path containment, rate limits |
## Recommendation: A (decided)
Confidence: high on the authority question (it agrees with Meta's ruling, with Eureka's lean, with the standing ruling that the Self never holds credentials while her Persona decides what is shared, and with the fact that everything built so far reads Matrix); moderate on the details below, which Eureka's answers can change.
What A gives up, stated plainly:
- **A live view of what is on disk.** Only what was published or uploaded appears. A handoff doc that was never marked final is not in the Commons.
- **Files over the homeserver's upload cap.** B had no Matrix limit; A has exactly one.
- **A server-side type allowlist.** Under A a member can upload any type the homeserver accepts; the client shows a refusal for types it does not want, and stewards redact. If a strict allowlist matters, a gating bot (post, check, redact) would have to exist, and it is a second authority again.
- **Seeking inside a large audio or video file** until Matrix media supports ranges for the client (**UNKNOWN**; the blob route is what runs today).
- **Hierarchy beyond the album level** as a native structure; see Folders.
What it buys: one identity, one audience, one audit trail, immutable files, existing receipts and the mouth's fetch, and no new service to keep secure.
## Option A in detail
**Rooms.** Commons is a room with create type `org.gamecult.file_zone`, alias `#commons:gamecult.org`, join rule `restricted` to the estate Space so members join without an invite and Minds are invited, history `shared`, unencrypted (the zones are, and `info.sha256` is written only there). Power levels: `events_default` 0 so members post; `redact` and `state_default` at steward level. The room is muted for push by provisioning: file posts are thread replies, which can raise unread counts and notifications (**UNKNOWN** under this server's push rules), so the room must not shout. Per-Persona zones are the rooms Eureka already provisions; nothing new.
**Folders.** Four ways to have folders on Matrix, in order of preference:
1. _Albums are folders; nesting is a path in the album title_ (`handoff/2026-11`, `cast-art/poses`). Zero wire change: `buildAlbums` already reads it, and the client groups albums by title path as a pure view. Cost: a thread root per folder, and the rule that a folder's root is posted once by whoever opens the folder. **Recommended.**
2. A `org.gamecult.file.path` key on each file event. Gives a real tree with files anywhere; needs every poster to write it and every client to honour it; other Matrix clients ignore it and show a flat thread.
3. A room per folder, in a Space. Native hierarchy and per-folder audience; heavy (a room is a membership, a sync entry and provisioning each) and it multiplies the sync load on a phone.
4. A state event per folder (`org.gamecult.file_folder`). Mutable folder metadata (title, order), writable only at steward level; useful later if folders need descriptions, not needed for a first cut.
**Albums in each Mind's room** are the same mechanism: a Mind's Media room holds that Mind's albums, the Commons holds the shared ones. The Files desk is the same view over either room; a zone differs only by room, not by code.
**The publisher.** A small service on Yggdrasil with its own Matrix account (a bot account that posts as the owning Mind, per Eureka's answer above). The Self never holds this account; the publisher holds it. It owns the allowlist.
- **When it posts.** Handoff documents are edited in place, so mirroring every save would spam the room with drafts. The rule (Eureka's lean, adopted): **post once, when the document is marked final**; a later final version posts again with a `replaces` relation to the earlier event. "Final" is a sibling `NAME.final` holding the document's sha256 (answered Q-E2); the client must not know.
- **Allowlist.** Lives on the publisher: a list of source roots and patterns, read by the publisher only. `handoff-private` is not on it and the publisher never lists, reads or posts from it. The client holds no path to anything on disk.
- **The event.** A file event in the thread of the folder's album, built the way `getMsgContent` builds them (`msgtype`, `body`, `filename`, `url` from the media repo, `info.mimetype|size|sha256`), plus one extra key `org.gamecult.publish`: `{ source, sha256, replaces? }` where `source` is a path relative to the allowlisted root, never absolute, and `replaces` is the event id of the version it supersedes.
- **`replaces`, not `m.replace`.** `m.replace` is the stock edit relation, but Ratatoskr's `buildAlbums` deliberately never treats an edit as a file, several clients do not render an edited file, and an edit hides the earlier version. A custom key keeps both events as files; the view shows the latest of a chain and a "N earlier versions" row under it, and other Matrix clients see two ordinary file posts. A chain is read from the events themselves (each carries its `replaces`), not from a table, and a `replaces` counts only when its event has the same sender as the event it names, so nobody else in the thread can fold a file away.
- **Idempotence.** The publisher's own state (a typed CultCache document of `source`, `sha256`, `event_id`) says what it posted; if that is lost, it rebuilds by reading its own events back from the room (`org.gamecult.publish.source` plus `sha256`) rather than guessing. The same `sha256` never posts twice.
- **Receipts and fetch** work unchanged: the event is an ordinary file event in a file-zone room, so a Mind's mouth can fetch it by room id and event id (5 MiB cap there) and tick `fetched for`.
**Uploads (approved for members and Minds).** The ordinary Matrix upload, through the composer pipeline and `ShareSet`. The host rules Eureka gave map onto Matrix as follows:
| Host rule | Under A |
| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| only under an `uploads/` subtree | an album (folder) named `uploads/...`; the client offers upload only there (and in a Mind's own zone) |
| never overwrite Mind-written handoff files | free: other people's events cannot be replaced; a duplicate name is just another post in the thread |
| size cap | the homeserver's `m.upload.size`, shown from `MediaConfigLoader`; the client refuses a larger file before sending |
| type allowlist | client-side only; see "gives up" |
| explicit flag to overwrite | no overwrite exists; a new version is a new post, optionally with `replaces` set by the same sender |
| audit log with the Matrix id | the event `sender` |
What A adds to `ShareSet`: sharing into an existing album ("add files", listed as not built in `docs/file-zone.md`), progress per file, cancel, and per-error refusal messages written against the SDK's `MatrixError` (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`) instead of host codes. The draft refusal table of Option B's upload flow carries over with those codes. **UNKNOWN:** whether the SDK exposes upload progress and abort for media (it does for `uploadContent` with a progress callback; the composer already shows progress, `state/upload.ts`).
## What each costs on the phone
Under both, the phone design is the same shape (one column, rows 56 px or more, hidden controls, in-place preview; see the Option B sections below, which are written against the host but whose layout applies).
- **A, new cost:** the Commons room is one more room in sync and it must be muted; albums and files are read to a cap of 20 pages of 100 per endpoint (a Commons past that shows a truncation note); a folder tree is a title-path grouping, so a deep tree is a long list of albums with breadcrumbs, not true directories; a file plays after a full download (small audio and images are fine; a 40 MB clip is not).
- **A, no cost:** no second sign-in, no ticket, no CORS, no new fetch layer, no host-unreachable state beyond the homeserver's own. The album list, album view, share panel and receipts exist and are tested; the view is their extension.
- **B, new cost:** every screen is a second client against a second service with its own errors, token refresh and unreachable state; media needs the ticket or the blob; the tree and preview are new UI.
- **B, benefit:** a tree that is live and complete, ranges, and no Matrix size limit.
## Changes to Eureka's host work
Under A the paused service is not built, and most of its list disappears:
- **Dropped:** `/index`, `/file`, `PUT`, OpenID verification pinned to the server name, CORS, path containment and sniff rules, tickets, the `uploads/` write rules, the role response, the per-path audit log (Q-E3, Q-E4, Q-E6, Q-E7, Q-E8 to Q-E11 of the Option B list).
- **Kept:** the Commons allowlist decision (Q-E1 of that list), moved to the publisher: which roots, and that `handoff` is only ever published through the final-marker rule, never browsed.
- **New:** (1) provision the Commons room (type, alias, restricted join to the estate Space, power levels, push muted); (2) the publisher: account, allowlist, final-marker rule, media upload, posting into folder threads, the `org.gamecult.publish` key, idempotence from its own events; (3) confirm the homeserver upload cap and whether the account may post file events from Yggdrasil (**Q-E1**, asked on the PR); (4) the per-Persona path stays the one already specified (`album-outbox-ops`: outbox, Persona decision, mouth post), so the `shared/` convention of Option B is retired.
## Cuts under A
Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. The Commons entry row is built (item 1): `useCommons` in `MediaRow.tsx` finds the room by the alias `#commons:<server>` (provisioning records no id for it), through `lookupZoneRoom` (the one lookup `lookupMediaRoom` also uses); `EstateNavigator` shows it above the tiers as a Commons link when joined, a join row when invited or not joined, and nothing when the room is absent, the lookup failed or is out. It is gated on the existing `fileZoneShare.enabled`, not a new `filesDesk.enabled` flag. The album view and ShareSet work there because provisioning creates the Commons with the `org.gamecult.file_zone` create type. Members can share only once the room's power levels let them post: provisioning gives the poster level to the Minds alone.
1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias), opening the room's album view. Flagged, no new data layer.
2. **Pagination** of albums and files in `useAlbums` (done, PR #148).
3. **Folders by title path** and the album list grouped by it.
4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149).
5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). Done: adding to an open album and the three refusal messages (PR #150); Stop for a send in flight is in too (PR for follow-up `files-desk-release-146-and-send-cancel`): it cancels the running upload through `onPromise` and `mx.cancelUpload`.
PR #143 (Option B cut 1: contract types, host client, fake host) is **held**; under A it is not needed and would be closed. Its Soul pass found, and a revived B would have to close, an unvalidated `host` that could send the bearer to the wrong origin, hostile-looking entry names beyond separators, loose numeric checks and missing CSP and `Content-Disposition` headers in the fake.
## Not in scope
The Mind-side fetch (the mouth's); encrypted rooms; deletion and rename by this client; search across zones; any permission model of our own beyond Matrix room membership and power levels.
## Open questions
**Eureka:** answered; see "Eureka's answers" at the top. Still open on Eureka's side: Range support (Q-E4) and the live runtime `max_upload_size`.
**Meta:**
- **Q-M1.** Commons audience: members and Minds as proposed; Users and Patrons never, or later?
- **Q-M2.** Is a Persona's zone visible to all members or to her stewards and Minds? (The Matrix zone's audience question, `ratatoskr:question:file-zone-audience`, is the same fork.)
- **Q-M3.** May Users or Patrons upload if they are ever let in?
- **Q-M4.** Names: "Files" for the view, "Commons" for the shared room.
- **Q-M5.** A type allowlist is not enforceable under A without a gating bot; is a client-side refusal plus steward redaction enough?
---
# Option B in full (kept for the comparison; superseded in part by Option A above)
The sections below were written against the host service. Where they speak of a host, a role, a ticket, a token, `/index` or `/file`, they are Option B. The phone layout, the zone table and the refusal wording carry over to A with the Matrix equivalents given above.
### What exists, and what this adds
| | Matrix file zone (`docs/file-zone.md`, built) | Files desk (this page) |
| -------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Storage | Matrix media in a `#files-<mind>` room, albums as threads | Directories on Yggdrasil, served by a small host |
| Listing | thread roots, `buildAlbums` | `GET /index?path=` |
| Unit | album of posted files | file in a directory tree |
| Strength | marks (keep / fix / drop), receipts (`fetched for`), any Matrix client works | whole trees without N uploads, no Matrix size limit, `/opt/commons` material becomes visible to people on a phone |
| Entry | Media row per Mind (`MediaRow.tsx`) | Files row (below) |
They do not compete. The Matrix zone stays where a file needs a mark or a receipt (Aqua's listening kits); the Files desk is for browsing and fetching what is already on disk. Neither replaces the other, and the Files desk does not write Matrix events. The ruling left "Matrix media plus a listing versus a served directory" open; this page is the served-directory half, built beside the Matrix half already live.
### Zones (host)
| Zone | Contents | Who sees it |
| ---------------- | ------------------------------------------------------------ | -------------------------------------------------------------- |
| Commons | a curated tree of `/opt/commons` | members and Minds |
| Persona `<slug>` | what that Persona has chosen to share from her Self's outbox | **Q-M:** all members, or the Persona's stewards and Minds only |
| handoff-private | `/opt/commons/handoff-private` (0750) | never: not a zone, not listed, not a path the host resolves |
Layout of `/opt/commons` today (read 2026-11-13): `backlog` (755, per-Mind backlog md and summary.json), `bin`, `cast-art` (setgid, group-writable: poses, busts), `handoff` (setgid, group-writable, 92 entries of briefs, patches, receipts, dings, kits), `handoff-private` (0750, ACL), `opt` (toolchains, root-owned), `situation` (0750, setgid), all `nobody:nogroup`. **`handoff` is not a publishable tree:** it holds ops notes, custody receipts (`bifrost-appsecret-custody-receipt-*`) and patches written for Minds, with no sticky bit. Serving it wholesale shows secrets-adjacent notes to every member and lets any Mind with group write change what a phone user sees. The Commons zone is therefore an allowlist of roots (candidate: `cast-art`, `backlog`, and a new `commons/` directory Minds publish into on purpose), not `/opt/commons` itself. **Q-E:** which roots; whether `handoff` ever, and if so through a reviewed `published/` subdirectory.
Per-Persona source is the outbox from `ratatoskr:follow_up:album-outbox-ops-and-persona-specs`: `/var/lib/mind-<slug>-outbox`, owned by `mind-<slug>-self`, 0750, ACL read for `mind-<slug>` and the host user. The Self writes there; the Persona decides what is shared. Making that decision a filesystem fact (a `shared/` subdirectory the Persona's turn populates by copy or hardlink, the host serves only `shared/`) keeps the host dumb: it never learns what "decides" means. **Q-E:** `shared/` subdirectory versus a per-file marker.
### Phone-first UI (host)
Phone width is the design width; desktop adds the navigator beside it (as `Desk` does in `Router.tsx`). Vertical space is cheap, so a screen shows one thing and hides what is not in use.
- **Entry.** A `Files` row pinned in the navigator beside `DeskEntry` and `MindMedia`: one at the estate level (Commons) and one inside each Mind's group (her zone), same `NavItem` anatomy as `DeskEntry`, dim when the zone has no items. Route `/files/:zone/*path`, sibling of `DESK_PATH`.
- **List.** One column. Row = icon or thumbnail, name (truncates in the middle, keeping the extension), size and age on a second dim line. Directories first. Rows are at least 56 px tall; the tap target is the whole row (the `PhoneHit` variants and the repo-wide guard test from `phoneHit.coverage.test.ts` apply to any IconButton inside).
- **Hidden until needed.** Breadcrumb is one line (current folder, a back arrow; the full path on tap). Search, sort and the grid toggle sit behind a single icon in the header and open inline above the list. Download and share appear on the open file, not on every row. Nothing is permanently stacked in the header.
- **Preview.** Tap a file: it opens in place below its row, full width, and pushes the rows below it down (vertical room is the cheap axis). Image: fitted, tap for the existing `ImageViewer`. Audio: the `AudioContent` controls rehosted (`renderMediaControl`), one player at a time, a mini-player pinned to the bottom only while something plays. Video: native controls. Text, md, json, patch: monospace, first 64 KiB, "show all" below. PDF: open in a new tab. Anything else: name, size, hash, one Download button.
- **Honesty rows.** Loading, empty, "host unreachable", "not allowed" are rows that say so (as `MediaNote` does); no spinner without a name for what it waits on.
- **Role-driven.** The index response carries the caller's role; the client uses it only to hide controls (upload), never to decide access.
### Host contract
The host is a service on Yggdrasil that Eureka owns. The client holds no filesystem knowledge. All JSON here is the xenos boundary between a browser and a file server, not state.
- `GET /index?path=<p>` returns `{ role, zone, path, entries: [{ name, kind: "file"|"dir", size, mtime, mime, hash }] }`. `mtime` is unix seconds. `hash` is the lower-case hex sha256 of the plaintext bytes, absent for directories, and may be absent for a file whose hash is not computed yet (client shows nothing, never blocks on it). `mime` is sniffed by the host from magic bytes, not guessed from the extension.
- `GET /file?path=<p>` streams the bytes with `Accept-Ranges: bytes` and 206 for `Range` (audio and video seek; a phone on mobile data does not fetch 40 MB to play 10 seconds). `Content-Type` is the sniffed mime, `X-Content-Type-Options: nosniff`, `Content-Disposition: attachment` for anything that can run in the origin (`html`, `svg`, `js`, `xhtml`), and a `Content-Security-Policy: sandbox` on every response.
- `path` is `<zone>/<relative path>`, with the zone one of the names the host announces. The host resolves the real path of every request and refuses anything that leaves the zone's root: `..`, absolute paths, NUL, symlinks that cross the root, dotfiles, and `handoff-private`, which is not on any allowlist. Errors are typed (`401 unauthenticated`, `403 zone not allowed`, `404`, `416`), and a path outside the allowlist is 404, not 403, so it says nothing about what exists.
- **Auth: Matrix OpenID.** The client calls `mx.getOpenIdToken()` (already used in `CallWidgetDriver.ts`) and sends it as `Authorization: Bearer <token>`. The host verifies it against the homeserver's federation `openid/userinfo` endpoint, **pinned to our server name** (an `@void:evil.example` token must fail), caches the verified `sub` for the token's lifetime, and derives the role. It never sees the user's access token, and a Mind's Self never holds a token (ruling above): Minds reach the same bytes through the filesystem or the mouth, not this host.
- **Role** in the response: `member`, `mind`, `steward` (host decides from the Matrix id and the room/space membership the host reads; the client trusts none of it for access). **Q-E:** exact source of membership (estate Space membership read by the host with a service account, versus the Persona catalogue file for Minds).
- **Uploads** (Meta approved for members and Minds, #swarm 2026-11-13 14:30Z; rules are Eureka's, below). `PUT /file?path=<p>` writes only under an `uploads/` subtree of a zone, with `Content-Length` required; the host enforces a size cap, a type allowlist (sniffed, not the client's claim), no overwrite unless the request carries an explicit flag, and never replaces a file a Mind wrote into the handoff tree; every write is audit-logged with the caller's Matrix id. Reads cover the whole allowlisted tree, so an uploaded file is listed like any other. Success is `201` with the stored name, size and hash. The `role` in the index response gates the upload control; the host gates the write.
### The one problem the contract leaves: media elements cannot send headers
`<audio src>`, `<video src>` and `<img src>` cannot attach `Authorization`. Options, none free:
1. **Fetch to a blob.** Works with the contract as written. No seeking before the whole file is in memory; bad for a 40 MB clip on a phone. Fine for images and small audio.
2. **Short-lived path ticket.** `POST /ticket?path=` with the bearer token returns a URL with an unguessable token valid for a few minutes for that one path and its ranges. The player gets a normal URL and seeks. One more endpoint on the host and one more thing to expire and log.
3. **Service worker adds the header** to `/files-host/*` requests. The PWA already has a worker (`src/sw.ts`); no host change, but the worker must carry a fresh OpenID token and range requests through it are fiddly.
Recommendation: 2 for audio and video, 1 for images and text. Confidence moderate: I have not tested a service worker against range requests on the target phone, and 2 is the usual answer for authenticated media (signed URLs). **Q-E.**
### Upload flow (host)
Design only. Every number and error code is a named placeholder until Eureka gives them on the PR: `<CAP_FILE>` (per-file size), `<CAP_BATCH>` (per-pick total, if any), `<TYPES>` (the allowlist), `<OVERWRITE_FLAG>` (the explicit query flag), and the codes `<E_AUTH>`, `<E_ROLE>`, `<E_PATH>`, `<E_TYPE>`, `<E_SIZE>`, `<E_EXISTS>`, `<E_PROTECTED>`, `<E_QUOTA>`, `<E_SERVER>`.
**Where.** The control exists only where an upload is allowed: inside a folder under a zone's `uploads/` subtree (or at the `uploads/` row itself), and only when the index `role` is member or mind. Elsewhere there is no button; the list does not carry a disabled one. A folder outside `uploads/` shows a one-line dim note, "Uploads go in uploads/", which links to that folder. Creating subfolders under `uploads/` is not in this design (**Q-E8**).
**Pick or drop.** One `Upload` row at the top of an `uploads/` folder opens the native picker (any number of files; on a phone this is the OS file sheet, camera roll included). On wide screens the list is also a drop target; the drop highlight appears only while a drag is over it. Nothing starts on pick: the picked files appear as a staging list (name, size, a type icon) with `Upload` and `Cancel` as full-width rows, as `ShareSet` does for a Matrix set. Files that already fail the client's cheap checks (over `<CAP_FILE>`, a type outside `<TYPES>`) are marked in the staging list with the reason and left out of the send; the client mirrors the cap and allowlist as a courtesy only, the host is the authority, and the list is read from the host (**Q-E9**: an `/index` field or a `/limits` call) rather than hard-coded.
**Send.** Files go one at a time, in pick order, each a `PUT /file?path=<folder>/<name>` with the bearer token. One at a time keeps a phone on mobile data from starving every transfer, and a refusal names exactly one file. The transport is `XMLHttpRequest`, not `fetch`: `fetch` has no upload progress and the row needs it. The body is the `File` itself (streamed by the browser, not read into memory; unlike the Matrix path, the client computes no hash first, the host returns one). The name is the file's own name, with path separators and control characters replaced, never a path the user typed.
**Progress.** The staging list becomes the progress list: per file a thin bar and "412 KB of 3.1 MB", per batch "2 of 5". Finished files show a tick and the stored name; refused ones show the refusal in place; waiting ones are dim. Only the active file animates. The list stays on screen after the last file until dismissed, so a refusal is not lost to a refresh of the folder underneath it. The folder listing refetches after each success, so the file appears in the list as it lands.
**Cancel.** `Cancel` on the active file aborts the request (`xhr.abort()`) and goes on to the next; `Cancel all` on the batch aborts the active file and drops the rest. The host must discard an aborted partial write and never leave a half file in the listing (**Q-E10**, written to a temporary name and renamed on completion). Leaving the page aborts whatever runs, as the Matrix share does; the client does not resume.
**Overwrite.** A name that already exists is refused with `<E_EXISTS>` and shown as "<name> is already there". A `Replace` row appears under that refusal only for a file the caller wrote themselves, and sends the same `PUT` with `<OVERWRITE_FLAG>`; a Mind-written handoff file refuses with `<E_PROTECTED>` and offers only "Keep both", which re-sends under a suffixed name (`name (2).ext`) chosen by the client. Whether the client can tell "mine" from the index (an `owner` field with the Matrix id) or learns it only from the refusal is **Q-E11**; absent an owner field, `Replace` is simply offered after `<E_EXISTS>` and the host's answer decides.
**Refusal messages.** One plain sentence per code, shown in the file's row; nothing says "error" without saying why, and none names a server path.
| Code | Message (draft) |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `<E_AUTH>` | Sign-in expired. Reload to upload again. (The client fetches a fresh OpenID token once and retries before showing this.) |
| `<E_ROLE>` | Uploads are for members and Minds. |
| `<E_PATH>` | That folder does not take uploads. |
| `<E_TYPE>` | "<name>" is a <type> file; allowed types are <TYPES>. |
| `<E_SIZE>` | "<name>" is <size>; the limit is <CAP_FILE>. |
| `<E_EXISTS>` | "<name>" is already there. |
| `<E_PROTECTED>` | "<name>" was written by a Mind and cannot be replaced. |
| `<E_QUOTA>` | The shared space is full. Tell a steward. |
| `<E_SERVER>` / network / timeout | Could not reach the file host. The file was not saved. |
Retry is one tap on a failed row; the batch never retries on its own. An unknown code shows the host's status text as it is, still without a path.
**Honest end state.** Done means the host answered `201` and the stored name, size and hash are shown. "Saved" is not said earlier; the hash the host returns is displayed so a sender can compare it with their own.
**Reuse and not.** `ShareSet`'s state machine (staging, one-send-per-zone guard, failed files kept by position) is the model, but the Matrix share path and its `createUploadAtom` are tied to the SDK's media upload and are not reused; the new controller sits in `features/files/uploadController.ts` with the same injected-port shape, so order, refusal and cancel rules are tested against a fake `PUT` without a browser. Real transfer progress and a real range of a phone's picker stay a phone check.
### Client shape (host)
Under `src/app/features/files`, mirroring `features/albums`:
- `filesHost.ts`: ports, `list(path)`, `url(path)`, `ticket(path)`, `put(path, file, onProgress, signal)`; the only module that knows the contract. Injected, so the UI is tested against a fake and the real client never runs in a test.
- `useFilesZone.ts`: react-query on `['files', zone, path]`, `staleTime` 30 s; the role comes with every index.
- `FilesDesk.tsx`, `FileRow.tsx`, `FilePreview.tsx`: pure rendering from the above; the preview picks its renderer from the host's `mime`, not the extension.
- `config.json`: `filesDesk: { enabled: false, host: "https://…" }`, dark by default as `fileZoneShare.enabled` is. With it off, no row mounts and no request leaves the client.
- Test host: `src/preview-demo` already answers for a pretend homeserver through a fetch guard (`install.ts`); it gains a fake `/index` and `/file` with ranges so the previews are checked in a real browser before the real host exists.
### Cuts (host)
1. **Contract and fake host** (no UI): `filesHost.ts`, types, `preview-demo` fake, path tests (traversal strings from the host side are Eureka's; the client must only build `path` from entries it was given).
2. **Read-only Commons desk**: route, row, list, breadcrumb, role display, flagged off.
3. **Preview and player**: image, audio with ranges, text, video; the ticket if Q-E settles on 2.
4. **Per-Persona rows** in each Mind's group, once the outbox `shared/` convention and the zone provisioning exist.
5. **Uploads**: the flow above; needs Eureka's codes and caps and the host's `PUT`.
Each is its own PR. Slices 1 to 3 need no host to build and test; slice 2 needs the real host to be useful, not to land.
### Not in scope (host)
The Matrix file zone (marks, receipts, `ShareSet`); any Mind-side fetch (the mouth's); encrypted rooms; deletion and rename (a read surface first; the files belong to whoever wrote them on disk); search across zones; a permission model of our own beyond what the host derives from Matrix identity.
### Open questions (host)
**For Eureka (host):**
- **Q-E1.** Which roots form Commons: the allowlist, and whether `handoff` is ever served (it holds custody receipts and ops notes; recommendation: no, a reviewed `commons/` directory instead).
- **Q-E2.** Where the host runs and what it is: Rust by default per doctrine; nginx with `auth_request` to a verifier is smaller if the sniff, range and role logic fit there. Which user; read-only mounts; ACLs on the outboxes.
- **Q-E3.** Media-element auth: blob, ticket or service worker (above).
- **Q-E4.** Role source: how the host learns membership and which Minds are Minds; token verification pinned to `gamecult.org`.
- **Q-E5.** Per-Persona publishing: a `shared/` subdirectory versus a marker, and who populates it when the Persona decides.
- **Q-E6.** Hash cost: compute lazily and cache by (path, mtime, size), or at publish time.
- **Q-E7.** CORS for `chat.gamecult.org` and the dev previews, rate limits, and the `Content-Disposition` list.
- **Q-E8.** Subfolders under `uploads/`: can a client create them (by a `PUT` path that implies them, or a `MKCOL`-like call), or is `uploads/` flat?
- **Q-E9.** Cap and allowlist discovery: fields in the index response, or a `/limits` endpoint; and the exact codes and cap numbers behind every placeholder in the upload flow.
- **Q-E10.** Partial writes: temporary name then rename, so an aborted or failed upload never appears in a listing.
- **Q-E11.** Does the index carry an `owner` Matrix id per file (so `Replace` is offered only on one's own files), and is the audit log readable by stewards from the client or only on the host?
**For Meta:**
- **Q-M1.** Audience: Commons for members and Minds as proposed; are Users and Patrons ever in (the Matrix zone's audience question, `ratatoskr:question:file-zone-audience`, is the same fork)?
- **Q-M2.** Is a Persona's zone visible to all members or to her stewards and Minds?
- **Q-M3.** ~~Uploads~~ approved for members and Minds (2026-11-13 14:30Z); open only: may Users or Patrons upload if they are ever let in?
- **Q-M4.** Name: "Files" for the row, "Commons" for the shared zone.
- **Q-M5.** Does the Matrix Media row stay beside the Files row on each Mind, or does one absorb the other once the Files desk exists (recommendation: both stay; marks and receipts are Matrix's).

View file

@ -120,4 +120,4 @@ Client, `src/app/features/albums`:
Flag: `fileZoneShare.enabled` in `config.json`, default `false`. With it off nothing mounts. Flag: `fileZoneShare.enabled` in `config.json`, default `false`. With it off nothing mounts.
Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; Built since: Stop for a send in flight (aborts the running upload, leaves it and the rest picked as "stopped"), pagination to 20 pages of 100 per endpoint (PR #148), adding files to an open album with named refusals (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`). Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; sharing into an existing album ("add files"); upload cancel; pagination beyond 100 albums/files.

View file

@ -47,10 +47,6 @@ handoff states which config differs and the installer decides. From Yggdrasil th
not resolve: pass `LIVE_CURL_ARGS="--resolve chat.gamecult.org:443:127.0.0.1"`. not resolve: pass `LIVE_CURL_ARGS="--resolve chat.gamecult.org:443:127.0.0.1"`.
The folder, with the three pins (`SHA256SUMS` sha256, `BUILD-INFO` sha256, lockfile sha256) and The folder, with the three pins (`SHA256SUMS` sha256, `BUILD-INFO` sha256, lockfile sha256) and
the node and npm versions, is what the install request names. the node and npm versions, is what the install request names.
Every build stamps its commit into `index.html` (`scripts/buildSha.js`): `<meta name="build-sha" content="<40-hex>">`,
with `-dirty` appended when the tree had uncommitted changes and `unknown` when there was no git. Where git governs the tree it decides: an explicit `BUILD_SHA` naming a different commit than HEAD stamps `<sha>-mismatch`, a git failure stamps `unknown`. A full-sha `BUILD_SHA` stands only for a tree git does not govern (a source archive) or cannot read (unusable git, for example a dubious-ownership refusal). The handoff
build refuses a dist whose stamp differs from the sha it was asked for, and prints the stamp in its block.
To read it from anywhere: `curl -s https://chat.gamecult.org/ | grep -o 'build-sha" content="[^"]*'`.
Before handing off: Before handing off:
@ -113,8 +109,9 @@ Hard-refresh to clear `sw.js`. Do not delete the failed release; leave it for di
## Open ## Open
- Release a5 (2026-11-20, dist `a1fdfee3`, receipt `/opt/commons/handoff/rat146-a5-receipt-20261120.md`) - The served config (checked 2026-11-12) is not the repo's: it says `backgroundScene.style`
replaced the carried config with the repo's `config.json` (ridge, `fileZoneShare` on; ruling `terrain` where the repo says `ridge` (#106, Meta 2026-11-11), lacks the repo's `dings`,
`ratatoskr:ruling:ridge-only-scene-terrain-cut`). The carried file and the build pin are equal, so a `fileZoneShare` and `registration` blocks (all off in the repo), and has no trailing newline.
handoff build passes its live check without `ALLOW_CONFIG_DRIFT=1`. A release that changes The new keys default off or inert when absent, so only the style is a decision. Meta says which
`config.json` changes the carried file deliberately, as a5's `carry.sh` did. style ships. Until the served file is replaced, every handoff build stops at the live check
unless `ALLOW_CONFIG_DRIFT=1` is set (section 1).

View file

@ -97,11 +97,9 @@ Probes run by Imagination on 2026-10-31, session `self-2026-10-29-eureka`.
events from the Minds' stewardship documents; each project room's alias is events from the Minds' stewardship documents; each project room's alias is
`#<repo lowercased>` (runbook 146-150). This is the only place the client `#<repo lowercased>` (runbook 146-150). This is the only place the client
can learn a not-yet-joined room's steward today: hierarchy `canonical_alias` can learn a not-yet-joined room's steward today: hierarchy `canonical_alias`
joined to the root `org.gamecult.stewardships`. The joined to the root `org.gamecult.stewardships`. Follow-up
projection now also names room ids under `@rooms.projects` and `ratatoskr:follow_up:stewardships-carry-room-ids` asks the projection to
`@rooms.file_zones` (gamecult-ops #111); the client reads `file_zones` for name room ids so the client stops leaning on the alias convention.
the Media row (`mediaRoom.ts`) and still joins projects by alias, since
nothing yet consumes `@rooms.projects`.
5. **Sync and storage** (`src/client/initMatrix.ts`). The client uses 5. **Sync and storage** (`src/client/initMatrix.ts`). The client uses
matrix-js-sdk 41.7.0 with `IndexedDBStore` (`web-sync-store`, 15-19) and the matrix-js-sdk 41.7.0 with `IndexedDBStore` (`web-sync-store`, 15-19) and the
Rust crypto store, and `startClient({ lazyLoadMembers: true })` (43-47): v2 Rust crypto store, and `startClient({ lazyLoadMembers: true })` (43-47): v2

View file

@ -1,19 +0,0 @@
# Ridge backdrop target
The scene's bottom silhouette is replaced by baked A+D ridge planes. The baker is Python and offline; the browser composes pre-lit planes over the live physical sky. Typed state for this campaign (ideas, questions, rulings, cuts) lives in the instance mind `nibu`, campaign `ratatoskr-backdrop`; this file keeps only the ends.
## Why
The live noise ridge is nearly invisible on a phone (about 1.35:1 against the darkest sky) because every ridge pixel is lifted to the text-contrast floor, and the star dots show between nav and header glyphs because the shell is transparent. Meta, 2026-11-13: do not polish the old backdrop; ship the A+D ridge pipeline (round 2 mockup: https://minds.gamecult.org/nibu/ridge-mockups-ad/).
## Ends
- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only the ring's residency, the camera's pose against its heading, blending and compositing. No ridge geometry is computed in the browser.
- The ground under the authored 500 m near clip is the place's own DEM from 1 m, drawn by card 0 inside the silhouette of the terrain at the clip and riding card 0's slide; everything that bounds the view reads terrain at or beyond the clip: `r_max` is where the linear slide holds for the nearest solid terrain each card draws in each tile (a tile of near ground only binds at the clip, 500 m, where it is slid), and every bake keeps 150 rows under the horizon so the plane reaches the bottom of every viewport.
- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it.
- Phone cost is bounded: no per-frame script for the ridge (one exception: while a finger or the mouse is down in the scene view, pointer events turn the heading and the heading owner re-issues the rig; the twinkle is the other), decoded size and fetched size gated in CI.
- The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps the heading: it is unwrapped within a stretch of motion and `ridge/heading.ts` `normalize` brings it into [0, 360) before each one, so no angle or pixel position grows with uptime, while `ridge/ring.ts` is the one place that reasons about the wrap at 0 / 360.
- Motion is derived, not authored: a card's scale and shift come each second from the heading, the camera's angle on its circle and the viewer's offset (one pose, one owner: `ridge/heading.ts`, whose every change starts a segment from the pose the view has, and whose eases keep each pose inside the baked bound) and the card's distance (`ridge/view.ts` `cardPose`), and ride the compositor as one animation per card.
- The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause.
- A baked asset names its baker version, DEM source and licence in a validated manifest; the terrain credit shown in the scene view's Place submenu comes from the manifest.
## Not in scope
Button size (Void's). Patching the old noise-ridge path. Cone sampling. Live DEM access from the browser.

View file

@ -1,101 +0,0 @@
# Symphony grammar harvest: Mimir's bioacoustic research
Follow-up: `ratatoskr:follow_up:symphony-grammar-harvest-mimir`. Source: GameCult/Mimir at
commit c6f4541eea61 (exists; read at that ref, not main), read-only through the forge API.
Paths below are Mimir paths. Written for Aqua (AquaSynth) before the generative activity grammar. It lives here because the symphony is a Ratatoskr cut (dings, then orbiting personas) and this repo is where its spec will be read; the follow-up named AquaSynth, where void holds no push right, so move it there if Aqua prefers.
## 1. The problem
One Mind's identity has to be a timbre plus a contour that stays recognisable after it is mixed with
the other Minds and passed through a lossy path. The symphony adds harmony (several Minds sounding
together as music), which Mimir never needed: Mimir emits one voice at a time, a low-gain song per speaker.
## 2. What Mimir found that transfers
Confidence: A = measured number in a receipt, B = measured but synthetic or single run,
C = design claim or authored opinion with no measurement behind it.
| Claim | Evidence | Conf. |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| Tidy lab beeps are the wrong signal for a room; a birdsong-like motif replaced them. | `docs/bioacoustic-timeline-watermark.md` L3-10 (stated as a decision, no listening test). | C |
| Identity is carried redundantly: contour survives pitch shift, rhythm survives bad frequency response, formant envelope survives a dead band, speaker variants expose room asymmetry. | same doc L82-95. Argument, not an ablation. | C |
| A word needs no sequence grammar: one heard word identifies its event directly (128 words x 2 speaker variants, 4 syllables each), in an event slot that repeats about every 41 s (derived, not reported: 128 words x 2 speakers = 256 events at 0.16 s spacing = 40.96 s, from `MimirBioacousticTimeline.cs` L34-39 and `SymbolForEvent` L735-739; no receipt or doc states it). No de Bruijn grammar. | same doc L26-33; `src/Mimir.Runtime/Synchronization/MimirBioacousticTimeline.cs` (WordCount, SymbolCount = WordCount\*SpeakerCount, BuildMotifs ~L690-730). | B |
| Word identity survives mel-cepstral warp/blur degradation; timing does not unless fitted as one global clock/delay hypothesis. | `docs/bioacoustic-training-harness.md` L58-112: identity 0.908-0.997 on clean input only; degraded identity 0.532-0.908 and timing 0.187-0.728 for compact-fast-index across the four degraded cases in `artifacts/bioacoustic-training/bioacoustic-20260524-150729/compact-fast-index/*/summary.json` (`IdentityScore`, `TimingScore`); clean timing 0.357 before vs 0.905 after the global clock fit. | A (synthetic, clean-only range) |
| Contestant shapes were scored against the same decoder family and damage panel; the best scorer was the six-syllable "canary-packet-trill", a hypothesis not confirmed on a physical room (two timing chips plus four payload-coloured formant notes), not the literal bird imitations. | `research/bioacoustic-contestants-2026-05-24.md` L24-38, L128-174 (honest floor 88.4 language_score, 19 bps, payload 1.000 clean), L487-489 (96 ms motif is the best tradeoff). | B |
| Too-short or too-tight songs fail under blur: 0.100 s event spacing lost anchors to overlap; 0.105 s kept; 78 ms motif and 5-syllable finch-burst-packet collapsed (blur-light 4.358, the razor decoder; 218.368 with the sprint decoder, L453-454). | contestants doc L169-171, L446-455, L487-489. | A |
| A 3-bit payload variant (separate band/rhythm bit) did not survive degradation (best 12.849, clean 8.084). | contestants doc L183-185. | A |
| Real birds carry identity through redundant contour, roughness, onset statistics and cepstral envelope together; Redpoll is dense chatter with short vertical attacks, not a neat token stream; Guan is a slow broad curved phrase, good for probing the channel, poor for bitrate. The packet song was judged "still too ladder-like". | contestants doc L565-581 (two Xeno-canto mirrors via Wikimedia; Brown Thornbill file invalid, L511-513, L534-539). Flux numbers L549-562. | B (two recordings, hand reading) |
| Positive log-mel spectral flux is a good onset/anchor surface; sustained bands recede, attacks and glides light up. | contestants doc L541-545, L577-581; but the naive flux decoder lost on speed (33.466 vs 88.129 score, clean roundtrip, L158 and L231-237). | B |
| Once the schedule is known, the receiver only discriminates among a few local candidates; wide identity search is only for acquisition. Streaming decoder reached 1121 score at 62.6x realtime, payload 1.000 on all nine damage cases. | contestants doc L248-309. | A (synthetic damage) |
| Polarity must be a nuisance variable; mic paths flip sign. | contestants doc L391-395. | B (physical, one capture) |
| Physical room run: with per-channel acquisition offsets the co-streamer shotgun mic (ch1) locked 37/37 events, payload 1.000, timing 0.828; the cardioid/near mic (ch0) reached 26/37, payload 0.595, and stayed unreliable. | contestants doc L371-388. | B (physical, one capture) |
| Speaker split: left and right vocabularies differ in root (x0.94 / x1.08) and syllable weights, so each side is separable. | `MimirBioacousticTimeline.cs` BuildMotifs ~L704-725 (read as code, no experiment isolates the benefit). | C |
Rendering recipe actually in code (`MimirBioacousticTimeline.cs` AddSyllable ~L610-640): each syllable is
a log-frequency glide (exponential sweep) with a raised-cosine envelope, summed partials at
1, 1.5, 2, 2.75 times the glide (weights 1, 0.42, 0.24, 0.10) plus 0.08 weight of a slow "air" term,
20-32 ms long, four per word, gain 0.030 (canary profile 0.024 in `MimirBioacousticContestant.cs`).
Word roots are log-spaced 2.6 to 9.6 kHz; syllable frequencies are clamped 2.3 to 14.6 kHz;
word length 118 ms. Contours come from a small hand-written bank (8 contour shapes and 8 rhythm
offset sets, chosen by hash of word and speaker).
## 3. Design constraints for Aqua's grammar
1. Identity lives in several channels at once: contour (syllable glide shapes), log-frequency position
(root), formant envelope (the partial ratios), rhythm (inter-syllable offsets) and per-speaker
timbre. No single channel may be load-bearing. Place Minds on a log-frequency axis, not linear.
2. Do not build a sequence grammar for identity (de Bruijn or otherwise). The whole word is the unit;
a hearer should identify the Mind from one short phrase. (watermark doc L31-33.) What it gives up:
a de Bruijn code has a provable recovery property from a symbol stream; per-word identity has only
an empirical one.
3. Keep words short and distinct, but not so tight that they overlap: Mimir's measured edge was about
100 to 105 ms event spacing and a 96 ms six-syllable motif; below that identity decayed. Aqua's
events need not carry timing, so it can relax this, which is untested.
4. Use sharp onsets for placement but avoid a ladder of evenly spaced rungs; Mimir's own verdict was
that its packet song was still too ladder-like and real birds use irregular, redundant contour
(contestants doc L573-576). Vary rhythm and syllable length per word as the code already does.
5. Reject: row of tidy lab beeps (watermark doc L3-6); literal bird imitation as an end in itself (the
prettiest contestant, nightingale-cascade, was expensive and easy to confuse under smearing, per
`MimirBioacousticContestant.cs` profile note); a third payload bit on a second axis (measured loss).
6. Keep the generator deterministic from a typed description (contour, root, rhythm, speaker tint),
authored once and rendered, not regenerated in the audio callback. Contestants doc L493-496 states
this as the AquaSynth lesson: separate authoring intent from realtime DSP.
## 4. What does not transfer, or is unknown
- Harmony. Mimir emits one voice per speaker and decodes one stream; nothing in the research tests
simultaneous voices, intervals between Minds, consonance, or masking between concurrent songs.
Searched for "harmon"; the only hit is the `HarmonicNotch` anchor kind (an envelope notch used as a
timing anchor, `MimirBioacousticContestant.cs` ~L33, L231), not musical harmony.
- Orbiting spatialisation. Mimir's left/right split is a calibration device (one vocabulary per
speaker to learn each side of the room), not a perceptual pan or orbit. Nothing here informs it.
- Pleasantness. There is no listening test, no psychoacoustic metric, and no loudness-weighted score
in any file read. The only pleasantness evidence is the authored one-line verdicts on each profile in
`MimirBioacousticContestant.cs` L52-170 ("lab bird with a clipboard", "most plausible room sound",
"prettiest contestant") and the "wrong animal for a room" sentence. The score is
`realtime * timing * frequency * payload_bitrate` (contestants doc L39-59): decodability only.
Gain 0.021-0.030 is chosen for low audibility, not for pleasing anyone.
- Mimir's numbers are synthetic damage (mel-cepstral and log-mel warp/blur) plus a few Scarlett loopback
runs. The first physical room runs decoded mics only partially (contestants doc L355-395), and the
later live receipt's cardioid result was retracted as noise
(`calibration/bioacoustic/complex-contour-live-20260525-063229.md`, correction at watermark doc L225-230).
- The pipeline decodes against a known schedule and tiny candidate set; Aqua's listener is a human
mix, so none of the decoder scores say how distinguishable Minds are to a person.
- Not read: `src/Mimir.BufferSmoke` (the harness executable). It does not match a "bioacoustic" path
filter on the tree listing, so I read its documentation (`docs/bioacoustic-training-harness.md`) and
the `MimirBioacoustic*.cs` sources instead. The `artifacts/bioacoustic-training/` receipts were listed
but not opened beyond the summary text in the docs.
## 5. Open questions for Aqua
- What is the "decoder" for Aqua: a human listener, a classifier, or both? Constraints above only
hold against a machine decoder.
- Does a Mind keep one word for life, or does the grammar generate many songs sharing a timbre and root
(activity-dependent contour over a fixed identity)? Mimir only has fixed words.
- How many Minds, and how are roots allocated on the log axis when several sound at once? Mimir used 2
speaker variants per word and 128 words; harmony will change the spacing rule.
- Which dimension bends with activity (contour, rhythm density, gain) and which must stay fixed
(timbre, root)? Mimir has no activity channel to copy.
- Is a measured pleasantness proxy wanted (roughness, masking, loudness-weighted)? Mimir has none to reuse.
- Spatialised orbit plus a speaker-keyed timbre: if the pan moves, does identity still rest on timbre
alone? Mimir's per-side vocabulary is not a precedent.

View file

@ -20,44 +20,3 @@ directory whose ancestors hold no empty `package.json` (esbuild reads them).
Timings from SwiftShader are CPU time: use them for the split between passes and for before and Timings from SwiftShader are CPU time: use them for the split between passes and for before and
after of one change, never as a phone frame time. after of one change, never as a phone frame time.
## Ridge live scene
`ridgeLive.html` is one live scene (tier 'full', the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot: `?h=214&sun=232:22&speed=6` (start heading, the sun's azimuth and elevation, degrees a second of rotation),
`?sky=night&lines=1`. `window.live` offers `hold(h)`, `pose()`, `plate()`, `left()` (the plate's left edge on the page) and `plateCost()` (ms of main thread to paint one plate here); `window.longTasks` lists the tasks over 50 ms.
A held heading's sun lands within a tenth of a pixel of the column the heading owner says, across re-centres of the plate.
## Ridge look sheet
Renders a baked place (`?place=`, the index default otherwise) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun)
by a set of looks (`RidgeLook`, `src/app/features/scene/ridge/lightCards.ts`, the one owner of look values), one 480x270 canvas per cell, drawn by the app's own still
path (`createRidgeScene` at tier 'still' over a `createBackdrop` of the tiles round the heading), at the rest azimuth unless `?views=` says otherwise. The sky
behind a cell is the app's own, without clouds. Not shipped.
...ridgeSheet.html?views=214:0:200,0:0:200,214:90:98.2&sky=2 # one column per view heading:phi:offset (degrees, degrees, metres) at one sky (an index of SKIES)
`&sun=100:6` puts the sun of that sky at compass azimuth 100, 6 degrees up (the stars are those of the moment the sheet is opened): a sun at the heading's side shows where the turned sky puts it, `&sky=5&lines=1` is the night.
A heading of 0 or 360 is across north; a phi other than 0 is the offset-only rotation mode (the camera circling the centre, the view direction staying); the offset is
clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, another phi: `camera.r_max_m`).
npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/
http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies
...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly)
...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D
...?w=640 # cell width
`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key).
A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab).
Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune:
| preset | values |
| --- | --- |
| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) |
| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 |
| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 |
| painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 |
| painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 |
Named moments (`ridgeSheet.html?named=1`): the six moments of the Sky menu (dawn, morning, noon, golden hour, dusk, night) at the baked place on the December and June solstices, drawn from `momentFor` as the app draws them (`SKY_MOMENTS` in `ridge/skyMoment.ts` is the table tuned by eye from this sheet). Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).

View file

@ -1,5 +1,6 @@
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the // Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
// tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks` // tier, `?probe=1` shows the rAF median/p95 readout. The bake record (each chunk's cost, from
// the scene's `onBake`) and the long tasks the page saw are on `window.bakes` and `window.longTasks`
// for a driver to read. Not shipped. // for a driver to read. Not shipped.
import { startBackgroundScene } from '../../src/app/features/scene'; import { startBackgroundScene } from '../../src/app/features/scene';
import type { SceneTier } from '../../src/app/features/scene'; import type { SceneTier } from '../../src/app/features/scene';
@ -7,7 +8,8 @@ import type { SceneTier } from '../../src/app/features/scene';
const q = new URLSearchParams(location.search); const q = new URLSearchParams(location.search);
const tier = (q.get('tier') ?? 'full') as SceneTier; const tier = (q.get('tier') ?? 'full') as SceneTier;
const canvas = document.getElementById('c') as HTMLCanvasElement; const canvas = document.getElementById('c') as HTMLCanvasElement;
const w = window as unknown as { scene: unknown; longTasks: number[]; firstViewMs: number }; const w = window as unknown as { scene: unknown; bakes: unknown[]; longTasks: number[]; firstViewMs: number };
w.bakes = [];
w.longTasks = []; w.longTasks = [];
try { try {
new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({ new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({
@ -19,6 +21,7 @@ try {
const t0 = performance.now(); const t0 = performance.now();
startBackgroundScene({ tier }, {}, { startBackgroundScene({ tier }, {}, {
canvas, canvas,
onBake: (b: unknown) => w.bakes.push(b),
} as never).then((scene) => { } as never).then((scene) => {
w.firstViewMs = performance.now() - t0; w.firstViewMs = performance.now() - t0;
w.scene = scene; w.scene = scene;

View file

@ -1,8 +0,0 @@
<!doctype html>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Ridge live scene</title>
<body style="margin:0;background:#111">
<div id="host" style="position:fixed;inset:0;overflow:hidden"><canvas id="c" style="position:absolute;left:0;top:0;width:100%;height:100%"></canvas></div>
<script type="module" src="./ridgeLive.ts"></script>
</body>

View file

@ -1,71 +0,0 @@
// One live ridge scene (tier 'full': the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot. Not shipped.
// `?h=214` the heading the scene starts at; `?sun=232:22` the sun's compass azimuth and elevation (degrees); `?sky=night` the stars of now (sun below the horizon); `?lines=1` the constellation lines.
// `?speed=6` degrees a second the view turns (rotation mode 'both'); 0 holds it. The page offers `window.live`: `hold(h)` turns the view by hand, `pose()` is the heading owner's pose now,
// `plate()` the sky plate's element and `left()` its left edge and width on the page.
import { parseManifest } from '../../src/app/features/scene/ridge/manifest';
import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky';
import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop';
import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge';
import { anchor, hold, poseAt } from '../../src/app/features/scene/ridge/heading';
import { setCamera } from '../../src/app/features/scene/cameraState';
import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view';
import { paintSky } from '../../src/app/features/scene/ridge/physicalSky';
import { nightBodies } from '../../src/app/features/scene/ridge/nightBodies';
import { plateCamera, plateSize, SLACK_MIN_DEG } from '../../src/app/features/scene/ridge/skyTurn';
const q = new URLSearchParams(location.search);
/** The main-thread tasks over 50 ms the page saw, ms: `window.longTasks`. */
const longTasks: number[] = [];
(window as unknown as { longTasks: number[] }).longTasks = longTasks;
try {
new PerformanceObserver((l) => l.getEntries().forEach((e) => longTasks.push(e.duration))).observe({ entryTypes: ['longtask'] });
} catch {
// No long-task entries in this browser.
}
async function main() {
const index = await (await fetch('/public/ridge/index.json')).json();
const dir = `/public/ridge/${index.places[q.get('place') ?? index.default]}/`;
const manifest = parseManifest(await (await fetch(`${dir}manifest.json`)).json(), dir);
const { view } = manifest;
const [az, el] = (q.get('sun') ?? '232:22').split(':').map(Number);
const time = new Date();
const sun = q.get('sky') === 'night' ? { azimuth: 0, elevation: -30, time } : { azimuth: az, elevation: el, time };
const physical = makePhysicalSky(sun, 0, view);
const h0 = Number(q.get('h') ?? view.lookAzDeg);
anchor(view.place.id, h0, performance.now());
setCamera({ mode: 'both', speedDegPerS: Number(q.get('speed') ?? 0), offsetM: 200 });
const backdrop = createBackdrop(manifest, physical);
await backdrop.ensure({ fromDeg: h0 - HFOV_MAX_DEG, toDeg: h0 + HFOV_MAX_DEG });
const canvas = document.getElementById('c') as HTMLCanvasElement;
const scene = createRidgeScene({ canvas, tier: 'full', sky: { ...physical.stops, physical }, backdrop, lines: q.get('lines') === '1' });
const host = document.getElementById('host') as HTMLElement;
// The plate is the host's div whose first child is a canvas (the rig's first child is a div, the rain's has none).
const plate = () => [...host.children].find((c) => c.tagName === 'DIV' && c.firstElementChild?.tagName === 'CANVAS');
(window as unknown as { live: unknown }).live = {
scene,
hold: (h: number) => hold(h, performance.now()),
pose: () => poseAt(performance.now()),
plate,
/** Mean ms of the main-thread part of painting one plate here (the dome, its pixels and the bodies, not the canvas upscale), over `n` runs. */
plateCost: (n = 10) => {
const w = innerWidth;
const h = innerHeight;
const win = windowFor(view, w, h);
const { cssW } = plateSize(win, w, h, devicePixelRatio >= 2 ? 2 : 1, SLACK_MIN_DEG);
const t0 = performance.now();
for (let i = 0; i < n; i += 1) nightBodies(physical, paintSky(physical, cssW, h, plateCamera(win, 214 + i, SLACK_MIN_DEG)), true);
return (performance.now() - t0) / n;
},
left: () => {
const r = plate()?.getBoundingClientRect();
return r && { left: r.left, width: r.width };
},
};
document.title = 'ridge live: done';
}
main().catch((e) => {
console.error(e);
document.title = `ridge live: failed ${e}`;
});

View file

@ -1,8 +0,0 @@
<!doctype html>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Ridge look sheet</title>
<body style="margin:0;background:#111;color:#ddd;font:12px monospace">
<div id="sheet" style="padding:8px"></div>
<script type="module" src="./ridgeSheet.ts"></script>
</body>

View file

@ -1,279 +0,0 @@
// Look sheet for the lit ridge cards: a baked place lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas drawn by the app's own still path
// (`createRidgeScene` at tier 'still', the tiles of the arc round the heading, each card at `cardPose`). Not shipped.
// `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading
// of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre.
// `?place=vienna` the baked place (index.json's default if absent)
// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=<JSON array, url-encoded or base64>` replaces the rows with
// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
// The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`),
// without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or:
// `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation
// `?night=1` the night set: the next new moon, first quarter and full moon from today (or from `?from=YYYY-MM-DD`), each at four night hours
// (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon
// `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped)
// `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only)
import { DEFAULT_LOOK, PHYSICAL_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards';
import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards';
import { parseIndex, parseManifest } from '../../src/app/features/scene/ridge/manifest';
import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky';
import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view';
import { onScreen } from '../../src/app/features/scene/ridge/nightBodies';
import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop';
import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge';
import { anchor, hold } from '../../src/app/features/scene/ridge/heading';
import { setCamera } from '../../src/app/features/scene/cameraState';
import { sunAt } from '../../src/app/features/scene/ridge/sunAt';
import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue';
import { moonPhase } from '../../src/sky/moon.js';
import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment';
type Override = Partial<Omit<RidgeLook, 'inkKeep' | 'reliefLight'>> & {
label: string;
/** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */
base?: 'physical';
inkKeep?: Partial<RidgeLook['inkKeep']>;
reliefLight?: Partial<RidgeLook['reliefLight']>;
};
interface Column {
label: string;
elevation?: number;
azimuth?: number;
/** A moment: the sun is the real one of it. */
time?: Date;
/** Where the view faces and the camera stands: heading and phi in degrees, offset in metres. Absent: the rest azimuth, phi 0, the app's default offset. */
view?: { h: number; phi: number; r: number };
}
/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. The band of the elevation (`skyBand`) picks the display budget. */
const SKIES: Column[] = [
{ label: 'dawn 2 deg', elevation: 2, azimuth: 100 },
{ label: 'morning 15 deg', elevation: 15, azimuth: 135 },
{ label: 'noon 55 deg', elevation: 55, azimuth: 190 },
{ label: 'golden 6 deg', elevation: 6, azimuth: 244 },
{ label: 'dusk -3 deg', elevation: -3, azimuth: 262 },
{ label: 'night -30 deg', elevation: -30, azimuth: 0 },
];
/** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */
const PRESETS: Record<string, Override> = {
physical: { label: 'physical', base: 'physical' },
swiss: {
label: 'swiss',
base: 'physical',
reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 },
contrastByDistance: 0.9,
hazeScale: 6,
hazeTint: [0, 0.05, 0.25],
nearWarm: 0.5,
inkScale: 0.6,
},
poster: {
label: 'poster',
base: 'physical',
reliefWeight: 0.15,
cardToneStep: 0.25,
cardGradient: 0.5,
inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 },
hazeScale: 4,
},
painterly: { label: 'painterly (default, cel 3)' },
'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 },
'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 },
'painterly-cel-4': { label: 'painterly-cel-4', celBands: 4 },
};
const merge = (o: Override): { label: string; look: RidgeLook } => {
const { label, base: baseName, inkKeep, reliefLight, ...rest } = o;
const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK;
return {
label,
look: {
...base,
...rest,
inkKeep: { ...base.inkKeep, ...inkKeep },
reliefLight: { ...base.reliefLight, ...reliefLight },
},
};
};
function parseLooks(raw: string): Override[] {
const tries = [() => decodeURIComponent(raw), () => atob(raw.replace(/-/g, '+').replace(/_/g, '/'))];
for (const t of tries) {
try {
const v = JSON.parse(t());
if (Array.isArray(v)) return v.map((e, i) => ({ label: `look ${i + 1}`, ...e }));
} catch {
// try the next encoding
}
}
throw new Error('looks= is neither a url-encoded nor a base64 JSON array');
}
const q = new URLSearchParams(location.search);
const HOUR = 3_600_000;
/** The first moment at or after `from` the moon's elongation passes `target` degrees (new 0, first quarter 90, full 180). */
function nextPhase(from: Date, target: number): Date {
const err = (t: number) => ((moonPhase(t).elongationDeg - target + 540) % 360) - 180;
let t = from.getTime();
while (!(err(t) < 0 && err(t + HOUR) >= 0)) t += HOUR;
let a = t;
let b = t + HOUR;
for (let i = 0; i < 20; i += 1) {
const m = (a + b) / 2;
if (err(m) < 0) a = m;
else b = m;
}
return new Date(b);
}
/** The first evening moment (UTC hour steps of 10 minutes from `day`) the sun is at `deg` below the horizon, going down. */
function sunDownTo(place: Parameters<typeof sunAt>[0], day: Date, deg: number): Date {
let t = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), 12);
while (sunAt(place, new Date(t)).elevation > -deg) t += 10 * 60_000;
return new Date(t);
}
const fmt = (d: Date) => d.toISOString().slice(0, 16).replace('T', ' ') + 'Z';
function momentsFrom(params: URLSearchParams, place: Parameters<typeof sunAt>[0]): Column[] | undefined {
const list = params.get('moments');
if (list)
return list.split(',').map((iso) => {
const time = new Date(iso.trim());
if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`);
return { label: fmt(time), time };
});
// `named=1`: the six named moments of the sky menu (`momentFor`, as the app draws them) on both solstices at the place: the look sheet the elevation table is tuned from.
if (params.get('named'))
return ['2026-12-21', '2026-06-21'].flatMap((day) =>
MOMENT_IDS.map((id) => {
const time = momentFor({ kind: 'named', id }, place, new Date(`${day}T12:00:00Z`));
return { label: `${id} ${day.slice(5)} ${fmt(time)}`, time };
})
);
if (!params.get('night')) return undefined;
const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date();
const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number);
const cols: Column[] = [];
const phases: [string, number][] = [['new', 0], ['first quarter', 90], ['full', 180]];
phases.forEach(([name, deg]) => {
const peak = nextPhase(from, deg);
const day = Date.UTC(peak.getUTCFullYear(), peak.getUTCMonth(), peak.getUTCDate());
hours.forEach((h) => {
// Hours before 12 belong to the night that ends the day of the phase, so the hours run on from the evening.
const time = new Date(day + (h < 12 ? 24 + h : h) * HOUR);
cols.push({ label: `${name} ${fmt(time)}`, time });
});
if (deg === 180) cols.push({ label: `deep dusk, full moon ${fmt(sunDownTo(place, peak, 10))}`, time: sunDownTo(place, peak, 10) });
});
return cols;
}
/** `?views=h:phi:r,...`: one column per view, all at the sky `?sky=` (default noon), whose sun `?sun=az:el` may put elsewhere (compass degrees, degrees above the horizon). */
function viewsFrom(params: URLSearchParams): Column[] | undefined {
const list = params.get('views');
if (!list) return undefined;
const [az, el] = (params.get('sun') ?? '').split(':').map(Number);
const sky = { ...SKIES[Number(params.get('sky') ?? 2)], ...(Number.isFinite(az) && Number.isFinite(el) ? { azimuth: az, elevation: el } : {}) };
return list.split(',').map((v) => {
const [h, phi, r] = v.split(':').map(Number);
return { ...sky, label: `h ${h} phi ${phi} r ${r}`, view: { h, phi, r } };
});
}
const preset = q.get('preset');
const pinned = q.get('moments') || q.get('night');
const rows = (q.get('looks')
? parseLooks(q.get('looks') as string)
: preset && preset !== 'all'
? [PRESETS[preset] ?? PRESETS.physical]
: pinned
? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise
: Object.values(PRESETS)
).map(merge);
const withLines = q.get('lines') === '1';
const LINES_JSON = 'https://raw.githubusercontent.com/ofrohn/d3-celestial/master/data/constellations.lines.json';
/** Debug: the constellation id of each packed chain, in the generator's order (feature by feature, chain by chain). */
async function chainIds(): Promise<string[]> {
const gj = await (await fetch(LINES_JSON)).json();
return gj.features.flatMap((f: { id: string; geometry: { coordinates: unknown[] } }) => f.geometry.coordinates.map(() => f.id));
}
const W = Number(q.get('w') ?? 480);
const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16);
const root = document.getElementById('sheet') as HTMLElement;
async function main() {
const index = parseIndex(await (await fetch('/public/ridge/index.json')).json());
const DIR = `/public/ridge/${index.places[q.get('place') ?? index.default] ?? index.places[index.default]}/`;
const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR);
const { view } = manifest;
const win = windowFor(view, W, H);
const now = new Date();
const columns = viewsFrom(q) ?? momentsFrom(q, view.place) ?? SKIES;
const ids = q.get('labels') === '1' ? await chainIds() : undefined;
const table = document.createElement('table');
table.style.borderSpacing = '4px';
root.append(table);
const head = table.insertRow();
head.insertCell();
columns.forEach((c) => (head.insertCell().textContent = c.label));
const tr = rows.map((r) => {
const row = table.insertRow();
row.insertCell().textContent = r.label;
return row;
});
for (const col of columns) {
const time = col.time ?? now;
const sun =
col.time !== undefined
? sunAt(view.place, col.time)
: { elevation: col.elevation as number, azimuth: col.azimuth as number, time };
const physical = makePhysicalSky(sun, 0, view);
const sky = { ...physical.stops, physical };
const v = col.view ?? { h: view.lookAzDeg, phi: 0, r: 200 };
for (let r = 0; r < rows.length; r += 1) {
// A host as the page has one: a positioned box of the cell's size holding the canvas the scene paints.
const host = document.createElement('div');
Object.assign(host.style, { position: 'relative', width: `${W}px`, height: `${H}px`, overflow: 'hidden' });
const cell = document.createElement('canvas');
Object.assign(cell.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%' });
host.append(cell);
tr[r].insertCell().append(host);
// The heading owner as the app leaves it: this view's heading, the camera on its circle at phi (offset-only rotation), the offset the viewer chose.
const t0 = performance.now() - 3_600_000;
anchor(`sheet-${manifest.bakeId}-${columns.indexOf(col)}-${r}`, v.h, t0); // a key of its own: every cell starts from phi 0
setCamera({ mode: 'offset', speedDegPerS: 1, offsetM: v.r }, t0); // the offset-only rotation mode for phi seconds at 1 degree per second ...
hold(v.h, t0 + v.phi * 1000); // ... then the view is held at h: the mode is still, the camera stays at phi (phi 0 is the camera on its heading)
const backdrop = createBackdrop(manifest, physical, { lighter: (m, s) => createLighter(m, s, rows[r].look) });
await backdrop.ensure({ fromDeg: v.h - HFOV_MAX_DEG, toDeg: v.h + HFOV_MAX_DEG });
const scene = createRidgeScene({ canvas: cell, tier: 'still', sky, backdrop, lines: withLines });
scene?.dispose();
if (ids) {
// Debug labels: each chain's id at the mean of its vertices that lie in the frame.
const ctx = cell.getContext('2d') as CanvasRenderingContext2D;
ctx.font = '11px monospace';
ctx.fillStyle = '#ffd24a';
linesAt(physical.sun.time, view.place.lat, view.place.lon).forEach((chain, i) => {
const pts = chain.map((p) => onScreen(win.camera, p.azimuth, p.elevation)).filter((a) => a.x >= 0 && a.x <= 1 && a.y >= 0 && a.y <= 1);
if (!pts.length) return;
const mx = pts.reduce((a, p) => a + p.x, 0) / pts.length;
const my = pts.reduce((a, p) => a + p.y, 0) / pts.length;
ctx.fillText(`${ids[i]} ${pts.length}/${chain.length}`, mx * W, my * H);
});
}
}
}
document.title = 'ridge look sheet: done';
}
main().catch((e) => {
console.error(e);
root.textContent = `ridge look sheet failed: ${e}`;
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 408 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 490 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 540 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 732 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 370 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 638 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 766 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 678 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 522 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 688 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 644 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 546 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 988 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 932 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 838 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 962 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 852 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 914 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 558 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 326 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 550 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 282 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Some files were not shown because too many files have changed in this diff Show more