Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit b719d8ad3172b3c17c8d041294bc87c092f6b4f6
parent 351127a25b1ed907f0746b1911eb3e7ee551dd6c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 08:43:28 -0400

Merge ux/integration (P5 live, e8d25fe8) into ux/p4a2; one generation-policy href

- The plan: both records kept (P5's then P4a-2's), one status row per phase.
- hrefs.test: Create's newArticleHref beside the article piece's assertions.
- generationSettingsHref folded into generationPolicyHref (/settings/generation):
  the article piece's chip and piece.spec use it, as P5's callers do.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 4++++
Mpackage.json | 2+-
Mplans/umtool-redesign.md | 165++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/app/api/doctor/route.ts | 15++++++++++-----
Aumtool/app/api/system/_respond.ts | 17+++++++++++++++++
Aumtool/app/api/system/index/route.ts | 22++++++++++++++++++++++
Aumtool/app/api/system/storage/route.ts | 23+++++++++++++++++++++++
Dumtool/app/articles/new/page.tsx | 30------------------------------
Aumtool/app/create/page.tsx | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/drafts/page.tsx | 8+++++---
Mumtool/app/page.tsx | 21+++++----------------
Aumtool/app/settings/generation/page.tsx | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/settings/page.tsx | 7+++----
Mumtool/app/settings/system/page.tsx | 30++++++++++++++++++++++--------
Mumtool/app/work/page.tsx | 14+++++---------
Mumtool/bin/umtool.mjs | 28++++------------------------
Mumtool/components/AppNav.tsx | 5++++-
Mumtool/components/NewProjectMenu.tsx | 294+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mumtool/components/articles/NewArticleForm.tsx | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Aumtool/components/create/CreateView.tsx | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/create/forms.tsx | 335+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/piece/PolicyChip.tsx | 7+++----
Mumtool/components/shell/AppRail.tsx | 2+-
Mumtool/components/shell/CreateMenu.tsx | 63++++++++++++++++-----------------------------------------------
Mumtool/components/shell/JumpPalette.tsx | 16++++++++++++----
Aumtool/components/system/ActionPlan.tsx | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/system/Maintenance.tsx | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/ui/lit-list.tsx | 10+++++++++-
Mumtool/e2e/article-new.spec.ts | 74++++++++++++++++++++++++--------------------------------------------------
Aumtool/e2e/create.spec.ts | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/inbox.spec.ts | 13+++++++++----
Mumtool/e2e/piece.spec.ts | 2+-
Mumtool/e2e/projects.spec.ts | 2+-
Mumtool/e2e/redirects.spec.ts | 16+++++++++++-----
Aumtool/e2e/settings.spec.ts | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/shell.spec.ts | 11++++++-----
Aumtool/lib/create.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/create/create.test.mjs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/create/estimate.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/create/iterations.mjs | 26++++++++++++++++++++++++++
Aumtool/lib/create/policy.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.test.mjs | 16++++++++++++----
Mumtool/lib/hrefs.ts | 51++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/projects.ts | 16++++++++++++++++
Aumtool/lib/projects/create.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/settings/settings.test.mjs | 31+++++++++++++++++++++++++++++++
Aumtool/lib/settings/spend.mjs | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/system/actions.ts | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/system/plan-types.ts | 27+++++++++++++++++++++++++++
Aumtool/lib/system/roots.mjs | 27+++++++++++++++++++++++++++
Aumtool/lib/system/storage-rows.ts | 36++++++++++++++++++++++++++++++++++++
Mumtool/redirects.mjs | 13++++++++++---
52 files changed, 3054 insertions(+), 368 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog ## [Unreleased] +- **umtool has Create: `/create`, "What are you making?"** One list of lines — Research a question · an article from a question or from a board · a video from an article, a board, a recording or a sweep report · a song — each opening its form under it, each a shell over a writer that already existed: a case (the board opens), a sweep (r27's new-article form, with the **estimate** said before Start: what earlier runs on that model spent, from the usage ledger, and the cap it stops at), a board's hand-off (its plan, then the confirm), the video chain over an article's iteration (its steps listed first), a project from a recording or a report on disk, a song. Keys: `j`/`k` the lines, Enter opens a form on its first field, Escape closes it back to the line. The policy is a chip — "Generation: balanced · Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts" — linking Settings. The rail's **+ Create** is a link to it, ⌘K's create actions open its lines (`/create?make=…`), and Work has one **+ Create**. Needs a restart of umtool. +- **The editor's "Make a video" lands on Create.** `/?from=<channel>/<id>` (VideoPanel, VideoNavStrip) now redirects to `/create?from=…`, which opens "Video from a recording" prefilled; `/articles/new` redirects to `/create?make=article`. The Inbox no longer carries the new-project form. +- **Settings · generation, `/settings/generation`.** The generation policy — routes per task, the presets, the models (the extractor among them), the caps, whether the API key's file is there (its path, never the key) — moved here from the new-article form, written through the editor's settings action as before; beside it the day's API spend job by job (task, article and iteration, the models, what it cost) and the last seven days, from the editor's usage ledger. +- **Settings · system does what a terminal did, plan first.** The doctor's roots (reports, the media root and whether its drive is there, the cache, an old cache), the project index (**Rebuild…** runs `umtool index --rebuild` as a umtool job; **Prune…** drops the records of projects that are gone) and storage (every project's `out/` and deliverables, with **Move out…**, **Move back…**, **Deliverables to media…** / **home…**, and every `out/` at once). Each shows its plan first — what it touches, with sizes, what refuses — then **Confirm** or **Keep it**; a move runs the same `umtool storage` a terminal would, as a job in the rail's Running list. `GET /api/doctor` also says the roots. - **umtool has a Research page, `/research`.** Ask the corpus (a phrase, a `/regex/`, or `a near:8 b`) in the local corpus, a published site or the hub; the scope chips (channels, dates, state on the platform, videos or streams, posts) say what the scope **holds** before anything runs: channels, videos, the years, and transcripts vs captions once a search has counted them. A search reads the whole scope once, with the MCP's own `enumerate_matches` engine (the same total and the same recordings), and says **full coverage** or **Partial — not reached:** the channels a cap left unread, with the mirrors it folded. Results are lit lines grouped by recording, the match marked, with year, channel, text, state and reading facets that narrow what is shown. The reader on the right shows the transcript around the lit hit with its cue lit, **−**/**+** to narrow or widen it, **Copy citation** in the house format, **Play from** a clip or source this machine holds, and **Fetch clip** through the editor's fetch-window route, as `fetch_clip` asks. Keys: `j`/`k` lines, `r` read, `s` skip, `u` unread, `c` copy citation, `/` the ask bar. Needs a restart of umtool. - **Research keeps a reading log.** Every hit is read, skipped or unread, and the header says **read 37 of 97**. The log is umtool's, under `REPORTS_ROOT/.umtool/research/sessions/`, one per query and scope, never in the corpus. - **umtool's archive inventory, `/research/archive`.** Channels × years: the videos the editor holds (its `GET /api/ops/coverage`, the MCP's `channel_coverage`) or the videos the source publishes, on the Meter ramp, gaps over 60 days marked, nothing held as —. Hover or focus a cell for what it holds, published, deleted or unlisted, and transcripts vs captions; the arrow keys walk the grid; **Table** lists the same numbers. When umtool has no `WORKER_TOKEN` or the editor does not answer, the page says which, and for the local corpus reads the held counts on disk instead. 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 umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.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 umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.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 @@ -353,8 +353,8 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─ | P2b jobs + drafts | `ux/p2b` → `main` `44c7b758` | LIVE 2026-10-14 (umtool BUILD_ID J2YDbFuc…) | | R2 research boards | `ux/r2` → `main` `b8561669` | LIVE 2026-10-14 (editor N0OAYPyM…, umtool 9lPefuiS…) | | P4a-1 piece frame | `ux/p4a` → `main` `a92251aa` | LIVE 2026-10-14 (umtool ErWqdPdg…) | -| P5 create + settings | `ux/p5` | in progress | -| P4a-2 article-rooted merge | `ux/p4a2` | shipped on the branch, awaiting review | +| P5 create + settings | `ux/p5` → `main` `20ee628a` | LIVE 2026-10-14 (umtool ZfQXZuNF…) | +| P4a-2 article-rooted merge | `ux/p4a2` | shipped on the branch | | P4a-3 song pieces | — | after P4a-2 | | R3, P4b, P6 | — | after R2 / P4a / all | @@ -1395,6 +1395,167 @@ the then-live code into `.next` and was stopped before its restart; the build wa real rollout followed. Live: `/projects/quartering-diet` and its `?tab=cut|build|media` 200, an article's video project 200, `/browse/<p>` 307, the Overview tab `aria-current`, decisions API 828 rows with notes' hrefs intact. +### P5, as shipped + +**What.** Create and Settings: one door to everything that can be made, and the settings a terminal held. Built on +P3's shell, R2's case API and r28's forms; no writer is new — every form is a shell over one that existed. + +- **`/create`, "What are you making?"** (`app/create/page.tsx`, `components/create/CreateView.tsx`, `forms.tsx`, + `lib/create.ts`; canvas "Create"): ONE lit list in two columns — Research · Article | Video · Song — eight lines, each + with its button (filled Signal on the lit line, an outline once its form is open: the form's own button is then the + one primary action). The form opens inline under its line; the result navigates to what was made. + - **Research a question** → `POST /api/research/cases {query, title?, scope: {source}}` (R2) → `/research/<case>`. + The corpus is a select of R1's sources. + - **Article from a question** → r28's `NewArticleForm`, reused with three props: `showPolicy` (false here: the + policy is the chip), `framed`, `history` + `onCancel`. It now says the **estimate** before Start + (`lib/create/estimate.mjs`, unit-tested): what earlier runs of the same task on the chosen model spent — the editor's + usage ledger summed per job, typical (median) and most, the latest 20 — and the cap it stops at; a local model + "Runs on the local model: no API spend"; the day's spend against the daily cap beside it. There is no price model of + a sweep (what it reads depends on what the question matches), so the estimate is the record, said as such. + - **Article / Video from a board** → a board select (`GET /api/research/cases`, `?case=` preselects), then R2's + `HandoffDialog` unchanged: the plan from `POST …/handoff {to}`, nothing written until its confirm. + - **Video from an article** → a store article and a done iteration with a report (newest first, `?article=` + preselects), the chain's steps from `GET /api/articles/chain` ("5 of 10 steps to run, from …"), then **Make the + video** (`POST /api/articles/chain`) → the article's Iterations tab, where the chain runs as a umtool job. + - **Video from a recording / from a sweep report / A song** → `NewProjectMenu` (restyled onto Field/Input/Select; + new props `kind` (fixed, no kind select), `inline`, `reports`, `fromLabel`/`fromHint`, `submitLabel`, `onCancel`) + → `POST /api/projects/new` (`scaffoldReportVideo`, the song scaffold). The report line offers every project of the + sweep-report kind on disk (`lib/projects/create.mjs`, which holds the make → kind mapping, so no page names a kind), + then "A path typed by hand…". + - **Keys:** `j`/`k` (and the arrows) glide the lit line down the left column and into the right — `LitList` gains an + opt-in `columns` prop so the head follows the line's left edge too (off everywhere else); Enter on a line opens its + form on its first field (`data-autofocus`, focused once the list's fieldset is live — a server-rendered form's + `autoFocus` never runs); Escape closes it and puts the focus back on the line's button. Inside a form `j`/`k` type. + The open form is the address (`history.replaceState` to `?make=`), so a reload or a link lands on it. + - **The policy chip** (`lib/create/policy.mjs`, unit-tested): the Meter dot and "Generation: balanced · Claude Code: + sweeps · API: report revisions, research · local: video revisions, drafts" — routes grouped by where they run, the + seven draft tasks as "drafts" when they agree, the two revisions as "revisions" when they agree — linking + `/settings/generation`. A red dot and "the editor did not answer" when it did not. +- **Addresses** (`redirects.mjs`, two P5 rows, 307): `/` **with a `from` query** → `/create` (a `has` row; the query + passes through, so the editor's `/?from=<slug>/<id>` lands on `/create?from=…`, which opens "Video from a recording" + prefilled — the Inbox no longer carries the form, and `/` without `from` is untouched); `/articles/new` → + `/create?make=article` (its page is deleted; `/drafts` redirects to Create itself until P6). `lib/hrefs.ts`: + `createHref({make, from, case, article})`, `MAKES`/`isMake`, `settingsHref`; `newArticleHref` is Create's article + line, `generationPolicyHref` is `/settings/generation`; `homeHref` lost `from`. +- **The rail and ⌘K:** **+ Create** is a link to `/create` (Signal edge and `aria-current` on it; no place is lit there — + `create` maps to no place in `AppNav`); the palette's create actions are the eight lines (`new-article` kept its id; + `new-project` became `new-video-recording` and five more), plus Create among the places. Work's two header links are + one **+ Create**. +- **`/settings/generation`** (`app/settings/generation/page.tsx`): r28's `PolicyPanel`, moved unchanged — routes, + presets, models (the policy's **extractor** is its own select there: Claude or local, as `settings.generation` + allows; `ExtractorSelect` stays the per-sweep override on the article form), caps, the key FILE's path and whether it + is there — and **Spend today**: the ledger's rows for the UTC day, job by job (time, task, article and iteration + linking its Iterations tab, the models it called, USD), against the daily cap, and the last seven days on a Meter bar + (`lib/settings/spend.mjs`, unit-tested). The head says the policy in one line. +- **`/settings/system`** gains the maintenance a terminal did (`components/system/Maintenance.tsx`, + `lib/system/actions.ts`, `lib/system/storage-rows.ts`, `lib/system/roots.mjs`): + - **Roots** — `umtool doctor`'s, now one module the CLI imports too: reports, the media root (or "= reports") and + the drive's problem, the cache and whether an index exists, a leftover old cache. `GET`/`POST /api/doctor` carry + `roots` (POST also sizes the old cache). + - **Index** — records, how many are for projects that are gone, when rebuilt, the store's path. **Rebuild…** runs + `umtool index --rebuild` as a umtool job ("Index rebuild" in the Running list); **Prune…** drops the stale records in + process (`pruneIndex`; the plan is the new read-only `indexPrunePlan` in `lib/projects.ts`). + - **Storage** — every project's `out/` (here, on media, DRIVE MISSING, none) and, for one with a manifest, its + deliverables switch and directories; **Move out…** (only when a media root is set), **Move back…**, **Deliverables to + media… / home…**, and every `out/` at once. A move runs `umtool storage …` as a umtool job ("Move out <project>"), + the same CLI a terminal runs; deliverables reuse `moveDeliverablesSteps`. + - **Plan, then confirm** (`components/system/ActionPlan.tsx`, the DeletePlan pattern): the trigger asks for the plan + (`POST /api/system/{index,storage} {…, dryRun: true}` — a dry run of the movers: what it touches with sizes, what + refuses, what is worth knowing), the plan takes the focus, and only its confirm (words naming the result: "Drop 2 + records", "Move out") acts; **Keep it** (or Escape) closes it, nothing written, focus back on the trigger. The confirm + re-reads the plan and refuses (409, with the plan) if it now refuses; a project is named by id, never a path; a busy + project (a pipeline process in it) is refused alone, skipped in an "all". + +**Commits** (`ux/p5`, from `main` `794a112b`): + +| sha | what | +|---|---| +| `63cc7294` | `/create` and its forms, the two P5 redirect rows, the hrefs, + Create as a link, ⌘K's create lines, Work's + Create, `/settings/generation`, the system actions behind plans, `LitList`'s `columns`, `NewProjectMenu` restyled with Create's props, `NewArticleForm`'s estimate and props, `rootsReport` shared with the CLI, unit tests (create 5, settings 2, hrefs +1) | +| `3411c0f2` | `create.spec` (10) and `settings.spec` (7); `article-new`, `inbox`, `shell`, `redirects`, `projects` follow Create; `test:scripts` runs `lib/create` and `lib/settings`; the system jobs named for the Running list | +| `a942547c` | a plan takes the focus (its confirm, else Keep it), Escape keeps it, closing returns to its button | +| (this commit) | this record, `[Unreleased]` bullets | + +**Gates.** + +| Gate | Result | +|---|---| +| repo-wide `tsc --noEmit` | clean at `63cc7294` and at the tip; `pnpm --filter umtool typecheck` clean at every commit | +| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 835 tests, 833 pass, 2 skipped, 0 fail (new: `create.test.mjs` 5, `settings.test.mjs` 2, `hrefs` +1) | +| `pnpm --filter umtool test` | 16/16 | +| `pnpm run test:scripts` (reads the capped build) | 986 tests, 984 pass, 2 skipped, 0 fail | +| capped umtool `next build` (corpus linked, `MemoryMax=5G`, heavy slot `--build --estimate 5120`) | exit 0; compiled 24.6 s, 81 s wall, 1.39 GB max RSS; the link removed | +| full umtool e2e (`pnpm --filter umtool run e2e`, detached, queued ~8 min behind `ux-p4a2`) at `a942547c` | **417 tests: 411 passed, 0 failed, 6 skipped** (the song-data skips), 7.5 min; `create.spec` 10/10, `settings.spec` 7/7 | + +Before it, dev-mode runs (`E2E_MODE=dev` through the queue, no prebuild) while two other lanes' servers held ~5 GB: +`create` + `settings` 13/17 then 17/17 (the four reds were `toHaveURL`'s 5 s against a dynamic page's first dev compile — +the navigations after an action now `waitForURL` 20 s — and a stub log not written yet); the touched specs 54/57 with +`last-page:55`, `shell`'s theme reload ("Page crashed") and `work:42` red under memory pressure in dev mode — all three +green in the start-mode suite above. + +**Screenshots and keys.** Job scratch `p5-shots/` (20): `/create`, `/create?make=article`, `/create?from=testchan%2Fvid1` +(the editor's hand-off, the recording's form open), `/settings/generation`, `/settings/system` with the index rebuild's +plan open — each at 1366×768 and 1440×900, dark and light, on the e2e fixture under the start-mode build. Against the +canvas's Create: the same two columns of grouped lines (Research · Article | Video · Song), the lit line's Signal edge +and notch with its filled button, the outline buttons at rest, the policy chip at the head's right with the Meter dot; +differences: the line subtitles carry live counts ("Fixture board · 3 quotes", "1 found"), the rail's + Create has no +`c` key (below), and an open form sits under its line. Every form fits 1366×768 with its line; the article form at +1366 is the tallest (it fits; with "research" chosen its autonomy row adds a line and the column scrolls). Keyboard +only (production build, reduced motion): the rail's 11 stops, the chip, then the list as ONE stop (the lit line, dashed +1 px), then its line buttons (P1's lit-list Tab order); every control the 2 px Signal ring; `j`/`k`, Enter, Escape as +above; on Settings · system the plan opens on its confirm (or Keep it) and Escape returns to its trigger. + +**Found and left.** +- **No `c` key for + Create.** The canvas's rail shows `+ Create c`. A bare `c` is the board's copy key (R2) and other + pages' own; a global one would race them. ⌘K "create" reaches every line. +- **"Pick from the archive" for a recording** is the editor's hand-off (`/?from=`) or a pasted `<channel>/<id>` / share + URL; there is no recording search on the form (Research is where recordings are found). +- **The sweep-report line lists what the walk calls a sweep report**, an article's sweep iteration in the store among + them (the fixture's `articles/p5-board/iterations/1` after the board hand-off) — the walk's existing behaviour. +- **Settings · system's "tools & disk" says `index off`** when every summary was served from memory (P3's + `indexHealth()` counts only index reads), while the new Index panel says the store's records. Not changed: P3's panel. +- **A storage move's plan is a dry run of the movers, per project**: `move-out --all` measures every project's `out/` + (a tree walk each) before it says anything; on the real reports root with a media root set that can take seconds. + Not run against the real REPORTS_ROOT here (the e2e fixture has no media root: the moves are proved refused, and the + CLI's own `storage.spec` proves the movers). +- **`/articles/new`'s page is deleted**; common still reserves the article id `new` (`registry.ts:353`) — still right: + the redirect shadows `/articles/new`. OPERATING.md, `umtool/docs/*` and FACTS still name `/articles/new` and the + policy's old home; they ride the redirect until P6 rewrites the docs. +- Not touched (other lanes'): `app/projects/**` (its `+ new project` form is `NewProjectMenu`, restyled here, same + contracts), `components/projects/**`, `lib/pieces/tabs.mjs`, `lib/inbox/what.mjs`, `e2e/urls.ts`. + +**Follow-up (review rulings, 2026-10-14).** +- Rulings: the policy's extractor stays PolicyPanel's own select on `/settings/generation` (the policy default; + `ExtractorSelect` is the per-run choice on the article form); no bare `c` for + Create (⌘K covers it); the edits + outside the lane's ownership are accepted. +- **Video from an article defaults to the newest done iteration with a report of its OWN** (a chain cuts from a + report): `lib/create/iterations.mjs` (`chainable`, `defaultChainIteration`; unit-tested on zeta's shape). A video + revision carrying an earlier iteration's report is offered but never the default. The plan line names the chosen + iteration and its kind ("i2 · revise-report:", "i3 · revise-video (the report of i1):"); `create.spec` asserts zeta + defaults to i2 and the line for i3 and i1. +- **Merged `ux/integration` `3c119873` (P4a-1, LIVE)** at `982d9a9d`. Two conflicts: `app/page.tsx` takes P4a-1's + `whatOf` (`lib/inbox/what.mjs`) and keeps P5's removal of the `?from` form; this plan keeps both records (P4a-1's + rollout, then P5's) and one status row per phase. `pnpm install`: up to date. No code fix was needed. +- **Gates** at `982d9a9d`: repo-wide tsc clean; umtool unit 843 tests, 841 pass, 2 skipped, 0 fail; `pnpm --filter + umtool test` 16/16; test:scripts 994, 992 pass, 2 skipped, 0 fail; capped build exit 0 (12.9 s compile, 45 s wall, + 1.42 GB); full umtool e2e (queued behind `ux-r3`) **426 tests: 420 passed, 0 failed, 6 skipped**, 7.9 min; + `create.spec` 10/10. + +| sha | what | +|---|---| +| `050bddd8` | the chain's default iteration (own report), the plan line names it; unit test and `create.spec` | +| `982d9a9d` | merge `ux/integration` `3c119873` (P4a-1) | + +### P5 rollout (orchestrator, 2026-10-14) + +Rulings: PolicyPanel's own extractor select is the policy default (r28's `ExtractorSelect` stays the per-run choice); +"Video from an article" defaults to the newest iteration with its own report (follow-up `050bddd8`); no bare `c` +shortcut (the board's copy key) — ⌘K reaches every create line. Gates on `982d9a9d` (P4a-1 merged): full umtool e2e 420 +passed, 0 failed, 6 skipped; test:scripts 992 pass, 0 fail; capped build ok. `main` fast-forwarded to `20ee628a`; umtool +built (40 s) and restarted (`scripts/p5-umtool.sh`). Live: `/?from=the-quartering/abc123` → 307 +`/create?from=the-quartering%2Fabc123`, the recording prefilled; `/articles/new` → 307 `/create?make=article`; `/create`, +`/settings/generation`, `/settings/system`, `/work`, `/research` 200; decisions API 828 rows, notes' hrefs intact. +For P6's audit: `/settings/system`'s index and storage panels carry explanatory sentences the copy rule would cut. + ### P4a-2, as shipped **What.** An article and the video project it claims are one page: the article's address (`/articles/<id>`, diff --git a/umtool/app/api/doctor/route.ts b/umtool/app/api/doctor/route.ts @@ -1,19 +1,24 @@ import { probeNow, toolsCache } from "@/lib/doctor"; +import { rootsReport } from "@/lib/system/roots.mjs"; export const dynamic = "force-dynamic"; // GET is the cache, and only the cache: `{ checked: false }` when nothing has // been probed in the last ten minutes. POST probes. The split is the rule that // the index and the pages never shell out -- a probe is an action somebody took. +// +// Both carry `roots` (P5, lib/system/roots.mjs -- `umtool doctor`'s): where +// projects are read, where out/ goes and whether that drive is there, the +// cache and the index, and a cache left at its old place. Stats only; POST +// also sizes the old cache. export async function GET() { const c = toolsCache(); - return Response.json( - c ? { checked: true, ...c } : { checked: false }, - { headers: { "cache-control": "no-store" } }, - ); + const roots = await rootsReport({ measureOld: false }); + return Response.json(c ? { checked: true, ...c, roots } : { checked: false, roots }, { headers: { "cache-control": "no-store" } }); } export async function POST() { const r = await probeNow(); - return Response.json({ checked: true, ...r }, { headers: { "cache-control": "no-store" } }); + const roots = await rootsReport(); + return Response.json({ checked: true, ...r, roots }, { headers: { "cache-control": "no-store" } }); } diff --git a/umtool/app/api/system/_respond.ts b/umtool/app/api/system/_respond.ts @@ -0,0 +1,17 @@ +import { ActionError } from "@/lib/system/actions"; + +// The system actions' answers: JSON, never cached; an error in words with its +// status, and the plan when the confirm was refused by it. +export const ok = (v: unknown) => Response.json(v, { headers: { "cache-control": "no-store" } }); + +export function fail(e: unknown) { + const status = e instanceof ActionError ? e.status : 500; + const plan = e instanceof ActionError ? e.plan : null; + return Response.json({ error: e instanceof Error ? e.message : String(e), ...(plan ? { plan } : {}) }, { status, headers: { "cache-control": "no-store" } }); +} + +export async function bodyOf(request: Request): Promise<Record<string, unknown>> { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b || typeof b !== "object" || Array.isArray(b)) throw new ActionError("expected a JSON object"); + return b; +} diff --git a/umtool/app/api/system/index/route.ts b/umtool/app/api/system/index/route.ts @@ -0,0 +1,22 @@ +import { ActionError, applyIndex, isIndexAction, planIndex } from "@/lib/system/actions"; +import { bodyOf, fail, ok } from "../_respond"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT INDEX, from Settings · system (P5): `umtool index --rebuild | +// --prune` behind a plan (lib/system/actions.ts). +// +// POST { action: "rebuild" | "prune", dryRun: true } -> { plan } writes nothing +// POST { action: "rebuild" | "prune" } -> { applied, message, job? } +// rebuild runs as a umtool job (the CLI); prune drops the records in +// process. A confirm the plan now refuses is 409 with the plan. +export async function POST(request: Request) { + try { + const b = await bodyOf(request); + if (!isIndexAction(b.action)) throw new ActionError('action is "rebuild" or "prune"'); + if (b.dryRun === true) return ok({ plan: await planIndex(b.action) }); + return ok({ applied: true, ...(await applyIndex(b.action)) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/system/storage/route.ts b/umtool/app/api/system/storage/route.ts @@ -0,0 +1,23 @@ +import { applyStorage, parseStorage, planStorage } from "@/lib/system/actions"; +import { bodyOf, fail, ok } from "../_respond"; + +export const dynamic = "force-dynamic"; + +// STORAGE MOVES, from Settings · system (P5): `umtool storage move-out | +// move-back | deliverables` behind a plan (lib/system/actions.ts). The body +// names a project id (or all), never a path. +// +// POST { action: "move-out" | "move-back", project | all: true, dryRun: true } -> { plan } +// POST { action: "deliverables", project, to: "media" | "local", dryRun: true } -> { plan } +// the same without dryRun -> { applied, message, job }: a umtool job running +// the CLI; a confirm the plan now refuses is 409 with the plan. +export async function POST(request: Request) { + try { + const b = await bodyOf(request); + const input = parseStorage(b); + if (b.dryRun === true) return ok({ plan: await planStorage(input) }); + return ok({ applied: true, ...(await applyStorage(input)) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/articles/new/page.tsx b/umtool/app/articles/new/page.tsx @@ -1,30 +0,0 @@ -import BrowseHeader from "@/components/BrowseHeader"; -import NewArticleForm from "@/components/articles/NewArticleForm"; -import { listArticleDirs, listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; -import { readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; -import { sitesPaths } from "@/lib/articles/sites"; - -export const dynamic = "force-dynamic"; - -// A NEW ARTICLE (release 27 S8): its first iteration, a sweep the editor runs -// (`report-draft`), and the generation policy it starts from. The article is -// in the making — on /articles as generating — until an iteration is used. -export default async function NewArticlePage() { - let policy: PolicyView | null = null; - try { - policy = await readPolicy(); - } catch { - policy = null; - } - const today = policy ? await readToday(policy.generation.caps.daily).catch(() => null) : null; - const paths = sitesPaths(); - const taken = [...(await listArticleDirs(paths)), ...(await listPendingArticles(paths))]; - return ( - <div className="flex h-full flex-col"> - <BrowseHeader active="articles" crumbs={[{ label: "articles", href: "/work?kind=article" }, { label: "new" }]} /> - <main className="deck-main flex-1 p-4"> - <NewArticleForm initialPolicy={policy} today={today} taken={taken} /> - </main> - </div> - ); -} diff --git a/umtool/app/create/page.tsx b/umtool/app/create/page.tsx @@ -0,0 +1,58 @@ +import Link from "next/link"; +import CreateView from "@/components/create/CreateView"; +import AppShell from "@/components/shell/AppShell"; +import { readCreate } from "@/lib/create"; +import { policyChip } from "@/lib/create/policy.mjs"; +import { generationPolicyHref, isMake, type Make } from "@/lib/hrefs"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// /create (plans/umtool-redesign.md, P5; canvas "Create"): "What are you +// making?" -- one shell over the writers that already exist. Research a +// question (a case, R2) · an article from a question (a sweep, r27/r28) or a +// board (R2's hand-off) · a video from an article (the chain), a board, a +// recording or a sweep report (scaffoldReportVideo) · a song. The policy is a +// chip (the Meter dot and where each task runs) linking /settings/generation. +// +// ?make=<make> opens that line's form (lib/hrefs.ts MAKES) +// ?from=<c>/<id> the editor's "make a video" (/?from= redirects here): +// "Video from a recording", prefilled +// ?case=<id> preselects a board; ?article=<id> an article +// --------------------------------------------------------------------------- + +export default async function CreatePage({ + searchParams, +}: { + searchParams: Promise<{ make?: string; from?: string; case?: string; article?: string }>; +}) { + const sp = await searchParams; + const from = typeof sp.from === "string" && sp.from.trim() ? sp.from.trim() : null; + const initial: Make | null = from ? "video-recording" : isMake(sp.make) ? sp.make : null; + const data = await readCreate(); + const chip = policyChip(data.policy?.generation ?? null, data.policy?.tasks); + + return ( + <div className="flex h-full flex-col"> + <AppShell + active="create" + crumbs={[{ label: "What are you making?" }]} + actions={ + <Link + href={generationPolicyHref()} + prefetch={false} + data-policy-chip={data.policy?.generation.preset ?? "unknown"} + title={data.policyError ?? "Where each task runs, the models, the caps: Settings · generation"} + className="inline-flex max-w-[640px] items-center gap-1.5 truncate rounded-[3px] border border-seam-2 px-2 py-[3px] text-[12px] text-text-2 no-underline hover:border-muted hover:text-text" + > + <i aria-hidden="true" className={`size-1.5 shrink-0 rounded-full ${data.policy ? "bg-meter" : "bg-reject"}`} /> + <span className="truncate">{chip}</span> + </Link> + } + /> + <main className="deck-main flex-1 px-4 pb-6 pt-4"> + <CreateView data={data} initial={initial} from={from} initialCase={sp.case ?? null} initialArticle={sp.article ?? null} /> + </main> + </div> + ); +} diff --git a/umtool/app/drafts/page.tsx b/umtool/app/drafts/page.tsx @@ -1,10 +1,12 @@ import { redirect } from "next/navigation"; +import { newArticleHref } from "@/lib/hrefs"; export const dynamic = "force-dynamic"; // The proof of concept's page (2026-10-12) is the application's now: a new -// article on /articles/new, its iterations on the article's Iterations tab -// (release 27 S8). +// article on Create (/create?make=article, P5; it was /articles/new), its +// iterations on the article's Iterations tab (release 27 S8). P6 deletes this +// page and redirects /drafts to the Inbox. export default function DraftsPage() { - redirect("/articles/new"); + redirect(newArticleHref()); } diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -2,17 +2,14 @@ import Link from "next/link"; import InboxList, { type InboxCard, type InboxGroup } from "@/components/dashboard/InboxList"; import { UndoBar } from "@/components/dashboard/Lifecycle"; import ResumeChip from "@/components/dashboard/ResumeChip"; -import NewProjectMenu from "@/components/NewProjectMenu"; import AppShell from "@/components/shell/AppShell"; import { buttonVariants } from "@/components/ui/button"; -import { Panel } from "@/components/ui/panel"; import { machineCalls } from "@/lib/machine"; import { homeHref, systemHref } from "@/lib/hrefs"; import { readInbox, type GroupCard, type GroupSummary } from "@/lib/inbox"; import { summarizeGroups } from "@/lib/inbox/groups.mjs"; import { headlineNote, inboxHeadline } from "@/lib/inbox/headline.mjs"; import { whatOf } from "@/lib/inbox/what.mjs"; -import { KINDS } from "@/lib/projects"; import type { Decision } from "@/lib/decisions"; import type { LifecycleState } from "@/lib/lifecycle"; @@ -30,10 +27,9 @@ export const dynamic = "force-dynamic"; // /settings/system. What is running is in the rail. // // `?from=<slug>/<id>` is the editor's "make a video" hand-off (VideoPanel, -// VideoNavStrip). Until /create (P5) it opens the new-project form here, -// prefilled, as the dashboard did. `?hidden=1` lists the calls on parked and -// done pieces, each with Reactivate; `?muted=1` the muted ones (lib/mutes.ts), -// each with Unmute. +// VideoNavStrip): redirects.mjs sends it to /create?from=… (P5) before this +// page is reached. `?hidden=1` lists the calls on parked and done pieces, each +// with Reactivate; `?muted=1` the muted ones (lib/mutes.ts), each with Unmute. // --------------------------------------------------------------------------- const GROUP_NOTE: Record<string, string> = { @@ -88,9 +84,9 @@ function hiddenCards(items: Decision[], keep: (d: Decision) => boolean, lifeOf: export default async function Inbox({ searchParams, }: { - searchParams: Promise<{ from?: string; hidden?: string; muted?: string }>; + searchParams: Promise<{ hidden?: string; muted?: string }>; }) { - const { from, hidden: showHidden, muted: showMuted } = await searchParams; + const { hidden: showHidden, muted: showMuted } = await searchParams; const inbox = await readInbox(); const lifeOf = new Map<string, LifecycleState>(); for (const d of inbox.items) if (d.piece && d.lifecycle) lifeOf.set(d.piece, d.lifecycle as LifecycleState); @@ -125,8 +121,6 @@ export default async function Inbox({ extra.push({ id: "hidden", label: "Hidden", note: "on parked and done pieces", collapsed: false, decisions: parkedN, hidden: 0, cards }); } - const kinds = KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold })); - return ( <div className="flex h-full flex-col"> <AppShell @@ -162,11 +156,6 @@ export default async function Inbox({ /> <main className="deck-main flex-1 px-4 pb-6 pt-4"> - {from && ( - <Panel title="Make a video" className="mb-4" data-handoff={from}> - <NewProjectMenu kinds={kinds} from={from} /> - </Panel> - )} {inbox.lifecycleError && ( <p role="alert" className="mb-3 text-[12.5px] text-reject-text"> {inbox.lifecycleError} — every piece reads as active until it is fixed. diff --git a/umtool/app/settings/generation/page.tsx b/umtool/app/settings/generation/page.tsx @@ -0,0 +1,118 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import PolicyPanel from "@/components/articles/PolicyPanel"; +import AppShell from "@/components/shell/AppShell"; +import { Panel } from "@/components/ui/panel"; +import { readPolicy, type PolicyView } from "@/lib/articles/generation"; +import { policyChip } from "@/lib/create/policy.mjs"; +import { articleHref, settingsHref } from "@/lib/hrefs"; +import { daySpend, recentDays } from "@/lib/settings/spend.mjs"; +import Link from "next/link"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// SETTINGS · GENERATION (plans/umtool-redesign.md, P5): the generation policy +// -- where each task runs (Claude Code, the API, the local model), the presets, +// the models (the extractor an API sweep reads its batches with among them), +// the caps, and whether the API key's FILE is there (its path; never the key) +// -- written through the editor's settings action (PolicyPanel, release 27 +// S8, moved here from the new-article form). Under it, the day's spend, job by +// job, from the editor's usage ledger (the total P2b's rail says). +// +// Read from the editor; an editor that does not answer is said, and the +// ledger is still read (it is a file). +// --------------------------------------------------------------------------- + +const usd = (v: number) => `$${v.toFixed(2)}`; +const hhmm = (iso: string) => iso.slice(11, 16); + +export default async function GenerationPage() { + let policy: PolicyView | null = null; + let policyError: string | null = null; + try { + policy = await readPolicy(); + } catch (e) { + policyError = e instanceof Error ? e.message : String(e); + } + const rows = await readGenerationUsage(getPaths().generationUsageFile).catch(() => []); + const day = utcDay(); + const spend = daySpend(rows, day); + const daily = policy?.generation.caps.daily ?? 0; + const today = { day, usd: spend.usd, jobs: spend.jobs.length, daily }; + const week = recentDays(rows, day, 7); + const weekMax = Math.max(...week.map((d) => d.usd), 0.01); + + return ( + <div className="flex h-full flex-col"> + <AppShell + active="generation" + crumbs={[{ href: settingsHref(), label: "Settings" }, { label: "Generation" }]} + meta={<span data-policy-summary="">{policyChip(policy?.generation ?? null, policy?.tasks)}</span>} + /> + <main className="deck-main flex-1 p-4"> + <div className="grid items-start gap-3 xl:grid-cols-[minmax(0,1fr)_360px]"> + {policy ? ( + <PolicyPanel initial={policy} today={today} /> + ) : ( + <Panel title="Policy"> + <p role="alert" className="m-0 text-[12.5px] text-reject-text" data-policy-error=""> + The editor did not answer ({policyError}), so the policy is unknown. Start it, then reload. + </p> + </Panel> + )} + + <Panel + title="Spend today" + aside={ + <span className="text-muted-2"> + {day} UTC · the editor&apos;s ledger + </span> + } + data-spend-today={spend.usd.toFixed(2)} + > + <p className="m-0 flex items-baseline gap-2"> + <span className="num text-[22px] font-semibold text-meter">{usd(spend.usd)}</span> + <span className="text-[12.5px] text-text-2"> + {daily > 0 ? `of the ${usd(daily)} daily cap` : "no daily cap"} · {spend.jobs.length} {spend.jobs.length === 1 ? "job" : "jobs"} + </span> + </p> + {spend.jobs.length > 0 ? ( + <ul className="mt-2 grid list-none gap-0 p-0 text-[12px]" aria-label="today's jobs"> + {spend.jobs.map((j) => ( + <li key={j.jobId} data-spend-job={j.jobId} className="grid grid-cols-[3.2em_minmax(0,1fr)_auto] gap-x-2 border-t border-seam py-1.5"> + <span className="num text-muted-2">{hhmm(j.at)}</span> + <span className="min-w-0 truncate"> + {j.task} ·{" "} + <Link href={articleHref({ site: "articles", id: j.article }, { tab: "iterations" })} prefetch={false} className="ink-link"> + {j.article} i{j.iteration} + </Link> + <span className="block truncate font-mono text-[11px] text-muted-2">{j.models.join(", ")}</span> + </span> + <span className="num text-meter">{usd(j.usd)}</span> + </li> + ))} + </ul> + ) : ( + <p className="mt-2 text-[12px] text-muted">Nothing spent on the API today.</p> + )} + <div className="mt-3 border-t border-seam pt-2"> + <h3 className="micro mb-1.5">Last 7 days</h3> + <ul className="grid list-none gap-1 p-0 text-[11.5px]" aria-label="last 7 days"> + {week.map((d) => ( + <li key={d.day} data-spend-day={d.day} className="grid grid-cols-[6.5em_minmax(0,1fr)_4.5em] items-center gap-x-2"> + <span className="num text-muted-2">{d.day}</span> + <span className="h-1.5 rounded-[1px] bg-seam"> + <i className="block h-full rounded-[1px] bg-meter" style={{ width: `${Math.round((d.usd / weekMax) * 100)}%` }} /> + </span> + <span className="num text-right text-text-2">{usd(d.usd)}</span> + </li> + ))} + </ul> + </div> + </Panel> + </div> + </main> + </div> + ); +} diff --git a/umtool/app/settings/page.tsx b/umtool/app/settings/page.tsx @@ -4,8 +4,7 @@ import { generationPolicyHref, systemHref } from "@/lib/hrefs"; export const dynamic = "force-dynamic"; -// SETTINGS: the two pages. /settings/generation arrives with P5; until then -// the generation policy is set on the new-article form, its current home. +// SETTINGS: the two pages (P5): the generation policy, and the machine. export default function SettingsPage() { return ( <div className="flex h-full flex-col"> @@ -16,8 +15,8 @@ export default function SettingsPage() { { title: "Settings", tools: [ - { href: systemHref(), name: "system", what: "Tools, disk, index, sources, deliverables, recent jobs", testid: "system" }, - { href: generationPolicyHref(), name: "generation policy", what: "Routes, models and caps — on the new-article form until P5", testid: "generation" }, + { href: generationPolicyHref(), name: "generation", what: "Routes, models, caps, the API key's file, today's spend", testid: "generation" }, + { href: systemHref(), name: "system", what: "Doctor, the index, storage moves, disk, sources, deliverables, recent jobs", testid: "system" }, ], }, ]} diff --git a/umtool/app/settings/system/page.tsx b/umtool/app/settings/system/page.tsx @@ -5,13 +5,17 @@ import SourcesPanel from "@/components/dashboard/SourcesPanel"; import StateStrip from "@/components/dashboard/StateStrip"; import ToolsPanel from "@/components/dashboard/ToolsPanel"; import AppShell from "@/components/shell/AppShell"; +import { IndexPanel, RootsPanel, StoragePanel } from "@/components/system/Maintenance"; import { listActivity, runningActivity } from "@/lib/activity"; import { projectsNote, sourceBuckets, stateRows } from "@/lib/dashboard"; import { toolsCache } from "@/lib/doctor"; -import { generationPolicyHref } from "@/lib/hrefs"; +import { generationPolicyHref, settingsHref } from "@/lib/hrefs"; import { freeBytesUnder } from "@/lib/machine"; import { REPORTS_ROOT } from "@/lib/paths"; -import { KINDS, decisionCounts, indexHealth, listProjects } from "@/lib/projects"; +import { KINDS, decisionCounts, indexHealth, indexPrunePlan, listProjects } from "@/lib/projects"; +import { MEDIA_ROOT, MEDIA_TIERED } from "@/lib/paths"; +import { rootsReport } from "@/lib/system/roots.mjs"; +import { storageRows } from "@/lib/system/storage-rows"; export const dynamic = "force-dynamic"; @@ -21,9 +25,15 @@ export const dynamic = "force-dynamic"; // build at all. These were the dashboard's panels; what in them is a CALL // (a required tool missing, a disk nearly full) is an Inbox card instead. // -// Everything is read from the index and the job registries; nothing here -// shells out -- the tools panel shows a cache or "not checked", and probing is -// its button. P5 adds the doctor, index and storage actions. +// Everything is read from the index, the job registries and a few stats; +// nothing here shells out -- the tools panel shows a cache or "not checked", +// and probing is its button. +// +// P5: the maintenance a terminal did -- the doctor's roots, `umtool index +// --rebuild | --prune`, `umtool storage move-out | move-back | deliverables` +// (lib/system/actions.ts) -- each one that changes or moves anything a plan +// first, then Confirm or Keep it (components/system/ActionPlan.tsx); the long +// ones run as umtool jobs, in the rail's Running list. export default async function SystemPage() { const projects = await listProjects(); @@ -33,6 +43,7 @@ export default async function SystemPage() { const tools = toolsCache(); const ix = indexHealth(); const free = await freeBytesUnder(REPORTS_ROOT); + const [roots, prune, storage] = await Promise.all([rootsReport({ measureOld: false }), indexPrunePlan(), storageRows()]); const blocking = [...counts.values()].reduce((n, c) => n + c.blocking, 0); const openN = [...counts.values()].reduce((n, c) => n + c.open, 0); @@ -42,16 +53,19 @@ export default async function SystemPage() { <div className="flex h-full flex-col"> <AppShell active="system" - crumbs={[{ href: "/settings", label: "settings" }, { label: "system" }]} + crumbs={[{ href: settingsHref(), label: "Settings" }, { label: "System" }]} actions={ - <Link href={generationPolicyHref()} data-policy-link="" className="ink-link text-[12.5px]"> - Generation policy → + <Link href={generationPolicyHref()} data-policy-link="" prefetch={false} className="ink-link text-[12.5px]"> + Generation → </Link> } /> <main className="deck-main flex-1 p-4"> <div className="grid gap-3 lg:grid-cols-2 2xl:grid-cols-3"> <ToolsPanel initial={tools} freeBytes={free} index={ix} /> + <RootsPanel roots={roots} /> + <IndexPanel index={{ ok: prune.ok, records: prune.records, path: prune.path, builtAt: prune.builtAt, stale: prune.stale.length }} /> + <StoragePanel rows={storage} tiered={MEDIA_TIERED} mediaRoot={MEDIA_ROOT} /> <NowPanel running={running} recent={recent} /> <StateStrip rows={stateRows(KINDS, projects)} note={projectsNote(projects.length, blocking, openN)} /> <SourcesPanel never={buckets.never} old={buckets.old} bad={buckets.bad} /> diff --git a/umtool/app/work/page.tsx b/umtool/app/work/page.tsx @@ -9,7 +9,7 @@ import { Input } from "@/components/ui/field"; import { LitList } from "@/components/ui/lit-list"; import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar"; -import { newArticleHref, projectsHref, siteHref, workHref, type WorkQuery } from "@/lib/hrefs"; +import { createHref, siteHref, workHref, type WorkQuery } from "@/lib/hrefs"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { KINDS } from "@/lib/projects"; import { readWork, type WorkRow } from "@/lib/work"; @@ -77,14 +77,10 @@ export default async function WorkPage({ searchParams }: { searchParams: Promise </span> } actions={ - <> - <Link href={newArticleHref()} className={buttonVariants({ variant: "quiet", size: "md" })}> - + New article - </Link> - <Link href={projectsHref({ new: true })} className={buttonVariants({ variant: "quiet", size: "md" })}> - + New project - </Link> - </> + // One way in to everything that can be made (canvas "Work"): /create. + <Link href={createHref()} prefetch={false} data-work-create="" className={buttonVariants({ variant: "outline", size: "md" })}> + + Create + </Link> } /> <SlashFocus target="[data-work-search]" /> diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -79,16 +79,14 @@ import { pipelineProcessesFor } from "../lib/report/busy.mjs"; import { probeTools } from "../lib/tools.mjs"; import { notesCommand } from "../lib/annotations/cli.mjs"; import { scaffoldReportVideo } from "../lib/projects/scaffold.mjs"; -import { ARTICLES_DIR, CACHE_DIR, INDEX_DIR, MEDIA_ROOT, MEDIA_TIERED, OLD_CACHE_DIR } from "../lib/paths.mjs"; +import { rootsReport } from "../lib/system/roots.mjs"; +import { ARTICLES_DIR, MEDIA_ROOT, MEDIA_TIERED } from "../lib/paths.mjs"; import { deliverablesState, - measureTree, - mediaRootProblem, moveDeliverables, moveDirToLocal, moveDirToMedia, outDirState, - pathState, } from "../lib/report/storage.mjs"; const argv = process.argv.slice(2); @@ -368,26 +366,8 @@ function cmdKinds() { } } -/** - * The roots, as the doctor reports them: where projects are read, where their - * out/ goes, where the cache is -- and a cache left where it used to live - * (under SONG_DATA, before release 17), which is derived and safe to delete - * once `umtool index` has rebuilt the new one. - */ -async function rootsReport() { - const isDir = async (p) => (await pathState(p)).kind === "dir"; - const problem = await mediaRootProblem(); - const oldPresent = OLD_CACHE_DIR !== CACHE_DIR && (await isDir(OLD_CACHE_DIR)); - return { - ok: !problem, - reports: { path: REPORTS_ROOT, present: await isDir(REPORTS_ROOT) }, - media: { path: MEDIA_ROOT, tiered: MEDIA_TIERED, present: await isDir(MEDIA_ROOT), problem }, - cache: { path: CACHE_DIR, present: await isDir(CACHE_DIR), index: await isDir(INDEX_DIR) }, - oldCache: oldPresent - ? { path: OLD_CACHE_DIR, present: true, bytes: (await measureTree(OLD_CACHE_DIR)).bytes } - : { path: OLD_CACHE_DIR, present: false }, - }; -} +// The roots, as the doctor reports them: lib/system/roots.mjs (shared with +// the app's /settings/system). const mb = (n) => `${(n / 1024 ** 2).toFixed(1)} MB`; diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -60,6 +60,9 @@ const PLACE_OF: Record<string, string> = { bench: "tools", settings: "settings", system: "settings", + generation: "settings", + // Create is the rail's + Create, not a place: no place is lit on it. + create: "create", ...Object.fromEntries([...TOOL_ITEMS, ...SONG_ITEMS].map((t) => [t.label, "tools"])), }; @@ -102,7 +105,7 @@ export default function AppNav({ active }: { active: string }) { ))} </div> )} - <Link href={systemHref()} prefetch={false} data-place="settings" aria-current={current("settings", ["settings", "system"])}> + <Link href={systemHref()} prefetch={false} data-place="settings" aria-current={current("settings", ["settings", "system", "generation"])}> Settings </Link> </nav> diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx @@ -2,35 +2,80 @@ import { useState } from "react"; import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { useHydrated } from "@/components/ui/use-hydrated"; // Start a project that is not there yet -- of any kind the registry says can be -// scaffolded. The kind select comes first; the fields under it are the ones -// that kind DECLARES (`scaffold.fields` in the registry), so this file renders -// from data and never branches on a kind id. `from` prefills the source field -// when the dashboard was opened with ?from=<channel>/<id>. +// scaffolded. The fields are the ones the kind DECLARES (`scaffold.fields` in +// the registry), so this file renders from data and never branches on a kind +// id. It writes through POST /api/projects/new (lib/projects/scaffold.ts). +// +// Two ways in: +// - the projects index's "+ new project": a kind select, then that kind's +// fields (opened by the button, or by ?new=1); +// - Create's lines (/create, P5): ONE kind, fixed (`kind`), always open +// (`inline`), and `from` prefilled when the editor handed a recording over +// (/?from=<channel>/<id> → /create?from=…). A sweep report's line offers +// the reports on disk (`reports`) before a path typed by hand. // // It creates no cut files and no clip windows it cannot know. What it writes is // a shape to fill in, which is the whole reason it exists: the five songs and // six report videos made by hand each came out slightly different. +// +// Contracts (projects.spec.ts, create.spec.ts): the toggle is +// [data-new-project]; the form [data-new-project-form] with [data-new-kind], +// [data-new-slug], [data-new-title], [data-new-from], [data-new-origin], +// [data-new-seed], [data-new-brand], [data-new-create] and [data-new-error]. type Brand = { id: string; label: string }; type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null }; +type Report = { project: string; path: string; title: string }; -const FIELD_LABEL: Record<string, string> = { - from: "from — a sweep-report .md, a viewer share URL, or <channel>/<videoId>", - siteOrigin: "site origin — the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)", +const FIELD_HINT: Record<string, string> = { + from: "a sweep-report .md, a viewer share URL, or <channel>/<videoId>", + siteOrigin: "the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)", seed: "seed the timeline from the video's digest chapters (review each)", - brand: "brand — a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card", + brand: "a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card", }; -export default function NewProjectMenu({ kinds, from = null, open: startOpen = false }: { kinds: Kind[]; from?: string | null; open?: boolean }) { +export default function NewProjectMenu({ + kinds, + kind: fixedKind, + from = null, + open: startOpen = false, + inline = false, + fromLabel = "From", + fromHint = FIELD_HINT.from, + fromPlaceholder = "report.md, share URL, or channel/videoId", + reports, + submitLabel = "Create", + onCancel, +}: { + kinds: Kind[]; + /** One kind, fixed: no kind select (Create's lines). */ + kind?: string; + from?: string | null; + open?: boolean; + /** Always open, no toggle; Cancel (and Escape) call `onCancel`. */ + inline?: boolean; + fromLabel?: string; + fromHint?: string; + fromPlaceholder?: string; + /** Sweep reports on disk, offered as the `from` (Create's "from a sweep report"). */ + reports?: Report[]; + submitLabel?: string; + onCancel?: () => void; +}) { const router = useRouter(); - const can = kinds.filter((k) => k.scaffold); - const [open, setOpen] = useState(!!from || startOpen); + const hydrated = useHydrated(); + const can = kinds.filter((k) => k.scaffold && (!fixedKind || k.id === fixedKind)); + const [open, setOpen] = useState(inline || !!from || startOpen); const [kind, setKind] = useState(can[0]?.id ?? ""); const [slug, setSlug] = useState(""); const [title, setTitle] = useState(""); - const [src, setSrc] = useState(from ?? ""); + const [src, setSrc] = useState(from ?? reports?.[0]?.path ?? ""); + const [byHand, setByHand] = useState(!reports?.length); const [origin, setOrigin] = useState(""); const [seed, setSeed] = useState(false); const [brand, setBrand] = useState(""); @@ -44,6 +89,7 @@ export default function NewProjectMenu({ kinds, from = null, open: startOpen = f const looksLikeVideo = /[?&]v=/.test(src) || /^[\w.-]+\/[\w.-]+$/.test(src.trim()); const create = async () => { + if (!slug.trim()) return; setBusy(true); setError(null); try { @@ -71,128 +117,142 @@ export default function NewProjectMenu({ kinds, from = null, open: startOpen = f if (!can.length) return null; if (!open) { return ( - <button - type="button" - onClick={() => setOpen(true)} - data-new-project - className="rounded border border-dashed border-[var(--color-line)] px-2.5 py-1 text-[12px] text-[var(--color-dim)] hover:border-[var(--color-sel)] hover:text-[var(--color-sel)]" - > + <Button type="button" size="sm" variant="outline" disabled={!hydrated} onClick={() => setOpen(true)} data-new-project className="border-dashed"> + new project - </button> + </Button> ); } - const input = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-1 text-[12px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"; - const onEnter = (e: React.KeyboardEvent) => e.key === "Enter" && slug.trim() && create(); + const cancel = () => { + setError(null); + if (inline) onCancel?.(); + else setOpen(false); + }; + // The first field takes the focus: the source when it is asked and empty. + const sourceFirst = inline && fields.includes("from") && !from && byHand; return ( - <div + <form data-new-project-form - className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2" + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onSubmit={(e) => { + e.preventDefault(); + void create(); + }} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + cancel(); + } + }} > - <select - value={kind} - onChange={(e) => setKind(e.target.value)} - aria-label="project kind" - data-new-kind - className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-2 py-1 text-[12px]" - > - {can.map((k) => ( - <option key={k.id} value={k.id}> - {k.label} - </option> - ))} - </select> - <input - autoFocus - value={slug} - onChange={(e) => setSlug(e.target.value)} - onKeyDown={onEnter} - placeholder="directory name, e.g. donkey-kong" - aria-label="project directory name" - data-new-slug - className={`w-52 font-mono ${input}`} - /> - <input - value={title} - onChange={(e) => setTitle(e.target.value)} - onKeyDown={onEnter} - placeholder="title (optional)" - aria-label="project title" - data-new-title - className={`w-56 ${input}`} - /> - {fields.includes("from") && ( - <input - value={src} - onChange={(e) => setSrc(e.target.value)} - onKeyDown={onEnter} - placeholder="from: report.md, share URL, or channel/videoId" - aria-label={FIELD_LABEL.from} - title={FIELD_LABEL.from} - data-new-from - className={`w-72 font-mono ${input}`} - /> + {!fixedKind && ( + <Field label="Kind"> + <Select value={kind} onChange={(e) => setKind(e.target.value)} aria-label="project kind" data-new-kind> + {can.map((k) => ( + <option key={k.id} value={k.id}> + {k.label} + </option> + ))} + </Select> + </Field> )} - {fields.includes("siteOrigin") && ( - <input - value={origin} - onChange={(e) => setOrigin(e.target.value)} - onKeyDown={onEnter} - placeholder="site origin, e.g. https://…pages.dev" - aria-label={FIELD_LABEL.siteOrigin} - title={FIELD_LABEL.siteOrigin} - data-new-origin - className={`w-56 font-mono ${input}`} + {fields.includes("from") && reports && reports.length > 0 && ( + <Field label="Report" className="min-w-0 basis-full"> + <Select + aria-label="sweep report" + data-new-report + autoFocus={inline} + data-autofocus={inline ? "" : undefined} + value={byHand ? "" : src} + onChange={(e) => { + const v = e.target.value; + setByHand(v === ""); + setSrc(v); + }} + > + {reports.map((r) => ( + <option key={r.path} value={r.path}> + {r.title} — {r.project} + </option> + ))} + <option value="">A path typed by hand…</option> + </Select> + </Field> + )} + {fields.includes("from") && byHand && ( + <Field label={fromLabel} hint={fromHint} className="min-w-0 basis-full"> + <Input + autoFocus={sourceFirst} + data-autofocus={sourceFirst ? "" : undefined} + value={src} + onChange={(e) => setSrc(e.target.value)} + placeholder={fromPlaceholder} + aria-label={`from — ${FIELD_HINT.from}`} + data-new-from + className="font-mono" + /> + </Field> + )} + <Field label="Folder"> + <Input + autoFocus={!sourceFirst && !(inline && reports?.length)} + data-autofocus={inline && !sourceFirst && !reports?.length ? "" : undefined} + value={slug} + onChange={(e) => setSlug(e.target.value)} + placeholder="e.g. donkey-kong" + aria-label="project directory name" + data-new-slug + className="w-48 font-mono" /> + </Field> + <Field label="Title"> + <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="optional" aria-label="project title" data-new-title className="w-52" /> + </Field> + {fields.includes("siteOrigin") && ( + <Field label="Site origin"> + <Input + value={origin} + onChange={(e) => setOrigin(e.target.value)} + placeholder="https://…pages.dev" + aria-label={`site origin — ${FIELD_HINT.siteOrigin}`} + title={FIELD_HINT.siteOrigin} + data-new-origin + className="w-52 font-mono" + /> + </Field> + )} + {fields.includes("brand") && brands.length > 0 && ( + <Field label="Brand"> + <Select value={brand} onChange={(e) => setBrand(e.target.value)} aria-label={`brand — ${FIELD_HINT.brand}`} title={FIELD_HINT.brand} data-new-brand> + <option value="">no brand</option> + {brands.map((b) => ( + <option key={b.id} value={b.id}> + {b.label} + </option> + ))} + </Select> + </Field> )} {fields.includes("seed") && looksLikeVideo && ( - <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title={FIELD_LABEL.seed}> + <label className="flex items-center gap-1.5 pb-1.5 text-[12px] text-text-2" title={FIELD_HINT.seed}> <input type="checkbox" checked={seed} onChange={(e) => setSeed(e.target.checked)} data-new-seed /> - seed from chapters + Seed from the digest's chapters </label> )} - {fields.includes("brand") && brands.length > 0 && ( - <select - value={brand} - onChange={(e) => setBrand(e.target.value)} - aria-label={FIELD_LABEL.brand} - title={FIELD_LABEL.brand} - data-new-brand - className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-2 py-1 text-[12px]" - > - <option value="">no brand</option> - {brands.map((b) => ( - <option key={b.id} value={b.id}> - {b.label} - </option> - ))} - </select> - )} - <button - type="button" - disabled={busy || !slug.trim()} - onClick={create} - data-new-create - className="rounded border border-[var(--color-sel)] px-2.5 py-1 text-[12px] text-[var(--color-sel)] disabled:opacity-40" - > - create - </button> - <button - type="button" - onClick={() => { - setOpen(false); - setError(null); - }} - className="text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]" - > - cancel - </button> + <div className="flex items-center gap-2 pb-px"> + <Button type="submit" variant={inline ? "go" : "primary"} disabled={!hydrated || busy || !slug.trim()} data-new-create> + {busy ? "Creating…" : submitLabel} + </Button> + <Button type="button" variant="quiet" disabled={!hydrated} onClick={cancel}> + Cancel + </Button> + </div> {error && ( - <span className="w-full text-[11px] text-[var(--color-bad)]" data-new-error> + <p role="alert" className="m-0 basis-full text-[12px] text-reject-text" data-new-error> {error} - </span> + </p> )} - </div> + </form> ); } diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -5,6 +5,7 @@ import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import PolicyPanel, { type Today } from "@/components/articles/PolicyPanel"; import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; +import { estimateOf, estimateText } from "@/lib/create/estimate.mjs"; import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // /articles/new (release 27 S8): a question over channels becomes an article's @@ -16,6 +17,12 @@ import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // archive lacks for the question and proposes acquisitions, under the // autonomy chosen here (propose, limits, auto); its queue is on the article's // Iterations tab, and a sweep continues it from there. +// +// It lives on Create (/create?make=article, P5) as "Article from a question": +// there the policy is a chip linking /settings/generation (`showPolicy` +// false), Escape is Cancel, and the ESTIMATE is said before Start -- what such +// runs on the chosen model have spent (the ledger, `history`), under the cap +// (lib/create/estimate.mjs). const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 text-[13px] text-[var(--color-text)] focus-visible:border-[var(--color-sel)] focus-visible:outline-none"; @@ -101,7 +108,26 @@ function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: str ); } -export default function NewArticleForm({ initialPolicy, today, taken }: { initialPolicy: PolicyView | null; today: Today | null; taken: string[] }) { +export default function NewArticleForm({ + initialPolicy, + today, + taken, + showPolicy = true, + framed = true, + history = {}, + onCancel, +}: { + initialPolicy: PolicyView | null; + today: Today | null; + taken: string[]; + /** The policy panel above the form (Create shows a chip instead). */ + showPolicy?: boolean; + /** Its own border (Create's line region frames it instead). */ + framed?: boolean; + /** task -> model -> per-job USD from the ledger, for the estimate. */ + history?: Record<string, Record<string, number[]>>; + onCancel?: () => void; +}) { const router = useRouter(); const [policy, setPolicy] = useState(initialPolicy); const onPolicy = useCallback((p: PolicyView) => setPolicy(p), []); @@ -136,6 +162,10 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia else setModel(task === "agent" ? (policy?.generation.models.api ?? "") : (policy?.generation.models.local ?? "")); }, [task, begin, policy, researchModel]); + const estimate = estimateText( + estimateOf(history, { task: begin, model, cap: capped ? Number(cap) || null : null, local: !model.startsWith("claude-") }), + ); + const idProblem = !id ? null : !ID_RE.test(id) ? "a lowercase slug: a-z, 0-9 and -" : taken.includes(id) ? "an article by that id exists — add an iteration on its page" : null; async function start(e: React.FormEvent) { @@ -174,14 +204,24 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia return ( <div className="flex max-w-4xl flex-col gap-4"> {policy ? ( - <PolicyPanel initial={policy} today={today} onChange={onPolicy} /> + showPolicy && <PolicyPanel initial={policy} today={today} onChange={onPolicy} /> ) : ( <p role="alert" className="text-[12px] text-[var(--color-bad)]"> The editor did not answer, so the policy and the channels are unknown. Start it, then reload. </p> )} - <form onSubmit={start} aria-label="new article" className="flex flex-col gap-3 rounded border border-[var(--color-line)] p-3"> + <form + onSubmit={start} + aria-label="new article" + className={`flex flex-col gap-3 ${framed ? "rounded border border-[var(--color-line)] p-3" : ""}`} + onKeyDown={(e) => { + if (e.key === "Escape" && onCancel) { + e.preventDefault(); + onCancel(); + } + }} + > <label className="flex flex-col gap-1"> <span className="micro">question</span> <textarea className={field} rows={2} required value={question} onChange={(e) => setQuestion(e.target.value)} aria-label="question" /> @@ -286,7 +326,24 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia <Button type="submit" variant="primary" size="lg" disabled={sending || !policy}> {sending ? "Starting…" : "Start"} </Button> + {onCancel && ( + <Button type="button" variant="quiet" size="lg" onClick={onCancel}> + Cancel + </Button> + )} </div> + {policy && ( + <p className="text-[12px] text-[var(--color-dim)]" data-estimate={begin}> + <span className="micro mr-2">estimate</span> + {estimate} + {today ? ( + <span className="ml-2"> + · today <span className="num text-[var(--color-meter)]">${today.usd.toFixed(2)}</span> + {today.daily > 0 ? ` of $${today.daily.toFixed(2)}` : ""} + </span> + ) : null} + </p> + )} {begin === "research" && policy && ( <p className="text-[12px] text-[var(--color-dim)]" data-research-limits> Limits a run: {policy.generation.research.maxItemsPerRun} items, {policy.generation.research.maxGbPerRun} GB,{" "} diff --git a/umtool/components/create/CreateView.tsx b/umtool/components/create/CreateView.tsx @@ -0,0 +1,244 @@ +"use client"; + +import { Fragment, useCallback, useEffect, useRef, useState } from "react"; +import NewArticleForm from "@/components/articles/NewArticleForm"; +import NewProjectMenu from "@/components/NewProjectMenu"; +import { Button } from "@/components/ui/button"; +import { LitList } from "@/components/ui/lit-list"; +import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; +import { createHref, type Make } from "@/lib/hrefs"; +import type { CreateData } from "@/lib/create"; +import { ArticleVideoForm, BoardForm, ResearchForm } from "./forms"; + +// --------------------------------------------------------------------------- +// CREATE (plans/umtool-redesign.md, P5; canvas "Create"): "What are you +// making?" as ONE lit list of lines in four groups -- Research · Article in the +// left column, Video · Song in the right -- each line a thing to make and the +// button that opens its form, inline under it. Every form is a thin shell over +// a writer that already exists (forms.tsx, NewArticleForm, NewProjectMenu); the +// result navigates to what was made. +// +// Keys: j/k (or the arrows) glide the lit line, Enter opens its form (the first +// field takes the focus), Escape closes it and puts the focus back on the line. +// The open form is in the address (`?make=`), so a reload or a link lands on +// it; `?from=<channel>/<id>` (the editor's hand-off) opens "Video from a +// recording" prefilled. +// --------------------------------------------------------------------------- + +const LIST_KEYS = new Set(["j", "k", "ArrowUp", "ArrowDown", "Home", "End"]); + +type Line = { make: Make; title: string; sub: string; action: string }; + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + +function lines(d: CreateData): { group: string; lines: Line[] }[][] { + const board = d.cases.find((c) => c.quotes > 0) ?? d.cases[0]; + const boardSub = board ? `${board.title} · ${plural(board.quotes, "quote")}${d.cases.length > 1 ? ` · ${plural(d.cases.length, "board")}` : ""}` : "No boards yet"; + return [ + [ + { group: "Research", lines: [{ make: "research", title: "Research a question", sub: "Opens a case: search, read, pin quotes to a board", action: "Open a case" }] }, + { + group: "Article", + lines: [ + { make: "article", title: "From a question", sub: "A sweep writes iteration 1 · estimate shown before it runs", action: "Start sweep" }, + { make: "article-board", title: "From a board", sub: boardSub, action: "Draft article" }, + ], + }, + ], + [ + { + group: "Video", + lines: [ + { make: "video-article", title: "From an article", sub: "Chains a cut from the current report", action: "Choose article" }, + { make: "video-board", title: "From a board", sub: "A timeline scaffolded from the pinned cites", action: "Choose board" }, + { make: "video-recording", title: "From a recording", sub: "A video URL, or <channel>/<id> from the archive", action: "Choose recording" }, + { + make: "video-report", + title: "From a sweep report", + sub: d.reports.length ? `A cited markdown report on disk · ${plural(d.reports.length, "found", "found")}` : "A cited markdown report on disk", + action: "Choose report", + }, + ], + }, + { group: "Song", lines: [{ make: "song", title: "A song cut", sub: "From the song piles in Tools", action: "New song" }] }, + ], + ]; +} + +export default function CreateView({ + data, + initial, + from, + initialCase, + initialArticle, +}: { + data: CreateData; + initial: Make | null; + from: string | null; + initialCase: string | null; + initialArticle: string | null; +}) { + const [open, setOpen] = useState<Make | null>(initial); + const root = useRef<HTMLDivElement>(null); + const columns = lines(data); + + // The open form is the address, so a reload lands on it (no navigation: the + // page has everything it needs). + const show = useCallback((m: Make | null) => { + setOpen(m); + try { + window.history.replaceState(window.history.state, "", m ? createHref({ make: m }) : createHref()); + } catch { + // a browser that refuses is only a lost bookmark + } + }, []); + + // Closing puts the focus back on the line's button, so the keys go on. + const close = useCallback( + (m: Make) => { + show(null); + requestAnimationFrame(() => root.current?.querySelector<HTMLElement>(`[data-make="${m}"]`)?.focus()); + }, + [show], + ); + + // An open form takes the focus: its first field (the one marked + // data-autofocus, else the first control), once the list's controls are + // live -- a form opened from the address was server-rendered inside the + // list's disabled fieldset, where React's autoFocus never runs. + useEffect(() => { + if (!open) return; + let frames = 0; + let raf = 0; + const go = () => { + const region = root.current?.querySelector<HTMLElement>(`[data-make-form="${open}"]`); + const el = + region?.querySelector<HTMLElement>("[data-autofocus]") ?? + region?.querySelector<HTMLElement>("input:not([type=hidden]):not([type=radio]):not([type=checkbox]), textarea, select"); + if (el && !el.matches(":disabled")) { + if (!region?.contains(document.activeElement)) el.focus(); + region?.scrollIntoView({ block: "nearest" }); + return; + } + if (++frames < 30) raf = requestAnimationFrame(go); + }; + raf = requestAnimationFrame(go); + return () => cancelAnimationFrame(raf); + }, [open]); + + const form = (m: Make) => { + const cancel = () => close(m); + switch (m) { + case "research": + return <ResearchForm sources={data.sources} onCancel={cancel} />; + case "article": + return ( + <NewArticleForm initialPolicy={data.policy} today={data.today} taken={data.taken} showPolicy={false} framed={false} history={data.history} onCancel={cancel} /> + ); + case "article-board": + return <BoardForm to="article" cases={data.cases} casesError={data.casesError} initialCase={initialCase} onCancel={cancel} />; + case "video-board": + return <BoardForm to="video" cases={data.cases} casesError={data.casesError} initialCase={initialCase} onCancel={cancel} />; + case "video-article": + return <ArticleVideoForm articles={data.articles} initialArticle={initialArticle} onCancel={cancel} />; + case "video-recording": + return data.kinds.recording ? ( + <NewProjectMenu + kinds={[data.kinds.recording]} + kind={data.kinds.recording.id} + inline + from={from} + fromLabel="Recording" + fromHint="a viewer share URL (…/?v=<channel>%2F<id>&t=<s>) or <channel>/<videoId>" + fromPlaceholder="channel/videoId, or a share URL" + submitLabel="Create the project" + onCancel={cancel} + /> + ) : null; + case "video-report": + return data.kinds.report ? ( + <NewProjectMenu + kinds={[data.kinds.report]} + kind={data.kinds.report.id} + inline + reports={data.reports} + fromLabel="Report" + fromHint="the path of a cited markdown report (.md)" + fromPlaceholder="/path/to/sweep-report.md" + submitLabel="Create the project" + onCancel={cancel} + /> + ) : null; + case "song": + return data.kinds.song ? <NewProjectMenu kinds={[data.kinds.song]} kind={data.kinds.song.id} inline submitLabel="Create the song" onCancel={cancel} /> : null; + } + }; + + return ( + <div ref={root}> + <LitList label="What to make" global columns initial={0}> + <div className="grid gap-x-7 gap-y-[18px] lg:grid-cols-2"> + {columns.map((col, i) => ( + <div key={i} className="flex min-w-0 flex-col gap-[18px]"> + {col.map((g) => ( + <LitGroup key={g.group} title={g.group} className="!mt-0" data-make-group={g.group}> + {g.lines.map((l) => ( + <Fragment key={l.make}> + <LitLine + id={l.make} + initial={open === l.make} + data-make-line={l.make} + className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 py-3" + onKeyDown={(e) => { + if (e.key === "Enter" && e.target === e.currentTarget) { + e.preventDefault(); + show(open === l.make ? null : l.make); + } + }} + > + <div className="min-w-0"> + <b className="block text-[14px] font-semibold">{l.title}</b> + <small className="block truncate text-[12.5px] text-muted-2">{l.sub}</small> + </div> + <LitActions> + <Button + type="button" + // Filled on the lit line -- until its form is open: + // then the form's own button is the one primary action. + className={open === l.make ? undefined : "lit-go"} + data-make={l.make} + aria-expanded={open === l.make} + aria-controls={`make-${l.make}`} + onClick={() => show(open === l.make ? null : l.make)} + > + {l.action} + </Button> + </LitActions> + </LitLine> + {open === l.make && ( + <div + id={`make-${l.make}`} + data-make-form={l.make} + role="region" + aria-label={`${g.group}: ${l.title}`} + className="border-b border-seam bg-panel px-5 pb-4 pt-3" + // The list's keys belong to the lines: j/k on a button + // in a form must not move the light (⌘K still passes). + onKeyDown={(e) => { + if (!e.metaKey && !e.ctrlKey && !e.altKey && LIST_KEYS.has(e.key)) e.stopPropagation(); + }} + > + {form(l.make)} + </div> + )} + </Fragment> + ))} + </LitGroup> + ))} + </div> + ))} + </div> + </LitList> + </div> + ); +} diff --git a/umtool/components/create/forms.tsx b/umtool/components/create/forms.tsx @@ -0,0 +1,335 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import HandoffDialog from "@/components/research/HandoffDialog"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { chainable, defaultChainIteration } from "@/lib/create/iterations.mjs"; +import { articleHref } from "@/lib/hrefs"; +import { researchCaseHref, researchCasesApi } from "@/lib/research/hrefs"; +import type { CaseSummary } from "@/lib/research/case-types"; +import type { SourceOption } from "@/lib/research/types"; + +// --------------------------------------------------------------------------- +// Create's own forms (plans/umtool-redesign.md, P5). Each is a thin shell over +// a writer that already exists -- none writes anything itself: +// +// ResearchForm POST /api/research/cases (R2) → the case's board +// BoardForm a board, then R2's hand-off: POST …/<case>/handoff, its +// plan shown and confirmed in R2's HandoffDialog → the +// article's iterations, or the new project +// ArticleVideoForm an article and a done iteration, the chain's steps +// (GET /api/articles/chain), then POST it → the article's +// iterations, where the chain runs +// +// Keyboard first: the first field takes the focus, Enter submits, Escape is +// Cancel (CreateView puts the focus back on the line). +// --------------------------------------------------------------------------- + +async function json<T>(r: Response): Promise<T> { + const b = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(b?.error ?? `HTTP ${r.status}`); + return b as T; +} + +const escToCancel = (onCancel: () => void) => (e: React.KeyboardEvent) => { + if (e.key === "Escape" && !e.defaultPrevented) { + e.preventDefault(); + onCancel(); + } +}; + +function Actions({ children, error }: { children: React.ReactNode; error?: string | null }) { + return ( + <> + <div className="flex items-center gap-2 pb-px">{children}</div> + {error && ( + <p role="alert" className="m-0 basis-full text-[12px] text-reject-text"> + {error} + </p> + )} + </> + ); +} + +// ── Research a question ───────────────────────────────────────────────────── + +export function ResearchForm({ sources, onCancel }: { sources: SourceOption[]; onCancel: () => void }) { + const router = useRouter(); + const [query, setQuery] = useState(""); + const [title, setTitle] = useState(""); + const [source, setSource] = useState(sources[0]?.handle ?? ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const open = async () => { + if (!query.trim()) return; + setBusy(true); + setError(null); + try { + const r = await json<{ case: { id: string } }>( + await fetch(researchCasesApi(), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ query: query.trim(), ...(title.trim() ? { title: title.trim() } : {}), ...(source ? { scope: { source } } : {}) }), + }), + ); + router.push(researchCaseHref(r.case.id)); + } catch (e) { + setError((e as Error).message); + setBusy(false); + } + }; + return ( + <form + aria-label="research a question" + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onKeyDown={escToCancel(onCancel)} + onSubmit={(e) => { + e.preventDefault(); + void open(); + }} + > + <Field label="Question" hint="The case's query; its board opens next" className="min-w-0 basis-full"> + <Input autoFocus data-autofocus="" required value={query} onChange={(e) => setQuery(e.target.value)} aria-label="question" placeholder="e.g. how many employees" /> + </Field> + <Field label="Title"> + <Input value={title} onChange={(e) => setTitle(e.target.value)} aria-label="case title" placeholder="the question, unless named" className="w-56" /> + </Field> + {sources.length > 0 && ( + <Field label="Corpus"> + <Select value={source} onChange={(e) => setSource(e.target.value)} aria-label="corpus"> + {sources.map((s) => ( + <option key={s.handle} value={s.handle}> + {s.label} + {s.detail ? ` — ${s.detail}` : ""} + </option> + ))} + </Select> + </Field> + )} + <Actions error={error}> + <Button type="submit" variant="go" disabled={busy || !query.trim()}> + {busy ? "Opening…" : "Open a case"} + </Button> + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + </Actions> + </form> + ); +} + +// ── An article or a video from a board (R2's hand-off) ────────────────────── + +export function BoardForm({ + to, + cases, + casesError, + initialCase, + onCancel, +}: { + to: "article" | "video"; + cases: CaseSummary[]; + casesError: string | null; + initialCase?: string | null; + onCancel: () => void; +}) { + const router = useRouter(); + const withQuotes = cases.filter((c) => c.quotes > 0); + const [pick, setPick] = useState( + initialCase && cases.some((c) => c.id === initialCase) ? initialCase : (withQuotes[0]?.id ?? cases[0]?.id ?? ""), + ); + const [planning, setPlanning] = useState(false); + const chosen = cases.find((c) => c.id === pick); + if (!cases.length) { + return ( + <p className="m-0 text-[12.5px] text-text-2" data-no-boards=""> + {casesError ? `The boards do not read: ${casesError}` : "No boards yet. Pin quotes from Research to a board, then hand it off here."} + </p> + ); + } + return ( + <> + <form + aria-label={to === "article" ? "article from a board" : "video from a board"} + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onKeyDown={escToCancel(onCancel)} + onSubmit={(e) => { + e.preventDefault(); + if (chosen) setPlanning(true); + }} + > + <Field label="Board" hint={chosen ? `${chosen.quotes} ${chosen.quotes === 1 ? "quote" : "quotes"} · ${chosen.sections} ${chosen.sections === 1 ? "section" : "sections"}` : undefined}> + <Select autoFocus data-autofocus="" value={pick} onChange={(e) => setPick(e.target.value)} aria-label="board" data-board-pick="" className="w-80"> + {cases.map((c) => ( + <option key={c.id} value={c.id}> + {c.title} · {c.quotes} {c.quotes === 1 ? "quote" : "quotes"} + </option> + ))} + </Select> + </Field> + <Actions> + <Button type="submit" variant="go" disabled={!chosen || chosen.quotes === 0}> + {to === "article" ? "Plan the article" : "Plan the video"} + </Button> + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + </Actions> + {chosen && chosen.quotes === 0 && <p className="m-0 basis-full text-[12px] text-muted">That board has no quotes yet.</p>} + </form> + {/* Outside the form: the dialog carries a form of its own (method="dialog"). */} + <HandoffDialog + caseId={pick} + to={planning ? to : null} + onClose={() => setPlanning(false)} + onDone={(href) => { + setPlanning(false); + router.push(href); + }} + /> + </> + ); +} + +// ── A video from an article: the chain over a done iteration ──────────────── + +type IterRow = { n: number; label: string; status: string; hasReport: boolean; reportFrom: number | null; currentReport: boolean; kind: string }; +type ChainView = { steps: { name: string; label: string; status: string; optional: boolean }[]; resumeAt: string | null; job: { id: string; state: string } | null }; + +export function ArticleVideoForm({ + articles, + initialArticle, + onCancel, +}: { + articles: { id: string; title: string; status: string | null }[]; + initialArticle?: string | null; + onCancel: () => void; +}) { + const router = useRouter(); + const [article, setArticle] = useState(initialArticle && articles.some((a) => a.id === initialArticle) ? initialArticle : (articles[0]?.id ?? "")); + const [its, setIts] = useState<IterRow[] | null>(null); + const [n, setN] = useState<number | null>(null); + const [chain, setChain] = useState<ChainView | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + + // The article's iterations: those with a report (done) are what a chain runs over. + useEffect(() => { + if (!article) return; + let live = true; + setIts(null); + setN(null); + setChain(null); + setError(null); + fetch(`/api/articles/iterations?article=${encodeURIComponent(article)}`, { cache: "no-store" }) + .then((r) => json<{ iterations: IterRow[] }>(r)) + .then((b) => { + if (!live) return; + // Done, with a report, newest first; the default is the newest with a + // report of its own (a chain cuts from a report), never a video revision. + const done = chainable(b.iterations); + setIts(done); + setN(defaultChainIteration(b.iterations) ?? done[0]?.n ?? null); + }) + .catch((e: Error) => live && setError(e.message)); + return () => { + live = false; + }; + }, [article]); + + // The chain's steps for that iteration, and where a start resumes. + useEffect(() => { + if (!article || n === null) return; + let live = true; + setChain(null); + fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" }) + .then((r) => json<{ chain: ChainView }>(r)) + .then((b) => live && setChain(b.chain)) + .catch((e: Error) => live && setError(e.message)); + return () => { + live = false; + }; + }, [article, n]); + + const start = async () => { + if (!article || n === null) return; + setBusy(true); + setError(null); + try { + await json(await fetch("/api/articles/chain", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ article, n }) })); + router.push(articleHref({ site: "articles", id: article }, { tab: "iterations" })); + } catch (e) { + setError((e as Error).message); + setBusy(false); + } + }; + + if (!articles.length) { + return <p className="m-0 text-[12.5px] text-text-2">No article in the store yet. Start one from a question.</p>; + } + const chosen = its?.find((it) => it.n === n) ?? null; + const todo = chain ? chain.steps.filter((s) => !s.optional) : []; + const from = chain?.resumeAt ? todo.findIndex((s) => s.name === chain.resumeAt) : -1; + return ( + <form + aria-label="video from an article" + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onKeyDown={escToCancel(onCancel)} + onSubmit={(e) => { + e.preventDefault(); + void start(); + }} + > + <Field label="Article"> + <Select autoFocus data-autofocus="" value={article} onChange={(e) => setArticle(e.target.value)} aria-label="article" className="w-80"> + {articles.map((a) => ( + <option key={a.id} value={a.id}> + {a.title} — {a.id} + </option> + ))} + </Select> + </Field> + <Field label="Iteration"> + <Select value={n ?? ""} onChange={(e) => setN(Number(e.target.value))} aria-label="iteration" disabled={!its?.length}> + {!its && <option value="">reading…</option>} + {its && its.length === 0 && <option value="">none done</option>} + {its?.map((it) => ( + <option key={it.n} value={it.n}> + {it.label} · {it.kind} + {it.currentReport ? " · current" : ""} + </option> + ))} + </Select> + </Field> + <Actions error={error}> + <Button type="submit" variant="go" disabled={busy || n === null || !chain || chain.resumeAt === null || chain.job?.state === "running"}> + {busy ? "Starting…" : "Make the video"} + </Button> + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + </Actions> + {its && its.length === 0 && <p className="m-0 basis-full text-[12px] text-muted">This article has no done iteration with a report: the chain runs over one.</p>} + {chain && ( + <p className="m-0 basis-full text-[12px] text-muted" data-chain-plan={chain.resumeAt ?? "done"}> + {chosen && ( + <span className="mr-1 text-text-2" data-chain-iteration={chosen.n}> + {chosen.label} · {chosen.kind} + {chosen.hasReport ? "" : ` (the report of i${chosen.reportFrom})`}: + </span> + )} + {chain.job?.state === "running" + ? "Its chain is running now." + : chain.resumeAt === null + ? "Every step is done; run one again from the article's Iterations tab." + : `${todo.length - Math.max(from, 0)} of ${todo.length} steps to run, from “${todo[Math.max(from, 0)]?.label}”: ${todo + .slice(Math.max(from, 0)) + .map((s) => s.label) + .join(" → ")}`} + </p> + )} + </form> + ); +} diff --git a/umtool/components/piece/PolicyChip.tsx b/umtool/components/piece/PolicyChip.tsx @@ -1,14 +1,13 @@ import Link from "next/link"; import { badgeVariants } from "@/components/ui/badge"; import { readPolicy, readToday } from "@/lib/articles/generation"; -import { generationSettingsHref } from "@/lib/hrefs"; +import { generationPolicyHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; // THE GENERATION POLICY, as a chip (P4a-2; canvas "Create": "Policy shown as a // chip"): the policy's one line -- its preset, the API model, the day's spend // against the daily cap -- with a Meter dot, linking to where it is set -// (/settings/generation, P5's page). The panel itself (PolicyPanel) is not on -// the article piece; it stays on the new-article form until P5 moves it. +// (/settings/generation, P5's page, which holds the PolicyPanel). // // Async: the policy is the editor's (askEditor), so the frame streams this in // under a <Suspense>; an editor that does not answer is said, not hidden. @@ -19,7 +18,7 @@ const shortModel = (m: string) => m.replace(/^claude-/, ""); export function PolicyChipShell({ children, preset }: { children: React.ReactNode; preset?: string }) { return ( <Link - href={generationSettingsHref()} + href={generationPolicyHref()} prefetch={false} data-policy-chip={preset ?? ""} title="Generation policy: routes, models, caps" diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx @@ -39,7 +39,7 @@ export default async function AppRail({ active }: { active: string }) { <AppNav active={active} /> - <CreateMenu /> + <CreateMenu active={active === "create"} /> <JumpButton /> diff --git a/umtool/components/shell/CreateMenu.tsx b/umtool/components/shell/CreateMenu.tsx @@ -1,52 +1,21 @@ -"use client"; - import Link from "next/link"; -import { useEffect, useRef, useState } from "react"; -import { newArticleHref, projectsHref } from "@/lib/hrefs"; +import { createHref } from "@/lib/hrefs"; -// + Create. Until /create exists (P5) it opens onto today's two doors: a new -// article (/articles/new) and a new project (/projects?new=1 opens 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]); +// + Create (canvas `.create`): the rail's one way in to /create, "What are you +// making?" (P5) -- research, an article, a video, a song, each a line there +// with its form. A link, not a menu: the page IS the menu. Its edge is Signal +// while you are on it. ⌘K's create actions open a line of it directly +// (`/create?make=…`). +export default function CreateMenu({ active = false }: { active?: boolean }) { 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={projectsHref({ new: true })} 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> + <Link + href={createHref()} + prefetch={false} + data-rail-create="" + aria-current={active ? "page" : undefined} + className={`mx-4 mb-1 mt-2.5 flex items-center gap-2 rounded-[3px] border px-2.5 py-[6px] font-medium text-text no-underline hover:border-muted ${active ? "border-signal" : "border-seam-2"}`} + > + + Create + </Link> ); } diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -4,12 +4,12 @@ import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { benchHref, + createHref, facesHref, findHref, generationPolicyHref, homeHref, mixHref, - newArticleHref, pileHref, projectsHref, researchHref, @@ -46,7 +46,8 @@ const FIXED: Item[] = [ { id: "projects", section: "Places", label: "Projects", hint: "every project, by folder", href: projectsHref() }, { id: "tools", section: "Places", label: "Tools", hint: "find, mix, song piles, faces, sources", href: toolsHref() }, { id: "system", section: "Places", label: "Settings · system", hint: "tools, disk, index, sources, recent jobs", href: systemHref() }, - { id: "policy", section: "Places", label: "Settings · generation policy", hint: "on the new-article form until /settings/generation", href: generationPolicyHref() }, + { id: "create", section: "Places", label: "Create", hint: "what are you making?", href: createHref() }, + { id: "policy", section: "Places", label: "Settings · generation", hint: "routes, models, caps, the key, today's spend", href: generationPolicyHref() }, { id: "find", section: "Tools", label: "Find", hint: "every occurrence of a word", href: findHref() }, { id: "mix", section: "Tools", label: "Mix", hint: "the mix bench", href: mixHref() }, { id: "song", section: "Tools", label: "Song piles", hint: "sort, salvage, verify, keeps", href: songToolsHref() }, @@ -54,8 +55,15 @@ const FIXED: Item[] = [ { id: "faces", section: "Tools", label: "Faces", hint: "the face judger", href: facesHref() }, { id: "sources", section: "Tools", label: "Sources", hint: "where the palette comes from", href: sourcesHref() }, { id: "bench", section: "Tools", label: "Verdict bench", hint: "could a model propose a verdict", href: benchHref() }, - { id: "new-article", section: "Create", label: "New article", hint: "from a question", href: newArticleHref() }, - { id: "new-project", section: "Create", label: "New project", hint: "a video, a song, a sweep", href: projectsHref({ new: true }) }, + // Each opens one line of /create (P5), its form open. + { id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) }, + { id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) }, + { id: "new-article-board", section: "Create", label: "New article from a board", hint: "a seeded sweep, planned first", href: createHref({ make: "article-board" }) }, + { id: "new-video-article", section: "Create", label: "New video from an article", hint: "the chain over an iteration", href: createHref({ make: "video-article" }) }, + { id: "new-video-board", section: "Create", label: "New video from a board", hint: "a timeline from the pinned cites", href: createHref({ make: "video-board" }) }, + { id: "new-video-recording", section: "Create", label: "New video from a recording", hint: "a URL or channel/id", href: createHref({ make: "video-recording" }) }, + { id: "new-video-report", section: "Create", label: "New video from a sweep report", hint: "a cited report on disk", href: createHref({ make: "video-report" }) }, + { id: "new-song", section: "Create", label: "New song", hint: "a song cut", href: createHref({ make: "song" }) }, ]; const words = (q: string) => q.toLowerCase().split(/\s+/).filter(Boolean); diff --git a/umtool/components/system/ActionPlan.tsx b/umtool/components/system/ActionPlan.tsx @@ -0,0 +1,201 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import type { ActionAnswer, ActionPlanView } from "@/lib/system/plan-types"; + +// --------------------------------------------------------------------------- +// PLAN, THEN CONFIRM for Settings · system's actions (P5) -- the DeletePlan +// pattern (components/DeletePlan.tsx) for a move or a prune: the button asks +// the route for the PLAN (a dry run: what it touches, with sizes, what refuses, +// what is worth knowing), shows it, and acts only on the confirm, whose words +// say what happens ("Move out", "Drop 2 records"). "Keep it" closes the plan +// and nothing was written. A long one starts a umtool job (the rail's Running +// list has it); the page re-reads when it is started. +// +// Labels are contracts (e2e/settings.spec.ts): the region is "plan <subject>" +// holding the lists "touches", "refused" and "worth knowing", and the buttons +// <confirm> (data-plan-confirm) and "Keep it". +// --------------------------------------------------------------------------- + +const fmt = (n: number) => { + if (n < 1024) return `${n} B`; + const u = ["KiB", "MiB", "GiB", "TiB"]; + let v = n / 1024; + let i = 0; + while (v >= 1024 && i < u.length - 1) { + v /= 1024; + i += 1; + } + return `${v.toFixed(v >= 100 ? 0 : 1)} ${u[i]}`; +}; + +type Phase = + | { at: "closed"; done?: string } + | { at: "asking" } + | { at: "plan"; plan: ActionPlanView; error: string | null } + | { at: "working"; plan: ActionPlanView } + | { at: "error"; error: string }; + +async function post(endpoint: string, body: Record<string, unknown>) { + const r = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const b = (await r.json().catch(() => ({}))) as Partial<ActionAnswer> & { plan?: ActionPlanView; error?: string }; + return { ok: r.ok, status: r.status, body: b }; +} + +export default function ActionPlan({ + label, + subject, + endpoint, + body, + variant = "outline", +}: { + /** The trigger's words ("Move out", "Prune"). */ + label: string; + /** What it acts on, for the region's name ("index prune", "reports/x out"). */ + subject: string; + endpoint: string; + body: Record<string, unknown>; + variant?: "outline" | "destructive"; +}) { + const router = useRouter(); + const hydrated = useHydrated(); + const [phase, setPhase] = useState<Phase>({ at: "closed" }); + // The keys follow the plan: it opens on its confirm (or Keep it when there + // is nothing to confirm), and closing returns to the button that opened it. + const trigger = useRef<HTMLButtonElement>(null); + const first = useRef<HTMLButtonElement>(null); + const opened = useRef(false); + useEffect(() => { + if (phase.at === "plan" || phase.at === "error") { + opened.current = true; + first.current?.focus(); + } else if (phase.at === "closed" && opened.current) { + opened.current = false; + trigger.current?.focus(); + } + }, [phase.at]); + + const ask = async () => { + setPhase({ at: "asking" }); + try { + const r = await post(endpoint, { ...body, dryRun: true }); + if (r.body.plan) setPhase({ at: "plan", plan: r.body.plan, error: null }); + else setPhase({ at: "error", error: r.body.error ?? `HTTP ${r.status}` }); + } catch (e) { + setPhase({ at: "error", error: (e as Error).message }); + } + }; + + const confirm = async (plan: ActionPlanView) => { + setPhase({ at: "working", plan }); + try { + const r = await post(endpoint, body); + if (r.ok && r.body.applied) { + setPhase({ at: "closed", done: r.body.job ? `${r.body.message} — a job, in Running` : r.body.message }); + router.refresh(); + return; + } + setPhase({ at: "plan", plan: r.body.plan ?? plan, error: r.body.error ?? `HTTP ${r.status}` }); + } catch (e) { + setPhase({ at: "plan", plan, error: (e as Error).message }); + } + }; + + if (phase.at === "closed") { + return ( + <span className="inline-flex flex-wrap items-center gap-2"> + <Button ref={trigger} size="sm" variant={variant} disabled={!hydrated} onClick={() => void ask()} data-plan-trigger={subject}> + {label} + </Button> + {phase.done && ( + <span role="status" className="text-[12px] text-text-2" data-plan-done={subject}> + {phase.done} + </span> + )} + </span> + ); + } + if (phase.at === "asking") return <span className="text-[12px] text-muted">Reading the plan…</span>; + if (phase.at === "error") { + return ( + <span role="alert" className="flex items-center gap-2 text-[12px] text-reject-text"> + {phase.error} + <Button ref={first} size="sm" variant="quiet" onClick={() => setPhase({ at: "closed" })}> + Keep it + </Button> + </span> + ); + } + const plan = phase.plan; + return ( + <section + role="region" + aria-label={`plan ${subject}`} + data-plan={plan.action} + data-plan-blocked={plan.blocked ? "yes" : "no"} + className="mt-2 basis-full rounded-[3px] border border-seam-2 bg-ink p-3 text-[12px]" + onKeyDown={(e) => { + if (e.key === "Escape" && phase.at === "plan") { + e.preventDefault(); + setPhase({ at: "closed" }); + } + }} + > + <p className="m-0 font-semibold text-text">{plan.title}</p> + <p className="m-0 mt-0.5 text-text-2">{plan.summary}</p> + {plan.refusals.length > 0 && ( + <ul aria-label="refused" className="mt-1.5 list-disc pl-5 text-reject-text"> + {plan.refusals.map((r, i) => ( + <li key={i}>{r}</li> + ))} + </ul> + )} + {plan.warnings.length > 0 && ( + <ul aria-label="worth knowing" className="mt-1.5 list-disc pl-5 text-doubt-text"> + {plan.warnings.map((w, i) => ( + <li key={i}>{w}</li> + ))} + </ul> + )} + {plan.rows.length > 0 && ( + <ul aria-label="touches" className="mt-1.5 grid max-h-[220px] list-none gap-0.5 overflow-auto p-0"> + {plan.rows.map((r, i) => ( + <li key={`${r.label}-${i}`} data-plan-row={r.label} data-plan-state={r.state ?? ""} className="grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 font-mono text-[11px]"> + <span className="min-w-0 truncate"> + <span className="text-text">{r.label}</span> <span className="text-muted-2">{r.what}</span> + </span> + <span className="num text-meter"> + {r.bytes !== undefined ? `${fmt(r.bytes)}${r.files !== undefined ? ` · ${r.files} files` : ""}` : ""} + </span> + </li> + ))} + </ul> + )} + {phase.at === "plan" && phase.error && ( + <p role="alert" className="m-0 mt-1.5 text-reject-text"> + {phase.error} + </p> + )} + <div className="mt-2.5 flex flex-wrap items-center gap-2"> + {!plan.blocked && ( + <Button + ref={first} + size="sm" + variant={variant === "destructive" ? "destructive" : "primary"} + disabled={phase.at === "working"} + onClick={() => void confirm(plan)} + data-plan-confirm="" + > + {phase.at === "working" ? "Working…" : plan.confirm} + </Button> + )} + <Button ref={plan.blocked ? first : undefined} size="sm" variant="quiet" onClick={() => setPhase({ at: "closed" })}> + Keep it + </Button> + </div> + </section> + ); +} diff --git a/umtool/components/system/Maintenance.tsx b/umtool/components/system/Maintenance.tsx @@ -0,0 +1,129 @@ +import ActionPlan from "@/components/system/ActionPlan"; +import { Panel } from "@/components/ui/panel"; +import { fmtAgo } from "@/lib/format"; +import type { StorageRow } from "@/lib/system/storage-rows"; + +// --------------------------------------------------------------------------- +// Settings · system's maintenance (P5): what `umtool doctor`, `umtool index` +// and `umtool storage` say and do, on the page. Reading is free; every action +// that changes or moves anything is a plan first (ActionPlan): Confirm, or +// Keep it. Server-rendered; the plans are the client's. +// --------------------------------------------------------------------------- + +type Roots = { + ok: boolean; + reports: { path: string; present: boolean }; + media: { path: string; tiered: boolean; present: boolean; problem: string | null }; + cache: { path: string; present: boolean; index: boolean }; + oldCache: { path: string; present: boolean }; +}; + +function Row({ k, children, bad = false }: { k: string; children: React.ReactNode; bad?: boolean }) { + return ( + <> + <dt className="text-muted">{k}</dt> + <dd className={`m-0 min-w-0 break-all font-mono text-[11.5px] ${bad ? "text-reject-text" : "text-text-2"}`}>{children}</dd> + </> + ); +} + +export function RootsPanel({ roots }: { roots: Roots }) { + return ( + <Panel title="Roots" aside={<span className="text-muted-2">umtool doctor</span>} data-panel="roots" data-roots-ok={roots.ok ? "yes" : "no"}> + <dl className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-[12px]"> + <Row k="reports" bad={!roots.reports.present}> + {roots.reports.path} + {roots.reports.present ? "" : " — not there"} + </Row> + <Row k="media" bad={!!roots.media.problem}> + {roots.media.tiered ? roots.media.path : "= reports (UMTOOL_MEDIA_DIR unset): out/ stays in each project"} + {roots.media.problem ? ` — ${roots.media.problem}` : ""} + </Row> + <Row k="cache"> + {roots.cache.path} + {roots.cache.index ? "" : " — no index yet"} + </Row> + {roots.oldCache.present && <Row k="old cache">{roots.oldCache.path} — the cache&apos;s old place, no longer read; derived, safe to delete</Row>} + </dl> + </Panel> + ); +} + +export function IndexPanel({ index }: { index: { ok: boolean; records: number; path: string | null; builtAt: number | null; stale: number } }) { + return ( + <Panel title="Index" aside={<span className="text-muted-2">umtool index</span>} data-panel="index" data-index-records={index.records} data-index-stale={index.stale}> + {index.ok ? ( + <p className="m-0 text-[12.5px] text-text-2"> + <b className="num text-meter">{index.records}</b> records + {index.stale > 0 ? ( + <> + , <b className="num text-meter">{index.stale}</b> for projects that are gone + </> + ) : null} + {index.builtAt ? ` · rebuilt ${fmtAgo(index.builtAt)}` : ""}. A cache of the walk: every read checks its own signature, so deleting it changes nothing but + latency. + </p> + ) : ( + <p className="m-0 text-[12.5px] text-text-2">No index (the lmdb store did not open): a normal state — everything works, just slower.</p> + )} + {index.path && <p className="m-0 mt-1 truncate font-mono text-[11px] text-muted-2">{index.path}</p>} + <div className="mt-2.5 flex flex-wrap items-start gap-2"> + <ActionPlan label="Rebuild…" subject="index rebuild" endpoint="/api/system/index" body={{ action: "rebuild" }} /> + <ActionPlan label="Prune…" subject="index prune" endpoint="/api/system/index" body={{ action: "prune" }} variant="destructive" /> + </div> + </Panel> + ); +} + +const WORD: Record<string, string> = { absent: "none", dir: "here", link: "on media", dangling: "DRIVE MISSING", other: "not a directory" }; + +export function StoragePanel({ rows, tiered, mediaRoot }: { rows: StorageRow[]; tiered: boolean; mediaRoot: string }) { + const outs = rows.filter((r) => r.out !== "absent"); + return ( + <Panel + title="Storage" + aside={<span className="text-muted-2">umtool storage · {tiered ? `media root ${mediaRoot}` : "no media root (UMTOOL_MEDIA_DIR unset)"}</span>} + data-panel="storage" + className="lg:col-span-2 2xl:col-span-3" + > + <div className="mb-2 flex flex-wrap items-start gap-2"> + <ActionPlan label="Move every out/ to the media root…" subject="storage move-out all" endpoint="/api/system/storage" body={{ action: "move-out", all: true }} /> + <ActionPlan label="Move every out/ back…" subject="storage move-back all" endpoint="/api/system/storage" body={{ action: "move-back", all: true }} /> + </div> + {outs.length === 0 && rows.length === 0 ? ( + <p className="m-0 text-[12px] text-muted">No projects.</p> + ) : ( + <ul aria-label="projects' storage" className="m-0 grid max-h-[420px] list-none overflow-auto p-0 text-[12px]"> + {rows.map((r) => ( + <li key={r.id} data-storage-row={r.id} data-out={r.out} className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-seam py-1.5 first:border-t-0"> + <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-text">{r.id}</span> + <span className={`text-[11.5px] ${r.out === "dangling" ? "text-reject-text" : "text-muted-2"}`}>out/ {WORD[r.out] ?? r.out}</span> + {r.deliverables && ( + <span className={`text-[11.5px] ${r.deliverables.problem ? "text-reject-text" : "text-muted-2"}`} title={r.deliverables.problem ?? undefined}> + deliverables {r.deliverables.mode ?? "INVALID"} + {r.deliverables.dirs ? ` · ${r.deliverables.dirs}` : ""} + </span> + )} + <span className="flex flex-wrap items-start gap-1.5"> + {tiered && r.out === "dir" && ( + <ActionPlan label="Move out…" subject={`storage move-out ${r.id}`} endpoint="/api/system/storage" body={{ action: "move-out", project: r.id }} /> + )} + {(r.out === "link" || r.out === "dangling") && ( + <ActionPlan label="Move back…" subject={`storage move-back ${r.id}`} endpoint="/api/system/storage" body={{ action: "move-back", project: r.id }} /> + )} + {r.deliverables && (tiered || r.deliverables.mode === "media") && ( + <ActionPlan + label={r.deliverables.mode === "media" ? "Deliverables home…" : "Deliverables to media…"} + subject={`storage deliverables ${r.id}`} + endpoint="/api/system/storage" + body={{ action: "deliverables", project: r.id, to: r.deliverables.mode === "media" ? "local" : "media" }} + /> + )} + </span> + </li> + ))} + </ul> + )} + </Panel> + ); +} diff --git a/umtool/components/ui/lit-list.tsx b/umtool/components/ui/lit-list.tsx @@ -36,6 +36,7 @@ const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable= export function LitList({ label, initial, + columns = false, global = false, onLight, className, @@ -46,6 +47,12 @@ export function LitList({ /** The line lit on load, by index; a line marked `initial` wins over it. */ initial?: number; /** + * The lines sit in more than one column (Create's two, P5): the head follows + * the lit line's left edge as well as its top. Off, the head stays at the + * list's left edge, as every one-column list has it. + */ + columns?: boolean; + /** * `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. */ @@ -83,9 +90,10 @@ export function LitList({ h.removeAttribute("data-off"); h.style.top = `${r.top - base.top}px`; h.style.height = `${r.height}px`; + if (columns) h.style.left = `${r.left - base.left}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]); + }, [lines, columns]); const light = useCallback( (i: number, opts: { focus?: boolean } = {}) => { diff --git a/umtool/e2e/article-new.spec.ts b/umtool/e2e/article-new.spec.ts @@ -3,14 +3,15 @@ import { readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WARM_TIMEOUT, warm } from "./warm"; +import * as urls from "./urls"; // --------------------------------------------------------------------------- -// /articles/new (release 27 S8): the generation policy (written through the -// editor's settings action, the key never shown) and a new article's first -// iteration — a sweep the editor runs — over the editor stub. +// A new article (release 27 S8): its first iteration — a sweep the editor +// runs — over the editor stub. The form is Create's "Article from a question" +// (/create?make=article, P5; it was /articles/new, which redirects there). +// The generation policy moved to /settings/generation: settings.spec.ts. // -// WRITES articles/new-e2e/ (through the stub; removed after) and the stub's -// in-memory policy (put back to `balanced` after) +// WRITES articles/new-e2e/ (through the stub; removed after) // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -22,59 +23,25 @@ const stubAsked = (route: string) => test.beforeAll(async ({ playwright }) => { test.setTimeout(WARM_TIMEOUT); - await warm(playwright, ["/articles/new", "/api/articles/policy", "/api/articles/channels"]); + await warm(playwright, [urls.newArticleHref(), "/api/articles/policy", "/api/articles/channels"]); }); -test.afterAll(async ({ request }) => { +test.afterAll(() => { rmSync(path.join(FIXTURE, "articles", ARTICLE), { recursive: true, force: true }); - await request.post("/api/articles/policy", { data: { routes: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" } } }); }); -test("/drafts is /articles/new now, and /articles links to it", async ({ page }) => { - await page.goto("/drafts"); - await expect(page).toHaveURL(/\/articles\/new$/); +test("/drafts and /articles/new land on Create's article form, and Work (/articles) links to Create", async ({ page }) => { + for (const old of ["/drafts", "/articles/new"]) { + await page.goto(old); + await expect(page).toHaveURL(/\/create\?make=article$/); + await expect(page.getByRole("form", { name: "new article" })).toBeVisible(); + } await page.goto("/articles"); - await page.getByRole("link", { name: "new article" }).click(); - await expect(page).toHaveURL(/\/articles\/new$/); -}); - -test("the policy: presets write their routes, a route alone makes it custom, caps are the editor's to refuse; the key is a file", async ({ page }) => { - await page.goto("/articles/new"); - const policy = page.getByRole("region", { name: "generation policy" }); - await expect(policy).toHaveAttribute("data-policy-preset", "balanced"); - await expect(policy.getByRole("button", { name: "balanced" })).toHaveAttribute("aria-pressed", "true"); - // The key FILE's path (the editor's read redacts it; settings.json names it) - // and whether a file is there — never a key. - await expect(policy.locator("[data-key-file-exists]")).toContainText("anthropic.env"); - await expect(policy.locator("[data-today-usd]")).toHaveAttribute("data-today-usd", "0.42"); - - await policy.getByRole("button", { name: "api", exact: true }).click(); - await expect(policy).toHaveAttribute("data-policy-preset", "api"); - expect(stubAsked("settings").at(-1)).toMatchObject({ - patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } }, - authorization: "Bearer umtool-e2e-token", - }); - - await policy.getByRole("combobox", { name: "route narrate" }).selectOption("local"); - await expect(policy).toHaveAttribute("data-policy-preset", "custom"); - - await policy.getByRole("textbox", { name: "cap sweep" }).fill("50"); - await policy.getByRole("button", { name: "Save caps" }).click(); - await expect(policy.getByRole("alert")).toContainText("generation.caps.sweep"); - await policy.getByRole("textbox", { name: "cap sweep" }).fill("4"); - await policy.getByRole("button", { name: "Save caps" }).click(); - await expect(policy.getByRole("status")).toHaveText("saved caps"); - expect(stubAsked("settings").at(-1)).toMatchObject({ patch: { generation: { caps: { sweep: 4, max: 10 } } } }); - for (const r of stubAsked("settings")) expect(JSON.stringify(r)).not.toContain("apiKeyFile"); - await policy.getByRole("textbox", { name: "cap sweep" }).fill("5"); - await policy.getByRole("button", { name: "Save caps" }).click(); - await expect(policy.getByRole("textbox", { name: "cap sweep" })).toHaveValue("5"); - - await policy.getByRole("button", { name: "balanced" }).click(); - await expect(policy).toHaveAttribute("data-policy-preset", "balanced"); + await page.locator("[data-work-create]").click(); + await expect(page).toHaveURL(/\/create$/); }); test("a new article: question, channels, the local pipeline — its first iteration runs, and the page is its iterations", async ({ page }) => { - await page.goto("/articles/new"); + await page.goto(urls.newArticleHref()); const form = page.getByRole("form", { name: "new article" }); await form.getByRole("textbox", { name: "question" }).fill("What did the channel say about the vote?"); await form.getByRole("textbox", { name: "find a channel" }).fill("site"); @@ -95,8 +62,15 @@ test("a new article: question, channels, the local pipeline — its first iterat await expect(form.getByRole("combobox", { name: "extractor for this sweep" })).toHaveValue("claude-haiku-4-5"); await form.getByRole("combobox", { name: "extractor for this sweep" }).selectOption("claude-haiku-5-5"); + // The estimate is said before anything runs (P5): what such runs have spent + // (the fixture's ledger: one $0.42 sweep on claude-sonnet-5-5), under the cap. + await expect(form.locator("[data-estimate]")).toContainText("1 earlier run on claude-sonnet-5-5: typical $0.42, most $0.42 · stops at $9.00 (its cap)"); + await form.getByRole("textbox", { name: "cap" }).fill("5"); + await expect(form.locator("[data-estimate]")).toContainText("stops at $5.00 (its cap)"); + await form.getByRole("radio", { name: /pipeline/ }).check(); await expect(form.getByRole("combobox", { name: "model" })).toHaveValue("qwen3:8b"); + await expect(form.locator("[data-estimate]")).toContainText("Runs on the local model: no API spend"); await expect(form.getByRole("combobox", { name: "extractor for this sweep" }), "the pipeline has no extractor").toHaveCount(0); await form.getByRole("button", { name: "Start" }).click(); diff --git a/umtool/e2e/create.spec.ts b/umtool/e2e/create.spec.ts @@ -0,0 +1,247 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { BOARD_CASE } from "./fixtures/research-fixture.mjs"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// Create (plans/umtool-redesign.md, P5; canvas "Create"): "What are you +// making?" -- one lit list of lines, each opening its form inline, each form a +// shell over a writer that already exists. Every path is driven to its writer +// on the fixture and the editor stub: +// +// research POST /api/research/cases → the case's board +// article r28's NewArticleForm → report-draft (article-new.spec +// drives the form; here the line, the chip, the estimate) +// article-board R2's hand-off: the plan, then the seeded sweep (stub) +// video-board R2's hand-off: the plan, then the project +// video-article the chain's steps, then the chain as a umtool job +// video-recording /?from= (the editor's hand-off) prefilled → a project +// video-report the sweep reports on disk → a project +// song a song +// +// WRITES (each removed after): .umtool/research/p5-*, articles/p5-board, +// p5-board/, p5-rec/, p5-rep/, reports/videos/p5-song/; a chain job on +// zeta i1, cancelled +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const stubAsked = (route: string) => + existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route) : []; +const caseJson = (id: string) => JSON.parse(readFileSync(path.join(FIXTURE, ".umtool", "research", id, "case.json"), "utf8")); +const manifestOf = (dir: string) => JSON.parse(readFileSync(path.join(FIXTURE, dir, "video.manifest.json"), "utf8")); + +const WRITTEN = [ + ".umtool/research/p5-case", + ".umtool/research/p5-board", + "articles/p5-board", + "p5-board", + "p5-rec", + "p5-rep", + "reports/videos/p5-song", +]; +const clean = () => { + for (const p of WRITTEN) rmSync(path.join(FIXTURE, p), { recursive: true, force: true }); +}; + +const line = (page: Page, make: string) => page.locator(`[data-make-line="${make}"]`); +const form = (page: Page, make: string) => page.locator(`[data-make-form="${make}"]`); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + clean(); + await warm(playwright, [urls.createHref(), urls.createHref({ make: "article" }), "/api/research/cases", "/api/articles/channels"]); +}); +test.afterAll(clean); + +test("the lines, grouped Research · Article · Video · Song; the policy chip links Settings; + Create is lit, no place", async ({ page }) => { + await page.goto(urls.createHref()); + await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("What are you making?"); + await expect(page.locator("[data-make-group]")).toHaveText([/^Research/, /^Article/, /^Video/, /^Song/]); + await expect(page.locator("[data-make-line]")).toHaveCount(8); + // The boards and the reports on disk are counted on their lines. + await expect(line(page, "article-board")).toContainText(/ · \d+ quotes?/); + await expect(line(page, "video-report")).toContainText(/ · \d+ found/); + const chip = page.locator("[data-policy-chip]"); + await expect(chip).toHaveAttribute("data-policy-chip", "balanced"); + await expect(chip).toHaveText("Generation: balanced · Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts"); + await expect(chip).toHaveAttribute("href", urls.generationPolicyHref()); + const rail = page.locator("[data-app-rail]"); + await expect(rail.locator("[data-rail-create]")).toHaveAttribute("aria-current", "page"); + await expect(rail.locator("nav[aria-label=Main] > a[aria-current]")).toHaveCount(0); + // The rail's + Create from anywhere comes here. + await page.goto(urls.workHref()); + await page.locator("[data-app-rail] [data-rail-create]").click(); + await expect(page).toHaveURL(/\/create$/); +}); + +test("keys: j/k light the lines, Enter opens the form on its first field, Escape closes it back to the line", async ({ page }) => { + await page.goto(urls.createHref()); + await expect(page.locator("[data-lit-list][data-hydrated]")).toBeAttached(); + await expect(line(page, "research")).toHaveAttribute("data-lit", ""); + await page.keyboard.press("j"); + await expect(line(page, "article")).toHaveAttribute("data-lit", ""); + await page.keyboard.press("Enter"); + await expect(form(page, "article")).toBeVisible(); + await expect(page).toHaveURL(/\/create\?make=article$/); + await expect(form(page, "article").getByRole("textbox", { name: "question" })).toBeFocused(); + // The form's own keys are the form's: j types, it does not move the light. + await page.keyboard.type("jk"); + await expect(line(page, "article")).toHaveAttribute("data-lit", ""); + await page.keyboard.press("Escape"); + await expect(form(page, "article")).toHaveCount(0); + await expect(page.locator('[data-make="article"]')).toBeFocused(); + await expect(page).toHaveURL(/\/create$/); + // Down the left column and into the right: the head follows the column. + for (let i = 0; i < 2; i++) await page.keyboard.press("j"); + await expect(line(page, "video-article")).toHaveAttribute("data-lit", ""); + const head = await page.locator(".lit-head").boundingBox(); + const lit = await line(page, "video-article").boundingBox(); + expect(Math.abs(head!.x - lit!.x)).toBeLessThan(2); +}); + +test("fits 1366×768: every line, and an open form under its line", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + await page.goto(urls.createHref()); + for (const g of await page.locator("[data-make-group]").all()) { + const b = await g.boundingBox(); + expect(b!.y + b!.height).toBeLessThanOrEqual(768); + } + await page.goto("/?from=testchan%2Fvid1"); + const f = await form(page, "video-recording").boundingBox(); + expect(f!.y + f!.height).toBeLessThanOrEqual(768); + const w = await page.evaluate(() => document.documentElement.scrollWidth); + expect(w).toBeLessThanOrEqual(1366); +}); + +test("Research a question → a case (R2's store), and its board opens", async ({ page }) => { + await page.goto(urls.createHref({ make: "research" })); + const f = form(page, "research"); + await expect(f.getByRole("textbox", { name: "question" })).toBeFocused(); + await f.getByRole("textbox", { name: "question" }).fill("lighthouse budget"); + await f.getByRole("textbox", { name: "case title" }).fill("P5 case"); + await f.getByRole("button", { name: "Open a case" }).click(); + await page.waitForURL(/\/research\/p5-case$/, { timeout: 20_000 }); + await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("P5 case"); + expect(caseJson("p5-case")).toMatchObject({ title: "P5 case", scope: { query: "lighthouse budget" } }); + expect(caseJson("p5-case").scope.source).toMatch(/^local:/); +}); + +test("Article from a question: the estimate before it runs, under the policy's chip (the form is article-new.spec's)", async ({ page }) => { + await page.goto(urls.createHref({ make: "article" })); + const f = form(page, "article"); + await expect(f.getByRole("form", { name: "new article" })).toBeVisible(); + // The policy is the chip, not a panel, on Create. + await expect(page.getByRole("region", { name: "generation policy" })).toHaveCount(0); + await expect(f.locator("[data-estimate]")).toContainText("1 earlier run on claude-sonnet-5-5: typical $0.42, most $0.42 · stops at $5.00 (its cap)"); + await expect(f.locator("[data-estimate]")).toContainText("today $0.42 of $20.00"); + await f.getByRole("radio", { name: /research/ }).check(); + await expect(f.locator("[data-estimate]")).toHaveAttribute("data-estimate", "research"); + await f.getByRole("button", { name: "Cancel" }).click(); + await expect(form(page, "article")).toHaveCount(0); +}); + +test("from a board: R2's hand-offs, planned then confirmed — an article (a seeded sweep) and a video (a project)", async ({ page, request }) => { + const made = await (await request.post("/api/research/cases", { data: { title: "P5 board" } })).json(); + expect(made.case.id).toBe("p5-board"); + const source = caseJson(BOARD_CASE).scope.source; + for (const t of [400, 404]) { + const pinned = await request.post("/api/research/cases/p5-board/quotes", { data: { source, channel: "night-desk", video: "nd-2023", t } }); + expect(pinned.ok(), await pinned.text()).toBe(true); + } + + // The article: the plan names the model and the cap; nothing is asked of the editor until the confirm. + await page.goto(urls.createHref({ make: "article-board", case: "p5-board" })); + const f = form(page, "article-board"); + await expect(f.getByRole("combobox", { name: "board" })).toHaveValue("p5-board"); + const before = stubAsked("report-draft").length; + await f.getByRole("button", { name: "Plan the article" }).click(); + const art = page.locator('dialog[data-handoff="article"]'); + await expect(art).toContainText("the board as cited markdown: 2 quotes"); + await expect(art).toContainText(/Runs on\s*claude-/); + expect(stubAsked("report-draft").length).toBe(before); + await art.getByRole("button", { name: /^Start the sweep/ }).click(); + await page.waitForURL(/\/articles\/p5-board/, { timeout: 20_000 }); + const asked = stubAsked("report-draft").at(-1)!; + expect(asked).toMatchObject({ task: "sweep", article: "p5-board" }); + expect(String(asked.seed)).toContain("P5 board"); + expect(caseJson("p5-board").handoffs.map((h: { to: string }) => h.to)).toEqual(["article"]); + + // The video: its plan lists the cue spans; the confirm writes the project. + await page.goto(urls.createHref({ make: "video-board", case: "p5-board" })); + await form(page, "video-board").getByRole("button", { name: "Plan the video" }).click(); + const vid = page.locator('dialog[data-handoff="video"]'); + await expect(vid).toContainText("2 — each the cue span of a pinned quote"); + await expect(vid).toContainText("night-desk/nd-2023"); + await vid.getByRole("button", { name: "Create the project" }).click(); + await page.waitForURL(/\/projects\/p5-board$/, { timeout: 20_000 }); + expect(manifestOf("p5-board").timeline).toHaveLength(2); +}); + +test("Video from an article: the chain's steps for its iteration, then the chain runs as a umtool job", async ({ page, request }) => { + await page.goto(urls.createHref({ make: "video-article", article: "zeta" })); + const f = form(page, "video-article"); + await expect(f.getByRole("combobox", { name: "article" })).toHaveValue("zeta"); + // The default is the newest done iteration with its OWN report (zeta's i2, a + // revise-report), never i3, a video revision carrying i1's report; the plan + // line names it. The chain runs over the one chosen. + await expect(f.getByRole("combobox", { name: "iteration" })).toHaveValue("2"); + await expect(f.locator("[data-chain-iteration]")).toHaveText("i2 · revise-report:"); + await f.getByRole("combobox", { name: "iteration" }).selectOption("3"); + await expect(f.locator("[data-chain-iteration]")).toHaveText("i3 · revise-video (the report of i1):"); + await f.getByRole("combobox", { name: "iteration" }).selectOption("1"); + await expect(f.locator("[data-chain-iteration]")).toHaveText("i1 · sweep:"); + await expect(f.locator("[data-chain-plan]")).toContainText(/\d+ of 10 steps to run, from “/); + await f.getByRole("button", { name: "Make the video" }).click(); + await page.waitForURL(/\/articles\/zeta\?tab=iterations$/, { timeout: 20_000 }); + // It is umtool's own job; stop it (a cancelled chain is a paused one). + const running = (await (await request.get("/api/jobs")).json()).running as { id: string; label: string } | null; + if (running) { + expect(running.label).toBe("chain zeta i1"); + await request.post("/api/articles/chain", { data: { cancel: running.id } }); + } + await expect.poll(async () => (await (await request.get("/api/jobs")).json()).running, { timeout: 30_000 }).toBeNull(); +}); + +test("Video from a recording: the editor's /?from= lands here prefilled, and makes the project", async ({ page }) => { + await page.goto("/?from=testchan%2Fvid1"); + await expect(page).toHaveURL(/\/create\?from=testchan%2Fvid1$/); + const f = form(page, "video-recording"); + await expect(f.locator("[data-new-from]")).toHaveValue("testchan/vid1"); + await expect(f.locator("[data-new-slug]")).toBeFocused(); + await expect(f.locator("[data-new-kind]")).toHaveCount(0); + await page.keyboard.type("p5-rec"); + await page.keyboard.press("Enter"); + await page.waitForURL(/\/projects\/p5-rec$/, { timeout: 20_000 }); + expect(manifestOf("p5-rec").provenance.channelSlug).toBe("testchan"); +}); + +test("Video from a sweep report: the reports on disk are offered, and one becomes a project", async ({ page }) => { + await page.goto(urls.createHref({ make: "video-report" })); + const f = form(page, "video-report"); + const pick = f.getByRole("combobox", { name: "sweep report" }); + await expect(pick).toBeFocused(); + // Every sweep report the walk finds (an article's sweep iteration among them), then a path by hand. + const bike = pick.locator("option", { hasText: "reports/bike-fixture" }); + await expect(bike).toHaveCount(1); + await expect(pick.locator("option").last()).toHaveText("A path typed by hand…"); + await pick.selectOption((await bike.getAttribute("value"))!); + await f.locator("[data-new-slug]").fill("p5-rep"); + await f.locator("[data-new-create]").click(); + await page.waitForURL(/\/projects\/p5-rep$/, { timeout: 20_000 }); + expect(existsSync(path.join(FIXTURE, "p5-rep", "sweep-report.md"))).toBe(true); +}); + +test("A song: the song scaffold", async ({ page }) => { + await page.goto(urls.createHref({ make: "song" })); + const f = form(page, "song"); + await expect(f.locator("[data-new-slug]")).toBeFocused(); + await f.locator("[data-new-slug]").fill("p5-song"); + await f.getByRole("button", { name: "Create the song" }).click(); + await page.waitForURL(/\/projects\/.*p5-song$/, { timeout: 20_000 }); + expect(existsSync(path.join(FIXTURE, "reports", "videos", "p5-song"))).toBe(true); +}); diff --git a/umtool/e2e/inbox.spec.ts b/umtool/e2e/inbox.spec.ts @@ -184,10 +184,15 @@ test("POST /api/pieces/mute refuses junk", async ({ request }) => { expect((await post({ piece: "p:no-such-project", kind: "unbuilt", muted: true })).status()).toBe(404); }); -test("the Inbox opens the new-project form prefilled from ?from= (the editor's hand-off)", async ({ page }) => { - await page.goto(urls.homeHref({ from: "testchan/vid1" })); - await expect(page.locator("[data-new-from]")).toHaveValue("testchan/vid1"); - await expect(page.locator("[data-new-seed]")).toBeVisible(); +test("the editor's hand-off, /?from=, lands on Create with the recording's form prefilled (P5)", async ({ page }) => { + await page.goto("/?from=testchan%2Fvid1"); + await expect(page).toHaveURL(/\/create\?from=testchan%2Fvid1$/); + const form = page.locator("[data-make-form=video-recording]"); + await expect(form.locator("[data-new-from]")).toHaveValue("testchan/vid1"); + await expect(form.locator("[data-new-seed]")).toBeVisible(); + // The Inbox itself, with no `from`, is not redirected. + await page.goto(urls.homeHref()); + await expect(page).toHaveURL(/\/$/); }); // --------------------------------------------------------------------------- diff --git a/umtool/e2e/piece.spec.ts b/umtool/e2e/piece.spec.ts @@ -194,7 +194,7 @@ test("an article piece: nine tabs, the stepper by what exists, the policy chip, await expect(steps.nth(3)).toHaveAttribute("data-step", "todo"); // The policy is a chip linking its page, not the panel. - await expect(page.locator("[data-policy-chip]")).toHaveAttribute("href", urls.generationSettingsHref()); + await expect(page.locator("[data-policy-chip]")).toHaveAttribute("href", urls.generationPolicyHref()); await expect(page.locator("[data-policy-chip]")).toContainText("balanced"); await expect(page.getByRole("region", { name: "generation policy" })).toHaveCount(0); diff --git a/umtool/e2e/projects.spec.ts b/umtool/e2e/projects.spec.ts @@ -565,7 +565,7 @@ test("new project offers the brand preset, and only a branded scaffold carries r const slug = "brand-ui-probe"; const created = path.join(FIXTURE, slug); rmSync(created, { recursive: true, force: true }); - // The form lives on the projects index (+ Create → A project) until /create (P5). + // The form on the projects index (+ new project); Create's video lines are the same form (create.spec.ts). await page.goto(urls.projectsHref()); await page.locator("[data-new-project]").click(); const brand = page.locator("[data-new-brand]"); diff --git a/umtool/e2e/redirects.spec.ts b/umtool/e2e/redirects.spec.ts @@ -37,7 +37,7 @@ function parts(href: string): [string, [string, string][]] { return [u.pathname, [...u.searchParams.entries()]]; } -test("the table has the P3 rows, reserved /browse tools before the catch-all", () => { +test("the table has the P3 and P5 rows, reserved /browse tools before the catch-all", () => { const sources = REDIRECTS.map((r) => r.source); const catchAll = sources.indexOf("/browse/:path*"); expect(catchAll).toBeGreaterThan(0); @@ -46,19 +46,24 @@ test("the table has the P3 rows, reserved /browse tools before the catch-all", ( expect(sources.indexOf(s), `${s} must come before the catch-all`).toBeLessThan(catchAll); } for (const r of REDIRECTS) expect(r.permanent, r.source).toBe(false); + // P5: the editor's hand-off, only when the query has `from`; the new-article form. + expect(REDIRECTS.find((r) => r.source === "/")).toMatchObject({ destination: "/create", has: [{ type: "query", key: "from" }] }); + expect(REDIRECTS.find((r) => r.source === "/articles/new")?.destination).toBe("/create?make=article"); }); for (const row of REDIRECTS) { const from = fill(row.source); - test(`${row.source} → ${row.destination} (307, query kept)`, async ({ request }) => { - for (const query of ["", "q=x+y&note=n1"]) { + // A row that matches only when the query HAS a key is asked with it. + const needs = (row.has ?? []).filter((h) => h.type === "query").map((h) => `${h.key}=testchan%2Fvid1`); + test(`${row.source}${needs.length ? `?${needs.join("&")}` : ""} → ${row.destination} (307, query kept)`, async ({ request }) => { + for (const query of (["", "q=x+y&note=n1"] as string[]).map((q) => [...needs, ...(q ? [q] : [])].join("&"))) { const url = query ? `${from}?${query}` : from; const res = await request.get(url, { maxRedirects: 0 }); expect(res.status(), url).toBe(307); expect(parts(res.headers()["location"]), url).toEqual(parts(expected(row.destination, query))); } // And where it lands answers (the escape hatch needs a project to open). - const landed = await request.get(row.source === "/browse/at" ? `${from}?path=find` : from); + const landed = await request.get(row.source === "/browse/at" ? `${from}?path=find` : needs.length ? `${from}?${needs.join("&")}` : from); expect(landed.status(), `${from} → ${landed.url()}`).toBe(200); }); } @@ -81,7 +86,8 @@ for (const [old, now] of [ } test("a page that did not move is not redirected", async ({ request }) => { - for (const p of ["/", "/work", "/tools", "/projects", "/sites/priv", "/articles/delta", "/articles/new", "/settings/system"]) { + // `/` is the Inbox unless the query has `from` (the hand-off row). + for (const p of ["/", "/?hidden=1", "/work", "/tools", "/projects", "/sites/priv", "/articles/delta", "/create", "/create?make=song", "/settings", "/settings/generation", "/settings/system"]) { const res = await request.get(p, { maxRedirects: 0 }); expect(res.status(), p).toBe(200); } diff --git a/umtool/e2e/settings.spec.ts b/umtool/e2e/settings.spec.ts @@ -0,0 +1,186 @@ +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// Settings (plans/umtool-redesign.md, P5), on the fixture and the editor stub: +// +// /settings/generation the generation policy (written through the editor's +// settings action, the key never shown; it moved here +// from /articles/new) and the day's spend, job by job, +// from the fixture's ledger +// /settings/system the maintenance a terminal did, each action that +// changes anything a plan first: the index prune's +// plan shown, Keep it changes nothing, Confirm drops +// the record; the rebuild runs as a job; a storage +// move with no media root is refused, never offered +// +// WRITES the stub's in-memory policy (put back to `balanced` after), a +// scaffolded project the spec deletes again (so its index record goes +// stale), and the fixture's index (UMTOOL_CACHE_DIR, rebuilt every run) +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const stubAsked = (route: string) => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route); +const STALE = "p5-stale-record"; + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [urls.generationPolicyHref(), urls.systemHref(), "/settings", "/api/articles/policy"]); +}); +test.afterAll(async ({ request }) => { + rmSync(path.join(FIXTURE, STALE), { recursive: true, force: true }); + await request.post("/api/articles/policy", { data: { routes: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" } } }); +}); + +test("/settings lists generation and system; both light Settings", async ({ page }) => { + await page.goto("/settings"); + await expect(page.locator("[data-tool-entry=generation] a")).toHaveAttribute("href", urls.generationPolicyHref()); + await expect(page.locator("[data-tool-entry=system] a")).toHaveAttribute("href", urls.systemHref()); + await page.goto(urls.systemHref()); + await expect(page.locator("[data-policy-link]")).toHaveAttribute("href", urls.generationPolicyHref()); +}); + +test("generation: presets write their routes, a route alone makes it custom, caps are the editor's to refuse; the key is a file", async ({ page }) => { + await page.goto(urls.generationPolicyHref()); + await expect(page.locator("[data-policy-summary]")).toHaveText( + "Generation: balanced · Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts", + ); + const policy = page.getByRole("region", { name: "generation policy" }); + await expect(policy).toHaveAttribute("data-policy-preset", "balanced"); + await expect(policy.getByRole("button", { name: "balanced" })).toHaveAttribute("aria-pressed", "true"); + // The key FILE's path (the editor's read redacts it; settings.json names it) + // and whether a file is there — never a key. + await expect(policy.locator("[data-key-file-exists]")).toContainText("anthropic.env"); + await expect(policy.locator("[data-today-usd]")).toHaveAttribute("data-today-usd", "0.42"); + + await policy.getByRole("button", { name: "api", exact: true }).click(); + await expect(policy).toHaveAttribute("data-policy-preset", "api"); + expect(stubAsked("settings").at(-1)).toMatchObject({ + patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } }, + authorization: "Bearer umtool-e2e-token", + }); + + await policy.getByRole("combobox", { name: "route narrate" }).selectOption("local"); + await expect(policy).toHaveAttribute("data-policy-preset", "custom"); + + await policy.getByRole("textbox", { name: "cap sweep" }).fill("50"); + await policy.getByRole("button", { name: "Save caps" }).click(); + await expect(policy.getByRole("alert")).toContainText("generation.caps.sweep"); + await policy.getByRole("textbox", { name: "cap sweep" }).fill("4"); + await policy.getByRole("button", { name: "Save caps" }).click(); + await expect(policy.getByRole("status")).toHaveText("saved caps"); + expect(stubAsked("settings").at(-1)).toMatchObject({ patch: { generation: { caps: { sweep: 4, max: 10 } } } }); + for (const r of stubAsked("settings")) expect(JSON.stringify(r)).not.toContain("apiKeyFile"); + // Read back on a fresh load: the round trip is the editor's, not the page's state. + await page.reload(); + await expect(page.getByRole("region", { name: "generation policy" })).toHaveAttribute("data-policy-preset", "custom"); + await expect(page.getByRole("region", { name: "generation policy" }).getByRole("textbox", { name: "cap sweep" })).toHaveValue("4"); + const again = page.getByRole("region", { name: "generation policy" }); + await again.getByRole("textbox", { name: "cap sweep" }).fill("5"); + await again.getByRole("button", { name: "Save caps" }).click(); + await expect(again.getByRole("textbox", { name: "cap sweep" })).toHaveValue("5"); + + await again.getByRole("button", { name: "balanced" }).click(); + await expect(again).toHaveAttribute("data-policy-preset", "balanced"); +}); + +test("generation: the day's spend, job by job, from the ledger", async ({ page }) => { + await page.goto(urls.generationPolicyHref()); + const spend = page.locator("[data-spend-today]"); + await expect(spend).toHaveAttribute("data-spend-today", "0.42"); + await expect(spend).toContainText("of the $20.00 daily cap · 1 job"); + const job = spend.locator("[data-spend-job=fixture-1]"); + await expect(job).toContainText("sweep · zeta i1"); + await expect(job).toContainText("claude-sonnet-5-5"); + await expect(job).toContainText("$0.42"); + await expect(spend.getByRole("list", { name: "last 7 days" }).locator("li")).toHaveCount(7); +}); + +async function planOf(request: APIRequestContext, data: Record<string, unknown>) { + const r = await request.post("/api/system/index", { data: { ...data, dryRun: true } }); + expect(r.ok()).toBe(true); + return (await r.json()).plan as { rows: { label: string }[]; blocked: boolean; summary: string }; +} + +test("system: the index prune is a plan — Keep it changes nothing, Confirm drops the stale record", async ({ page, request }) => { + // A project the index has a record of, then gone from disk: its record is stale. + rmSync(path.join(FIXTURE, STALE), { recursive: true, force: true }); + const made = await request.post("/api/projects/new", { data: { kind: "report-video", slug: STALE } }); + expect(made.ok(), await made.text()).toBe(true); + expect((await request.get("/api/browse/projects")).ok()).toBe(true); // the walk writes the record + rmSync(path.join(FIXTURE, STALE), { recursive: true, force: true }); + await expect.poll(async () => (await planOf(request, { action: "prune" })).rows.map((r) => r.label)).toContain(STALE); + + await page.goto(urls.systemHref()); + const panel = page.locator("[data-panel=index]"); + await panel.getByRole("button", { name: "Prune…" }).click(); + const plan = page.getByRole("region", { name: "plan index prune" }); + await expect(plan).toContainText("Prune the index"); + await expect(plan.getByRole("list", { name: "touches" }).locator(`[data-plan-row="${STALE}"]`)).toBeVisible(); + await plan.getByRole("button", { name: "Keep it" }).click(); + await expect(plan).toBeHidden(); + // Nothing was written: the record is still there. + expect((await planOf(request, { action: "prune" })).rows.map((r) => r.label)).toContain(STALE); + + await panel.getByRole("button", { name: "Prune…" }).click(); + const n = (await planOf(request, { action: "prune" })).rows.length; + await plan.locator("[data-plan-confirm]").click(); + await expect(panel.locator("[data-plan-done='index prune']")).toHaveText(`Dropped ${n} ${n === 1 ? "record" : "records"}`); + const after = await planOf(request, { action: "prune" }); + expect(after.rows).toEqual([]); + expect(after.blocked).toBe(true); +}); + +test("system: the index rebuild runs as a umtool job, after its plan", async ({ page, request }) => { + await page.goto(urls.systemHref()); + const panel = page.locator("[data-panel=index]"); + await panel.getByRole("button", { name: "Rebuild…" }).click(); + const plan = page.getByRole("region", { name: "plan index rebuild" }); + await expect(plan).toContainText(/Re-read \d+ projects/); + await expect(plan).toContainText("Runs as a job"); + await plan.getByRole("button", { name: "Rebuild the index" }).click(); + await expect(panel.locator("[data-plan-done='index rebuild']")).toHaveText("The index rebuild is running — a job, in Running"); + // The job is umtool's own, through the CLI, and finishes. + await expect + .poll(async () => ((await (await request.get("/api/jobs?n=8")).json()).jobs as { label: string; state: string }[]).find((j) => j.label === "index-rebuild")?.state, { timeout: 60_000 }) + .toBe("done"); +}); + +test("system: a storage move with no media root is refused in the plan, never offered, and the API refuses its confirm", async ({ page, request }) => { + await page.goto(urls.systemHref()); + const panel = page.locator("[data-panel=storage]"); + await expect(panel).toContainText("no media root (UMTOOL_MEDIA_DIR unset)"); + await panel.getByRole("button", { name: "Move every out/ to the media root…" }).click(); + const plan = page.getByRole("region", { name: "plan storage move-out all" }); + await expect(plan.getByRole("list", { name: "refused" })).toContainText("UMTOOL_MEDIA_DIR is not set"); + await expect(plan).toHaveAttribute("data-plan-blocked", "yes"); + await expect(plan.locator("[data-plan-confirm]")).toHaveCount(0); + await plan.getByRole("button", { name: "Keep it" }).click(); + await expect(plan).toBeHidden(); + + const refused = await request.post("/api/system/storage", { data: { action: "move-out", all: true } }); + expect(refused.status()).toBe(409); + expect((await refused.json()).plan.refusals[0]).toContain("UMTOOL_MEDIA_DIR is not set"); + // A project id, never a path; an unknown one is a 404. + expect((await request.post("/api/system/storage", { data: { action: "move-back", project: "no/such", dryRun: true } })).status()).toBe(404); + expect((await request.post("/api/system/storage", { data: { action: "rm", project: "x" } })).status()).toBe(400); + // Nothing on disk moved. + expect(existsSync(path.join(FIXTURE, "reports", "report-fixture", "video.manifest.json"))).toBe(true); +}); + +test("system: the doctor's roots are the fixture's", async ({ page, request }) => { + await page.goto(urls.systemHref()); + const roots = page.locator("[data-panel=roots]"); + await expect(roots).toContainText(".e2e-song"); + await expect(roots).toContainText("UMTOOL_MEDIA_DIR unset"); + const doctor = await (await request.get("/api/doctor")).json(); + expect(doctor.roots.reports.path).toContain(".e2e-song"); + expect(doctor.roots.media.tiered).toBe(false); +}); diff --git a/umtool/e2e/shell.spec.ts b/umtool/e2e/shell.spec.ts @@ -27,6 +27,7 @@ const PLACES: { url: string; lit: string; current: "page" | "true" }[] = [ { url: urls.mixHref(), lit: "tools", current: "true" }, { url: urls.findHref(), lit: "tools", current: "true" }, { url: urls.systemHref(), lit: "settings", current: "page" }, + { url: urls.generationPolicyHref(), lit: "settings", current: "page" }, ]; for (const { url, lit, current } of PLACES) { @@ -109,15 +110,15 @@ test("the palette jumps to a piece, moves with the arrows, closes on Escape, and await expect(page).toHaveURL(/\/articles\/zeta$/); }); -test("a create action from the palette", async ({ page }) => { +test("a create action from the palette opens its line of /create (P5)", async ({ page }) => { await page.goto(urls.workHref()); await ready(page); await page.keyboard.press("Control+k"); - await page.keyboard.type("new project"); - await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "new-project"); + await page.keyboard.type("video from a recording"); + await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "new-video-recording"); await page.keyboard.press("Enter"); - await expect(page).toHaveURL(/\/projects\?new=1$/); - await expect(page.locator("[data-new-project-form]")).toBeVisible(); + await expect(page).toHaveURL(/\/create\?make=video-recording$/); + await expect(page.locator("[data-make-form=video-recording] [data-new-project-form]")).toBeVisible(); }); test("a bench collapses the rail; its head still links home", async ({ page }) => { diff --git a/umtool/lib/create.ts b/umtool/lib/create.ts @@ -0,0 +1,87 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { listArticleDirs, listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; +import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; +import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; +import { sitesPaths } from "@/lib/articles/sites"; +import { spendHistory } from "@/lib/create/estimate.mjs"; +import { readPieceGraph } from "@/lib/pieces"; +import { projectRefs } from "@/lib/projects"; +import { makeKinds, sweepReports } from "@/lib/projects/create.mjs"; +import { listCases } from "@/lib/research/boards"; +import { listSources } from "@/lib/research/sources"; +import type { CaseSummary } from "@/lib/research/case-types"; +import type { SourceOption } from "@/lib/research/types"; + +// --------------------------------------------------------------------------- +// What Create (/create, plans/umtool-redesign.md P5) needs to draw its lines +// and open their forms: the policy (the chip, the new-article form), the day's +// spend and the ledger's history (the estimate), the article ids taken, the +// boards, the store's articles (a video from one), the sweep reports on disk, +// the corpora a case may read, and the kinds the scaffolds write. +// +// Every part is read on its own and fails on its own: an editor that does not +// answer costs the policy and the channels, never the page. +// --------------------------------------------------------------------------- + +export type Today = { day: string; usd: number; jobs: number; daily: number }; +export type ScaffoldKind = { id: string; label: string; scaffold: { fields: string[]; brands?: { id: string; label: string }[] } }; +export type StoreArticle = { id: string; title: string; status: string | null }; +export type SweepReport = { project: string; path: string; title: string }; + +export type CreateData = { + policy: PolicyView | null; + policyError: string | null; + today: Today | null; + /** task -> model -> per-job USD, oldest first (lib/create/estimate.mjs). */ + history: Record<string, Record<string, number[]>>; + taken: string[]; + cases: CaseSummary[]; + casesError: string | null; + articles: StoreArticle[]; + reports: SweepReport[]; + sources: SourceOption[]; + kinds: { recording: ScaffoldKind | null; report: ScaffoldKind | null; song: ScaffoldKind | null }; +}; + +const msg = (e: unknown) => (e instanceof Error ? e.message : String(e)); + +export async function readCreate(): Promise<CreateData> { + let policy: PolicyView | null = null; + let policyError: string | null = null; + try { + policy = await readPolicy(); + } catch (e) { + policyError = msg(e); + } + const paths = sitesPaths(); + const [today, rows, taken, cases, graph, refs, sources] = await Promise.all([ + policy ? readToday(policy.generation.caps.daily).catch(() => null) : Promise.resolve(null), + readGenerationUsage(getPaths().generationUsageFile).catch(() => []), + Promise.all([listArticleDirs(paths), listPendingArticles(paths)]).then(([a, b]) => [...a, ...b]).catch(() => [] as string[]), + listCases().then( + (c) => ({ cases: c, error: null as string | null }), + (e) => ({ cases: [] as CaseSummary[], error: msg(e) }), + ), + readPieceGraph().catch(() => null), + projectRefs().catch(() => []), + listSources().catch(() => [] as SourceOption[]), + ]); + const articles: StoreArticle[] = (graph?.pieces ?? []) + .filter((p) => p.kind === "article" && p.site === ARTICLES_KEY && p.report) + .sort((a, b) => b.newestMs - a.newestMs) + .map((p) => ({ id: p.report as string, title: p.title, status: p.status })); + return { + policy, + policyError, + today, + history: spendHistory(rows), + taken, + cases: cases.cases.filter((c) => !c.error), + casesError: cases.error, + articles, + reports: await sweepReports(refs).catch(() => []), + sources, + kinds: makeKinds() as CreateData["kinds"], + }; +} diff --git a/umtool/lib/create/create.test.mjs b/umtool/lib/create/create.test.mjs @@ -0,0 +1,62 @@ +// node --test umtool/lib/create/create.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { policyChip, routeGroups, routeSummary } from "./policy.mjs"; +import { estimateOf, estimateText, spendHistory } from "./estimate.mjs"; +import { chainable, defaultChainIteration } from "./iterations.mjs"; + +const TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]; +const media = (r) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r }); +const BALANCED = { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...media("local") }; + +test("the balanced preset in one line: grouped by route, drafts as one word", () => { + assert.equal(routeSummary(BALANCED, TASKS), "Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts"); + assert.deepEqual(routeGroups(BALANCED, TASKS).map((g) => g.route), ["code", "api", "local"]); +}); + +test("one route for everything says so; agreeing revisions are one word; split drafts are named", () => { + const api = Object.fromEntries(TASKS.map((t) => [t, "api"])); + assert.equal(routeSummary(api, TASKS), "everything on the API"); + assert.equal(routeSummary(Object.fromEntries(TASKS.map((t) => [t, "local"])), TASKS), "everything local"); + const custom = { ...api, sweep: "code", narrate: "local" }; + assert.equal(routeSummary(custom, TASKS), "Claude Code: sweeps · API: revisions, research, cut drafts, on-screen drafts, teaser drafts, flips drafts, threads drafts, YouTube drafts · local: narration"); +}); + +test("the chip names the preset, or why there is none", () => { + assert.equal(policyChip({ preset: "balanced", routes: BALANCED }, TASKS), "Generation: balanced · Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts"); + assert.equal(policyChip(null), "Generation: the editor did not answer"); +}); + +test("the ledger as per-job spend: rows summed per job under its main model, by task", () => { + const rows = [ + { jobId: "a", task: "sweep", model: "claude-sonnet", usd: 0.4, at: "2026-10-01T00:00:00Z" }, + { jobId: "a", task: "sweep", model: "claude-haiku", usd: 0.02, at: "2026-10-01T00:00:00Z" }, + { jobId: "b", task: "sweep", model: "claude-sonnet", usd: 1.1, at: "2026-10-02T00:00:00Z" }, + { jobId: "c", task: "narrate", model: "claude-sonnet", usd: 0.3, at: "2026-10-02T00:00:00Z" }, + { jobId: "d", task: "research", model: "claude-opus", usd: 2, at: "2026-10-03T00:00:00Z" }, + ]; + assert.deepEqual(spendHistory(rows), { sweep: { "claude-sonnet": [0.42, 1.1] }, research: { "claude-opus": [2] } }); +}); + +test("an estimate: the past runs' typical and most, under the cap; a local model spends nothing", () => { + const h = { sweep: { "claude-sonnet": [0.42, 1.1, 0.5] } }; + const e = estimateOf(h, { task: "sweep", model: "claude-sonnet", cap: 5, local: false }); + assert.deepEqual(e, { kind: "api", model: "claude-sonnet", runs: 3, typical: 0.5, most: 1.1, cap: 5 }); + assert.equal(estimateText(e), "3 earlier runs on claude-sonnet: typical $0.50, most $1.10 · stops at $5.00 (its cap)"); + assert.equal(estimateText(estimateOf(h, { task: "sweep", model: "claude-opus", cap: 3, local: false })), "No earlier run on claude-opus in the ledger · stops at $3.00 (its cap)"); + assert.equal(estimateText(estimateOf(h, { task: "sweep", model: "qwen3:8b", cap: 5, local: true })), "Runs on the local model: no API spend"); +}); + +test("video from an article: the newest done iteration with its OWN report is the default, never a video revision", () => { + // The fixture's zeta: i1 sweep (report), i2 revise-report (report), i3 revise-video (i1's report), i4 failed. + const its = [ + { n: 4, status: "failed", hasReport: false, reportFrom: null }, + { n: 3, status: "done", hasReport: false, reportFrom: 1 }, + { n: 2, status: "done", hasReport: true, reportFrom: 2 }, + { n: 1, status: "done", hasReport: true, reportFrom: 1 }, + ]; + assert.deepEqual(chainable(its).map((i) => i.n), [3, 2, 1]); + assert.equal(defaultChainIteration(its), 2); + assert.equal(defaultChainIteration([{ n: 2, status: "done", hasReport: false, reportFrom: 1 }]), null); + assert.equal(defaultChainIteration([]), null); +}); diff --git a/umtool/lib/create/estimate.mjs b/umtool/lib/create/estimate.mjs @@ -0,0 +1,85 @@ +// --------------------------------------------------------------------------- +// What a new sweep (or research run) is likely to spend, shown BEFORE it runs +// (plans/umtool-redesign.md, P5: "Article from a question … with the estimate +// shown before it runs"). +// +// There is no price model of a sweep -- how much it reads depends on what the +// question matches -- so the estimate is what such runs HAVE spent: the +// editor's usage ledger (common/controller/generationUsage.ts, one row per +// model per finished API job), summed per job, for the same task and model. +// The cap is the ceiling the editor enforces; a local model spends nothing on +// the API. Said as it is: "2 earlier runs on <model>: typical $0.41, most +// $0.63 · stops at $5.00 (its cap)". +// +// Plain ESM: the server reads the ledger, the client form says the estimate. +// --------------------------------------------------------------------------- + +/** How many of a model's latest jobs an estimate reads. */ +export const HISTORY_RUNS = 20; + +/** + * The ledger as per-job spend: task -> model -> [usd per job], oldest first, + * at most HISTORY_RUNS each. A job's rows (one per model it called) are summed + * under the model of its largest row, which is the job's own model: an API + * sweep's extractor runs on a cheaper model beside it. + * @param {{ jobId: string, task: string, model: string, usd: number, at?: string }[]} rows + * @param {readonly string[]} [tasks] + * @returns {Record<string, Record<string, number[]>>} + */ +export function spendHistory(rows, tasks = ["sweep", "research"]) { + /** @type {Map<string, { task: string, at: string, usd: number, models: Map<string, number> }>} */ + const jobs = new Map(); + for (const r of rows) { + if (!r || !tasks.includes(r.task) || typeof r.usd !== "number" || !r.jobId) continue; + const j = jobs.get(r.jobId) ?? { task: r.task, at: r.at ?? "", usd: 0, models: new Map() }; + j.usd += r.usd; + j.models.set(r.model, (j.models.get(r.model) ?? 0) + r.usd); + if ((r.at ?? "") > j.at) j.at = r.at ?? j.at; + jobs.set(r.jobId, j); + } + /** @type {Record<string, Record<string, number[]>>} */ + const out = {}; + for (const j of [...jobs.values()].sort((a, b) => a.at.localeCompare(b.at))) { + const model = [...j.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; + if (!model) continue; + const list = ((out[j.task] ??= {})[model] ??= []); + list.push(Math.round(j.usd * 10_000) / 10_000); + if (list.length > HISTORY_RUNS) list.shift(); + } + return out; +} + +const median = (xs) => { + const s = [...xs].sort((a, b) => a - b); + const m = s.length >> 1; + return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; +}; + +/** + * The estimate for one run. + * @param {Record<string, Record<string, number[]>>} history + * @param {{ task: string, model: string, cap: number | null, local: boolean }} run + * @returns {{ kind: "local" } | { kind: "api", model: string, runs: number, typical: number | null, most: number | null, cap: number | null }} + */ +export function estimateOf(history, { task, model, cap, local }) { + if (local) return { kind: "local" }; + const past = history?.[task]?.[model] ?? []; + return { + kind: "api", + model, + runs: past.length, + typical: past.length ? Math.round(median(past) * 100) / 100 : null, + most: past.length ? Math.max(...past) : null, + cap: typeof cap === "number" && cap > 0 ? cap : null, + }; +} + +const usd = (v) => `$${v.toFixed(2)}`; + +/** The estimate in words. */ +export function estimateText(e) { + if (e.kind === "local") return "Runs on the local model: no API spend"; + const ceiling = e.cap !== null ? ` · stops at ${usd(e.cap)} (its cap)` : ""; + if (!e.runs) return `No earlier run on ${e.model} in the ledger${ceiling}`; + return `${e.runs} earlier ${e.runs === 1 ? "run" : "runs"} on ${e.model}: typical ${usd(e.typical)}, most ${usd(e.most)}${ceiling}`; +} diff --git a/umtool/lib/create/iterations.mjs b/umtool/lib/create/iterations.mjs @@ -0,0 +1,26 @@ +// --------------------------------------------------------------------------- +// Which iteration "Video from an article" (/create, P5) offers first: the +// NEWEST done iteration with a report of its OWN -- a chain cuts from a report, +// so a video revision that carries an earlier iteration's report is never the +// default (it can still be chosen). Plain ESM, unit-tested. +// --------------------------------------------------------------------------- + +/** + * The iterations a chain can run over: done, with a report (its own or an + * ancestor's), newest first. + * @template {{ n: number, status: string, hasReport: boolean, reportFrom: number | null }} T + * @param {T[]} iterations + * @returns {T[]} + */ +export function chainable(iterations) { + return iterations.filter((it) => it.status === "done" && it.reportFrom !== null).sort((a, b) => b.n - a.n); +} + +/** + * The default: the newest done iteration with its own report, else null. + * @param {{ n: number, status: string, hasReport: boolean, reportFrom: number | null }[]} iterations + * @returns {number | null} + */ +export function defaultChainIteration(iterations) { + return chainable(iterations).find((it) => it.hasReport)?.n ?? null; +} diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs @@ -0,0 +1,96 @@ +// --------------------------------------------------------------------------- +// The generation policy in one line (plans/umtool-redesign.md, P5): Create's +// policy chip and the Settings page's head say where each kind of task runs, +// grouped by route -- "Claude Code: sweeps · API: report revisions, research · +// local: video revisions, drafts" for the balanced preset. +// +// Plain ESM, no imports: a server page, a client component and `node --test` +// read the same function. +// --------------------------------------------------------------------------- + +/** How a route is said. */ +export const ROUTE_WORD = { code: "Claude Code", api: "API", local: "local" }; + +/** The media drafts (release 28) and narration: one word, "drafts", when they agree. */ +const DRAFT_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]; + +/** One task's word when it is said alone. */ +const TASK_WORD = { + sweep: "sweeps", + "revise-report": "report revisions", + "revise-video": "video revisions", + research: "research", + narrate: "narration", + cut: "cut drafts", + onscreen: "on-screen drafts", + teaser: "teaser drafts", + flips: "flips drafts", + threads: "threads drafts", + youtube: "YouTube drafts", +}; + +/** + * The routes, grouped: `[{ route, words }]` in the order code → api → local, + * each with the tasks that run there in the policy's task order. The draft + * tasks read as "drafts" when they all share a route; the two revisions as + * "revisions" when they do. + * @param {Record<string, string>} routes task -> route + * @param {readonly string[]} [tasks] the order tasks are said in + * @returns {{ route: string, words: string[] }[]} + */ +export function routeGroups(routes, tasks = Object.keys(routes)) { + const present = tasks.filter((t) => typeof routes[t] === "string"); + const drafts = DRAFT_TASKS.filter((t) => present.includes(t)); + const draftsAgree = drafts.length > 1 && drafts.every((t) => routes[t] === routes[drafts[0]]); + const revisionsAgree = present.includes("revise-report") && present.includes("revise-video") && routes["revise-report"] === routes["revise-video"]; + const said = new Set(); + /** @type {Map<string, string[]>} */ + const by = new Map(); + const add = (route, word) => { + if (!by.has(route)) by.set(route, []); + by.get(route).push(word); + }; + for (const t of present) { + if (said.has(t)) continue; + if (draftsAgree && drafts.includes(t)) { + drafts.forEach((d) => said.add(d)); + add(routes[t], "drafts"); + continue; + } + if (revisionsAgree && (t === "revise-report" || t === "revise-video")) { + said.add("revise-report"); + said.add("revise-video"); + add(routes[t], "revisions"); + continue; + } + said.add(t); + add(routes[t], TASK_WORD[t] ?? t); + } + const order = ["code", "api", "local"]; + return [...by.entries()] + .sort((a, b) => (order.indexOf(a[0]) + 99) % 99 - (order.indexOf(b[0]) + 99) % 99) + .map(([route, words]) => ({ route, words })); +} + +/** + * The policy in one line: "Claude Code: sweeps · API: report revisions, + * research · local: video revisions, drafts", or "everything on the API". + * @param {Record<string, string>} routes + * @param {readonly string[]} [tasks] + */ +export function routeSummary(routes, tasks) { + const groups = routeGroups(routes, tasks); + if (groups.length === 1) return `everything ${groups[0].route === "local" ? "local" : `on ${groups[0].route === "api" ? "the API" : "Claude Code"}`}`; + return groups.map((g) => `${ROUTE_WORD[g.route] ?? g.route}: ${g.words.join(", ")}`).join(" · "); +} + +/** + * The chip's words: "balanced · Claude Code: sweeps · …", or the reason the + * policy is unknown. + * @param {{ preset: string, routes: Record<string, string> } | null} generation + * @param {readonly string[]} [tasks] + */ +export function policyChip(generation, tasks) { + if (!generation) return "Generation: the editor did not answer"; + return `Generation: ${generation.preset} · ${routeSummary(generation.routes, tasks)}`; +} diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs @@ -53,14 +53,13 @@ test("articles open in the store or on their site", () => { 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"); + assert.equal(H.newArticleHref(), "/create?make=article"); // An article piece's tabs (P4a-2): the Overview is never written; another video project, the cut's every quote. assert.equal(H.articleHref({ site: "articles", id: "poker" }, { tab: "overview" }), "/articles/poker"); assert.equal( H.articleHref({ site: "articles", id: "poker" }, { note: "n", all: true, project: "gen/poker/i1", tab: "cut" }), "/articles/poker?tab=cut&all=1&project=gen%2Fpoker%2Fi1&note=n", ); - assert.equal(H.generationSettingsHref(), "/settings/generation"); }); test("the places: Inbox, Work (and the lists it replaced), Settings", () => { @@ -73,7 +72,7 @@ test("the places: Inbox, Work (and the lists it replaced), Settings", () => { test("every page address the builders make is still served or redirected", async () => { const { REDIRECTS } = await import("../redirects.mjs"); - const old = ["/browse", "/browse/decisions", "/browse/find", "/browse/faces", "/browse/sources", "/browse/trim/:set", "/browse/at", "/browse/:path*", "/articles", "/sites", "/mix", "/bench"]; + const old = ["/browse", "/browse/decisions", "/browse/find", "/browse/faces", "/browse/sources", "/browse/trim/:set", "/browse/at", "/browse/:path*", "/articles", "/sites", "/mix", "/bench", "/articles/new", "/"]; for (const s of old) assert.ok(REDIRECTS.some((r) => r.source === s), s); for (const r of REDIRECTS) assert.equal(r.permanent, false, r.source); }); @@ -92,6 +91,15 @@ test("site pages, tools and piles", () => { assert.equal(H.toolsHref(), "/tools"); assert.equal(H.songToolsHref(), "/tools/song"); assert.equal(H.cutHref("yoshi", "wide", { plan: "p1" }), "/projects/yoshi/wide?plan=p1"); - assert.equal(H.homeHref({ from: "ch/vid" }), "/?from=ch%2Fvid"); assert.equal(H.homeHref(), "/"); }); + +test("Create and Settings (P5)", () => { + assert.equal(H.createHref(), "/create"); + assert.equal(H.createHref({ from: "ch/vid" }), "/create?from=ch%2Fvid"); + assert.equal(H.createHref({ make: "video-board", case: "c1" }), "/create?make=video-board&case=c1"); + for (const m of H.MAKES) assert.ok(H.isMake(m), m); + assert.equal(H.isMake("video"), false); + assert.equal(H.generationPolicyHref(), "/settings/generation"); + assert.equal(H.settingsHref(), "/settings"); +}); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -68,11 +68,12 @@ type NoteOpt = { note?: string | null }; // ── the places ────────────────────────────────────────────────────────────── /** - * The Inbox. `from` is the editor's "make a video" handoff - * (`/?from=<slug>/<id>`, editor VideoPanel/VideoNavStrip): the Inbox opens the - * new-project form prefilled until /create exists (P5). + * The Inbox. `hidden` lists the calls on parked and done pieces, `muted` the + * muted ones. The editor's "make a video" hand-off, `/?from=<slug>/<id>` + * (VideoPanel, VideoNavStrip), is answered by a redirect to Create + * (redirects.mjs, P5) -- build it with createHref({ from }). */ -export function homeHref(q: { from?: string; hidden?: boolean; muted?: boolean } = {}): string { +export function homeHref(q: { hidden?: boolean; muted?: boolean } = {}): string { return withQuery("/", q); } @@ -144,23 +145,43 @@ export function articlesHref(q: ArticlesQuery = {}): string { return workHref({ kind: "article", site: ARTICLES_KEY, ...q }); } -/** A new article (release 27). */ +/** + * What Create makes (P5): each is a line on /create, `?make=` opens its form. + * research a case for a question (R2's board) + * article an article from a question: a sweep, or research first + * article-board an article from a board (R2's hand-off) + * video-article a video from an article: the chain over an iteration + * video-board a video from a board (R2's hand-off) + * video-recording a video from a recording (`from` = <channel>/<id> or a share URL) + * video-report a video from a sweep report on disk + * song a song + */ +export const MAKES = ["research", "article", "article-board", "video-article", "video-board", "video-recording", "video-report", "song"] as const; +export type Make = (typeof MAKES)[number]; +export const isMake = (v: unknown): v is Make => typeof v === "string" && (MAKES as readonly string[]).includes(v); + +/** + * Create: "What are you making?". `make` opens one line's form; `from` is the + * editor's hand-off (a recording, `<channel>/<id>`), which opens "Video from a + * recording" prefilled. `case` preselects a board, `article` an article. + */ +export function createHref(q: { make?: Make; from?: string; case?: string; article?: string } = {}): string { + return withQuery("/create", q); +} + +/** A new article: Create's "Article from a question" (it was /articles/new). */ export function newArticleHref(): string { - return "/articles/new"; + return createHref({ make: "article" }); } -/** Where the generation policy is set today (the new-article form) until /settings/generation (P5). */ +/** Settings: the generation policy -- routes, models, caps, the key, the extractor, today's spend. */ export function generationPolicyHref(): string { - return "/articles/new"; + return "/settings/generation"; } -/** - * The generation policy's own page (P5 builds it). The article piece's policy - * chip links here from P4a-2 on; generationPolicyHref keeps the page that - * holds the panel today until P5 lands. - */ -export function generationSettingsHref(): string { - return "/settings/generation"; +/** Settings: the two pages. */ +export function settingsHref(): string { + return "/settings"; } /** Settings: the machine -- tools, disk, index, sources, deliverables, recent jobs. */ diff --git a/umtool/lib/projects.ts b/umtool/lib/projects.ts @@ -112,6 +112,22 @@ export async function projectRefs(): Promise<ProjectRef[]> { return refs; } +/** + * What `pruneIndex` would drop, read only (Settings · system's plan, P5): the + * index's records for projects the walk no longer finds, against a fresh walk. + */ +export async function indexPrunePlan(): Promise<{ ok: boolean; records: number; path: string | null; builtAt: number | null; stale: { id: string; title: string | null }[] }> { + const ix = await indexHandle(); + const st = ix.stats() as { ok: boolean; records: number; path: string | null; builtAt?: number }; + if (!ix.ok) return { ok: false, records: 0, path: st.path ?? null, builtAt: null, stale: [] }; + CACHES.walk = null; + const live = new Set((await projectRefs()).map((p) => p.id)); + const stale = (ix.recent(10_000) as { id: string; title?: string }[]) + .filter((r) => !live.has(r.id)) + .map((r) => ({ id: r.id, title: typeof r.title === "string" ? r.title : null })); + return { ok: true, records: st.records, path: st.path ?? null, builtAt: st.builtAt || null, stale }; +} + /** Drop index records for projects the walk no longer finds. */ export async function pruneIndex(): Promise<number> { const ix = await indexHandle(); diff --git a/umtool/lib/projects/create.mjs b/umtool/lib/projects/create.mjs @@ -0,0 +1,65 @@ +// --------------------------------------------------------------------------- +// What Create (/create, plans/umtool-redesign.md P5) scaffolds, by KIND -- here +// because a kind id is a literal only lib/projects/ and components/projects/ +// may write (e2e/projects.spec.ts enforces it). The page asks for "the kind a +// video from a recording is" and never learns its name. +// +// video-recording a report video whose `from` is <channel>/<id> or a share URL +// video-report a report video whose `from` is a sweep report (.md) on disk +// song a song +// +// And the sweep reports on disk the "from a sweep report" form offers: every +// project of the sweep-report kind (a cited report, not yet a video), with +// its report's path and title. +// --------------------------------------------------------------------------- +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { kindById } from "./kinds.mjs"; + +const REPORT_VIDEO = "report-video"; +const SONG = "song"; +const SWEEP = "sweep-report"; + +/** The kind each scaffolding make writes. */ +export const MAKE_KIND = { "video-recording": REPORT_VIDEO, "video-report": REPORT_VIDEO, song: SONG }; + +/** + * The kind a make scaffolds, with what its form asks for (the registry's + * `scaffold`), or null when that kind cannot be scaffolded here. + * @param {string} make + * @returns {{ id: string, label: string, scaffold: { fields: string[], brands?: { id: string, label: string }[] } } | null} + */ +export function makeKind(make) { + const id = MAKE_KIND[make]; + const k = id ? kindById(id) : null; + if (!k?.scaffold) return null; + return { id: k.id, label: k.label, scaffold: k.scaffold }; +} + +const SWEEP_RE = /(^|[-_])sweep([-_]report)?\.md$|^sweep-report\.md$/i; + +/** + * The sweep reports a video can be made from: each sweep-report project's + * report file, newest first. + * @param {{ id: string, dir: string, kind: string }[]} refs the project walk + * @returns {Promise<{ project: string, path: string, title: string }[]>} + */ +export async function sweepReports(refs) { + const out = []; + for (const p of refs) { + if (p.kind !== SWEEP) continue; + const names = await readdir(/* turbopackIgnore: true */ p.dir).catch(() => []); + const name = names.find((n) => SWEEP_RE.test(n)); + if (!name) continue; + const file = path.join(/* turbopackIgnore: true */ p.dir, name); + const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch(() => ""); + const title = text.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? p.id; + out.push({ project: p.id, path: file, title }); + } + return out; +} + +/** The three scaffolding makes' kinds, as Create's page wants them. */ +export function makeKinds() { + return { recording: makeKind("video-recording"), report: makeKind("video-report"), song: makeKind("song") }; +} diff --git a/umtool/lib/settings/settings.test.mjs b/umtool/lib/settings/settings.test.mjs @@ -0,0 +1,31 @@ +// node --test umtool/lib/settings/settings.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { daySpend, recentDays } from "./spend.mjs"; + +const row = (jobId, model, usd, at, day = at.slice(0, 10), task = "sweep") => ({ at, day, jobId, article: "zeta", iteration: 1, task, model, usd, inputTokens: 0, outputTokens: 0 }); + +test("a day's spend, job by job: rows summed per job, newest first, other days left out", () => { + const rows = [ + row("a", "claude-sonnet", 0.4, "2026-10-14T09:00:00Z"), + row("a", "claude-haiku", 0.02, "2026-10-14T09:00:01Z"), + row("b", "claude-opus", 1.1, "2026-10-14T12:00:00Z", undefined, "revise-report"), + row("c", "claude-opus", 3, "2026-10-13T12:00:00Z"), + ]; + const d = daySpend(rows, "2026-10-14"); + assert.equal(d.usd, 1.52); + assert.deepEqual(d.jobs.map((j) => [j.jobId, j.task, j.models, j.usd]), [ + ["b", "revise-report", ["claude-opus"], 1.1], + ["a", "sweep", ["claude-sonnet", "claude-haiku"], 0.42], + ]); + assert.deepEqual(daySpend(rows, "2026-10-01"), { day: "2026-10-01", usd: 0, jobs: [] }); +}); + +test("the last days' totals, a quiet day as 0", () => { + const rows = [row("a", "m", 0.5, "2026-10-14T09:00:00Z"), row("c", "m", 3, "2026-10-12T12:00:00Z")]; + assert.deepEqual(recentDays(rows, "2026-10-14", 3), [ + { day: "2026-10-14", usd: 0.5 }, + { day: "2026-10-13", usd: 0 }, + { day: "2026-10-12", usd: 3 }, + ]); +}); diff --git a/umtool/lib/settings/spend.mjs b/umtool/lib/settings/spend.mjs @@ -0,0 +1,50 @@ +// --------------------------------------------------------------------------- +// A day's API spend, job by job, from the editor's usage ledger +// (common/controller/generationUsage.ts: one row per model per finished Claude +// API job, the day in UTC). /settings/generation says it under the policy: the +// total against the daily cap, and each job -- when it ended, its task, the +// article and iteration, the models it called, what it cost. P2b's rail says +// only the total ("$0.42 today"). +// +// Plain ESM: `node --test` reads it with no bundler. +// --------------------------------------------------------------------------- + +/** + * @param {{ at: string, day: string, jobId: string, article: string, iteration: number, task: string, model: string, usd: number }[]} rows + * @param {string} day YYYY-MM-DD (UTC) + * @returns {{ day: string, usd: number, jobs: { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }[] }} + */ +export function daySpend(rows, day) { + /** @type {Map<string, { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }>} */ + const jobs = new Map(); + for (const r of rows) { + if (!r || r.day !== day || typeof r.usd !== "number") continue; + const j = jobs.get(r.jobId) ?? { jobId: r.jobId, at: r.at, task: r.task, article: r.article, iteration: r.iteration, models: [], usd: 0 }; + j.usd += r.usd; + if (!j.models.includes(r.model)) j.models.push(r.model); + if (r.at > j.at) j.at = r.at; + jobs.set(r.jobId, j); + } + const list = [...jobs.values()] + .map((j) => ({ ...j, usd: Math.round(j.usd * 10_000) / 10_000 })) + .sort((a, b) => b.at.localeCompare(a.at)); + return { day, usd: Math.round(list.reduce((s, j) => s + j.usd, 0) * 10_000) / 10_000, jobs: list }; +} + +/** + * The last `n` days' totals, newest first, a day with no spend included as 0. + * @param {{ day: string, usd: number }[]} rows + * @param {string} today YYYY-MM-DD + * @param {number} [n] + */ +export function recentDays(rows, today, n = 7) { + const by = new Map(); + for (const r of rows) if (r && typeof r.usd === "number") by.set(r.day, (by.get(r.day) ?? 0) + r.usd); + const out = []; + const t = Date.parse(`${today}T00:00:00Z`); + for (let i = 0; i < n; i++) { + const day = new Date(t - i * 86_400_000).toISOString().slice(0, 10); + out.push({ day, usd: Math.round((by.get(day) ?? 0) * 100) / 100 }); + } + return out; +} diff --git a/umtool/lib/system/actions.ts b/umtool/lib/system/actions.ts @@ -0,0 +1,252 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { jobView, runningJob, startJob } from "@/lib/jobs"; +import { MEDIA_ROOT, MEDIA_TIERED } from "@/lib/paths"; +import { indexPrunePlan, invalidateProjects, projectRef, projectRefs, pruneIndex } from "@/lib/projects"; +import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; +import { pipelineProcessesFor } from "@/lib/report/busy.mjs"; +import { UMTOOL_DIR, moveDeliverablesSteps } from "@/lib/report/driver.mjs"; +import { moveDeliverables, moveDirToLocal, moveDirToMedia } from "@/lib/report/storage.mjs"; +import type { Step } from "@/lib/trim"; +import type { ActionPlanView, PlanRow } from "./plan-types"; + +// --------------------------------------------------------------------------- +// SETTINGS · SYSTEM's actions (plans/umtool-redesign.md, P5): thin APIs over +// what `umtool` already does from a terminal -- `umtool index --rebuild | +// --prune` and `umtool storage move-out | move-back | deliverables`. Every one +// that changes or moves anything is PLAN, THEN CONFIRM (the DeletePlan +// pattern): the plan is a dry run that measures and refuses and writes +// nothing; the confirm reads the plan again, refuses if it now refuses, and +// only then acts. A long one runs as a umtool job (lib/jobs.ts: one at a time, +// cancellable, in the rail's Running list) through the same CLI a terminal +// would run, so the app and the terminal can never disagree about a move. +// +// index rebuild re-read every project, write its record back (a job) +// index prune drop the records of projects that are gone (in process: +// a few hundred deletes) +// storage move-out <project> | all out/ to the media root, a link left +// storage move-back <project> | all out/ back into the project +// storage deliverables <project> media|local clips/ and share-*/, then the switch +// +// Never against the real reports root in a test: every path here is +// REPORTS_ROOT's, which the e2e suite points at its fixture. +// --------------------------------------------------------------------------- + +export class ActionError extends Error { + constructor( + message: string, + readonly status = 400, + readonly plan: ActionPlanView | null = null, + ) { + super(message); + } +} + +const CLI = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); +const mb = (n: number) => `${(n / 1024 ** 2).toFixed(1)} MB`; + +function cliStep(label: string, args: string[], timeoutMs: number): Step { + return { cwd: UMTOOL_DIR, env: {}, label, argv: ["node", CLI(), ...args], timeoutMs }; +} + +/** Start a job, or say which one is in the way. */ +function runJob(kind: string, steps: Step[], project: string | null) { + const running = runningJob(); + if (running) throw new ActionError(`a job is already running (${running.kind}) — run this when it has finished`, 409); + try { + return jobView(startJob(kind, steps, { project })); + } catch (e) { + throw new ActionError(e instanceof Error ? e.message : String(e), 409); + } +} + +// ── the index ─────────────────────────────────────────────────────────────── + +export type IndexAction = "rebuild" | "prune"; +export const isIndexAction = (v: unknown): v is IndexAction => v === "rebuild" || v === "prune"; + +export async function planIndex(action: IndexAction): Promise<ActionPlanView> { + const ix = await indexPrunePlan(); + const refusals = ix.ok ? [] : ["There is no index (the lmdb store did not open) — nothing to do; everything works without it."]; + if (action === "prune") { + return { + action: "index prune", + title: "Prune the index", + summary: ix.stale.length + ? `Drop ${ix.stale.length} of ${ix.records} records: projects the walk no longer finds. Their folders are gone already; nothing on disk changes.` + : `Nothing to drop: all ${ix.records} records are projects that exist.`, + rows: ix.stale.map((r) => ({ label: r.id, what: r.title ?? "a record with no title", state: "drop" })), + refusals, + warnings: [], + confirm: ix.stale.length ? `Drop ${ix.stale.length} ${ix.stale.length === 1 ? "record" : "records"}` : "Nothing to drop", + job: false, + blocked: !ix.ok || ix.stale.length === 0, + }; + } + invalidateProjects(); + const n = (await projectRefs()).length; + return { + action: "index rebuild", + title: "Rebuild the index", + summary: `Re-read ${n} ${n === 1 ? "project" : "projects"} and write each record back (${ix.records} now). Never needed for correctness — every read checks its own signature — but the first load after a big change is fast instead of merely correct. Runs as a job.`, + rows: ix.path ? [{ label: "store", what: ix.path }] : [], + refusals, + warnings: runningJob() ? [`a job is running (${runningJob()!.kind}): the rebuild cannot start until it has finished`] : [], + confirm: "Rebuild the index", + job: true, + blocked: !ix.ok, + }; +} + +export async function applyIndex(action: IndexAction): Promise<{ message: string; job?: ReturnType<typeof jobView> }> { + const plan = await planIndex(action); + if (plan.blocked) throw new ActionError(plan.refusals[0] ?? plan.summary, 409, plan); + if (action === "prune") { + invalidateProjects(); + const dropped = await pruneIndex(); + return { message: `Dropped ${dropped} ${dropped === 1 ? "record" : "records"}` }; + } + // The kind reads as "Index rebuild" in the rail's Running list (lib/running.mjs ownJobLabel). + const job = runJob("index-rebuild", [cliStep("rebuild the project index", ["index", "--rebuild"], 30 * 60_000)], null); + return { message: "The index rebuild is running", job }; +} + +// ── storage ───────────────────────────────────────────────────────────────── + +export type StorageAction = "move-out" | "move-back" | "deliverables"; +export type StorageInput = { action: StorageAction; project: string | null; all: boolean; to: "media" | "local" | null }; + +export function parseStorage(body: Record<string, unknown>): StorageInput { + const action = body.action; + if (action !== "move-out" && action !== "move-back" && action !== "deliverables") { + throw new ActionError('action is "move-out", "move-back" or "deliverables"'); + } + const all = body.all === true; + const project = typeof body.project === "string" && body.project.trim() ? body.project.trim() : null; + if (!all && !project) throw new ActionError("which project? name one, or all: true"); + if (all && action === "deliverables") throw new ActionError("deliverables move one project at a time"); + const to = body.to === "media" || body.to === "local" ? body.to : null; + if (action === "deliverables" && !to) throw new ActionError('to is "media" or "local"'); + return { action, project: all ? null : project, all, to }; +} + +const hasManifest = (dir: string) => stat(path.join(/* turbopackIgnore: true */ dir, MANIFEST_NAME)).then((s) => s.isFile(), () => false); + +const WORD: Record<string, string> = { + "would-move": "moves", + "would-finish": "finishes a cut move", + already: "already there", + absent: "nothing to move", + busy: "busy — skipped", + failed: "refused", +}; + +export async function planStorage(input: StorageInput): Promise<ActionPlanView> { + const refusals: string[] = []; + const warnings: string[] = []; + const rows: PlanRow[] = []; + const refs = input.all ? await projectRefs() : [await projectRef(input.project as string)]; + if (refs.some((r) => !r)) throw new ActionError(`no such project: ${input.project}`, 404); + const projects = refs as NonNullable<(typeof refs)[number]>[]; + + if (input.action === "deliverables") { + const p = projects[0]; + const to = input.to as "media" | "local"; + if (!(await hasManifest(p.dir))) refusals.push(`${p.id} has no ${MANIFEST_NAME} — deliverables are a report video's`); + const busy = pipelineProcessesFor(p); + if (busy.length) refusals.push(`a pipeline process is working in ${p.id} (pid ${busy.join(", ")}) — run this when it has finished`); + if (!refusals.length) { + try { + const r = await moveDeliverables(p.dir, to, { dryRun: true, writeMode: async () => {} }); + for (const x of r.results as { name: string; state: string; bytes?: number; files?: number; error?: string }[]) { + rows.push({ label: `${x.name}/`, what: x.error ?? WORD[x.state] ?? x.state, state: x.state, bytes: x.bytes, files: x.files }); + if (x.state === "failed") refusals.push(`${x.name}/: ${x.error}`); + } + if (!r.results.length) rows.push({ label: "—", what: "no clips/ and no share-*/ yet; only the switch is set" }); + rows.push({ + label: "storage.deliverables", + what: r.before === to ? `${to} already` : `${r.before ?? "unset (reads as local)"} → ${to}`, + state: r.before === to ? "already" : "would-move", + }); + } catch (e) { + refusals.push(e instanceof Error ? e.message : String(e)); + } + } + const bytes = rows.reduce((n, r) => n + (r.state === "would-move" ? (r.bytes ?? 0) : 0), 0); + return { + action: `storage deliverables ${p.id} ${to}`, + title: `Move ${p.id}'s deliverables to ${to === "media" ? "the media root" : "the project"}`, + summary: `clips/ and every share-*/ ${to === "media" ? `to ${MEDIA_ROOT}` : "back into the project"}, ${mb(bytes)}; then storage.deliverables: ${to}. Copied, mirrored and verified before the original goes. Runs as a job.`, + rows, + refusals, + warnings, + confirm: `Move to ${to}`, + job: true, + blocked: refusals.length > 0, + }; + } + + const toMedia = input.action === "move-out"; + if (toMedia && !MEDIA_TIERED) { + refusals.push("UMTOOL_MEDIA_DIR is not set: there is no media root to move out/ to. Set it to a directory on the media drive (outside the reports root), then restart umtool."); + } + let moving = 0; + let bytes = 0; + if (!refusals.length) { + for (const p of projects) { + const busy = pipelineProcessesFor(p); + if (busy.length) { + rows.push({ label: p.id, what: `a pipeline process is writing it (pid ${busy.join(", ")})`, state: "busy" }); + (input.all ? warnings : refusals).push(`${p.id} is busy (pid ${busy.join(", ")}) — ${input.all ? "it is skipped" : "run this when it has finished"}`); + continue; + } + try { + const r = (await (toMedia ? moveDirToMedia : moveDirToLocal)(p.dir, "out", { dryRun: true })) as { state: string; bytes?: number; files?: number }; + if (input.all && (r.state === "absent" || r.state === "already")) continue; + if (r.state === "would-move" || r.state === "would-finish") { + moving += 1; + bytes += r.bytes ?? 0; + } + rows.push({ label: p.id, what: WORD[r.state] ?? r.state, state: r.state, bytes: r.bytes, files: r.files }); + } catch (e) { + const m = e instanceof Error ? e.message : String(e); + rows.push({ label: p.id, what: m, state: "failed" }); + (input.all ? warnings : refusals).push(`${p.id}: ${m}`); + } + } + } + const subject = input.all ? "every project's out/" : `${projects[0].id}'s out/`; + return { + action: `storage ${input.action} ${input.all ? "--all" : projects[0].id}`, + title: toMedia ? `Move ${subject} to the media root` : `Move ${subject} back into the project`, + summary: refusals.length + ? "Nothing can move." + : moving + ? `${moving} ${moving === 1 ? "project" : "projects"}, ${mb(bytes)}: copied, mirrored and verified ${toMedia ? `under ${MEDIA_ROOT}, then a link left in its place` : "into the project, then the link removed"}. Runs as a job.` + : "Nothing to move: every out/ is already where it should be.", + rows, + refusals, + warnings, + confirm: toMedia ? "Move out" : "Move back", + job: true, + blocked: refusals.length > 0 || moving === 0, + }; +} + +export async function applyStorage(input: StorageInput): Promise<{ message: string; job: ReturnType<typeof jobView> }> { + const plan = await planStorage(input); + if (plan.blocked) throw new ActionError(plan.refusals[0] ?? plan.summary, 409, plan); + if (input.action === "deliverables") { + const p = (await projectRef(input.project as string))!; + const job = runJob(`move deliverables ${p.id} to ${input.to}`, moveDeliverablesSteps(p, input.to as "media" | "local"), p.id); + return { message: `Moving ${p.id}'s deliverables to ${input.to}`, job }; + } + const target = input.all ? "--all" : (input.project as string); + // "Move out reports/x", "Move back every project" in the Running list. + const job = runJob( + `${input.action} ${input.all ? "every project" : target}`, + [cliStep(`${input.action} ${input.all ? "every project" : target}`, ["storage", input.action, target], 60 * 60_000)], + input.all ? null : target, + ); + return { message: `${input.action === "move-out" ? "Moving out" : "Moving back"} ${input.all ? "every project" : target}`, job }; +} diff --git a/umtool/lib/system/plan-types.ts b/umtool/lib/system/plan-types.ts @@ -0,0 +1,27 @@ +// The shape of a Settings · system action's plan (lib/system/actions.ts), shared +// with the client's ActionPlan. Types only: safe for a client component. + +/** One thing the action touches: a project, a directory, an index record. */ +export type PlanRow = { label: string; what?: string; state?: string; bytes?: number; files?: number }; + +export type ActionPlanView = { + /** The action as the CLI would say it (`storage move-out reports/x`). */ + action: string; + title: string; + /** One or two sentences: what happens, how big, that it is a job. */ + summary: string; + rows: PlanRow[]; + /** Why it cannot run now. Any refusal blocks the confirm. */ + refusals: string[]; + /** Worth knowing; does not block. */ + warnings: string[]; + /** The confirm button's words ("Move out", "Drop 2 records"). */ + confirm: string; + /** It runs as a umtool job (in the rail's Running list). */ + job: boolean; + /** Nothing to do, or refused: the confirm is not offered. */ + blocked: boolean; +}; + +/** A confirm's answer. */ +export type ActionAnswer = { applied: true; message: string; job?: { id: string; kind: string; state: string } }; diff --git a/umtool/lib/system/roots.mjs b/umtool/lib/system/roots.mjs @@ -0,0 +1,27 @@ +// The roots, as the doctor reports them (`umtool doctor`, /settings/system): +// where projects are read, where their out/ goes, where the cache is -- and a +// cache left where it used to live (under SONG_DATA, before release 17), which +// is derived and safe to delete once `umtool index` has rebuilt the new one. +// +// Shared by the CLI and the app (P5 moved it out of bin/umtool.mjs). +import { CACHE_DIR, INDEX_DIR, MEDIA_ROOT, MEDIA_TIERED, OLD_CACHE_DIR, REPORTS_ROOT } from "../paths.mjs"; +import { measureTree, mediaRootProblem, pathState } from "../report/storage.mjs"; + +/** + * @param {{ measureOld?: boolean }} [opts] `measureOld` false skips sizing the + * old cache (a page render does not walk a tree) + */ +export async function rootsReport({ measureOld = true } = {}) { + const isDir = async (p) => (await pathState(p)).kind === "dir"; + const problem = await mediaRootProblem(); + const oldPresent = OLD_CACHE_DIR !== CACHE_DIR && (await isDir(OLD_CACHE_DIR)); + return { + ok: !problem, + reports: { path: REPORTS_ROOT, present: await isDir(REPORTS_ROOT) }, + media: { path: MEDIA_ROOT, tiered: MEDIA_TIERED, present: await isDir(MEDIA_ROOT), problem }, + cache: { path: CACHE_DIR, present: await isDir(CACHE_DIR), index: await isDir(INDEX_DIR) }, + oldCache: oldPresent + ? { path: OLD_CACHE_DIR, present: true, ...(measureOld ? { bytes: (await measureTree(OLD_CACHE_DIR)).bytes } : {}) } + : { path: OLD_CACHE_DIR, present: false }, + }; +} diff --git a/umtool/lib/system/storage-rows.ts b/umtool/lib/system/storage-rows.ts @@ -0,0 +1,36 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { projectRefs } from "@/lib/projects"; +import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; +import { deliverablesProblems, deliverablesState, outDirState } from "@/lib/report/storage.mjs"; + +// Where every project's bulk is, for Settings · system's Storage panel (P5): +// `umtool storage`'s table. out/ for every project; the deliverables (clips/, +// share-*/ and the switch) for one with a manifest. One lstat per name. + +export type StorageRow = { + id: string; + out: "absent" | "dir" | "link" | "dangling" | "other"; + deliverables: { mode: "local" | "media" | null; dirs: string; problem: string | null } | null; +}; + +const isFile = (p: string) => stat(p).then((s) => s.isFile(), () => false); + +export async function storageRows(): Promise<StorageRow[]> { + const refs = await projectRefs(); + return Promise.all( + refs.map(async (p) => { + const out = (await outDirState(p.dir)).state as StorageRow["out"]; + let deliverables: StorageRow["deliverables"] = null; + if (await isFile(path.join(/* turbopackIgnore: true */ p.dir, MANIFEST_NAME))) { + const d = await deliverablesState(p.dir); + deliverables = { + mode: d.mode, + dirs: d.dirs.map((x: { name: string; state: string }) => `${x.name}${x.state === "link" ? "→media" : x.state === "dangling" ? " MISSING" : ""}`).join(" "), + problem: deliverablesProblems(d)[0] ?? null, + }; + } + return { id: p.id, out, deliverables }; + }), + ); +} diff --git a/umtool/redirects.mjs b/umtool/redirects.mjs @@ -39,14 +39,21 @@ * }} RedirectRow */ -// Not here yet, by phase: `/?from=` → `/create?from=` and `/articles/new` → -// `/create?make=article` (P5, when /create exists -- until then the Inbox -// answers `?from=` itself); `/drafts` → `/` (P6 deletes the page). +// Not here yet, by phase: `/drafts` → `/` (P6 deletes the page; until then +// it redirects to Create's new article by itself). const p3 = (source, destination) => ({ source, destination, permanent: false, phase: "P3" }); +const p5 = (source, destination, extra = {}) => ({ source, destination, permanent: false, ...extra, phase: "P5" }); /** @type {RedirectRow[]} */ export const REDIRECTS = [ + // The editor's "make a video" hand-off (VideoPanel, VideoNavStrip link + // `<umtool>/?from=<slug>/<id>`): only when the query HAS `from`, so the Inbox + // itself is untouched. The query is passed through, so it lands on + // /create?from=<slug>/<id>, which opens "Video from a recording" prefilled. + p5("/", "/create", { has: [{ type: "query", key: "from" }] }), + // The new-article form is Create's "Article from a question". + p5("/articles/new", "/create?make=article"), // The project list became Work; the decision list became the Inbox. p3("/browse", "/work"), p3("/browse/decisions", "/"),