commit f4257ed9cf8351091ece5685764c2742acdc8449
parent e96cb2bc8a4a5c28139ee22e027c2029cea5756c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 02:03:24 -0400
Merge main into r28/integration: the umtool redesign P0–P2a (live) and its project-cache fix
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# editor/CHANGELOG.md
Diffstat:
113 files changed, 5772 insertions(+), 673 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -27,6 +27,14 @@
- **`pnpm ops delete-site {"id", "dryRun"?, "force"?}` deletes a site, plan first.** It removes the site's directory (its settings, pages, tags, charts and reports), its last build and publish state, and its export staging, and says what it keeps: every channel's data (never touched), the Pages project and anything already deployed (a delete does not undeploy), a deployed hub until it is rebuilt. A site with a Pages project, a recorded deploy or reports of its own is refused unless `force`; a missing site, a linked site directory or a publish stage running is refused whatever.
- **A paused parakeet transcription no longer leaves its working files in the temp directory**, and each run clears what a crashed or killed run left there more than a day ago (unless another run still owns it).
- **New settings key `generation.verdicts`** (SETTINGS.md): the verdict bench's bar (`agreement`, `contradictedRecall`, `notFoundRecall`, fractions) and the passing models you ticked (`models`, never set automatically).
+- **umtool has a new look, in dark and light: the desk and the reader.** Tool chrome is a warm-ink desk (warm grey in light) and anything a source said — a quote, a post, a transcript window, the clip and claim benches' transcripts — sits on a pale green-grey reader surface, so a quote is never mistaken for a claim about it. Colours are roles: Signal (teal) only for focus, the lit line and the one primary action; Meter (violet) for counts and spend; the three verdicts always as glyph and word (✓ ? ✕), never on the reader. The faces are vendored (Archivo, IBM Plex Sans and Mono, Source Serif 4 for the reader) and load with no network.
+- **umtool: Auto / Light / Dark at the foot of the rail.** Auto follows the system; a choice is a cookie the server reads, so the page is served in it with no flash.
+- **umtool: every page has the rail.** The mark and the wordmark (home), the places (unchanged: home · browse · decisions · articles · mix · find · song ▸), + Create (a new article or a new project), Pinned, what umtool is running, and the theme. The page's name is its title under the breadcrumb. The clip, claim and takes benches drop the rail and take the full width.
+- **umtool: /browse/decisions is a lit list.** One line per decision, grouped by project; `j` / `k` (or the arrows) move the lit line from anywhere on the page, and focus goes with it. The head glides 120 ms, and jumps under reduced motion.
+- **umtool's decisions API carries the inbox: each decision's piece, group and one action.** `GET /api/browse/decisions` still answers one row per decision (`items[]`, each row's `project`, `href` and `counts` as before; a note's `href` still ends in `note=<id>`), and each row now also names its `piece` — `a:<site>/<report>` for an article and the video projects made from it, `p:<project>` for a project no article claims — its `category`, its `group` (Your call → Review → Blocking → Notes → Open → Ready to finish → Quiet), one `action` whose label names the result ("Make i3 current", "Adjudicate claim", "Answer note"), the piece's `lifecycle` and `hidden`. A new `groups` key holds the same rows as cards, one per piece and kind, with counts; `hidden` counts the rows on parked or done pieces. Five decisions are read from disk for the first time: `iteration-ready` (a finished iteration newer than the current one), `iteration-failed` (with what it spent), `research-proposal` (an acquisition waiting on a yes or no, read from `proposals.json`, never through the editor), `link-ambiguous` and `looks-done`.
+- **umtool: a piece can be parked or marked done.** `POST /api/pieces/lifecycle {piece, state}` sets `active`, `parked` or `done`, kept in `REPORTS_ROOT/.umtool/lifecycle.json` with when and by whom; a parked or done piece's decisions stay in the list, `hidden`. "Looks done" — a song with every cut, a final video with a `share-*` batch, a published article with its video — is only ever a suggestion (a `looks-done` decision) and never sets it. `GET /api/pieces` lists every piece with its stage, lifecycle, linked projects and how many decisions wait on it.
+- **`umtool inbox [--all] [--json]`** prints the decisions grouped and ranked as the inbox shows them, one card per piece and kind, and how many are hidden; `--all` lists the hidden ones and the quiet group.
+- **umtool links an article's video by its iterations first.** A project an article's iteration made (`projectDir`) is that article's, and no other article matches it by slug, so a generated article no longer lists its own `…/i1` as "possible"; `current.video` picks the one its Cut opens, and a project outside the reports root is listed as not reachable here. Then a manifest's `article`, then a unique slug in the article's workspace — the only step that can be ambiguous.
- **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan.
- **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept.
- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
diff --git a/package.json b/package.json
@@ -24,7 +24,7 @@
"wt": "node scripts/worktree.mjs",
"e2e:sharded": "node scripts/run-sharded-e2e.mjs",
"e2e:all": "node scripts/e2e-all.mjs",
- "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs",
+ "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs",
"test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]",
"typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit",
"lint": "pnpm --filter export run lint",
diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -0,0 +1,536 @@
+# umtool redesign — research, decisions, pieces (epic, phase by phase)
+
+## Context
+
+umtool grew one feature at a time: the song deck, then report videos, benches, articles and sites, then in-app generation (r27/r28). Surveyed 2026-10-13 against the live :3050 and the code:
+
+- **Too many places, no single model.**
+ - Nav: home · browse · decisions · articles · mix · find · song▸.
+ - Articles live in two lists (`/articles`, `/sites`). Projects live in `/browse`, and an article's video is a separate project page.
+ - Two creation entries share nothing: `NewProjectMenu` and `/articles/new`.
+ - Song-only tools (mix, find) are top-level. Faces and trims are reachable only through deep links. `/drafts` is dead.
+ - There are five header implementations.
+- **The decision list is noise and misses the decisions that matter.** Live: 797 decisions, 518 "blocking", and **483 of them are `claim-unadjudicated` in `quartering-diet`, a finished video.** The generation-era decisions sit outside `openDecisions()`:
+ - research proposals;
+ - a finished iteration that has not been made current;
+ - failed iterations;
+ - r28's drafted fields.
+- **Running work is half-visible.** Editor-side generation jobs never reach the front door.
+- **Research has no home.** The interactive loop (`/ask`, `/sweep`) runs only inside Claude Code. Agent sweeps run unattended:
+ - their `turns.jsonl` trace is written, but nothing shows it;
+ - coverage (matched / read / partial) exists only as prose;
+ - collected quotes exist only for songs (`lib/shortlist.ts`).
+- **The design system is thin.**
+ - The palette is GitHub-dark (`#0b0e12`, `#58a6ff`, `#3fb950`) and disconnected from the Archilyzer brand (warm ink `#0c0a08`, the Found-line mark, Signal teal, Plex/Archivo).
+ - There are two primitives; 49 files hand-roll controls.
+
+**Goal:** a simpler UI where any function is two clicks away, the decisions the operator has to make come first, and **research is first-class**: transparent, operator-driven, useful with or without media generation.
+
+**Rulings (operator, 2026-10-13):**
+- **The unit is the *piece*.** An article plus the video project(s) made from it is one item with one page; standalone projects are pieces too.
+- **Interleave with release 28.** Phases off r28's surfaces go now; the piece page and Create/Settings wait for r28 on `main`.
+- **Song tooling moves into Tools.**
+- **Full visual refresh**, designed with the frontend-design skill and signed off on a canvas before code.
+- **Research tools are first-class**, beside media generation.
+
+## Design direction (frontend-design brief; the P0 canvas tests and may revise it)
+
+**Subject.** umtool is the Archilyzer operator's studio: research a transcript archive of streamers, rule on evidence, turn findings into articles and videos. One user, keyboard-first, long sittings.
+**The app's single job:** put the next call in front of the operator with its evidence within reach.
+
+**Concept: the desk and the reader.** The tool chrome is a warm-ink desk. Anything a *source* said (transcripts, quotes, posts, article bodies under review) is shown on a **reader surface**: a pale, slightly green-grey screen, like an archive's microfilm reader rather than cream paper.
+- **Encoded truth:** paper is the record, ink is our work. A quote can never be mistaken for our claim about it.
+- **This is the one aesthetic risk.** It is justified by long reading sessions, and it is the clearest line between evidence and editorialising.
+
+**Palette.** Named roles; the hexes are starting points, to be checked with the dataviz skill's validator for contrast and colour-blindness on both surfaces:
+
+| Role | Start | Rule |
+|---|---|---|
+| Ink | `#0c0a08` | Desk background (the brand's dark base) |
+| Desk | `#17140f` | Rail, panels |
+| Seam | `#2b251d` | Hairlines |
+| Bone | `#ece4d6` | Text on ink |
+| Reader | `#dfe5e1` | Source surface (text `#141210`) |
+| Signal | `#3fc1b0` | The ONE interaction colour (brand teal): focus, the lit line, primary action |
+| Meter | `#a59bd8` | Measurement only (counts, coverage, loudness) |
+| Verdicts | moss / ochre / brick | Judgements only. Keep the `globals.css` "colour means something" rule |
+
+**Type.** Fonts are vendored OFL with `next/font/local` (no network; the brand slice hit `fonts.gstatic` failures).
+
+| Role | Face | Where |
+|---|---|---|
+| Display | **Archivo**, expanded width (the brand wordmark face) | Place and piece titles and the Inbox's one big count only |
+| UI | **IBM Plex Sans** | 13–14px, dense |
+| Reader | **Source Serif 4** (opsz) vs **IBM Plex Serif** | Transcripts, quotes, article bodies; the canvas decides |
+| Data | **IBM Plex Mono**, tabular | Timecodes, ids, counts |
+
+**Layout.** A left rail holds the places, pinned pieces, and a **Running** list at its foot with live spend. The centre is the work column. On the right, a **reader pane** opens wherever anything cited is focused: the same component in Inbox, Research, an article, or the claim bench. Benches go full-screen and collapse the rail.
+
+```
+┌rail──────┬ centre ─────────────────────────┬ reader (pale) ──────────┐
+│ Inbox 7 │ RESEARCH "ferret sanctuary" │ Ferret Rescue · 2025-03 │
+│ Research │ 412 matches · 97 recordings │ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │
+│ Work │ read 37 of 97 · full coverage │ …the county said no to │
+│ Tools ▸ │ ▌▸ 1:02:14 the county wants… │ ▌▸ the permit until the │
+│ Settings │ 1:07:40 we're five months… │ groundbreaking which… │
+│──────────│ 0:12:03 sanctuary fund is… │ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │
+│ RUNNING │ │ [pin to board] [copy ⧉] │
+│ sweep i2 │ │ ░░░░░░▮░░░░ 1:02:14/4:10│
+│ $0.41 ▪▪ │ │ │
+└──────────┴──────────────────────────────────┴─────────────────────────┘
+```
+
+**Signature: the lit line.** The brand's Found-line mark becomes the interaction model.
+- Every list is a stack of lines: inbox cards, research hits, transcript cues, clips.
+- The focused line is *lit*: a Signal edge, Bone text, and the play-head notch. The others sit dim.
+- `j`/`k` glide the head (about 120 ms). This is the app's only motion; with reduced motion it is instant.
+- In a transcript, the cited cue is literally the lit line among dim ones: the logo, enacted by the data.
+
+**Quiet supporting device: the cite thread.** A hairline bar showing where a cited second sits in its source (a quote at 1:02:14 of a 4-hour VOD). It is information, not decoration.
+
+**Copy.** Sentence case, literal, active. Buttons name the result ("Approve draft", "Mark done", "Pin to board"). No lead paragraphs. Errors say what to fix.
+
+## Target information architecture
+
+**Rail, every page (one `AppShell`):** Inbox · **Research** · Work · Tools · Settings · **[+ Create]**, plus the **⌘K jump** to any piece, case, place or create action.
+
+| Place | URL | What it is |
+|---|---|---|
+| **Inbox** | `/` | The decisions, grouped and ranked: **Your call** (research proposals and failed runs → review gates: drafts, iteration ready → blocking on active pieces → notes) → **Ready to finish** → quiet info, collapsed. Each card: piece · what · count · ONE primary action · park/mute. Running jobs live in the rail. `/?from=` → `/create?from=` (a redirect `has` rule). |
+| **Research** | `/research`, `/research/<case>`, `/research/archive`, `/research/runs/<article>/<n>` | See below. |
+| **Work** | `/work` | Every piece in one list. Facets: stage, kind, site, lifecycle, search. Accepts the old `/browse`, `/articles` and `/sites` query keys. |
+| **Site** | `/sites/<site>` | Kept as a page: its workspace files (`?ws=&rel=`), report-video grid, takes. Linked from Work's site facet. |
+| **Piece** | `/articles/<id>`, `/sites/<site>/<report>` (article-rooted; the MCP/notes addresses); `/projects/<path>` (project-rooted) | Header: title · site · **stage stepper** (Research → Article → Video → Deliver; song: Spec → Cuts → Done) · lifecycle · ⋯. A **Next** card. Tabs: Overview · Article · Iterations · Cut · Media · Build · Deliver · Sources · History (song: Overview · Cuts · Spec · Cover · Notes). |
+| **Benches** | `/projects/<path>/{clip,claim}/<id>`, `…/narration`, `…/takes`, `…/review` | One bench shell: ← piece · N of M · prev/next · key legend · verdict bar · reader pane. Fits 1366×768. |
+| **Create** | `/create` | "What are you making?": research a question (opens a case) · an article from a question or a board · a video from an article, board, recording or sweep report · a song. Policy shown as a chip. |
+| **Tools** | `/tools`, `/tools/{find,mix,song/<mode>,faces,trim/<set>,sources,bench}` | Song piles, find, mix, faces, trims, sources, r28's verdict bench. |
+| **Settings** | `/settings/generation`, `/settings/system` | Generation policy, routes, models, caps and key. System: doctor, index rebuild/prune, storage move-out/tiers (CLI-only today). |
+
+### Research, first-class
+1. **Ask bar + scope.**
+ - A query with phrase/regex/near hints. Scope chips: channels/groups, dates, state, media type, posts.
+ - Source: the local corpus, a published site, or the hub.
+ - **Before running**, show what the scope holds: "3 channels · 2,140 videos · 2019–2026 · transcripts 81% · captions 19%".
+2. **Results as lit lines.**
+ - Grouped by recording, with a timecode and cite thread per hit.
+ - Facets: channel, year histogram, track (transcript vs captions), state.
+ - An honest header: "412 matches · 97 recordings · full coverage". When a cap is hit: "Partial — not reached: X, Y".
+3. **Reader pane.**
+ - The transcript window with the hit lit, ±expand.
+ - Play local media, or fetch the clip through the editor (`fetch_clip`'s route).
+ - Copy citation in the house format; date, state and track shown.
+4. **Reading log.** Each hit is read, skipped or unread; the header reads "read 37 of 97". This is the sweep discipline's coverage rule, made visible for the human too.
+5. **Board (a case).**
+ - Pin a hit as a **snapshot quote**: verbatim text, cite, note, claim line (the shape of `lib/shortlist.ts` `Pick`). Sections and order.
+ - Export as cited markdown in the house format.
+ - Hand off: **Draft an article from this board**, **Start a video from this board**.
+ - Stored umtool-side under `REPORTS_ROOT/.umtool/research/<case>/`, never in the corpus. A case becomes the Research stage of a piece.
+6. **Archive inventory** (`/research/archive`): what the archive can and can't answer. A channels × years heatmap with gaps (`channel_coverage`), transcript/captions/none, video states. Built with the dataviz skill.
+7. **Transparent agent runs.**
+ - Run a sweep from the same scope and watch it step by step: scope → enumerated N (the ids) → batches k/n with each extractor's lines → findings → quote checks (kept / dropped, with the reason) → cost per step.
+ - Past runs replay from the trace.
+ - Agent findings land in the same board shape, so human and agent research meet in one place.
+
+**Mechanism:**
+- Add `"yt-dlp-transcript-mcp": "workspace:*"` to `umtool/package.json`, and use `createCorpusTools` (`mcp/src/callTool.ts`) in-process and server-side. It is the same read-only tools Claude Code uses (`search_transcripts`, `enumerate_matches`, `get_transcripts`, `get_post`, `get_thread`, `channel_coverage`, `list_channels`, `list_tags`) with the same caps (`MCP_POLICY`), already used by `editor/app/api/ops/report-draft/route.ts`.
+- `channel_coverage` needs the editor (it proxies `GET /api/ops/coverage`). Alternatively call `common/controller/channelCoverage.ts` directly when umtool has the corpus on disk.
+
+## Data and engine rules (from the code review)
+
+- **Piece ids are namespaced:** `a:<site>/<report>` (site may be `articles`) and `p:<projectId>`. `resolveTarget` is ambiguous on two-segment ids (`lib/annotations/targets.mjs:139`). Research cases are `c:<case>`.
+- **Linking a project to an article, in order:**
+ 1. each iteration's `projectDir` (`iteration.json`), with `current.video` choosing the Cut tab's project;
+ 2. the manifest's `article` key;
+ 3. a slug match (`lib/articles/links.mjs`).
+
+ Only (3) can raise `link-ambiguous`. Today every generated article shows its own `…/i1` as "possible" (`links.mjs:84-99`). A `projectDir` outside `REPORTS_ROOT` is shown as "not reachable here".
+- **Lifecycle:**
+ - Values are `active | parked | done`; `shipped` is already a derived song state (`lib/project-types.ts:35`).
+ - Stored in `REPORTS_ROOT/.umtool/lifecycle.json`, keyed by piece id. The walk skips dot-dirs (`walk.mjs:105`). It is state, not cache.
+ - "Looks done" signals, which only ever suggest:
+ - a song's derived `shipped`;
+ - a final mp4 (`buildStateOf`, `report.mjs:437`) plus a `share-*` batch (`deliver.mjs listBatches`);
+ - a published article with `report.video.src` or `current.video`.
+- **Decisions API stays one row per decision.**
+ - `GET /api/browse/decisions` keeps `items[]` ungrouped and never drops rows. New fields are additive: `piece`, `category`, `group`, `action`, `lifecycle`, `hidden`. Grouping and hiding happen in the UI.
+ - Reason: the MCP reads `items[]`, filters `open-note`/`unreadable-notes`, uses `project` as the notes target, and needs `href` to end in `note=<id>` (`mcp/src/archivalTools.ts:306-321,393-410`). `lib/hrefs.ts` must keep `?note=` last.
+- **Decision sources from disk, without the editor:**
+ - **Iterations** come from `readArticleIterations` (`lib/articles/generation.ts:338`). `iteration-ready` means done, not current, and newer than current; `iteration-failed` is a failed run. Spend comes from iteration `usage` joined on `jobId`.
+ - **Research proposals** come from common's `readResearchState` (`common/lib/report/draft/research/state.ts:93`); a waiting one has status `proposed`. Not `readResearch()`: that POSTs to the editor, which can rewrite `proposals.json`.
+ - **There is no "waiting on a cap" state.** The daily cap refuses at start and per-job caps end the run. The "spend" category is research proposals plus failed runs.
+ - **Drafts** come from r28 `draftsView()` (`umtool/lib/report/drafts.mjs`). Add `drafts.review.json`, `narration.review.json` and `*-draft.json` to `reportSignature` (`lib/projects/report.mjs:493-510`), or the decision cache never refreshes after an approve.
+ - `verdict-proposed` (r28 M8) is deferred until M8 is built.
+- **Running list:**
+ - Source: the editor's `GET /api/ops/jobs?active=1`. Call it without `kind` (research acquisitions use other kinds) and filter in umtool.
+ - Give `askEditor` a timeout and a ~2 s memo (`generation.ts:76` has none).
+ - Distinguish "editor unreachable" from "WORKER_TOKEN not set" (the editor returns 503).
+ - `ActivityItem` gains `queued`.
+ - Add `/api/ops/jobs` to `e2e/fixtures/editor-stub.mjs`.
+- **Pieces list cost:** the article side re-reads every `report.json` per request (`sites.ts:127-158`). Use a 10–30 s memo, cleared on writes like `clearLinksCache`. Live, warm: `/` 0.89 s, `/api/browse/decisions` 0.27 s.
+- **Redirects:**
+ - Use `redirects()` in `next.config.ts` (`node_modules/next/dist/docs/01-app/03-api-reference/05-config/01-next-config-js/redirects.md`). It runs before the filesystem and passes the query through.
+ - One table in `umtool/redirects.mjs`, imported by both the config and `e2e/redirects.spec.ts` (`maxRedirects: 0`).
+ - Reserved `/browse/<tool>` rules go before `/browse/:path*`. `/:mode(sort|salvage|verify|keeps)` → `/tools/song/:mode`. `/bench` → `/tools/bench`.
+ - **307 (`permanent: false`) until P6**, because browsers cache 308s forever.
+- **LastPage/ResumeChip:**
+ - `DEFAULT_PAGE` → `/work` (`lib/last-page.ts:21`).
+ - The chip shows `res.url`, the address after the redirect.
+ - `/projects` and `/tools/song` get index pages, so the parent walk lands somewhere real.
+
+## Phases
+
+Each phase: its own branch from `main` (or the current integration branch), gates green, merged, and rolled out live (umtool rebuild + restart). At most three parallel Opus lanes. Every shared hotspot has ONE owning lane per phase: `globals.css`, `AppShell`, `app/page.tsx`, `lib/activity.ts`, `editor-stub.mjs`, `redirects.mjs`.
+
+```
+NOW (beside r28) AFTER r28 IS ON main
+P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─► P2b jobs+drafts ─► P4a-1 ─► P4a-2 ─► P4a-3 ─► P4b ─► P6
+ P2a engine ────┘ ├─► P5 create+settings (after P3)
+ └─► R1 research: search+reader+inventory ─► R2 boards ─► R3 transparent runs (after r28)
+```
+
+### P0 — Design (no app code; operator sign-off gates P1)
+- Use the frontend-design skill:
+ 1. brainstorm against the direction above;
+ 2. critique each part against generic defaults and record what changed and why;
+ 3. build the canvas;
+ 4. screenshot it at 1366×768 and 1440×900;
+ 5. critique again and take one thing away.
+- Choose the hexes with the dataviz validator, on both surfaces.
+- Screens, with real data: Inbox · Research (results + reader + reading log) · Research board · Archive inventory · a transparent run · Work · Piece Overview · Piece Media (drafts review) · Clip bench · Create.
+- Include the lit line's motion study and the reader-serif decision.
+- Also produce the URL map and the redirect table.
+- Deliverable: `~/reports/umtool-redesign/canvas.html`, published as a private Artifact for review.
+
+### P1 — Foundation (avoids every r28-touched file)
+- Tokens and the vendored fonts in `umtool/app/globals.css` (Tailwind v4 `@theme`; keep `source(none)` and the `@source` list).
+- Primitives in `components/ui/`, server-safe cva like `button.tsx`/`badge.tsx`:
+ - Panel, Card, Tabs (link-driven), Table, Field/Input/Select, Dialog (native `<dialog>`), Stepper, Kbd, EmptyState, Toolbar;
+ - **LitList** (the signature: roving focus, `j`/`k`, the play-head notch);
+ - **ReaderPane**, **CiteThread**.
+- `AppShell` with the rail.
+ - `BrowseHeader` becomes a thin wrapper over it, same props, until P6: it has 22 users, including r28's `ReportProject`, `NarrationPage` and `app/bench/page.tsx`.
+ - The hand-rolled headers in `app/page.tsx`, `app/mix/page.tsx`, `components/Deck.tsx` and `app/articles/[report]/compare/page.tsx` move onto it.
+ - Keep `<header>`, `.micro`, `[data-nav-group=song]` and `aria-current`, so about 0 specs break. The rail keeps today's entries until P3.
+- `lib/hrefs.ts` (one builder per URL shape, `?note=` last), `e2e/urls.ts`, and an empty `umtool/redirects.mjs` wired into `next.config.ts`.
+- A restyle pass onto the primitives, **excluding** r28-touched files: `IterationsTab`, `NewArticleForm`, `ResearchSlot`, `NarrationReview`, `OnscreenSection`, `ReportProject`, `StructureEditors`, `ChainPanel`, `app/articles/page.tsx`, plus everything new on `r28/integration` and `r28/surfaces`.
+
+### P2a — Engine: pieces, lifecycle, grouping (lib + API; parallel to P1)
+- `lib/pieces.ts`: namespaced ids, the three-step linking, and a memo.
+- `lib/lifecycle.ts`, plus `POST /api/pieces/lifecycle` and `GET /api/pieces`.
+- Decision fields: `category`, `group`, `action`, `lifecycle`, `hidden`. Grouping and ranking are pure functions with unit tests.
+- Disk sources: `iteration-ready`, `iteration-failed`, `research-proposal`, `link-ambiguous`, `looks-done`.
+- The CLI `umtool inbox` prints the grouped list.
+- Must not edit `generation.ts`'s `askEditor` or `editor-stub.mjs`; those belong to P2b.
+
+### R1 — Research: search, reader, inventory (after P1; parallel to P3)
+- Add the `yt-dlp-transcript-mcp` dependency.
+- `lib/research/corpus.ts` over `createCorpusTools`, with the source picker. Routes:
+ - `/api/research/{scope,search,window,coverage}`;
+ - search runs `enumerate_matches` once; it never pages (the coverage rule).
+- `/research`: ask bar, scope preview, LitList results with facets, ReaderPane, copy citation, play/fetch (the editor's fetch-window route, as `fetch_clip` does).
+- `/research/archive` inventory.
+- The reading log, stored per case or per scratch session.
+
+### P3 — Inbox, Work, Tools, URLs (after P1 + P2a)
+- `/` becomes the Inbox.
+ - The dashboard panels become Inbox cards when actionable; otherwise their content goes to `/settings/system`.
+ - `dashboard.spec` is rewritten.
+- `/work` replaces the `/browse`, `/articles` and `/sites` lists. `/sites/<site>` stays a page.
+- Tool pages move to `/tools/*`. `app/[mode]` goes.
+- **`/browse/<path>[/…]` → `/projects/<path>[/…]` moves here** (r28 never touches `app/browse/[...path]`, and its hard-coded `/browse/${id}/review` keeps working through the redirect).
+- The rail becomes Inbox · Research · Work · Tools · Settings · +Create. Create and Settings link to their current homes until P5. ⌘K palette.
+- Blast radius: about 12 specs (about 17 `toHaveURL` checks, 9 href assertions, `projects.spec.ts:264`'s RESERVED_BROWSE list). Old `goto()`s ride the redirects.
+
+### P2b — Jobs and drafts (after r28 on `main`)
+- The editor jobs list goes into `lib/activity.ts` (timeout, memo, 503 vs unreachable), the Running list and the stub route.
+- `drafts-unreviewed` decisions plus the `reportSignature` addition.
+
+### P4a — The piece page (after r28 on `main`), three slices
+- **P4a-1:**
+ - the `PieceView` frame: header, stepper, Next card, tabs;
+ - `ReportProject`'s 14 sections moved unchanged into tabs;
+ - `OnscreenSection` (2144 lines) parked whole in the Build tab until P4b;
+ - an `e2e/urls.ts` `section(project, name)` helper. About 15 specs and 80 tests open a project page and expect every section on it.
+- **P4a-2:** the article-rooted merge.
+ - The iteration's `projectDir` feeds the Cut tab, and the `ArticlePage` tabs become Article/Iterations.
+ - The `PolicyPanel` becomes a chip linking to Settings.
+ - A project linked to an article renders as that article's piece.
+- **P4a-3:** song pieces (`SongProject`, `CutPage`).
+
+### P5 — Create and Settings (after P3 and r28; parallel to P4a)
+- `/create`: one shell over the existing writers.
+ - `POST /api/articles/generate`, for an article from a question.
+ - `POST /api/projects/new` → `scaffoldReportVideo` (`lib/projects/scaffold.mjs`), for a video from a recording or a report.
+ - The chain, `/api/articles/chain`, for a video from an article.
+ - "Research a question" opens a case.
+- `/settings/generation`: `PolicyPanel`, caps, models, the extractor (r28 `ExtractorSelect`).
+- `/settings/system`: thin APIs over `lib/doctor.ts`, `umtool index --rebuild|--prune` and `umtool storage move-out|move-back|deliverables`, with plan-then-confirm on anything destructive (the `DeletePlan` pattern).
+- Specs: `projects.spec.ts:551` (`[data-new-project]`), `article-new.spec`.
+
+### R2 — Research boards (after R1; the hand-offs land with P5)
+- `/research/<case>`:
+ - pin from results or the reader as a snapshot quote;
+ - sections, order, notes, claim lines;
+ - export as cited markdown;
+ - re-verify quotes against the current transcript, and flag drift (the en/en-orig hazard in memory).
+- Hand-offs:
+ - an article from a board: a `report-draft` sweep seeded with the board's cites, or the exported markdown as the first iteration's input (verify which the editor accepts);
+ - a video from a board: scaffold a timeline from the cites.
+
+### R3 — Transparent agent runs (after r28; it touches common's report-draft tasks)
+- In common, `sweep-agent.ts` and `sweep-pipeline.ts` write a structured `trace.jsonl` beside `turns.jsonl`. Events:
+ - `scope`;
+ - `enumerate {n, ids, partial, unreached}`;
+ - `batch {k, ids, lines}`;
+ - `finding`;
+ - `check {quote, ok, reason}`, which includes the dropped quotes that are invisible today;
+ - `cost {usd, step}`.
+- `iteration.json` gains `coverage {matched, read, partial, unreached}`.
+- `/research/runs/<article>/<n>` shows the live step view while running (polls the trace) and replays when done. Old runs fall back to a `turns.jsonl` projection.
+- Agent findings appear as a board, and a run can be started from a case's scope.
+
+### P4b — Benches and Media (after P4a)
+- The bench shell for clip, claim, narration, takes and review, with the ReaderPane. `ClipBench` (3059 lines) keeps its internals.
+- The **Media** tab:
+ - every drafted field with provenance and approve/reject;
+ - absorbs r28's `DraftsReview`/`ReviewPage`/`DraftPanel`/`YoutubeSection`;
+ - on-screen (moved out of Build), narration, and "Draft with <model>" / "Draft everything" per section.
+- One `JobProgress` for chain and editor jobs.
+
+### P6 — Cleanup, docs, audit
+- Redirects become 308.
+- Delete `/drafts`, `BrowseHeader`, the dashboard panels and dead components.
+- Rewrite `umtool/docs/`: dashboard, browse, decisions, sites, projects and README become inbox, research, work, piece, tools and settings.
+- Update the umtool URLs and button names in `AGENTS.md` and `plans/FACTS.md`, and the notes addressing.
+- A screenshot audit of every page against the canvas.
+
+## Constraints on every phase
+- **External contracts:**
+ - `/?from=<slug>/<id>` (editor `VideoPanel.tsx`/`VideoNavStrip.tsx`);
+ - `/api/browse/decisions`, `/api/notes`, `/api/notes/context` (MCP);
+ - note targets `sites/<site>/<report>` and the bare project id;
+ - every old page URL is in `redirects.mjs`.
+- **House rules:**
+ - no `loading.tsx`, no `not-found.tsx`, no `useSearchParams()`;
+ - static segments win over catch-alls;
+ - buttons disabled until hydrated;
+ - delete is plan-then-confirm;
+ - no lead paragraphs, terse literal copy;
+ - kind-id literals only in `lib/projects/` and `components/projects/`;
+ - every human-piloted audit is app-like (fits 1366×768, one question per item, keys).
+- **Research rules:**
+ - read-only on the corpus;
+ - every fetch goes through the editor (never `yt-dlp` by hand);
+ - citations in the house format (`mcp/src/instructions.ts`, `authoringRules.ts`);
+ - Candace channels stay local-only and never appear in anything published;
+ - the X archive is never put on a site.
+- **e2e:** keep `data-testid` names when components move. Each phase fixes the specs it breaks and adds its own: `inbox`, `work`, `research`, `board`, `run-trace`, `piece`, `create`, `redirects`. The research specs run on the fixture corpus (`LocalSource` over the e2e public dir).
+- **Memory gate:** `free -m` ≥ 6 GB before a build or e2e, one `next build` at a time. Scratch goes in the job dir, not `/tmp`.
+- **Records:** `plans/umtool-redesign.md` in the repo (this plan, plus a Record per phase). No session links anywhere; commits end with `Co-Authored-By` only.
+
+## Verification (every phase)
+- `pnpm --filter umtool typecheck`, then the unit tests (`node --test` over `umtool/lib/**/*.test.mjs`, `umtool/report-to-video/*.test.mjs`; common's tests for R3).
+- A capped umtool build (`systemd-run -p MemoryMax=5G`), then the full `pnpm --filter umtool run e2e`, detached with `setsid nohup` and a log monitor.
+- Screenshots of the phase's pages at 1366×768 and 1440×900 on live data, compared with the P0 canvas, plus a keyboard-only pass (lit line, focus visible, reduced motion).
+- After rollout (rebuild + restart :3050):
+ - curl every row of `redirects.mjs`;
+ - `/?from=` lands in Create;
+ - the MCP `notes` tool still lists and replies;
+ - from P2a on, report the Inbox's actionable count against today's 518 "blocking";
+ - from R1 on, run a research query against the local corpus and check the counts against the MCP `enumerate_matches` for the same scope.
+
+## Record
+
+### Status
+
+| Phase | Branch | State |
+|---|---|---|
+| P0 design | — (`~/reports/umtool-redesign/canvas.html`, version 2) | signed off 2026-10-14 |
+| P2a engine | `ux/p2a` → `main` `fe1cb2d3` | LIVE 2026-10-14 (umtool BUILD_ID 4aRwqu6sh…) |
+| P1 foundation | `ux/p1` | merged with `main`; gating for rollout (below) |
+| R1, P3 | — | wait for P1 live |
+| P2b, P4a, P5, R3, P4b, P6 | — | wait for r28 on `main` |
+
+### P2a, as shipped
+
+**What.** The engine behind the Inbox and Work, with no UI change: pieces, a lifecycle, the generation era's
+decisions, and the grouping, all as data.
+
+- **Piece ids** (`umtool/lib/pieces/ids.mjs`): `a:<site>/<report>` (site may be `articles`), `p:<project>`, and
+ `c:<case>` reserved. A bare `x/y` never parses, so a two-segment id is never ambiguous.
+- **Linking** (`umtool/lib/articles/links.mjs`), in the plan's order:
+ 1. An iteration's `projectDir` links its project, and CLAIMS it: no other article can match it by slug.
+ `current.video` picks the cut. A `projectDir` outside `REPORTS_ROOT` is listed in `unreachable`.
+ 2. The manifest's `article` key.
+ 3. A unique slug in the article's workspace. Only this step yields `possible`.
+
+ The iterations are read as plain JSON (`projectDir`, `current.json`'s `video`), so `umtool notes` links the same
+ way. `/articles` and `/sites` rows carry `via`, `cut`, `how` and `unreachable` (additive). `clearLinksCache`
+ bumps an epoch.
+- **Pieces** (`umtool/lib/pieces.ts`):
+ - Every article: the sites', the store's, and those in the making.
+ - Every project no article claims.
+ - For each: stage, linked projects, `possible`, `unreachable`, and why it looks done.
+ - A project is owned by the strongest link, then by list order.
+ - The graph is memoised 15 s and dropped when the links-cache epoch moves. The lifecycle is read fresh.
+- **Lifecycle** (`umtool/lib/lifecycle.mjs` + `.ts`):
+ - `active | parked | done`, stored in `REPORTS_ROOT/.umtool/lifecycle.json` as `{state, at, by?}`.
+ - Every write goes to a temp file and is renamed into place, serialised. An unreadable file is never overwritten (409).
+ - `POST /api/pieces/lifecycle`: 400 for a bad id or state; 404 for an unknown piece, a `c:`, or a project an
+ article owns, naming the owner. `GET /api/pieces` gives each piece with its decision counts by group.
+- **Decisions** (`umtool/lib/inbox.ts`, `umtool/lib/inbox/groups.mjs`):
+ - `GET /api/browse/decisions` keeps `items[]` one row per decision. `project`, `href` (a note's still ends in
+ `note=<id>`) and `counts` are unchanged.
+ - Each row gains `piece`, `category`, `group`, `action {label, href}`, `lifecycle` and `hidden`.
+ - Two new keys: `groups` (cards, one per piece and kind) and `hidden`.
+ - New disk sources:
+ - `iteration-ready`: done, could be current, newer than current.
+ - `iteration-failed`: not superseded by a later live iteration. Spend is the iteration's `usage`, else the
+ ledger joined on `jobId`.
+ - `research-proposal`: `readResearchState`, status `proposed`.
+ - `link-ambiguous` and `looks-done`.
+ - Groups: Your call → Review → Blocking → Notes → **Open** → Ready to finish → Quiet. **Open** was added for the
+ open decisions the plan did not place (a variant with no verdict, a link to choose).
+ - `openDecisions()` and the pages that call it are unchanged.
+- **CLI:** `umtool inbox [--all] [--json]` runs `bin/inbox.ts` through tsx.
+
+| Commit | What |
+|---|---|
+| `2abb6ee9` | links: iterations, then manifest, then slug; claimed projects never a slug match; unreachable listed |
+| `6498c072` | piece ids, the lifecycle store, the inbox's grouping and ranking (pure, unit-tested) |
+| `d78b7e15` | pieces, `lib/inbox.ts` (disk sources, annotation), the decisions route, `/api/pieces`, `/api/pieces/lifecycle`, `umtool inbox` |
+| `a7bda172` | `e2e/inbox-engine.spec.ts`; `test:scripts` runs `lib/pieces` and `lib/inbox` |
+| `64c3ac84` | an unreadable site, store or disk source never takes the decisions down |
+| `d51b85ea` | `docs/cli.md` lists `umtool inbox` |
+| `f36632a0` | (orchestrator, review) one project cache for every bundle, cleared by a scaffold — fixes the `browse.spec:342` flake |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| `pnpm --filter umtool typecheck` | clean |
+| repo-wide `tsc --noEmit` | clean |
+| umtool unit tests (`node --test` over `umtool/lib/**/*.test.mjs` and `report-to-video/*.test.mjs`) | 734 tests: 732 pass, 2 skip. 22 are new: ids 5, lifecycle 6, groups 5, links 6 |
+| `pnpm run test:scripts` | 882 tests: 880 pass, 2 skip |
+| `next-build-trace.test.mjs` | 10/10, against the capped build |
+| mcp | 343/343 |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`) | exit 0, ~18 s compile. The `/api/pieces` and decisions route traces hold 792 files, none from the corpus or a dot-dir |
+| full umtool e2e | 308 passed, 1 failed, 6 skipped, 5.5 min. The four new `inbox-engine` specs passed |
+| `browse.spec.ts` alone | on `ux/p2a`: 22/23. On the base `604d43c1`, in a temporary worktree: one run 23/23, one run 22/23. Both reds are the same test |
+
+The one red is `browse.spec:342` ("a new song gets the shape…"). `/browse/gamma` 404s right after
+`/api/projects/new` scaffolds it, red and green on the base alike. Release 24 recorded it as a flake. No P2a module
+is on its path: the page and the scaffold route import none of `lib/pieces`, `lib/inbox`, `lib/lifecycle` or
+`links.mjs`. The suspected cause is the 1 s project-walk memo, held per module instance, outliving
+`invalidateProjects()`. That is not verified.
+
+**Review fix (orchestrator).** Verified and fixed in `f36632a0`: `/api/projects/new` never called
+`invalidateProjects()`, and the caches were module-level, one copy per Next bundle, so an API route's invalidation
+never reached the page rendered next. The caches now live on `globalThis` and the scaffold route clears them.
+`browse.spec.ts` after the fix: 3 runs, 23/23 each.
+
+**The real `REPORTS_ROOT`, read-only.**
+- Run offline with tsx on 2026-10-13/14, over the primary's corpus and a scratch copy of the umtool cache.
+- No `lifecycle.json` was written; `~/reports/.umtool` does not exist.
+
+| Measure | Value |
+|---|---|
+| Total rows | 825 = today's 797 + 28 new (1 `iteration-ready`, `api-shondo-recent` i1, $1.14; 1 `link-ambiguous`, `polemic-flips` and two `takes/*` projects; 26 `looks-done`: 25 published store articles with their video + the `pokemon` song). No `iteration-failed` and no `research-proposal` exist on disk |
+| Severity | 518 blocking, 181 open, 126 info. Blocking is still 518: nothing is parked yet |
+| Pieces | 57: 30 article, 27 project. 25 linked projects; none unreachable; no project linked to two articles |
+| Timing | warm `readInbox` 138–578 ms. Disk sources add ~6 ms over `openDecisions()` |
+
+Actionable decisions per group (decisions / cards):
+
+| Group | Today, no lifecycle | `p:quartering-diet` done | Plus the 26 looks-done pieces done |
+|---|---|---|---|
+| Your call | 0 / 0 | 0 / 0 | 0 / 0 |
+| Review | 1 / 1 | 1 / 1 | 1 / 1 |
+| Blocking | **518 / 33** | **35 / 32** (483 hidden) | **11 / 8** (507 hidden) |
+| Notes | 14 / 1 | 14 / 1 | 14 / 1 |
+| Open | 140 / 16 | 104 / 14 | 102 / 12 |
+| Ready to finish | 26 / 26 | 26 / 26 | 0 / 0 |
+| Quiet (collapsed) | 126 / 84 | 104 / 82 | 34 / 27 |
+
+**Found and left.**
+- `quartering-diet` does NOT look done by the plan's signals. It has its final mp4 but no `share-*` batch, so the
+ 483 stay blocking until the operator marks it done. One POST does it.
+- 24 of the 26 looks-done articles carry one blocking `manifest-invalid` on their linked project (no `channelSlug`
+ or a dead origin, in `hasan-leads/*` and `piratesoftware-polemics/*`). Accepting the suggestions hides them.
+- With no `current.json`, every done iteration is `iteration-ready`. The fixture's zeta shows i1, i2 and i3 as one
+ card of 3.
+- `looks-done` and the other new kinds are severity `open`, so `counts.open` rises by 28. `counts.blocking` is
+ unchanged.
+- Not built here: drafts (r28 `draftsView`), running jobs and `askEditor`'s timeout and memo (P2b). No UI: the
+ dashboard and `/browse/decisions` still read `openDecisions()`.
+
+**Rollout (orchestrator, 2026-10-14).** Gates on the integration tip `f36632a0`: full umtool e2e 309 passed,
+0 failed, 6 skipped (8.5 min); `scripts/queue-lock.test.mjs` 37/37 with the queue idle (2 timing reds earlier came
+from runs holding the live queue). `main` fast-forwarded to `fe1cb2d3`; umtool built (79 s, capped) and restarted
+(`~/reports/umtool-redesign/scripts/p2a-umtool.sh`), `/` 200. Live smoke: `/api/browse/decisions` 825 rows, 518 /
+181 / 126, the groups as above, every `open-note` href ending `note=<id>`, 0.48 s; `/api/pieces` 57; a junk
+lifecycle POST 400; no `lifecycle.json` written; the MCP `notes` tool lists the 14 open notes.
+
+### P0, as delivered
+
+The canvas `~/reports/umtool-redesign/canvas.html` (published as a private Artifact; its link is kept out of the
+repo) is P1's visual spec. Version 1, 2026-10-13: ten screens on real data, the validated dark palette, the lit-line
+motion study, the reader serif (Source Serif 4), the URL map and redirect table. Version 2, 2026-10-14, at the
+operator's request: light and dark both first-class, and the wordmark one word ("umtool", bold lead "um"). Signed
+off the same day ("everything else looks great").
+
+Rulings recorded in the canvas's critique section and binding on P1 onward:
+- Tokens are named by role (`--ground --panel --text --muted …`); dark is the base, light under
+ `prefers-color-scheme` and `data-theme`.
+- Dark roles: Signal `#3fc1b0` (the brand's `#5fa8a0` stays on the mark), Meter `#b9a2ec`, kept `#c6e283`, doubt
+ `#ef9a2a`, reject `#de4c3c`. Light: ground `#f1efec`, Signal `#107c8b`, Meter `#5d33bd`, kept `#566609`, doubt
+ `#b0730f`, reject `#6e1b08`. Each set passes the dataviz validator's CVD, normal-vision and contrast checks.
+- In light, no green/ochre/red set clears 4.5:1 words and CVD separation together (52,272 searched): a verdict's
+ colour is its glyph, the word takes a `*-text` step. Verdict colours never land on the reader surface.
+- Signal only on the lit line and one primary action per screen; counts and spend are Meter; the cite thread only
+ on the lit line and the reader header.
+
+### P1, as shipped
+
+**What.** The foundation every later phase builds on, to the signed-off canvas (v2). Nothing moved URL.
+
+- **Tokens** (`umtool/app/globals.css`): the canvas's role tokens exactly — `--ground --panel --panel-2 --seam --seam-2 --text --text-2 --muted --muted-2`, the `--reader*` set, `--signal --signal-text --on-signal --mark --mark-dim --meter`, the verdicts and their `*-text` steps, `--m1..m5` and their inks, `--player-text`. Dark is the base; light under `prefers-color-scheme: light` unless `data-theme="dark"`, and again under `[data-theme="light"]`; `[data-theme="dark"]` states the scheme. `@theme inline` makes them Tailwind colours (`bg-panel`, `text-muted`, `border-seam-2` …). The old palette's names are aliases of the roles they meant (`dim`→muted, `line`→seam, `sel`→signal-text, `good/dirty/bad`→the verdicts' text steps, `ink`→ground; `fg`/`bg`, never defined, now resolve), so every page — r28's included — draws the new desk in both themes. The "colour means something" rule is restated for the roles.
+- **Faces** (`umtool/app/fonts.ts`, `next/font/local`, no network): Archivo, Plex Sans and Plex Mono Regular/Bold are REFERENCED from `report-to-video/fonts/` (one copy, the brand's vendored set; nothing added there, because its `fonts.conf` hands the whole directory to the renderer). Source Serif 4 4.005 (variable, wght+opsz, roman and italic; adobe-fonts/source-serif) and Plex Mono Medium 2.005 (IBM/plex `@ibm/plex-mono@2.5.0`) are new under `umtool/fonts/`, each with its OFL.txt. TTF, unconverted (Plex's Reserved Font Name; transfer size is moot on a local tool).
+- **Theme**: system by default; Auto / Light / Dark at the rail's foot writes the `umtool-theme` cookie (`lib/theme.ts`), the root layout reads it and stamps `data-theme` on `<html>` server-side — no inline script, no flash. Reading the cookie makes every route dynamic; every page already read the disk per request.
+- **Primitives** (`components/ui/`): `button` and `badge` restyled with their exports kept (button gains `go`, the one filled Signal action, and `quiet`; `primary` is a Signal outline, `ghost` an alias of quiet; badge `md` is the canvas filter chip, `sm` a status tag); `Panel`, `Card`, `Tabs` (links, `aria-current`), `Table`/`TH`/`TD`, `Field`/`Input`/`Select`/`Textarea`, `Dialog` (native `<dialog>`), `Stepper`, `Kbd`/`KeyHint`, `EmptyState`, `Toolbar`/`ToolbarGroup`, `Verdict`; the signature **`LitList`** (client: roving tabindex, `j`/`k`/arrows/Home/End, one lit line with the Signal edge and play-head notch, 120 ms glide and 0 ms under reduced motion, nested groups via `LitGroup`, every button in it disabled until hydration by one `<fieldset disabled>`, a `lit` DOM event) with its server half `LitLine`/`LitActions`/`LitOnly`/`LitGroup`; **`ReaderPane`** and **`CiteThread`** (desk and reader forms); `use-palette.ts` (the roles as hex for canvases, repainting on a theme switch); `use-hydrated.ts`.
+- **Shell** (`components/shell/`): `AppRail` (server: the mark and the one-word wordmark, today's places unchanged — home · browse · decisions · articles · mix · find · song ▸ — + Create, the inert ⌘K hint, Pinned (empty), Running (umtool's own in-process job), the theme control), `AppHeader` (one Breadcrumb nav whose last crumb is the `<h1>` in Archivo 125%; the note stays the header's last `.micro`; a compact bench variant), `AppShell`. The rail is `position: fixed` and the body pads for it (`body:has(.app-rail)`), so `BrowseHeader` became a 3-line wrapper with the SAME props and its 22 users changed nothing. `/`, `/mix` and the song deck moved their hand-rolled headers onto it (the deck renders `AppHeader`; its server page renders `AppRail`); the compare page's per-side `<header>` became a panel. The clip, claim and takes benches render the shell with the rail collapsed. Below 760 px the rail is a top strip.
+- **URLs**: `lib/hrefs.ts`, one builder per page address (project ids encoded per segment, `?note=` always last), with `lib/hrefs.test.mjs`; `e2e/urls.ts` re-exports it; `umtool/redirects.mjs` — an empty, documented table (Next's row shape plus `phase`) answered by `next.config.ts`'s `redirects()`.
+- **Restyle pass** (excluding the r28 list below): `/browse/decisions` is the first real lit list (grouped by project, `j`/`k` from anywhere, severity said as glyph + word); `/browse` and `/sites` filters on the Toolbar with an `Input` and outline buttons; the article views are `Tabs`; the dashboard's panels are `Panel`; the clip bench's transcript pane, the claim bench's context and as-recorded quote, and the evidence panel's quote, post and cue list are on the reader; links that wore Signal are ink (`.ink-link`, now in 34 files); hand-rolled controls get the seam-2 edge from one utilities-layer rule; the waveform, mix lanes and pitch rail paint the roles; the face deck's overlays use the dark roles over the photo; the dev indicator moved bottom-right (it covered the theme control on the e2e dev server; the live umtool runs `next start`, which has none).
+
+**Commits** (`ux/p1`, from `ux/integration` `604d43c1`):
+
+| sha | what |
+|---|---|
+| `c412d77c` | role tokens in light and dark, the vendored faces, the theme cookie |
+| `49361eeb` | `lib/hrefs.ts` + tests, `e2e/urls.ts`, empty `redirects.mjs` in `next.config.ts` |
+| `e9f657ff` | the primitives, LitList, ReaderPane, CiteThread; button/badge restyled |
+| `fb06131e` | AppShell and the rail; BrowseHeader wraps it; `/`, `/mix`, the deck on it |
+| `36f8daea` | decisions as a lit list; benches collapse the rail; bench transcripts on the reader; canvases paint the roles |
+| `dafd0928` | article views as Tabs, evidence on the reader, links in ink; `e2e/shell.spec.ts` |
+| `aa4db9d8` | `/browse` and `/sites` filters on the Toolbar; controls drawn with a visible edge |
+| `46f710bf` | the compare page on AppShell |
+| `ada5fe42` | the lit line's own focus mark |
+| `30dd0ebd` | a menu at the column's left edge stays clickable over the rail (the first run's one red) |
+
+**Gates.**
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean; `pnpm --filter umtool typecheck`: clean.
+- Unit, `node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`: 718 tests, 716 pass, 2 skipped, 0 fail (hrefs: 6 new). `pnpm run test:scripts` (reads the fresh build's traces): 866, 864 pass, 2 skipped, 0 fail.
+- Capped build with the primary's corpus linked (`systemd-run … MemoryMax=5G`): compiled in 12.4 s, 37.5 s wall, 1.27 GB max RSS; link removed.
+- Full umtool e2e, run 1 (`ada5fe42`): 323 tests — 316 passed, 1 failed (`timeline-edit.spec.ts:70`, the rail over a leftward row menu — fixed in `30dd0ebd`, the spec then 17/17 with `shell.spec` on the fixture dev server), 6 skipped (the five `faces.spec` and one `find.spec` song-data capability skips), 6.4 min. Run 2 (`30dd0ebd`): 323 tests — 316 passed, 1 failed, 6 skipped (the same six), 5.9 min (28 with the heavy-slot wait). The red is `browse.spec.ts:342` ("a new song gets the shape but NO cut files": `/browse/gamma` 404s right after `POST /api/projects/new`), a known intermittent — browse.spec has the same one red in the shared timings on `r24/integration` ×2, `r25/integration`, `r27/integration`, `HEAD` ×2 and `ux/p2a` ×2 — which passed in run 1 and passes alone (23/23) on a fresh fixture; nothing in this phase touches project creation or the index. `timeline-edit.spec` is 5/5 in run 2.
+- `e2e/shell.spec.ts`: 12 tests — the rail on `/`, `/browse`, `/browse/decisions`, `/articles`, `/sites`, `/mix`, `/browse/find` with the right place lit and one `<h1>` in the breadcrumb; the song group on `/sort`; a bench without the rail; the theme cookie both ways (served stamped after a reload, dark pinned over a light system, Auto clears it); `j`/`k` with focus and the head following; the glide's 0.12 s and 0 s under reduced motion.
+- The FOUC/de-flake theme specs are the export's and the homepage's (`data-theme-ready`); this phase changes no file in either. umtool's theme is server-stamped, so it has no flash to guard; `shell.spec` checks the served HTML.
+- Screenshots at 1366×768 and 1440×900, both themes, of `/`, `/browse`, a project, `/articles`, the clip bench, `/mix` and `/browse/decisions` on the e2e fixture (28, job scratch `p1-shots/final/`), and a keyboard-only pass: every rail stop and page control shows the 2 px Signal ring; the lit line is its own focus mark (edge, notch, raised ground, a dashed outline); the head glides 0.12 s, 0 s under reduced motion.
+
+**The r28 exclusion list** (computed: the union of `git diff --name-only main...r28/<b>` over the eight `r28/*` branches, plus the named nine). Not edited; they inherit the tokens through `globals.css` and read in both themes: `app/articles/page.tsx`, `components/articles/{ChainPanel,IterationsTab,NewArticleForm,ResearchSlot}.tsx`, `components/projects/{NarrationPage,NarrationReview,OnscreenSection,ProjectView,ReportProject,StructureEditors}.tsx` (r28-new and absent here: `app/bench/page.tsx`, `components/articles/ExtractorSelect.tsx`, `components/bench/BarForm.tsx`, `components/projects/{DraftPanel,DraftsReview,drafts,ReviewPage,YoutubeSection}.tsx`); r28's specs and fixtures and the `lib/`, `report-to-video/` and `bin/` files on the list were not touched either. Hard-coded colour left in them: `OnscreenSection.tsx:282` `bg-[#0d0f14]` (the neutral video frame) and `:1731` `#000` (a preview's default background) — both frame stand-ins, legible in either theme; and `text-[var(--color-sel)]` as a link and state colour (ReportProject 14, OnscreenSection 6, others 1–3), now Signal's text step, so Signal shows more often on a project page than the canvas allows — for P4a.
+
+**Found and left.**
+- The rail keeps today's places, lowercase (specs name them); no counts beside them. Running is umtool's own job only, no spend (P2b). Pinned has no store (P4a). ⌘K is an inert hint (P3). `c` for Create is not bound — it would collide with the benches' keys; + Create opens two links (a new article, a new project) until `/create` (P5).
+- Header padding is 16 px, not the canvas's 28 px, to line up with every page's existing `p-4` column; existing pages keep their 11–12 px densities outside the restyled surfaces.
+- Article bodies stay on the desk: they carry claim verdicts and note marks, which the reader must never carry. Quotes, posts, cue windows and the benches' transcripts are on the reader. The clip bench's and claim context's reader text is 15 px serif, not 16, for the panes' density.
+- Tab order is the rail (12 stops with the theme control) before the page; no skip link yet.
+- 40-odd project chips on `/browse/decisions` are still a wall; the Inbox (P3) replaces the page.
diff --git a/umtool/app/[mode]/page.tsx b/umtool/app/[mode]/page.tsx
@@ -4,6 +4,7 @@ import { isMode } from "@/lib/types";
import { CURATED, COMPOUNDS, readVocab } from "@/lib/vocab";
import { REASONS, OTHER_CODE } from "../../song/reasons.mjs";
import Deck from "@/components/Deck";
+import AppRail from "@/components/shell/AppRail";
export const dynamic = "force-dynamic";
@@ -28,11 +29,16 @@ export default async function ModePage({
});
const custom = await readVocab();
+ // The deck is a client component and the rail reads the server, so the rail
+ // is rendered here and the deck draws only its own head (AppHeader).
return (
- <Deck
- page={page}
- vocab={{ curated: CURATED, compounds: COMPOUNDS, custom }}
- reasons={{ bad: REASONS.bad, dirty: REASONS.dirty, other: OTHER_CODE }}
- />
+ <>
+ <AppRail active={mode} />
+ <Deck
+ page={page}
+ vocab={{ curated: CURATED, compounds: COMPOUNDS, custom }}
+ reasons={{ bad: REASONS.bad, dirty: REASONS.dirty, other: OTHER_CODE }}
+ />
+ </>
);
}
diff --git a/umtool/app/api/browse/decisions/route.ts b/umtool/app/api/browse/decisions/route.ts
@@ -1,5 +1,5 @@
-import { countBySeverity, decisionsForSong } from "@/lib/decisions";
-import { openDecisions } from "@/lib/projects";
+import { countBySeverity } from "@/lib/decisions";
+import { readInbox } from "@/lib/inbox";
import { isSegment } from "@/lib/browse";
export const dynamic = "force-dynamic";
@@ -12,17 +12,32 @@ export const dynamic = "force-dynamic";
//
// `?project=` narrows to one. The parameter is deliberately not called `song`,
// because nothing else in this route knows what a song is.
+//
+// `items[]` is ONE ROW PER DECISION, never grouped and never filtered: the MCP
+// reads it (mcp/src/archivalTools.ts: `open-note` rows, `project` as the notes
+// target, `href` ending in `note=<id>`). The inbox's fields on each row --
+// `piece`, `category`, `group`, `action`, `lifecycle`, `hidden` -- are
+// additive (lib/inbox.ts), and so is `groups`, the same rows as per-group
+// cards, and `hidden`, how many rows sit on parked or done pieces.
export async function GET(request: Request) {
const project = new URL(request.url).searchParams.get("project");
if (project && !isSegment(project)) {
return Response.json({ error: "bad project" }, { status: 400 });
}
- const items = project ? await decisionsForSong(project) : await openDecisions();
+ const inbox = await readInbox({ project });
+ const items = inbox.items;
const projects = new Set(items.map((d) => d.project)).size;
return Response.json(
- { items, projects, counts: countBySeverity(items) },
+ {
+ items,
+ projects,
+ counts: countBySeverity(items),
+ groups: inbox.groups,
+ hidden: inbox.hidden,
+ ...(inbox.lifecycleError ? { lifecycleError: inbox.lifecycleError } : {}),
+ },
{ headers: { "cache-control": "no-store" } },
);
}
diff --git a/umtool/app/api/pieces/lifecycle/route.ts b/umtool/app/api/pieces/lifecycle/route.ts
@@ -0,0 +1,38 @@
+import { isLifecycleState, LifecycleError, setLifecycle } from "@/lib/lifecycle";
+import { parsePieceId, readPieceGraph } from "@/lib/pieces";
+
+export const dynamic = "force-dynamic";
+
+// Park a piece, mark it done, or make it active again (lib/lifecycle.ts).
+//
+// POST { piece: "a:<site>/<report>" | "p:<project>", state: "active" | "parked" | "done" }
+// → { piece, state, at, by }
+//
+// 400 for a body that is not a piece id and a state; 404 for a piece nothing on
+// disk is (a research case `c:` is reserved until research boards exist); 409
+// when lifecycle.json does not parse (it is never overwritten). A "looks done"
+// signal never comes through here: only this POST sets a lifecycle.
+const NO_STORE = { "cache-control": "no-store" };
+const fail = (status: number, error: string) => Response.json({ error }, { status, headers: NO_STORE });
+
+export async function POST(request: Request) {
+ const body = (await request.json().catch(() => null)) as { piece?: unknown; state?: unknown } | null;
+ if (!body || typeof body !== "object") return fail(400, "the body is { piece, state }");
+ const parsed = parsePieceId(body.piece);
+ if (!parsed) return fail(400, `not a piece id: ${JSON.stringify(body.piece ?? null)} (a:<site>/<report> or p:<project>)`);
+ if (!isLifecycleState(body.state)) return fail(400, `state is active | parked | done, not ${JSON.stringify(body.state ?? null)}`);
+ if (parsed.kind === "case") return fail(404, "research cases have no lifecycle yet");
+ const graph = await readPieceGraph();
+ if (!graph.byId.has(body.piece as string)) {
+ // A project an article claims is part of that article's piece.
+ const owner = parsed.kind === "project" ? graph.pieceOfProject.get(parsed.project) : undefined;
+ return fail(404, owner ? `${body.piece} is part of ${owner}: set that piece's lifecycle` : `no piece ${body.piece}`);
+ }
+ try {
+ const entry = await setLifecycle(body.piece as string, body.state, "operator");
+ return Response.json({ piece: entry.id, state: entry.state, at: entry.at, by: entry.by ?? null }, { headers: NO_STORE });
+ } catch (err) {
+ if (err instanceof LifecycleError) return fail((err as LifecycleError & { status: number }).status, err.message);
+ return fail(500, (err as Error).message);
+ }
+}
diff --git a/umtool/app/api/pieces/route.ts b/umtool/app/api/pieces/route.ts
@@ -0,0 +1,32 @@
+import { readInbox } from "@/lib/inbox";
+import { listPieces } from "@/lib/pieces";
+import { readLifecycle } from "@/lib/lifecycle";
+
+export const dynamic = "force-dynamic";
+
+// Every piece (lib/pieces.ts): an article with its linked video projects, or a
+// project no article claims. Each with its kind, title, site, stage, lifecycle,
+// linked projects, and how many decisions wait on it -- per inbox group, the
+// visible ones, plus how many are hidden (a parked or done piece's).
+//
+// GET { pieces: [...], lifecycleError? }
+export async function GET() {
+ const life = await readLifecycle();
+ const [pieces, inbox] = await Promise.all([listPieces(life), readInbox()]);
+ const counts = new Map<string, { total: number; hidden: number; byGroup: Record<string, number> }>();
+ for (const d of inbox.items) {
+ if (!d.piece) continue;
+ let c = counts.get(d.piece);
+ if (!c) counts.set(d.piece, (c = { total: 0, hidden: 0, byGroup: {} }));
+ c.total += 1;
+ if (d.hidden) c.hidden += 1;
+ else if (d.group) c.byGroup[d.group] = (c.byGroup[d.group] ?? 0) + 1;
+ }
+ return Response.json(
+ {
+ pieces: pieces.map((p) => ({ ...p, decisions: counts.get(p.id) ?? { total: 0, hidden: 0, byGroup: {} } })),
+ ...(life.error ? { lifecycleError: life.error } : {}),
+ },
+ { headers: { "cache-control": "no-store" } },
+ );
+}
diff --git a/umtool/app/api/projects/new/route.ts b/umtool/app/api/projects/new/route.ts
@@ -1,3 +1,4 @@
+import { invalidateProjects } from "@/lib/projects";
import { ScaffoldError, scaffoldProject } from "@/lib/projects/scaffold";
export const dynamic = "force-dynamic";
@@ -14,6 +15,8 @@ export async function POST(request: Request) {
}
try {
const r = await scaffoldProject(body);
+ // The walk is memoised; the page this href opens must see the new project.
+ invalidateProjects();
return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } });
} catch (e) {
const status = e instanceof ScaffoldError ? e.status : 500;
diff --git a/umtool/app/articles/[report]/compare/page.tsx b/umtool/app/articles/[report]/compare/page.tsx
@@ -1,6 +1,8 @@
import Link from "next/link";
import { notFound } from "next/navigation";
-import BrowseHeader from "@/components/BrowseHeader";
+import AppShell from "@/components/shell/AppShell";
+import { ARTICLES_KEY } from "@/lib/articles/key.mjs";
+import { articleHref, articlesHref } from "@/lib/hrefs";
import { badgeVariants } from "@/components/ui/badge";
import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
import { readCompareSide, type CompareSide } from "@/lib/articles/compare";
@@ -24,13 +26,15 @@ function Side({ side, other, both }: { side: CompareSide; other: CompareSide; bo
const otherCut = new Set((other.cut?.entries ?? []).map((e) => `${e.type}:${e.id}:${e.narration ?? e.quote ?? ""}`));
return (
<section aria-label={side.label} data-side={side.n} className="min-w-0 space-y-3">
- <header className="space-y-1 border-b border-[var(--color-line)] pb-2">
+ {/* The side's head: which iteration, by whom, at what spend -- a Panel,
+ not a page header (the page has one, the shell's). */}
+ <div className="space-y-1 rounded-[3px] border border-seam bg-panel px-4 py-3">
<div className="flex flex-wrap items-baseline gap-2">
<h2 className="font-mono text-[16px]">{side.label}</h2>
<span className="text-[12px] text-[var(--color-dim)]">{side.kind}</span>
<span className="font-mono text-[12px]">{side.model}</span>
<span className={badgeVariants({ variant: side.status === "done" ? "on" : side.status === "failed" ? "blocking" : "open", size: "sm" })}>{side.status}</span>
- <span className="num ml-auto text-[12px] text-[var(--color-meter)]">${side.usd.toFixed(2)}</span>
+ <span className="num ml-auto font-mono text-[12px] text-meter">${side.usd.toFixed(2)}</span>
</div>
<p className="text-[12px] text-[var(--color-dim)]">
{side.parent !== null ? `of i${side.parent}` : "first sweep"}
@@ -39,7 +43,7 @@ function Side({ side, other, both }: { side: CompareSide; other: CompareSide; bo
{side.minutes !== null ? ` · ${side.minutes.toFixed(1)} min` : ""}
</p>
{(side.feedback ?? side.question) && <p className="text-[13px]">{side.feedback ? `“${side.feedback}”` : side.question}</p>}
- </header>
+ </div>
<div className="text-[12px]" data-ops-applied={side.applied.length} data-ops-refused={side.refused.length}>
<div className="micro">
@@ -49,12 +53,12 @@ function Side({ side, other, both }: { side: CompareSide; other: CompareSide; bo
<ul className="mt-1 space-y-0.5 font-mono text-[11px]">
{side.applied.map((o) => (
<li key={`a${o.index}`} data-op="applied">
- <span className="text-[var(--color-good)]">✓</span> {o.index} {o.op} <span className="text-[var(--color-dim)]">{o.detail}</span>
+ <span className="text-kept">✓</span> {o.index} {o.op} <span className="text-[var(--color-dim)]">{o.detail}</span>
</li>
))}
{side.refused.map((o) => (
<li key={`r${o.index}`} data-op="refused">
- <span className="text-[var(--color-bad)]">✗</span> {o.index} {o.op} <span className="text-[var(--color-dim)]">{o.detail}</span>
+ <span className="text-reject">✕</span> {o.index} {o.op} <span className="text-[var(--color-dim)]">{o.detail}</span>
{o.why && <div className="pl-4 font-sans text-[var(--color-bad)]">{o.why}</div>}
</li>
))}
@@ -153,7 +157,14 @@ export default async function ComparePage({
const a = num(sp.a);
const b = num(sp.b);
const [left, right] = a && b ? await Promise.all([readCompareSide(report, a), readCompareSide(report, b)]) : [null, null];
- const header = <BrowseHeader active="articles" crumbs={[{ href: "/articles", label: "articles" }, { href: `/articles/${report}?tab=iterations`, label: report }, { label: "compare" }]} />;
+ const iterations = articleHref({ site: ARTICLES_KEY, id: report }, { tab: "iterations" });
+ const header = (
+ <AppShell
+ active="articles"
+ crumbs={[{ href: articlesHref(), label: "articles" }, { href: iterations, label: report }, { label: "compare" }]}
+ meta={left && right ? `${left.label} and ${right.label}` : undefined}
+ />
+ );
if (!left || !right) {
return (
<div className="flex h-full flex-col">
@@ -161,7 +172,7 @@ export default async function ComparePage({
<main className="deck-main flex-1 p-4">
<p role="alert" className="text-[12px] text-[var(--color-bad)]">
{!a || !b ? "name two iterations: ?a=<n>&b=<n>" : `no iteration ${!left ? `i${a}` : `i${b}`}`} —{" "}
- <Link href={`/articles/${report}?tab=iterations`} className="text-[var(--color-sel)] hover:underline">
+ <Link href={iterations} className="ink-link">
the iterations
</Link>
</p>
diff --git a/umtool/app/browse/[...path]/page.tsx b/umtool/app/browse/[...path]/page.tsx
@@ -57,7 +57,7 @@ export default async function BrowsePathPage({
<li key={p.id}>
<Link
href={`/browse/${p.id}${segments.slice(1).map((s) => `/${s}`).join("")}`}
- className="font-mono text-[12px] text-[var(--color-sel)] hover:underline"
+ className="font-mono text-[12px] ink-link"
>
/browse/{p.id}
</Link>
diff --git a/umtool/app/browse/decisions/page.tsx b/umtool/app/browse/decisions/page.tsx
@@ -11,6 +11,11 @@ import {
} from "@/lib/decisions";
import { openDecisions } from "@/lib/projects";
import { fmtAgo } from "@/lib/format";
+import { decisionsHref } from "@/lib/hrefs";
+import { LitList } from "@/components/ui/lit-list";
+import { LitGroup, LitLine } from "@/components/ui/lit-line";
+import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar";
+import { EmptyState } from "@/components/ui/empty-state";
export const dynamic = "force-dynamic";
@@ -20,12 +25,15 @@ export const dynamic = "force-dynamic";
// because when this regresses the page still renders perfectly in isolation and
// only the URL stops working.
//
-// Zero client JS. The filters are links that change searchParams; nothing here
-// changes without a navigation, and the list is short by construction.
+// The filters are links that change searchParams; nothing here changes
+// without a navigation. The list is the page's one LIT LIST (components/ui/
+// lit-list.tsx): one line per decision, grouped by project, `j`/`k` from
+// anywhere on the page -- the shape the Inbox takes in P3.
-// The three severities ARE three badge variants, one for one. That is not a
-// coincidence to be tidied away: the palette reserves its hues for verdicts,
-// and a severity is the closest thing this list has to one.
+// The three severities ARE three badge variants, one for one, on the filter
+// chips. That is not a coincidence to be tidied away: the palette reserves its
+// hues for verdicts, and a severity is the closest thing this list has to one.
+// On a line it is said the verdict way, glyph and word (Severity below).
const TONE: Record<Severity, BadgeVariants["variant"]> = {
blocking: "blocking",
open: "open",
@@ -57,13 +65,8 @@ export default async function DecisionsPage({
else byProject.set(d.project, [d]);
}
- const q = (next: Partial<{ severity: string; kind: string; project: string }>) => {
- const p = new URLSearchParams();
- const merged = { severity, kind, project, ...next };
- for (const [k, v] of Object.entries(merged)) if (v) p.set(k, v);
- const s = p.toString();
- return `/browse/decisions${s ? `?${s}` : ""}`;
- };
+ const q = (next: Partial<{ severity: string; kind: string; project: string }>) =>
+ decisionsHref({ severity, kind, project, ...next });
return (
<div className="flex h-full flex-col">
@@ -73,9 +76,8 @@ export default async function DecisionsPage({
note={`${openCount(all)} waiting · ${all.length - openCount(all)} for information`}
/>
- <main className="deck-main flex-1 p-4">
- <div className="mb-3 flex flex-wrap items-center gap-1.5">
- <span className="micro">severity</span>
+ <Toolbar aria-label="Filters">
+ <ToolbarGroup label="Severity">
<Chip href={q({ severity: "" })} on={!severity} label={`all ${all.length}`} />
{SEVERITIES.map((s) => (
<Chip
@@ -86,88 +88,91 @@ export default async function DecisionsPage({
tone={TONE[s]}
/>
))}
-
- <span className="micro ml-3">project</span>
- <Chip href={q({ project: "" })} on={!project} label="all" />
- {projects.map((p) => (
- <Chip key={p} href={q({ project: p })} on={project === p} label={p} />
- ))}
-
- <div className="ml-auto">
- <CopyButton
- label="copy the whole picture"
- title="every project as markdown — including this list"
- url="/api/browse/context"
- />
- </div>
+ </ToolbarGroup>
+ <div className="ml-auto">
+ <CopyButton
+ label="copy the whole picture"
+ title="every project as markdown — including this list"
+ url="/api/browse/context"
+ />
</div>
-
- <div className="mb-3 flex flex-wrap items-center gap-1.5">
- <span className="micro">kind</span>
+ <ToolbarGroup label="Kind" className="basis-full">
<Chip href={q({ kind: "" })} on={!kind} label="all" />
{kinds.map((k) => (
<Chip key={k} href={q({ kind: k })} on={kind === k} label={k} />
))}
- </div>
+ </ToolbarGroup>
+ <ToolbarGroup label="Project" className="basis-full">
+ <Chip href={q({ project: "" })} on={!project} label="all" />
+ {projects.map((p) => (
+ <Chip key={p} href={q({ project: p })} on={project === p} label={p} />
+ ))}
+ </ToolbarGroup>
+ </Toolbar>
+ <main className="deck-main flex-1 p-4">
{items.length === 0 ? (
- <p className="text-[12px] text-[var(--color-dim)]">
+ <EmptyState
+ title={all.length === 0 ? "Nothing undecided" : "Nothing matches that filter"}
+ >
{all.length === 0
- ? "Nothing undecided. Every cut ships, every live variant is judged, every recipe still describes its file."
- : "Nothing matches that filter."}
- </p>
+ ? "Every cut ships, every live variant is judged, every recipe still describes its file."
+ : null}
+ </EmptyState>
) : (
- <div className="space-y-4">
+ <LitList label="Decisions" global>
{[...byProject.entries()].map(([id, list]) => (
- <section key={id} data-project={id}>
- <h2 className="mb-1.5 flex items-baseline gap-2">
+ <LitGroup
+ key={id}
+ data-project={id}
+ title={
<Link
// An article's notes are listed under its page's path
// (lib/decisions.ts noteDecisions), not a project's.
href={id.startsWith("sites/") ? `/${id}` : `/browse/${id}`}
- className="font-mono text-[13px] text-[var(--color-text)] hover:text-[var(--color-sel)]"
+ className="font-mono text-[13px] normal-case tracking-normal text-text hover:underline"
>
{id}
</Link>
- <span className="micro">
- {list.filter((d) => d.severity !== "info").length} waiting of {list.length}
- </span>
- </h2>
- <ul className="space-y-1">
- {list.map((d, i) => (
- <li
- key={`${d.kind}-${d.target}-${i}`}
- data-decision={d.kind}
- data-severity={d.severity}
- data-target={d.target}
- className="flex flex-wrap items-baseline gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5"
- >
- <span className={badgeVariants({ variant: TONE[d.severity], size: "sm" })}>
- {d.severity}
- </span>
- <Link
- href={d.href}
- className="font-mono text-[12px] text-[var(--color-sel)] hover:underline"
- >
+ }
+ count={list.filter((d) => d.severity !== "info").length}
+ note={`waiting of ${list.length}`}
+ >
+ {list.map((d, i) => (
+ <LitLine
+ key={`${d.kind}-${d.target}-${i}`}
+ id={`${d.project}:${d.kind}:${d.target}`}
+ data-decision={d.kind}
+ data-severity={d.severity}
+ data-target={d.target}
+ className="grid grid-cols-[86px_minmax(0,1fr)_auto_auto] items-baseline gap-x-3.5"
+ >
+ <Severity s={d.severity} />
+ <span className="min-w-0 truncate">
+ <Link href={d.href} className="font-mono text-[12px] text-inherit underline-offset-2 hover:underline">
{d.target}
</Link>
- <span className="text-[12px] text-[var(--color-dim)]">{d.why}</span>
- <span className="micro ml-auto">{d.kind}</span>
- <span className="num text-[11px] text-[var(--color-dim)]">
- {fmtAgo(d.at)}
- </span>
- </li>
- ))}
- </ul>
- </section>
+ <span className="ml-2 text-[12.5px]">{d.why}</span>
+ </span>
+ <span className="font-mono text-[11px] text-muted-2">{d.kind}</span>
+ <span className="num text-[11px] text-muted-2">{fmtAgo(d.at)}</span>
+ </LitLine>
+ ))}
+ </LitGroup>
))}
- </div>
+ </LitList>
)}
</main>
</div>
);
}
+/** A severity the verdict way: glyph and word, the glyph in the colour. */
+function Severity({ s }: { s: Severity }) {
+ if (s === "info") return <span className="verdict text-muted">· info</span>;
+ return <span className="verdict" data-verdict={s === "blocking" ? "reject" : "doubt"}>{s}</span>;
+}
+
function Chip({
href,
on,
diff --git a/umtool/app/browse/find/page.tsx b/umtool/app/browse/find/page.tsx
@@ -142,7 +142,7 @@ export default async function FindPage({ searchParams }: { searchParams: Promise
as broken. */}
{filler && (
<p className="text-[12px]">
- <Link href="/sort" className="text-[var(--color-sel)] hover:underline">
+ <Link href="/sort" className="ink-link">
The fillers are in /sort
</Link>
<span className="text-[var(--color-dim)]">
diff --git a/umtool/app/browse/page.tsx b/umtool/app/browse/page.tsx
@@ -1,5 +1,10 @@
import Link from "next/link";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { EmptyState } from "@/components/ui/empty-state";
+import { Input } from "@/components/ui/field";
+import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar";
+import { browseHref, decisionsHref } from "@/lib/hrefs";
import BrowseHeader from "@/components/BrowseHeader";
import NewProjectMenu from "@/components/NewProjectMenu";
import CopyButton from "@/components/CopyButton";
@@ -64,12 +69,7 @@ export default async function BrowsePage({
const nOf = (pred: (p: (typeof all)[number]) => boolean) => all.filter(pred).length;
- const qs = (next: Partial<Search>) => {
- const p = new URLSearchParams();
- for (const [k, v] of Object.entries({ ...sp, ...next })) if (v && k !== "deleted") p.set(k, String(v));
- const s = p.toString();
- return `/browse${s ? `?${s}` : ""}`;
- };
+ const qs = (next: Partial<Search>) => browseHref({ ...sp, deleted: undefined, ...next });
// Group by folder, using the COLLAPSED labels but never collapsed URLs.
const groups = new Map<string, typeof sorted>();
@@ -105,103 +105,98 @@ export default async function BrowsePage({
</p>
)}
{/* --- filters, as links ---------------------------------------- */}
- <div className="mb-2 flex flex-wrap items-center gap-1.5">
- <span className="micro">kind</span>
- <Chip href={qs({ kind: "", template: "" })} on={!kind && !template} label={`all ${all.length}`} />
- {KINDS.map((k) => (
- <Chip
- key={k.id}
- href={qs({ kind: k.id, template: "" })}
- on={kind === k.id && !template}
- label={`${k.label} ${nOf((p) => p.kind === k.id)}`}
- />
- ))}
- </div>
+ <Toolbar aria-label="Filters" className="-mx-4 -mt-4 mb-4">
+ <ToolbarGroup label="Kind">
+ <Chip href={qs({ kind: "", template: "" })} on={!kind && !template} label={`all ${all.length}`} />
+ {KINDS.map((k) => (
+ <Chip
+ key={k.id}
+ href={qs({ kind: k.id, template: "" })}
+ on={kind === k.id && !template}
+ label={`${k.label} ${nOf((p) => p.kind === k.id)}`}
+ />
+ ))}
+ </ToolbarGroup>
+
+ <ToolbarGroup label="State">
+ <Chip href={qs({ state: "" })} on={!state} label="any" />
+ {PROJECT_STATES.filter((s) => nOf((p) => p.state === s) > 0).map((s) => (
+ <Chip
+ key={s}
+ href={qs({ state: s })}
+ on={state === s}
+ label={`${s} ${nOf((p) => p.state === s)}`}
+ />
+ ))}
+ </ToolbarGroup>
- <div className="mb-2 flex flex-wrap items-center gap-1.5">
- <span className="micro">state</span>
- <Chip href={qs({ state: "" })} on={!state} label="any" />
- {PROJECT_STATES.filter((s) => nOf((p) => p.state === s) > 0).map((s) => (
+ <ToolbarGroup label="Decisions">
+ <Chip href={qs({ open: "" })} on={!open} label="any" />
<Chip
- key={s}
- href={qs({ state: s })}
- on={state === s}
- label={`${s} ${nOf((p) => p.state === s)}`}
+ href={qs({ open: "blocking" })}
+ on={open === "blocking"}
+ label={`blocking ${nOf((p) => (counts.get(p.id)?.blocking ?? 0) > 0)}`}
+ tone="blocking"
/>
- ))}
-
- <span className="micro ml-3">decisions</span>
- <Chip href={qs({ open: "" })} on={!open} label="any" />
- <Chip
- href={qs({ open: "blocking" })}
- on={open === "blocking"}
- label={`blocking ${nOf((p) => (counts.get(p.id)?.blocking ?? 0) > 0)}`}
- tone="blocking"
- />
- <Chip
- href={qs({ open: "1" })}
- on={open === "1"}
- label={`waiting ${nOf(
- (p) => (counts.get(p.id)?.blocking ?? 0) + (counts.get(p.id)?.open ?? 0) > 0,
- )}`}
- />
-
- <span className="micro ml-3">sort</span>
- <Chip href={qs({ sort: "" })} on={sort !== "name"} label="recent" />
- <Chip href={qs({ sort: "name" })} on={sort === "name"} label="name" />
- </div>
-
- <div className="mb-3 flex flex-wrap items-center gap-2">
- {/* A GET form so the result is a pasteable URL, and hidden inputs so
- searching does not throw away the filters you already set. */}
- <form method="get" action="/browse" className="flex items-center gap-1.5">
- {(["kind", "template", "state", "open", "sort"] as const).map((k) =>
- sp[k] ? <input key={k} type="hidden" name={k} value={sp[k]} /> : null,
- )}
- <input
- type="search"
- name="q"
- defaultValue={q ?? ""}
- placeholder="title, id, source…"
- aria-label="filter projects"
- className="w-56 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 font-mono text-[12px] text-[var(--color-text)] placeholder:text-[var(--color-dim)]"
+ <Chip
+ href={qs({ open: "1" })}
+ on={open === "1"}
+ label={`waiting ${nOf(
+ (p) => (counts.get(p.id)?.blocking ?? 0) + (counts.get(p.id)?.open ?? 0) > 0,
+ )}`}
/>
- <button
- type="submit"
- className="rounded border border-[var(--color-line)] px-2 py-1 text-[11px] text-[var(--color-dim)] hover:text-[var(--color-text)]"
- >
- filter
- </button>
- {q && (
- <Link href={qs({ q: "" })} className="micro hover:text-[var(--color-text)]">
- clear
+ </ToolbarGroup>
+
+ <ToolbarGroup label="Sort">
+ <Chip href={qs({ sort: "" })} on={sort !== "name"} label="recent" />
+ <Chip href={qs({ sort: "name" })} on={sort === "name"} label="name" />
+ </ToolbarGroup>
+
+ <div className="flex basis-full flex-wrap items-center gap-2">
+ {/* A GET form so the result is a pasteable URL, and hidden inputs so
+ searching does not throw away the filters you already set. */}
+ <form method="get" action="/browse" className="flex items-center gap-1.5">
+ {(["kind", "template", "state", "open", "sort"] as const).map((k) =>
+ sp[k] ? <input key={k} type="hidden" name={k} value={sp[k]} /> : null,
+ )}
+ <Input
+ type="search"
+ name="q"
+ defaultValue={q ?? ""}
+ placeholder="title, id, source…"
+ aria-label="filter projects"
+ className="w-60 font-mono text-[12.5px]"
+ />
+ <button type="submit" className={buttonVariants({ size: "md" })}>
+ filter
+ </button>
+ {q && (
+ <Link href={qs({ q: "" })} className="ink-link text-[12px]">
+ clear
+ </Link>
+ )}
+ </form>
+
+ <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} />
+ <div className="ml-auto flex items-center gap-2">
+ <Link href={decisionsHref()} className={buttonVariants({ size: "md" })}>
+ decisions
</Link>
- )}
- </form>
-
- <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} />
- <div className="ml-auto flex items-center gap-2">
- <Link
- href="/browse/decisions"
- className="rounded border border-[var(--color-line)] px-2.5 py-1 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"
- >
- decisions
- </Link>
- <CopyButton
- label="copy the whole picture"
- title="every project as markdown — spec, cuts, verdicts, notes and resolved marks"
- url="/api/browse/context"
- className="rounded border border-[var(--color-sel)] px-2.5 py-1 text-[12px] text-[var(--color-sel)] hover:bg-[color-mix(in_srgb,var(--color-sel)_14%,transparent)]"
- />
+ <CopyButton
+ label="copy the whole picture"
+ title="every project as markdown — spec, cuts, verdicts, notes and resolved marks"
+ url="/api/browse/context"
+ className={buttonVariants({ size: "md" })}
+ />
+ </div>
</div>
- </div>
+ </Toolbar>
{all.length === 0 ? (
- <p className="text-[12px] text-[var(--color-dim)]">
- No projects under <code className="font-mono">REPORTS_DIR</code>. A directory becomes
- one by holding a <code className="font-mono">video.manifest.json</code>, a{" "}
+ <EmptyState title={<>No projects under <code className="font-mono">REPORTS_DIR</code></>}>
+ A directory becomes one by holding a <code className="font-mono">video.manifest.json</code>, a{" "}
<code className="font-mono">spec.json</code>, or a sweep report.
- </p>
+ </EmptyState>
) : (
<div className="space-y-5">
{[...groups.entries()].map(([folderPath, list]) => (
diff --git a/umtool/app/browse/sources/page.tsx b/umtool/app/browse/sources/page.tsx
@@ -78,7 +78,7 @@ export default async function SourcesPage() {
href={v.link}
target="_blank"
rel="noreferrer"
- className="text-[var(--color-sel)] underline"
+ className="ink-link"
>
{v.title || v.video}
</a>
diff --git a/umtool/app/fonts.ts b/umtool/app/fonts.ts
@@ -0,0 +1,67 @@
+import localFont from "next/font/local";
+
+// ---------------------------------------------------------------------------
+// The four faces, vendored. NO NETWORK at build or at run time: the brand slice
+// hit fonts.gstatic failures, and this is a tool on a machine that is often
+// offline from the services it talks to.
+//
+// Archivo, Plex Sans and Plex Mono Regular/Bold are REFERENCED from
+// report-to-video/fonts/ rather than copied: that directory is already the
+// brand's vendored set (unmodified from google/fonts, OFL.txt beside them), the
+// renderer draws the same videos with them, and one copy cannot drift from the
+// other. Nothing new goes INTO that directory, though: its fonts.conf hands the
+// whole directory to the renderer's own children, so a face added there would
+// change what a video can render with. The two faces only the app needs --
+// Source Serif 4 (the reader) and Plex Mono Medium -- live in umtool/fonts/,
+// each with its OFL.txt, from the families' own releases (adobe-fonts/
+// source-serif 4.005R, IBM/plex @ibm/plex-mono@2.5.0).
+//
+// TTF, not woff2: Plex carries a Reserved Font Name and ships unmodified here
+// (report-to-video/fonts/gen-face-metrics.py says why), and on a local tool the
+// transfer size is not worth a conversion step to reason about.
+//
+// Each sets a CSS variable on <html>; app/globals.css builds --f-ui, --f-mono,
+// --f-reader and --f-display on them, and Tailwind's font-sans / font-mono /
+// font-serif / font-display read those.
+// ---------------------------------------------------------------------------
+
+export const archivo = localFont({
+ src: [{ path: "../report-to-video/fonts/Archivo[wdth,wght].ttf", weight: "100 900", style: "normal" }],
+ variable: "--font-archivo",
+ display: "swap",
+ // Only titles use it, and only at expanded width.
+ preload: false,
+ declarations: [{ prop: "font-stretch", value: "62% 125%" }],
+});
+
+export const plexSans = localFont({
+ src: [{ path: "../report-to-video/fonts/IBMPlexSans[wdth,wght].ttf", weight: "100 700", style: "normal" }],
+ variable: "--font-plex-sans",
+ display: "swap",
+ declarations: [{ prop: "font-stretch", value: "75% 100%" }],
+});
+
+export const plexMono = localFont({
+ src: [
+ { path: "../report-to-video/fonts/IBMPlexMono-Regular.ttf", weight: "400", style: "normal" },
+ { path: "../fonts/ibm-plex-mono/IBMPlexMono-Medium.ttf", weight: "500", style: "normal" },
+ { path: "../report-to-video/fonts/IBMPlexMono-Bold.ttf", weight: "700", style: "normal" },
+ ],
+ variable: "--font-plex-mono",
+ display: "swap",
+});
+
+export const sourceSerif = localFont({
+ src: [
+ { path: "../fonts/source-serif-4/SourceSerif4Variable-Roman.ttf", weight: "200 900", style: "normal" },
+ { path: "../fonts/source-serif-4/SourceSerif4Variable-Italic.ttf", weight: "200 900", style: "italic" },
+ ],
+ variable: "--font-source-serif",
+ display: "swap",
+ // The reader appears on a minority of pages; do not make every page fetch it.
+ preload: false,
+ adjustFontFallback: "Times New Roman",
+});
+
+/** Every face's variable, for <html className>. */
+export const fontVariables = [archivo, plexSans, plexMono, sourceSerif].map((f) => f.variable).join(" ");
diff --git a/umtool/app/globals.css b/umtool/app/globals.css
@@ -20,130 +20,347 @@
Named, not detected, as above. */
@source "../../common/components/report";
-/* A dark, dense, keyboard-first bench. Nothing here is deployed; the only user
- is someone judging thousands of clips, or auditioning one transition, in a
- long sitting -- so contrast and hit-size beat decoration.
-
- COLOUR MEANS SOMETHING, OR IT IS NEUTRAL. Three hues are reserved for
- VERDICTS (good/dirty/bad), `sel` is the only INTERACTION colour, and `meter`
- is the only MEASUREMENT colour. The old `--color-accent` (a second green)
- broke that rule: it marked the active nav link while competing with
- `--color-good` two inches away, so a navigation state wore a verdict's
- clothes. It is gone rather than retuned.
-
- `meter` teal is the one colour risk here, and it is deliberate: it sits far
- from all three verdict hues, so a READING can never be mistaken for a
- JUDGEMENT. */
-@theme {
- --color-ink: #0b0e12;
- --color-panel: #161c24;
- /* Wells -- video, waveform. The ramp is wider than it was: the old
- panel/panel-2 pair differed by so little that a well and the card it sat in
- read as one surface. */
- --color-panel-2: #1e2732;
- --color-line: #2c3743;
- --color-text: #e7edf4;
- --color-dim: #8496a8;
-
- /* verdicts ONLY */
- --color-good: #3fb950;
- --color-dirty: #d29922;
- --color-bad: #f85149;
-
- /* interaction ONLY */
- --color-sel: #58a6ff;
-
- /* measurement ONLY -- the pitch rail, and every number that is a reading */
- --color-meter: #56d4c4;
-
- /* ---------------------------------------------------------------------
- shadcn/ui's token names, MAPPED ONTO THE PALETTE ABOVE. Not imported.
-
- Its default theme ships `primary`, `accent` and `destructive` as their own
- hues. Adopting those would walk straight back into the rule this file
- opens with: a second green marked the active nav link while competing with
- --color-good two inches away, so a navigation state wore a verdict's
- clothes, and --color-accent was DELETED rather than retuned.
-
- So every shadcn name is an alias for a colour that already means something
- here, and `accent` is mapped to a SURFACE rather than to a hue -- shadcn
- uses it for hover backgrounds, which is a surface change, not a statement.
- No new colour enters the app, and `cn()` + cva give us the variants and the
- class-merging without the theme.
- --------------------------------------------------------------------- */
- --color-background: var(--color-ink);
- --color-foreground: var(--color-text);
- --color-card: var(--color-panel);
- --color-card-foreground: var(--color-text);
- --color-popover: var(--color-panel);
- --color-popover-foreground: var(--color-text);
- --color-muted: var(--color-panel-2);
- --color-muted-foreground: var(--color-dim);
- /* A surface, never a hue. */
- --color-accent: var(--color-panel-2);
- --color-accent-foreground: var(--color-text);
- --color-secondary: var(--color-panel-2);
- --color-secondary-foreground: var(--color-text);
- --color-border: var(--color-line);
- --color-input: var(--color-line);
- --color-primary: var(--color-sel);
- --color-primary-foreground: var(--color-ink);
- --color-ring: var(--color-sel);
- --color-destructive: var(--color-bad);
- --color-destructive-foreground: var(--color-ink);
-
- --radius: 4px;
+/* ===========================================================================
+ THE DESK AND THE READER (plans/umtool-redesign.md, "Design direction"; the
+ signed-off canvas is ~/reports/umtool-redesign/canvas.html, version 2).
+
+ Tool chrome is the DESK -- warm ink in dark, warm grey in light. Anything a
+ SOURCE said (a transcript, a quote, a post) sits on the READER: a pale
+ green-grey microfilm surface. Paper is the record; ink is our work. A quote
+ can never be mistaken for our claim about it.
+
+ COLOUR MEANS SOMETHING, OR IT IS NEUTRAL. Every token is named by ROLE, not
+ by hue, so one set of components draws both themes:
+ - SIGNAL is the ONE interaction colour: focus, the lit line, and the one
+ primary action per screen. Every other button is an outline.
+ - METER is the ONE measurement colour: counts, coverage, spend. A number
+ you cannot click does not wear the click colour.
+ - KEPT / DOUBT / REJECT are VERDICTS only, always with their glyph and
+ word (✓ ? ✕). The glyph carries the colour; the word takes the *-text
+ step, which in light is darker than the glyph (no green/ochre/red set
+ clears 4.5:1 text and colour-blind separation together on a light
+ ground -- 52,272 sets searched).
+ - Verdict colours NEVER land on the reader. The record carries no
+ judgement, and on the pale surface ochre and brick collapse under
+ deuteranopia at any legible lightness.
+ - MARK is the brand teal, on the logo only: too grey to carry focus.
+ The old palette's rule survives in its aliases below: `sel` is Signal,
+ `meter` is Meter, good/dirty/bad are the three verdicts.
+
+ Dark is the base. Light applies when the system asks for it and nobody
+ pinned dark, or when somebody pinned light; `data-theme` is stamped on
+ <html> by the root layout from the theme cookie (lib/theme.ts), so an
+ explicit choice wins BOTH ways and paints on the first frame.
+ =========================================================================== */
+
+:root {
+ color-scheme: dark;
+ /* desk -- dark */
+ --ground: #0c0a08;
+ --panel: #17140f;
+ --panel-2: #201b15;
+ --seam: #2b251d;
+ --seam-2: #3d3429;
+ --text: #ece4d6;
+ --text-2: #c9bfae;
+ --muted: #9a8f7e;
+ --muted-2: #8a8070;
+ /* reader */
+ --reader: #dfe5e1;
+ --reader-ink: #141210;
+ --reader-2: #3f4742;
+ --reader-dim: #5a625d;
+ --reader-seam: #c2cac5;
+ --reader-edge: transparent;
+ --reader-signal: #0b6b5f;
+ /* roles: the colour is the graphic; *-text is the colour as small text */
+ --signal: #3fc1b0;
+ --signal-text: #3fc1b0;
+ --on-signal: #0c0a08;
+ --mark: #5fa8a0;
+ --mark-dim: #6b5d47;
+ --meter: #b9a2ec;
+ --kept: #c6e283;
+ --kept-text: #c6e283;
+ --doubt: #ef9a2a;
+ --doubt-text: #ef9a2a;
+ --reject: #de4c3c;
+ --reject-text: #de4c3c;
+ /* meter ramp (sequential, light end clears the ground) + its cell text */
+ --m1: #4e4279;
+ --m2: #66559f;
+ --m3: #8a74c8;
+ --m4: #ad98e5;
+ --m5: #d4c6fa;
+ --m1-ink: #ece4d6;
+ --m2-ink: #ece4d6;
+ --m3-ink: #0c0a08;
+ --m4-ink: #0c0a08;
+ --m5-ink: #0c0a08;
+ --player-text: #c9bfae;
+ /* type -- the faces are vendored and loaded by app/fonts.ts (next/font/local),
+ which sets the --font-* variables on <html> */
+ --f-display: var(--font-archivo), "Arial Narrow", system-ui, sans-serif;
+ --f-ui: var(--font-plex-sans), system-ui, -apple-system, "Segoe UI", sans-serif;
+ --f-reader: var(--font-source-serif), "Source Serif Pro", Georgia, serif;
+ --f-mono: var(--font-plex-mono), ui-monospace, "SFMono-Regular", Menlo, monospace;
+ /* the app's only motion: the lit line's head */
+ --glide: 120ms cubic-bezier(0.2, 0.7, 0.2, 1);
+ /* the rail */
+ --rail-w: 212px;
+}
+
+/* Light, when the system asks and nobody pinned dark. The block is repeated for
+ an explicit light below; CSS has no way to share it between a media query and
+ an attribute selector, and the canvas this was signed off on does the same. */
+@media (prefers-color-scheme: light) {
+ :root:not([data-theme="dark"]) {
+ color-scheme: light;
+ --ground: #f1efec;
+ --panel: #e8e4de;
+ --panel-2: #dfd9d1;
+ --seam: #d4cdc3;
+ --seam-2: #bdb4a7;
+ --text: #17130f;
+ --text-2: #3d362e;
+ --muted: #675e52;
+ --muted-2: #5f564b;
+ --reader: #d5ded8;
+ --reader-ink: #141210;
+ --reader-2: #333b36;
+ --reader-dim: #535b56;
+ --reader-seam: #b9c4bd;
+ --reader-edge: #b9c4bd;
+ --reader-signal: #0a5f54;
+ --signal: #107c8b;
+ --signal-text: #0b6372;
+ --on-signal: #ffffff;
+ --mark: #2e7b73;
+ --mark-dim: #b5aa97;
+ --meter: #5d33bd;
+ --kept: #566609;
+ --kept-text: #566609;
+ --doubt: #b0730f;
+ --doubt-text: #8a5a0b;
+ --reject: #6e1b08;
+ --reject-text: #6e1b08;
+ --m1: #ad9ae7;
+ --m2: #9c84df;
+ --m3: #7f63cf;
+ --m4: #6145b8;
+ --m5: #432690;
+ --m1-ink: #17130f;
+ --m2-ink: #17130f;
+ --m3-ink: #ffffff;
+ --m4-ink: #ffffff;
+ --m5-ink: #ffffff;
+ }
+}
+
+:root[data-theme="light"] {
+ color-scheme: light;
+ --ground: #f1efec;
+ --panel: #e8e4de;
+ --panel-2: #dfd9d1;
+ --seam: #d4cdc3;
+ --seam-2: #bdb4a7;
+ --text: #17130f;
+ --text-2: #3d362e;
+ --muted: #675e52;
+ --muted-2: #5f564b;
+ --reader: #d5ded8;
+ --reader-ink: #141210;
+ --reader-2: #333b36;
+ --reader-dim: #535b56;
+ --reader-seam: #b9c4bd;
+ --reader-edge: #b9c4bd;
+ --reader-signal: #0a5f54;
+ --signal: #107c8b;
+ --signal-text: #0b6372;
+ --on-signal: #ffffff;
+ --mark: #2e7b73;
+ --mark-dim: #b5aa97;
+ --meter: #5d33bd;
+ --kept: #566609;
+ --kept-text: #566609;
+ --doubt: #b0730f;
+ --doubt-text: #8a5a0b;
+ --reject: #6e1b08;
+ --reject-text: #6e1b08;
+ --m1: #ad9ae7;
+ --m2: #9c84df;
+ --m3: #7f63cf;
+ --m4: #6145b8;
+ --m5: #432690;
+ --m1-ink: #17130f;
+ --m2-ink: #17130f;
+ --m3-ink: #ffffff;
+ --m4-ink: #ffffff;
+ --m5-ink: #ffffff;
+}
+
+/* An explicit dark. The base already is dark and the light media block skips
+ `[data-theme="dark"]`; this states the scheme, so a pinned dark on a light
+ system gets dark form controls and scrollbars too. */
+:root[data-theme="dark"] {
+ color-scheme: dark;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ :root {
+ --glide: 0ms linear;
+ }
+}
+
+/* The roles as Tailwind colours (`bg-panel`, `text-muted`, `border-seam`,
+ `text-signal-text`, …). INLINE, so a utility reads the role variable itself
+ and follows the theme at run time. */
+@theme inline {
+ --color-ground: var(--ground);
+ --color-panel: var(--panel);
+ --color-panel-2: var(--panel-2);
+ --color-seam: var(--seam);
+ --color-seam-2: var(--seam-2);
+ --color-text: var(--text);
+ --color-text-2: var(--text-2);
+ --color-muted: var(--muted);
+ --color-muted-2: var(--muted-2);
+ --color-reader: var(--reader);
+ --color-reader-ink: var(--reader-ink);
+ --color-reader-2: var(--reader-2);
+ --color-reader-dim: var(--reader-dim);
+ --color-reader-seam: var(--reader-seam);
+ --color-reader-signal: var(--reader-signal);
+ --color-signal: var(--signal);
+ --color-signal-text: var(--signal-text);
+ --color-on-signal: var(--on-signal);
+ --color-mark: var(--mark);
+ --color-mark-dim: var(--mark-dim);
+ --color-meter: var(--meter);
+ --color-kept: var(--kept);
+ --color-kept-text: var(--kept-text);
+ --color-doubt: var(--doubt);
+ --color-doubt-text: var(--doubt-text);
+ --color-reject: var(--reject);
+ --color-reject-text: var(--reject-text);
+ --color-m1: var(--m1);
+ --color-m2: var(--m2);
+ --color-m3: var(--m3);
+ --color-m4: var(--m4);
+ --color-m5: var(--m5);
+ --color-player-text: var(--player-text);
+
+ /* The OLD palette's names, kept as aliases of the roles so the ~1,800 places
+ that still say `var(--color-dim)` draw the new desk in both themes. Each
+ maps to the role it always meant: `sel` (interaction, almost always text
+ or an outline) is Signal's text step; the verdicts are their word step;
+ `line` is the hairline. `fg`/`bg` were never defined -- ClaimBench and
+ DeliverActions used them -- and now resolve. New code says the role. */
+ --color-ink: var(--ground);
+ --color-line: var(--seam);
+ --color-dim: var(--muted);
+ --color-sel: var(--signal-text);
+ --color-good: var(--kept-text);
+ --color-dirty: var(--doubt-text);
+ --color-bad: var(--reject-text);
+ --color-fg: var(--text);
+ --color-bg: var(--ground);
+
+ /* shadcn/ui's names, MAPPED ONTO THE ROLES. Not imported: its default theme
+ ships `primary`, `accent` and `destructive` as their own hues, which would
+ walk straight back into the rule above (a second green once marked the
+ active nav link two inches from a verdict). `accent` is a SURFACE (shadcn
+ uses it for hover backgrounds), `primary` is Signal, `destructive` is the
+ reject word. shadcn's `muted` surface is NOT here: `muted` is the role (a
+ text colour), and `muted-foreground` says the same thing in shadcn's words. */
+ --color-background: var(--ground);
+ --color-foreground: var(--text);
+ --color-card: var(--panel);
+ --color-card-foreground: var(--text);
+ --color-popover: var(--panel);
+ --color-popover-foreground: var(--text);
+ --color-muted-foreground: var(--muted);
+ --color-accent: var(--panel-2);
+ --color-accent-foreground: var(--text);
+ --color-secondary: var(--panel-2);
+ --color-secondary-foreground: var(--text);
+ --color-border: var(--seam-2);
+ --color-input: var(--seam-2);
+ --color-primary: var(--signal);
+ --color-primary-foreground: var(--on-signal);
+ --color-ring: var(--signal);
+ --color-destructive: var(--reject-text);
+ --color-destructive-foreground: var(--ground);
+
+ --font-sans: var(--f-ui);
+ --font-mono: var(--f-mono);
+ --font-serif: var(--f-reader);
+ --font-display: var(--f-display);
+
+ --radius: 3px;
}
html,
body {
height: 100%;
+ background: var(--ground);
+ color: var(--text);
}
body {
- background: var(--color-ink);
- color: var(--color-text);
- font: 14px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ font: 14px/1.45 var(--f-ui);
-webkit-font-smoothing: antialiased;
}
+:focus-visible {
+ outline: 2px solid var(--signal);
+ outline-offset: 2px;
+}
+
/* EVERY NUMBER IS TABULAR. f0, times and durations change while you stare at
them; proportional digits make the row jitter on every update, which in a
tool you sit with for hours reads as instability rather than as data. */
.num,
+.font-mono,
input[type="number"],
kbd {
font-variant-numeric: tabular-nums;
}
-/* Micro-labels: only on the rail and the evidence panel, never on controls. */
+/* Micro-labels: section heads, the rail, the evidence panel; never on controls. */
.micro {
- font-size: 10px;
- line-height: 1.2;
- letter-spacing: 0.08em;
+ font: 600 10.5px/1.2 var(--f-ui);
+ letter-spacing: 0.09em;
text-transform: uppercase;
- color: var(--color-dim);
+ color: var(--muted);
+}
+
+/* Archivo at 125% width is spent on three things only: place titles, piece
+ titles, and the Inbox's one big count. */
+.display {
+ font-family: var(--f-display);
+ font-variation-settings: "wdth" 125;
+ font-weight: 800;
+ letter-spacing: -0.01em;
}
/* The word under judgement is the display element -- what is being decided is a
word, so it is set as a specimen rather than as a caption. */
.specimen {
- font: 500 34px/1 ui-monospace, "SF Mono", Menlo, monospace;
+ font: 500 34px/1 var(--f-mono);
letter-spacing: 0.14em;
text-transform: lowercase;
}
kbd {
display: inline-block;
- padding: 1px 5px;
- border: 1px solid var(--color-line);
+ padding: 0 4px;
+ border: 1px solid var(--seam-2);
border-bottom-width: 2px;
- border-radius: 4px;
- background: var(--color-panel-2);
- font-family: ui-monospace, monospace;
- font-size: 11px;
- line-height: 1.4;
- color: var(--color-dim);
+ border-radius: 3px;
+ background: var(--ground);
+ font: 500 10.5px/1.5 var(--f-mono);
+ color: var(--muted-2);
}
/* The overflow fix, and it is a fix rather than a workaround.
@@ -165,18 +382,389 @@ canvas.grabbable {
touch-action: none;
}
-/* The slides and the overview (common/styles/slides.css) in this bench's
- palette: its ink and panels, `sel` as the accent (it is the interaction
- colour, and every mark on a slide that is not a verdict is a way to act). */
+/* The slides and the overview (common/styles/slides.css) on the desk: its ink
+ and panels, Signal as the accent (it is the interaction colour, and every
+ mark on a slide that is not a verdict is a way to act). */
.rs-root {
- --rs-ground: var(--color-ink);
- --rs-paper: var(--color-panel);
- --rs-ink: var(--color-text);
- --rs-muted: var(--color-dim);
- --rs-faint: var(--color-dim);
- --rs-line: var(--color-line);
- --rs-line-strong: color-mix(in srgb, var(--color-line) 55%, var(--color-dim));
- --rs-accent: var(--color-sel);
- --rs-accent-soft: color-mix(in srgb, var(--color-sel) 16%, transparent);
- --rs-focus: var(--color-sel);
+ --rs-ground: var(--ground);
+ --rs-paper: var(--panel);
+ --rs-ink: var(--text);
+ --rs-muted: var(--muted);
+ --rs-faint: var(--muted-2);
+ --rs-line: var(--seam);
+ --rs-line-strong: var(--seam-2);
+ --rs-accent: var(--signal-text);
+ --rs-accent-soft: color-mix(in srgb, var(--signal) 16%, transparent);
+ --rs-focus: var(--signal);
+ --rs-display: var(--f-display);
+ --rs-sans: var(--f-ui);
+ --rs-mono: var(--f-mono);
}
+
+/* ===========================================================================
+ The shell (components/shell/). The rail is FIXED and the page pads for it,
+ so BrowseHeader -- rendered as the first child of each page's own flex
+ column, 22 call sites, some of them release 28's -- could become the shell
+ without any page changing shape. A page with no rail (a bench) pads nothing.
+ =========================================================================== */
+
+@layer components {
+ body:has(.app-rail) {
+ padding-left: var(--rail-w);
+ }
+
+ .app-rail {
+ position: fixed;
+ inset-block: 0;
+ left: 0;
+ /* Above the page's flow, BELOW its popovers (z-10 and up): a menu opened
+ at the column's left edge may cross the rail and must stay clickable. */
+ z-index: 5;
+ width: var(--rail-w);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ overflow-y: auto;
+ background: var(--panel);
+ border-right: 1px solid var(--seam);
+ }
+
+ /* Below a laptop the rail stops being a column and becomes the top strip, so
+ a narrow window keeps every place without a horizontal scroll. */
+ @media (max-width: 760px) {
+ body:has(.app-rail) {
+ padding-left: 0;
+ }
+ .app-rail {
+ position: static;
+ width: auto;
+ flex-direction: row;
+ flex-wrap: wrap;
+ align-items: center;
+ overflow: visible;
+ border-right: 0;
+ border-bottom: 1px solid var(--seam);
+ }
+ .app-rail [data-rail-section="pins"],
+ .app-rail [data-rail-section="running"],
+ .app-rail [data-rail-section="jump"] {
+ display: none;
+ }
+ }
+
+ .app-places > a,
+ .app-places > [data-nav-group] > button {
+ position: relative;
+ display: flex;
+ width: 100%;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 10px 6px 12px;
+ border-radius: 3px;
+ color: var(--muted-2);
+ text-decoration: none;
+ text-align: left;
+ }
+ .app-places > a:hover,
+ .app-places > [data-nav-group] > button:hover {
+ color: var(--text);
+ background: var(--panel-2);
+ }
+ .app-places > a[aria-current="page"],
+ .app-places > [data-nav-group] > button[aria-current="page"] {
+ color: var(--text);
+ background: var(--panel-2);
+ }
+ /* The Signal edge on the place you are in: the lit line, at rest. */
+ .app-places > a[aria-current="page"]::before,
+ .app-places > [data-nav-group] > button[aria-current="page"]::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 6px;
+ bottom: 6px;
+ width: 2px;
+ background: var(--signal);
+ }
+
+ /* A link in running text or a row: ink, with a quiet underline that wakes on
+ hover. Signal is not a link colour -- it is kept for the lit line and the
+ one primary action (canvas critique, "Signal only on the lit line"). */
+ .ink-link {
+ color: var(--text-2);
+ text-decoration: underline;
+ text-decoration-color: var(--seam-2);
+ text-underline-offset: 3px;
+ }
+ .ink-link:hover {
+ color: var(--text);
+ text-decoration-color: currentColor;
+ }
+
+ /* ── the lit line (components/ui/lit-list.tsx; canvas .lines/.ln/.head) ── */
+ .lit-list {
+ position: relative;
+ outline: none;
+ }
+ .lit-head {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 3px;
+ height: 0;
+ z-index: 2;
+ pointer-events: none;
+ background: var(--signal);
+ transition:
+ top var(--glide),
+ height var(--glide);
+ }
+ .lit-head[data-off] {
+ display: none;
+ }
+ .lit-head:not([data-placed]) {
+ transition: none;
+ }
+ /* The play-head notch. */
+ .lit-head::after {
+ content: "";
+ position: absolute;
+ left: 3px;
+ top: 50%;
+ margin-top: -6px;
+ border-left: 7px solid var(--signal);
+ border-top: 6px solid transparent;
+ border-bottom: 6px solid transparent;
+ }
+ .lit-line {
+ position: relative;
+ padding: 8px 12px 8px 20px;
+ color: var(--muted);
+ border-bottom: 1px solid var(--seam);
+ transition:
+ color var(--glide),
+ background-color var(--glide);
+ }
+ .lit-line:last-child {
+ border-bottom: 0;
+ }
+ /* The lit line IS the focus mark (the edge, the notch, the raised ground);
+ the outline only says the keys are live here, as the canvas's dashed
+ list outline did. */
+ .lit-line:focus-visible {
+ outline: 1px dashed var(--seam-2);
+ outline-offset: -1px;
+ }
+ .lit-line[data-lit] {
+ color: var(--text);
+ background: var(--panel);
+ }
+ /* A line's actions show on the lit line (and on hover or keyboard focus, so
+ a pointer or Tab never finds an invisible button). */
+ .lit-line [data-lit-act] {
+ opacity: 0;
+ transition: opacity var(--glide);
+ }
+ .lit-line[data-lit] [data-lit-act],
+ .lit-line:focus-within [data-lit-act],
+ .lit-line:hover [data-lit-act] {
+ opacity: 1;
+ }
+ /* The cite thread shows on the lit line only: on every row it was a barcode. */
+ .lit-line [data-lit-only] {
+ display: none;
+ }
+ .lit-line[data-lit] [data-lit-only] {
+ display: block;
+ }
+ .lit-group + .lit-group {
+ margin-top: 18px;
+ }
+ .lit-group-head {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ padding: 0 0 6px;
+ border-bottom: 1px solid var(--seam-2);
+ }
+
+ /* ── the reader (components/ui/reader-pane.tsx; canvas .paper/.cue) ── */
+ .reader {
+ display: flex;
+ min-height: 0;
+ flex-direction: column;
+ background: var(--reader);
+ color: var(--reader-ink);
+ box-shadow: inset 0 0 0 1px var(--reader-edge);
+ }
+ .reader .micro {
+ color: var(--reader-dim);
+ }
+ .reader :focus-visible {
+ outline-color: var(--reader-signal);
+ }
+ .reader .lit-head {
+ background: var(--reader-signal);
+ }
+ .reader .lit-head::after {
+ border-left-color: var(--reader-signal);
+ }
+ .reader .lit-line {
+ color: var(--reader-2);
+ border-bottom: 0;
+ padding: 5px 16px 5px 22px;
+ }
+ .reader .lit-line[data-lit] {
+ color: var(--reader-ink);
+ background: color-mix(in srgb, var(--reader-signal) 9%, transparent);
+ }
+ .reader-cue {
+ display: grid;
+ grid-template-columns: 58px minmax(0, 1fr);
+ column-gap: 14px;
+ align-items: baseline;
+ }
+ .reader-t {
+ font: 11px var(--f-mono);
+ font-variant-numeric: tabular-nums;
+ color: var(--reader-dim);
+ }
+ .lit-line[data-lit] .reader-t {
+ color: var(--reader-signal);
+ font-weight: 600;
+ }
+ .reader-cue p,
+ .reader-text {
+ margin: 0;
+ font: 16px/1.5 var(--f-reader);
+ font-optical-sizing: auto;
+ }
+ .reader-cue[data-turn] p::before {
+ content: "»";
+ font-family: var(--f-mono);
+ font-size: 11px;
+ color: var(--reader-dim);
+ margin-right: 6px;
+ vertical-align: 1px;
+ }
+
+ /* ── the cite thread (components/ui/cite-thread.tsx; canvas .cthread/.pthread) ── */
+ .cite-thread {
+ position: relative;
+ height: 14px;
+ }
+ .cite-thread::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 7px;
+ height: 1px;
+ background: var(--seam-2);
+ }
+ .cite-thread > i {
+ position: absolute;
+ top: 2px;
+ width: 2px;
+ height: 11px;
+ background: var(--signal);
+ }
+ .cite-thread > span {
+ position: absolute;
+ top: -1px;
+ right: 0;
+ padding-left: 6px;
+ font: 10px var(--f-mono);
+ color: var(--muted-2);
+ background: var(--panel);
+ }
+ .reader .cite-thread {
+ height: 22px;
+ }
+ .reader .cite-thread::before {
+ top: 6px;
+ background: var(--reader-2);
+ opacity: 0.45;
+ }
+ .reader .cite-thread > i {
+ top: 0;
+ height: 13px;
+ background: var(--reader-signal);
+ }
+ .reader .cite-thread > span {
+ top: 12px;
+ right: auto;
+ padding: 0;
+ font-size: 10.5px;
+ color: var(--reader-dim);
+ background: none;
+ }
+
+ /* ── a verdict: glyph + word, never colour alone (canvas .v) ── */
+ .verdict {
+ font: 600 11.5px var(--f-ui);
+ white-space: nowrap;
+ }
+ .verdict::before {
+ font-family: var(--f-mono);
+ margin-right: 4px;
+ }
+ .verdict[data-verdict="kept"] {
+ color: var(--kept-text);
+ }
+ .verdict[data-verdict="kept"]::before {
+ content: "✓";
+ color: var(--kept);
+ }
+ .verdict[data-verdict="doubt"] {
+ color: var(--doubt-text);
+ }
+ .verdict[data-verdict="doubt"]::before {
+ content: "?";
+ color: var(--doubt);
+ }
+ .verdict[data-verdict="reject"] {
+ color: var(--reject-text);
+ }
+ .verdict[data-verdict="reject"]::before {
+ content: "✕";
+ color: var(--reject);
+ }
+
+ /* ── the stage stepper (canvas .stepper) ── */
+ .stepper-dot {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ border: 1.5px solid var(--seam-2);
+ }
+ [data-step="done"] .stepper-dot {
+ background: var(--text-2);
+ border-color: var(--text-2);
+ }
+ [data-step="current"] .stepper-dot {
+ background: var(--signal);
+ border-color: var(--signal);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--signal) 20%, transparent);
+ }
+
+ /* ── the native dialog (components/ui/dialog.tsx) ── */
+ dialog.ui-dialog::backdrop {
+ background: color-mix(in srgb, var(--ground) 70%, transparent);
+ }
+}
+
+/* Controls hand-rolled against the old palette drew their edge in `line`,
+ which is now the HAIRLINE (seam) -- too faint for something you press or
+ type into. A control's edge is seam-2 (the canvas's .btn), whatever its
+ class says. In the utilities layer, element + attribute, so it beats the
+ bare border utility and loses to every hover/focus/state variant. */
+@layer utilities {
+ button[class*="border-[var(--color-line)]"],
+ select[class*="border-[var(--color-line)]"],
+ input[class*="border-[var(--color-line)]"],
+ textarea[class*="border-[var(--color-line)]"] {
+ border-color: var(--seam-2);
+ }
+}
+
diff --git a/umtool/app/layout.tsx b/umtool/app/layout.tsx
@@ -1,6 +1,9 @@
import type { Metadata } from "next";
+import { cookies } from "next/headers";
import "./globals.css";
+import { fontVariables } from "./fonts";
import { LastPageRecorder } from "@/components/LastPage";
+import { THEME_COOKIE, parseTheme, themeAttr } from "@/lib/theme";
export const metadata: Metadata = {
title: "umtool",
@@ -10,9 +13,15 @@ export const metadata: Metadata = {
// Deliberately no loading.tsx anywhere in this app. In this Next it turns
// notFound() 404s into 200s and never shows on a client sibling navigation --
// see the note in editor/next.config.ts.
-export default function RootLayout({ children }: { children: React.ReactNode }) {
+//
+// The theme is read HERE, from its cookie, and stamped on <html> server-side:
+// an explicit light or dark is on the first frame with no inline script and
+// nothing for hydration to change (lib/theme.ts). Reading a cookie makes every
+// route dynamic; every page here reads the disk per request anyway.
+export default async function RootLayout({ children }: { children: React.ReactNode }) {
+ const theme = parseTheme((await cookies()).get(THEME_COOKIE)?.value);
return (
- <html lang="en">
+ <html lang="en" data-theme={themeAttr(theme)} className={fontVariables}>
<body className="h-full">
{/* Writes down where you are, so / can bring you back. Renders nothing,
and needs no Suspense boundary -- see components/LastPage.tsx. */}
diff --git a/umtool/app/mix/page.tsx b/umtool/app/mix/page.tsx
@@ -1,5 +1,5 @@
import Link from "next/link";
-import AppNav from "@/components/AppNav";
+import AppShell from "@/components/shell/AppShell";
import MixBench from "@/components/MixBench";
import { MEDIA_ROOTS } from "@/lib/paths";
import { isRefusal, resolvePreset } from "@/lib/mix-preset";
@@ -25,33 +25,32 @@ export default async function MixPage({
return (
<div className="flex h-full flex-col">
- <header className="flex flex-wrap items-center gap-3 border-b border-[var(--color-line)] bg-[var(--color-panel)] px-4 py-2">
- <AppNav active="mix" />
- {preset?.fromHref ? (
- <Link
- href={preset.fromHref}
- className="text-[12px] text-[var(--color-sel)] hover:underline"
- data-mix-from={preset.from ?? ""}
- >
- ← {preset.from}
- {preset.clip ? ` / ${preset.clip}` : ""}
- </Link>
- ) : (
- <div className="text-[12px] text-[var(--color-dim)]">
- set the handover and the end point, hear it, then render it
- </div>
- )}
- <div className="num ml-auto hidden text-[10px] text-[var(--color-dim)] lg:block">
- {MEDIA_ROOTS.length} roots
- </div>
- </header>
+ <AppShell
+ active="mix"
+ crumbs={[{ label: "mix" }]}
+ meta={
+ preset?.fromHref ? (
+ <Link
+ href={preset.fromHref}
+ className="text-[12.5px] text-signal-text hover:underline"
+ data-mix-from={preset.from ?? ""}
+ >
+ ← {preset.from}
+ {preset.clip ? ` / ${preset.clip}` : ""}
+ </Link>
+ ) : (
+ "set the handover and the end point, hear it, then render it"
+ )
+ }
+ note={<span className="num hidden lg:inline">{MEDIA_ROOTS.length} roots</span>}
+ />
{refused && (
// Refused, not clamped. A link that quietly opened a DIFFERENT file than
// it named would be worse than this message.
<p
data-mix-refused=""
- className="border-b border-[var(--color-bad)] bg-[color-mix(in_srgb,var(--color-bad)_10%,transparent)] px-4 py-2 text-[12px] text-[var(--color-bad)]"
+ className="border-b border-reject-text bg-[color-mix(in_srgb,var(--reject)_10%,transparent)] px-4 py-2 text-[12.5px] text-reject-text"
>
that link was refused — {refused.reason}
</p>
diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx
@@ -1,5 +1,4 @@
import { statfs } from "node:fs/promises";
-import AppNav from "@/components/AppNav";
import DecisionsPanel from "@/components/dashboard/DecisionsPanel";
import DeliverablesPanel from "@/components/dashboard/DeliverablesPanel";
import NowPanel from "@/components/dashboard/NowPanel";
@@ -9,6 +8,7 @@ import SourcesPanel from "@/components/dashboard/SourcesPanel";
import StateStrip from "@/components/dashboard/StateStrip";
import ToolsPanel from "@/components/dashboard/ToolsPanel";
import NewProjectMenu from "@/components/NewProjectMenu";
+import AppShell from "@/components/shell/AppShell";
import ProjectGrid from "@/components/projects/ProjectGrid";
import { listActivity, runningActivity } from "@/lib/activity";
import { projectsNote, sourceBuckets, stateRows } from "@/lib/dashboard";
@@ -60,13 +60,16 @@ export default async function Home({
return (
<div className="flex h-full flex-col">
- <header className="flex flex-wrap items-center gap-3 border-b border-[var(--color-line)] bg-[var(--color-panel)] px-4 py-2">
- <AppNav active="home" />
- <ResumeChip />
- <div className="ml-auto flex items-center gap-2">
- <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} from={from ?? null} />
- </div>
- </header>
+ <AppShell
+ active="home"
+ crumbs={[{ label: "home" }]}
+ actions={
+ <>
+ <ResumeChip />
+ <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} from={from ?? null} />
+ </>
+ }
+ />
<main className="deck-main flex-1 p-4">
<div className="grid gap-3 lg:grid-cols-2 2xl:grid-cols-3">
diff --git a/umtool/app/sites/[site]/page.tsx b/umtool/app/sites/[site]/page.tsx
@@ -97,7 +97,7 @@ export default async function SitePage({
<ul className="space-y-1">
{linked.map((p) => (
<li key={p.id} data-video-project={p.id} className="flex flex-wrap items-baseline gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 text-[12px]">
- <Link href={`/browse/${p.id}`} className="font-mono text-[var(--color-sel)] hover:underline">
+ <Link href={`/browse/${p.id}`} className="font-mono ink-link">
{p.id}
</Link>
<span className="text-[var(--color-dim)]">{p.articles.map((a) => a.title).join(", ")}</span>
diff --git a/umtool/app/sites/page.tsx b/umtool/app/sites/page.tsx
@@ -3,6 +3,9 @@ import BrowseHeader from "@/components/BrowseHeader";
import ArticleTable from "@/components/articles/ArticleTable";
import SiteChips from "@/components/articles/SiteChips";
import { badgeVariants } from "@/components/ui/badge";
+import { EmptyState } from "@/components/ui/empty-state";
+import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar";
+import { sitesHref } from "@/lib/hrefs";
import { listSiteRows, type ArticleRow } from "@/lib/articles/sites";
export const dynamic = "force-dynamic";
@@ -27,39 +30,39 @@ export default async function SitesPage({ searchParams }: { searchParams: Promis
const articles = all.flatMap((s) => s.articles);
const open = articles.reduce((n, a) => n + a.openNotes, 0);
const qs = (next: Partial<Search>) => {
- const p = new URLSearchParams();
- for (const [k, v] of Object.entries({ ...sp, ...next })) if (v) p.set(k, String(v));
- const s = p.toString();
- return `/sites${s ? `?${s}` : ""}`;
+ return sitesHref({ ...sp, ...next });
};
return (
<div className="flex h-full flex-col">
<BrowseHeader active="articles" crumbs={[{ label: "articles" }]} note={`${all.length} sites · ${articles.length} articles · ${open} open notes`} />
<main className="deck-main flex-1 p-4">
- <div className="mb-3 flex flex-wrap items-center gap-1.5">
- <span className="micro">site</span>
- <Chip href={qs({ site: "" })} on={!sp.site} label={`all ${all.length}`} />
- {all.map((s) => (
- <Chip key={s.siteId} href={qs({ site: s.siteId })} on={sp.site === s.siteId} label={s.siteId} />
- ))}
- <span className="micro ml-3">status</span>
- <Chip href={qs({ status: "" })} on={!sp.status} label="all" />
- <Chip href={qs({ status: "published" })} on={sp.status === "published"} label={`published ${articles.filter((a) => a.status === "published").length}`} />
- <Chip href={qs({ status: "draft" })} on={sp.status === "draft"} label={`draft ${articles.filter((a) => a.status === "draft").length}`} />
- <span className="micro ml-3">notes</span>
- <Chip href={qs({ notes: "" })} on={sp.notes !== "open"} label="all" />
- <Chip href={qs({ notes: "open" })} on={sp.notes === "open"} label={`open ${articles.filter((a) => a.openNotes > 0).length}`} />
- </div>
+ <Toolbar aria-label="Filters" className="-mx-4 -mt-4 mb-4">
+ <ToolbarGroup label="Site">
+ <Chip href={qs({ site: "" })} on={!sp.site} label={`all ${all.length}`} />
+ {all.map((s) => (
+ <Chip key={s.siteId} href={qs({ site: s.siteId })} on={sp.site === s.siteId} label={s.siteId} />
+ ))}
+ </ToolbarGroup>
+ <ToolbarGroup label="Status">
+ <Chip href={qs({ status: "" })} on={!sp.status} label="all" />
+ <Chip href={qs({ status: "published" })} on={sp.status === "published"} label={`published ${articles.filter((a) => a.status === "published").length}`} />
+ <Chip href={qs({ status: "draft" })} on={sp.status === "draft"} label={`draft ${articles.filter((a) => a.status === "draft").length}`} />
+ </ToolbarGroup>
+ <ToolbarGroup label="Notes">
+ <Chip href={qs({ notes: "" })} on={sp.notes !== "open"} label="all" />
+ <Chip href={qs({ notes: "open" })} on={sp.notes === "open"} label={`open ${articles.filter((a) => a.openNotes > 0).length}`} />
+ </ToolbarGroup>
+ </Toolbar>
{sites.length === 0 ? (
- <p className="text-[12px] text-[var(--color-dim)]">{all.length === 0 ? "no sites" : "nothing matches that filter"}</p>
+ <EmptyState title={all.length === 0 ? "No sites" : "Nothing matches that filter"} />
) : (
<div className="space-y-6">
{sites.map((s) => (
<section key={s.siteId} data-site={s.siteId}>
<h2 className="mb-1.5 flex flex-wrap items-baseline gap-2">
- <Link href={`/sites/${s.siteId}`} className="text-[14px] font-semibold text-[var(--color-text)] hover:text-[var(--color-sel)]">
+ <Link href={`/sites/${s.siteId}`} className="text-[14px] font-semibold text-text hover:underline">
{s.title}
</Link>
<span className="font-mono text-[11px] text-[var(--color-dim)]">{s.siteId}</span>
diff --git a/umtool/bin/inbox.ts b/umtool/bin/inbox.ts
@@ -0,0 +1,71 @@
+// `umtool inbox` -- the inbox's grouped list, from a terminal (lib/inbox.ts).
+//
+// TypeScript, because the inbox is: the song reducer, the article side and the
+// iteration readers are the app's own modules, and printing them from a second
+// implementation is the thing lib/projects/core.mjs exists to avoid. So
+// bin/umtool.mjs runs this file through tsx, from umtool/ (the `@/` paths).
+//
+// umtool inbox [--all] [--json]
+//
+// Per group: its cards (one per piece and kind), the decisions they hold, and
+// how many are hidden on parked or done pieces. `--all` lists the hidden ones
+// too, and the quiet group's cards. Read-only.
+import { readInbox, type GroupCard, type GroupSummary } from "../lib/inbox";
+import { summarizeGroups } from "../lib/inbox/groups.mjs";
+
+const args = process.argv.slice(2);
+const all = args.includes("--all");
+const json = args.includes("--json");
+
+const inbox = await readInbox();
+const visible = inbox.items.filter((d) => !d.hidden);
+
+if (json) {
+ console.log(
+ JSON.stringify(
+ {
+ groups: inbox.groups,
+ hidden: inbox.hidden,
+ decisions: visible.length,
+ ...(inbox.lifecycleError ? { lifecycleError: inbox.lifecycleError } : {}),
+ ...(all ? { items: inbox.items } : {}),
+ },
+ null,
+ 2,
+ ),
+ );
+ process.exit(0);
+}
+
+const clip = (s: string, n = 110) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
+const card = (c: GroupCard) =>
+ ` ${c.severity === "blocking" ? "BLOCKING " : ""}${c.piece ?? c.project} ${c.kind}${c.count > 1 ? ` ×${c.count}` : ""}` +
+ `\n ${clip(c.why)}\n → ${c.action.label} ${c.action.href}`;
+
+// The hidden rows, carded as if visible, for --all.
+const hiddenGroups = all
+ ? (summarizeGroups(inbox.items.filter((d) => d.hidden).map((d) => ({ ...d, hidden: false }))) as GroupSummary[])
+ : [];
+
+let cards = 0;
+for (const g of inbox.groups) {
+ if (!g.decisions && !g.hidden) continue;
+ cards += g.cards.length;
+ const hidden = g.hidden ? ` · ${g.hidden} hidden` : "";
+ console.log(`\n## ${g.label} — ${g.cards.length} card${g.cards.length === 1 ? "" : "s"}, ${g.decisions} decision${g.decisions === 1 ? "" : "s"}${hidden}`);
+ if (g.collapsed && !all) {
+ if (g.decisions) console.log(" (collapsed; --all lists it)");
+ } else {
+ for (const c of g.cards) console.log(card(c));
+ }
+ const h = hiddenGroups.find((x) => x.id === g.id);
+ if (h?.cards.length) {
+ console.log(" hidden (parked or done):");
+ for (const c of h.cards) console.log(card(c).replace(/^ {2}/gm, " "));
+ }
+}
+console.log(
+ `\n${visible.length} decision${visible.length === 1 ? "" : "s"} in ${cards} card${cards === 1 ? "" : "s"}` +
+ (inbox.hidden ? ` · ${inbox.hidden} hidden on parked or done pieces${all ? "" : " (--all lists them)"}` : ""),
+);
+if (inbox.lifecycleError) console.log(`lifecycle: ${inbox.lifecycleError} — every piece reads as active`);
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -15,6 +15,7 @@
// umtool show <project> [--json]
// umtool check [<project> | --all] [--json] exit 1 on anything blocking
// umtool decisions [--json]
+// umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them
// umtool folders [--json]
// umtool kinds [--json]
// umtool window <project> <clip> [--start S] [--end E] [--lock] [--lock-end]
@@ -687,6 +688,8 @@ function usage() {
" umtool show <project> [--json]",
" umtool check [<project>] [--json] exit 1 on anything blocking",
" umtool decisions [--json]",
+ " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them",
+ " (--all: the hidden ones on parked/done pieces, and the quiet group)",
" umtool folders [--json]",
" umtool kinds [--json]",
" umtool window <project> <clip> [--start S] [--end E] [--lock|--lock-end|…]",
@@ -746,9 +749,33 @@ const COMMANDS = {
export: cmdExport,
"check-sources": cmdCheckSources,
notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))),
+ inbox: cmdInbox,
help: usage,
};
+// `umtool inbox`: bin/inbox.ts, through tsx -- the inbox is the app's
+// TypeScript (lib/inbox.ts), run from umtool/ so its `@/` paths resolve.
+async function cmdInbox() {
+ const { createRequire } = await import("node:module");
+ const { fileURLToPath } = await import("node:url");
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ let cli;
+ try {
+ cli = createRequire(import.meta.url).resolve("tsx/cli");
+ } catch {
+ die("umtool inbox needs tsx (the workspace's devDependency): run `pnpm install` at the repo root");
+ }
+ const code = await new Promise((resolve) => {
+ const child = spawn(process.execPath, [cli, path.join(here, "inbox.ts"), ...argv.slice(argv.indexOf("inbox") + 1)], {
+ cwd: path.dirname(here),
+ stdio: "inherit",
+ });
+ child.on("error", () => resolve(1));
+ child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1)));
+ });
+ process.exit(code);
+}
+
const run = COMMANDS[cmd];
if (!run) die(`unknown command "${cmd}"\n\nRun \`umtool help\`.`);
await run();
diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx
@@ -1,67 +1,57 @@
import Link from "next/link";
import { MODES } from "@/lib/types";
+import { articlesHref, browseHref, decisionsHref, findHref, homeHref, mixHref, pileHref, sourcesHref } from "@/lib/hrefs";
import NavGroup from "./NavGroup";
// The places, in the order somebody works: the dashboard, every project, what
-// is waiting, the two benches that are not a project (mix, find), and the song
-// piles folded under one entry.
+// is waiting, the articles, the two benches that are not a project (mix, find),
+// and the song piles folded under one entry. They are the rail's list now
+// (components/shell/AppRail.tsx), one place per line.
//
-// SEVEN visible entries (home, browse, decisions, articles, mix, find, song ▸),
-// and the cap is still NINE. A tenth wraps the header on
-// a laptop, and a nav that wraps stops reading as one row of places and starts
-// reading as a list. The next tool goes UNDER one of these, not beside them --
-// which is exactly what happened to the four judging piles and the sources
-// page: they are the `song ▸` group now, at the same URLs they always had, so
-// `/sort`, `/keeps` and every bookmark still land where they did.
+// These are TODAY's places, kept as they were -- labels included, since the
+// specs name them -- until P3 (plans/umtool-redesign.md) makes the rail Inbox ·
+// Research · Work · Tools · Settings. The next tool goes UNDER one of these, not
+// beside them: the four judging piles and the sources page are the `song ▸`
+// group, at the same URLs they always had, so `/sort`, `/keeps` and every
+// bookmark still land where they did.
//
-// The active link is `sel`, the one interaction colour. It used to be
-// `--color-accent`, a second green two inches from `--color-good` on a verdict
-// button -- a NAVIGATION state wearing a VERDICT's colour -- and accent is gone
-// rather than retuned.
+// The place you are in carries `aria-current="page"` and the Signal edge (the
+// lit line, at rest; app/globals.css `.app-places`). It used to be
+// `--color-accent`, a second green two inches from a verdict button -- a
+// NAVIGATION state wearing a VERDICT's colour -- and accent is gone rather than
+// retuned.
const SONG_ITEMS = [
- ...MODES.map((m) => ({ href: `/${m}`, label: m as string })),
+ ...MODES.map((m) => ({ href: pileHref(m), label: m as string })),
// Where the palette comes from, across every song at once.
- { href: "/browse/sources", label: "sources" },
+ { href: sourcesHref(), label: "sources" },
];
export default function AppNav({ active }: { active: string }) {
const items = [
- { href: "/", label: "home" },
- { href: "/browse", label: "browse" },
+ { href: homeHref(), label: "home" },
+ { href: browseHref(), label: "browse" },
// The worklist across every project, not a sixth pile. It sits beside
// browse because that is where every decision it names gets settled.
- { href: "/browse/decisions", label: "decisions" },
+ { href: decisionsHref(), label: "decisions" },
// The articles -- the homepage's (/articles, release 26) and every site's
// own pages (/sites, linked from it) -- published and drafts, with their
// notes, their evidence and the workspace they were written in. Both pages
// mark this entry: the editor's /sites is the sites themselves, and two
// "sites" a tab apart were two places with one name.
- { href: "/articles", label: "articles" },
- { href: "/mix", label: "mix" },
+ { href: articlesHref(), label: "articles" },
+ { href: mixHref(), label: "mix" },
// Every occurrence of a word across the corpus. It sits with browse because
// what it retrieves is raw material for a build, not a pile to judge.
- { href: "/browse/find", label: "find" },
+ { href: findHref(), label: "find" },
];
const songActive = SONG_ITEMS.some((it) => it.label === active);
return (
- <nav className="flex gap-1" aria-label="Main">
- {items.map((it) => {
- const on = it.label === active;
- return (
- <Link
- key={it.href}
- href={it.href}
- aria-current={on ? "page" : undefined}
- className={`rounded px-2.5 py-1 text-sm ${
- on
- ? "bg-[var(--color-panel-2)] text-[var(--color-sel)]"
- : "text-[var(--color-dim)] hover:text-[var(--color-text)]"
- }`}
- >
- {it.label}
- </Link>
- );
- })}
+ <nav className="app-places grid gap-px px-2 py-1 text-[13.5px]" aria-label="Main">
+ {items.map((it) => (
+ <Link key={it.href} href={it.href} aria-current={it.label === active ? "page" : undefined}>
+ {it.label}
+ </Link>
+ ))}
<NavGroup label="song" items={SONG_ITEMS} active={active} on={songActive} />
</nav>
);
diff --git a/umtool/components/BrowseHeader.tsx b/umtool/components/BrowseHeader.tsx
@@ -1,14 +1,17 @@
-import Link from "next/link";
-import AppNav from "@/components/AppNav";
+import AppShell from "@/components/shell/AppShell";
+import type { Crumb } from "@/components/shell/AppHeader";
-export type Crumb = { href?: string; label: string };
+export type { Crumb };
/**
- * The header the three browse levels share.
+ * The header the browse levels share -- now a thin wrapper over the shell
+ * (components/shell/AppShell.tsx): the rail, and the page head with these
+ * crumbs and this note.
*
- * app/mix/page.tsx writes its header inline, which is fine for one page. Three
- * copies of it would be two too many, and the breadcrumb is the only part that
- * differs between the levels.
+ * Kept, with the SAME props, until P6 deletes it: it has 22 call sites,
+ * release 28's ReportProject, NarrationPage and app/bench/page.tsx among them,
+ * and every one of them gets the rail by changing nothing. New pages use
+ * AppShell directly.
*/
export default function BrowseHeader({
crumbs,
@@ -20,24 +23,5 @@ export default function BrowseHeader({
/** Which nav item is lit. Defaults to browse, which is the common case. */
active?: string;
}) {
- return (
- <header className="flex flex-wrap items-center gap-3 border-b border-[var(--color-line)] bg-[var(--color-panel)] px-4 py-2">
- <AppNav active={active} />
- <nav className="flex items-center gap-1.5 text-[12px]" aria-label="Breadcrumb">
- {crumbs.map((c, i) => (
- <span key={`${c.label}-${i}`} className="flex items-center gap-1.5">
- {i > 0 && <span className="text-[var(--color-line)]">/</span>}
- {c.href ? (
- <Link href={c.href} className="text-[var(--color-dim)] hover:text-[var(--color-text)]">
- {c.label}
- </Link>
- ) : (
- <span className="text-[var(--color-text)]">{c.label}</span>
- )}
- </span>
- ))}
- </nav>
- {note && <div className="micro ml-auto">{note}</div>}
- </header>
- );
+ return <AppShell active={active} crumbs={crumbs} note={note} />;
}
diff --git a/umtool/components/Deck.tsx b/umtool/components/Deck.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import AppNav from "./AppNav";
+import AppHeader from "./shell/AppHeader";
import PitchRail, { type CorpusPitch } from "./PitchRail";
import Waveform, { type Peaks } from "./Waveform";
import WordSelector, { type Vocab } from "./WordSelector";
@@ -1004,24 +1004,28 @@ export default function Deck({ page, vocab: initialVocab, reasons }: Props) {
const header = useMemo(
() => (
- <header className="flex flex-wrap items-center gap-3 border-b border-[var(--color-line)] bg-[var(--color-panel)] px-4 py-2">
- <AppNav active={mode} />
- <div className="text-[12px] text-[var(--color-dim)]">
- {clips.length} on this page of {total} · {orderNote}
- </div>
- <div className="ml-auto flex gap-4 text-[12px]">
- <span>
- palette <b className="text-[var(--color-good)]">{counts.accepted}</b>
- </span>
- <span>
- unclean <b className="text-[var(--color-dirty)]">{counts.unclean}</b>
- </span>
- <span>
- dirty <b>{counts.impure}</b>
- </span>
- <span className="text-[var(--color-dim)]">rejected {counts.rejected}</span>
- </div>
- </header>
+ <AppHeader
+ crumbs={[{ label: "song" }, { label: mode }]}
+ meta={
+ <>
+ {clips.length} on this page of {total} · {orderNote}
+ </>
+ }
+ actions={
+ <div className="flex gap-4 text-[12.5px]">
+ <span>
+ palette <b className="num text-[var(--color-good)]">{counts.accepted}</b>
+ </span>
+ <span>
+ unclean <b className="num text-[var(--color-dirty)]">{counts.unclean}</b>
+ </span>
+ <span>
+ dirty <b className="num">{counts.impure}</b>
+ </span>
+ <span className="text-muted">rejected {counts.rejected}</span>
+ </div>
+ }
+ />
),
[mode, clips.length, total, orderNote, counts],
);
diff --git a/umtool/components/FaceDeck.tsx b/umtool/components/FaceDeck.tsx
@@ -242,15 +242,18 @@ export default function FaceDeck({
ctx.restore();
};
- if (det?.face) stroke(det.face, "rgba(132,150,168,0.75)", [4, 4], 2);
+ // Drawn over a photo, not the desk, so these are the dark roles as
+ // constants whatever the theme: muted (the detector), doubt (the CLI's
+ // automatic crop), meter (the guess), Signal (the chosen crop).
+ if (det?.face) stroke(det.face, "rgba(154,143,126,0.75)", [4, 4], 2);
// WHAT THE CLI WOULD DO, always drawn, so the diff between the automatic
// crop and the chosen one is visible rather than remembered.
- if (det?.auto) stroke(det.auto, "rgba(210,153,34,0.85)", [10, 6], 3);
- if (guess) stroke(guess, "rgba(86,212,196,0.9)", [2, 6], 3);
+ if (det?.auto) stroke(det.auto, "rgba(239,154,42,0.85)", [10, 6], 3);
+ if (guess) stroke(guess, "rgba(185,162,236,0.9)", [2, 6], 3);
if (crop) {
- stroke(crop, "#58a6ff", [], 4);
+ stroke(crop, "#3fc1b0", [], 4);
ctx.save();
- ctx.fillStyle = "#58a6ff";
+ ctx.fillStyle = "#3fc1b0";
for (const [hx, hy] of [
[crop.x, crop.y],
[crop.x + crop.w, crop.y],
@@ -594,7 +597,7 @@ export default function FaceDeck({
href={entry.link}
target="_blank"
rel="noreferrer"
- className="text-[11px] text-[var(--color-sel)] underline"
+ className="text-[11px] ink-link"
>
the moment
</a>
@@ -701,7 +704,7 @@ export default function FaceDeck({
setGuess(null);
}}
data-take-guess
- className="text-[var(--color-sel)] underline"
+ className="ink-link"
>
take it
</button>{" "}
diff --git a/umtool/components/MixLanes.tsx b/umtool/components/MixLanes.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
+import { alpha, usePalette } from "@/components/ui/use-palette";
export type Analysis = {
label: string;
@@ -57,6 +58,8 @@ export default function MixLanes({
height = 210,
}: Props) {
const ref = useRef<HTMLCanvasElement | null>(null);
+ // The roles as colours, repainting on a theme switch (components/ui/use-palette.ts).
+ const pal = usePalette();
const [width, setWidth] = useState(900);
const drag = useRef<Marker | null>(null);
@@ -90,7 +93,7 @@ export default function MixLanes({
{ a: body, top: laneH, title: body ? `song · ${body.label}` : "song — none loaded", isBg: false },
];
- g.fillStyle = "#1e2732"; // panel-2: this is a well
+ g.fillStyle = pal["panel-2"]; // panel-2: this is a well
g.fillRect(0, 0, width, height);
for (const { a, top, title, isBg } of lanes) {
@@ -100,7 +103,7 @@ export default function MixLanes({
g.rect(0, top, width, laneH);
g.clip();
- g.fillStyle = "#161c24";
+ g.fillStyle = pal.panel;
g.fillRect(0, top, width, laneH);
if (a && a.peak.length) {
@@ -113,14 +116,14 @@ export default function MixLanes({
const p = a.peak[i];
const h = Math.min(laneH / 2 - 2, p * (laneH / 2 - 2) * 1.6);
const audible = !isBg || t < handover + fade;
- g.fillStyle = audible ? "#4a5d72" : "#28323e";
+ g.fillStyle = audible ? pal["muted-2"] : pal["seam-2"];
g.fillRect(x, mid - h, 1, Math.max(1, h * 2));
}
}
- // The measurement curve, and the only teal in the drawing.
+ // The measurement curve, and the only Meter in the drawing.
if (a && isBg && a.ratio.length) {
- g.strokeStyle = "#56d4c4";
+ g.strokeStyle = pal.meter;
g.lineWidth = 1.5;
g.beginPath();
let started = false;
@@ -141,7 +144,7 @@ export default function MixLanes({
for (const s of a.steps) {
const x = toX(s.at);
if (x < -6 || x > width + 6) continue;
- g.fillStyle = "rgba(86,212,196,0.85)";
+ g.fillStyle = alpha(pal.meter, 0.85);
g.beginPath();
g.moveTo(x, top + 2);
g.lineTo(x - 4, top + 9);
@@ -156,7 +159,7 @@ export default function MixLanes({
const x = toX(a.firstSound);
if (x > -2 && x < width + 2) {
g.setLineDash([2, 3]);
- g.strokeStyle = "rgba(86,212,196,0.7)";
+ g.strokeStyle = alpha(pal.meter, 0.7);
g.lineWidth = 1;
g.beginPath();
g.moveTo(x, top);
@@ -168,10 +171,10 @@ export default function MixLanes({
g.restore();
- g.fillStyle = "#8496a8";
+ g.fillStyle = pal.muted;
g.font = "10px ui-monospace, monospace";
g.fillText(title.toUpperCase(), 6, top + 12);
- g.strokeStyle = "#2c3743";
+ g.strokeStyle = pal.seam;
g.lineWidth = 1;
g.beginPath();
g.moveTo(0, top + laneH + 0.5);
@@ -180,21 +183,21 @@ export default function MixLanes({
}
// Outside [start, end] is not in the output at all.
- g.fillStyle = "rgba(11,14,18,0.62)";
+ g.fillStyle = alpha(pal.ground, 0.62);
const sx = toX(start);
const ex = toX(end);
if (sx > 0) g.fillRect(0, 0, sx, height - AXIS);
if (ex < width) g.fillRect(ex, 0, width - ex, height - AXIS);
// -- the axis -------------------------------------------------------------
- g.fillStyle = "#161c24";
+ g.fillStyle = pal.panel;
g.fillRect(0, height - AXIS, width, AXIS);
- g.fillStyle = "#8496a8";
+ g.fillStyle = pal.muted;
g.font = "10px ui-monospace, monospace";
const step = span > 120 ? 30 : span > 60 ? 10 : span > 20 ? 5 : span > 6 ? 1 : 0.5;
for (let t = Math.ceil(view.from / step) * step; t <= view.to; t += step) {
const x = toX(t);
- g.strokeStyle = "#2c3743";
+ g.strokeStyle = pal.seam;
g.beginPath();
g.moveTo(x, height - AXIS);
g.lineTo(x, height - AXIS + 4);
@@ -219,22 +222,22 @@ export default function MixLanes({
const w = g.measureText(label).width;
g.fillText(label, Math.min(width - w - 3, Math.max(3, x + 7)), 20);
};
- line(start, "#58a6ff", "start", false);
- line(end, "#58a6ff", "end", false);
+ line(start, pal.signal, "start", false);
+ line(end, pal.signal, "end", false);
// The ramp itself, so a fade is a shape rather than a number in a box.
if (fade > 0.0005) {
const a = toX(handover);
const b = toX(handover + fade);
- g.fillStyle = "rgba(86,212,196,0.16)";
+ g.fillStyle = alpha(pal.meter, 0.16);
g.fillRect(a, 0, Math.max(1, b - a), height - AXIS);
}
- line(handover, "#56d4c4", `handover ${handover.toFixed(3)}s`, true);
+ line(handover, pal.meter, `handover ${handover.toFixed(3)}s`, true);
if (playhead != null && playhead >= view.from && playhead <= view.to) {
- g.fillStyle = "#e7edf4";
+ g.fillStyle = pal.text;
g.fillRect(toX(playhead), 0, 1, height - AXIS);
}
- }, [width, height, bg, body, view, handover, fade, start, end, playhead, toX, toT]);
+ }, [width, height, bg, body, view, handover, fade, start, end, playhead, toX, toT, pal]);
const pick = (x: number): Marker | null => {
const near: [Marker, number][] = [
diff --git a/umtool/components/MomentMarks.tsx b/umtool/components/MomentMarks.tsx
@@ -145,7 +145,7 @@ export default function MomentMarks({
<button
type="button"
onClick={() => onSeek(m.t)}
- className="num text-[11px] text-[var(--color-sel)] underline"
+ className="num text-[11px] ink-link"
title="seek here"
>
{ts(m.t)}
diff --git a/umtool/components/NavGroup.tsx b/umtool/components/NavGroup.tsx
@@ -3,12 +3,14 @@
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
-// One nav entry that opens into several. Click (or Enter/Space) to expand,
+// One rail entry that opens into several. Click (or Enter/Space) to expand,
// Escape or a click elsewhere to close; the items are real links, so the
// keyboard reaches every one of them and the URLs are unchanged.
//
-// Native <details> would do most of this with no JS, but it cannot close on an
-// outside click and it renders its own marker; this is small enough to own.
+// It opens IN PLACE, under its button, not as a popover: the rail scrolls, and
+// a popover inside it would be clipped. Native <details> would do most of this
+// with no JS, but it cannot close on an outside click and it renders its own
+// marker; this is small enough to own.
export default function NavGroup({
label,
items,
@@ -40,26 +42,15 @@ export default function NavGroup({
}, [open]);
return (
- <div ref={ref} className="relative" data-nav-group={label}>
- <button
- type="button"
- aria-haspopup="menu"
- aria-expanded={open}
- aria-current={on ? "page" : undefined}
- onClick={() => setOpen((v) => !v)}
- className={`rounded px-2.5 py-1 text-sm ${
- on
- ? "bg-[var(--color-panel-2)] text-[var(--color-sel)]"
- : "text-[var(--color-dim)] hover:text-[var(--color-text)]"
- }`}
- >
- {label} <span aria-hidden="true">▸</span>
+ <div ref={ref} data-nav-group={label}>
+ <button type="button" aria-haspopup="menu" aria-expanded={open} aria-current={on ? "page" : undefined} onClick={() => setOpen((v) => !v)}>
+ {label}
+ <span aria-hidden="true" className="ml-auto text-muted-2">
+ {open ? "▾" : "▸"}
+ </span>
</button>
{open && (
- <div
- role="menu"
- className="absolute left-0 top-full z-20 mt-1 flex min-w-32 flex-col rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-1 shadow-lg"
- >
+ <div role="menu" className="ml-3 mt-px grid gap-px border-l border-seam-2 pl-1.5">
{items.map((it) => {
const lit = it.label === active;
return (
@@ -69,10 +60,8 @@ export default function NavGroup({
role="menuitem"
aria-current={lit ? "page" : undefined}
onClick={() => setOpen(false)}
- className={`rounded px-2.5 py-1 text-sm ${
- lit
- ? "bg-[var(--color-panel-2)] text-[var(--color-sel)]"
- : "text-[var(--color-dim)] hover:text-[var(--color-text)]"
+ className={`rounded-[3px] px-2.5 py-1 text-[13px] ${
+ lit ? "bg-panel-2 text-text" : "text-muted-2 hover:bg-panel-2 hover:text-text"
}`}
>
{it.label}
diff --git a/umtool/components/PhraseConsole.tsx b/umtool/components/PhraseConsole.tsx
@@ -386,7 +386,7 @@ export default function PhraseConsole({
href={h.archive}
target="_blank"
rel="noreferrer"
- className="font-mono text-[11px] text-[var(--color-sel)] hover:underline"
+ className="font-mono text-[11px] ink-link"
>
in the archive
</a>
diff --git a/umtool/components/PitchRail.tsx b/umtool/components/PitchRail.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { alpha, usePalette } from "@/components/ui/use-palette";
export type CorpusPitch = {
lo: number;
@@ -37,6 +38,8 @@ type Props = {
// a verdict, which is why none of the three verdict hues appear here.
export default function PitchRail({ corpus, f0, sourceF0s, flat = false }: Props) {
const ref = useRef<HTMLCanvasElement | null>(null);
+ // The roles as colours, repainting on a theme switch (components/ui/use-palette.ts).
+ const pal = usePalette();
const [size, setSize] = useState({ w: 64, h: 320 });
useEffect(() => {
@@ -71,11 +74,11 @@ export default function PitchRail({ corpus, f0, sourceF0s, flat = false }: Props
const ribbonFrom = LABEL;
const ribbonTo = flat ? h : w;
- g.fillStyle = "#161c24";
+ g.fillStyle = pal.panel;
g.fillRect(0, 0, w, h);
// -- the region above the gate, shaded ------------------------------------
- g.fillStyle = "rgba(210,153,34,0.07)";
+ g.fillStyle = alpha(pal.doubt, 0.08);
if (flat) {
const x = pos(corpus.gate);
g.fillRect(x, 0, w - x, h);
@@ -85,7 +88,7 @@ export default function PitchRail({ corpus, f0, sourceF0s, flat = false }: Props
// -- the corpus, as a density ribbon --------------------------------------
const peak = Math.max(1, corpus.peak);
- g.fillStyle = "rgba(86,212,196,0.30)";
+ g.fillStyle = alpha(pal.meter, 0.32);
for (let i = 0; i < corpus.bins.length; i += 1) {
const c = corpus.bins[i];
if (!c) continue;
@@ -105,7 +108,7 @@ export default function PitchRail({ corpus, f0, sourceF0s, flat = false }: Props
}
// -- this source's own clips, faint marks behind the needle ---------------
- g.fillStyle = "rgba(231,237,244,0.42)";
+ g.fillStyle = alpha(pal.text, 0.42);
for (const s of sourceF0s) {
if (s < corpus.lo || s > corpus.hi) continue;
const p = pos(s);
@@ -134,15 +137,15 @@ export default function PitchRail({ corpus, f0, sourceF0s, flat = false }: Props
if (flat) g.fillText(label, Math.min(w - 22, p + 2), 9);
else g.fillText(label, 2, Math.max(8, Math.min(h - 2, p + 3)));
};
- tick(corpus.median, "#8496a8", String(Math.round(corpus.median)), false);
- tick(corpus.p95, "#8496a8", String(Math.round(corpus.p95)), false);
- tick(corpus.gate, "#d29922", String(corpus.gate), true);
+ tick(corpus.median, pal.muted, String(Math.round(corpus.median)), false);
+ tick(corpus.p95, pal.muted, String(Math.round(corpus.p95)), false);
+ tick(corpus.gate, pal.doubt, String(corpus.gate), true);
// -- this clip, as a bright needle ----------------------------------------
if (f0 > 0) {
const clamped = Math.max(corpus.lo, Math.min(corpus.hi, f0));
const p = pos(clamped);
- g.fillStyle = "#56d4c4";
+ g.fillStyle = pal.meter;
if (flat) {
g.fillRect(p - 1, 0, 2, h);
g.beginPath();
@@ -162,12 +165,12 @@ export default function PitchRail({ corpus, f0, sourceF0s, flat = false }: Props
}
// Off the end of the scale is itself the finding, so say so.
if (f0 > corpus.hi || f0 < corpus.lo) {
- g.fillStyle = "#f85149";
+ g.fillStyle = pal.reject;
g.font = "9px ui-monospace, monospace";
g.fillText("off scale", flat ? Math.max(2, p - 20) : 2, flat ? h - 12 : Math.max(9, p - 5));
}
}
- }, [corpus, f0, sourceF0s, size, flat]);
+ }, [corpus, f0, sourceF0s, size, flat, pal]);
return (
<div className={flat ? "h-12 w-full" : "h-full w-16"}>
diff --git a/umtool/components/PlanDiffPanel.tsx b/umtool/components/PlanDiffPanel.tsx
@@ -241,7 +241,7 @@ function Side({ row }: { row: PlanDelta["a"] }) {
href={row.link}
target="_blank"
rel="noreferrer"
- className="font-mono text-[var(--color-sel)] underline"
+ className="font-mono ink-link"
title={row.title}
>
{row.clipId}
diff --git a/umtool/components/ProvenancePanel.tsx b/umtool/components/ProvenancePanel.tsx
@@ -144,7 +144,7 @@ export default function ProvenancePanel({
{prov.videos.length > 0 && (
<p className="num mt-1 text-[11px] text-[var(--color-dim)]" data-concentration>
{concentrationLine(shares(prov.videos.map((v) => v.clips)))} ·{" "}
- <Link href="/browse/sources" className="text-[var(--color-sel)] underline">
+ <Link href="/browse/sources" className="ink-link">
across every song
</Link>
</p>
@@ -221,7 +221,7 @@ export default function ProvenancePanel({
href={v.link}
target="_blank"
rel="noreferrer"
- className="num text-[var(--color-sel)] underline"
+ className="num ink-link"
>
{fmtDur(v.firstSrcStart)}
</a>
@@ -252,7 +252,7 @@ export default function ProvenancePanel({
showing the first {shown.length} by song time — {hidden} not shown.{" "}
<Link
href={`${href(planParam)}${planParam ? "&" : "?"}notes=all`}
- className="text-[var(--color-sel)] underline"
+ className="ink-link"
>
show all {prov.rows.length}
</Link>
@@ -295,7 +295,7 @@ export default function ProvenancePanel({
href={r.link}
target="_blank"
rel="noreferrer"
- className="text-[var(--color-sel)] underline"
+ className="ink-link"
title={r.title}
>
archive
diff --git a/umtool/components/ShortlistBar.tsx b/umtool/components/ShortlistBar.tsx
@@ -153,13 +153,13 @@ export default function ShortlistBar({
<span className="ml-auto flex items-center gap-2">
<a
href={`/api/shortlist?list=${encodeURIComponent(list.slug)}&format=json`}
- className="font-mono text-[11px] text-[var(--color-sel)] hover:underline"
+ className="font-mono text-[11px] ink-link"
>
export json
</a>
<a
href={`/api/shortlist?list=${encodeURIComponent(list.slug)}&format=md`}
- className="font-mono text-[11px] text-[var(--color-sel)] hover:underline"
+ className="font-mono text-[11px] ink-link"
>
markdown
</a>
diff --git a/umtool/components/SpecSheet.tsx b/umtool/components/SpecSheet.tsx
@@ -109,7 +109,7 @@ export default function SpecSheet({
className="flex flex-wrap items-baseline gap-2 text-[12px]"
>
{o.href && !o.blocked ? (
- <Link href={o.href} className="text-[var(--color-sel)] underline">
+ <Link href={o.href} className="ink-link">
{o.label}
</Link>
) : (
diff --git a/umtool/components/ThumbBench.tsx b/umtool/components/ThumbBench.tsx
@@ -135,7 +135,7 @@ export default function ThumbBench({
href={v.link}
target="_blank"
rel="noreferrer"
- className="text-[var(--color-sel)] underline"
+ className="ink-link"
>
{v.video}
</a>
@@ -155,7 +155,7 @@ export default function ThumbBench({
<Link
href={`/browse/faces?cover=${encodeURIComponent(c.name)}`}
data-judge-faces={c.name}
- className="text-[11px] text-[var(--color-sel)] hover:underline"
+ className="text-[11px] ink-link"
>
judge {c.corners.length === 1 ? "this face" : `these ${c.corners.length} faces`} →
</Link>
diff --git a/umtool/components/Waveform.tsx b/umtool/components/Waveform.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
+import { alpha, usePalette } from "@/components/ui/use-palette";
import type { AsrWord } from "@/lib/types";
export type Peaks = { from: number; to: number; min: number[]; max: number[] };
@@ -49,6 +50,8 @@ export default function Waveform({
height = 168,
}: Props) {
const ref = useRef<HTMLCanvasElement | null>(null);
+ // The roles as colours, repainting on a theme switch (components/ui/use-palette.ts).
+ const pal = usePalette();
const [width, setWidth] = useState(900);
const drag = useRef<"start" | "end" | null>(null);
const edgeFired = useRef(false);
@@ -78,7 +81,7 @@ export default function Waveform({
g.clearRect(0, 0, width, height);
// ground
- g.fillStyle = "#0f141a";
+ g.fillStyle = pal.ground;
g.fillRect(0, 0, width, height);
const mid = height / 2;
@@ -86,7 +89,7 @@ export default function Waveform({
// outside the selection is dimmed, so the selection reads without a border
const sx = toX(sel.from);
const ex = toX(sel.to);
- g.fillStyle = "#131b24";
+ g.fillStyle = pal.panel;
g.fillRect(Math.max(0, sx), 0, Math.max(0, ex - sx), height);
// waveform
@@ -100,7 +103,7 @@ export default function Waveform({
const x = toX(t0);
if (x < -2 || x > width + 2) continue;
const inSel = t0 >= sel.from && t0 <= sel.to;
- g.fillStyle = inSel ? "#e7edf4" : "#3d4b5a";
+ g.fillStyle = inSel ? pal.text : pal["seam-2"];
const hi = peaks.max[i];
const lo = peaks.min[i];
const y0 = mid - hi * (mid - 6);
@@ -108,7 +111,7 @@ export default function Waveform({
g.fillRect(x, Math.min(y0, y1), Math.max(1, width / n), Math.max(1, Math.abs(y1 - y0)));
}
} else {
- g.fillStyle = "#26313d";
+ g.fillStyle = pal.seam;
g.fillRect(0, mid - 1, width, 2);
}
@@ -118,16 +121,16 @@ export default function Waveform({
if (w.end < view.from || w.start > view.to) continue;
const a = toX(w.start);
const b = toX(w.end);
- g.fillStyle = "rgba(88,166,255,0.10)";
+ g.fillStyle = alpha(pal.signal, 0.1);
g.fillRect(a, height - 22, Math.max(1, b - a), 22);
- g.fillStyle = "#6f8296";
+ g.fillStyle = pal.muted;
g.fillText(w.w, a + 3, height - 7);
}
// Whisper's own detection, as a dashed reference -- the window may be well
// outside it, and that is the point.
g.setLineDash([3, 3]);
- g.strokeStyle = "#4a5a6b";
+ g.strokeStyle = pal["muted-2"];
g.lineWidth = 1;
g.beginPath();
g.moveTo(toX(cand.from), 0);
@@ -144,8 +147,8 @@ export default function Waveform({
const a = toX(c.from);
const b = toX(c.to);
if (b < -2 || a > width + 2) continue;
- const colour = c.verdict === 1 ? "#3fb950" : c.verdict === 0 ? "#f85149" : "#d29922";
- g.fillStyle = `${colour}22`;
+ const colour = c.verdict === 1 ? pal.kept : c.verdict === 0 ? pal.reject : pal.doubt;
+ g.fillStyle = alpha(colour, 0.13);
g.fillRect(a, 0, Math.max(1, b - a), height);
g.fillStyle = colour;
g.fillRect(a, 0, Math.max(1, b - a), 3);
@@ -157,8 +160,8 @@ export default function Waveform({
// handles
for (const [x, colour] of [
- [sx, "#58a6ff"],
- [ex, "#58a6ff"],
+ [sx, pal.signal],
+ [ex, pal.signal],
] as const) {
g.fillStyle = colour;
g.fillRect(x - 1, 0, 2, height);
@@ -167,10 +170,10 @@ export default function Waveform({
}
if (playhead != null && playhead >= view.from && playhead <= view.to) {
- g.fillStyle = "#f0f6fc";
+ g.fillStyle = pal.text;
g.fillRect(toX(playhead), 0, 1, height);
}
- }, [width, height, peaks, sel, cand, words, view, toX, playhead, captured]);
+ }, [width, height, peaks, sel, cand, words, view, toX, playhead, captured, pal]);
const pick = (x: number): "start" | "end" => {
const ds = Math.abs(x - toX(sel.from));
diff --git a/umtool/components/articles/ArticleBody.tsx b/umtool/components/articles/ArticleBody.tsx
@@ -33,7 +33,7 @@ function CiteLink({ href, children }: AnchorHTMLAttributes<HTMLAnchorElement>) {
const id = href?.startsWith(CITE_SCHEME) ? href.slice(CITE_SCHEME.length).trim() : null;
if (id === null) {
return (
- <a href={href} target="_blank" rel="noopener noreferrer" className="text-[var(--color-sel)] underline decoration-[var(--color-sel)]/40">
+ <a href={href} target="_blank" rel="noopener noreferrer" className="ink-link">
{children}
</a>
);
diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx
@@ -10,6 +10,7 @@ import ArticleReader from "@/components/articles/ArticleReader";
import WorkspacePanel from "@/components/articles/WorkspacePanel";
import IterationsView from "@/components/articles/IterationsView";
import { badgeVariants } from "@/components/ui/badge";
+import { Tabs } from "@/components/ui/tabs";
import { articleView } from "@/lib/articles/article";
import { articleHref } from "@/lib/articles/href";
import { articleWorkspaceListing, openWorkspaceFile } from "@/lib/articles/files";
@@ -84,7 +85,7 @@ export default async function ArticlePage({
{r?.updated && <span>updated {r.updated}</span>}
{head && <span data-revisions={head.revision}>{head.revision} revision{head.revision === 1 ? "" : "s"}</span>}
{links.linked.map((p: { id: string }) => (
- <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="font-mono text-[var(--color-sel)] hover:underline">
+ <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="font-mono ink-link">
{p.id}
</Link>
))}
@@ -93,27 +94,22 @@ export default async function ArticlePage({
{p.id} (possible)
</Link>
))}
- <nav className="ml-auto flex gap-2" aria-label="article views">
- <Link href={base} aria-current={tab === "article" ? "page" : undefined} className={tab === "article" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}>
- article
- </Link>
- <Link href={`${base}?tab=source`} aria-current={tab === "source" ? "page" : undefined} className={tab === "source" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}>
- source
- </Link>
- <Link href={`${base}/evidence`} className="hover:text-[var(--color-text)]">
- evidence
- </Link>
- {store && (
- <Link
- href={`${base}?tab=iterations`}
- aria-current={tab === "iterations" ? "page" : undefined}
- className={tab === "iterations" ? "text-[var(--color-sel)]" : "hover:text-[var(--color-text)]"}
- >
- iterations
- </Link>
- )}
- </nav>
- {store && <DeleteArticle article={reportId} published={published} />}
+ {/* The article's views as link tabs: each an address, the current one lit. */}
+ <Tabs
+ label="article views"
+ className="order-last w-full"
+ items={[
+ { href: base, label: "article", current: tab === "article" },
+ { href: `${base}?tab=source`, label: "source", current: tab === "source" },
+ { href: `${base}/evidence`, label: "evidence" },
+ ...(store ? [{ href: `${base}?tab=iterations`, label: "iterations", current: tab === "iterations" }] : []),
+ ]}
+ />
+ {store && (
+ <span className="ml-auto">
+ <DeleteArticle article={reportId} published={published} />
+ </span>
+ )}
{source && (
<div className="w-full font-mono text-[11px]" title={source.how}>
{source.draft && <span>draft {source.draft}</span>}
@@ -183,7 +179,7 @@ export default async function ArticlePage({
<div className="space-y-4">
{meta}
{hasSlides(slideView) && (
- <section data-slide-lint={lint.length + slideProblems.length} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]">
+ <section data-slide-lint={lint.length + slideProblems.length} className="rounded-[3px] border border-seam bg-panel px-4 py-3 text-[12px]">
<div className="micro">slides</div>
{lint.length + slideProblems.length === 0 ? (
<p className="mt-1 text-[var(--color-dim)]">nothing to fix</p>
@@ -196,7 +192,7 @@ export default async function ArticlePage({
))}
{lint.map((l, i) => (
<li key={`l${i}`} data-lint={l.key}>
- <Link href={`${base}?rv=slides#${l.anchorId}`} className="font-mono text-[11px] text-[var(--color-sel)] hover:underline">
+ <Link href={`${base}?rv=slides#${l.anchorId}`} className="font-mono text-[11px] ink-link">
{l.key}
</Link>{" "}
<span className="text-[var(--color-text)]">{l.message}</span>
diff --git a/umtool/components/articles/ArticleTable.tsx b/umtool/components/articles/ArticleTable.tsx
@@ -85,7 +85,7 @@ export default function ArticleTable({ articles }: { articles: ArticleRow[] }) {
</td>
<td className="py-1.5 pl-3 pr-3">
{a.projects.linked.map((p) => (
- <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="block font-mono text-[11px] text-[var(--color-sel)] hover:underline">
+ <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="block font-mono text-[11px] ink-link">
{p.id}
</Link>
))}
diff --git a/umtool/components/articles/EvidencePanel.tsx b/umtool/components/articles/EvidencePanel.tsx
@@ -71,8 +71,10 @@ const EvidencePanel = forwardRef<
return (
<div data-evidence={ev.cite} className="space-y-2 text-[12px]">
- <blockquote className="border-l-2 border-[var(--color-sel)] pl-2 text-[13px] text-[var(--color-text)]">
- {number !== undefined && <span className="mr-1 font-mono text-[11px] text-[var(--color-sel)]">[{number}]</span>}“{ev.quote}”
+ {/* The source's words on the READER (app/globals.css); our notes about
+ them stay on the desk around it. */}
+ <blockquote className="reader m-0 rounded-[2px] px-3.5 py-2.5 font-serif text-[16px] leading-snug">
+ {number !== undefined && <span className="mr-1.5 font-mono text-[11px] text-reader-signal">[{number}]</span>}“{ev.quote}”
</blockquote>
<div className="text-[var(--color-dim)]">
{[ev.speaker ?? ev.record?.channelTitle, ev.date, ev.label].filter(Boolean).join(" · ")}
@@ -84,7 +86,7 @@ const EvidencePanel = forwardRef<
</div>
{ev.record?.title && <div className="text-[var(--color-dim)]">{ev.record.title}</div>}
{ev.originalUrl && (
- <a href={ev.originalUrl} target="_blank" rel="noopener noreferrer" className="text-[var(--color-sel)] hover:underline">
+ <a href={ev.originalUrl} target="_blank" rel="noopener noreferrer" className="ink-link">
original ↗
</a>
)}
@@ -129,28 +131,28 @@ const EvidencePanel = forwardRef<
) : null}
{ev.post && (
- <div data-post className="space-y-1 rounded border border-[var(--color-line)] p-2">
- {ev.post.author && <div className="text-[var(--color-dim)]">{ev.post.author}</div>}
- {ev.post.text && <p className="whitespace-pre-wrap text-[var(--color-text)]">{ev.post.text}</p>}
+ <div data-post className="reader space-y-1 rounded-[2px] px-3.5 py-2.5">
+ {ev.post.author && <div className="text-[12px] text-reader-dim">{ev.post.author}</div>}
+ {ev.post.text && <p className="whitespace-pre-wrap font-serif text-[15px] leading-snug">{ev.post.text}</p>}
{ev.post.shot && (
// eslint-disable-next-line @next/next/no-img-element
- <img src={ev.post.shot} alt="capture of the post" className="w-full rounded border border-[var(--color-line)]" />
+ <img src={ev.post.shot} alt="capture of the post" className="w-full rounded-[2px] border border-reader-seam" />
)}
</div>
)}
{ev.cues.length > 0 ? (
- <ol data-cues className="space-y-0.5">
+ <ol data-cues className="reader space-y-0.5 rounded-[2px] py-1.5">
{ev.cues.map((c) => (
<li key={c.start} data-cited={c.cited ? "true" : undefined}>
<button
type="button"
onClick={() => seek(c.start)}
disabled={!play}
- className={`flex w-full gap-2 rounded px-1 text-left ${c.cited ? "bg-[var(--color-panel-2)] text-[var(--color-text)]" : "text-[var(--color-dim)]"} enabled:hover:text-[var(--color-text)]`}
+ className={`flex w-full items-baseline gap-3 border-l-[3px] px-2.5 py-px text-left ${c.cited ? "border-reader-signal bg-[color-mix(in_srgb,var(--reader-signal)_9%,transparent)] text-reader-ink" : "border-transparent text-reader-2"} enabled:hover:text-reader-ink`}
>
- <span className="num shrink-0 font-mono text-[10px] leading-5">{fmt(c.start)}</span>
- <span>{c.text}</span>
+ <span className={`num shrink-0 font-mono text-[10.5px] ${c.cited ? "font-semibold text-reader-signal" : "text-reader-dim"}`}>{fmt(c.start)}</span>
+ <span className="font-serif text-[15px] leading-snug">{c.text}</span>
</button>
</li>
))}
diff --git a/umtool/components/dashboard/DecisionsPanel.tsx b/umtool/components/dashboard/DecisionsPanel.tsx
@@ -36,7 +36,7 @@ export default function DecisionsPanel({ decisions }: { decisions: Decision[] })
className="flex flex-wrap items-baseline gap-1.5 text-[11px]"
>
<span className={badgeVariants({ variant: TONE[d.severity], size: "sm" })}>{d.severity}</span>
- <Link href={d.href} className="font-mono text-[var(--color-sel)] hover:underline">
+ <Link href={d.href} className="font-mono ink-link">
{d.project}
</Link>
<span className="truncate text-[var(--color-dim)]">
diff --git a/umtool/components/dashboard/DeliverablesPanel.tsx b/umtool/components/dashboard/DeliverablesPanel.tsx
@@ -22,7 +22,7 @@ export default function DeliverablesPanel({ projects }: { projects: ProjectSumma
{newest && (
<span>
newest{" "}
- <Link href={`/browse/${newest.id}`} className="font-mono text-[var(--color-sel)] hover:underline">
+ <Link href={`/browse/${newest.id}`} className="font-mono ink-link">
{newest.id}
</Link>{" "}
<span className="num">{fmtAgo(newest.newestMtimeMs)}</span>
diff --git a/umtool/components/dashboard/NowLive.tsx b/umtool/components/dashboard/NowLive.tsx
@@ -68,7 +68,7 @@ export default function NowLive({ initial }: { initial: ActivityItem | null }) {
return (
<div data-now={now.state} data-now-id={now.id} className="space-y-1.5">
<div className="flex flex-wrap items-baseline gap-2 text-[12px]">
- <Link href={now.href} className="font-mono text-[var(--color-sel)] hover:underline">
+ <Link href={now.href} className="font-mono ink-link">
{now.label}
</Link>
<span className="micro">{now.source}</span>
diff --git a/umtool/components/dashboard/Panel.tsx b/umtool/components/dashboard/Panel.tsx
@@ -1,6 +1,7 @@
import Link from "next/link";
+import { Panel as UiPanel } from "@/components/ui/panel";
-/** The dashboard's one box shape: a micro title, an optional "all →", a body. */
+/** The dashboard's one box shape: a micro title, an optional "all →", a body (components/ui/panel.tsx). */
export default function Panel({
title,
testid,
@@ -15,19 +16,19 @@ export default function Panel({
className?: string;
}) {
return (
- <section
+ <UiPanel
data-panel={testid}
- className={`rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 ${className}`}
- >
- <div className="mb-1.5 flex items-baseline">
- <h2 className="micro">{title}</h2>
- {more && (
- <Link href={more.href} className="ml-auto text-[11px] text-[var(--color-sel)] hover:underline">
+ title={title}
+ aside={
+ more && (
+ <Link href={more.href} className="ink-link text-[12px]">
{more.label}
</Link>
- )}
- </div>
+ )
+ }
+ className={className}
+ >
{children}
- </section>
+ </UiPanel>
);
}
diff --git a/umtool/components/dashboard/SourcesPanel.tsx b/umtool/components/dashboard/SourcesPanel.tsx
@@ -20,7 +20,7 @@ export default function SourcesPanel({
<ul className="space-y-0.5" data-sources-list={attr}>
{items.map((p) => (
<li key={p.id} data-source-project={p.id} className="flex flex-wrap gap-2 text-[11px]">
- <Link href={`/browse/${p.id}`} className="font-mono text-[var(--color-sel)] hover:underline">
+ <Link href={`/browse/${p.id}`} className="font-mono ink-link">
{p.id}
</Link>
<span className="text-[var(--color-dim)]">
diff --git a/umtool/components/notes/AnchoredNotes.tsx b/umtool/components/notes/AnchoredNotes.tsx
@@ -41,7 +41,7 @@ export default function AnchoredNotes({
type="button"
data-action="toggle-notes"
onClick={() => setOpen((o) => !o)}
- className={openCount ? badgeVariants({ variant: "open", size: "sm" }) : "text-[var(--color-sel)] hover:underline"}
+ className={openCount ? badgeVariants({ variant: "open", size: "sm" }) : "ink-link"}
>
{openCount ? `${openCount} open ${openCount === 1 ? "note" : "notes"}` : mine.length ? `${label} (${mine.length})` : `+ ${label.replace(/s$/, "")}`}
</button>
diff --git a/umtool/components/notes/NoteThread.tsx b/umtool/components/notes/NoteThread.tsx
@@ -45,11 +45,11 @@ export function NoteThread({
</button>
</>
) : (
- <button type="button" data-note-action="reopen" disabled={busy} onClick={() => void write({ op: "status", id: note.id, status: "open" })} className="text-[var(--color-sel)] hover:underline disabled:opacity-40">
+ <button type="button" data-note-action="reopen" disabled={busy} onClick={() => void write({ op: "status", id: note.id, status: "open" })} className="ink-link disabled:opacity-40">
reopen
</button>
)}
- <button type="button" data-note-action="reply" disabled={busy} onClick={() => setReply((r) => (r === null ? "" : null))} className="text-[var(--color-sel)] hover:underline disabled:opacity-40">
+ <button type="button" data-note-action="reply" disabled={busy} onClick={() => setReply((r) => (r === null ? "" : null))} className="ink-link disabled:opacity-40">
reply
</button>
{note.author === "operator" && (
diff --git a/umtool/components/notes/TimedNotes.tsx b/umtool/components/notes/TimedNotes.tsx
@@ -170,7 +170,7 @@ export default function TimedNotes({
<button
type="button"
onClick={() => seek(n.anchor.t)}
- className="num text-[11px] text-[var(--color-sel)] underline"
+ className="num text-[11px] ink-link"
title="seek here"
>
{ts(n.anchor.t)}
@@ -183,7 +183,7 @@ export default function TimedNotes({
)}
{r?.approx && <span className={badgeVariants({ variant: "info", size: "sm" })}>approx</span>}
{r?.url && (
- <a href={r.url} target="_blank" rel="noreferrer" className="text-[11px] text-[var(--color-sel)] hover:underline">
+ <a href={r.url} target="_blank" rel="noreferrer" className="text-[11px] ink-link">
source
</a>
)}
diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx
@@ -280,8 +280,8 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
className={
"cursor-pointer " +
(c.cited
- ? "bg-[var(--color-sel)]/25 text-[var(--color-fg)]"
- : "text-[var(--color-dim)] hover:text-[var(--color-fg)]")
+ ? "bg-[color-mix(in_srgb,var(--reader-signal)_14%,transparent)] text-reader-ink"
+ : "text-reader-2 hover:text-reader-ink")
}
>
{c.text}{" "}
@@ -300,12 +300,12 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
</div>
<div className="flex-1" />
{data.prev ? (
- <Link className="text-[11px] text-[var(--color-sel)] hover:underline" href={`/browse/${data.project}/claim/${data.prev}`}>
+ <Link className="text-[11px] ink-link" href={`/browse/${data.project}/claim/${data.prev}`}>
← {data.prev}
</Link>
) : null}
{data.next ? (
- <Link className="text-[11px] text-[var(--color-sel)] hover:underline" href={`/browse/${data.project}/claim/${data.next}`}>
+ <Link className="text-[11px] ink-link" href={`/browse/${data.project}/claim/${data.next}`}>
{data.next} →
</Link>
) : null}
@@ -337,30 +337,31 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
</div>
)}
- <div className="rounded border border-[var(--color-line)] p-3">
+ {/* The source's words, on the READER (app/globals.css). */}
+ <div className="reader rounded-[2px] px-4 py-3">
<div className="micro mb-2">
±{data.pad}s of context · {hms(view.from)}–{hms(view.to)}
{at != null ? ` · cited at ${hms(at)}` : ""}
</div>
{data.noCues ? (
- <div className="text-[12px] text-[var(--color-dim)]">
+ <div className="text-[12px] text-reader-dim">
no transcript.cues.json for {claim.channel}/{claim.video} — on Rumble, check the
directory is the URL slug and not the site id
</div>
) : (
<p
data-testid="claim-context"
- className="max-h-[320px] overflow-y-auto text-[12px] leading-relaxed"
+ className="max-h-[320px] overflow-y-auto font-serif text-[15px] leading-relaxed"
>
{paragraph}
</p>
)}
</div>
- <div className="rounded border border-[var(--color-line)] p-3 text-[12px]">
+ <div className="reader rounded-[2px] px-4 py-3 text-[12px]">
<div className="micro mb-1">as recorded</div>
- <div className="text-[var(--color-fg)]">“{claim.quote}”</div>
- <div className="mt-1 text-[11px] text-[var(--color-dim)]">
+ <div className="font-serif text-[16px] leading-snug text-reader-ink">“{claim.quote}”</div>
+ <div className="mt-1 font-mono text-[11px] text-reader-dim">
{claim.label} · {claim.src}
</div>
</div>
@@ -368,7 +369,7 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
<div className="space-y-3 text-[12px]">
{data.gaps.length ? (
- <div className="rounded border border-[var(--color-warn,#E8A33F)] p-2 text-[11px] text-[var(--color-dim)]">
+ <div className="rounded border border-doubt-text p-2 text-[11px] text-doubt-text">
unadjudicated — missing {data.gaps.join(", ")}
</div>
) : (
diff --git a/umtool/components/projects/ClaimBenchPage.tsx b/umtool/components/projects/ClaimBenchPage.tsx
@@ -1,5 +1,6 @@
import { notFound } from "next/navigation";
-import BrowseHeader from "@/components/BrowseHeader";
+import AppShell from "@/components/shell/AppShell";
+import { browseHref, projectHref } from "@/lib/hrefs";
import ClaimBench, { type ClaimBenchData } from "./ClaimBench";
import { manifestToken } from "@/lib/report/manifest.mjs";
import { readClaimDetail, readManifest } from "@/lib/projects/report.mjs";
@@ -85,10 +86,13 @@ export default async function ClaimBenchPage({
return (
<div className="flex h-full flex-col">
- <BrowseHeader
+ {/* A bench: the rail collapses and the work takes the width. */}
+ <AppShell
+ active="browse"
+ rail="collapsed"
crumbs={[
- { href: "/browse", label: "projects" },
- { href: `/browse/${project.id}`, label: project.name },
+ { href: browseHref(), label: "projects" },
+ { href: projectHref(project.id), label: project.name },
{ label: claimId },
]}
note={`claim ${i + 1} of ${ledger.length} · ${outstanding} unadjudicated`}
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -1883,7 +1883,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<Link
data-clip-nav="prev"
href={`/browse/${data.project}/clip/${data.prev}`}
- className="text-[var(--color-sel)] hover:underline"
+ className="ink-link"
>
← {data.prev}
</Link>
@@ -1894,7 +1894,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<Link
data-clip-nav="next"
href={`/browse/${data.project}/clip/${data.next}`}
- className="text-[var(--color-sel)] hover:underline"
+ className="ink-link"
>
{data.next} →
</Link>
@@ -2437,7 +2437,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<div
data-transcript=""
ref={transcriptBox}
- className="relative flex h-48 min-h-0 flex-col overflow-y-auto rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] lg:h-auto lg:flex-[2_1_0%]"
+ // On the READER: these are the source's words (app/globals.css).
+ className="reader relative flex h-48 min-h-0 flex-col overflow-y-auto rounded-[2px] lg:h-auto lg:flex-[2_1_0%]"
>
<ul>
{railCues.map((c, i) => {
@@ -2457,7 +2458,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
{rule && (
<div
data-cache-rule={outside ? "end" : "start"}
- className="flex items-center gap-2 border-t border-dashed border-[var(--color-meter)] px-2 py-0.5 text-[10px] uppercase tracking-wider text-[var(--color-meter)]"
+ className="flex items-center gap-2 border-t border-dashed border-reader-2 px-2 py-0.5 text-[10px] uppercase tracking-wider text-reader-dim"
>
{outside ? "not fetched — reading only" : "cached from here"}
</div>
@@ -2479,36 +2480,32 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
}
void play(c.start, Math.min(c.end + 4, view.to));
}}
- className={`flex w-full gap-2 px-2 py-1 text-left hover:bg-[color-mix(in_srgb,var(--color-sel)_10%,transparent)] ${
- inSel ? "bg-[color-mix(in_srgb,var(--color-sel)_14%,transparent)]" : ""
- } ${playing ? "border-l-2 border-[var(--color-meter)]" : "border-l-2 border-transparent"}`}
+ className={`flex w-full items-baseline gap-3 px-2.5 py-[3px] text-left hover:bg-[color-mix(in_srgb,var(--reader-signal)_6%,transparent)] ${
+ inSel ? "bg-[color-mix(in_srgb,var(--reader-signal)_11%,transparent)]" : ""
+ } ${playing ? "border-l-[3px] border-reader-signal" : "border-l-[3px] border-transparent"}`}
>
<span
- className={`num w-10 shrink-0 font-mono text-[10px] ${
- playing ? "text-[var(--color-meter)]" : "text-[var(--color-dim)]"
+ className={`num w-10 shrink-0 font-mono text-[10.5px] ${
+ playing ? "font-semibold text-reader-signal" : "text-reader-dim"
}`}
>
{clock(c.start)}
</span>
<span
- className={`min-w-0 text-[12px] leading-snug ${
- outside
- ? "text-[var(--color-dim)] opacity-70"
- : playing
- ? "text-[var(--color-text)]"
- : "text-[var(--color-text)]"
+ className={`min-w-0 font-serif text-[15px] leading-snug ${
+ outside ? "text-reader-dim opacity-70" : inSel || playing ? "text-reader-ink" : "text-reader-2"
}`}
>
{owner && (
<span
- className="mr-1.5 rounded border border-[var(--color-sel)] px-1 text-[10px] text-[var(--color-sel)]"
+ className="mr-1.5 rounded-[2px] border border-reader-2 px-1 font-mono text-[10px] text-reader-ink"
title={`already in the cut as ${owner.id} (${owner.where})`}
>
{owner.id}
</span>
)}
{c.endsSentence && (
- <span className="mr-1 text-[var(--color-meter)]" aria-hidden>
+ <span className="mr-1 font-mono text-[11px] text-reader-dim" aria-hidden>
¶
</span>
)}
@@ -2525,17 +2522,15 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
bottom of its scrollport: they cost the pane a line and the
left column nothing, and "peek further" ends up beside the
dimmed lines it widens. Opaque, because it sits over text. */}
- <div className="micro sticky bottom-0 z-10 flex flex-wrap items-center gap-2 border-t border-[var(--color-line)] bg-[var(--color-panel-2)] px-2 py-0.5">
+ <div className="micro sticky bottom-0 z-10 flex flex-wrap items-center gap-2 border-t border-reader-seam bg-reader px-2.5 py-1">
<span>click a line to play it</span>
{peek.length > 0 && (
<>
- <span className="text-[var(--color-dim)]">
- · dimmed lines are not fetched — click to fetch
- </span>
+ <span>· dimmed lines are not fetched — click to fetch</span>
<button
type="button"
data-peek-further=""
- className="ml-auto text-[var(--color-sel)] hover:underline"
+ className="ml-auto text-reader-signal hover:underline"
onClick={() => setPeekPad((n) => n + PEEK_STEP)}
>
peek further (±{peekPad + PEEK_STEP} s)
@@ -2799,7 +2794,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<li key={sb.id} data-sibling={sb.id} className="leading-snug">
<Link
href={`/browse/${data.project}/clip/${sb.id}`}
- className="font-mono text-[var(--color-sel)] hover:underline"
+ className="font-mono ink-link"
>
{sb.id}
</Link>{" "}
diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx
@@ -1,5 +1,6 @@
import { notFound } from "next/navigation";
-import BrowseHeader from "@/components/BrowseHeader";
+import AppShell from "@/components/shell/AppShell";
+import { browseHref, projectHref } from "@/lib/hrefs";
import ClipBench, { type ClipBenchData } from "./ClipBench";
import { manifestToken } from "@/lib/report/manifest.mjs";
import {
@@ -165,10 +166,13 @@ export default async function ClipBenchPage({
return (
<div className="flex h-full flex-col">
- <BrowseHeader
+ {/* A bench: the rail collapses and the work takes the width. */}
+ <AppShell
+ active="browse"
+ rail="collapsed"
crumbs={[
- { href: "/browse", label: "projects" },
- { href: `/browse/${project.id}`, label: project.name },
+ { href: browseHref(), label: "projects" },
+ { href: projectHref(project.id), label: project.name },
{ label: clipId },
]}
// The progress reading moved INTO the bench, where pressing `y` can
diff --git a/umtool/components/projects/CutPage.tsx b/umtool/components/projects/CutPage.tsx
@@ -87,7 +87,7 @@ export default async function CutPage({
<div className="p-4 text-[12px] text-[var(--color-dim)]">
Nothing here yet — no <code className="font-mono">{cutName}.mp4</code> and no variants
named for it.{" "}
- <Link href={`/browse/${song.id}`} className="text-[var(--color-sel)] underline">
+ <Link href={`/browse/${song.id}`} className="ink-link">
back to {song.id}
</Link>
</div>
diff --git a/umtool/components/projects/DeliverSection.tsx b/umtool/components/projects/DeliverSection.tsx
@@ -222,7 +222,7 @@ export default async function DeliverSection({
<Link
href={`/browse/${project.id}/clip/${c.id}`}
data-need-cut-id={c.id}
- className="font-mono text-[var(--color-sel)] hover:underline"
+ className="font-mono ink-link"
>
{c.id}
</Link>
@@ -270,7 +270,7 @@ export default async function DeliverSection({
<div key={c.id} data-incorrect={c.id} className="text-[11px] leading-snug">
<Link
href={`/browse/${project.id}/clip/${c.id}`}
- className="font-mono text-[var(--color-sel)] hover:underline"
+ className="font-mono ink-link"
>
{c.id}
</Link>{" "}
diff --git a/umtool/components/projects/PodcastExport.tsx b/umtool/components/projects/PodcastExport.tsx
@@ -80,17 +80,17 @@ export default function PodcastExport({
{state === "running" || state === "busy" ? "rendering the podcast…" : files.m4a ? "re-render podcast" : "podcast"}
</button>
{files.m4a && (
- <a href={href("m4a", true)} data-podcast-file="m4a" className="font-mono text-[var(--color-sel)] hover:underline">
+ <a href={href("m4a", true)} data-podcast-file="m4a" className="font-mono ink-link">
podcast.m4a
</a>
)}
{files.mp3 && (
- <a href={href("mp3", true)} data-podcast-file="mp3" className="font-mono text-[var(--color-sel)] hover:underline">
+ <a href={href("mp3", true)} data-podcast-file="mp3" className="font-mono ink-link">
podcast.mp3
</a>
)}
{files.notes && (
- <a href={href("notes")} target="_blank" rel="noreferrer" data-podcast-file="notes" className="font-mono text-[var(--color-sel)] hover:underline">
+ <a href={href("notes")} target="_blank" rel="noreferrer" data-podcast-file="notes" className="font-mono ink-link">
show-notes.md
</a>
)}
diff --git a/umtool/components/projects/SweepProject.tsx b/umtool/components/projects/SweepProject.tsx
@@ -64,7 +64,7 @@ export default async function SweepProject({ project }: { project: ProjectRef })
</p>
)}
- <Link href="/browse" className="text-[12px] text-[var(--color-sel)] hover:underline">
+ <Link href="/browse" className="text-[12px] ink-link">
← every project
</Link>
</main>
diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx
@@ -1,5 +1,6 @@
import Link from "next/link";
-import BrowseHeader from "@/components/BrowseHeader";
+import AppShell from "@/components/shell/AppShell";
+import { browseHref, projectHref } from "@/lib/hrefs";
import { listTakes, readVerdicts } from "@/lib/report/takes.mjs";
import type { ProjectRef } from "@/lib/project-types";
import TakesBench, { type Take, type TakeVerdict } from "./TakesBench";
@@ -17,10 +18,13 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
return (
<div className="flex h-full flex-col">
- <BrowseHeader
+ {/* A bench: the rail collapses and the work takes the width. */}
+ <AppShell
+ active="browse"
+ rail="collapsed"
crumbs={[
- { href: "/browse", label: "projects" },
- { href: `/browse/${project.id}`, label: project.id },
+ { href: browseHref(), label: "projects" },
+ { href: projectHref(project.id), label: project.id },
{ label: "takes" },
]}
note={takes.length ? `${takes.length} takes · ${judged} judged` : undefined}
@@ -29,7 +33,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
{takes.length === 0 ? (
<p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]">
No takes yet.{" "}
- <Link href={`/browse/${project.id}`} className="text-[var(--color-sel)] hover:underline">
+ <Link href={`/browse/${project.id}`} className="ink-link">
back to {project.id}
</Link>
</p>
diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx
@@ -161,7 +161,7 @@ export function RowControls({ id, at }: { id: string; at: number }) {
⋯
</button>
{menu && (
- <span className="absolute right-0 z-10 mt-1 flex w-36 flex-col rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-1 text-[11px] shadow">
+ <span className="absolute left-0 z-10 mt-1 flex w-36 flex-col rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-1 text-[11px] shadow">
<button type="button" data-row-action="duplicate" disabled={busy} onClick={() => (setMenu(false), void run("duplicate", { id, at }))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]">
duplicate
</button>
diff --git a/umtool/components/shell/AppHeader.tsx b/umtool/components/shell/AppHeader.tsx
@@ -0,0 +1,105 @@
+import Link from "next/link";
+import { cn } from "@/lib/utils";
+import { Mark } from "./Wordmark";
+
+export type Crumb = { href?: string; label: string };
+
+// ---------------------------------------------------------------------------
+// The page head (canvas `.pagehead`), the top of the work column.
+//
+// The breadcrumb is ONE nav (aria-label "Breadcrumb"): the trail above, small,
+// and the page's own name under it as the <h1> -- set in Archivo at 125% width,
+// the face kept for place and piece titles. The name stays INSIDE the nav, so
+// the breadcrumb still contains every crumb (specs read it) and no text is on
+// the page twice.
+//
+// `note` is the page's one-line status (`.micro`), always the LAST `.micro` in
+// the header -- dashboard.spec reads /browse's that way. `actions` sit to its
+// left. A BENCH header is one compact row (canvas `.benchtop`): a bench fits
+// 1366×768 and its rail is collapsed, so the mark links home from here.
+//
+// No hooks, no server imports: a client page (the song deck) renders it too.
+// ---------------------------------------------------------------------------
+
+export default function AppHeader({
+ crumbs,
+ note,
+ actions,
+ meta,
+ variant = "page",
+ className,
+}: {
+ crumbs: Crumb[];
+ note?: React.ReactNode;
+ /** Controls on the right, before the note. */
+ actions?: React.ReactNode;
+ /** A line under the title (counts, a hint); muted. */
+ meta?: React.ReactNode;
+ variant?: "page" | "bench";
+ className?: string;
+}) {
+ const trail = crumbs.slice(0, -1);
+ const here = crumbs[crumbs.length - 1];
+ const bench = variant === "bench";
+ return (
+ <header
+ data-app-header={variant}
+ className={cn(
+ "flex flex-wrap items-end gap-x-[18px] gap-y-2 border-b border-seam",
+ bench ? "items-center bg-panel px-4 py-2.5" : "px-4 pb-3.5 pt-4",
+ className,
+ )}
+ >
+ {bench && (
+ <Link href="/" aria-label="umtool home" className="shrink-0">
+ <Mark size={18} />
+ </Link>
+ )}
+ <nav aria-label="Breadcrumb" className={cn("min-w-0", bench ? "flex items-center gap-1.5 text-[12.5px]" : "flex flex-col gap-1")}>
+ {trail.length > 0 && (
+ <span className="flex flex-wrap items-center gap-1.5 text-[12px]">
+ {trail.map((c, i) => (
+ <span key={`${c.label}-${i}`} className="flex items-center gap-1.5">
+ {i > 0 && <span className="text-seam-2">/</span>}
+ {c.href ? (
+ <Link href={c.href} className="text-muted-2 hover:text-text">
+ {c.label}
+ </Link>
+ ) : (
+ <span className="text-muted-2">{c.label}</span>
+ )}
+ </span>
+ ))}
+ {bench && <span className="text-seam-2">/</span>}
+ </span>
+ )}
+ {here &&
+ (bench ? (
+ <span aria-current="page" className="font-mono text-[13px] font-medium text-text">
+ {here.href ? <Link href={here.href}>{here.label}</Link> : here.label}
+ </span>
+ ) : (
+ <h1
+ aria-current="page"
+ className={cn(
+ "display m-0 truncate leading-none text-text",
+ here.label.length > 36 ? "text-[20px]" : "text-[26px]",
+ // A place (no trail) is a title in sentence case; a piece's id
+ // stays exactly as it is spelled.
+ trail.length === 0 && "first-letter:uppercase",
+ )}
+ >
+ {here.href ? <Link href={here.href}>{here.label}</Link> : here.label}
+ </h1>
+ ))}
+ </nav>
+ {meta && <div className="text-[12.5px] text-muted">{meta}</div>}
+ {(actions || note) && (
+ <div className="ml-auto flex flex-wrap items-center gap-3">
+ {actions}
+ {note && <div className="micro">{note}</div>}
+ </div>
+ )}
+ </header>
+ );
+}
diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx
@@ -0,0 +1,92 @@
+import Link from "next/link";
+import { cookies } from "next/headers";
+import AppNav from "@/components/AppNav";
+import { runningActivity } from "@/lib/activity";
+import { homeHref } from "@/lib/hrefs";
+import { THEME_COOKIE, parseTheme } from "@/lib/theme";
+import CreateMenu from "./CreateMenu";
+import ThemeControl from "./ThemeControl";
+import { Mark, Wordmark } from "./Wordmark";
+
+// ---------------------------------------------------------------------------
+// The rail (canvas `.rail`): every page's left column. Top to bottom:
+// the mark and the wordmark (home), the places, + Create, the jump hint,
+// Pinned, and at the foot what is Running and the theme.
+//
+// SERVER ONLY: it reads the theme cookie and the in-process job registries.
+// A client page (the song deck) gets it from its server page instead.
+//
+// What is not built yet says so plainly rather than pretending:
+// - Jump (⌘K) is P3's palette; the hint is here, inert, so the rail has its
+// final shape.
+// - Pinned has no store until the piece page (P4a); it is empty.
+// - Running lists umtool's own job (a build, a fetch, a render). The editor's
+// jobs and their spend join it in P2b.
+// ---------------------------------------------------------------------------
+
+export default async function AppRail({ active }: { active: string }) {
+ const theme = parseTheme((await cookies()).get(THEME_COOKIE)?.value);
+ const running = runningActivity();
+ return (
+ <div className="app-rail" data-app-rail="">
+ <Link href={homeHref()} aria-label="umtool home" className="flex items-center gap-[9px] px-4 pb-3.5 pt-4 no-underline">
+ <Mark />
+ <Wordmark />
+ </Link>
+
+ <AppNav active={active} />
+
+ <CreateMenu />
+
+ <div
+ data-rail-section="jump"
+ aria-disabled="true"
+ title="Not built yet"
+ className="mx-4 mb-2 mt-0.5 flex items-center gap-2 px-0.5 py-1 text-[12.5px] text-muted-2"
+ >
+ Jump to…
+ <kbd className="ml-auto">⌘K</kbd>
+ </div>
+
+ <section data-rail-section="pins" aria-label="Pinned">
+ <h2 className="micro px-5 pb-1.5 pt-4">Pinned</h2>
+ <p className="px-5 text-[12px] text-muted-2">Nothing pinned</p>
+ </section>
+
+ <section
+ data-rail-section="running"
+ aria-label="Running"
+ className="mt-auto border-t border-seam pb-2 pt-3"
+ >
+ <h2 className="micro flex justify-between px-5 pb-2">
+ <span>Running</span>
+ <span className="font-mono normal-case tracking-normal text-meter">{running ? 1 : 0}</span>
+ </h2>
+ {running ? (
+ <Link href={running.href} data-running={running.id} className="grid grid-cols-[1fr_auto] gap-x-2 gap-y-0.5 px-5 text-[12px] text-text-2 no-underline hover:text-text">
+ <span className="truncate">{running.label}</span>
+ {running.progress && (
+ <span className="font-mono text-[11px] text-muted-2">
+ {running.progress.step}/{running.progress.of}
+ </span>
+ )}
+ {running.progress && (
+ <span className="relative col-span-2 h-0.5 overflow-hidden bg-seam">
+ <i
+ className="absolute inset-y-0 left-0 bg-meter"
+ style={{ width: `${Math.round((running.progress.step / Math.max(1, running.progress.of)) * 100)}%` }}
+ />
+ </span>
+ )}
+ </Link>
+ ) : (
+ <p className="px-5 text-[12px] text-muted-2">No umtool job running</p>
+ )}
+ </section>
+
+ <div className="px-4 pb-4 pt-3">
+ <ThemeControl initial={theme} />
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/components/shell/AppShell.tsx b/umtool/components/shell/AppShell.tsx
@@ -0,0 +1,47 @@
+import AppHeader, { type Crumb } from "./AppHeader";
+import AppRail from "./AppRail";
+
+export type { Crumb };
+
+// ---------------------------------------------------------------------------
+// The shell: the rail (fixed, left) and the page head, rendered as the FIRST
+// children of a page's own `flex h-full flex-col` column -- the shape every
+// page here already has. The rail is out of flow and the body pads for it
+// (app/globals.css, `body:has(.app-rail)`), so no page changes shape to get it.
+//
+// `rail="collapsed"` is a bench (canvas "Clip bench"): no rail, a compact head
+// whose mark links home, and the whole width for the work.
+//
+// SERVER ONLY (the rail reads the cookie and the job registries). A client page
+// renders <AppRail> from its server page and <AppHeader> itself.
+// ---------------------------------------------------------------------------
+
+export default function AppShell({
+ active,
+ crumbs,
+ note,
+ actions,
+ meta,
+ rail = "open",
+}: {
+ /** The rail entry that is lit. */
+ active: string;
+ crumbs: Crumb[];
+ note?: React.ReactNode;
+ actions?: React.ReactNode;
+ meta?: React.ReactNode;
+ rail?: "open" | "collapsed";
+}) {
+ return (
+ <>
+ {rail === "open" && <AppRail active={active} />}
+ <AppHeader
+ crumbs={crumbs}
+ note={note}
+ actions={actions}
+ meta={meta}
+ variant={rail === "collapsed" ? "bench" : "page"}
+ />
+ </>
+ );
+}
diff --git a/umtool/components/shell/CreateMenu.tsx b/umtool/components/shell/CreateMenu.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useRef, useState } from "react";
+import { browseHref, newArticleHref } from "@/lib/hrefs";
+
+// + Create. Until /create exists (P5) it opens onto today's two doors: a new
+// article (/articles/new) and a new project (/browse carries the "+ new
+// project" form). Inline in the rail, not a popover: the rail scrolls, and a
+// popover would be clipped by it.
+export default function CreateMenu() {
+ const [open, setOpen] = useState(false);
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!open) return;
+ const away = (e: MouseEvent) => {
+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
+ };
+ const key = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
+ document.addEventListener("mousedown", away);
+ document.addEventListener("keydown", key);
+ return () => {
+ document.removeEventListener("mousedown", away);
+ document.removeEventListener("keydown", key);
+ };
+ }, [open]);
+ return (
+ <div ref={ref} data-rail-create="" className="mx-4 mb-1 mt-2.5">
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center gap-2 rounded-[3px] border border-seam-2 px-2.5 py-[6px] text-left font-medium text-text hover:border-muted"
+ >
+ + Create
+ <span aria-hidden="true" className="ml-auto text-muted-2">
+ {open ? "▾" : "▸"}
+ </span>
+ </button>
+ {open && (
+ <div className="mt-1 flex flex-col">
+ <Link href={newArticleHref()} onClick={() => setOpen(false)} className="rounded-[3px] px-2.5 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text">
+ An article
+ </Link>
+ <Link href={browseHref()} onClick={() => setOpen(false)} className="rounded-[3px] px-2.5 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text">
+ A project (video, song, sweep)
+ </Link>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/shell/ThemeControl.tsx b/umtool/components/shell/ThemeControl.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { useState } from "react";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { THEMES, themeAttr, themeCookie, type Theme } from "@/lib/theme";
+
+// Auto / Light / Dark, at the foot of the rail. A choice writes the cookie the
+// root layout reads (lib/theme.ts) and stamps <html> at once, so this page
+// changes now and every later page is served in it -- no reload, no flash.
+export default function ThemeControl({ initial }: { initial: Theme }) {
+ const hydrated = useHydrated();
+ const [theme, setTheme] = useState<Theme>(initial);
+ const choose = (t: Theme) => {
+ document.cookie = themeCookie(t);
+ const attr = themeAttr(t);
+ if (attr) document.documentElement.dataset.theme = attr;
+ else delete document.documentElement.dataset.theme;
+ setTheme(t);
+ };
+ return (
+ <div role="group" aria-label="Theme" data-theme-control={theme} className="flex overflow-hidden rounded-[3px] border border-seam-2">
+ {THEMES.map((t, i) => (
+ <button
+ key={t}
+ type="button"
+ disabled={!hydrated}
+ aria-pressed={theme === t}
+ onClick={() => choose(t)}
+ className={`flex-1 px-2 py-[3px] text-[11.5px] font-medium ${i > 0 ? "border-l border-seam-2" : ""} ${
+ theme === t ? "bg-panel-2 text-text" : "text-muted hover:text-text"
+ }`}
+ >
+ {t === "auto" ? "Auto" : t === "light" ? "Light" : "Dark"}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/umtool/components/shell/Wordmark.tsx b/umtool/components/shell/Wordmark.tsx
@@ -0,0 +1,29 @@
+// The Found-line mark and the wordmark (canvas `.wmk`). "umtool" is ONE word:
+// a bold lead "um" (Archivo 850) and a light "tool" (400), no gap, no space --
+// the brand's two-weight wordmark split. The mark's lines are the lit line's
+// origin: the lit one wears --mark, the others --mark-dim.
+export function Mark({ size = 20 }: { size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 512 512" aria-hidden="true" className="shrink-0">
+ <g transform="translate(51.2 51.2) scale(0.8)">
+ <rect x="112" y="128" width="288" height="44" rx="22" fill="var(--mark-dim)" />
+ <polygon points="112,210 172,234 112,258" fill="var(--mark)" />
+ <rect x="188" y="212" width="212" height="44" rx="22" fill="var(--mark)" />
+ <rect x="112" y="296" width="232" height="44" rx="22" fill="var(--mark-dim)" />
+ <rect x="112" y="380" width="152" height="44" rx="22" fill="var(--mark-dim)" />
+ </g>
+ </svg>
+ );
+}
+
+export function Wordmark({ size = 17 }: { size?: number }) {
+ return (
+ <span
+ className="whitespace-nowrap font-display leading-none"
+ style={{ fontSize: size, fontVariationSettings: '"wdth" 125' }}
+ >
+ <b className="font-[850]">um</b>
+ <span className="font-normal text-text-2">tool</span>
+ </span>
+ );
+}
diff --git a/umtool/components/ui/badge.tsx b/umtool/components/ui/badge.tsx
@@ -9,28 +9,31 @@ import { cn } from "@/lib/utils";
// client component. /browse and /browse/decisions are server-rendered with
// their filters as plain links, and a Radix component would quietly end that.
//
-// The variants name PALETTE MEANINGS rather than shadcn's defaults, because the
-// palette's rule is that colour means something: `on` is the interaction colour
-// (the only one), and blocking/open/info are the three severities the decisions
-// inbox already speaks in. There is no `primary`/`secondary` pair here because
-// this app has no such distinction to make.
+// Two jobs, by size:
+// - `md` is the canvas's FILTER CHIP (`.chip`): UI type, an outline, and the
+// chosen one (`on`) a raised surface with an ink edge -- a selection is a
+// state of the desk, not a Signal (Signal is for the lit line and the one
+// primary action).
+// - `sm` is a STATUS TAG: mono, caps, in the colour of what it reports.
+// The variants name ROLES (app/globals.css): blocking/open are the reject and
+// doubt words, `meter` is a measurement, neutral/info are ink.
// ---------------------------------------------------------------------------
export const badgeVariants = cva(
- "inline-flex items-center rounded border px-1.5 py-0.5 font-mono text-[11px] transition-colors",
+ "inline-flex items-center gap-1.5 whitespace-nowrap rounded-[3px] border transition-colors",
{
variants: {
variant: {
- neutral: "border-border text-muted-foreground hover:text-foreground",
- on: "border-primary text-primary",
- blocking: "border-destructive text-destructive",
- open: "border-[var(--color-dirty)] text-[var(--color-dirty)]",
- info: "border-border text-muted-foreground",
- meter: "border-[var(--color-meter)] text-[var(--color-meter)]",
+ neutral: "border-seam-2 text-text-2 hover:text-text",
+ on: "border-muted bg-panel-2 text-text",
+ blocking: "border-reject-text text-reject-text",
+ open: "border-doubt-text text-doubt-text",
+ info: "border-seam-2 text-muted",
+ meter: "border-meter text-meter",
},
size: {
- sm: "px-1.5 py-0.5 text-[10px] uppercase tracking-wider",
- md: "",
+ sm: "px-1.5 py-px font-mono text-[10px] uppercase tracking-wider",
+ md: "px-2 py-[3px] text-[12px]",
},
},
defaultVariants: { variant: "neutral", size: "md" },
diff --git a/umtool/components/ui/button.tsx b/umtool/components/ui/button.tsx
@@ -4,26 +4,40 @@ import { cn } from "@/lib/utils";
// Same posture as badge.tsx: the variants are a class helper first, so a <Link>
// can wear them without hydrating, and a <button> second.
//
+// The canvas's three buttons, by role (app/globals.css, "COLOUR MEANS
+// SOMETHING"):
+// - `go` FILLED Signal. The ONE primary action on a screen -- what the
+// operator came here to do. Never two on a screen.
+// - `outline` the default: every other action is an outline in ink.
+// - `quiet` no border; secondary moves like Park, prev / next.
+// and three kept from before, restyled onto the roles:
+// - `primary` an outline in Signal: an action that is interaction-led
+// but not THE action (there are screens with several).
+// - `destructive` an outline in the reject word; deletes are plan-then-confirm.
+// - `ghost` an alias of `quiet`, for the call sites that already say it.
+//
// Hit sizes are the ones this app already uses. It is a bench somebody sits
// with for hours, so nothing here is smaller than what the existing controls
-// are, and `sm` is the default because dense is the point.
+// are, and dense is the point.
export const buttonVariants = cva(
- "inline-flex items-center justify-center gap-1.5 rounded border transition-colors disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none focus-visible:border-primary",
+ "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border font-medium transition-colors disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
- outline: "border-border text-muted-foreground hover:text-foreground hover:bg-accent",
+ go: "border-signal bg-signal font-semibold text-on-signal hover:bg-[color-mix(in_srgb,var(--signal)_86%,var(--text))]",
+ outline: "border-seam-2 text-text hover:border-muted hover:bg-panel-2",
primary:
- "border-primary text-primary hover:bg-[color-mix(in_srgb,var(--color-primary)_14%,transparent)]",
+ "border-signal text-signal-text hover:bg-[color-mix(in_srgb,var(--signal)_14%,transparent)]",
destructive:
- "border-destructive text-destructive hover:bg-[color-mix(in_srgb,var(--color-destructive)_14%,transparent)]",
- ghost: "border-transparent text-muted-foreground hover:text-foreground hover:bg-accent",
+ "border-reject-text text-reject-text hover:bg-[color-mix(in_srgb,var(--reject)_14%,transparent)]",
+ quiet: "border-transparent text-muted-2 hover:text-text hover:bg-panel-2",
+ ghost: "border-transparent text-muted-2 hover:text-text hover:bg-panel-2",
},
size: {
- sm: "px-2 py-1 text-[11px]",
- md: "px-2.5 py-1 text-[12px]",
- lg: "px-3 py-1.5 text-[13px]",
+ sm: "px-2 py-[3px] text-[11.5px]",
+ md: "px-[11px] py-[5px] text-[12.5px]",
+ lg: "px-3.5 py-1.5 text-[13.5px]",
},
},
defaultVariants: { variant: "outline", size: "md" },
diff --git a/umtool/components/ui/cite-thread.tsx b/umtool/components/ui/cite-thread.tsx
@@ -0,0 +1,46 @@
+import { cn } from "@/lib/utils";
+import { clock } from "./clock";
+
+// Where a cited second sits in its source (canvas `.cthread` / `.pthread`): a
+// hairline the length of the recording, a notch at the cite. Information, not
+// decoration -- a quote at 1:02:14 of a four-hour VOD reads differently from one
+// at 0:00:40 of a clip.
+//
+// On the DESK (a result line) it is one row with "at / of" on the right, and
+// shows on the lit line only (wrap it in `data-lit-only`); on the READER (a
+// pane's header) it carries 0:00, the cite and the end under the line.
+export function CiteThread({
+ at,
+ duration,
+ className,
+}: {
+ /** The cited second. */
+ at: number;
+ /** The recording's length, seconds. */
+ duration: number;
+ className?: string;
+}) {
+ const pct = duration > 0 ? Math.min(100, Math.max(0, (at / duration) * 100)) : 0;
+ const label = `${clock(at)} of ${clock(duration)}`;
+ return (
+ <div className={cn("cite-thread", className)} role="img" aria-label={`Cited at ${label}`} data-cite-at={at}>
+ <i style={{ left: `${pct}%` }} />
+ <span>
+ {clock(at)} / {clock(duration)}
+ </span>
+ </div>
+ );
+}
+
+/** The reader's version: start, cite and end under the line. */
+export function ReaderThread({ at, duration, className }: { at: number; duration: number; className?: string }) {
+ const pct = duration > 0 ? Math.min(100, Math.max(0, (at / duration) * 100)) : 0;
+ return (
+ <div className={cn("cite-thread mt-2.5", className)} role="img" aria-label={`Cited at ${clock(at)} of ${clock(duration)}`} data-cite-at={at}>
+ <i style={{ left: `${pct}%` }} />
+ <span style={{ left: 0 }}>0:00</span>
+ <span style={{ left: `calc(${pct}% - 22px)` }}>{clock(at)}</span>
+ <span style={{ left: "auto", right: 0 }}>{clock(duration)}</span>
+ </div>
+ );
+}
diff --git a/umtool/components/ui/clock.ts b/umtool/components/ui/clock.ts
@@ -0,0 +1,9 @@
+/** Seconds as a timecode: 4973 → "1:22:53", 58 → "0:58". */
+export function clock(s: number): string {
+ const t = Math.max(0, Math.floor(s));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const sec = t % 60;
+ const ss = String(sec).padStart(2, "0");
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+}
diff --git a/umtool/components/ui/dialog.tsx b/umtool/components/ui/dialog.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+// A modal on the NATIVE <dialog>: the browser owns the focus trap, Escape, the
+// top layer and the inert page behind it, so there is nothing here to get
+// wrong. `open` drives showModal()/close(); `onClose` hears every way it closes
+// (Escape, a form with method="dialog", the backdrop is NOT one -- a stray click
+// should not throw away a half-typed reason).
+export function Dialog({
+ open,
+ onClose,
+ title,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"dialog">, "open" | "title"> & {
+ open: boolean;
+ onClose: () => void;
+ title: React.ReactNode;
+}) {
+ const ref = useRef<HTMLDialogElement>(null);
+ useEffect(() => {
+ const d = ref.current;
+ if (!d) return;
+ if (open && !d.open) d.showModal();
+ if (!open && d.open) d.close();
+ }, [open]);
+ return (
+ <dialog
+ ref={ref}
+ onClose={onClose}
+ className={cn(
+ "ui-dialog m-auto w-[min(560px,calc(100vw-32px))] rounded-[3px] border border-seam-2 bg-panel p-0 text-text shadow-2xl",
+ className,
+ )}
+ {...props}
+ >
+ <div className="flex items-baseline gap-3 border-b border-seam px-4 py-3">
+ <h2 className="text-[14px] font-semibold">{title}</h2>
+ <form method="dialog" className="ml-auto">
+ <button type="submit" aria-label="Close" className="px-1 text-muted-2 hover:text-text">
+ ✕
+ </button>
+ </form>
+ </div>
+ <div className="px-4 py-3">{children}</div>
+ </dialog>
+ );
+}
diff --git a/umtool/components/ui/empty-state.tsx b/umtool/components/ui/empty-state.tsx
@@ -0,0 +1,20 @@
+import { cn } from "@/lib/utils";
+
+// Nothing here, said plainly, with the one thing to do about it when there is
+// one. Copy rule: what is absent, literally ("No umtool job running"), never a
+// mood ("All caught up!").
+export function EmptyState({
+ title,
+ action,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"div">, "title"> & { title: React.ReactNode; action?: React.ReactNode }) {
+ return (
+ <div data-empty="" className={cn("py-6 text-center text-[12.5px] text-muted", className)} {...props}>
+ <p className="text-text-2">{title}</p>
+ {children && <div className="mt-1">{children}</div>}
+ {action && <div className="mt-3">{action}</div>}
+ </div>
+ );
+}
diff --git a/umtool/components/ui/field.tsx b/umtool/components/ui/field.tsx
@@ -0,0 +1,51 @@
+import { cn } from "@/lib/utils";
+
+// Form controls on the desk. Server-safe class helpers plus thin elements, so a
+// plain GET form (the /browse/find idiom) stays zero-JS.
+//
+// Field a label over a control, with a hint or an error under it. The
+// error says what to fix ("Slug: letters, digits and dashes only").
+// Input / Select / Textarea one look: panel ground, seam-2 edge, Signal on
+// focus (the global :focus-visible ring).
+
+export const controlClass =
+ "rounded-[3px] border border-seam-2 bg-panel px-2.5 py-[5px] text-[13px] text-text placeholder:text-muted-2 disabled:opacity-50";
+
+export function Field({
+ label,
+ hint,
+ error,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"label">, "title"> & {
+ label: React.ReactNode;
+ hint?: React.ReactNode;
+ error?: React.ReactNode;
+}) {
+ return (
+ <label className={cn("flex flex-col gap-1", className)} {...props}>
+ <span className="text-[12px] font-medium text-text-2">{label}</span>
+ {children}
+ {error ? (
+ <span role="alert" className="text-[12px] text-reject-text">
+ {error}
+ </span>
+ ) : hint ? (
+ <span className="text-[11.5px] text-muted">{hint}</span>
+ ) : null}
+ </label>
+ );
+}
+
+export function Input({ className, ...props }: React.ComponentProps<"input">) {
+ return <input className={cn(controlClass, className)} {...props} />;
+}
+
+export function Select({ className, ...props }: React.ComponentProps<"select">) {
+ return <select className={cn(controlClass, "pr-7", className)} {...props} />;
+}
+
+export function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+ return <textarea className={cn(controlClass, "leading-relaxed", className)} {...props} />;
+}
diff --git a/umtool/components/ui/kbd.tsx b/umtool/components/ui/kbd.tsx
@@ -0,0 +1,19 @@
+import { cn } from "@/lib/utils";
+
+// A key, as the legend under a bench names it. The look is global (kbd in
+// app/globals.css), so a bare <kbd> in old markup matches this.
+export function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
+ return <kbd className={cn(className)} {...props} />;
+}
+
+/** A key and what it does: `<KeyHint keys={["j", "k"]}>cue</KeyHint>`. */
+export function KeyHint({ keys, children }: { keys: string[]; children: React.ReactNode }) {
+ return (
+ <span className="inline-flex items-center gap-1 text-[11.5px] text-muted-2">
+ {keys.map((k) => (
+ <kbd key={k}>{k}</kbd>
+ ))}
+ <span>{children}</span>
+ </span>
+ );
+}
diff --git a/umtool/components/ui/lit-line.tsx b/umtool/components/ui/lit-line.tsx
@@ -0,0 +1,65 @@
+import { cn } from "@/lib/utils";
+
+// The parts of a lit list that need no client JS (lit-list.tsx is the client
+// half): a LINE, a GROUP of lines under a head, and a line's ACTIONS, which show
+// on the lit line. Server components render these straight into a <LitList>.
+
+export function LitLine({
+ id,
+ initial = false,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"div">, "id"> & {
+ /** Announced in the list's `lit` event. */
+ id?: string;
+ /** Lit on load (beats the list's `initial` index). */
+ initial?: boolean;
+}) {
+ return (
+ <div
+ data-lit-line=""
+ data-lit-id={id}
+ data-lit-initial={initial ? "" : undefined}
+ tabIndex={-1}
+ className={cn("lit-line", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+/** A line's actions: shown on the lit line, and on hover or keyboard focus. */
+export function LitActions({ className, ...props }: React.ComponentProps<"div">) {
+ return <div data-lit-act="" className={cn("flex items-center gap-1.5", className)} {...props} />;
+}
+
+/** Only on the lit line (the cite thread: on every row it was a barcode). */
+export function LitOnly({ className, ...props }: React.ComponentProps<"div">) {
+ return <div data-lit-only="" className={className} {...props} />;
+}
+
+export function LitGroup({
+ title,
+ count,
+ note,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"section">, "title"> & {
+ title: React.ReactNode;
+ count?: number | string;
+ note?: React.ReactNode;
+}) {
+ return (
+ <section className={cn("lit-group", className)} {...props}>
+ <div className="lit-group-head">
+ <h3 className="micro">{title}</h3>
+ {count !== undefined && <span className="font-mono text-[11.5px] text-meter">{count}</span>}
+ {note && <span className="ml-auto text-[11.5px] text-muted-2">{note}</span>}
+ </div>
+ {children}
+ </section>
+ );
+}
diff --git a/umtool/components/ui/lit-list.tsx b/umtool/components/ui/lit-list.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import { useCallback, useEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+import { useHydrated } from "./use-hydrated";
+
+// ---------------------------------------------------------------------------
+// THE LIT LINE -- the signature (plans/umtool-redesign.md, "Signature").
+//
+// Every list is a stack of lines; the focused one is LIT: a Signal edge with
+// the play-head notch, ink text, its actions shown. The others sit dim. `j`/`k`
+// (and the arrows) glide the head about 120 ms -- the app's only motion -- and
+// with reduced motion it jumps (--glide is 0 ms then, app/globals.css).
+//
+// Lines are found in the DOM, not passed as data: anything marked
+// `data-lit-line` inside this list is a line, however deep (LitGroup nests them
+// under a head), and the lines themselves can be server-rendered (lit-line.tsx).
+// A line inside ANOTHER list nested in this one belongs to that one.
+//
+// Focus ROVES: the lit line is the one Tab stop into the list, the keys move
+// focus with the light, and Tab from the lit line reaches its own buttons. A
+// click or a focus anywhere on a line lights it.
+//
+// Every button in the list is disabled until hydration (the house rule,
+// components/VerdictChip.tsx) -- a <fieldset disabled> does it for the whole
+// list at once, server-rendered, and lifts on the first client render.
+//
+// `lit` is announced as a DOM event, so a client parent can follow it:
+// el.addEventListener("lit", (e) => e.detail.index, e.detail.id)
+// ---------------------------------------------------------------------------
+
+export type LitDetail = { index: number; id: string | null };
+
+const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
+
+export function LitList({
+ label,
+ initial,
+ global = false,
+ onLight,
+ className,
+ children,
+}: {
+ /** The list's accessible name ("Results", "Decisions"). */
+ label: string;
+ /** The line lit on load, by index; a line marked `initial` wins over it. */
+ initial?: number;
+ /**
+ * `j`/`k` anywhere on the page move this list (when nothing is being typed
+ * in), not only with focus inside it. For the ONE list a page is about.
+ */
+ global?: boolean;
+ onLight?: (d: LitDetail) => void;
+ className?: string;
+ children: React.ReactNode;
+}) {
+ const hydrated = useHydrated();
+ const ref = useRef<HTMLDivElement>(null);
+ const head = useRef<HTMLElement>(null);
+ const lit = useRef(-1);
+ const onLightRef = useRef(onLight);
+ onLightRef.current = onLight;
+
+ const lines = useCallback((): HTMLElement[] => {
+ const root = ref.current;
+ if (!root) return [];
+ return [...root.querySelectorAll<HTMLElement>("[data-lit-line]")].filter(
+ (el) => el.closest("[data-lit-list]") === root,
+ );
+ }, []);
+
+ const place = useCallback(() => {
+ const root = ref.current;
+ const h = head.current;
+ if (!root || !h) return;
+ const el = lines()[lit.current];
+ if (!el) {
+ h.setAttribute("data-off", "");
+ return;
+ }
+ const r = el.getBoundingClientRect();
+ const base = root.getBoundingClientRect();
+ h.removeAttribute("data-off");
+ h.style.top = `${r.top - base.top}px`;
+ h.style.height = `${r.height}px`;
+ // The first placement must not glide in from the top of the list.
+ if (!h.hasAttribute("data-placed")) requestAnimationFrame(() => h.setAttribute("data-placed", ""));
+ }, [lines]);
+
+ const light = useCallback(
+ (i: number, opts: { focus?: boolean } = {}) => {
+ const all = lines();
+ if (!all.length) return;
+ const n = Math.max(0, Math.min(all.length - 1, i));
+ all.forEach((el, k) => {
+ if (k === n) el.setAttribute("data-lit", "");
+ else el.removeAttribute("data-lit");
+ el.tabIndex = k === n ? 0 : -1;
+ });
+ const el = all[n];
+ const changed = lit.current !== n;
+ lit.current = n;
+ place();
+ if (opts.focus) {
+ el.focus({ preventScroll: true });
+ el.scrollIntoView({ block: "nearest" });
+ }
+ if (changed) {
+ const detail: LitDetail = { index: n, id: el.dataset.litId ?? null };
+ ref.current?.dispatchEvent(new CustomEvent<LitDetail>("lit", { detail }));
+ onLightRef.current?.(detail);
+ }
+ },
+ [lines, place],
+ );
+
+ // Light the first line once the list is live, and follow its size.
+ useEffect(() => {
+ const root = ref.current;
+ if (!root) return;
+ const all = lines();
+ const marked = all.findIndex((el) => el.hasAttribute("data-lit-initial"));
+ light(marked >= 0 ? marked : (initial ?? 0));
+ const ro = new ResizeObserver(() => place());
+ ro.observe(root);
+ window.addEventListener("resize", place);
+ void document.fonts?.ready.then(place);
+ return () => {
+ ro.disconnect();
+ window.removeEventListener("resize", place);
+ };
+ // `initial` is read once: after that the operator owns the light.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [lines, light, place]);
+
+ const step = useCallback(
+ (e: KeyboardEvent | React.KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return false;
+ const t = e.target as HTMLElement | null;
+ if (t?.closest?.(TYPING)) return false;
+ const k = e.key;
+ const last = lines().length - 1;
+ const to =
+ k === "j" || k === "ArrowDown"
+ ? lit.current + 1
+ : k === "k" || k === "ArrowUp"
+ ? lit.current - 1
+ : k === "Home"
+ ? 0
+ : k === "End"
+ ? last
+ : null;
+ if (to === null || last < 0) return false;
+ e.preventDefault();
+ light(to, { focus: true });
+ return true;
+ },
+ [light, lines],
+ );
+
+ // A page's ONE list can take j/k from anywhere that is not typing.
+ useEffect(() => {
+ if (!global) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
+ const inOther = (e.target as HTMLElement | null)?.closest?.("[data-lit-list]");
+ if (inOther && inOther !== ref.current) return;
+ if (e.key !== "j" && e.key !== "k") return;
+ step(e);
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [global, step]);
+
+ const fromEvent = (target: EventTarget | null) => {
+ const el = (target as HTMLElement | null)?.closest?.<HTMLElement>("[data-lit-line]");
+ if (!el || el.closest("[data-lit-list]") !== ref.current) return -1;
+ return lines().indexOf(el);
+ };
+
+ return (
+ <div
+ ref={ref}
+ data-lit-list=""
+ data-hydrated={hydrated ? "" : undefined}
+ aria-label={label}
+ role="group"
+ className={cn("lit-list", className)}
+ onKeyDown={(e) => {
+ if (!global || (e.key !== "j" && e.key !== "k")) step(e);
+ }}
+ onClick={(e) => {
+ const i = fromEvent(e.target);
+ if (i >= 0 && i !== lit.current) light(i);
+ }}
+ onFocus={(e) => {
+ const i = fromEvent(e.target);
+ if (i >= 0 && i !== lit.current) light(i);
+ }}
+ >
+ <i ref={head} className="lit-head" data-off="" aria-hidden="true" />
+ <fieldset disabled={!hydrated} className="m-0 min-w-0 border-0 p-0">
+ {children}
+ </fieldset>
+ </div>
+ );
+}
diff --git a/umtool/components/ui/panel.tsx b/umtool/components/ui/panel.tsx
@@ -0,0 +1,49 @@
+import { cn } from "@/lib/utils";
+
+// The desk's two boxes (canvas `.block`, `.nextcard`). Server-safe.
+//
+// Panel a titled region of a page: a micro title, an optional aside on the
+// right of it (a count, an "all →" link), and the body.
+// Card one thing to act on, raised off the panel. `lit` gives it the
+// Signal edge -- the Next card, the one thing to do here.
+
+export function Panel({
+ title,
+ aside,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"section">, "title"> & { title?: React.ReactNode; aside?: React.ReactNode }) {
+ return (
+ <section className={cn("rounded-[3px] border border-seam bg-panel px-4 py-3", className)} {...props}>
+ {(title || aside) && (
+ <div className="mb-2 flex items-baseline gap-3">
+ {title && <h2 className="micro">{title}</h2>}
+ {aside && <div className="ml-auto text-[12px]">{aside}</div>}
+ </div>
+ )}
+ {children}
+ </section>
+ );
+}
+
+export function Card({
+ lit = false,
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & { lit?: boolean }) {
+ return (
+ <div
+ className={cn(
+ "relative rounded-[3px] border border-seam-2 bg-panel px-4 py-3",
+ lit &&
+ "before:absolute before:-left-px before:-top-px before:-bottom-px before:w-[3px] before:rounded-l-[3px] before:bg-signal before:content-['']",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/umtool/components/ui/reader-pane.tsx b/umtool/components/ui/reader-pane.tsx
@@ -0,0 +1,114 @@
+import { cva } from "class-variance-authority";
+import { cn } from "@/lib/utils";
+import { ReaderThread } from "./cite-thread";
+import { clock } from "./clock";
+import { LitList } from "./lit-list";
+import { LitLine } from "./lit-line";
+
+// ---------------------------------------------------------------------------
+// THE READER (canvas `.paper`): anything a SOURCE said -- a transcript window,
+// a quote, a post -- on the pale microfilm surface, apart from the desk. Paper
+// is the record; ink is our work. Wherever something cited is focused (Inbox,
+// Research, an article, the claim bench) it is this component.
+//
+// header the source's title; channel · date · track; the cite thread
+// (start, the cite, the end) when the cite and the length are known
+// body the cues as a lit list, the cited cue lit; `»` marks a change of
+// speaker when the transcript knows one
+// footer the actions (paperButtonVariants), and a fine line (the citation)
+//
+// Rules from the canvas critique: no verdict colour on the reader, ever; the
+// reader's own Signal is `--reader-signal`, a teal dark enough for the paper.
+// ---------------------------------------------------------------------------
+
+export type Cue = { t: number; text: React.ReactNode; turn?: boolean; lit?: boolean; id?: string };
+
+export const paperButtonVariants = cva(
+ "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border px-[11px] py-[5px] text-[12.5px] font-medium transition-colors disabled:pointer-events-none disabled:opacity-50",
+ {
+ variants: {
+ variant: {
+ outline: "border-reader-2 text-reader-ink hover:border-reader-ink",
+ go: "border-reader-signal bg-reader-signal font-semibold text-white",
+ },
+ },
+ defaultVariants: { variant: "outline" },
+ },
+);
+
+export function ReaderPane({
+ source,
+ byline,
+ cite,
+ note,
+ cues,
+ label = "Transcript",
+ footer,
+ fine,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"aside">, "children"> & {
+ /** The source's title. */
+ source: React.ReactNode;
+ /** channel · date · track, as nodes; joined with a middle dot. */
+ byline?: React.ReactNode[];
+ /** The cited second and the recording's length, for the thread. */
+ cite?: { at: number; duration: number };
+ /** A line under the header ("Speaker not identified"). */
+ note?: React.ReactNode;
+ cues?: Cue[];
+ label?: string;
+ footer?: React.ReactNode;
+ /** The fine print under the actions: the citation in the house format. */
+ fine?: React.ReactNode;
+ /** Instead of cues: anything else the source said (a post, a quote). */
+ children?: React.ReactNode;
+}) {
+ const parts = (byline ?? []).filter(Boolean);
+ return (
+ <aside aria-label="Reader" data-reader="" className={cn("reader", className)} {...props}>
+ <div className="border-b border-reader-seam px-[22px] pb-3 pt-4">
+ <div className="text-[13px] font-semibold leading-snug">{source}</div>
+ {parts.length > 0 && (
+ <div className="mt-[3px] text-[12px] text-reader-dim">
+ {parts.map((p, i) => (
+ <span key={i}>
+ {i > 0 && " · "}
+ {p}
+ </span>
+ ))}
+ </div>
+ )}
+ {cite && <ReaderThread at={cite.at} duration={cite.duration} />}
+ </div>
+ {note && <div className="px-[22px] pt-2 text-[11.5px] text-reader-dim">{note}</div>}
+ <div className="min-h-0 flex-1 overflow-auto py-2 pr-2.5">
+ {cues ? (
+ <LitList label={label}>
+ {cues.map((c, i) => (
+ <LitLine
+ key={c.id ?? `${c.t}-${i}`}
+ id={c.id}
+ initial={c.lit}
+ className="reader-cue"
+ data-turn={c.turn ? "" : undefined}
+ >
+ <span className="reader-t">{clock(c.t)}</span>
+ <p>{c.text}</p>
+ </LitLine>
+ ))}
+ </LitList>
+ ) : (
+ <div className="reader-text px-[22px]">{children}</div>
+ )}
+ </div>
+ {(footer || fine) && (
+ <div className="flex flex-wrap items-center gap-2 border-t border-reader-seam px-[22px] pb-3.5 pt-3">
+ {footer}
+ {fine && <span className="basis-full font-mono text-[11px] text-reader-dim">{fine}</span>}
+ </div>
+ )}
+ </aside>
+ );
+}
diff --git a/umtool/components/ui/stepper.tsx b/umtool/components/ui/stepper.tsx
@@ -0,0 +1,31 @@
+import { cn } from "@/lib/utils";
+
+// The stage stepper (canvas `.stepper`): Research → Article → Video → Deliver.
+// Done stages are ink, the current one Signal, the rest seams. Information, not
+// navigation: it says where a piece is, and the page's tabs take you there.
+export type Step = { label: string; state: "done" | "current" | "todo" };
+
+export function Stepper({ steps, className, ...props }: React.ComponentProps<"ol"> & { steps: Step[] }) {
+ return (
+ <ol className={cn("flex flex-wrap items-center", className)} aria-label="Stage" {...props}>
+ {steps.map((s, i) => (
+ <li key={s.label} data-step={s.state} className="flex items-center" aria-current={s.state === "current" ? "step" : undefined}>
+ {i > 0 && (
+ <span aria-hidden="true" className={cn("mx-2.5 h-px w-10", s.state === "todo" ? "bg-seam-2" : "bg-text-2")} />
+ )}
+ <span
+ className={cn(
+ "flex items-center gap-[7px] text-[12.5px]",
+ s.state === "done" && "text-text-2",
+ s.state === "current" && "font-semibold text-text",
+ s.state === "todo" && "text-muted-2",
+ )}
+ >
+ <i className="stepper-dot" aria-hidden="true" />
+ {s.label}
+ </span>
+ </li>
+ ))}
+ </ol>
+ );
+}
diff --git a/umtool/components/ui/table.tsx b/umtool/components/ui/table.tsx
@@ -0,0 +1,33 @@
+import { cn } from "@/lib/utils";
+
+// A data table on the desk (canvas `.itab`): hairline rows, micro heads, mono
+// for anything that is a number. Plain elements with the look attached, so a
+// server page builds one with no client JS.
+export function Table({ className, ...props }: React.ComponentProps<"table">) {
+ return (
+ <div className="overflow-x-auto">
+ <table className={cn("w-full border-collapse text-[12.5px]", className)} {...props} />
+ </div>
+ );
+}
+
+export function TH({ className, ...props }: React.ComponentProps<"th">) {
+ return (
+ <th
+ className={cn(
+ "border-b border-seam px-1.5 py-[7px] text-left text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export function TD({ className, numeric = false, ...props }: React.ComponentProps<"td"> & { numeric?: boolean }) {
+ return (
+ <td
+ className={cn("border-b border-seam px-1.5 py-[7px] align-top text-text-2", numeric && "font-mono text-[12px] text-right", className)}
+ {...props}
+ />
+ );
+}
diff --git a/umtool/components/ui/tabs.tsx b/umtool/components/ui/tabs.tsx
@@ -0,0 +1,35 @@
+import Link from "next/link";
+import { cn } from "@/lib/utils";
+
+// Tabs that are LINKS (canvas `.tabs`): each tab is an address, so a tab is
+// bookmarkable, the back button works, and a server page renders the right one
+// with no client state. The current one carries `aria-current="page"` and the
+// Signal underline; a count sits beside its label in Meter.
+export type TabItem = { href: string; label: React.ReactNode; current?: boolean; count?: number | string; testid?: string };
+
+export function Tabs({
+ items,
+ label,
+ className,
+ ...props
+}: React.ComponentProps<"nav"> & { items: TabItem[]; label: string }) {
+ return (
+ <nav aria-label={label} className={cn("flex flex-wrap gap-0.5 border-b border-seam", className)} {...props}>
+ {items.map((t) => (
+ <Link
+ key={t.href}
+ href={t.href}
+ data-testid={t.testid}
+ aria-current={t.current ? "page" : undefined}
+ className={cn(
+ "-mb-px border-b-2 px-3 pb-2 pt-2.5 text-[13px] no-underline",
+ t.current ? "border-signal text-text" : "border-transparent text-muted-2 hover:text-text",
+ )}
+ >
+ {t.label}
+ {t.count !== undefined && <span className="ml-1.5 font-mono text-[11px] text-meter">{t.count}</span>}
+ </Link>
+ ))}
+ </nav>
+ );
+}
diff --git a/umtool/components/ui/toolbar.tsx b/umtool/components/ui/toolbar.tsx
@@ -0,0 +1,27 @@
+import { cn } from "@/lib/utils";
+
+// A row of controls over a list: filters left, actions right (canvas
+// `.facetbar`). `ToolbarGroup` is one labelled cluster ("Stage", "Kind").
+export function Toolbar({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ role="toolbar"
+ className={cn("flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-seam px-4 py-2.5", className)}
+ {...props}
+ />
+ );
+}
+
+export function ToolbarGroup({
+ label,
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & { label?: React.ReactNode }) {
+ return (
+ <div className={cn("flex flex-wrap items-center gap-1", className)} {...props}>
+ {label && <span className="micro mr-1">{label}</span>}
+ {children}
+ </div>
+ );
+}
diff --git a/umtool/components/ui/use-hydrated.ts b/umtool/components/ui/use-hydrated.ts
@@ -0,0 +1,17 @@
+"use client";
+
+import { useSyncExternalStore } from "react";
+
+// FALSE on the server and through hydration, TRUE from the first client render
+// after it. The house rule (components/VerdictChip.tsx): a button is disabled
+// until this is true, because a click that lands before React hydrates fires
+// nothing at all -- no request, no error -- and an action lost that way looks
+// like one never taken.
+const subscribe = () => () => {};
+export function useHydrated(): boolean {
+ return useSyncExternalStore(
+ subscribe,
+ () => true,
+ () => false,
+ );
+}
diff --git a/umtool/components/ui/use-palette.ts b/umtool/components/ui/use-palette.ts
@@ -0,0 +1,91 @@
+"use client";
+
+import { useSyncExternalStore } from "react";
+
+// The role tokens (app/globals.css) as hex strings, for what CSS cannot reach:
+// a <canvas> (the waveform, the mix lanes, the pitch rail) paints with
+// fillStyle, which takes a colour, not var(--panel).
+//
+// It follows the theme: an explicit choice (data-theme on <html>, set by the
+// rail's control) and the system's preference both re-read it, so a canvas that
+// lists the palette in its draw effect's deps repaints on the switch. Values
+// are read from the computed style -- the stylesheet stays the one source --
+// and the server, and hydration, see the dark base (a canvas paints only in an
+// effect, after it).
+export const ROLES = [
+ "ground",
+ "panel",
+ "panel-2",
+ "seam",
+ "seam-2",
+ "text",
+ "text-2",
+ "muted",
+ "muted-2",
+ "signal",
+ "meter",
+ "kept",
+ "doubt",
+ "reject",
+] as const;
+export type Role = (typeof ROLES)[number];
+export type Palette = Record<Role, string>;
+
+// The dark base, as app/globals.css declares it.
+const DARK: Palette = {
+ ground: "#0c0a08",
+ panel: "#17140f",
+ "panel-2": "#201b15",
+ seam: "#2b251d",
+ "seam-2": "#3d3429",
+ text: "#ece4d6",
+ "text-2": "#c9bfae",
+ muted: "#9a8f7e",
+ "muted-2": "#8a8070",
+ signal: "#3fc1b0",
+ meter: "#b9a2ec",
+ kept: "#c6e283",
+ doubt: "#ef9a2a",
+ reject: "#de4c3c",
+};
+
+let cacheKey = "";
+let cache: Palette = DARK;
+
+function read(): Palette {
+ const root = document.documentElement;
+ const key = `${root.dataset.theme ?? ""}|${matchMedia("(prefers-color-scheme: light)").matches}`;
+ if (key === cacheKey) return cache;
+ const cs = getComputedStyle(root);
+ const next = { ...DARK };
+ for (const r of ROLES) {
+ const v = cs.getPropertyValue(`--${r}`).trim();
+ if (v) next[r] = v;
+ }
+ cacheKey = key;
+ cache = next;
+ return cache;
+}
+
+function subscribe(onChange: () => void) {
+ const mo = new MutationObserver(onChange);
+ mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
+ const mq = matchMedia("(prefers-color-scheme: light)");
+ mq.addEventListener("change", onChange);
+ return () => {
+ mo.disconnect();
+ mq.removeEventListener("change", onChange);
+ };
+}
+
+export function usePalette(): Palette {
+ return useSyncExternalStore(subscribe, read, () => DARK);
+}
+
+/** `#rrggbb` at an alpha, for a canvas: alpha("#3fc1b0", 0.1). */
+export function alpha(hex: string, a: number): string {
+ const h = hex.replace("#", "");
+ const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h.slice(0, 6);
+ const n = parseInt(full, 16);
+ return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
+}
diff --git a/umtool/components/ui/verdict.tsx b/umtool/components/ui/verdict.tsx
@@ -0,0 +1,22 @@
+import { cn } from "@/lib/utils";
+
+// A judgement: glyph AND word, never colour alone (canvas `.v`). The glyph
+// carries the verdict colour; the word takes its text step, which in light is
+// darker than the glyph (app/globals.css, "COLOUR MEANS SOMETHING").
+//
+// Desk only. A verdict never sits on the reader: the record carries no
+// judgement, and on the pale surface the hues collapse for colour-blind eyes.
+export type VerdictKind = "kept" | "doubt" | "reject";
+
+export function Verdict({
+ kind,
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"span"> & { kind: VerdictKind }) {
+ return (
+ <span data-verdict={kind} className={cn("verdict", className)} {...props}>
+ {children}
+ </span>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -20,6 +20,7 @@ decisions inbox cannot disagree about what is wrong with one.
| `show <project> [--json]` | one project: summary, the cut, per-clip status, decisions |
| `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) |
| `decisions [--json]` | the inbox |
+| `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx |
| `folders [--json]` · `kinds [--json]` | the tree, the registry |
| `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
diff --git a/umtool/e2e/inbox-engine.spec.ts b/umtool/e2e/inbox-engine.spec.ts
@@ -0,0 +1,157 @@
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { warm, WARM_TIMEOUT } from "./warm";
+
+// The inbox engine (plans/umtool-redesign.md, P2a): GET /api/browse/decisions
+// keeps one row per decision and adds the inbox's fields; the generation era's
+// decisions come from disk; a parked piece's decisions are hidden, never
+// dropped; POST /api/pieces/lifecycle round-trips. Over the fixture's article in
+// the making, zeta (e2e/fixtures/iterations-fixture.mjs): i1 and i2 done with
+// reports, i3 a video revision, i4 failed -- and no current.json.
+//
+// WRITES the fixture's REPORTS_ROOT/.umtool/lifecycle.json (zeta parked, then
+// active again) and a note on articles/zeta, deleted before the test ends.
+
+type Row = {
+ kind: string;
+ project: string;
+ projectKind?: string;
+ target: string;
+ href: string;
+ severity: "blocking" | "open" | "info";
+ piece?: string;
+ category?: string;
+ group?: string;
+ action?: { label: string; href: string };
+ lifecycle?: "active" | "parked" | "done";
+ hidden?: boolean;
+};
+type Group = { id: string; label: string; decisions: number; hidden: number; cards: { piece: string | null; kind: string; count: number }[] };
+type Inbox = { items: Row[]; projects: number; counts: Record<string, number>; groups: Group[]; hidden: number };
+
+const ZETA = "a:articles/zeta";
+
+const inbox = async (request: APIRequestContext): Promise<Inbox> => {
+ const r = await request.get("/api/browse/decisions");
+ expect(r.ok()).toBe(true);
+ return r.json();
+};
+const lifecycle = (request: APIRequestContext, piece: unknown, state: unknown) => request.post("/api/pieces/lifecycle", { data: { piece, state } });
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, ["/api/browse/decisions", "/api/pieces", "/api/notes?article=articles/zeta"]);
+});
+
+test.afterAll(async ({ request }) => {
+ await lifecycle(request, ZETA, "active");
+});
+
+test("one row per decision, each with the inbox's fields; the counts add up", async ({ request }) => {
+ const { items, counts, groups, hidden } = await inbox(request);
+ expect(items.length).toBeGreaterThan(0);
+ expect(counts.blocking + counts.open + counts.info).toBe(items.length);
+ expect(groups.reduce((n, g) => n + g.decisions + g.hidden, 0)).toBe(items.length);
+ expect(hidden).toBe(items.filter((d) => d.hidden).length);
+ expect(groups.map((g) => g.id)).toEqual(["your-call", "review", "blocking", "notes", "open", "ready-to-finish", "quiet"]);
+ for (const d of items) {
+ expect(d.piece, `${d.kind} ${d.project}`).toMatch(/^[ap]:/);
+ expect(d.group).toBeTruthy();
+ expect(d.category).toBeTruthy();
+ expect(d.lifecycle).toBeTruthy();
+ expect(typeof d.hidden).toBe("boolean");
+ expect(d.action?.label).toBeTruthy();
+ expect(d.action?.href).toBe(d.href);
+ }
+ // The rows openDecisions() always made are still there, project ids intact.
+ expect(items.some((d) => d.kind === "shadowed-name" && d.project === "find")).toBe(true);
+});
+
+test("the generation era's decisions come from disk", async ({ request }) => {
+ const { items } = await inbox(request);
+ const zeta = items.filter((d) => d.piece === ZETA);
+ const of = (kind: string) => zeta.filter((d) => d.kind === kind).map((d) => d.target).sort();
+ // No current.json: every done iteration that could be current is ready.
+ expect(of("iteration-ready")).toEqual(["i1", "i2", "i3"]);
+ expect(of("iteration-failed")).toEqual(["i4"]);
+ const failed = zeta.find((d) => d.kind === "iteration-failed")!;
+ expect(failed.group).toBe("your-call");
+ expect(failed.category).toBe("spend");
+ expect(failed.project).toBe("sites/articles/zeta");
+ expect(failed.projectKind).toBe("article");
+ expect(failed.href).toBe("/articles/zeta?tab=iterations");
+ const ready = zeta.find((d) => d.kind === "iteration-ready" && d.target === "i1")!;
+ expect(ready.group).toBe("review");
+ expect(ready.action?.label).toBe("Make i1 current");
+ // The project zeta's iterations made belongs to zeta's piece (linked by its
+ // iteration, not by slug), so its manifest decisions do too.
+ expect(items.some((d) => d.project === "gen-projects/zeta/i1" && d.piece === ZETA)).toBe(true);
+ // A published article with its video looks done: a suggestion, not a state.
+ const done = items.find((d) => d.kind === "looks-done" && d.piece === "a:priv/polemic-alpha");
+ expect(done?.group).toBe("ready-to-finish");
+ expect(done?.lifecycle).toBe("active");
+});
+
+test("a parked piece's decisions are hidden, never dropped; active again shows them", async ({ request }) => {
+ // A note on zeta, so the MCP's contract is checked on a hidden row too.
+ const add = await request.post("/api/notes?article=articles/zeta", { data: { op: { op: "add", text: "Inbox engine.", anchor: { kind: "whole" } } } });
+ expect(add.status()).toBe(200);
+ const noteId = (await add.json()).note.id as string;
+ try {
+ const before = await inbox(request);
+ const zetaRows = before.items.filter((d) => d.piece === ZETA);
+ expect(zetaRows.length).toBeGreaterThan(5);
+ expect(zetaRows.every((d) => !d.hidden && d.lifecycle === "active")).toBe(true);
+
+ const park = await lifecycle(request, ZETA, "parked");
+ expect(park.status()).toBe(200);
+ expect(await park.json()).toMatchObject({ piece: ZETA, state: "parked", by: "operator" });
+
+ const after = await inbox(request);
+ expect(after.items.length).toBe(before.items.length);
+ const parked = after.items.filter((d) => d.piece === ZETA);
+ expect(parked.length).toBe(zetaRows.length);
+ expect(parked.every((d) => d.hidden && d.lifecycle === "parked")).toBe(true);
+ expect(after.hidden).toBe(before.hidden + zetaRows.length);
+ // Hidden rows are counted per group and left out of the cards.
+ expect(after.groups.flatMap((g) => g.cards).some((c) => c.piece === ZETA)).toBe(false);
+ // The note row keeps the MCP's contract: project is the notes target, href ends in note=<id>.
+ const note = after.items.find((d) => d.kind === "open-note" && d.piece === ZETA)!;
+ expect(note.project).toBe("sites/articles/zeta");
+ expect(note.href.endsWith(`note=${noteId}`)).toBe(true);
+ expect(note.action?.href.endsWith(`note=${noteId}`)).toBe(true);
+
+ const pieces = await (await request.get("/api/pieces")).json();
+ const z = pieces.pieces.find((p: { id: string }) => p.id === ZETA);
+ expect(z).toMatchObject({ kind: "article", site: "articles", report: "zeta", status: "in the making", stage: "research", lifecycle: "parked", lifecycleBy: "operator" });
+ expect(z.projects.map((p: { id: string; via: string }) => `${p.id}:${p.via}`).sort()).toEqual(["gen-projects/zeta/i1:iteration", "gen-projects/zeta/i3:iteration"]);
+ expect(z.decisions.hidden).toBe(zetaRows.length);
+
+ expect((await lifecycle(request, ZETA, "active")).status()).toBe(200);
+ const again = await inbox(request);
+ expect(again.items.filter((d) => d.piece === ZETA).every((d) => !d.hidden && d.lifecycle === "active")).toBe(true);
+ } finally {
+ await request.post("/api/notes?article=articles/zeta", { data: { op: { op: "delete", id: noteId } } });
+ }
+});
+
+test("POST /api/pieces/lifecycle refuses junk", async ({ request }) => {
+ for (const [piece, state, status] of [
+ ["articles/zeta", "parked", 400], // no namespace: ambiguous, refused
+ ["a:articles/zeta/extra", "parked", 400],
+ ["p:../etc", "parked", 400],
+ [ZETA, "shipped", 400],
+ [ZETA, null, 400],
+ [null, "parked", 400],
+ ["a:articles/no-such-article", "parked", 404],
+ ["p:no/such/project", "done", 404],
+ ["c:some-case", "parked", 404],
+ // A project zeta's iterations made is part of zeta's piece.
+ ["p:gen-projects/zeta/i1", "parked", 404],
+ ] as const) {
+ const r = await lifecycle(request, piece, state);
+ expect(r.status(), `${piece} ${state}`).toBe(status);
+ expect((await r.json()).error).toBeTruthy();
+ }
+ const r = await request.post("/api/pieces/lifecycle", { data: "not json", headers: { "content-type": "text/plain" } });
+ expect(r.status()).toBe(400);
+});
diff --git a/umtool/e2e/shell.spec.ts b/umtool/e2e/shell.spec.ts
@@ -0,0 +1,129 @@
+import { test, expect, type Page } from "@playwright/test";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The shell (plans/umtool-redesign.md, P1): the rail on every page, the place
+// you are in lit, a bench without it, the theme choice surviving a reload in
+// both directions, and the lit line's keys and motion.
+// ---------------------------------------------------------------------------
+
+const rail = (page: Page) => page.locator("[data-app-rail]");
+const place = (page: Page, name: string) =>
+ rail(page).getByRole("navigation", { name: "Main" }).getByRole("link", { name, exact: true });
+
+// Every top-level page today, and the rail entry it lights.
+const PLACES: { url: string; lit: string }[] = [
+ { url: urls.homeHref(), lit: "home" },
+ { url: urls.browseHref(), lit: "browse" },
+ { url: urls.decisionsHref(), lit: "decisions" },
+ { url: urls.articlesHref(), lit: "articles" },
+ { url: urls.sitesHref(), lit: "articles" },
+ { url: urls.mixHref(), lit: "mix" },
+ { url: urls.findHref(), lit: "find" },
+];
+
+for (const { url, lit } of PLACES) {
+ test(`${url} has the rail, with ${lit} lit`, async ({ page }) => {
+ const res = await page.goto(url);
+ expect(res?.status()).toBe(200);
+ await expect(rail(page)).toBeVisible();
+ await expect(place(page, lit)).toHaveAttribute("aria-current", "page");
+ // Exactly one place is lit.
+ await expect(rail(page).locator("nav[aria-label=Main] > a[aria-current=page]")).toHaveCount(1);
+ // The page head: one Breadcrumb nav, the page's name its h1.
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveCount(1);
+ });
+}
+
+test("a song pile lights the song group, and its menu opens in the rail", async ({ page }) => {
+ await page.goto(urls.pileHref("sort"));
+ const group = rail(page).locator("[data-nav-group=song]");
+ await expect(group.getByRole("button")).toHaveAttribute("aria-current", "page");
+ await expect(rail(page).locator("nav[aria-label=Main] > a[aria-current=page]")).toHaveCount(0);
+ await group.getByRole("button").click();
+ await expect(group.getByRole("menuitem", { name: "sort", exact: true })).toHaveAttribute("aria-current", "page");
+});
+
+test("a bench collapses the rail; its head still links home", async ({ page }) => {
+ await page.goto(urls.clipBenchHref("reports/report-fixture", "c01"));
+ await expect(page.locator("[data-app-header=bench]")).toBeVisible();
+ await expect(rail(page)).toHaveCount(0);
+ await expect(page.locator("[data-app-header=bench]").getByRole("link", { name: "umtool home" })).toHaveAttribute("href", "/");
+});
+
+test("the theme choice is a cookie the server stamps on <html>, both ways", async ({ page, context }) => {
+ const themeCookie = async () => (await context.cookies()).find((c) => c.name === "umtool-theme")?.value ?? null;
+ const control = (page: Page) => rail(page).getByRole("group", { name: "Theme" });
+
+ await page.goto(urls.homeHref());
+ await expect(page.locator("html")).not.toHaveAttribute("data-theme", /.+/);
+ await expect(control(page).getByRole("button", { name: "Auto" })).toHaveAttribute("aria-pressed", "true");
+
+ // Light: stamped at once, and served stamped after a reload.
+ await control(page).getByRole("button", { name: "Light" }).click();
+ await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
+ expect(await themeCookie()).toBe("light");
+ let html = await (await page.request.get(urls.browseHref())).text();
+ expect(html).toMatch(/<html[^>]*data-theme="light"/);
+ await page.reload();
+ await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
+ await expect(control(page).getByRole("button", { name: "Light" })).toHaveAttribute("aria-pressed", "true");
+
+ // Dark wins over a light system too: the explicit choice goes both ways.
+ await page.emulateMedia({ colorScheme: "light" });
+ await control(page).getByRole("button", { name: "Dark" }).click();
+ await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
+ expect(await themeCookie()).toBe("dark");
+ await page.reload();
+ await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
+ const ground = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--ground").trim());
+ expect(ground).toBe("#0c0a08");
+
+ // Auto: the cookie goes, the attribute goes, and the system decides again.
+ await control(page).getByRole("button", { name: "Auto" }).click();
+ await expect(page.locator("html")).not.toHaveAttribute("data-theme", /.+/);
+ expect(await themeCookie()).toBeNull();
+ await page.reload();
+ await expect(page.locator("html")).not.toHaveAttribute("data-theme", /.+/);
+ const lightGround = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--ground").trim());
+ expect(lightGround).toBe("#f1efec");
+ html = await (await page.request.get(urls.browseHref())).text();
+ expect(html).not.toMatch(/<html[^>]*data-theme=/);
+});
+
+test("j and k move the lit line, and focus goes with it", async ({ page }) => {
+ await page.goto(urls.decisionsHref());
+ const list = page.locator("[data-lit-list]").first();
+ await expect(list).toHaveAttribute("data-hydrated", "");
+ const lines = list.locator("[data-lit-line]");
+ expect(await lines.count()).toBeGreaterThan(2);
+ await expect(lines.nth(0)).toHaveAttribute("data-lit", "");
+ // From anywhere on the page: the decision list is the page's one list.
+ await page.locator("body").press("j");
+ await expect(lines.nth(1)).toHaveAttribute("data-lit", "");
+ await expect(lines.nth(0)).not.toHaveAttribute("data-lit", "");
+ await expect(lines.nth(1)).toBeFocused();
+ await page.keyboard.press("j");
+ await expect(lines.nth(2)).toHaveAttribute("data-lit", "");
+ await page.keyboard.press("k");
+ await expect(lines.nth(1)).toHaveAttribute("data-lit", "");
+ // Exactly one line is lit, and it is the one Tab stop into the list.
+ await expect(list.locator("[data-lit-line][data-lit]")).toHaveCount(1);
+ await expect(lines.nth(1)).toHaveAttribute("tabindex", "0");
+ await expect(lines.nth(0)).toHaveAttribute("tabindex", "-1");
+ // The head sits on the lit line.
+ const line = await lines.nth(1).boundingBox();
+ await expect.poll(async () => Math.round((await list.locator(".lit-head").boundingBox())?.y ?? -1)).toBe(Math.round(line!.y));
+});
+
+test("the head glides, and does not under reduced motion", async ({ page }) => {
+ const duration = () =>
+ page.locator("[data-lit-list] .lit-head").first().evaluate((el) => getComputedStyle(el).transitionDuration);
+ await page.goto(urls.decisionsHref());
+ await expect(page.locator("[data-lit-list] .lit-head[data-placed]").first()).toBeAttached();
+ expect(await duration()).toMatch(/^0\.12s/);
+ await page.emulateMedia({ reducedMotion: "reduce" });
+ await page.reload();
+ await expect(page.locator("[data-lit-list] .lit-head[data-placed]").first()).toBeAttached();
+ expect(await duration()).toMatch(/^0s/);
+});
diff --git a/umtool/e2e/urls.ts b/umtool/e2e/urls.ts
@@ -0,0 +1,11 @@
+// The page addresses a spec opens, from the same table the app links with.
+//
+// A spec that writes `page.goto("/browse/" + id)` by hand pins today's URL; one
+// that writes `page.goto(urls.projectHref(id))` follows the app when P3 moves
+// /browse to /projects. Old addresses keep working through redirects.mjs either
+// way -- this is so a spec states WHERE it means to be, not where that was.
+//
+// Assertions on hrefs (`toHaveAttribute("href", …)`) should build the expected
+// value here too, so a URL change is one edit in lib/hrefs.ts.
+export * from "../lib/hrefs";
+export { REDIRECTS } from "../redirects.mjs";
diff --git a/umtool/fonts/ibm-plex-mono/IBMPlexMono-Medium.ttf b/umtool/fonts/ibm-plex-mono/IBMPlexMono-Medium.ttf
Binary files differ.
diff --git a/umtool/fonts/ibm-plex-mono/OFL.txt b/umtool/fonts/ibm-plex-mono/OFL.txt
@@ -0,0 +1,93 @@
+Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/umtool/fonts/source-serif-4/OFL.txt b/umtool/fonts/source-serif-4/OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2014 - 2023 Adobe (http://www.adobe.com/), with Reserved Font Name ‘Source’. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/umtool/fonts/source-serif-4/SourceSerif4Variable-Italic.ttf b/umtool/fonts/source-serif-4/SourceSerif4Variable-Italic.ttf
Binary files differ.
diff --git a/umtool/fonts/source-serif-4/SourceSerif4Variable-Roman.ttf b/umtool/fonts/source-serif-4/SourceSerif4Variable-Roman.ttf
Binary files differ.
diff --git a/umtool/lib/articles/links.mjs b/umtool/lib/articles/links.mjs
@@ -1,23 +1,38 @@
// Which umtool report-video project is an article's video.
//
-// Two ways, in order:
+// Three ways, in order (plans/umtool-redesign.md, "Linking a project to an
+// article"):
//
-// 1. The manifest says so: a top-level `"article": "<site>/<report>"` in
+// 1. The article's iterations made it: an article of the store
+// (`articles/<id>`) whose `iterations/<n>/iteration.json` names a
+// `projectDir`. That project is linked, and it is CLAIMED -- no other
+// article can match it by slug. `current.json`'s `video` picks the one
+// the article's Cut is. A `projectDir` outside REPORTS_ROOT is not
+// dropped: it is listed as `unreachable` (not reachable here).
+// 2. The manifest says so: a top-level `"article": "<site>/<report>"` in
// video.manifest.json. build-video.mjs never reads top-level keys it does
// not know (it reads `generatedBy` no more than this), so the key costs
// the render nothing. A manifest that names an article is linked to it
// and to nothing else.
-// 2. The slug matches: the manifest's `slug` (else the project directory's
+// 3. The slug matches: the manifest's `slug` (else the project directory's
// name) is the report id, `polemic-<id>`, or the id without `polemic-` --
// and the project lives in the same workspace as the article's draft
// (lib/articles/sources.mjs). A UNIQUE match is linked; two or more are
-// only "possible", and the page says so rather than picking one.
+// only "possible", and the page says so rather than picking one. Only
+// this step is ever ambiguous. A project an iteration claimed (1) or
+// whose manifest names an article (2) is never a slug match: before (1),
+// every generated article listed its own `…/i1` as "possible".
+//
+// The iterations are read here as plain JSON (two keys: `projectDir`, and
+// `current.json`'s `video`) rather than through common's reader, so `umtool
+// notes` -- plain ESM -- links the same way the app does. Every write of
+// those files is common's (lib/report/iterations.ts); this only reads.
//
// Plain ESM, so `umtool notes` can name an article's video too.
-import { readFile } from "node:fs/promises";
+import { readdir, readFile, realpath } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { REPORTS_ROOT } from "../paths.mjs";
+import { ARTICLES_DIR, ARTICLES_KEY, REPORTS_ROOT } from "../paths.mjs";
import { projectRefs } from "../projects/core.mjs";
import { kindLinksArticles } from "../projects/kinds.mjs";
import { idKeys } from "./sources.mjs";
@@ -25,6 +40,11 @@ import { idKeys } from "./sources.mjs";
const CACHE_MS = 30_000;
/** @type {Map<string, { at: number, value: Promise<any[]> }>} */
const cache = new Map();
+/** @type {Map<string, { at: number, value: Promise<Map<string, any[]>> }>} */
+const iterCache = new Map();
+// Bumped by every clearLinksCache(), so a memo built from these reads (the
+// pieces list, lib/pieces.ts) is dropped by the same writes that drop them.
+let epoch = 0;
/** `~/x` back to an absolute path. */
export function untildify(p) {
@@ -70,31 +90,152 @@ export function videoProjects(reportsRoot = REPORTS_ROOT) {
export function clearLinksCache() {
cache.clear();
+ iterCache.clear();
+ epoch += 1;
+}
+
+/** How many times the links cache has been cleared: a memo built on it compares this. */
+export const linksCacheEpoch = () => epoch;
+
+const NUMERIC = /^[1-9][0-9]*$/;
+
+async function readJson(file) {
+ try {
+ return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Every iteration of the article store that names a video project, by article:
+ * `Map<article, [{ n, dir, current, reachable, projectId }]>`, newest first.
+ *
+ * `reachable` is whether `dir` is under REPORTS_ROOT (realpaths, so a linked
+ * root still matches); `projectId` is its path relative to the root, which is
+ * the walk's project id when a project is there.
+ *
+ * @param {{ articlesDir?: string, reportsRoot?: string }} [opts]
+ */
+export function iterationProjects({ articlesDir = ARTICLES_DIR, reportsRoot = REPORTS_ROOT } = {}) {
+ const key = `${articlesDir}\0${reportsRoot}`;
+ const hit = iterCache.get(key);
+ if (hit && Date.now() - hit.at < CACHE_MS) return hit.value;
+ const value = readIterationProjects(articlesDir, reportsRoot);
+ iterCache.set(key, { at: Date.now(), value });
+ value.catch(() => iterCache.delete(key));
+ return value;
+}
+
+/** `dir` relative to `root` as a POSIX path, or null when it is not strictly under it. */
+function under(root, dir) {
+ const rel = path.relative(/* turbopackIgnore: true */ root, dir);
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
+ return rel.split(path.sep).join("/");
+}
+
+async function readIterationProjects(articlesDir, reportsRoot) {
+ const out = new Map();
+ const lexRoot = path.resolve(/* turbopackIgnore: true */ reportsRoot);
+ const root = await realpath(/* turbopackIgnore: true */ lexRoot).catch(() => lexRoot);
+ for (const article of await readdir(/* turbopackIgnore: true */ articlesDir).catch(() => [])) {
+ if (article.startsWith(".")) continue;
+ const itDir = path.join(/* turbopackIgnore: true */ articlesDir, article, "iterations");
+ const names = (await readdir(/* turbopackIgnore: true */ itDir).catch(() => [])).filter((n) => NUMERIC.test(n));
+ if (!names.length) continue;
+ const current = await readJson(path.join(/* turbopackIgnore: true */ itDir, "current.json"));
+ const video = Number.isInteger(current?.video) ? current.video : null;
+ const list = [];
+ for (const name of names) {
+ const it = await readJson(path.join(/* turbopackIgnore: true */ itDir, name, "iteration.json"));
+ const raw = it && typeof it.projectDir === "string" && it.projectDir.trim() ? it.projectDir.trim() : null;
+ if (!raw) continue;
+ const n = Number(name);
+ const dir = path.resolve(/* turbopackIgnore: true */ untildify(raw));
+ // Lexically first (the walk's ids are lexical: a linked folder inside the
+ // root keeps its name), then by realpath (a root reached through a link).
+ let rel = under(lexRoot, dir);
+ if (rel === null) rel = under(root, await realpath(/* turbopackIgnore: true */ dir).catch(() => dir));
+ list.push({ n, dir, current: video === n, reachable: rel !== null, projectId: rel });
+ }
+ if (list.length) out.set(article, list.sort((a, b) => b.n - a.n));
+ }
+ return out;
}
const inside = (root, p) => p === root || p.startsWith(root + path.sep);
/**
- * The projects linked to one article: `{ linked, possible, how }`.
+ * The projects linked to one article:
+ * `{ linked, possible, how, cut, unreachable }`.
+ *
+ * `linked` rows carry `via`: "iteration" (1), "manifest" (2) or "slug" (3).
+ * `cut` is the linked project the article's Cut tab opens: the iteration
+ * `current.video` names, else the first linked. `unreachable` lists the
+ * iterations whose project is outside REPORTS_ROOT (`{ n, dir }`) -- shown as
+ * "not reachable here", never dropped.
*
* @param {string} siteId
* @param {string} reportId
- * @param {{ reportsRoot?: string, workspace?: string | null, projects?: any[] }} [opts]
+ * @param {{ reportsRoot?: string, articlesDir?: string, workspace?: string | null, projects?: any[], iterations?: Map<string, any[]> }} [opts]
* `workspace` is the article's workspace dir (sourceFor's, `~` allowed); without
* one, slug matches are only ever "possible".
*/
-export async function linkedProjects(siteId, reportId, { reportsRoot = REPORTS_ROOT, workspace = null, projects } = {}) {
+export async function linkedProjects(
+ siteId,
+ reportId,
+ { reportsRoot = REPORTS_ROOT, articlesDir = ARTICLES_DIR, workspace = null, projects, iterations } = {},
+) {
const all = projects ?? (await videoProjects(reportsRoot));
+ const its = iterations ?? (await iterationProjects({ articlesDir, reportsRoot }));
const key = `${siteId}/${reportId}`;
- const declared = all.filter((p) => p.article === key);
- if (declared.length) return { linked: declared, possible: [], how: "manifest names the article" };
+ const byId = new Map(all.map((p) => [p.id, p]));
+
+ // (1) the article's own iterations.
+ const mine = siteId === ARTICLES_KEY ? (its.get(reportId) ?? []) : [];
+ const unreachable = mine.filter((x) => !x.reachable).map((x) => ({ n: x.n, dir: x.dir }));
+ const viaIteration = [];
+ for (const x of mine) {
+ const p = x.projectId ? byId.get(x.projectId) : null;
+ if (p && !viaIteration.includes(p)) viaIteration.push(p);
+ }
+ // (2) a manifest that names the article.
+ const declared = all.filter((p) => p.article === key && !viaIteration.includes(p));
+ const linked = [...viaIteration.map((p) => ({ ...p, via: "iteration" })), ...declared.map((p) => ({ ...p, via: "manifest" }))];
+ if (linked.length) {
+ const currentId = mine.find((x) => x.current)?.projectId ?? null;
+ const cut = linked.find((p) => p.id === currentId) ?? linked[0];
+ const how = [
+ viaIteration.length ? `${viaIteration.length} made by the article's iterations` : null,
+ declared.length ? "manifest names the article" : null,
+ ]
+ .filter(Boolean)
+ .join("; ");
+ return { linked, possible: [], how, cut: cut.id, unreachable };
+ }
+ // (3) the slug. Never a project an iteration claimed or a manifest gave away.
+ const claimed = new Set();
+ for (const list of its.values()) for (const x of list) if (x.projectId) claimed.add(x.projectId);
const keys = idKeys(reportId);
- // A manifest that names a DIFFERENT article is never a slug match.
- const bySlug = all.filter((p) => !p.article && keys.has(p.slug));
+ const bySlug = all.filter((p) => !p.article && !claimed.has(p.id) && keys.has(p.slug));
const ws = workspace ? untildify(workspace) : null;
const inWs = ws ? bySlug.filter((p) => inside(ws, p.dir)) : [];
- if (inWs.length === 1) return { linked: inWs, possible: [], how: `slug ${inWs[0].slug} in the article's workspace` };
+ if (inWs.length === 1) {
+ return {
+ linked: [{ ...inWs[0], via: "slug" }],
+ possible: [],
+ how: `slug ${inWs[0].slug} in the article's workspace`,
+ cut: inWs[0].id,
+ unreachable,
+ };
+ }
const possible = inWs.length > 1 ? inWs : bySlug;
- return { linked: [], possible, how: possible.length ? `${possible.length} project(s) share the slug` : "no project" };
+ return {
+ linked: [],
+ possible,
+ how: possible.length ? `${possible.length} project(s) share the slug` : unreachable.length ? "not reachable here" : "no project",
+ cut: null,
+ unreachable,
+ };
}
diff --git a/umtool/lib/articles/links.test.mjs b/umtool/lib/articles/links.test.mjs
@@ -0,0 +1,110 @@
+// Linking a video project to an article, in the plan's order: the article's
+// iterations, then the manifest's `article`, then the slug -- and only the
+// slug is ever ambiguous.
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { clearLinksCache, iterationProjects, linkedProjects, linksCacheEpoch } from "./links.mjs";
+
+async function put(file, value) {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, typeof value === "string" ? value : JSON.stringify(value));
+}
+
+const manifest = (slug, extra = {}) => ({ slug, title: slug, timeline: [], ...extra });
+const iteration = (article, n, projectDir) => ({ format: "archilyzer-iteration", version: 1, article, n, ...(projectDir ? { projectDir } : {}) });
+
+async function fixture() {
+ const base = await mkdtemp(path.join(tmpdir(), "umtool-links-"));
+ const reports = path.join(base, "reports");
+ const articles = path.join(base, "articles");
+ // (1) zeta's iterations made two projects; a third is on another machine.
+ await put(path.join(reports, "articles/zeta/i1/video.manifest.json"), manifest("zeta"));
+ await put(path.join(reports, "articles/zeta/i3/video.manifest.json"), manifest("zeta"));
+ await put(path.join(articles, "zeta/iterations/1/iteration.json"), iteration("zeta", 1, path.join(reports, "articles/zeta/i1")));
+ await put(path.join(articles, "zeta/iterations/2/iteration.json"), iteration("zeta", 2, null));
+ await put(path.join(articles, "zeta/iterations/3/iteration.json"), iteration("zeta", 3, path.join(reports, "articles/zeta/i3")));
+ await put(path.join(articles, "zeta/iterations/4/iteration.json"), iteration("zeta", 4, "/elsewhere/reports/articles/zeta/i4"));
+ await put(path.join(articles, "zeta/iterations/current.json"), { format: "archilyzer-iterations-current", version: 1, report: 1, reportFrom: 1, video: 3 });
+ // (2) a hand-made project whose manifest names zeta.
+ await put(path.join(reports, "hand/zeta-cut/video.manifest.json"), manifest("zeta", { article: "articles/zeta" }));
+ // (3) slugs: one in a workspace, one outside it; two that only share a slug.
+ await put(path.join(reports, "ws/polemic-alpha/video.manifest.json"), manifest("polemic-alpha"));
+ await put(path.join(reports, "elsewhere/alpha/video.manifest.json"), manifest("alpha"));
+ await put(path.join(reports, "one/beta/video.manifest.json"), manifest("beta"));
+ await put(path.join(reports, "two/beta/video.manifest.json"), manifest("beta"));
+ clearLinksCache();
+ return { base, reports, articles, o: { reportsRoot: reports, articlesDir: articles } };
+}
+
+test("(1) an article's iterations link their projects; current.video is the cut; a far one is unreachable", async () => {
+ const { o } = await fixture();
+ const r = await linkedProjects("articles", "zeta", o);
+ assert.deepEqual(
+ r.linked.map((p) => [p.id, p.via]),
+ [
+ ["articles/zeta/i3", "iteration"],
+ ["articles/zeta/i1", "iteration"],
+ ["hand/zeta-cut", "manifest"],
+ ],
+ );
+ assert.equal(r.cut, "articles/zeta/i3");
+ assert.deepEqual(r.possible, []);
+ assert.deepEqual(r.unreachable, [{ n: 4, dir: "/elsewhere/reports/articles/zeta/i4" }]);
+ assert.match(r.how, /2 made by the article's iterations; manifest names the article/);
+});
+
+test("(3) a claimed project is never another article's slug match", async () => {
+ const { o } = await fixture();
+ // A site's own `zeta` shares the slug with zeta's i1 and i3 and with the
+ // hand-made cut. Before (1) claimed them, each was "possible" here -- and the
+ // store's zeta listed its own i1 as possible too.
+ const r = await linkedProjects("priv", "zeta", o);
+ assert.deepEqual(r.linked, []);
+ assert.deepEqual(r.possible, []);
+ assert.equal(r.cut, null);
+ assert.deepEqual(r.unreachable, []);
+});
+
+test("(3) a unique slug in the article's workspace links; without one it is only possible", async () => {
+ const { reports, o } = await fixture();
+ const inWs = await linkedProjects("priv", "polemic-alpha", { ...o, workspace: path.join(reports, "ws") });
+ assert.deepEqual(inWs.linked.map((p) => [p.id, p.via]), [["ws/polemic-alpha", "slug"]]);
+ assert.equal(inWs.cut, "ws/polemic-alpha");
+ const noWs = await linkedProjects("priv", "polemic-alpha", o);
+ assert.deepEqual(noWs.linked, []);
+ assert.deepEqual(noWs.possible.map((p) => p.id).sort(), ["elsewhere/alpha", "ws/polemic-alpha"]);
+});
+
+test("(3) two projects sharing a slug are possible, never picked", async () => {
+ const { o } = await fixture();
+ const r = await linkedProjects("priv", "beta", o);
+ assert.deepEqual(r.linked, []);
+ assert.deepEqual(r.possible.map((p) => p.id).sort(), ["one/beta", "two/beta"]);
+});
+
+test("iteration dirs: a root reached through a link still matches; far dirs are kept, not dropped", async () => {
+ const { base, reports, articles } = await fixture();
+ const alias = path.join(base, "alias");
+ await symlink(reports, alias);
+ await put(path.join(articles, "kappa/iterations/1/iteration.json"), iteration("kappa", 1, path.join(alias, "articles/zeta/i1")));
+ clearLinksCache();
+ const its = await iterationProjects({ articlesDir: articles, reportsRoot: reports });
+ assert.deepEqual(its.get("kappa"), [{ n: 1, dir: path.join(alias, "articles/zeta/i1"), current: false, reachable: true, projectId: "articles/zeta/i1" }]);
+ assert.deepEqual(
+ its.get("zeta").map((x) => [x.n, x.reachable, x.projectId, x.current]),
+ [
+ [4, false, null, false],
+ [3, true, "articles/zeta/i3", true],
+ [1, true, "articles/zeta/i1", false],
+ ],
+ );
+});
+
+test("clearing the cache bumps the epoch a memo compares", () => {
+ const before = linksCacheEpoch();
+ clearLinksCache();
+ assert.equal(linksCacheEpoch(), before + 1);
+});
diff --git a/umtool/lib/articles/sites.ts b/umtool/lib/articles/sites.ts
@@ -47,7 +47,13 @@ export function reportDirFor(site: string, report: string): string {
export type ArticleStatus = "published" | "draft";
-export type ProjectLinkRow = { id: string; title: string; slug: string };
+export type ProjectLinkRow = {
+ id: string;
+ title: string;
+ slug: string;
+ /** How a linked project is linked (lib/articles/links.mjs): its iterations, its manifest, or its slug. */
+ via?: "iteration" | "manifest" | "slug";
+};
export type ArticleRow = {
site: string;
@@ -71,7 +77,16 @@ export type ArticleRow = {
problem: string | null;
problems: number;
source: { draft?: string; generator?: string; how?: string; workspace?: string } | null;
- projects: { linked: ProjectLinkRow[]; possible: ProjectLinkRow[] };
+ projects: {
+ linked: ProjectLinkRow[];
+ possible: ProjectLinkRow[];
+ /** The linked project the Cut opens (current.video's), else null. */
+ cut?: string | null;
+ /** In words: how the links were made. */
+ how?: string;
+ /** Iterations whose project is outside REPORTS_ROOT: not reachable here. */
+ unreachable?: { n: number; dir: string }[];
+ };
};
export type SiteRow = {
@@ -132,7 +147,12 @@ async function articleRow(siteId: string, id: string, published: Set<string>, pr
const dir = reportDirFor(siteId, id);
const r = read.report;
const links = await linkedProjects(siteId, id, { workspace: source?.workspace ?? null, projects });
- const row = (p: { id: string; title: string; slug: string }) => ({ id: p.id, title: p.title, slug: p.slug });
+ const row = (p: { id: string; title: string; slug: string; via?: ProjectLinkRow["via"] }): ProjectLinkRow => ({
+ id: p.id,
+ title: p.title,
+ slug: p.slug,
+ ...(p.via ? { via: p.via } : {}),
+ });
return {
site: siteId,
id,
@@ -151,7 +171,13 @@ async function articleRow(siteId: string, id: string, published: Set<string>, pr
problem: read.problems[0]?.message ?? null,
problems: read.problems.length,
source,
- projects: { linked: links.linked.map(row), possible: links.possible.map(row) },
+ projects: {
+ linked: links.linked.map(row),
+ possible: links.possible.map(row),
+ cut: links.cut ?? null,
+ how: links.how,
+ unreachable: links.unreachable ?? [],
+ },
...(siteId === ARTICLES_KEY ? { audience: articleAudience(r) } : {}),
};
}
diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts
@@ -76,6 +76,21 @@ export type Decision = {
severity: Severity;
/** Newest evidence first. */
at: number;
+
+ // ---- The inbox's fields (lib/inbox.ts). ADDITIVE: a row without them is
+ // still a decision, and the reducers above never set them. ----
+ /** The piece it belongs to (lib/pieces/ids.mjs): `a:<site>/<report>` or `p:<project>`. */
+ piece?: string;
+ /** What kind of thing it is (lib/inbox/groups.mjs CATEGORIES): spend, review, fix, note, choose, finish, info. */
+ category?: string;
+ /** Where the inbox puts it (lib/inbox/groups.mjs GROUPS). */
+ group?: string;
+ /** The ONE primary action; its label names the result. `href` is the row's own (a note's ends in `note=<id>`). */
+ action?: { label: string; href: string };
+ /** The piece's lifecycle (lib/lifecycle.ts); absent from the file is `active`. */
+ lifecycle?: "active" | "parked" | "done";
+ /** On a parked or done piece: kept in the list, out of the way. */
+ hidden?: boolean;
};
export const SEVERITIES: Severity[] = ["blocking", "open", "info"];
diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs
@@ -0,0 +1,66 @@
+// node --test umtool/lib/hrefs.test.mjs (Node strips hrefs.ts's types itself)
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as H from "./hrefs.ts";
+
+test("note is always the last parameter", () => {
+ assert.equal(H.articleHref({ site: "articles", id: "x" }, { note: "n1", tab: "source" }), "/articles/x?tab=source¬e=n1");
+ assert.equal(H.projectHref("a/b", { note: "n2", all: true }), "/browse/a/b?all=1¬e=n2");
+ assert.equal(H.withQuery("/p", { note: "sneaky", z: "1", a: "2" }, "n3"), "/p?z=1&a=2¬e=n3");
+ // A note passed in the query map never lands anywhere but the end -- and only via `note`.
+ assert.equal(H.withQuery("/p", { note: "sneaky", z: "1" }), "/p?z=1");
+ for (const href of [
+ H.clipBenchHref("p", "c04", { note: "n" }),
+ H.claimBenchHref("p", "k1", { note: "n" }),
+ H.takesHref("p", { note: "n" }),
+ H.narrationHref("p", { note: "n" }),
+ H.reviewHref("p", { note: "n" }),
+ H.projectAtHref("tools/x", { note: "n" }),
+ H.articleHref({ site: "jeralyzer", id: "r" }, { status: "draft", tab: "source", ws: "w", rel: "a.md", note: "n" }),
+ ]) {
+ assert.match(href, /[?&]note=n$/, href);
+ }
+});
+
+test("withNote re-points an href and keeps note last, and the fragment after it", () => {
+ assert.equal(H.withNote("/articles/x?note=old&tab=source", "new"), "/articles/x?tab=source¬e=new");
+ assert.equal(H.withNote("/browse/p", "n"), "/browse/p?note=n");
+ assert.equal(H.withNote("/sites/s?ws=a#files", "n"), "/sites/s?ws=a¬e=n#files");
+});
+
+test("project ids are encoded per segment, slashes kept", () => {
+ assert.equal(H.projectHref("quartering-uh-song/videos/mortal-kombat"), "/browse/quartering-uh-song/videos/mortal-kombat");
+ assert.equal(H.projectHref("a b/c?d"), "/browse/a%20b/c%3Fd");
+ assert.equal(H.clipBenchHref("articles/x/i1", "c 04"), "/browse/articles/x/i1/clip/c%2004");
+ assert.equal(H.encodePath("/lead//trail/"), "lead/trail");
+});
+
+test("empty, null and false values are left out; true is 1", () => {
+ assert.equal(H.browseHref({}), "/browse");
+ assert.equal(H.browseHref({ kind: "", state: undefined, q: "x y" }), "/browse?q=x+y");
+ assert.equal(H.projectHref("p", { all: false }), "/browse/p");
+ assert.equal(H.decisionsHref({ severity: "blocking", project: "a/b" }), "/browse/decisions?severity=blocking&project=a%2Fb");
+});
+
+test("articles open in the store or on their site", () => {
+ assert.equal(H.articleHref({ site: "articles", id: "poker" }), "/articles/poker");
+ assert.equal(H.articleHref({ site: "jeralyzer", id: "poker" }), "/sites/jeralyzer/poker");
+ assert.equal(H.articleEvidenceHref({ site: "jeralyzer", id: "poker" }, { c: "3" }), "/sites/jeralyzer/poker/evidence?c=3");
+ assert.equal(H.articleCompareHref("poker", { a: "1", b: "2" }), "/articles/poker/compare?a=1&b=2");
+ assert.equal(H.newArticleHref(), "/articles/new");
+});
+
+test("site pages, tools and piles", () => {
+ assert.equal(H.siteHref("jeralyzer"), "/sites/jeralyzer");
+ assert.equal(H.siteHref("jeralyzer", { ws: "w", rel: "a/b.md" }), "/sites/jeralyzer?ws=w&rel=a%2Fb.md#files");
+ assert.equal(H.sitesHref({ status: "draft" }), "/sites?status=draft");
+ assert.equal(H.findHref({ q: "um" }), "/browse/find?q=um");
+ assert.equal(H.facesHref({ cover: "c 1" }), "/browse/faces?cover=c+1");
+ assert.equal(H.sourcesHref(), "/browse/sources");
+ assert.equal(H.trimHref("hooks"), "/browse/trim/hooks");
+ assert.equal(H.mixHref({ body: "/a/b.wav", from: "p", start: 1.5 }), "/mix?body=%2Fa%2Fb.wav&from=p&start=1.5");
+ assert.equal(H.pileHref("sort", { limit: 5 }), "/sort?limit=5");
+ assert.equal(H.cutHref("yoshi", "wide", { plan: "p1" }), "/browse/yoshi/wide?plan=p1");
+ assert.equal(H.homeHref({ from: "ch/vid" }), "/?from=ch%2Fvid");
+ assert.equal(H.homeHref(), "/");
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -0,0 +1,220 @@
+// ---------------------------------------------------------------------------
+// Every page address umtool links to, one builder per URL shape.
+//
+// The URLs are about to move (plans/umtool-redesign.md, P3: /browse becomes
+// /work and /projects, the song tools go under /tools). When they do, the
+// change is a body here and a row in redirects.mjs, not a grep across ~70 call
+// sites with template literals in them. A link written as a literal from now on
+// is a link P3 has to find by hand.
+//
+// Two contracts:
+// - `?note=<id>` is ALWAYS the last parameter. The MCP's notes tool reads a
+// decision's href and expects it to END in `note=<id>`
+// (mcp/src/archivalTools.ts), so the builder puts it last whatever else the
+// query carries.
+// - Project ids are paths (`quartering-uh-song/videos/mortal-kombat`): each
+// SEGMENT is encoded, the slashes are not.
+//
+// Pure and dependency-free (one .mjs constant), so a client component, a server
+// page and an e2e spec (e2e/urls.ts) all import the same table, and
+// `node --test lib/hrefs.test.mjs` runs it without a bundler.
+// ---------------------------------------------------------------------------
+
+import { ARTICLES_KEY } from "./articles/key.mjs";
+
+/** A query value; `undefined`, `null`, `false` and "" are left out. */
+export type QueryValue = string | number | boolean | null | undefined;
+export type Query = Record<string, QueryValue>;
+
+/** Encode a path id segment by segment, keeping its slashes. */
+export function encodePath(id: string): string {
+ return id
+ .split("/")
+ .filter((s) => s.length > 0)
+ .map(encodeURIComponent)
+ .join("/");
+}
+
+/**
+ * `path` + its query, with `note` last. `true` is written as `1`, the form every
+ * flag here already takes (`?all=1`).
+ */
+export function withQuery(path: string, query: Query = {}, note?: string | null): string {
+ const sp = new URLSearchParams();
+ for (const [k, v] of Object.entries(query)) {
+ if (k === "note") continue; // only ever through `note`, so it stays last
+ if (v === undefined || v === null || v === false || v === "") continue;
+ sp.set(k, v === true ? "1" : String(v));
+ }
+ if (note) sp.set("note", note);
+ const q = sp.toString();
+ return q ? `${path}?${q}` : path;
+}
+
+/** Re-point an existing href at a note, keeping `note` last. */
+export function withNote(href: string, note: string): string {
+ const hash = href.indexOf("#");
+ const frag = hash >= 0 ? href.slice(hash) : "";
+ const bare = hash >= 0 ? href.slice(0, hash) : href;
+ const q = bare.indexOf("?");
+ const path = q >= 0 ? bare.slice(0, q) : bare;
+ const sp = new URLSearchParams(q >= 0 ? bare.slice(q + 1) : "");
+ sp.delete("note");
+ sp.set("note", note);
+ return `${path}?${sp.toString()}${frag}`;
+}
+
+type NoteOpt = { note?: string | null };
+
+// ── home and the lists ──────────────────────────────────────────────────────
+
+/** The dashboard. `from` is the editor's "make a video" handoff (`/?from=<slug>/<id>`). */
+export function homeHref(q: { from?: string } = {}): string {
+ return withQuery("/", q);
+}
+
+export type BrowseQuery = {
+ kind?: string;
+ template?: string;
+ state?: string;
+ open?: string;
+ q?: string;
+ sort?: string;
+ deleted?: string;
+};
+/** Every project, filtered. */
+export function browseHref(q: BrowseQuery = {}): string {
+ return withQuery("/browse", q);
+}
+
+export type DecisionsQuery = { severity?: string; kind?: string; project?: string };
+/** The decision list across every project. */
+export function decisionsHref(q: DecisionsQuery = {}): string {
+ return withQuery("/browse/decisions", q);
+}
+
+export type ArticlesQuery = { status?: string; notes?: string; audience?: string; deleted?: string; freed?: string };
+/** The article store's list (release 26). */
+export function articlesHref(q: ArticlesQuery = {}): string {
+ return withQuery("/articles", q);
+}
+
+/** A new article (release 27). */
+export function newArticleHref(): string {
+ return "/articles/new";
+}
+
+export type SitesQuery = { site?: string; status?: string; notes?: string };
+/** Every site's articles. */
+export function sitesHref(q: SitesQuery = {}): string {
+ return withQuery("/sites", q);
+}
+
+/** One site's page; `ws`+`rel` open a workspace file, `#files` scrolls to it. */
+export function siteHref(site: string, q: { ws?: string; rel?: string } = {}): string {
+ const base = withQuery(`/sites/${encodeURIComponent(site)}`, q);
+ return q.ws || q.rel ? `${base}#files` : base;
+}
+
+// ── articles ────────────────────────────────────────────────────────────────
+
+export type ArticleRef = { site: string; id: string };
+export type ArticleQuery = { tab?: string; status?: string; ws?: string; rel?: string } & NoteOpt;
+
+function articleBase(a: ArticleRef): string {
+ return a.site === ARTICLES_KEY
+ ? `/articles/${encodeURIComponent(a.id)}`
+ : `/sites/${encodeURIComponent(a.site)}/${encodeURIComponent(a.id)}`;
+}
+
+/** An article's page: `/articles/<id>` in the store, `/sites/<site>/<id>` on a site. */
+export function articleHref(a: ArticleRef, q: ArticleQuery = {}): string {
+ const { note, ...rest } = q;
+ return withQuery(articleBase(a), rest, note);
+}
+
+/** The evidence walk of one article. */
+export function articleEvidenceHref(a: ArticleRef, q: { c?: string } = {}): string {
+ return withQuery(`${articleBase(a)}/evidence`, q);
+}
+
+/** Two revisions of a store article side by side. */
+export function articleCompareHref(id: string, q: { a?: string; b?: string } = {}): string {
+ return withQuery(`/articles/${encodeURIComponent(id)}/compare`, q);
+}
+
+// ── projects ────────────────────────────────────────────────────────────────
+
+/** A project's page. `all` shows every row of a long list. */
+export function projectHref(id: string, q: { all?: boolean } & NoteOpt = {}): string {
+ const { note, ...rest } = q;
+ return withQuery(`/browse/${encodePath(id)}`, rest, note);
+}
+
+/** A project by its path, for an id that a tool page shadows at its own URL. */
+export function projectAtHref(id: string, q: NoteOpt = {}): string {
+ return withQuery("/browse/at", { path: id }, q.note);
+}
+
+/** The clip bench, one timeline entry. */
+export function clipBenchHref(project: string, clip: string, q: NoteOpt = {}): string {
+ return withQuery(`/browse/${encodePath(project)}/clip/${encodeURIComponent(clip)}`, {}, q.note);
+}
+
+/** The claim bench, one ledger entry. */
+export function claimBenchHref(project: string, claim: string, q: NoteOpt = {}): string {
+ return withQuery(`/browse/${encodePath(project)}/claim/${encodeURIComponent(claim)}`, {}, q.note);
+}
+
+/** Alternative renders of one part of a cut. */
+export function takesHref(project: string, q: NoteOpt = {}): string {
+ return withQuery(`/browse/${encodePath(project)}/takes`, {}, q.note);
+}
+
+/** The narration script, card by card. */
+export function narrationHref(project: string, q: NoteOpt = {}): string {
+ return withQuery(`/browse/${encodePath(project)}/narration`, {}, q.note);
+}
+
+/** The drafts review (release 28). */
+export function reviewHref(project: string, q: NoteOpt = {}): string {
+ return withQuery(`/browse/${encodePath(project)}/review`, {}, q.note);
+}
+
+/** One cut of a song; `plan` opens a plan of it, `v` a variant row. */
+export function cutHref(song: string, cut: string, q: { plan?: string; v?: string } = {}): string {
+ return withQuery(`/browse/${encodePath(song)}/${encodeURIComponent(cut)}`, q);
+}
+
+// ── tools ───────────────────────────────────────────────────────────────────
+
+/** Every occurrence of a word across the corpus. */
+export function findHref(q: Query = {}): string {
+ return withQuery("/browse/find", q);
+}
+
+/** The face judger; `cover` opens on one cover's corners. */
+export function facesHref(q: { cover?: string } = {}): string {
+ return withQuery("/browse/faces", q);
+}
+
+/** Where the palette comes from, across every song. */
+export function sourcesHref(): string {
+ return "/browse/sources";
+}
+
+/** A trim set's bench. */
+export function trimHref(set: string): string {
+ return `/browse/trim/${encodeURIComponent(set)}`;
+}
+
+export type MixQuery = { body?: string; start?: string | number; end?: string | number; from?: string; clip?: string };
+/** The mix bench; the deep link is resolved server-side (lib/mix-preset.ts). */
+export function mixHref(q: MixQuery = {}): string {
+ return withQuery("/mix", q);
+}
+
+/** A song judging pile (`/sort`, `/salvage`, `/verify`, `/keeps`). */
+export function pileHref(mode: string, q: { limit?: number; only?: string } = {}): string {
+ return withQuery(`/${encodeURIComponent(mode)}`, q);
+}
diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts
@@ -0,0 +1,246 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage";
+import { readResearchState } from "yt-dlp-transcript-common/lib/report/draft/research/state";
+import { ARTICLES_KEY } from "./paths";
+import { readArticleIterations, type IterationRow } from "./articles/generation";
+import { sitesPaths } from "./articles/sites";
+import { decisionsForSong, type Decision } from "./decisions";
+import { openDecisions } from "./projects";
+import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces";
+import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle";
+import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs";
+
+// ---------------------------------------------------------------------------
+// THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the
+// projects' and the notes'), plus the generation era's, read from disk --
+//
+// iteration-ready a finished iteration that is not current and is newer
+// than the current one: make it current, or not
+// iteration-failed a failed run nothing later has superseded, with what
+// it spent
+// research-proposal an acquisition a research run proposed, waiting on a
+// yes or no (common's readResearchState: a READ of
+// proposals.json -- never readResearch(), which POSTs to
+// the editor and may rewrite the file)
+// link-ambiguous an article whose video only a slug suggests
+// looks-done a piece every signal says is finished (a suggestion:
+// it never sets the lifecycle)
+//
+// -- each row given its piece, category, group, one action, lifecycle and
+// `hidden` (lib/inbox/groups.mjs), ranked. One row per decision, never dropped:
+// the MCP reads `items[]` (mcp/src/archivalTools.ts).
+//
+// No editor call anywhere here: there is no "waiting on a cap" state (the daily
+// cap refuses at start, a per-job cap ends the run), and running jobs are
+// P2b's.
+//
+// SERVER ONLY.
+// ---------------------------------------------------------------------------
+
+export type GroupCard = {
+ piece: string | null;
+ project: string;
+ title: string;
+ kind: string;
+ severity: Decision["severity"];
+ count: number;
+ why: string;
+ action: { label: string; href: string };
+ at: number;
+};
+export type GroupSummary = {
+ id: string;
+ label: string;
+ collapsed: boolean;
+ /** Visible decisions in the group. */
+ decisions: number;
+ /** Decisions on parked or done pieces. */
+ hidden: number;
+ cards: GroupCard[];
+};
+
+export type Inbox = {
+ items: Decision[];
+ groups: GroupSummary[];
+ hidden: number;
+ /** lifecycle.json could not be read: every piece reads as active. */
+ lifecycleError?: string;
+};
+
+export const INBOX_GROUPS = GROUPS as { id: string; label: string; collapsed: boolean }[];
+
+const iterationsHref = (article: string) => `/articles/${article}?tab=iterations`;
+const timeOf = (iso: string | null | undefined) => {
+ const ms = iso ? Date.parse(iso) : NaN;
+ return Number.isFinite(ms) ? ms : 0;
+};
+const usd = (n: number) => `$${n.toFixed(2)}`;
+
+/** The store's articles: published, drafts and those in the making. */
+const storeArticles = (graph: PieceGraph): Piece[] => graph.pieces.filter((p) => p.kind === "article" && p.site === ARTICLES_KEY);
+
+const articleRow = (piece: Piece) => ({
+ project: `sites/${piece.site}/${piece.report}`,
+ projectKind: "article",
+ projectTitle: piece.title,
+ piece: piece.id,
+});
+
+/**
+ * Iteration decisions for one article: ready, failed, and its research runs'
+ * proposals. `spend` joins the ledger's rows on the iteration's job when the
+ * iteration itself recorded no usage.
+ */
+async function iterationDecisions(piece: Piece, spendOfJob: Map<string, number>): Promise<Decision[]> {
+ const article = piece.report as string;
+ const its = await readArticleIterations(article).catch(() => null);
+ if (!its) return [];
+ const out: Decision[] = [];
+ const base = articleRow(piece);
+ const href = iterationsHref(article);
+ const cur = its.current;
+ const spent = (r: IterationRow) => (r.usd > 0 ? r.usd : r.jobId ? (spendOfJob.get(r.jobId) ?? 0) : 0);
+ const live = (r: IterationRow) => r.status === "queued" || r.status === "running" || r.status === "done";
+
+ for (const r of its.iterations) {
+ const at = timeOf(r.endedAt ?? r.createdAt);
+ if (r.status === "done" && r.kind !== "research") {
+ // A video revision competes with the current video; anything else with
+ // the current report. Only something that could BE current is ready.
+ const video = r.kind === "revise-video";
+ const against = video ? cur.video : cur.report;
+ const makeable = video ? r.hasManifest : r.hasReport;
+ if (makeable && (against === null || r.n > against)) {
+ out.push({
+ ...base,
+ kind: "iteration-ready",
+ target: r.label,
+ why:
+ `${r.label} (${r.kind} on ${r.model}) is done and newer than the current ${video ? "video" : "report"}` +
+ `${against === null ? " (none yet)" : ` (i${against})`}${spent(r) ? ` · ${usd(spent(r))}` : ""}`,
+ href,
+ severity: "open",
+ at,
+ });
+ }
+ }
+ if (r.status === "failed") {
+ // A failed run is a decision until something after it runs.
+ const superseded = its.iterations.some((o) => o.n > r.n && live(o));
+ if (!superseded) {
+ out.push({
+ ...base,
+ kind: "iteration-failed",
+ target: r.label,
+ why: `${r.label} (${r.kind} on ${r.model}) failed${r.error ? `: ${r.error}` : ""}${spent(r) ? ` · ${usd(spent(r))} spent` : ""}`,
+ href,
+ severity: "open",
+ at,
+ });
+ }
+ }
+ if (r.kind === "research") {
+ const state = await readResearchState(article, r.n, sitesPaths()).catch(() => null);
+ for (const p of state?.proposals ?? []) {
+ if (p.status !== "proposed") continue;
+ const est = p.estimate
+ ? [
+ p.estimate.items ? `${p.estimate.items} item${p.estimate.items === 1 ? "" : "s"}` : null,
+ p.estimate.gb ? `${p.estimate.gb} GB` : null,
+ p.estimate.transcribeHours ? `${p.estimate.transcribeHours} h to transcribe` : null,
+ ]
+ .filter(Boolean)
+ .join(", ")
+ : "";
+ out.push({
+ ...base,
+ kind: "research-proposal",
+ target: `${r.label} ${p.id}`,
+ why: `${p.action}${p.reason ? `: ${p.reason}` : ""}${est ? ` (${est})` : ""}`,
+ href,
+ severity: "open",
+ at,
+ });
+ }
+ }
+ }
+ return out;
+}
+
+/** Decisions only the pieces can see: ambiguous links and pieces that look done. */
+function pieceDecisions(graph: PieceGraph, life: LifecycleRead): Decision[] {
+ const out: Decision[] = [];
+ for (const p of graph.pieces) {
+ const base =
+ p.kind === "article"
+ ? articleRow(p)
+ : { project: p.project as string, projectTitle: p.title, piece: p.id };
+ if (p.kind === "article" && !p.projects.length && p.possible.length) {
+ out.push({
+ ...base,
+ kind: "link-ambiguous",
+ target: p.possible.map((x) => x.id).join(", "),
+ why:
+ p.possible.length === 1
+ ? `${p.possible[0].id} shares its slug but is not linked — name the article in its manifest to link it`
+ : `${p.possible.length} projects share its slug and none is linked: ${p.possible.map((x) => x.id).join(", ")}`,
+ href: p.href,
+ severity: "open",
+ at: p.newestMs,
+ });
+ }
+ if (p.looksDone.length && lifecycleOf(life, p.id) !== "done") {
+ out.push({
+ ...base,
+ kind: "looks-done",
+ target: p.id,
+ why: `looks done: ${p.looksDone.join("; ")}`,
+ href: p.href,
+ severity: "open",
+ at: p.newestMs,
+ });
+ }
+ }
+ return out;
+}
+
+/** The ledger's spend per job id, for an iteration that recorded none itself. */
+async function spendByJob(): Promise<Map<string, number>> {
+ const rows = await readGenerationUsage(getPaths().generationUsageFile).catch(() => []);
+ const out = new Map<string, number>();
+ for (const r of rows) if (r.jobId) out.set(r.jobId, (out.get(r.jobId) ?? 0) + r.usd);
+ return out;
+}
+
+/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done. */
+export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> {
+ const spend = await spendByJob();
+ const perArticle = await Promise.all(storeArticles(graph).map((p) => iterationDecisions(p, spend)));
+ return [...perArticle.flat(), ...pieceDecisions(graph, life)];
+}
+
+/**
+ * The inbox. `project` narrows to one song's reducer (the decisions route's
+ * `?project=`), annotated the same way, with no disk sources added.
+ */
+export async function readInbox({ project }: { project?: string | null } = {}): Promise<Inbox> {
+ const [base, graph, life] = await Promise.all([
+ project ? decisionsForSong(project) : openDecisions(),
+ readPieceGraph(),
+ readLifecycle(),
+ ]);
+ // A disk source that cannot be read adds nothing; it never hides the rest.
+ const extra = project ? [] : await diskDecisions(graph, life).catch(() => [] as Decision[]);
+ const items = rankDecisions(
+ annotate([...base, ...extra], {
+ pieceOf: (d: Decision) => pieceOfDecision(d, graph),
+ lifecycleOf: (id: string) => lifecycleOf(life, id),
+ }),
+ ) as Decision[];
+ return {
+ items,
+ groups: summarizeGroups(items) as GroupSummary[],
+ hidden: items.filter((d) => d.hidden).length,
+ ...(life.error ? { lifecycleError: life.error } : {}),
+ };
+}
diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs
@@ -0,0 +1,218 @@
+// THE INBOX'S ORDER: which group a decision is in, how the groups rank, and
+// the one action each offers (plans/umtool-redesign.md, "Target information
+// architecture", Inbox). Pure functions over decision rows -- no disk, no
+// clock -- so the ranking is unit-tested and the API, the CLI and (P3) the page
+// share one definition.
+//
+// GROUPS, in order:
+//
+// your-call research proposals, then failed runs: money is waiting
+// on a yes or no ("spend")
+// review a finished iteration that is not current (r28's drafts
+// join here in P2b)
+// blocking something downstream would lie, on an ACTIVE piece
+// notes the operator's open notes
+// open every other open decision (a variant with no verdict, a
+// link only the operator can choose, …)
+// ready-to-finish a piece that looks done: mark it done, or keep it going
+// quiet true facts that are not decisions; collapsed
+//
+// A decision on a PARKED or DONE piece keeps its group and is `hidden`. The
+// API never drops it (one row per decision, the MCP reads every row); the
+// inbox shows a hidden count instead of the rows.
+
+export const GROUPS = [
+ { id: "your-call", label: "Your call", collapsed: false },
+ { id: "review", label: "Review", collapsed: false },
+ { id: "blocking", label: "Blocking", collapsed: false },
+ { id: "notes", label: "Notes", collapsed: false },
+ { id: "open", label: "Open", collapsed: false },
+ { id: "ready-to-finish", label: "Ready to finish", collapsed: false },
+ { id: "quiet", label: "Quiet", collapsed: true },
+];
+export const GROUP_IDS = GROUPS.map((g) => g.id);
+
+/**
+ * A decision's CATEGORY: what kind of thing it is, independent of where it
+ * sits. `spend` is research proposals plus failed runs (there is no "waiting
+ * on a cap" state: the daily cap refuses at start, a per-job cap ends the run).
+ */
+export const CATEGORIES = ["spend", "review", "fix", "note", "choose", "finish", "info"];
+
+const KIND_CATEGORY = {
+ "research-proposal": "spend",
+ "iteration-failed": "spend",
+ "iteration-ready": "review",
+ "open-note": "note",
+ "unreadable-notes": "fix",
+ "link-ambiguous": "choose",
+ "looks-done": "finish",
+};
+
+const CATEGORY_GROUP = {
+ spend: "your-call",
+ review: "review",
+ fix: "blocking",
+ note: "notes",
+ choose: "open",
+ finish: "ready-to-finish",
+ info: "quiet",
+};
+
+/** @param {{ kind: string, severity: string }} d */
+export function categoryOf(d) {
+ const named = KIND_CATEGORY[d.kind];
+ if (named) return named;
+ return d.severity === "blocking" ? "fix" : d.severity === "open" ? "choose" : "info";
+}
+
+/** @param {{ kind: string, severity: string }} d */
+export function groupOf(d) {
+ // Information is quiet whatever its kind: a fact is not a decision.
+ if (d.severity === "info") return "quiet";
+ return CATEGORY_GROUP[categoryOf(d)];
+}
+
+// Within a group: the brief's order first (proposals before failed runs), then
+// everything else as equals.
+const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "unreadable-notes": 0 };
+const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 };
+
+// ONE primary action per decision, its button copy naming the result.
+const ACTION_LABEL = {
+ "research-proposal": "Approve acquisition",
+ "iteration-failed": "Retry run",
+ "iteration-ready": (d) => `Make ${d.target} current`,
+ "open-note": "Answer note",
+ "unreadable-notes": "Repair notes.json",
+ "link-ambiguous": "Link the video",
+ "looks-done": "Mark done",
+ "claim-unadjudicated": "Adjudicate claim",
+ "claim-incoherent": "Rule on the flag",
+ "clip-no-cues": "Fix the cue source",
+ "clip-unfetchable": "Replace the source",
+ "clip-mid-sentence": "Trim to the sentence",
+ "clip-cue-gap": "Fix the window",
+ "clip-cut-outside": "Fix the cut",
+ "window-overlap": "Fix the windows",
+ "no-punctuation": "Check the windows",
+ "manifest-invalid": "Fix the manifest",
+ "stale-build": "Rebuild the video",
+ unbuilt: "Build the video",
+ "storage-unreachable": "Reconnect the media drive",
+ "storage-mismatch": "Settle the storage",
+ "unjudged-variant": "Judge variant",
+ "missing-cut": "Ship the cut",
+ "stale-recipe": "Record the recipe",
+ "no-recipe": "Record the recipe",
+ "spec-problem": "Fix the spec",
+ "no-plan": "Name the plan",
+ unattributed: "Attribute variant",
+ "thumb-unaccepted": "Accept a cover",
+ loudness: "Re-render at the target",
+ "shadowed-name": "Rename the project",
+ "unroutable-name": "Rename the project",
+ "ambiguous-project": "Fix the project's files",
+};
+
+const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" };
+
+/**
+ * The decision's one action: `{ label, href }`. The href is the decision's
+ * own, untouched -- a note's still ends in `note=<id>` (the MCP relies on it).
+ *
+ * @param {{ kind: string, severity: string, target: string, href: string }} d
+ */
+export function actionOf(d) {
+ const named = ACTION_LABEL[d.kind];
+ const label = typeof named === "function" ? named(d) : (named ?? CATEGORY_LABEL[categoryOf(d)]);
+ return { label, href: d.href };
+}
+
+/**
+ * Add the inbox's fields to each row: `piece`, `category`, `group`, `action`,
+ * `lifecycle`, `hidden`. Never drops or merges a row.
+ *
+ * @template {{ kind: string, severity: string, target: string, href: string, project: string }} D
+ * @param {D[]} items
+ * @param {{ pieceOf: (d: D) => string | null, lifecycleOf: (piece: string) => string }} how
+ */
+export function annotate(items, { pieceOf, lifecycleOf }) {
+ return items.map((d) => {
+ const piece = d.piece ?? pieceOf(d);
+ const lifecycle = piece ? lifecycleOf(piece) : "active";
+ return {
+ ...d,
+ ...(piece ? { piece } : {}),
+ category: categoryOf(d),
+ group: groupOf(d),
+ action: actionOf(d),
+ lifecycle,
+ hidden: lifecycle === "parked" || lifecycle === "done",
+ };
+ });
+}
+
+/**
+ * The inbox's order: visible before hidden, then by group, then the kind's
+ * rank in its group, then severity, then newest first. Stable for equals (by
+ * piece, kind, target), so two reads of the same disk give the same list.
+ */
+export function rankDecisions(items) {
+ const g = (d) => GROUP_IDS.indexOf(d.group ?? groupOf(d));
+ return [...items].sort(
+ (a, b) =>
+ Number(!!a.hidden) - Number(!!b.hidden) ||
+ g(a) - g(b) ||
+ (KIND_RANK[a.kind] ?? 9) - (KIND_RANK[b.kind] ?? 9) ||
+ (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3) ||
+ (b.at ?? 0) - (a.at ?? 0) ||
+ String(a.piece ?? a.project).localeCompare(String(b.piece ?? b.project)) ||
+ a.kind.localeCompare(b.kind) ||
+ String(a.target).localeCompare(String(b.target)),
+ );
+}
+
+/**
+ * The grouped summary, for a page or a terminal: per group, its CARDS (one per
+ * piece and kind -- 483 unadjudicated claims on one video are one card), how
+ * many decisions they hold, and how many are hidden. Rows are counted, never
+ * dropped: `decisions + hidden` over every group is `items.length`.
+ *
+ * @param {Array<Record<string, any>>} items annotated rows
+ */
+export function summarizeGroups(items) {
+ const ranked = rankDecisions(items);
+ const out = GROUPS.map((g) => ({ ...g, decisions: 0, hidden: 0, cards: [] }));
+ const byId = new Map(out.map((g) => [g.id, g]));
+ const cardOf = new Map();
+ for (const d of ranked) {
+ const group = byId.get(d.group ?? groupOf(d));
+ if (d.hidden) {
+ group.hidden += 1;
+ continue;
+ }
+ group.decisions += 1;
+ const key = `${group.id}\u0000${d.piece ?? d.project}\u0000${d.kind}`;
+ let card = cardOf.get(key);
+ if (!card) {
+ card = {
+ piece: d.piece ?? null,
+ project: d.project,
+ title: d.projectTitle ?? d.project,
+ kind: d.kind,
+ severity: d.severity,
+ count: 0,
+ why: d.why,
+ action: d.action ?? actionOf(d),
+ at: d.at ?? 0,
+ };
+ cardOf.set(key, card);
+ group.cards.push(card);
+ }
+ card.count += 1;
+ if ((SEVERITY_RANK[d.severity] ?? 3) < (SEVERITY_RANK[card.severity] ?? 3)) card.severity = d.severity;
+ card.at = Math.max(card.at, d.at ?? 0);
+ }
+ return out;
+}
diff --git a/umtool/lib/inbox/groups.test.mjs b/umtool/lib/inbox/groups.test.mjs
@@ -0,0 +1,114 @@
+// The inbox's grouping and ranking: pure, over hand-made rows.
+import assert from "node:assert/strict";
+import test from "node:test";
+import { GROUP_IDS, actionOf, annotate, categoryOf, groupOf, rankDecisions, summarizeGroups } from "./groups.mjs";
+
+const row = (kind, severity, extra = {}) => ({
+ kind,
+ severity,
+ project: extra.project ?? "proj",
+ target: extra.target ?? "t",
+ why: extra.why ?? `${kind} why`,
+ href: extra.href ?? "/browse/proj",
+ at: extra.at ?? 0,
+ ...extra,
+});
+
+test("each kind lands in its group, in the brief's order", () => {
+ const cases = [
+ ["research-proposal", "open", "your-call", "spend"],
+ ["iteration-failed", "open", "your-call", "spend"],
+ ["iteration-ready", "open", "review", "review"],
+ ["claim-unadjudicated", "blocking", "blocking", "fix"],
+ ["unreadable-notes", "blocking", "blocking", "fix"],
+ ["open-note", "open", "notes", "note"],
+ ["link-ambiguous", "open", "open", "choose"],
+ ["unjudged-variant", "open", "open", "choose"],
+ ["looks-done", "open", "ready-to-finish", "finish"],
+ ["loudness", "info", "quiet", "info"],
+ ["unbuilt", "info", "quiet", "info"],
+ ];
+ for (const [kind, severity, group, category] of cases) {
+ assert.equal(groupOf({ kind, severity }), group, kind);
+ assert.equal(categoryOf({ kind, severity }), category, kind);
+ }
+ assert.deepEqual(GROUP_IDS, ["your-call", "review", "blocking", "notes", "open", "ready-to-finish", "quiet"]);
+});
+
+test("ranking: group order, proposals before failed runs, newest first, hidden last", () => {
+ const items = annotate(
+ [
+ row("loudness", "info", { at: 9 }),
+ row("looks-done", "open", { at: 8 }),
+ row("open-note", "open", { at: 7 }),
+ row("claim-unadjudicated", "blocking", { at: 1, project: "old" }),
+ row("claim-unadjudicated", "blocking", { at: 5, project: "new" }),
+ row("iteration-ready", "open", { at: 6 }),
+ row("iteration-failed", "open", { at: 10 }),
+ row("research-proposal", "open", { at: 2 }),
+ row("clip-no-cues", "blocking", { at: 99, project: "parked-one" }),
+ ],
+ { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:parked-one" ? "parked" : "active") },
+ );
+ const ranked = rankDecisions(items).map((d) => `${d.kind}:${d.project}`);
+ assert.deepEqual(ranked, [
+ "research-proposal:proj",
+ "iteration-failed:proj",
+ "iteration-ready:proj",
+ "claim-unadjudicated:new",
+ "claim-unadjudicated:old",
+ "open-note:proj",
+ "looks-done:proj",
+ "loudness:proj",
+ "clip-no-cues:parked-one",
+ ]);
+});
+
+test("annotate adds the fields and never drops, merges or reorders a row", () => {
+ const input = [row("open-note", "open", { href: "/sites/priv/x?note=n1" }), row("clip-no-cues", "blocking", { project: "gone" })];
+ const out = annotate(input, { pieceOf: (d) => (d.project === "gone" ? null : "a:priv/x"), lifecycleOf: () => "done" });
+ assert.equal(out.length, 2);
+ assert.equal(out[0].piece, "a:priv/x");
+ assert.equal(out[0].lifecycle, "done");
+ assert.equal(out[0].hidden, true);
+ // A note's action keeps its href, `note=<id>` last.
+ assert.deepEqual(out[0].action, { label: "Answer note", href: "/sites/priv/x?note=n1" });
+ assert.match(out[0].href, /note=n1$/);
+ // No piece: active, not hidden, no piece key.
+ assert.equal("piece" in out[1], false);
+ assert.equal(out[1].lifecycle, "active");
+ assert.equal(out[1].hidden, false);
+ // A piece already on the row wins.
+ assert.equal(annotate([row("x", "open", { piece: "p:keep" })], { pieceOf: () => "p:other", lifecycleOf: () => "active" })[0].piece, "p:keep");
+});
+
+test("an action names its result; an iteration's names the iteration", () => {
+ assert.equal(actionOf(row("iteration-ready", "open", { target: "i3" })).label, "Make i3 current");
+ assert.equal(actionOf(row("looks-done", "open")).label, "Mark done");
+ assert.equal(actionOf(row("never-heard-of-it", "blocking")).label, "Fix it");
+ assert.equal(actionOf(row("never-heard-of-it", "info")).label, "Open");
+});
+
+test("the summary: one card per piece and kind, counts that add up, hidden counted", () => {
+ const claims = Array.from({ length: 483 }, (_, i) => row("claim-unadjudicated", "blocking", { project: "quartering-diet", target: `c${i}`, at: i }));
+ const items = annotate(
+ [...claims, row("clip-no-cues", "blocking", { project: "other" }), row("open-note", "open", { project: "parked" }), row("loudness", "info")],
+ { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:parked" ? "parked" : "active") },
+ );
+ const groups = summarizeGroups(items);
+ const blocking = groups.find((g) => g.id === "blocking");
+ assert.equal(blocking.decisions, 484);
+ assert.equal(blocking.cards.length, 2);
+ assert.equal(blocking.cards[0].piece, "p:quartering-diet");
+ assert.equal(blocking.cards[0].count, 483);
+ assert.equal(blocking.cards[0].at, 482);
+ const notes = groups.find((g) => g.id === "notes");
+ assert.equal(notes.decisions, 0);
+ assert.equal(notes.hidden, 1);
+ assert.equal(groups.find((g) => g.id === "quiet").collapsed, true);
+ assert.equal(groups.reduce((n, g) => n + g.decisions + g.hidden, 0), items.length);
+ // Parking the video hides all 483 and leaves one card.
+ const parked = summarizeGroups(annotate(items, { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:quartering-diet" ? "done" : "active") }));
+ assert.equal(parked.find((g) => g.id === "blocking").decisions, 1);
+ assert.equal(parked.find((g) => g.id === "blocking").hidden, 483);
+});
diff --git a/umtool/lib/lifecycle.mjs b/umtool/lib/lifecycle.mjs
@@ -0,0 +1,122 @@
+// A PIECE's lifecycle: active, parked or done (plans/umtool-redesign.md,
+// "Lifecycle").
+//
+// REPORTS_ROOT/.umtool/lifecycle.json
+// { format: "umtool-lifecycle", version: 1,
+// pieces: { "<piece id>": { state, at, by? } } }
+//
+// STATE, NOT CACHE: it is the operator's word on a piece, so it lives beside
+// the projects (the walk skips dot-dirs, so it is never a project) and not in
+// CACHE_DIR. A piece with no entry is `active`.
+//
+// "Looks done" signals (a song's every cut shipped, a final mp4 plus a
+// `share-*` batch, a published article with its video) only ever SUGGEST: they
+// become a `looks-done` decision (lib/inbox.ts) and never write here. Only
+// the operator's POST /api/pieces/lifecycle does.
+//
+// One writer, serialised in-process, and every write is a whole file to a temp
+// name and a rename. A file that does not parse is never overwritten: a write
+// refuses (LifecycleUnreadable) until somebody fixes it; a read treats it as
+// "nothing set" and says so in `error`.
+//
+// Plain ESM, so a CLI and a unit test read it the way the app does.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { isPieceId } from "./pieces/ids.mjs";
+
+export const LIFECYCLE_STATES = ["active", "parked", "done"];
+export const LIFECYCLE_FORMAT = "umtool-lifecycle";
+export const LIFECYCLE_VERSION = 1;
+
+export class LifecycleError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.name = "LifecycleError";
+ this.status = status;
+ }
+}
+
+/** The file under a reports root. */
+export function lifecycleFile(reportsRoot) {
+ return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "lifecycle.json");
+}
+
+const isState = (s) => LIFECYCLE_STATES.includes(s);
+
+/**
+ * Every entry: `{ pieces: { [id]: { state, at, by? } }, error? }`. A missing
+ * file is empty; an unreadable one is empty with `error`. Entries that are not
+ * a piece id or a state are skipped, never fatal.
+ *
+ * @param {string} reportsRoot
+ */
+export async function readLifecycle(reportsRoot) {
+ let text;
+ try {
+ text = await readFile(/* turbopackIgnore: true */ lifecycleFile(reportsRoot), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return { pieces: {} };
+ return { pieces: {}, error: `lifecycle.json cannot be read: ${err?.message ?? err}` };
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ return { pieces: {}, error: `lifecycle.json is not JSON: ${err.message}` };
+ }
+ if (!raw || typeof raw !== "object" || raw.format !== LIFECYCLE_FORMAT || typeof raw.pieces !== "object" || !raw.pieces) {
+ return { pieces: {}, error: "lifecycle.json is not a umtool-lifecycle file" };
+ }
+ const pieces = {};
+ for (const [id, e] of Object.entries(raw.pieces)) {
+ if (!isPieceId(id) || !e || typeof e !== "object" || !isState(e.state)) continue;
+ pieces[id] = { state: e.state, at: typeof e.at === "string" ? e.at : "", ...(typeof e.by === "string" ? { by: e.by } : {}) };
+ }
+ return { pieces };
+}
+
+/** A piece's state in a read: its entry's, else `active`. */
+export function lifecycleOf(read, id) {
+ return read?.pieces?.[id]?.state ?? "active";
+}
+
+let chain = Promise.resolve();
+
+/**
+ * Set one piece's state. Answers the entry written.
+ *
+ * @param {string} reportsRoot
+ * @param {string} id a piece id (lib/pieces/ids.mjs)
+ * @param {string} state active | parked | done
+ * @param {{ by?: string, now?: Date }} [opts]
+ */
+export function setLifecycle(reportsRoot, id, state, { by, now } = {}) {
+ if (!isPieceId(id)) return Promise.reject(new LifecycleError(`not a piece id: ${JSON.stringify(id)}`));
+ if (!isState(state)) return Promise.reject(new LifecycleError(`state is ${LIFECYCLE_STATES.join(" | ")}, not ${JSON.stringify(state)}`));
+ const run = chain.then(() => write(reportsRoot, id, state, by, now ?? new Date()));
+ // The next write waits for this one, whether it failed or not.
+ chain = run.catch(() => {});
+ return run;
+}
+
+async function write(reportsRoot, id, state, by, now) {
+ const file = lifecycleFile(reportsRoot);
+ const read = await readLifecycle(reportsRoot);
+ if (read.error) throw new LifecycleError(`${read.error}; fix or remove ${file} first`, 409);
+ const entry = { state, at: now.toISOString(), ...(by ? { by } : {}) };
+ const doc = {
+ format: LIFECYCLE_FORMAT,
+ version: LIFECYCLE_VERSION,
+ pieces: Object.fromEntries(Object.entries({ ...read.pieces, [id]: entry }).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
+ };
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+ return { id, ...entry };
+}
diff --git a/umtool/lib/lifecycle.test.mjs b/umtool/lib/lifecycle.test.mjs
@@ -0,0 +1,74 @@
+// A piece's lifecycle, read and written in a temp reports root.
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { LIFECYCLE_STATES, lifecycleFile, lifecycleOf, readLifecycle, setLifecycle } from "./lifecycle.mjs";
+
+const root = () => mkdtemp(path.join(tmpdir(), "umtool-lifecycle-"));
+
+test("absent is active, and a read never creates the file", async () => {
+ const r = await root();
+ const read = await readLifecycle(r);
+ assert.deepEqual(read, { pieces: {} });
+ assert.equal(lifecycleOf(read, "a:articles/zeta"), "active");
+ assert.deepEqual(await readdir(r), []);
+});
+
+test("a write round-trips, with when and by whom", async () => {
+ const r = await root();
+ const now = new Date("2026-10-13T12:00:00.000Z");
+ const e = await setLifecycle(r, "p:quartering-diet", "done", { by: "operator", now });
+ assert.deepEqual(e, { id: "p:quartering-diet", state: "done", at: "2026-10-13T12:00:00.000Z", by: "operator" });
+ await setLifecycle(r, "a:articles/zeta", "parked", { now });
+ const read = await readLifecycle(r);
+ assert.equal(lifecycleOf(read, "p:quartering-diet"), "done");
+ assert.equal(lifecycleOf(read, "a:articles/zeta"), "parked");
+ assert.equal(read.pieces["a:articles/zeta"].by, undefined);
+ const doc = JSON.parse(await readFile(lifecycleFile(r), "utf8"));
+ assert.equal(doc.format, "umtool-lifecycle");
+ assert.deepEqual(Object.keys(doc.pieces), ["a:articles/zeta", "p:quartering-diet"]);
+ // Back to active is a write like any other.
+ await setLifecycle(r, "p:quartering-diet", "active", { now });
+ assert.equal(lifecycleOf(await readLifecycle(r), "p:quartering-diet"), "active");
+ // No temp file is left beside it.
+ assert.deepEqual(await readdir(path.dirname(lifecycleFile(r))), ["lifecycle.json"]);
+});
+
+test("concurrent writes all land", async () => {
+ const r = await root();
+ const ids = Array.from({ length: 12 }, (_, i) => `p:project-${i}`);
+ await Promise.all(ids.map((id, i) => setLifecycle(r, id, LIFECYCLE_STATES[i % 3])));
+ const read = await readLifecycle(r);
+ for (const [i, id] of ids.entries()) assert.equal(lifecycleOf(read, id), LIFECYCLE_STATES[i % 3]);
+});
+
+test("junk ids and states are refused, and nothing is written", async () => {
+ const r = await root();
+ await assert.rejects(setLifecycle(r, "articles/zeta", "done"), /not a piece id/);
+ await assert.rejects(setLifecycle(r, "p:../x", "done"), /not a piece id/);
+ await assert.rejects(setLifecycle(r, "p:x", "shipped"), /state is active \| parked \| done/);
+ assert.deepEqual(await readdir(r), []);
+});
+
+test("an unreadable file is reported, and never overwritten", async () => {
+ const r = await root();
+ await mkdir(path.dirname(lifecycleFile(r)), { recursive: true });
+ await writeFile(lifecycleFile(r), "{ not json");
+ const read = await readLifecycle(r);
+ assert.deepEqual(read.pieces, {});
+ assert.match(read.error, /not JSON/);
+ await assert.rejects(setLifecycle(r, "p:x", "done"), (err) => err.status === 409);
+ assert.equal(await readFile(lifecycleFile(r), "utf8"), "{ not json");
+});
+
+test("entries that are not a piece or a state are skipped on read", async () => {
+ const r = await root();
+ await mkdir(path.dirname(lifecycleFile(r)), { recursive: true });
+ await writeFile(
+ lifecycleFile(r),
+ JSON.stringify({ format: "umtool-lifecycle", version: 1, pieces: { "p:ok": { state: "parked", at: "x" }, junk: { state: "done" }, "p:bad": { state: "gone" } } }),
+ );
+ assert.deepEqual(Object.keys((await readLifecycle(r)).pieces), ["p:ok"]);
+});
diff --git a/umtool/lib/lifecycle.ts b/umtool/lib/lifecycle.ts
@@ -0,0 +1,35 @@
+import { REPORTS_ROOT } from "./paths";
+import {
+ LIFECYCLE_STATES as STATES,
+ LifecycleError,
+ lifecycleOf as lifecycleOfRead,
+ readLifecycle as readAt,
+ setLifecycle as setAt,
+} from "./lifecycle.mjs";
+
+// The app's view of lib/lifecycle.mjs, typed and bound to REPORTS_ROOT. The
+// logic, the file format and the rules are there (plain ESM, unit-tested).
+
+export type LifecycleState = "active" | "parked" | "done";
+export type LifecycleEntry = { state: LifecycleState; at: string; by?: string };
+export type LifecycleRead = { pieces: Record<string, LifecycleEntry>; error?: string };
+
+export const LIFECYCLE_STATES = STATES as LifecycleState[];
+export { LifecycleError };
+
+export const isLifecycleState = (s: unknown): s is LifecycleState => (LIFECYCLE_STATES as unknown[]).includes(s);
+
+export async function readLifecycle(): Promise<LifecycleRead> {
+ return (await readAt(REPORTS_ROOT)) as LifecycleRead;
+}
+
+export function lifecycleOf(read: LifecycleRead, id: string): LifecycleState {
+ return lifecycleOfRead(read, id) as LifecycleState;
+}
+
+export async function setLifecycle(id: string, state: LifecycleState, by?: string): Promise<LifecycleEntry & { id: string }> {
+ return (await setAt(REPORTS_ROOT, id, state, { by })) as LifecycleEntry & { id: string };
+}
+
+/** Parked and done pieces are out of the way: their decisions are `hidden`. */
+export const isQuiet = (state: LifecycleState): boolean => state !== "active";
diff --git a/umtool/lib/pieces.ts b/umtool/lib/pieces.ts
@@ -0,0 +1,294 @@
+import { listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry";
+import { ARTICLES_KEY, REPORTS_ROOT } from "./paths";
+import { articleHref } from "./articles/href";
+import { listSiteRows, readStoreRow, sitesPaths, type ArticleRow } from "./articles/sites";
+import { iterationProjects, linkedProjects, linksCacheEpoch, videoProjects } from "./articles/links.mjs";
+import { listProjects } from "./projects";
+import type { ProjectSummary } from "./project-types";
+import { listBatches } from "./report/deliver.mjs";
+import { articleOfDecisionProject, articlePieceId, projectPieceId } from "./pieces/ids.mjs";
+import { lifecycleOf, readLifecycle, type LifecycleRead, type LifecycleState } from "./lifecycle";
+import type { Decision } from "./decisions";
+
+export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId } from "./pieces/ids.mjs";
+
+// ---------------------------------------------------------------------------
+// PIECES (plans/umtool-redesign.md): the unit the operator works on.
+//
+// an ARTICLE piece `a:<site>/<report>` -- a site's report, or one of the
+// article store's (`articles/<id>`, published, draft or
+// still in the making) -- plus every video project linked
+// to it (lib/articles/links.mjs: its iterations, then a
+// manifest that names it, then a unique slug)
+// a PROJECT piece `p:<id>` -- a project under REPORTS_ROOT linked to no
+// article: a song, a hand-made report video, a sweep
+//
+// A project linked to two articles belongs to the first that claims it, by
+// strength (iteration, then manifest, then slug) and then in list order --
+// private sites first, as /sites lists them.
+//
+// SERVER ONLY. The article side re-reads every report.json (lib/articles/
+// sites.ts), so the graph is memoised for MEMO_MS -- and dropped at once by
+// anything that clears the links cache (a project or an article deleted), the
+// way clearLinksCache already drops the links. The lifecycle is NOT memoised:
+// it is one small file, and a park has to show on the next read.
+// ---------------------------------------------------------------------------
+
+export type PieceKind = "article" | "project";
+
+export type PieceProject = {
+ id: string;
+ title: string;
+ via: "iteration" | "manifest" | "slug";
+ /** The one the article's Cut opens (current.video's, else the first linked). */
+ cut: boolean;
+ /** The project's state (draft … built, shipped, stale), or null when the walk did not summarise it. */
+ state: string | null;
+ href: string;
+};
+
+export type Piece = {
+ id: string;
+ kind: PieceKind;
+ title: string;
+ /** An article's site (`articles` for the store), else null. */
+ site: string | null;
+ report: string | null;
+ /** A project piece's project id, else null. */
+ project: string | null;
+ href: string;
+ /** An article's: published, draft, or in the making (iterations, no report.json). */
+ status: "published" | "draft" | "in the making" | null;
+ /**
+ * Where it is. An article: research (in the making) → article (no video) →
+ * video → deliver (looks done). A project: its own state (draft, windows,
+ * fetched, built, shipped, stale).
+ */
+ stage: string;
+ projects: PieceProject[];
+ /** Slug matches nobody has chosen between (link-ambiguous). */
+ possible: { id: string; title: string }[];
+ /** Iterations whose project is outside REPORTS_ROOT: not reachable here. */
+ unreachable: { n: number; dir: string }[];
+ /** Why it looks done, when it does. A suggestion: it never sets the lifecycle. */
+ looksDone: string[];
+ newestMs: number;
+};
+
+export type PieceWithLifecycle = Piece & { lifecycle: LifecycleState; lifecycleAt: string | null; lifecycleBy: string | null };
+
+export type PieceGraph = {
+ pieces: Piece[];
+ byId: Map<string, Piece>;
+ /** Project id → the piece it belongs to. */
+ pieceOfProject: Map<string, string>;
+ /** A project's basename → its id, when the name is unique (the song routes' alias). */
+ projectByName: Map<string, string>;
+};
+
+const MEMO_MS = 15_000;
+let memo: { at: number; epoch: number; value: Promise<PieceGraph> } | null = null;
+
+/** Drop the memo (a test, or a write that changed what an article links). */
+export function clearPiecesCache(): void {
+ memo = null;
+}
+
+export function readPieceGraph(): Promise<PieceGraph> {
+ const epoch = linksCacheEpoch();
+ if (memo && memo.epoch === epoch && Date.now() - memo.at < MEMO_MS) return memo.value;
+ const value = buildGraph();
+ const entry = { at: Date.now(), epoch, value };
+ memo = entry;
+ value.catch(() => {
+ if (memo === entry) memo = null;
+ });
+ return value;
+}
+
+type LinkRow = { id: string; title: string; via?: "iteration" | "manifest" | "slug" };
+type ArticleIn = {
+ site: string;
+ id: string;
+ title: string;
+ status: Piece["status"];
+ hasVideo: boolean;
+ mtimeMs: number;
+ linked: LinkRow[];
+ possible: { id: string; title: string }[];
+ cut: string | null;
+ unreachable: { n: number; dir: string }[];
+};
+
+const STRENGTH = { iteration: 0, manifest: 1, slug: 2 } as const;
+
+function fromRow(a: ArticleRow): ArticleIn {
+ return {
+ site: a.site,
+ id: a.id,
+ title: a.title,
+ status: a.status,
+ hasVideo: a.hasVideo,
+ mtimeMs: a.mtimeMs ?? 0,
+ linked: a.projects.linked,
+ possible: a.projects.possible.map((p) => ({ id: p.id, title: p.title })),
+ cut: a.projects.cut ?? null,
+ unreachable: a.projects.unreachable ?? [],
+ };
+}
+
+async function pendingArticles(): Promise<ArticleIn[]> {
+ const ids = await listPendingArticles(sitesPaths()).catch(() => [] as string[]);
+ const projects = await videoProjects(REPORTS_ROOT);
+ return Promise.all(
+ ids.map(async (id) => {
+ const links = await linkedProjects(ARTICLES_KEY, id, { projects });
+ return {
+ site: ARTICLES_KEY,
+ id,
+ title: id,
+ status: "in the making" as const,
+ hasVideo: false,
+ mtimeMs: 0,
+ linked: links.linked as LinkRow[],
+ possible: (links.possible as LinkRow[]).map((p) => ({ id: p.id, title: p.title })),
+ cut: links.cut ?? null,
+ unreachable: links.unreachable ?? [],
+ };
+ }),
+ );
+}
+
+/** Why a project looks finished, or null. Kind-blind: it reads the shared state vocabulary. */
+async function projectLooksDone(p: ProjectSummary): Promise<string | null> {
+ // A song's derived `shipped` (every cut present, lib/projects/song.mjs).
+ if (p.state === "shipped") return `${p.id}: every cut shipped`;
+ // A final video, current with its manifest, AND a share batch made from it.
+ if (p.state === "built") {
+ const batches = await listBatches(p.dir).catch(() => [] as { name: string }[]);
+ if (batches.length) return `${p.id}: final video and ${batches.map((b: { name: string }) => b.name).join(", ")}`;
+ }
+ return null;
+}
+
+async function buildGraph(): Promise<PieceGraph> {
+ // The article side must never take the decisions down with it: a site whose
+ // site.json does not read is an article list without that site, not a 500.
+ const [sites, store, pending, summaries, its] = await Promise.all([
+ listSiteRows().catch(() => []),
+ readStoreRow().catch(() => ({ articles: [] as ArticleRow[] })),
+ pendingArticles().catch(() => [] as ArticleIn[]),
+ listProjects(),
+ iterationProjects().catch(() => new Map<string, { current: boolean }[]>()),
+ ]);
+ const articles: ArticleIn[] = [
+ ...sites.flatMap((s) => s.articles.map(fromRow)),
+ ...store.articles.map(fromRow),
+ ...pending,
+ ];
+ const summaryOf = new Map(summaries.map((p) => [p.id, p]));
+
+ // Who owns each linked project: the strongest link, then list order.
+ const pieceOfProject = new Map<string, string>();
+ const claims = articles.flatMap((a, order) =>
+ a.linked.map((p) => ({ project: p.id, piece: articlePieceId(a.site, a.id), strength: STRENGTH[p.via ?? "slug"], order })),
+ );
+ claims.sort((x, y) => x.strength - y.strength || x.order - y.order);
+ for (const c of claims) if (!pieceOfProject.has(c.project)) pieceOfProject.set(c.project, c.piece);
+
+ const doneCache = new Map<string, Promise<string | null>>();
+ const looksDoneOf = (id: string) => {
+ const s = summaryOf.get(id);
+ if (!s) return Promise.resolve(null);
+ let hit = doneCache.get(id);
+ if (!hit) doneCache.set(id, (hit = projectLooksDone(s)));
+ return hit;
+ };
+
+ const pieces: Piece[] = [];
+ for (const a of articles) {
+ const id = articlePieceId(a.site, a.id);
+ const projects: PieceProject[] = a.linked.map((p) => ({
+ id: p.id,
+ title: p.title,
+ via: p.via ?? "slug",
+ cut: p.id === a.cut,
+ state: summaryOf.get(p.id)?.state ?? null,
+ href: `/browse/${p.id}`,
+ }));
+ const looksDone: string[] = [];
+ const currentVideo = a.site === ARTICLES_KEY && (its.get(a.id) ?? []).some((x: { current: boolean }) => x.current);
+ if (a.status === "published" && (a.hasVideo || currentVideo)) looksDone.push("published with its video");
+ for (const p of projects) {
+ if (pieceOfProject.get(p.id) !== id) continue;
+ const why = await looksDoneOf(p.id);
+ if (why) looksDone.push(why);
+ }
+ const newestMs = Math.max(a.mtimeMs, ...projects.map((p) => summaryOf.get(p.id)?.newestMtimeMs ?? 0));
+ pieces.push({
+ id,
+ kind: "article",
+ title: a.title,
+ site: a.site,
+ report: a.id,
+ project: null,
+ href: articleHref({ site: a.site, id: a.id }),
+ status: a.status,
+ stage: a.status === "in the making" ? "research" : !projects.length ? "article" : looksDone.length ? "deliver" : "video",
+ projects,
+ possible: a.possible,
+ unreachable: a.unreachable,
+ looksDone,
+ newestMs,
+ });
+ }
+
+ for (const p of summaries) {
+ if (pieceOfProject.has(p.id)) continue;
+ const why = await looksDoneOf(p.id);
+ pieces.push({
+ id: projectPieceId(p.id),
+ kind: "project",
+ title: p.title,
+ site: null,
+ report: null,
+ project: p.id,
+ href: `/browse/${p.id}`,
+ status: null,
+ stage: p.state,
+ projects: [],
+ possible: [],
+ unreachable: [],
+ looksDone: why ? [why] : [],
+ newestMs: p.newestMtimeMs,
+ });
+ pieceOfProject.set(p.id, projectPieceId(p.id));
+ }
+
+ const names = new Map<string, string[]>();
+ for (const p of summaries) names.set(p.name, [...(names.get(p.name) ?? []), p.id]);
+ const projectByName = new Map([...names].filter(([, ids]) => ids.length === 1).map(([n, ids]) => [n, ids[0]]));
+
+ pieces.sort((a, b) => b.newestMs - a.newestMs || a.id.localeCompare(b.id));
+ return { pieces, byId: new Map(pieces.map((p) => [p.id, p])), pieceOfProject, projectByName };
+}
+
+/** The piece a decision row is about, or null when nothing on disk owns it. */
+export function pieceOfDecision(d: Decision, graph: PieceGraph): string | null {
+ if (d.piece) return d.piece;
+ if (d.projectKind === "article") {
+ const a = articleOfDecisionProject(d.project);
+ return a ? articlePieceId(a.site, a.report) : null;
+ }
+ const id = graph.pieceOfProject.has(d.project) ? d.project : graph.projectByName.get(d.project);
+ return id ? (graph.pieceOfProject.get(id) ?? null) : null;
+}
+
+/** Every piece, with its lifecycle (read now, never memoised). */
+export async function listPieces(read?: LifecycleRead): Promise<PieceWithLifecycle[]> {
+ const [graph, life] = await Promise.all([readPieceGraph(), read ? Promise.resolve(read) : readLifecycle()]);
+ return graph.pieces.map((p) => {
+ const e = life.pieces[p.id];
+ return { ...p, lifecycle: lifecycleOf(life, p.id), lifecycleAt: e?.at ?? null, lifecycleBy: e?.by ?? null };
+ });
+}
diff --git a/umtool/lib/pieces/ids.mjs b/umtool/lib/pieces/ids.mjs
@@ -0,0 +1,94 @@
+// A PIECE's id (plans/umtool-redesign.md, "Data and engine rules").
+//
+// A piece is the unit the operator works on: an article plus the video
+// project(s) made from it, or a project that belongs to no article. Its id is
+// NAMESPACED, because the bare spellings collide: `resolveTarget`
+// (lib/annotations/targets.mjs) reads a two-segment `x/y` as an article when
+// such a report exists and as a project otherwise -- and a project id is a
+// path, so `articles/zeta` can be either.
+//
+// a:<site>/<report> an article; `site` may be `articles` (the store's)
+// p:<projectId> a project under REPORTS_ROOT, by its path id
+// c:<case> a research case (reserved: research boards, R2)
+//
+// Pure, no imports with side effects: a client component may parse an id.
+
+/** A site or report id: lib/paths.mjs SEGMENT_RE (a test holds them equal). */
+export const PIECE_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+/** One segment of a project id: lib/projects/walk.mjs isSegment (a test holds them equal). */
+const PROJECT_SEGMENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+const projectSegment = (v) => PROJECT_SEGMENT_RE.test(v) && !v.includes("..");
+
+export const PIECE_KINDS = ["article", "project", "case"];
+const PREFIX = { article: "a", project: "p", case: "c" };
+
+/**
+ * Parse a piece id, or null when it is not one. Never guesses: a bare
+ * `site/report` or project id is null.
+ *
+ * @param {unknown} id
+ * @returns {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string } | null}
+ */
+export function parsePieceId(id) {
+ if (typeof id !== "string" || id.length > 512) return null;
+ const m = /^([apc]):(.+)$/.exec(id);
+ if (!m) return null;
+ const [, ns, rest] = m;
+ if (ns === "a") {
+ const parts = rest.split("/");
+ if (parts.length !== 2 || !parts.every((s) => PIECE_SEGMENT_RE.test(s))) return null;
+ return { kind: "article", site: parts[0], report: parts[1] };
+ }
+ if (ns === "p") {
+ const parts = rest.split("/");
+ if (!parts.length || !parts.every(projectSegment)) return null;
+ return { kind: "project", project: rest };
+ }
+ if (!PIECE_SEGMENT_RE.test(rest)) return null;
+ return { kind: "case", case: rest };
+}
+
+/** True when `id` is a piece id. */
+export const isPieceId = (id) => parsePieceId(id) !== null;
+
+/**
+ * The id for a parsed piece. Throws on parts that would not parse back: an id
+ * that cannot round-trip is a bug at the caller, not a value to pass along.
+ *
+ * @param {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string }} p
+ */
+export function formatPieceId(p) {
+ const id =
+ p?.kind === "article"
+ ? `${PREFIX.article}:${p.site}/${p.report}`
+ : p?.kind === "project"
+ ? `${PREFIX.project}:${p.project}`
+ : p?.kind === "case"
+ ? `${PREFIX.case}:${p.case}`
+ : null;
+ if (id === null || !isPieceId(id)) throw new Error(`not a piece: ${JSON.stringify(p)}`);
+ return id;
+}
+
+/** `a:<site>/<report>`. */
+export const articlePieceId = (site, report) => formatPieceId({ kind: "article", site, report });
+
+/** `p:<projectId>`. */
+export const projectPieceId = (project) => formatPieceId({ kind: "project", project });
+
+/** `c:<case>`. */
+export const casePieceId = (slug) => formatPieceId({ kind: "case", case: slug });
+
+/**
+ * An article decision's `project` (`sites/<site>/<report>`, lib/decisions.ts
+ * noteDecisions) back to its article, or null. Only meaningful for a row whose
+ * `projectKind` is "article": a project may itself live under a `sites/` folder.
+ *
+ * @param {string} project
+ */
+export function articleOfDecisionProject(project) {
+ const m = /^sites\/([^/]+)\/([^/]+)$/.exec(String(project ?? ""));
+ if (!m || !PIECE_SEGMENT_RE.test(m[1]) || !PIECE_SEGMENT_RE.test(m[2])) return null;
+ return { site: m[1], report: m[2] };
+}
diff --git a/umtool/lib/pieces/ids.test.mjs b/umtool/lib/pieces/ids.test.mjs
@@ -0,0 +1,67 @@
+// Piece ids: namespaced, round-tripping, never ambiguous.
+import assert from "node:assert/strict";
+import test from "node:test";
+import { SEGMENT_RE } from "../paths.mjs";
+import { isSegment } from "../projects/walk.mjs";
+import {
+ PIECE_SEGMENT_RE,
+ articleOfDecisionProject,
+ articlePieceId,
+ casePieceId,
+ formatPieceId,
+ isPieceId,
+ parsePieceId,
+ projectPieceId,
+} from "./ids.mjs";
+
+test("each namespace parses and formats back", () => {
+ for (const id of ["a:articles/zeta", "a:priv/polemic-alpha", "p:ferret-rescue", "p:quartering-uh-song/videos/yoshi", "p:gen-projects/zeta/i1", "c:vote-rigging"]) {
+ const parsed = parsePieceId(id);
+ assert.ok(parsed, id);
+ assert.equal(formatPieceId(parsed), id);
+ }
+ assert.deepEqual(parsePieceId("a:articles/zeta"), { kind: "article", site: "articles", report: "zeta" });
+ assert.deepEqual(parsePieceId("p:quartering-uh-song/videos/yoshi"), { kind: "project", project: "quartering-uh-song/videos/yoshi" });
+ assert.deepEqual(parsePieceId("c:vote"), { kind: "case", case: "vote" });
+ assert.equal(articlePieceId("articles", "zeta"), "a:articles/zeta");
+ assert.equal(projectPieceId("articles/zeta"), "p:articles/zeta");
+ assert.equal(casePieceId("vote"), "c:vote");
+});
+
+test("a two-segment id is never ambiguous: the namespace says which", () => {
+ // resolveTarget reads `articles/zeta` as an article when the report exists
+ // and as a project otherwise. A piece id carries the answer.
+ assert.equal(parsePieceId("articles/zeta"), null);
+ assert.equal(parsePieceId("a:articles/zeta").kind, "article");
+ assert.equal(parsePieceId("p:articles/zeta").kind, "project");
+ assert.notEqual(articlePieceId("articles", "zeta"), projectPieceId("articles/zeta"));
+});
+
+test("junk is refused", () => {
+ for (const bad of [
+ "", "a:", "p:", "c:", "x:y", "A:articles/zeta", "a:articles", "a:articles/zeta/extra", "a:Articles/zeta",
+ "a:articles/../x", "p:../x", "p:a//b", "p:/abs", "p:.hidden", "p:a/..b", "p:a b", "c:Up", "c:a/b",
+ "a:articles/zeta\n", " p:x", null, undefined, 42, {}, `p:${"a/".repeat(300)}a`,
+ ]) {
+ assert.equal(parsePieceId(bad), null, JSON.stringify(bad));
+ assert.equal(isPieceId(bad), false);
+ }
+ assert.throws(() => formatPieceId({ kind: "article", site: "x", report: "a/b" }));
+ assert.throws(() => projectPieceId("../etc"));
+ assert.throws(() => formatPieceId({ kind: "nope" }));
+});
+
+test("the segment rules are the ones the rest of umtool uses", () => {
+ assert.equal(PIECE_SEGMENT_RE.source, SEGMENT_RE.source);
+ for (const seg of ["ferret-rescue", "i1", "Mixed_Case.v2", ".hidden", "a..b", "a b", "-x", "x-"]) {
+ assert.equal(isPieceId(`p:${seg}`), isSegment(seg), seg);
+ }
+});
+
+test("an article decision's project names its article", () => {
+ assert.deepEqual(articleOfDecisionProject("sites/articles/zeta"), { site: "articles", report: "zeta" });
+ assert.deepEqual(articleOfDecisionProject("sites/priv/polemic-alpha"), { site: "priv", report: "polemic-alpha" });
+ assert.equal(articleOfDecisionProject("ferret-rescue"), null);
+ assert.equal(articleOfDecisionProject("sites/priv"), null);
+ assert.equal(articleOfDecisionProject("sites/priv/a/b"), null);
+});
diff --git a/umtool/lib/projects.ts b/umtool/lib/projects.ts
@@ -57,10 +57,24 @@ export const ALL_DECISION_KINDS: string[] = [
// not changed and is thrown away the moment it has. That is the same rule the
// export build's incremental signatures follow, and it is the reason no index
// is needed yet at twelve projects.
+//
+// The caches live on globalThis, not in module scope: Next bundles each route
+// handler and page separately, so a module-level cache is one copy PER BUNDLE,
+// and invalidateProjects() called from an API route never reached the page that
+// renders next -- a project scaffolded a moment ago 404'd for up to a second.
// ---------------------------------------------------------------------------
-let walkCache: { at: number; refs: ProjectRef[] } | null = null;
-const summaryCache = new Map<string, { sig: string; value: ProjectSummary }>();
-const decisionCache = new Map<string, { sig: string; value: Decision[] }>();
+type ProjectCaches = {
+ walk: { at: number; refs: ProjectRef[] } | null;
+ summary: Map<string, { sig: string; value: ProjectSummary }>;
+ decision: Map<string, { sig: string; value: Decision[] }>;
+};
+const CACHES = ((globalThis as { __umtoolProjectCaches?: ProjectCaches }).__umtoolProjectCaches ??= {
+ walk: null,
+ summary: new Map(),
+ decision: new Map(),
+});
+const summaryCache = CACHES.summary;
+const decisionCache = CACHES.decision;
// ---------------------------------------------------------------------------
// The persistent index, opened once and held.
@@ -84,15 +98,16 @@ export const indexHealth = () => ({ ...lastIndexHits });
/** Drop every cache. The CLI's `scan` and the e2e suite want this. */
export function invalidateProjects(): void {
- walkCache = null;
+ CACHES.walk = null;
summaryCache.clear();
decisionCache.clear();
}
export async function projectRefs(): Promise<ProjectRef[]> {
- if (walkCache && Date.now() - walkCache.at < 1000) return walkCache.refs;
+ const hit = CACHES.walk;
+ if (hit && Date.now() - hit.at < 1000) return hit.refs;
const refs = (await walkProjects(REPORTS_ROOT)) as ProjectRef[];
- walkCache = { at: Date.now(), refs };
+ CACHES.walk = { at: Date.now(), refs };
return refs;
}
diff --git a/umtool/lib/theme.ts b/umtool/lib/theme.ts
@@ -0,0 +1,31 @@
+// The theme choice: the system's (no cookie), or an explicit light or dark.
+//
+// Stored in a cookie rather than localStorage because the ROOT LAYOUT reads it:
+// the server stamps `data-theme` on <html> before a byte of CSS is applied, so an
+// explicit choice paints right on the first frame -- no inline script, no flash,
+// nothing for hydration to correct. "auto" is the absence of the cookie, which is
+// also what a cleared or refused cookie reads as.
+//
+// Pure, so the client control and the server layout share it.
+
+export const THEME_COOKIE = "umtool-theme";
+
+export const THEMES = ["auto", "light", "dark"] as const;
+export type Theme = (typeof THEMES)[number];
+
+/** A cookie value read back is untrusted: anything but light/dark is auto. */
+export function parseTheme(v: string | undefined | null): Theme {
+ return v === "light" || v === "dark" ? v : "auto";
+}
+
+/** The `data-theme` attribute for a choice; auto leaves the system in charge. */
+export function themeAttr(t: Theme): "light" | "dark" | undefined {
+ return t === "auto" ? undefined : t;
+}
+
+/** One year, path-wide; Lax because nothing cross-site ever needs it. */
+export function themeCookie(t: Theme): string {
+ return t === "auto"
+ ? `${THEME_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`
+ : `${THEME_COOKIE}=${t}; Path=/; Max-Age=31536000; SameSite=Lax`;
+}
diff --git a/umtool/next.config.ts b/umtool/next.config.ts
@@ -1,5 +1,6 @@
import path from "node:path";
import type { NextConfig } from "next";
+import { nextRedirects } from "./redirects.mjs";
const nextConfig: NextConfig = {
// A SECOND dev server for the e2e suite, alongside the one being used.
@@ -18,6 +19,15 @@ const nextConfig: NextConfig = {
// fail the whole module graph. Every page importing lib/projects then 500s
// with "Can't resolve 'cbor-x'", which names a package nothing here uses.
serverExternalPackages: ["lmdb"],
+ // The dev indicator defaults to the bottom-left corner, which is the rail's
+ // foot -- it sat over the theme control on the e2e dev server. (The live
+ // umtool runs `next start`, which shows no indicator.)
+ devIndicators: { position: "bottom-right" },
+ // Every old page address and where it lives now: ONE table, redirects.mjs,
+ // which e2e/redirects.spec.ts (P3) reads too. Empty until P3 moves a page.
+ async redirects() {
+ return nextRedirects();
+ },
// No route's trace may list the e2e fixture (.e2e-song, where
// e2e/fixtures/make-fixture.mjs links the song data; .e2e-song-media, the
// storage spec's media root), the e2e server's own
diff --git a/umtool/redirects.mjs b/umtool/redirects.mjs
@@ -0,0 +1,48 @@
+// ---------------------------------------------------------------------------
+// Every old umtool page address, and where it lives now. EMPTY until P3.
+//
+// ONE table, read by two things (plans/umtool-redesign.md, "Redirects"):
+// - next.config.ts's `redirects()`, which answers them. Next checks redirects
+// BEFORE the filesystem, so a row here beats a page still at the old path,
+// and the query string is passed through to the destination unchanged.
+// - e2e/redirects.spec.ts (P3), which requests every `source` with
+// `maxRedirects: 0` and checks the status and the Location.
+//
+// A row is Next's own redirect shape
+// (node_modules/next/dist/docs/01-app/03-api-reference/05-config/01-next-config-js/redirects.md):
+//
+// {
+// source: "/browse/:path*", // path-to-regexp; `:x*` zero or more segments
+// destination: "/projects/:path*", // matched parameters carry over
+// permanent: false, // 307 until P6, then 308 -- a browser
+// // caches a 308 forever, so a wrong one
+// // cannot be taken back
+// has: [{ type: "query", key: "from" }], // optional: only when the query has `from`
+// phase: "P3", // ours, not Next's: which phase added it.
+// // next.config.ts strips it.
+// }
+//
+// ORDER MATTERS: Next takes the first match, so a reserved `/browse/<tool>` row
+// goes BEFORE the `/browse/:path*` catch-all. Every page address lib/hrefs.ts
+// builds is either still served or has a row here.
+// ---------------------------------------------------------------------------
+
+/** @typedef {{ type: "query" | "header" | "cookie", key: string, value?: string }} RedirectMatch */
+/**
+ * @typedef {{
+ * source: string,
+ * destination: string,
+ * permanent: boolean,
+ * has?: RedirectMatch[],
+ * missing?: RedirectMatch[],
+ * phase: string,
+ * }} RedirectRow
+ */
+
+/** @type {RedirectRow[]} */
+export const REDIRECTS = [];
+
+/** The rows in the shape next.config.ts's `redirects()` returns. */
+export function nextRedirects() {
+ return REDIRECTS.map(({ phase: _phase, ...row }) => row);
+}