Archilyzer · Source

archilyzer

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

commit 46fdda71e9f6e35c2b7ff2280b0d1675790beba6
parent 6ba0e77731fea0f41ee52d285dc0847c85a2dcdb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 01:51:08 -0400

Merge main into ux/p1: P2a (live) and the project-cache fix

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

# Conflicts:
#	editor/CHANGELOG.md
#	plans/umtool-redesign.md

Diffstat:
Meditor/CHANGELOG.md | 4++++
Mpackage.json | 2+-
Mplans/umtool-redesign.md | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/app/api/browse/decisions/route.ts | 23+++++++++++++++++++----
Aumtool/app/api/pieces/lifecycle/route.ts | 38++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/pieces/route.ts | 32++++++++++++++++++++++++++++++++
Mumtool/app/api/projects/new/route.ts | 3+++
Aumtool/bin/inbox.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 27+++++++++++++++++++++++++++
Mumtool/docs/cli.md | 1+
Aumtool/e2e/inbox-engine.spec.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/links.mjs | 171++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Aumtool/lib/articles/links.test.mjs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/sites.ts | 34++++++++++++++++++++++++++++++----
Mumtool/lib/decisions.ts | 15+++++++++++++++
Aumtool/lib/inbox.ts | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/groups.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/groups.test.mjs | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/lifecycle.mjs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/lifecycle.test.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/lifecycle.ts | 35+++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces.ts | 294+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces/ids.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces/ids.test.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/projects.ts | 27+++++++++++++++++++++------
25 files changed, 2093 insertions(+), 36 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -5,6 +5,10 @@ - **umtool: Auto / Light / Dark at the foot of the rail.** Auto follows the system; a choice is a cookie the server reads, so the page is served in it with no flash. - **umtool: every page has the rail.** The mark and the wordmark (home), the places (unchanged: home · browse · decisions · articles · mix · find · song ▸), + Create (a new article or a new project), Pinned, what umtool is running, and the theme. The page's name is its title under the breadcrumb. The clip, claim and takes benches drop the rail and take the full width. - **umtool: /browse/decisions is a lit list.** One line per decision, grouped by project; `j` / `k` (or the arrows) move the lit line from anywhere on the page, and focus goes with it. The head glides 120 ms, and jumps under reduced motion. +- **umtool's decisions API carries the inbox: each decision's piece, group and one action.** `GET /api/browse/decisions` still answers one row per decision (`items[]`, each row's `project`, `href` and `counts` as before; a note's `href` still ends in `note=<id>`), and each row now also names its `piece` — `a:<site>/<report>` for an article and the video projects made from it, `p:<project>` for a project no article claims — its `category`, its `group` (Your call → Review → Blocking → Notes → Open → Ready to finish → Quiet), one `action` whose label names the result ("Make i3 current", "Adjudicate claim", "Answer note"), the piece's `lifecycle` and `hidden`. A new `groups` key holds the same rows as cards, one per piece and kind, with counts; `hidden` counts the rows on parked or done pieces. Five decisions are read from disk for the first time: `iteration-ready` (a finished iteration newer than the current one), `iteration-failed` (with what it spent), `research-proposal` (an acquisition waiting on a yes or no, read from `proposals.json`, never through the editor), `link-ambiguous` and `looks-done`. +- **umtool: a piece can be parked or marked done.** `POST /api/pieces/lifecycle {piece, state}` sets `active`, `parked` or `done`, kept in `REPORTS_ROOT/.umtool/lifecycle.json` with when and by whom; a parked or done piece's decisions stay in the list, `hidden`. "Looks done" — a song with every cut, a final video with a `share-*` batch, a published article with its video — is only ever a suggestion (a `looks-done` decision) and never sets it. `GET /api/pieces` lists every piece with its stage, lifecycle, linked projects and how many decisions wait on it. +- **`umtool inbox [--all] [--json]`** prints the decisions grouped and ranked as the inbox shows them, one card per piece and kind, and how many are hidden; `--all` lists the hidden ones and the quiet group. +- **umtool links an article's video by its iterations first.** A project an article's iteration made (`projectDir`) is that article's, and no other article matches it by slug, so a generated article no longer lists its own `…/i1` as "possible"; `current.video` picks the one its Cut opens, and a project outside the reports root is listed as not reachable here. Then a manifest's `article`, then a unique slug in the article's workspace — the only step that can be ambiguous. - **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan. - **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept. - **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor. diff --git a/package.json b/package.json @@ -24,7 +24,7 @@ "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", - "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs", + "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", "lint": "pnpm --filter export run lint", diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md @@ -345,12 +345,151 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─ | Phase | Branch | State | |---|---|---| -| P0 design | — (`~/reports/umtool-redesign/canvas.html`) | signed off 2026-10-14 (canvas v2) | -| P2a engine | `ux/p2a` | in progress | -| P1 foundation | `ux/p1` | shipped on the branch, gates green; awaiting merge (below) | -| R1, P3 | — | wait for P1 + P2a | +| P0 design | — (`~/reports/umtool-redesign/canvas.html`, version 2) | signed off 2026-10-14 | +| P2a engine | `ux/p2a` → `main` `fe1cb2d3` | LIVE 2026-10-14 (umtool BUILD_ID 4aRwqu6sh…) | +| P1 foundation | `ux/p1` | merged with `main`; gating for rollout (below) | +| R1, P3 | — | wait for P1 live | | P2b, P4a, P5, R3, P4b, P6 | — | wait for r28 on `main` | +### P2a, as shipped + +**What.** The engine behind the Inbox and Work, with no UI change: pieces, a lifecycle, the generation era's +decisions, and the grouping, all as data. + +- **Piece ids** (`umtool/lib/pieces/ids.mjs`): `a:<site>/<report>` (site may be `articles`), `p:<project>`, and + `c:<case>` reserved. A bare `x/y` never parses, so a two-segment id is never ambiguous. +- **Linking** (`umtool/lib/articles/links.mjs`), in the plan's order: + 1. An iteration's `projectDir` links its project, and CLAIMS it: no other article can match it by slug. + `current.video` picks the cut. A `projectDir` outside `REPORTS_ROOT` is listed in `unreachable`. + 2. The manifest's `article` key. + 3. A unique slug in the article's workspace. Only this step yields `possible`. + + The iterations are read as plain JSON (`projectDir`, `current.json`'s `video`), so `umtool notes` links the same + way. `/articles` and `/sites` rows carry `via`, `cut`, `how` and `unreachable` (additive). `clearLinksCache` + bumps an epoch. +- **Pieces** (`umtool/lib/pieces.ts`): + - Every article: the sites', the store's, and those in the making. + - Every project no article claims. + - For each: stage, linked projects, `possible`, `unreachable`, and why it looks done. + - A project is owned by the strongest link, then by list order. + - The graph is memoised 15 s and dropped when the links-cache epoch moves. The lifecycle is read fresh. +- **Lifecycle** (`umtool/lib/lifecycle.mjs` + `.ts`): + - `active | parked | done`, stored in `REPORTS_ROOT/.umtool/lifecycle.json` as `{state, at, by?}`. + - Every write goes to a temp file and is renamed into place, serialised. An unreadable file is never overwritten (409). + - `POST /api/pieces/lifecycle`: 400 for a bad id or state; 404 for an unknown piece, a `c:`, or a project an + article owns, naming the owner. `GET /api/pieces` gives each piece with its decision counts by group. +- **Decisions** (`umtool/lib/inbox.ts`, `umtool/lib/inbox/groups.mjs`): + - `GET /api/browse/decisions` keeps `items[]` one row per decision. `project`, `href` (a note's still ends in + `note=<id>`) and `counts` are unchanged. + - Each row gains `piece`, `category`, `group`, `action {label, href}`, `lifecycle` and `hidden`. + - Two new keys: `groups` (cards, one per piece and kind) and `hidden`. + - New disk sources: + - `iteration-ready`: done, could be current, newer than current. + - `iteration-failed`: not superseded by a later live iteration. Spend is the iteration's `usage`, else the + ledger joined on `jobId`. + - `research-proposal`: `readResearchState`, status `proposed`. + - `link-ambiguous` and `looks-done`. + - Groups: Your call → Review → Blocking → Notes → **Open** → Ready to finish → Quiet. **Open** was added for the + open decisions the plan did not place (a variant with no verdict, a link to choose). + - `openDecisions()` and the pages that call it are unchanged. +- **CLI:** `umtool inbox [--all] [--json]` runs `bin/inbox.ts` through tsx. + +| Commit | What | +|---|---| +| `2abb6ee9` | links: iterations, then manifest, then slug; claimed projects never a slug match; unreachable listed | +| `6498c072` | piece ids, the lifecycle store, the inbox's grouping and ranking (pure, unit-tested) | +| `d78b7e15` | pieces, `lib/inbox.ts` (disk sources, annotation), the decisions route, `/api/pieces`, `/api/pieces/lifecycle`, `umtool inbox` | +| `a7bda172` | `e2e/inbox-engine.spec.ts`; `test:scripts` runs `lib/pieces` and `lib/inbox` | +| `64c3ac84` | an unreadable site, store or disk source never takes the decisions down | +| `d51b85ea` | `docs/cli.md` lists `umtool inbox` | +| `f36632a0` | (orchestrator, review) one project cache for every bundle, cleared by a scaffold — fixes the `browse.spec:342` flake | + +**Gates.** + +| Gate | Result | +|---|---| +| `pnpm --filter umtool typecheck` | clean | +| repo-wide `tsc --noEmit` | clean | +| umtool unit tests (`node --test` over `umtool/lib/**/*.test.mjs` and `report-to-video/*.test.mjs`) | 734 tests: 732 pass, 2 skip. 22 are new: ids 5, lifecycle 6, groups 5, links 6 | +| `pnpm run test:scripts` | 882 tests: 880 pass, 2 skip | +| `next-build-trace.test.mjs` | 10/10, against the capped build | +| mcp | 343/343 | +| capped umtool `next build` (corpus linked, `MemoryMax=5G`) | exit 0, ~18 s compile. The `/api/pieces` and decisions route traces hold 792 files, none from the corpus or a dot-dir | +| full umtool e2e | 308 passed, 1 failed, 6 skipped, 5.5 min. The four new `inbox-engine` specs passed | +| `browse.spec.ts` alone | on `ux/p2a`: 22/23. On the base `604d43c1`, in a temporary worktree: one run 23/23, one run 22/23. Both reds are the same test | + +The one red is `browse.spec:342` ("a new song gets the shape…"). `/browse/gamma` 404s right after +`/api/projects/new` scaffolds it, red and green on the base alike. Release 24 recorded it as a flake. No P2a module +is on its path: the page and the scaffold route import none of `lib/pieces`, `lib/inbox`, `lib/lifecycle` or +`links.mjs`. The suspected cause is the 1 s project-walk memo, held per module instance, outliving +`invalidateProjects()`. That is not verified. + +**Review fix (orchestrator).** Verified and fixed in `f36632a0`: `/api/projects/new` never called +`invalidateProjects()`, and the caches were module-level, one copy per Next bundle, so an API route's invalidation +never reached the page rendered next. The caches now live on `globalThis` and the scaffold route clears them. +`browse.spec.ts` after the fix: 3 runs, 23/23 each. + +**The real `REPORTS_ROOT`, read-only.** +- Run offline with tsx on 2026-10-13/14, over the primary's corpus and a scratch copy of the umtool cache. +- No `lifecycle.json` was written; `~/reports/.umtool` does not exist. + +| Measure | Value | +|---|---| +| Total rows | 825 = today's 797 + 28 new (1 `iteration-ready`, `api-shondo-recent` i1, $1.14; 1 `link-ambiguous`, `polemic-flips` and two `takes/*` projects; 26 `looks-done`: 25 published store articles with their video + the `pokemon` song). No `iteration-failed` and no `research-proposal` exist on disk | +| Severity | 518 blocking, 181 open, 126 info. Blocking is still 518: nothing is parked yet | +| Pieces | 57: 30 article, 27 project. 25 linked projects; none unreachable; no project linked to two articles | +| Timing | warm `readInbox` 138–578 ms. Disk sources add ~6 ms over `openDecisions()` | + +Actionable decisions per group (decisions / cards): + +| Group | Today, no lifecycle | `p:quartering-diet` done | Plus the 26 looks-done pieces done | +|---|---|---|---| +| Your call | 0 / 0 | 0 / 0 | 0 / 0 | +| Review | 1 / 1 | 1 / 1 | 1 / 1 | +| Blocking | **518 / 33** | **35 / 32** (483 hidden) | **11 / 8** (507 hidden) | +| Notes | 14 / 1 | 14 / 1 | 14 / 1 | +| Open | 140 / 16 | 104 / 14 | 102 / 12 | +| Ready to finish | 26 / 26 | 26 / 26 | 0 / 0 | +| Quiet (collapsed) | 126 / 84 | 104 / 82 | 34 / 27 | + +**Found and left.** +- `quartering-diet` does NOT look done by the plan's signals. It has its final mp4 but no `share-*` batch, so the + 483 stay blocking until the operator marks it done. One POST does it. +- 24 of the 26 looks-done articles carry one blocking `manifest-invalid` on their linked project (no `channelSlug` + or a dead origin, in `hasan-leads/*` and `piratesoftware-polemics/*`). Accepting the suggestions hides them. +- With no `current.json`, every done iteration is `iteration-ready`. The fixture's zeta shows i1, i2 and i3 as one + card of 3. +- `looks-done` and the other new kinds are severity `open`, so `counts.open` rises by 28. `counts.blocking` is + unchanged. +- Not built here: drafts (r28 `draftsView`), running jobs and `askEditor`'s timeout and memo (P2b). No UI: the + dashboard and `/browse/decisions` still read `openDecisions()`. + +**Rollout (orchestrator, 2026-10-14).** Gates on the integration tip `f36632a0`: full umtool e2e 309 passed, +0 failed, 6 skipped (8.5 min); `scripts/queue-lock.test.mjs` 37/37 with the queue idle (2 timing reds earlier came +from runs holding the live queue). `main` fast-forwarded to `fe1cb2d3`; umtool built (79 s, capped) and restarted +(`~/reports/umtool-redesign/scripts/p2a-umtool.sh`), `/` 200. Live smoke: `/api/browse/decisions` 825 rows, 518 / +181 / 126, the groups as above, every `open-note` href ending `note=<id>`, 0.48 s; `/api/pieces` 57; a junk +lifecycle POST 400; no `lifecycle.json` written; the MCP `notes` tool lists the 14 open notes. + +### P0, as delivered + +The canvas `~/reports/umtool-redesign/canvas.html` (published as a private Artifact; its link is kept out of the +repo) is P1's visual spec. Version 1, 2026-10-13: ten screens on real data, the validated dark palette, the lit-line +motion study, the reader serif (Source Serif 4), the URL map and redirect table. Version 2, 2026-10-14, at the +operator's request: light and dark both first-class, and the wordmark one word ("umtool", bold lead "um"). Signed +off the same day ("everything else looks great"). + +Rulings recorded in the canvas's critique section and binding on P1 onward: +- Tokens are named by role (`--ground --panel --text --muted …`); dark is the base, light under + `prefers-color-scheme` and `data-theme`. +- Dark roles: Signal `#3fc1b0` (the brand's `#5fa8a0` stays on the mark), Meter `#b9a2ec`, kept `#c6e283`, doubt + `#ef9a2a`, reject `#de4c3c`. Light: ground `#f1efec`, Signal `#107c8b`, Meter `#5d33bd`, kept `#566609`, doubt + `#b0730f`, reject `#6e1b08`. Each set passes the dataviz validator's CVD, normal-vision and contrast checks. +- In light, no green/ochre/red set clears 4.5:1 words and CVD separation together (52,272 searched): a verdict's + colour is its glyph, the word takes a `*-text` step. Verdict colours never land on the reader surface. +- Signal only on the lit line and one primary action per screen; counts and spend are Meter; the cite thread only + on the lit line and the reader header. + ### P1, as shipped **What.** The foundation every later phase builds on, to the signed-off canvas (v2). Nothing moved URL. @@ -361,7 +500,7 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─ - **Primitives** (`components/ui/`): `button` and `badge` restyled with their exports kept (button gains `go`, the one filled Signal action, and `quiet`; `primary` is a Signal outline, `ghost` an alias of quiet; badge `md` is the canvas filter chip, `sm` a status tag); `Panel`, `Card`, `Tabs` (links, `aria-current`), `Table`/`TH`/`TD`, `Field`/`Input`/`Select`/`Textarea`, `Dialog` (native `<dialog>`), `Stepper`, `Kbd`/`KeyHint`, `EmptyState`, `Toolbar`/`ToolbarGroup`, `Verdict`; the signature **`LitList`** (client: roving tabindex, `j`/`k`/arrows/Home/End, one lit line with the Signal edge and play-head notch, 120 ms glide and 0 ms under reduced motion, nested groups via `LitGroup`, every button in it disabled until hydration by one `<fieldset disabled>`, a `lit` DOM event) with its server half `LitLine`/`LitActions`/`LitOnly`/`LitGroup`; **`ReaderPane`** and **`CiteThread`** (desk and reader forms); `use-palette.ts` (the roles as hex for canvases, repainting on a theme switch); `use-hydrated.ts`. - **Shell** (`components/shell/`): `AppRail` (server: the mark and the one-word wordmark, today's places unchanged — home · browse · decisions · articles · mix · find · song ▸ — + Create, the inert ⌘K hint, Pinned (empty), Running (umtool's own in-process job), the theme control), `AppHeader` (one Breadcrumb nav whose last crumb is the `<h1>` in Archivo 125%; the note stays the header's last `.micro`; a compact bench variant), `AppShell`. The rail is `position: fixed` and the body pads for it (`body:has(.app-rail)`), so `BrowseHeader` became a 3-line wrapper with the SAME props and its 22 users changed nothing. `/`, `/mix` and the song deck moved their hand-rolled headers onto it (the deck renders `AppHeader`; its server page renders `AppRail`); the compare page's per-side `<header>` became a panel. The clip, claim and takes benches render the shell with the rail collapsed. Below 760 px the rail is a top strip. - **URLs**: `lib/hrefs.ts`, one builder per page address (project ids encoded per segment, `?note=` always last), with `lib/hrefs.test.mjs`; `e2e/urls.ts` re-exports it; `umtool/redirects.mjs` — an empty, documented table (Next's row shape plus `phase`) answered by `next.config.ts`'s `redirects()`. -- **Restyle pass** (excluding the r28 list below): `/browse/decisions` is the first real lit list (grouped by project, `j`/`k` from anywhere, severity said as glyph + word); `/browse` and `/sites` filters on the Toolbar with an `Input` and outline buttons; the article views are `Tabs`; the dashboard's panels are `Panel`; the clip bench's transcript pane, the claim bench's context and as-recorded quote, and the evidence panel's quote, post and cue list are on the reader; links that wore Signal are ink (`.ink-link`, now in 34 files); hand-rolled controls get the seam-2 edge from one utilities-layer rule; the waveform, mix lanes and pitch rail paint the roles; the face deck's overlays use the dark roles over the photo; the dev indicator moved bottom-right (it covered the theme control; the live umtool runs `next dev`). +- **Restyle pass** (excluding the r28 list below): `/browse/decisions` is the first real lit list (grouped by project, `j`/`k` from anywhere, severity said as glyph + word); `/browse` and `/sites` filters on the Toolbar with an `Input` and outline buttons; the article views are `Tabs`; the dashboard's panels are `Panel`; the clip bench's transcript pane, the claim bench's context and as-recorded quote, and the evidence panel's quote, post and cue list are on the reader; links that wore Signal are ink (`.ink-link`, now in 34 files); hand-rolled controls get the seam-2 edge from one utilities-layer rule; the waveform, mix lanes and pitch rail paint the roles; the face deck's overlays use the dark roles over the photo; the dev indicator moved bottom-right (it covered the theme control on the e2e dev server; the live umtool runs `next start`, which has none). **Commits** (`ux/p1`, from `ux/integration` `604d43c1`): @@ -395,4 +534,3 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─ - Article bodies stay on the desk: they carry claim verdicts and note marks, which the reader must never carry. Quotes, posts, cue windows and the benches' transcripts are on the reader. The clip bench's and claim context's reader text is 15 px serif, not 16, for the panes' density. - Tab order is the rail (12 stops with the theme control) before the page; no skip link yet. - 40-odd project chips on `/browse/decisions` are still a wall; the Inbox (P3) replaces the page. - diff --git a/umtool/app/api/browse/decisions/route.ts b/umtool/app/api/browse/decisions/route.ts @@ -1,5 +1,5 @@ -import { countBySeverity, decisionsForSong } from "@/lib/decisions"; -import { openDecisions } from "@/lib/projects"; +import { countBySeverity } from "@/lib/decisions"; +import { readInbox } from "@/lib/inbox"; import { isSegment } from "@/lib/browse"; export const dynamic = "force-dynamic"; @@ -12,17 +12,32 @@ export const dynamic = "force-dynamic"; // // `?project=` narrows to one. The parameter is deliberately not called `song`, // because nothing else in this route knows what a song is. +// +// `items[]` is ONE ROW PER DECISION, never grouped and never filtered: the MCP +// reads it (mcp/src/archivalTools.ts: `open-note` rows, `project` as the notes +// target, `href` ending in `note=<id>`). The inbox's fields on each row -- +// `piece`, `category`, `group`, `action`, `lifecycle`, `hidden` -- are +// additive (lib/inbox.ts), and so is `groups`, the same rows as per-group +// cards, and `hidden`, how many rows sit on parked or done pieces. export async function GET(request: Request) { const project = new URL(request.url).searchParams.get("project"); if (project && !isSegment(project)) { return Response.json({ error: "bad project" }, { status: 400 }); } - const items = project ? await decisionsForSong(project) : await openDecisions(); + const inbox = await readInbox({ project }); + const items = inbox.items; const projects = new Set(items.map((d) => d.project)).size; return Response.json( - { items, projects, counts: countBySeverity(items) }, + { + items, + projects, + counts: countBySeverity(items), + groups: inbox.groups, + hidden: inbox.hidden, + ...(inbox.lifecycleError ? { lifecycleError: inbox.lifecycleError } : {}), + }, { headers: { "cache-control": "no-store" } }, ); } diff --git a/umtool/app/api/pieces/lifecycle/route.ts b/umtool/app/api/pieces/lifecycle/route.ts @@ -0,0 +1,38 @@ +import { isLifecycleState, LifecycleError, setLifecycle } from "@/lib/lifecycle"; +import { parsePieceId, readPieceGraph } from "@/lib/pieces"; + +export const dynamic = "force-dynamic"; + +// Park a piece, mark it done, or make it active again (lib/lifecycle.ts). +// +// POST { piece: "a:<site>/<report>" | "p:<project>", state: "active" | "parked" | "done" } +// → { piece, state, at, by } +// +// 400 for a body that is not a piece id and a state; 404 for a piece nothing on +// disk is (a research case `c:` is reserved until research boards exist); 409 +// when lifecycle.json does not parse (it is never overwritten). A "looks done" +// signal never comes through here: only this POST sets a lifecycle. +const NO_STORE = { "cache-control": "no-store" }; +const fail = (status: number, error: string) => Response.json({ error }, { status, headers: NO_STORE }); + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as { piece?: unknown; state?: unknown } | null; + if (!body || typeof body !== "object") return fail(400, "the body is { piece, state }"); + const parsed = parsePieceId(body.piece); + if (!parsed) return fail(400, `not a piece id: ${JSON.stringify(body.piece ?? null)} (a:<site>/<report> or p:<project>)`); + if (!isLifecycleState(body.state)) return fail(400, `state is active | parked | done, not ${JSON.stringify(body.state ?? null)}`); + if (parsed.kind === "case") return fail(404, "research cases have no lifecycle yet"); + const graph = await readPieceGraph(); + if (!graph.byId.has(body.piece as string)) { + // A project an article claims is part of that article's piece. + const owner = parsed.kind === "project" ? graph.pieceOfProject.get(parsed.project) : undefined; + return fail(404, owner ? `${body.piece} is part of ${owner}: set that piece's lifecycle` : `no piece ${body.piece}`); + } + try { + const entry = await setLifecycle(body.piece as string, body.state, "operator"); + return Response.json({ piece: entry.id, state: entry.state, at: entry.at, by: entry.by ?? null }, { headers: NO_STORE }); + } catch (err) { + if (err instanceof LifecycleError) return fail((err as LifecycleError & { status: number }).status, err.message); + return fail(500, (err as Error).message); + } +} diff --git a/umtool/app/api/pieces/route.ts b/umtool/app/api/pieces/route.ts @@ -0,0 +1,32 @@ +import { readInbox } from "@/lib/inbox"; +import { listPieces } from "@/lib/pieces"; +import { readLifecycle } from "@/lib/lifecycle"; + +export const dynamic = "force-dynamic"; + +// Every piece (lib/pieces.ts): an article with its linked video projects, or a +// project no article claims. Each with its kind, title, site, stage, lifecycle, +// linked projects, and how many decisions wait on it -- per inbox group, the +// visible ones, plus how many are hidden (a parked or done piece's). +// +// GET { pieces: [...], lifecycleError? } +export async function GET() { + const life = await readLifecycle(); + const [pieces, inbox] = await Promise.all([listPieces(life), readInbox()]); + const counts = new Map<string, { total: number; hidden: number; byGroup: Record<string, number> }>(); + for (const d of inbox.items) { + if (!d.piece) continue; + let c = counts.get(d.piece); + if (!c) counts.set(d.piece, (c = { total: 0, hidden: 0, byGroup: {} })); + c.total += 1; + if (d.hidden) c.hidden += 1; + else if (d.group) c.byGroup[d.group] = (c.byGroup[d.group] ?? 0) + 1; + } + return Response.json( + { + pieces: pieces.map((p) => ({ ...p, decisions: counts.get(p.id) ?? { total: 0, hidden: 0, byGroup: {} } })), + ...(life.error ? { lifecycleError: life.error } : {}), + }, + { headers: { "cache-control": "no-store" } }, + ); +} diff --git a/umtool/app/api/projects/new/route.ts b/umtool/app/api/projects/new/route.ts @@ -1,3 +1,4 @@ +import { invalidateProjects } from "@/lib/projects"; import { ScaffoldError, scaffoldProject } from "@/lib/projects/scaffold"; export const dynamic = "force-dynamic"; @@ -14,6 +15,8 @@ export async function POST(request: Request) { } try { const r = await scaffoldProject(body); + // The walk is memoised; the page this href opens must see the new project. + invalidateProjects(); return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } }); } catch (e) { const status = e instanceof ScaffoldError ? e.status : 500; diff --git a/umtool/bin/inbox.ts b/umtool/bin/inbox.ts @@ -0,0 +1,71 @@ +// `umtool inbox` -- the inbox's grouped list, from a terminal (lib/inbox.ts). +// +// TypeScript, because the inbox is: the song reducer, the article side and the +// iteration readers are the app's own modules, and printing them from a second +// implementation is the thing lib/projects/core.mjs exists to avoid. So +// bin/umtool.mjs runs this file through tsx, from umtool/ (the `@/` paths). +// +// umtool inbox [--all] [--json] +// +// Per group: its cards (one per piece and kind), the decisions they hold, and +// how many are hidden on parked or done pieces. `--all` lists the hidden ones +// too, and the quiet group's cards. Read-only. +import { readInbox, type GroupCard, type GroupSummary } from "../lib/inbox"; +import { summarizeGroups } from "../lib/inbox/groups.mjs"; + +const args = process.argv.slice(2); +const all = args.includes("--all"); +const json = args.includes("--json"); + +const inbox = await readInbox(); +const visible = inbox.items.filter((d) => !d.hidden); + +if (json) { + console.log( + JSON.stringify( + { + groups: inbox.groups, + hidden: inbox.hidden, + decisions: visible.length, + ...(inbox.lifecycleError ? { lifecycleError: inbox.lifecycleError } : {}), + ...(all ? { items: inbox.items } : {}), + }, + null, + 2, + ), + ); + process.exit(0); +} + +const clip = (s: string, n = 110) => (s.length > n ? `${s.slice(0, n - 1)}…` : s); +const card = (c: GroupCard) => + ` ${c.severity === "blocking" ? "BLOCKING " : ""}${c.piece ?? c.project} ${c.kind}${c.count > 1 ? ` ×${c.count}` : ""}` + + `\n ${clip(c.why)}\n → ${c.action.label} ${c.action.href}`; + +// The hidden rows, carded as if visible, for --all. +const hiddenGroups = all + ? (summarizeGroups(inbox.items.filter((d) => d.hidden).map((d) => ({ ...d, hidden: false }))) as GroupSummary[]) + : []; + +let cards = 0; +for (const g of inbox.groups) { + if (!g.decisions && !g.hidden) continue; + cards += g.cards.length; + const hidden = g.hidden ? ` · ${g.hidden} hidden` : ""; + console.log(`\n## ${g.label} — ${g.cards.length} card${g.cards.length === 1 ? "" : "s"}, ${g.decisions} decision${g.decisions === 1 ? "" : "s"}${hidden}`); + if (g.collapsed && !all) { + if (g.decisions) console.log(" (collapsed; --all lists it)"); + } else { + for (const c of g.cards) console.log(card(c)); + } + const h = hiddenGroups.find((x) => x.id === g.id); + if (h?.cards.length) { + console.log(" hidden (parked or done):"); + for (const c of h.cards) console.log(card(c).replace(/^ {2}/gm, " ")); + } +} +console.log( + `\n${visible.length} decision${visible.length === 1 ? "" : "s"} in ${cards} card${cards === 1 ? "" : "s"}` + + (inbox.hidden ? ` · ${inbox.hidden} hidden on parked or done pieces${all ? "" : " (--all lists them)"}` : ""), +); +if (inbox.lifecycleError) console.log(`lifecycle: ${inbox.lifecycleError} — every piece reads as active`); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -15,6 +15,7 @@ // umtool show <project> [--json] // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool decisions [--json] +// umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them // umtool folders [--json] // umtool kinds [--json] // umtool window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] @@ -685,6 +686,8 @@ function usage() { " umtool show <project> [--json]", " umtool check [<project>] [--json] exit 1 on anything blocking", " umtool decisions [--json]", + " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them", + " (--all: the hidden ones on parked/done pieces, and the quiet group)", " umtool folders [--json]", " umtool kinds [--json]", " umtool window <project> <clip> [--start S] [--end E] [--lock|--lock-end|…]", @@ -742,9 +745,33 @@ const COMMANDS = { export: cmdExport, "check-sources": cmdCheckSources, notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))), + inbox: cmdInbox, help: usage, }; +// `umtool inbox`: bin/inbox.ts, through tsx -- the inbox is the app's +// TypeScript (lib/inbox.ts), run from umtool/ so its `@/` paths resolve. +async function cmdInbox() { + const { createRequire } = await import("node:module"); + const { fileURLToPath } = await import("node:url"); + const here = path.dirname(fileURLToPath(import.meta.url)); + let cli; + try { + cli = createRequire(import.meta.url).resolve("tsx/cli"); + } catch { + die("umtool inbox needs tsx (the workspace's devDependency): run `pnpm install` at the repo root"); + } + const code = await new Promise((resolve) => { + const child = spawn(process.execPath, [cli, path.join(here, "inbox.ts"), ...argv.slice(argv.indexOf("inbox") + 1)], { + cwd: path.dirname(here), + stdio: "inherit", + }); + child.on("error", () => resolve(1)); + child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); + }); + process.exit(code); +} + const run = COMMANDS[cmd]; if (!run) die(`unknown command "${cmd}"\n\nRun \`umtool help\`.`); await run(); diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -20,6 +20,7 @@ decisions inbox cannot disagree about what is wrong with one. | `show <project> [--json]` | one project: summary, the cut, per-clip status, decisions | | `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) | | `decisions [--json]` | the inbox | +| `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx | | `folders [--json]` · `kinds [--json]` | the tree, the registry | | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | diff --git a/umtool/e2e/inbox-engine.spec.ts b/umtool/e2e/inbox-engine.spec.ts @@ -0,0 +1,157 @@ +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { warm, WARM_TIMEOUT } from "./warm"; + +// The inbox engine (plans/umtool-redesign.md, P2a): GET /api/browse/decisions +// keeps one row per decision and adds the inbox's fields; the generation era's +// decisions come from disk; a parked piece's decisions are hidden, never +// dropped; POST /api/pieces/lifecycle round-trips. Over the fixture's article in +// the making, zeta (e2e/fixtures/iterations-fixture.mjs): i1 and i2 done with +// reports, i3 a video revision, i4 failed -- and no current.json. +// +// WRITES the fixture's REPORTS_ROOT/.umtool/lifecycle.json (zeta parked, then +// active again) and a note on articles/zeta, deleted before the test ends. + +type Row = { + kind: string; + project: string; + projectKind?: string; + target: string; + href: string; + severity: "blocking" | "open" | "info"; + piece?: string; + category?: string; + group?: string; + action?: { label: string; href: string }; + lifecycle?: "active" | "parked" | "done"; + hidden?: boolean; +}; +type Group = { id: string; label: string; decisions: number; hidden: number; cards: { piece: string | null; kind: string; count: number }[] }; +type Inbox = { items: Row[]; projects: number; counts: Record<string, number>; groups: Group[]; hidden: number }; + +const ZETA = "a:articles/zeta"; + +const inbox = async (request: APIRequestContext): Promise<Inbox> => { + const r = await request.get("/api/browse/decisions"); + expect(r.ok()).toBe(true); + return r.json(); +}; +const lifecycle = (request: APIRequestContext, piece: unknown, state: unknown) => request.post("/api/pieces/lifecycle", { data: { piece, state } }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, ["/api/browse/decisions", "/api/pieces", "/api/notes?article=articles/zeta"]); +}); + +test.afterAll(async ({ request }) => { + await lifecycle(request, ZETA, "active"); +}); + +test("one row per decision, each with the inbox's fields; the counts add up", async ({ request }) => { + const { items, counts, groups, hidden } = await inbox(request); + expect(items.length).toBeGreaterThan(0); + expect(counts.blocking + counts.open + counts.info).toBe(items.length); + expect(groups.reduce((n, g) => n + g.decisions + g.hidden, 0)).toBe(items.length); + expect(hidden).toBe(items.filter((d) => d.hidden).length); + expect(groups.map((g) => g.id)).toEqual(["your-call", "review", "blocking", "notes", "open", "ready-to-finish", "quiet"]); + for (const d of items) { + expect(d.piece, `${d.kind} ${d.project}`).toMatch(/^[ap]:/); + expect(d.group).toBeTruthy(); + expect(d.category).toBeTruthy(); + expect(d.lifecycle).toBeTruthy(); + expect(typeof d.hidden).toBe("boolean"); + expect(d.action?.label).toBeTruthy(); + expect(d.action?.href).toBe(d.href); + } + // The rows openDecisions() always made are still there, project ids intact. + expect(items.some((d) => d.kind === "shadowed-name" && d.project === "find")).toBe(true); +}); + +test("the generation era's decisions come from disk", async ({ request }) => { + const { items } = await inbox(request); + const zeta = items.filter((d) => d.piece === ZETA); + const of = (kind: string) => zeta.filter((d) => d.kind === kind).map((d) => d.target).sort(); + // No current.json: every done iteration that could be current is ready. + expect(of("iteration-ready")).toEqual(["i1", "i2", "i3"]); + expect(of("iteration-failed")).toEqual(["i4"]); + const failed = zeta.find((d) => d.kind === "iteration-failed")!; + expect(failed.group).toBe("your-call"); + expect(failed.category).toBe("spend"); + expect(failed.project).toBe("sites/articles/zeta"); + expect(failed.projectKind).toBe("article"); + expect(failed.href).toBe("/articles/zeta?tab=iterations"); + const ready = zeta.find((d) => d.kind === "iteration-ready" && d.target === "i1")!; + expect(ready.group).toBe("review"); + expect(ready.action?.label).toBe("Make i1 current"); + // The project zeta's iterations made belongs to zeta's piece (linked by its + // iteration, not by slug), so its manifest decisions do too. + expect(items.some((d) => d.project === "gen-projects/zeta/i1" && d.piece === ZETA)).toBe(true); + // A published article with its video looks done: a suggestion, not a state. + const done = items.find((d) => d.kind === "looks-done" && d.piece === "a:priv/polemic-alpha"); + expect(done?.group).toBe("ready-to-finish"); + expect(done?.lifecycle).toBe("active"); +}); + +test("a parked piece's decisions are hidden, never dropped; active again shows them", async ({ request }) => { + // A note on zeta, so the MCP's contract is checked on a hidden row too. + const add = await request.post("/api/notes?article=articles/zeta", { data: { op: { op: "add", text: "Inbox engine.", anchor: { kind: "whole" } } } }); + expect(add.status()).toBe(200); + const noteId = (await add.json()).note.id as string; + try { + const before = await inbox(request); + const zetaRows = before.items.filter((d) => d.piece === ZETA); + expect(zetaRows.length).toBeGreaterThan(5); + expect(zetaRows.every((d) => !d.hidden && d.lifecycle === "active")).toBe(true); + + const park = await lifecycle(request, ZETA, "parked"); + expect(park.status()).toBe(200); + expect(await park.json()).toMatchObject({ piece: ZETA, state: "parked", by: "operator" }); + + const after = await inbox(request); + expect(after.items.length).toBe(before.items.length); + const parked = after.items.filter((d) => d.piece === ZETA); + expect(parked.length).toBe(zetaRows.length); + expect(parked.every((d) => d.hidden && d.lifecycle === "parked")).toBe(true); + expect(after.hidden).toBe(before.hidden + zetaRows.length); + // Hidden rows are counted per group and left out of the cards. + expect(after.groups.flatMap((g) => g.cards).some((c) => c.piece === ZETA)).toBe(false); + // The note row keeps the MCP's contract: project is the notes target, href ends in note=<id>. + const note = after.items.find((d) => d.kind === "open-note" && d.piece === ZETA)!; + expect(note.project).toBe("sites/articles/zeta"); + expect(note.href.endsWith(`note=${noteId}`)).toBe(true); + expect(note.action?.href.endsWith(`note=${noteId}`)).toBe(true); + + const pieces = await (await request.get("/api/pieces")).json(); + const z = pieces.pieces.find((p: { id: string }) => p.id === ZETA); + expect(z).toMatchObject({ kind: "article", site: "articles", report: "zeta", status: "in the making", stage: "research", lifecycle: "parked", lifecycleBy: "operator" }); + expect(z.projects.map((p: { id: string; via: string }) => `${p.id}:${p.via}`).sort()).toEqual(["gen-projects/zeta/i1:iteration", "gen-projects/zeta/i3:iteration"]); + expect(z.decisions.hidden).toBe(zetaRows.length); + + expect((await lifecycle(request, ZETA, "active")).status()).toBe(200); + const again = await inbox(request); + expect(again.items.filter((d) => d.piece === ZETA).every((d) => !d.hidden && d.lifecycle === "active")).toBe(true); + } finally { + await request.post("/api/notes?article=articles/zeta", { data: { op: { op: "delete", id: noteId } } }); + } +}); + +test("POST /api/pieces/lifecycle refuses junk", async ({ request }) => { + for (const [piece, state, status] of [ + ["articles/zeta", "parked", 400], // no namespace: ambiguous, refused + ["a:articles/zeta/extra", "parked", 400], + ["p:../etc", "parked", 400], + [ZETA, "shipped", 400], + [ZETA, null, 400], + [null, "parked", 400], + ["a:articles/no-such-article", "parked", 404], + ["p:no/such/project", "done", 404], + ["c:some-case", "parked", 404], + // A project zeta's iterations made is part of zeta's piece. + ["p:gen-projects/zeta/i1", "parked", 404], + ] as const) { + const r = await lifecycle(request, piece, state); + expect(r.status(), `${piece} ${state}`).toBe(status); + expect((await r.json()).error).toBeTruthy(); + } + const r = await request.post("/api/pieces/lifecycle", { data: "not json", headers: { "content-type": "text/plain" } }); + expect(r.status()).toBe(400); +}); diff --git a/umtool/lib/articles/links.mjs b/umtool/lib/articles/links.mjs @@ -1,23 +1,38 @@ // Which umtool report-video project is an article's video. // -// Two ways, in order: +// Three ways, in order (plans/umtool-redesign.md, "Linking a project to an +// article"): // -// 1. The manifest says so: a top-level `"article": "<site>/<report>"` in +// 1. The article's iterations made it: an article of the store +// (`articles/<id>`) whose `iterations/<n>/iteration.json` names a +// `projectDir`. That project is linked, and it is CLAIMED -- no other +// article can match it by slug. `current.json`'s `video` picks the one +// the article's Cut is. A `projectDir` outside REPORTS_ROOT is not +// dropped: it is listed as `unreachable` (not reachable here). +// 2. The manifest says so: a top-level `"article": "<site>/<report>"` in // video.manifest.json. build-video.mjs never reads top-level keys it does // not know (it reads `generatedBy` no more than this), so the key costs // the render nothing. A manifest that names an article is linked to it // and to nothing else. -// 2. The slug matches: the manifest's `slug` (else the project directory's +// 3. The slug matches: the manifest's `slug` (else the project directory's // name) is the report id, `polemic-<id>`, or the id without `polemic-` -- // and the project lives in the same workspace as the article's draft // (lib/articles/sources.mjs). A UNIQUE match is linked; two or more are -// only "possible", and the page says so rather than picking one. +// only "possible", and the page says so rather than picking one. Only +// this step is ever ambiguous. A project an iteration claimed (1) or +// whose manifest names an article (2) is never a slug match: before (1), +// every generated article listed its own `…/i1` as "possible". +// +// The iterations are read here as plain JSON (two keys: `projectDir`, and +// `current.json`'s `video`) rather than through common's reader, so `umtool +// notes` -- plain ESM -- links the same way the app does. Every write of +// those files is common's (lib/report/iterations.ts); this only reads. // // Plain ESM, so `umtool notes` can name an article's video too. -import { readFile } from "node:fs/promises"; +import { readdir, readFile, realpath } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { REPORTS_ROOT } from "../paths.mjs"; +import { ARTICLES_DIR, ARTICLES_KEY, REPORTS_ROOT } from "../paths.mjs"; import { projectRefs } from "../projects/core.mjs"; import { kindLinksArticles } from "../projects/kinds.mjs"; import { idKeys } from "./sources.mjs"; @@ -25,6 +40,11 @@ import { idKeys } from "./sources.mjs"; const CACHE_MS = 30_000; /** @type {Map<string, { at: number, value: Promise<any[]> }>} */ const cache = new Map(); +/** @type {Map<string, { at: number, value: Promise<Map<string, any[]>> }>} */ +const iterCache = new Map(); +// Bumped by every clearLinksCache(), so a memo built from these reads (the +// pieces list, lib/pieces.ts) is dropped by the same writes that drop them. +let epoch = 0; /** `~/x` back to an absolute path. */ export function untildify(p) { @@ -70,31 +90,152 @@ export function videoProjects(reportsRoot = REPORTS_ROOT) { export function clearLinksCache() { cache.clear(); + iterCache.clear(); + epoch += 1; +} + +/** How many times the links cache has been cleared: a memo built on it compares this. */ +export const linksCacheEpoch = () => epoch; + +const NUMERIC = /^[1-9][0-9]*$/; + +async function readJson(file) { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch { + return null; + } +} + +/** + * Every iteration of the article store that names a video project, by article: + * `Map<article, [{ n, dir, current, reachable, projectId }]>`, newest first. + * + * `reachable` is whether `dir` is under REPORTS_ROOT (realpaths, so a linked + * root still matches); `projectId` is its path relative to the root, which is + * the walk's project id when a project is there. + * + * @param {{ articlesDir?: string, reportsRoot?: string }} [opts] + */ +export function iterationProjects({ articlesDir = ARTICLES_DIR, reportsRoot = REPORTS_ROOT } = {}) { + const key = `${articlesDir}\0${reportsRoot}`; + const hit = iterCache.get(key); + if (hit && Date.now() - hit.at < CACHE_MS) return hit.value; + const value = readIterationProjects(articlesDir, reportsRoot); + iterCache.set(key, { at: Date.now(), value }); + value.catch(() => iterCache.delete(key)); + return value; +} + +/** `dir` relative to `root` as a POSIX path, or null when it is not strictly under it. */ +function under(root, dir) { + const rel = path.relative(/* turbopackIgnore: true */ root, dir); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null; + return rel.split(path.sep).join("/"); +} + +async function readIterationProjects(articlesDir, reportsRoot) { + const out = new Map(); + const lexRoot = path.resolve(/* turbopackIgnore: true */ reportsRoot); + const root = await realpath(/* turbopackIgnore: true */ lexRoot).catch(() => lexRoot); + for (const article of await readdir(/* turbopackIgnore: true */ articlesDir).catch(() => [])) { + if (article.startsWith(".")) continue; + const itDir = path.join(/* turbopackIgnore: true */ articlesDir, article, "iterations"); + const names = (await readdir(/* turbopackIgnore: true */ itDir).catch(() => [])).filter((n) => NUMERIC.test(n)); + if (!names.length) continue; + const current = await readJson(path.join(/* turbopackIgnore: true */ itDir, "current.json")); + const video = Number.isInteger(current?.video) ? current.video : null; + const list = []; + for (const name of names) { + const it = await readJson(path.join(/* turbopackIgnore: true */ itDir, name, "iteration.json")); + const raw = it && typeof it.projectDir === "string" && it.projectDir.trim() ? it.projectDir.trim() : null; + if (!raw) continue; + const n = Number(name); + const dir = path.resolve(/* turbopackIgnore: true */ untildify(raw)); + // Lexically first (the walk's ids are lexical: a linked folder inside the + // root keeps its name), then by realpath (a root reached through a link). + let rel = under(lexRoot, dir); + if (rel === null) rel = under(root, await realpath(/* turbopackIgnore: true */ dir).catch(() => dir)); + list.push({ n, dir, current: video === n, reachable: rel !== null, projectId: rel }); + } + if (list.length) out.set(article, list.sort((a, b) => b.n - a.n)); + } + return out; } const inside = (root, p) => p === root || p.startsWith(root + path.sep); /** - * The projects linked to one article: `{ linked, possible, how }`. + * The projects linked to one article: + * `{ linked, possible, how, cut, unreachable }`. + * + * `linked` rows carry `via`: "iteration" (1), "manifest" (2) or "slug" (3). + * `cut` is the linked project the article's Cut tab opens: the iteration + * `current.video` names, else the first linked. `unreachable` lists the + * iterations whose project is outside REPORTS_ROOT (`{ n, dir }`) -- shown as + * "not reachable here", never dropped. * * @param {string} siteId * @param {string} reportId - * @param {{ reportsRoot?: string, workspace?: string | null, projects?: any[] }} [opts] + * @param {{ reportsRoot?: string, articlesDir?: string, workspace?: string | null, projects?: any[], iterations?: Map<string, any[]> }} [opts] * `workspace` is the article's workspace dir (sourceFor's, `~` allowed); without * one, slug matches are only ever "possible". */ -export async function linkedProjects(siteId, reportId, { reportsRoot = REPORTS_ROOT, workspace = null, projects } = {}) { +export async function linkedProjects( + siteId, + reportId, + { reportsRoot = REPORTS_ROOT, articlesDir = ARTICLES_DIR, workspace = null, projects, iterations } = {}, +) { const all = projects ?? (await videoProjects(reportsRoot)); + const its = iterations ?? (await iterationProjects({ articlesDir, reportsRoot })); const key = `${siteId}/${reportId}`; - const declared = all.filter((p) => p.article === key); - if (declared.length) return { linked: declared, possible: [], how: "manifest names the article" }; + const byId = new Map(all.map((p) => [p.id, p])); + + // (1) the article's own iterations. + const mine = siteId === ARTICLES_KEY ? (its.get(reportId) ?? []) : []; + const unreachable = mine.filter((x) => !x.reachable).map((x) => ({ n: x.n, dir: x.dir })); + const viaIteration = []; + for (const x of mine) { + const p = x.projectId ? byId.get(x.projectId) : null; + if (p && !viaIteration.includes(p)) viaIteration.push(p); + } + // (2) a manifest that names the article. + const declared = all.filter((p) => p.article === key && !viaIteration.includes(p)); + const linked = [...viaIteration.map((p) => ({ ...p, via: "iteration" })), ...declared.map((p) => ({ ...p, via: "manifest" }))]; + if (linked.length) { + const currentId = mine.find((x) => x.current)?.projectId ?? null; + const cut = linked.find((p) => p.id === currentId) ?? linked[0]; + const how = [ + viaIteration.length ? `${viaIteration.length} made by the article's iterations` : null, + declared.length ? "manifest names the article" : null, + ] + .filter(Boolean) + .join("; "); + return { linked, possible: [], how, cut: cut.id, unreachable }; + } + // (3) the slug. Never a project an iteration claimed or a manifest gave away. + const claimed = new Set(); + for (const list of its.values()) for (const x of list) if (x.projectId) claimed.add(x.projectId); const keys = idKeys(reportId); - // A manifest that names a DIFFERENT article is never a slug match. - const bySlug = all.filter((p) => !p.article && keys.has(p.slug)); + const bySlug = all.filter((p) => !p.article && !claimed.has(p.id) && keys.has(p.slug)); const ws = workspace ? untildify(workspace) : null; const inWs = ws ? bySlug.filter((p) => inside(ws, p.dir)) : []; - if (inWs.length === 1) return { linked: inWs, possible: [], how: `slug ${inWs[0].slug} in the article's workspace` }; + if (inWs.length === 1) { + return { + linked: [{ ...inWs[0], via: "slug" }], + possible: [], + how: `slug ${inWs[0].slug} in the article's workspace`, + cut: inWs[0].id, + unreachable, + }; + } const possible = inWs.length > 1 ? inWs : bySlug; - return { linked: [], possible, how: possible.length ? `${possible.length} project(s) share the slug` : "no project" }; + return { + linked: [], + possible, + how: possible.length ? `${possible.length} project(s) share the slug` : unreachable.length ? "not reachable here" : "no project", + cut: null, + unreachable, + }; } diff --git a/umtool/lib/articles/links.test.mjs b/umtool/lib/articles/links.test.mjs @@ -0,0 +1,110 @@ +// Linking a video project to an article, in the plan's order: the article's +// iterations, then the manifest's `article`, then the slug -- and only the +// slug is ever ambiguous. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { clearLinksCache, iterationProjects, linkedProjects, linksCacheEpoch } from "./links.mjs"; + +async function put(file, value) { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, typeof value === "string" ? value : JSON.stringify(value)); +} + +const manifest = (slug, extra = {}) => ({ slug, title: slug, timeline: [], ...extra }); +const iteration = (article, n, projectDir) => ({ format: "archilyzer-iteration", version: 1, article, n, ...(projectDir ? { projectDir } : {}) }); + +async function fixture() { + const base = await mkdtemp(path.join(tmpdir(), "umtool-links-")); + const reports = path.join(base, "reports"); + const articles = path.join(base, "articles"); + // (1) zeta's iterations made two projects; a third is on another machine. + await put(path.join(reports, "articles/zeta/i1/video.manifest.json"), manifest("zeta")); + await put(path.join(reports, "articles/zeta/i3/video.manifest.json"), manifest("zeta")); + await put(path.join(articles, "zeta/iterations/1/iteration.json"), iteration("zeta", 1, path.join(reports, "articles/zeta/i1"))); + await put(path.join(articles, "zeta/iterations/2/iteration.json"), iteration("zeta", 2, null)); + await put(path.join(articles, "zeta/iterations/3/iteration.json"), iteration("zeta", 3, path.join(reports, "articles/zeta/i3"))); + await put(path.join(articles, "zeta/iterations/4/iteration.json"), iteration("zeta", 4, "/elsewhere/reports/articles/zeta/i4")); + await put(path.join(articles, "zeta/iterations/current.json"), { format: "archilyzer-iterations-current", version: 1, report: 1, reportFrom: 1, video: 3 }); + // (2) a hand-made project whose manifest names zeta. + await put(path.join(reports, "hand/zeta-cut/video.manifest.json"), manifest("zeta", { article: "articles/zeta" })); + // (3) slugs: one in a workspace, one outside it; two that only share a slug. + await put(path.join(reports, "ws/polemic-alpha/video.manifest.json"), manifest("polemic-alpha")); + await put(path.join(reports, "elsewhere/alpha/video.manifest.json"), manifest("alpha")); + await put(path.join(reports, "one/beta/video.manifest.json"), manifest("beta")); + await put(path.join(reports, "two/beta/video.manifest.json"), manifest("beta")); + clearLinksCache(); + return { base, reports, articles, o: { reportsRoot: reports, articlesDir: articles } }; +} + +test("(1) an article's iterations link their projects; current.video is the cut; a far one is unreachable", async () => { + const { o } = await fixture(); + const r = await linkedProjects("articles", "zeta", o); + assert.deepEqual( + r.linked.map((p) => [p.id, p.via]), + [ + ["articles/zeta/i3", "iteration"], + ["articles/zeta/i1", "iteration"], + ["hand/zeta-cut", "manifest"], + ], + ); + assert.equal(r.cut, "articles/zeta/i3"); + assert.deepEqual(r.possible, []); + assert.deepEqual(r.unreachable, [{ n: 4, dir: "/elsewhere/reports/articles/zeta/i4" }]); + assert.match(r.how, /2 made by the article's iterations; manifest names the article/); +}); + +test("(3) a claimed project is never another article's slug match", async () => { + const { o } = await fixture(); + // A site's own `zeta` shares the slug with zeta's i1 and i3 and with the + // hand-made cut. Before (1) claimed them, each was "possible" here -- and the + // store's zeta listed its own i1 as possible too. + const r = await linkedProjects("priv", "zeta", o); + assert.deepEqual(r.linked, []); + assert.deepEqual(r.possible, []); + assert.equal(r.cut, null); + assert.deepEqual(r.unreachable, []); +}); + +test("(3) a unique slug in the article's workspace links; without one it is only possible", async () => { + const { reports, o } = await fixture(); + const inWs = await linkedProjects("priv", "polemic-alpha", { ...o, workspace: path.join(reports, "ws") }); + assert.deepEqual(inWs.linked.map((p) => [p.id, p.via]), [["ws/polemic-alpha", "slug"]]); + assert.equal(inWs.cut, "ws/polemic-alpha"); + const noWs = await linkedProjects("priv", "polemic-alpha", o); + assert.deepEqual(noWs.linked, []); + assert.deepEqual(noWs.possible.map((p) => p.id).sort(), ["elsewhere/alpha", "ws/polemic-alpha"]); +}); + +test("(3) two projects sharing a slug are possible, never picked", async () => { + const { o } = await fixture(); + const r = await linkedProjects("priv", "beta", o); + assert.deepEqual(r.linked, []); + assert.deepEqual(r.possible.map((p) => p.id).sort(), ["one/beta", "two/beta"]); +}); + +test("iteration dirs: a root reached through a link still matches; far dirs are kept, not dropped", async () => { + const { base, reports, articles } = await fixture(); + const alias = path.join(base, "alias"); + await symlink(reports, alias); + await put(path.join(articles, "kappa/iterations/1/iteration.json"), iteration("kappa", 1, path.join(alias, "articles/zeta/i1"))); + clearLinksCache(); + const its = await iterationProjects({ articlesDir: articles, reportsRoot: reports }); + assert.deepEqual(its.get("kappa"), [{ n: 1, dir: path.join(alias, "articles/zeta/i1"), current: false, reachable: true, projectId: "articles/zeta/i1" }]); + assert.deepEqual( + its.get("zeta").map((x) => [x.n, x.reachable, x.projectId, x.current]), + [ + [4, false, null, false], + [3, true, "articles/zeta/i3", true], + [1, true, "articles/zeta/i1", false], + ], + ); +}); + +test("clearing the cache bumps the epoch a memo compares", () => { + const before = linksCacheEpoch(); + clearLinksCache(); + assert.equal(linksCacheEpoch(), before + 1); +}); diff --git a/umtool/lib/articles/sites.ts b/umtool/lib/articles/sites.ts @@ -47,7 +47,13 @@ export function reportDirFor(site: string, report: string): string { export type ArticleStatus = "published" | "draft"; -export type ProjectLinkRow = { id: string; title: string; slug: string }; +export type ProjectLinkRow = { + id: string; + title: string; + slug: string; + /** How a linked project is linked (lib/articles/links.mjs): its iterations, its manifest, or its slug. */ + via?: "iteration" | "manifest" | "slug"; +}; export type ArticleRow = { site: string; @@ -71,7 +77,16 @@ export type ArticleRow = { problem: string | null; problems: number; source: { draft?: string; generator?: string; how?: string; workspace?: string } | null; - projects: { linked: ProjectLinkRow[]; possible: ProjectLinkRow[] }; + projects: { + linked: ProjectLinkRow[]; + possible: ProjectLinkRow[]; + /** The linked project the Cut opens (current.video's), else null. */ + cut?: string | null; + /** In words: how the links were made. */ + how?: string; + /** Iterations whose project is outside REPORTS_ROOT: not reachable here. */ + unreachable?: { n: number; dir: string }[]; + }; }; export type SiteRow = { @@ -132,7 +147,12 @@ async function articleRow(siteId: string, id: string, published: Set<string>, pr const dir = reportDirFor(siteId, id); const r = read.report; const links = await linkedProjects(siteId, id, { workspace: source?.workspace ?? null, projects }); - const row = (p: { id: string; title: string; slug: string }) => ({ id: p.id, title: p.title, slug: p.slug }); + const row = (p: { id: string; title: string; slug: string; via?: ProjectLinkRow["via"] }): ProjectLinkRow => ({ + id: p.id, + title: p.title, + slug: p.slug, + ...(p.via ? { via: p.via } : {}), + }); return { site: siteId, id, @@ -151,7 +171,13 @@ async function articleRow(siteId: string, id: string, published: Set<string>, pr problem: read.problems[0]?.message ?? null, problems: read.problems.length, source, - projects: { linked: links.linked.map(row), possible: links.possible.map(row) }, + projects: { + linked: links.linked.map(row), + possible: links.possible.map(row), + cut: links.cut ?? null, + how: links.how, + unreachable: links.unreachable ?? [], + }, ...(siteId === ARTICLES_KEY ? { audience: articleAudience(r) } : {}), }; } diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -76,6 +76,21 @@ export type Decision = { severity: Severity; /** Newest evidence first. */ at: number; + + // ---- The inbox's fields (lib/inbox.ts). ADDITIVE: a row without them is + // still a decision, and the reducers above never set them. ---- + /** The piece it belongs to (lib/pieces/ids.mjs): `a:<site>/<report>` or `p:<project>`. */ + piece?: string; + /** What kind of thing it is (lib/inbox/groups.mjs CATEGORIES): spend, review, fix, note, choose, finish, info. */ + category?: string; + /** Where the inbox puts it (lib/inbox/groups.mjs GROUPS). */ + group?: string; + /** The ONE primary action; its label names the result. `href` is the row's own (a note's ends in `note=<id>`). */ + action?: { label: string; href: string }; + /** The piece's lifecycle (lib/lifecycle.ts); absent from the file is `active`. */ + lifecycle?: "active" | "parked" | "done"; + /** On a parked or done piece: kept in the list, out of the way. */ + hidden?: boolean; }; export const SEVERITIES: Severity[] = ["blocking", "open", "info"]; diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -0,0 +1,246 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { readResearchState } from "yt-dlp-transcript-common/lib/report/draft/research/state"; +import { ARTICLES_KEY } from "./paths"; +import { readArticleIterations, type IterationRow } from "./articles/generation"; +import { sitesPaths } from "./articles/sites"; +import { decisionsForSong, type Decision } from "./decisions"; +import { openDecisions } from "./projects"; +import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces"; +import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle"; +import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs"; + +// --------------------------------------------------------------------------- +// THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the +// projects' and the notes'), plus the generation era's, read from disk -- +// +// iteration-ready a finished iteration that is not current and is newer +// than the current one: make it current, or not +// iteration-failed a failed run nothing later has superseded, with what +// it spent +// research-proposal an acquisition a research run proposed, waiting on a +// yes or no (common's readResearchState: a READ of +// proposals.json -- never readResearch(), which POSTs to +// the editor and may rewrite the file) +// link-ambiguous an article whose video only a slug suggests +// looks-done a piece every signal says is finished (a suggestion: +// it never sets the lifecycle) +// +// -- each row given its piece, category, group, one action, lifecycle and +// `hidden` (lib/inbox/groups.mjs), ranked. One row per decision, never dropped: +// the MCP reads `items[]` (mcp/src/archivalTools.ts). +// +// No editor call anywhere here: there is no "waiting on a cap" state (the daily +// cap refuses at start, a per-job cap ends the run), and running jobs are +// P2b's. +// +// SERVER ONLY. +// --------------------------------------------------------------------------- + +export type GroupCard = { + piece: string | null; + project: string; + title: string; + kind: string; + severity: Decision["severity"]; + count: number; + why: string; + action: { label: string; href: string }; + at: number; +}; +export type GroupSummary = { + id: string; + label: string; + collapsed: boolean; + /** Visible decisions in the group. */ + decisions: number; + /** Decisions on parked or done pieces. */ + hidden: number; + cards: GroupCard[]; +}; + +export type Inbox = { + items: Decision[]; + groups: GroupSummary[]; + hidden: number; + /** lifecycle.json could not be read: every piece reads as active. */ + lifecycleError?: string; +}; + +export const INBOX_GROUPS = GROUPS as { id: string; label: string; collapsed: boolean }[]; + +const iterationsHref = (article: string) => `/articles/${article}?tab=iterations`; +const timeOf = (iso: string | null | undefined) => { + const ms = iso ? Date.parse(iso) : NaN; + return Number.isFinite(ms) ? ms : 0; +}; +const usd = (n: number) => `$${n.toFixed(2)}`; + +/** The store's articles: published, drafts and those in the making. */ +const storeArticles = (graph: PieceGraph): Piece[] => graph.pieces.filter((p) => p.kind === "article" && p.site === ARTICLES_KEY); + +const articleRow = (piece: Piece) => ({ + project: `sites/${piece.site}/${piece.report}`, + projectKind: "article", + projectTitle: piece.title, + piece: piece.id, +}); + +/** + * Iteration decisions for one article: ready, failed, and its research runs' + * proposals. `spend` joins the ledger's rows on the iteration's job when the + * iteration itself recorded no usage. + */ +async function iterationDecisions(piece: Piece, spendOfJob: Map<string, number>): Promise<Decision[]> { + const article = piece.report as string; + const its = await readArticleIterations(article).catch(() => null); + if (!its) return []; + const out: Decision[] = []; + const base = articleRow(piece); + const href = iterationsHref(article); + const cur = its.current; + const spent = (r: IterationRow) => (r.usd > 0 ? r.usd : r.jobId ? (spendOfJob.get(r.jobId) ?? 0) : 0); + const live = (r: IterationRow) => r.status === "queued" || r.status === "running" || r.status === "done"; + + for (const r of its.iterations) { + const at = timeOf(r.endedAt ?? r.createdAt); + if (r.status === "done" && r.kind !== "research") { + // A video revision competes with the current video; anything else with + // the current report. Only something that could BE current is ready. + const video = r.kind === "revise-video"; + const against = video ? cur.video : cur.report; + const makeable = video ? r.hasManifest : r.hasReport; + if (makeable && (against === null || r.n > against)) { + out.push({ + ...base, + kind: "iteration-ready", + target: r.label, + why: + `${r.label} (${r.kind} on ${r.model}) is done and newer than the current ${video ? "video" : "report"}` + + `${against === null ? " (none yet)" : ` (i${against})`}${spent(r) ? ` · ${usd(spent(r))}` : ""}`, + href, + severity: "open", + at, + }); + } + } + if (r.status === "failed") { + // A failed run is a decision until something after it runs. + const superseded = its.iterations.some((o) => o.n > r.n && live(o)); + if (!superseded) { + out.push({ + ...base, + kind: "iteration-failed", + target: r.label, + why: `${r.label} (${r.kind} on ${r.model}) failed${r.error ? `: ${r.error}` : ""}${spent(r) ? ` · ${usd(spent(r))} spent` : ""}`, + href, + severity: "open", + at, + }); + } + } + if (r.kind === "research") { + const state = await readResearchState(article, r.n, sitesPaths()).catch(() => null); + for (const p of state?.proposals ?? []) { + if (p.status !== "proposed") continue; + const est = p.estimate + ? [ + p.estimate.items ? `${p.estimate.items} item${p.estimate.items === 1 ? "" : "s"}` : null, + p.estimate.gb ? `${p.estimate.gb} GB` : null, + p.estimate.transcribeHours ? `${p.estimate.transcribeHours} h to transcribe` : null, + ] + .filter(Boolean) + .join(", ") + : ""; + out.push({ + ...base, + kind: "research-proposal", + target: `${r.label} ${p.id}`, + why: `${p.action}${p.reason ? `: ${p.reason}` : ""}${est ? ` (${est})` : ""}`, + href, + severity: "open", + at, + }); + } + } + } + return out; +} + +/** Decisions only the pieces can see: ambiguous links and pieces that look done. */ +function pieceDecisions(graph: PieceGraph, life: LifecycleRead): Decision[] { + const out: Decision[] = []; + for (const p of graph.pieces) { + const base = + p.kind === "article" + ? articleRow(p) + : { project: p.project as string, projectTitle: p.title, piece: p.id }; + if (p.kind === "article" && !p.projects.length && p.possible.length) { + out.push({ + ...base, + kind: "link-ambiguous", + target: p.possible.map((x) => x.id).join(", "), + why: + p.possible.length === 1 + ? `${p.possible[0].id} shares its slug but is not linked — name the article in its manifest to link it` + : `${p.possible.length} projects share its slug and none is linked: ${p.possible.map((x) => x.id).join(", ")}`, + href: p.href, + severity: "open", + at: p.newestMs, + }); + } + if (p.looksDone.length && lifecycleOf(life, p.id) !== "done") { + out.push({ + ...base, + kind: "looks-done", + target: p.id, + why: `looks done: ${p.looksDone.join("; ")}`, + href: p.href, + severity: "open", + at: p.newestMs, + }); + } + } + return out; +} + +/** The ledger's spend per job id, for an iteration that recorded none itself. */ +async function spendByJob(): Promise<Map<string, number>> { + const rows = await readGenerationUsage(getPaths().generationUsageFile).catch(() => []); + const out = new Map<string, number>(); + for (const r of rows) if (r.jobId) out.set(r.jobId, (out.get(r.jobId) ?? 0) + r.usd); + return out; +} + +/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done. */ +export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> { + const spend = await spendByJob(); + const perArticle = await Promise.all(storeArticles(graph).map((p) => iterationDecisions(p, spend))); + return [...perArticle.flat(), ...pieceDecisions(graph, life)]; +} + +/** + * The inbox. `project` narrows to one song's reducer (the decisions route's + * `?project=`), annotated the same way, with no disk sources added. + */ +export async function readInbox({ project }: { project?: string | null } = {}): Promise<Inbox> { + const [base, graph, life] = await Promise.all([ + project ? decisionsForSong(project) : openDecisions(), + readPieceGraph(), + readLifecycle(), + ]); + // A disk source that cannot be read adds nothing; it never hides the rest. + const extra = project ? [] : await diskDecisions(graph, life).catch(() => [] as Decision[]); + const items = rankDecisions( + annotate([...base, ...extra], { + pieceOf: (d: Decision) => pieceOfDecision(d, graph), + lifecycleOf: (id: string) => lifecycleOf(life, id), + }), + ) as Decision[]; + return { + items, + groups: summarizeGroups(items) as GroupSummary[], + hidden: items.filter((d) => d.hidden).length, + ...(life.error ? { lifecycleError: life.error } : {}), + }; +} diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -0,0 +1,218 @@ +// THE INBOX'S ORDER: which group a decision is in, how the groups rank, and +// the one action each offers (plans/umtool-redesign.md, "Target information +// architecture", Inbox). Pure functions over decision rows -- no disk, no +// clock -- so the ranking is unit-tested and the API, the CLI and (P3) the page +// share one definition. +// +// GROUPS, in order: +// +// your-call research proposals, then failed runs: money is waiting +// on a yes or no ("spend") +// review a finished iteration that is not current (r28's drafts +// join here in P2b) +// blocking something downstream would lie, on an ACTIVE piece +// notes the operator's open notes +// open every other open decision (a variant with no verdict, a +// link only the operator can choose, …) +// ready-to-finish a piece that looks done: mark it done, or keep it going +// quiet true facts that are not decisions; collapsed +// +// A decision on a PARKED or DONE piece keeps its group and is `hidden`. The +// API never drops it (one row per decision, the MCP reads every row); the +// inbox shows a hidden count instead of the rows. + +export const GROUPS = [ + { id: "your-call", label: "Your call", collapsed: false }, + { id: "review", label: "Review", collapsed: false }, + { id: "blocking", label: "Blocking", collapsed: false }, + { id: "notes", label: "Notes", collapsed: false }, + { id: "open", label: "Open", collapsed: false }, + { id: "ready-to-finish", label: "Ready to finish", collapsed: false }, + { id: "quiet", label: "Quiet", collapsed: true }, +]; +export const GROUP_IDS = GROUPS.map((g) => g.id); + +/** + * A decision's CATEGORY: what kind of thing it is, independent of where it + * sits. `spend` is research proposals plus failed runs (there is no "waiting + * on a cap" state: the daily cap refuses at start, a per-job cap ends the run). + */ +export const CATEGORIES = ["spend", "review", "fix", "note", "choose", "finish", "info"]; + +const KIND_CATEGORY = { + "research-proposal": "spend", + "iteration-failed": "spend", + "iteration-ready": "review", + "open-note": "note", + "unreadable-notes": "fix", + "link-ambiguous": "choose", + "looks-done": "finish", +}; + +const CATEGORY_GROUP = { + spend: "your-call", + review: "review", + fix: "blocking", + note: "notes", + choose: "open", + finish: "ready-to-finish", + info: "quiet", +}; + +/** @param {{ kind: string, severity: string }} d */ +export function categoryOf(d) { + const named = KIND_CATEGORY[d.kind]; + if (named) return named; + return d.severity === "blocking" ? "fix" : d.severity === "open" ? "choose" : "info"; +} + +/** @param {{ kind: string, severity: string }} d */ +export function groupOf(d) { + // Information is quiet whatever its kind: a fact is not a decision. + if (d.severity === "info") return "quiet"; + return CATEGORY_GROUP[categoryOf(d)]; +} + +// Within a group: the brief's order first (proposals before failed runs), then +// everything else as equals. +const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "unreadable-notes": 0 }; +const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; + +// ONE primary action per decision, its button copy naming the result. +const ACTION_LABEL = { + "research-proposal": "Approve acquisition", + "iteration-failed": "Retry run", + "iteration-ready": (d) => `Make ${d.target} current`, + "open-note": "Answer note", + "unreadable-notes": "Repair notes.json", + "link-ambiguous": "Link the video", + "looks-done": "Mark done", + "claim-unadjudicated": "Adjudicate claim", + "claim-incoherent": "Rule on the flag", + "clip-no-cues": "Fix the cue source", + "clip-unfetchable": "Replace the source", + "clip-mid-sentence": "Trim to the sentence", + "clip-cue-gap": "Fix the window", + "clip-cut-outside": "Fix the cut", + "window-overlap": "Fix the windows", + "no-punctuation": "Check the windows", + "manifest-invalid": "Fix the manifest", + "stale-build": "Rebuild the video", + unbuilt: "Build the video", + "storage-unreachable": "Reconnect the media drive", + "storage-mismatch": "Settle the storage", + "unjudged-variant": "Judge variant", + "missing-cut": "Ship the cut", + "stale-recipe": "Record the recipe", + "no-recipe": "Record the recipe", + "spec-problem": "Fix the spec", + "no-plan": "Name the plan", + unattributed: "Attribute variant", + "thumb-unaccepted": "Accept a cover", + loudness: "Re-render at the target", + "shadowed-name": "Rename the project", + "unroutable-name": "Rename the project", + "ambiguous-project": "Fix the project's files", +}; + +const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" }; + +/** + * The decision's one action: `{ label, href }`. The href is the decision's + * own, untouched -- a note's still ends in `note=<id>` (the MCP relies on it). + * + * @param {{ kind: string, severity: string, target: string, href: string }} d + */ +export function actionOf(d) { + const named = ACTION_LABEL[d.kind]; + const label = typeof named === "function" ? named(d) : (named ?? CATEGORY_LABEL[categoryOf(d)]); + return { label, href: d.href }; +} + +/** + * Add the inbox's fields to each row: `piece`, `category`, `group`, `action`, + * `lifecycle`, `hidden`. Never drops or merges a row. + * + * @template {{ kind: string, severity: string, target: string, href: string, project: string }} D + * @param {D[]} items + * @param {{ pieceOf: (d: D) => string | null, lifecycleOf: (piece: string) => string }} how + */ +export function annotate(items, { pieceOf, lifecycleOf }) { + return items.map((d) => { + const piece = d.piece ?? pieceOf(d); + const lifecycle = piece ? lifecycleOf(piece) : "active"; + return { + ...d, + ...(piece ? { piece } : {}), + category: categoryOf(d), + group: groupOf(d), + action: actionOf(d), + lifecycle, + hidden: lifecycle === "parked" || lifecycle === "done", + }; + }); +} + +/** + * The inbox's order: visible before hidden, then by group, then the kind's + * rank in its group, then severity, then newest first. Stable for equals (by + * piece, kind, target), so two reads of the same disk give the same list. + */ +export function rankDecisions(items) { + const g = (d) => GROUP_IDS.indexOf(d.group ?? groupOf(d)); + return [...items].sort( + (a, b) => + Number(!!a.hidden) - Number(!!b.hidden) || + g(a) - g(b) || + (KIND_RANK[a.kind] ?? 9) - (KIND_RANK[b.kind] ?? 9) || + (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3) || + (b.at ?? 0) - (a.at ?? 0) || + String(a.piece ?? a.project).localeCompare(String(b.piece ?? b.project)) || + a.kind.localeCompare(b.kind) || + String(a.target).localeCompare(String(b.target)), + ); +} + +/** + * The grouped summary, for a page or a terminal: per group, its CARDS (one per + * piece and kind -- 483 unadjudicated claims on one video are one card), how + * many decisions they hold, and how many are hidden. Rows are counted, never + * dropped: `decisions + hidden` over every group is `items.length`. + * + * @param {Array<Record<string, any>>} items annotated rows + */ +export function summarizeGroups(items) { + const ranked = rankDecisions(items); + const out = GROUPS.map((g) => ({ ...g, decisions: 0, hidden: 0, cards: [] })); + const byId = new Map(out.map((g) => [g.id, g])); + const cardOf = new Map(); + for (const d of ranked) { + const group = byId.get(d.group ?? groupOf(d)); + if (d.hidden) { + group.hidden += 1; + continue; + } + group.decisions += 1; + const key = `${group.id}\u0000${d.piece ?? d.project}\u0000${d.kind}`; + let card = cardOf.get(key); + if (!card) { + card = { + piece: d.piece ?? null, + project: d.project, + title: d.projectTitle ?? d.project, + kind: d.kind, + severity: d.severity, + count: 0, + why: d.why, + action: d.action ?? actionOf(d), + at: d.at ?? 0, + }; + cardOf.set(key, card); + group.cards.push(card); + } + card.count += 1; + if ((SEVERITY_RANK[d.severity] ?? 3) < (SEVERITY_RANK[card.severity] ?? 3)) card.severity = d.severity; + card.at = Math.max(card.at, d.at ?? 0); + } + return out; +} diff --git a/umtool/lib/inbox/groups.test.mjs b/umtool/lib/inbox/groups.test.mjs @@ -0,0 +1,114 @@ +// The inbox's grouping and ranking: pure, over hand-made rows. +import assert from "node:assert/strict"; +import test from "node:test"; +import { GROUP_IDS, actionOf, annotate, categoryOf, groupOf, rankDecisions, summarizeGroups } from "./groups.mjs"; + +const row = (kind, severity, extra = {}) => ({ + kind, + severity, + project: extra.project ?? "proj", + target: extra.target ?? "t", + why: extra.why ?? `${kind} why`, + href: extra.href ?? "/browse/proj", + at: extra.at ?? 0, + ...extra, +}); + +test("each kind lands in its group, in the brief's order", () => { + const cases = [ + ["research-proposal", "open", "your-call", "spend"], + ["iteration-failed", "open", "your-call", "spend"], + ["iteration-ready", "open", "review", "review"], + ["claim-unadjudicated", "blocking", "blocking", "fix"], + ["unreadable-notes", "blocking", "blocking", "fix"], + ["open-note", "open", "notes", "note"], + ["link-ambiguous", "open", "open", "choose"], + ["unjudged-variant", "open", "open", "choose"], + ["looks-done", "open", "ready-to-finish", "finish"], + ["loudness", "info", "quiet", "info"], + ["unbuilt", "info", "quiet", "info"], + ]; + for (const [kind, severity, group, category] of cases) { + assert.equal(groupOf({ kind, severity }), group, kind); + assert.equal(categoryOf({ kind, severity }), category, kind); + } + assert.deepEqual(GROUP_IDS, ["your-call", "review", "blocking", "notes", "open", "ready-to-finish", "quiet"]); +}); + +test("ranking: group order, proposals before failed runs, newest first, hidden last", () => { + const items = annotate( + [ + row("loudness", "info", { at: 9 }), + row("looks-done", "open", { at: 8 }), + row("open-note", "open", { at: 7 }), + row("claim-unadjudicated", "blocking", { at: 1, project: "old" }), + row("claim-unadjudicated", "blocking", { at: 5, project: "new" }), + row("iteration-ready", "open", { at: 6 }), + row("iteration-failed", "open", { at: 10 }), + row("research-proposal", "open", { at: 2 }), + row("clip-no-cues", "blocking", { at: 99, project: "parked-one" }), + ], + { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:parked-one" ? "parked" : "active") }, + ); + const ranked = rankDecisions(items).map((d) => `${d.kind}:${d.project}`); + assert.deepEqual(ranked, [ + "research-proposal:proj", + "iteration-failed:proj", + "iteration-ready:proj", + "claim-unadjudicated:new", + "claim-unadjudicated:old", + "open-note:proj", + "looks-done:proj", + "loudness:proj", + "clip-no-cues:parked-one", + ]); +}); + +test("annotate adds the fields and never drops, merges or reorders a row", () => { + const input = [row("open-note", "open", { href: "/sites/priv/x?note=n1" }), row("clip-no-cues", "blocking", { project: "gone" })]; + const out = annotate(input, { pieceOf: (d) => (d.project === "gone" ? null : "a:priv/x"), lifecycleOf: () => "done" }); + assert.equal(out.length, 2); + assert.equal(out[0].piece, "a:priv/x"); + assert.equal(out[0].lifecycle, "done"); + assert.equal(out[0].hidden, true); + // A note's action keeps its href, `note=<id>` last. + assert.deepEqual(out[0].action, { label: "Answer note", href: "/sites/priv/x?note=n1" }); + assert.match(out[0].href, /note=n1$/); + // No piece: active, not hidden, no piece key. + assert.equal("piece" in out[1], false); + assert.equal(out[1].lifecycle, "active"); + assert.equal(out[1].hidden, false); + // A piece already on the row wins. + assert.equal(annotate([row("x", "open", { piece: "p:keep" })], { pieceOf: () => "p:other", lifecycleOf: () => "active" })[0].piece, "p:keep"); +}); + +test("an action names its result; an iteration's names the iteration", () => { + assert.equal(actionOf(row("iteration-ready", "open", { target: "i3" })).label, "Make i3 current"); + assert.equal(actionOf(row("looks-done", "open")).label, "Mark done"); + assert.equal(actionOf(row("never-heard-of-it", "blocking")).label, "Fix it"); + assert.equal(actionOf(row("never-heard-of-it", "info")).label, "Open"); +}); + +test("the summary: one card per piece and kind, counts that add up, hidden counted", () => { + const claims = Array.from({ length: 483 }, (_, i) => row("claim-unadjudicated", "blocking", { project: "quartering-diet", target: `c${i}`, at: i })); + const items = annotate( + [...claims, row("clip-no-cues", "blocking", { project: "other" }), row("open-note", "open", { project: "parked" }), row("loudness", "info")], + { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:parked" ? "parked" : "active") }, + ); + const groups = summarizeGroups(items); + const blocking = groups.find((g) => g.id === "blocking"); + assert.equal(blocking.decisions, 484); + assert.equal(blocking.cards.length, 2); + assert.equal(blocking.cards[0].piece, "p:quartering-diet"); + assert.equal(blocking.cards[0].count, 483); + assert.equal(blocking.cards[0].at, 482); + const notes = groups.find((g) => g.id === "notes"); + assert.equal(notes.decisions, 0); + assert.equal(notes.hidden, 1); + assert.equal(groups.find((g) => g.id === "quiet").collapsed, true); + assert.equal(groups.reduce((n, g) => n + g.decisions + g.hidden, 0), items.length); + // Parking the video hides all 483 and leaves one card. + const parked = summarizeGroups(annotate(items, { pieceOf: (d) => `p:${d.project}`, lifecycleOf: (p) => (p === "p:quartering-diet" ? "done" : "active") })); + assert.equal(parked.find((g) => g.id === "blocking").decisions, 1); + assert.equal(parked.find((g) => g.id === "blocking").hidden, 483); +}); diff --git a/umtool/lib/lifecycle.mjs b/umtool/lib/lifecycle.mjs @@ -0,0 +1,122 @@ +// A PIECE's lifecycle: active, parked or done (plans/umtool-redesign.md, +// "Lifecycle"). +// +// REPORTS_ROOT/.umtool/lifecycle.json +// { format: "umtool-lifecycle", version: 1, +// pieces: { "<piece id>": { state, at, by? } } } +// +// STATE, NOT CACHE: it is the operator's word on a piece, so it lives beside +// the projects (the walk skips dot-dirs, so it is never a project) and not in +// CACHE_DIR. A piece with no entry is `active`. +// +// "Looks done" signals (a song's every cut shipped, a final mp4 plus a +// `share-*` batch, a published article with its video) only ever SUGGEST: they +// become a `looks-done` decision (lib/inbox.ts) and never write here. Only +// the operator's POST /api/pieces/lifecycle does. +// +// One writer, serialised in-process, and every write is a whole file to a temp +// name and a rename. A file that does not parse is never overwritten: a write +// refuses (LifecycleUnreadable) until somebody fixes it; a read treats it as +// "nothing set" and says so in `error`. +// +// Plain ESM, so a CLI and a unit test read it the way the app does. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { isPieceId } from "./pieces/ids.mjs"; + +export const LIFECYCLE_STATES = ["active", "parked", "done"]; +export const LIFECYCLE_FORMAT = "umtool-lifecycle"; +export const LIFECYCLE_VERSION = 1; + +export class LifecycleError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "LifecycleError"; + this.status = status; + } +} + +/** The file under a reports root. */ +export function lifecycleFile(reportsRoot) { + return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "lifecycle.json"); +} + +const isState = (s) => LIFECYCLE_STATES.includes(s); + +/** + * Every entry: `{ pieces: { [id]: { state, at, by? } }, error? }`. A missing + * file is empty; an unreadable one is empty with `error`. Entries that are not + * a piece id or a state are skipped, never fatal. + * + * @param {string} reportsRoot + */ +export async function readLifecycle(reportsRoot) { + let text; + try { + text = await readFile(/* turbopackIgnore: true */ lifecycleFile(reportsRoot), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return { pieces: {} }; + return { pieces: {}, error: `lifecycle.json cannot be read: ${err?.message ?? err}` }; + } + let raw; + try { + raw = JSON.parse(text); + } catch (err) { + return { pieces: {}, error: `lifecycle.json is not JSON: ${err.message}` }; + } + if (!raw || typeof raw !== "object" || raw.format !== LIFECYCLE_FORMAT || typeof raw.pieces !== "object" || !raw.pieces) { + return { pieces: {}, error: "lifecycle.json is not a umtool-lifecycle file" }; + } + const pieces = {}; + for (const [id, e] of Object.entries(raw.pieces)) { + if (!isPieceId(id) || !e || typeof e !== "object" || !isState(e.state)) continue; + pieces[id] = { state: e.state, at: typeof e.at === "string" ? e.at : "", ...(typeof e.by === "string" ? { by: e.by } : {}) }; + } + return { pieces }; +} + +/** A piece's state in a read: its entry's, else `active`. */ +export function lifecycleOf(read, id) { + return read?.pieces?.[id]?.state ?? "active"; +} + +let chain = Promise.resolve(); + +/** + * Set one piece's state. Answers the entry written. + * + * @param {string} reportsRoot + * @param {string} id a piece id (lib/pieces/ids.mjs) + * @param {string} state active | parked | done + * @param {{ by?: string, now?: Date }} [opts] + */ +export function setLifecycle(reportsRoot, id, state, { by, now } = {}) { + if (!isPieceId(id)) return Promise.reject(new LifecycleError(`not a piece id: ${JSON.stringify(id)}`)); + if (!isState(state)) return Promise.reject(new LifecycleError(`state is ${LIFECYCLE_STATES.join(" | ")}, not ${JSON.stringify(state)}`)); + const run = chain.then(() => write(reportsRoot, id, state, by, now ?? new Date())); + // The next write waits for this one, whether it failed or not. + chain = run.catch(() => {}); + return run; +} + +async function write(reportsRoot, id, state, by, now) { + const file = lifecycleFile(reportsRoot); + const read = await readLifecycle(reportsRoot); + if (read.error) throw new LifecycleError(`${read.error}; fix or remove ${file} first`, 409); + const entry = { state, at: now.toISOString(), ...(by ? { by } : {}) }; + const doc = { + format: LIFECYCLE_FORMAT, + version: LIFECYCLE_VERSION, + pieces: Object.fromEntries(Object.entries({ ...read.pieces, [id]: entry }).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), + }; + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw err; + } + return { id, ...entry }; +} diff --git a/umtool/lib/lifecycle.test.mjs b/umtool/lib/lifecycle.test.mjs @@ -0,0 +1,74 @@ +// A piece's lifecycle, read and written in a temp reports root. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { LIFECYCLE_STATES, lifecycleFile, lifecycleOf, readLifecycle, setLifecycle } from "./lifecycle.mjs"; + +const root = () => mkdtemp(path.join(tmpdir(), "umtool-lifecycle-")); + +test("absent is active, and a read never creates the file", async () => { + const r = await root(); + const read = await readLifecycle(r); + assert.deepEqual(read, { pieces: {} }); + assert.equal(lifecycleOf(read, "a:articles/zeta"), "active"); + assert.deepEqual(await readdir(r), []); +}); + +test("a write round-trips, with when and by whom", async () => { + const r = await root(); + const now = new Date("2026-10-13T12:00:00.000Z"); + const e = await setLifecycle(r, "p:quartering-diet", "done", { by: "operator", now }); + assert.deepEqual(e, { id: "p:quartering-diet", state: "done", at: "2026-10-13T12:00:00.000Z", by: "operator" }); + await setLifecycle(r, "a:articles/zeta", "parked", { now }); + const read = await readLifecycle(r); + assert.equal(lifecycleOf(read, "p:quartering-diet"), "done"); + assert.equal(lifecycleOf(read, "a:articles/zeta"), "parked"); + assert.equal(read.pieces["a:articles/zeta"].by, undefined); + const doc = JSON.parse(await readFile(lifecycleFile(r), "utf8")); + assert.equal(doc.format, "umtool-lifecycle"); + assert.deepEqual(Object.keys(doc.pieces), ["a:articles/zeta", "p:quartering-diet"]); + // Back to active is a write like any other. + await setLifecycle(r, "p:quartering-diet", "active", { now }); + assert.equal(lifecycleOf(await readLifecycle(r), "p:quartering-diet"), "active"); + // No temp file is left beside it. + assert.deepEqual(await readdir(path.dirname(lifecycleFile(r))), ["lifecycle.json"]); +}); + +test("concurrent writes all land", async () => { + const r = await root(); + const ids = Array.from({ length: 12 }, (_, i) => `p:project-${i}`); + await Promise.all(ids.map((id, i) => setLifecycle(r, id, LIFECYCLE_STATES[i % 3]))); + const read = await readLifecycle(r); + for (const [i, id] of ids.entries()) assert.equal(lifecycleOf(read, id), LIFECYCLE_STATES[i % 3]); +}); + +test("junk ids and states are refused, and nothing is written", async () => { + const r = await root(); + await assert.rejects(setLifecycle(r, "articles/zeta", "done"), /not a piece id/); + await assert.rejects(setLifecycle(r, "p:../x", "done"), /not a piece id/); + await assert.rejects(setLifecycle(r, "p:x", "shipped"), /state is active \| parked \| done/); + assert.deepEqual(await readdir(r), []); +}); + +test("an unreadable file is reported, and never overwritten", async () => { + const r = await root(); + await mkdir(path.dirname(lifecycleFile(r)), { recursive: true }); + await writeFile(lifecycleFile(r), "{ not json"); + const read = await readLifecycle(r); + assert.deepEqual(read.pieces, {}); + assert.match(read.error, /not JSON/); + await assert.rejects(setLifecycle(r, "p:x", "done"), (err) => err.status === 409); + assert.equal(await readFile(lifecycleFile(r), "utf8"), "{ not json"); +}); + +test("entries that are not a piece or a state are skipped on read", async () => { + const r = await root(); + await mkdir(path.dirname(lifecycleFile(r)), { recursive: true }); + await writeFile( + lifecycleFile(r), + JSON.stringify({ format: "umtool-lifecycle", version: 1, pieces: { "p:ok": { state: "parked", at: "x" }, junk: { state: "done" }, "p:bad": { state: "gone" } } }), + ); + assert.deepEqual(Object.keys((await readLifecycle(r)).pieces), ["p:ok"]); +}); diff --git a/umtool/lib/lifecycle.ts b/umtool/lib/lifecycle.ts @@ -0,0 +1,35 @@ +import { REPORTS_ROOT } from "./paths"; +import { + LIFECYCLE_STATES as STATES, + LifecycleError, + lifecycleOf as lifecycleOfRead, + readLifecycle as readAt, + setLifecycle as setAt, +} from "./lifecycle.mjs"; + +// The app's view of lib/lifecycle.mjs, typed and bound to REPORTS_ROOT. The +// logic, the file format and the rules are there (plain ESM, unit-tested). + +export type LifecycleState = "active" | "parked" | "done"; +export type LifecycleEntry = { state: LifecycleState; at: string; by?: string }; +export type LifecycleRead = { pieces: Record<string, LifecycleEntry>; error?: string }; + +export const LIFECYCLE_STATES = STATES as LifecycleState[]; +export { LifecycleError }; + +export const isLifecycleState = (s: unknown): s is LifecycleState => (LIFECYCLE_STATES as unknown[]).includes(s); + +export async function readLifecycle(): Promise<LifecycleRead> { + return (await readAt(REPORTS_ROOT)) as LifecycleRead; +} + +export function lifecycleOf(read: LifecycleRead, id: string): LifecycleState { + return lifecycleOfRead(read, id) as LifecycleState; +} + +export async function setLifecycle(id: string, state: LifecycleState, by?: string): Promise<LifecycleEntry & { id: string }> { + return (await setAt(REPORTS_ROOT, id, state, { by })) as LifecycleEntry & { id: string }; +} + +/** Parked and done pieces are out of the way: their decisions are `hidden`. */ +export const isQuiet = (state: LifecycleState): boolean => state !== "active"; diff --git a/umtool/lib/pieces.ts b/umtool/lib/pieces.ts @@ -0,0 +1,294 @@ +import { listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; +import { ARTICLES_KEY, REPORTS_ROOT } from "./paths"; +import { articleHref } from "./articles/href"; +import { listSiteRows, readStoreRow, sitesPaths, type ArticleRow } from "./articles/sites"; +import { iterationProjects, linkedProjects, linksCacheEpoch, videoProjects } from "./articles/links.mjs"; +import { listProjects } from "./projects"; +import type { ProjectSummary } from "./project-types"; +import { listBatches } from "./report/deliver.mjs"; +import { articleOfDecisionProject, articlePieceId, projectPieceId } from "./pieces/ids.mjs"; +import { lifecycleOf, readLifecycle, type LifecycleRead, type LifecycleState } from "./lifecycle"; +import type { Decision } from "./decisions"; + +export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId } from "./pieces/ids.mjs"; + +// --------------------------------------------------------------------------- +// PIECES (plans/umtool-redesign.md): the unit the operator works on. +// +// an ARTICLE piece `a:<site>/<report>` -- a site's report, or one of the +// article store's (`articles/<id>`, published, draft or +// still in the making) -- plus every video project linked +// to it (lib/articles/links.mjs: its iterations, then a +// manifest that names it, then a unique slug) +// a PROJECT piece `p:<id>` -- a project under REPORTS_ROOT linked to no +// article: a song, a hand-made report video, a sweep +// +// A project linked to two articles belongs to the first that claims it, by +// strength (iteration, then manifest, then slug) and then in list order -- +// private sites first, as /sites lists them. +// +// SERVER ONLY. The article side re-reads every report.json (lib/articles/ +// sites.ts), so the graph is memoised for MEMO_MS -- and dropped at once by +// anything that clears the links cache (a project or an article deleted), the +// way clearLinksCache already drops the links. The lifecycle is NOT memoised: +// it is one small file, and a park has to show on the next read. +// --------------------------------------------------------------------------- + +export type PieceKind = "article" | "project"; + +export type PieceProject = { + id: string; + title: string; + via: "iteration" | "manifest" | "slug"; + /** The one the article's Cut opens (current.video's, else the first linked). */ + cut: boolean; + /** The project's state (draft … built, shipped, stale), or null when the walk did not summarise it. */ + state: string | null; + href: string; +}; + +export type Piece = { + id: string; + kind: PieceKind; + title: string; + /** An article's site (`articles` for the store), else null. */ + site: string | null; + report: string | null; + /** A project piece's project id, else null. */ + project: string | null; + href: string; + /** An article's: published, draft, or in the making (iterations, no report.json). */ + status: "published" | "draft" | "in the making" | null; + /** + * Where it is. An article: research (in the making) → article (no video) → + * video → deliver (looks done). A project: its own state (draft, windows, + * fetched, built, shipped, stale). + */ + stage: string; + projects: PieceProject[]; + /** Slug matches nobody has chosen between (link-ambiguous). */ + possible: { id: string; title: string }[]; + /** Iterations whose project is outside REPORTS_ROOT: not reachable here. */ + unreachable: { n: number; dir: string }[]; + /** Why it looks done, when it does. A suggestion: it never sets the lifecycle. */ + looksDone: string[]; + newestMs: number; +}; + +export type PieceWithLifecycle = Piece & { lifecycle: LifecycleState; lifecycleAt: string | null; lifecycleBy: string | null }; + +export type PieceGraph = { + pieces: Piece[]; + byId: Map<string, Piece>; + /** Project id → the piece it belongs to. */ + pieceOfProject: Map<string, string>; + /** A project's basename → its id, when the name is unique (the song routes' alias). */ + projectByName: Map<string, string>; +}; + +const MEMO_MS = 15_000; +let memo: { at: number; epoch: number; value: Promise<PieceGraph> } | null = null; + +/** Drop the memo (a test, or a write that changed what an article links). */ +export function clearPiecesCache(): void { + memo = null; +} + +export function readPieceGraph(): Promise<PieceGraph> { + const epoch = linksCacheEpoch(); + if (memo && memo.epoch === epoch && Date.now() - memo.at < MEMO_MS) return memo.value; + const value = buildGraph(); + const entry = { at: Date.now(), epoch, value }; + memo = entry; + value.catch(() => { + if (memo === entry) memo = null; + }); + return value; +} + +type LinkRow = { id: string; title: string; via?: "iteration" | "manifest" | "slug" }; +type ArticleIn = { + site: string; + id: string; + title: string; + status: Piece["status"]; + hasVideo: boolean; + mtimeMs: number; + linked: LinkRow[]; + possible: { id: string; title: string }[]; + cut: string | null; + unreachable: { n: number; dir: string }[]; +}; + +const STRENGTH = { iteration: 0, manifest: 1, slug: 2 } as const; + +function fromRow(a: ArticleRow): ArticleIn { + return { + site: a.site, + id: a.id, + title: a.title, + status: a.status, + hasVideo: a.hasVideo, + mtimeMs: a.mtimeMs ?? 0, + linked: a.projects.linked, + possible: a.projects.possible.map((p) => ({ id: p.id, title: p.title })), + cut: a.projects.cut ?? null, + unreachable: a.projects.unreachable ?? [], + }; +} + +async function pendingArticles(): Promise<ArticleIn[]> { + const ids = await listPendingArticles(sitesPaths()).catch(() => [] as string[]); + const projects = await videoProjects(REPORTS_ROOT); + return Promise.all( + ids.map(async (id) => { + const links = await linkedProjects(ARTICLES_KEY, id, { projects }); + return { + site: ARTICLES_KEY, + id, + title: id, + status: "in the making" as const, + hasVideo: false, + mtimeMs: 0, + linked: links.linked as LinkRow[], + possible: (links.possible as LinkRow[]).map((p) => ({ id: p.id, title: p.title })), + cut: links.cut ?? null, + unreachable: links.unreachable ?? [], + }; + }), + ); +} + +/** Why a project looks finished, or null. Kind-blind: it reads the shared state vocabulary. */ +async function projectLooksDone(p: ProjectSummary): Promise<string | null> { + // A song's derived `shipped` (every cut present, lib/projects/song.mjs). + if (p.state === "shipped") return `${p.id}: every cut shipped`; + // A final video, current with its manifest, AND a share batch made from it. + if (p.state === "built") { + const batches = await listBatches(p.dir).catch(() => [] as { name: string }[]); + if (batches.length) return `${p.id}: final video and ${batches.map((b: { name: string }) => b.name).join(", ")}`; + } + return null; +} + +async function buildGraph(): Promise<PieceGraph> { + // The article side must never take the decisions down with it: a site whose + // site.json does not read is an article list without that site, not a 500. + const [sites, store, pending, summaries, its] = await Promise.all([ + listSiteRows().catch(() => []), + readStoreRow().catch(() => ({ articles: [] as ArticleRow[] })), + pendingArticles().catch(() => [] as ArticleIn[]), + listProjects(), + iterationProjects().catch(() => new Map<string, { current: boolean }[]>()), + ]); + const articles: ArticleIn[] = [ + ...sites.flatMap((s) => s.articles.map(fromRow)), + ...store.articles.map(fromRow), + ...pending, + ]; + const summaryOf = new Map(summaries.map((p) => [p.id, p])); + + // Who owns each linked project: the strongest link, then list order. + const pieceOfProject = new Map<string, string>(); + const claims = articles.flatMap((a, order) => + a.linked.map((p) => ({ project: p.id, piece: articlePieceId(a.site, a.id), strength: STRENGTH[p.via ?? "slug"], order })), + ); + claims.sort((x, y) => x.strength - y.strength || x.order - y.order); + for (const c of claims) if (!pieceOfProject.has(c.project)) pieceOfProject.set(c.project, c.piece); + + const doneCache = new Map<string, Promise<string | null>>(); + const looksDoneOf = (id: string) => { + const s = summaryOf.get(id); + if (!s) return Promise.resolve(null); + let hit = doneCache.get(id); + if (!hit) doneCache.set(id, (hit = projectLooksDone(s))); + return hit; + }; + + const pieces: Piece[] = []; + for (const a of articles) { + const id = articlePieceId(a.site, a.id); + const projects: PieceProject[] = a.linked.map((p) => ({ + id: p.id, + title: p.title, + via: p.via ?? "slug", + cut: p.id === a.cut, + state: summaryOf.get(p.id)?.state ?? null, + href: `/browse/${p.id}`, + })); + const looksDone: string[] = []; + const currentVideo = a.site === ARTICLES_KEY && (its.get(a.id) ?? []).some((x: { current: boolean }) => x.current); + if (a.status === "published" && (a.hasVideo || currentVideo)) looksDone.push("published with its video"); + for (const p of projects) { + if (pieceOfProject.get(p.id) !== id) continue; + const why = await looksDoneOf(p.id); + if (why) looksDone.push(why); + } + const newestMs = Math.max(a.mtimeMs, ...projects.map((p) => summaryOf.get(p.id)?.newestMtimeMs ?? 0)); + pieces.push({ + id, + kind: "article", + title: a.title, + site: a.site, + report: a.id, + project: null, + href: articleHref({ site: a.site, id: a.id }), + status: a.status, + stage: a.status === "in the making" ? "research" : !projects.length ? "article" : looksDone.length ? "deliver" : "video", + projects, + possible: a.possible, + unreachable: a.unreachable, + looksDone, + newestMs, + }); + } + + for (const p of summaries) { + if (pieceOfProject.has(p.id)) continue; + const why = await looksDoneOf(p.id); + pieces.push({ + id: projectPieceId(p.id), + kind: "project", + title: p.title, + site: null, + report: null, + project: p.id, + href: `/browse/${p.id}`, + status: null, + stage: p.state, + projects: [], + possible: [], + unreachable: [], + looksDone: why ? [why] : [], + newestMs: p.newestMtimeMs, + }); + pieceOfProject.set(p.id, projectPieceId(p.id)); + } + + const names = new Map<string, string[]>(); + for (const p of summaries) names.set(p.name, [...(names.get(p.name) ?? []), p.id]); + const projectByName = new Map([...names].filter(([, ids]) => ids.length === 1).map(([n, ids]) => [n, ids[0]])); + + pieces.sort((a, b) => b.newestMs - a.newestMs || a.id.localeCompare(b.id)); + return { pieces, byId: new Map(pieces.map((p) => [p.id, p])), pieceOfProject, projectByName }; +} + +/** The piece a decision row is about, or null when nothing on disk owns it. */ +export function pieceOfDecision(d: Decision, graph: PieceGraph): string | null { + if (d.piece) return d.piece; + if (d.projectKind === "article") { + const a = articleOfDecisionProject(d.project); + return a ? articlePieceId(a.site, a.report) : null; + } + const id = graph.pieceOfProject.has(d.project) ? d.project : graph.projectByName.get(d.project); + return id ? (graph.pieceOfProject.get(id) ?? null) : null; +} + +/** Every piece, with its lifecycle (read now, never memoised). */ +export async function listPieces(read?: LifecycleRead): Promise<PieceWithLifecycle[]> { + const [graph, life] = await Promise.all([readPieceGraph(), read ? Promise.resolve(read) : readLifecycle()]); + return graph.pieces.map((p) => { + const e = life.pieces[p.id]; + return { ...p, lifecycle: lifecycleOf(life, p.id), lifecycleAt: e?.at ?? null, lifecycleBy: e?.by ?? null }; + }); +} diff --git a/umtool/lib/pieces/ids.mjs b/umtool/lib/pieces/ids.mjs @@ -0,0 +1,94 @@ +// A PIECE's id (plans/umtool-redesign.md, "Data and engine rules"). +// +// A piece is the unit the operator works on: an article plus the video +// project(s) made from it, or a project that belongs to no article. Its id is +// NAMESPACED, because the bare spellings collide: `resolveTarget` +// (lib/annotations/targets.mjs) reads a two-segment `x/y` as an article when +// such a report exists and as a project otherwise -- and a project id is a +// path, so `articles/zeta` can be either. +// +// a:<site>/<report> an article; `site` may be `articles` (the store's) +// p:<projectId> a project under REPORTS_ROOT, by its path id +// c:<case> a research case (reserved: research boards, R2) +// +// Pure, no imports with side effects: a client component may parse an id. + +/** A site or report id: lib/paths.mjs SEGMENT_RE (a test holds them equal). */ +export const PIECE_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; + +/** One segment of a project id: lib/projects/walk.mjs isSegment (a test holds them equal). */ +const PROJECT_SEGMENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const projectSegment = (v) => PROJECT_SEGMENT_RE.test(v) && !v.includes(".."); + +export const PIECE_KINDS = ["article", "project", "case"]; +const PREFIX = { article: "a", project: "p", case: "c" }; + +/** + * Parse a piece id, or null when it is not one. Never guesses: a bare + * `site/report` or project id is null. + * + * @param {unknown} id + * @returns {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string } | null} + */ +export function parsePieceId(id) { + if (typeof id !== "string" || id.length > 512) return null; + const m = /^([apc]):(.+)$/.exec(id); + if (!m) return null; + const [, ns, rest] = m; + if (ns === "a") { + const parts = rest.split("/"); + if (parts.length !== 2 || !parts.every((s) => PIECE_SEGMENT_RE.test(s))) return null; + return { kind: "article", site: parts[0], report: parts[1] }; + } + if (ns === "p") { + const parts = rest.split("/"); + if (!parts.length || !parts.every(projectSegment)) return null; + return { kind: "project", project: rest }; + } + if (!PIECE_SEGMENT_RE.test(rest)) return null; + return { kind: "case", case: rest }; +} + +/** True when `id` is a piece id. */ +export const isPieceId = (id) => parsePieceId(id) !== null; + +/** + * The id for a parsed piece. Throws on parts that would not parse back: an id + * that cannot round-trip is a bug at the caller, not a value to pass along. + * + * @param {{ kind: "article", site: string, report: string } | { kind: "project", project: string } | { kind: "case", case: string }} p + */ +export function formatPieceId(p) { + const id = + p?.kind === "article" + ? `${PREFIX.article}:${p.site}/${p.report}` + : p?.kind === "project" + ? `${PREFIX.project}:${p.project}` + : p?.kind === "case" + ? `${PREFIX.case}:${p.case}` + : null; + if (id === null || !isPieceId(id)) throw new Error(`not a piece: ${JSON.stringify(p)}`); + return id; +} + +/** `a:<site>/<report>`. */ +export const articlePieceId = (site, report) => formatPieceId({ kind: "article", site, report }); + +/** `p:<projectId>`. */ +export const projectPieceId = (project) => formatPieceId({ kind: "project", project }); + +/** `c:<case>`. */ +export const casePieceId = (slug) => formatPieceId({ kind: "case", case: slug }); + +/** + * An article decision's `project` (`sites/<site>/<report>`, lib/decisions.ts + * noteDecisions) back to its article, or null. Only meaningful for a row whose + * `projectKind` is "article": a project may itself live under a `sites/` folder. + * + * @param {string} project + */ +export function articleOfDecisionProject(project) { + const m = /^sites\/([^/]+)\/([^/]+)$/.exec(String(project ?? "")); + if (!m || !PIECE_SEGMENT_RE.test(m[1]) || !PIECE_SEGMENT_RE.test(m[2])) return null; + return { site: m[1], report: m[2] }; +} diff --git a/umtool/lib/pieces/ids.test.mjs b/umtool/lib/pieces/ids.test.mjs @@ -0,0 +1,67 @@ +// Piece ids: namespaced, round-tripping, never ambiguous. +import assert from "node:assert/strict"; +import test from "node:test"; +import { SEGMENT_RE } from "../paths.mjs"; +import { isSegment } from "../projects/walk.mjs"; +import { + PIECE_SEGMENT_RE, + articleOfDecisionProject, + articlePieceId, + casePieceId, + formatPieceId, + isPieceId, + parsePieceId, + projectPieceId, +} from "./ids.mjs"; + +test("each namespace parses and formats back", () => { + for (const id of ["a:articles/zeta", "a:priv/polemic-alpha", "p:ferret-rescue", "p:quartering-uh-song/videos/yoshi", "p:gen-projects/zeta/i1", "c:vote-rigging"]) { + const parsed = parsePieceId(id); + assert.ok(parsed, id); + assert.equal(formatPieceId(parsed), id); + } + assert.deepEqual(parsePieceId("a:articles/zeta"), { kind: "article", site: "articles", report: "zeta" }); + assert.deepEqual(parsePieceId("p:quartering-uh-song/videos/yoshi"), { kind: "project", project: "quartering-uh-song/videos/yoshi" }); + assert.deepEqual(parsePieceId("c:vote"), { kind: "case", case: "vote" }); + assert.equal(articlePieceId("articles", "zeta"), "a:articles/zeta"); + assert.equal(projectPieceId("articles/zeta"), "p:articles/zeta"); + assert.equal(casePieceId("vote"), "c:vote"); +}); + +test("a two-segment id is never ambiguous: the namespace says which", () => { + // resolveTarget reads `articles/zeta` as an article when the report exists + // and as a project otherwise. A piece id carries the answer. + assert.equal(parsePieceId("articles/zeta"), null); + assert.equal(parsePieceId("a:articles/zeta").kind, "article"); + assert.equal(parsePieceId("p:articles/zeta").kind, "project"); + assert.notEqual(articlePieceId("articles", "zeta"), projectPieceId("articles/zeta")); +}); + +test("junk is refused", () => { + for (const bad of [ + "", "a:", "p:", "c:", "x:y", "A:articles/zeta", "a:articles", "a:articles/zeta/extra", "a:Articles/zeta", + "a:articles/../x", "p:../x", "p:a//b", "p:/abs", "p:.hidden", "p:a/..b", "p:a b", "c:Up", "c:a/b", + "a:articles/zeta\n", " p:x", null, undefined, 42, {}, `p:${"a/".repeat(300)}a`, + ]) { + assert.equal(parsePieceId(bad), null, JSON.stringify(bad)); + assert.equal(isPieceId(bad), false); + } + assert.throws(() => formatPieceId({ kind: "article", site: "x", report: "a/b" })); + assert.throws(() => projectPieceId("../etc")); + assert.throws(() => formatPieceId({ kind: "nope" })); +}); + +test("the segment rules are the ones the rest of umtool uses", () => { + assert.equal(PIECE_SEGMENT_RE.source, SEGMENT_RE.source); + for (const seg of ["ferret-rescue", "i1", "Mixed_Case.v2", ".hidden", "a..b", "a b", "-x", "x-"]) { + assert.equal(isPieceId(`p:${seg}`), isSegment(seg), seg); + } +}); + +test("an article decision's project names its article", () => { + assert.deepEqual(articleOfDecisionProject("sites/articles/zeta"), { site: "articles", report: "zeta" }); + assert.deepEqual(articleOfDecisionProject("sites/priv/polemic-alpha"), { site: "priv", report: "polemic-alpha" }); + assert.equal(articleOfDecisionProject("ferret-rescue"), null); + assert.equal(articleOfDecisionProject("sites/priv"), null); + assert.equal(articleOfDecisionProject("sites/priv/a/b"), null); +}); diff --git a/umtool/lib/projects.ts b/umtool/lib/projects.ts @@ -57,10 +57,24 @@ export const ALL_DECISION_KINDS: string[] = [ // not changed and is thrown away the moment it has. That is the same rule the // export build's incremental signatures follow, and it is the reason no index // is needed yet at twelve projects. +// +// The caches live on globalThis, not in module scope: Next bundles each route +// handler and page separately, so a module-level cache is one copy PER BUNDLE, +// and invalidateProjects() called from an API route never reached the page that +// renders next -- a project scaffolded a moment ago 404'd for up to a second. // --------------------------------------------------------------------------- -let walkCache: { at: number; refs: ProjectRef[] } | null = null; -const summaryCache = new Map<string, { sig: string; value: ProjectSummary }>(); -const decisionCache = new Map<string, { sig: string; value: Decision[] }>(); +type ProjectCaches = { + walk: { at: number; refs: ProjectRef[] } | null; + summary: Map<string, { sig: string; value: ProjectSummary }>; + decision: Map<string, { sig: string; value: Decision[] }>; +}; +const CACHES = ((globalThis as { __umtoolProjectCaches?: ProjectCaches }).__umtoolProjectCaches ??= { + walk: null, + summary: new Map(), + decision: new Map(), +}); +const summaryCache = CACHES.summary; +const decisionCache = CACHES.decision; // --------------------------------------------------------------------------- // The persistent index, opened once and held. @@ -84,15 +98,16 @@ export const indexHealth = () => ({ ...lastIndexHits }); /** Drop every cache. The CLI's `scan` and the e2e suite want this. */ export function invalidateProjects(): void { - walkCache = null; + CACHES.walk = null; summaryCache.clear(); decisionCache.clear(); } export async function projectRefs(): Promise<ProjectRef[]> { - if (walkCache && Date.now() - walkCache.at < 1000) return walkCache.refs; + const hit = CACHES.walk; + if (hit && Date.now() - hit.at < 1000) return hit.refs; const refs = (await walkProjects(REPORTS_ROOT)) as ProjectRef[]; - walkCache = { at: Date.now(), refs }; + CACHES.walk = { at: Date.now(), refs }; return refs; }