From 6b1dfec45e4928dfa7e2ce7cdf249bda667242f1 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Fri, 27 Nov 2026 12:30:56 +0100 Subject: [PATCH] docs(37): plan Phase 37 Media Library (album) across 5 waves --- .planning/ROADMAP.md | 56 +++++ .../37-media-library-album/37-01-PLAN.md | 202 +++++++++++++++++ .../37-media-library-album/37-02-PLAN.md | 206 ++++++++++++++++++ .../37-media-library-album/37-03-PLAN.md | 134 ++++++++++++ .../37-media-library-album/37-04-PLAN.md | 124 +++++++++++ .../37-media-library-album/37-05-PLAN.md | 136 ++++++++++++ .../37-media-library-album/37-RESEARCH.md | 190 ++++++++++++++++ 7 files changed, 1048 insertions(+) create mode 100644 .planning/phases/37-media-library-album/37-01-PLAN.md create mode 100644 .planning/phases/37-media-library-album/37-02-PLAN.md create mode 100644 .planning/phases/37-media-library-album/37-03-PLAN.md create mode 100644 .planning/phases/37-media-library-album/37-04-PLAN.md create mode 100644 .planning/phases/37-media-library-album/37-05-PLAN.md create mode 100644 .planning/phases/37-media-library-album/37-RESEARCH.md diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md index 06a80678..509c3dde 100644 --- a/.planning/ROADMAP.md +++ b/.planning/ROADMAP.md @@ -49,6 +49,8 @@ Decimal phases appear between their surrounding integers in numeric order. - [ ] **Phase 31: Chat polish against WavePath clients** - `tide` additions, `sm-wavepath-app`, the full PHP recording of WavePath's community routes and the foundation slice green - [ ] **Phase 31.1: WavePath messaging parity** (INSERTED) - Group chat, channels, DMs, threads, commands and attachments replay green - [ ] **Phase 31.2: WavePath satellites parity and close-out** (INSERTED) - Presence, push, webhooks, bot, video, guests, forums and notes; zero pending +- [ ] **Phase 37: Media Library (`album`)** - Plugin-agnostic DB-indexed media library with friendly SEO slugs, WebP `srcset` variants, admin Media screen + `mediafinder` / shared picker, and MCP uploads (signed URLs + base64) +- [ ] **Phase 38: Extensible Journal embed providers** - Pluggable `data-embed` registry in `sm-journal-plugin` and lazy `IntersectionObserver` hydration registry in `vue-journal-layer` (CSP-safe, static fallback preserved) ## Phase Details @@ -1919,6 +1921,8 @@ Phases execute in numeric order: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → | 34. Plugin marketplace | 6/6 | In Progress| | | 35. Mail templates and layouts editor | 9/9 | Complete | 2026-11-14 | | 36. Granular MCP OAuth & API token scope picker | 4/4 | Complete | 2026-11-24 | +| 37. Media Library (`album`) | 0/TBD | Not started | - | +| 38. Extensible Journal embed providers | 0/TBD | Not started | - | ## Backlog @@ -2027,3 +2031,55 @@ Plans: **Wave 4** *(blocked on Wave 3 completion)* - [x] 36-04-PLAN.md — Comprehensive Go & Vitest unit/component suites (closing all 7 UI-SPEC backstops), full release gates, human release-tag checkpoint, and `sm-grzybyfunkcjonalne-app` local E2E proof + +### Phase 37: Media Library (`album`) + +**Goal:** Ship a core, plugin-agnostic Media Library (`modules/album`) backed by `lagoon/attach` and Postgres metadata with virtual folders, immutable blob keys and friendly SEO slugs, automatic responsive WebP `srcset` variants, a first-class admin Media screen + `type: mediafinder` field + shared Media Picker modal, and MCP media tools (single-use signed upload URLs for CLI agents + size-capped base64 upload for remote web connectors). Unify `cabana` Mail Images and `sm-journal-plugin` media uploads onto `album` with backward-compatible aliases. Decision note: `.planning/notes/2026-11-26-media-library-album-module.md`. +**Mode:** mvp +**Depends on:** Phase 35 (Mail templates and layouts editor), Phase 36 (Granular MCP OAuth & API token scope picker) +**Repos:** `summercms.go`, `sm-journal-plugin` (unification/alias + inline `srcset` support), `vue-journal-layer` (inline `srcset` rendering), consuming apps as adopted +**Requirements**: TBD +**Success Criteria** (what must be TRUE): + + 1. `modules/album` stores virtual folders and media items (`alt`, `title`, `width`, `height`, `sha256`, `variants`) in Postgres over `lagoon/attach` (`blob.Bucket`), serving public assets at immutable-ID + friendly-slug URLs with `Cache-Control: immutable`, safe `Content-Disposition`, and `nosniff`, so moving or renaming items never breaks published URLs. + 2. Image uploads automatically produce responsive WebP width variants (`srcset` metadata exposed in API and MCP responses), while interactive JS/HTML bundles and SVG remain disallowed in v1. + 3. `cabana` / `boardwalk` provide a permission-gated **Media** admin screen (folders, search, upload, metadata edit, delete), a reusable `type: mediafinder` form field, and a shared Media Picker modal used by Mail Editor and Blog Editor; existing Mail Images and Journal upload endpoints remain backward-compatible. + 4. `pier` exposes granularly scoped (`media` / `media:read`) MCP tools supporting both **short-lived single-use signed upload URLs** (`media_prepare_upload` → HTTP binary upload) and **size-capped direct base64 upload** (`media_upload`), alongside `media_list`, `media_get`, `media_update`, `media_delete`, and `media_create_folder`. + 5. OpenAPI schema, embedded `boardwalk/dist`, module README + `docs/`, and Go + Vitest unit tests (last plan) pass green. + +**Plans:** 5 plans + +Plans: +**Wave 1** +- [ ] 37-01-PLAN.md — Core `modules/album` package (Postgres migrations in `lagoon`, upload + synchronous WebP `480w`/`960w`/`1600w` variants + `sha256`, single-use `summer_media_upload_tokens`, after-commit delete seam, zero-DB-hit `/media/...` & `/media/upload/{token}` in `surf`, Mail Images backfill, README & `docs/services/media-library.md`) + +**Wave 2** *(blocked on Wave 1 completion)* +- [ ] 37-02-PLAN.md — `cabana` admin Media REST API, `media.view_media`/`media.manage_media` permissions, `media`/`media:read` token scopes, `type: mediafinder` YAML schema, backward-compatible `/mail/images` unification, 7 `media_*` MCP tools in `pier` (+ 8 MiB body cap), EN/PL phrasebooks, OpenAPI & TS regen + +**Wave 3** *(blocked on Wave 2 completion)* +- [ ] 37-03-PLAN.md — Admin Vue 3 SPA (`MediaView.vue` with folder tree, grid/list, search, upload, metadata edit, delete warning; shared `MediaPickerModal.vue` reused by `MailImagePicker.vue`; `MediaFinderField.vue`; rebuilt `modules/boardwalk/dist`) + +**Wave 4** *(blocked on Wave 3 completion)* +- [ ] 37-04-PLAN.md — Sibling unification (`sm-journal-plugin` `/_journal/api/v1/media/upload` over `album`, Blog Editor media picker hook, single-query batched inline `srcset`/`sizes` enrichment; `vue-journal-layer` sanitizer allow-list for inline `srcset`/`sizes`/`width`/`height`) + +**Wave 5** *(blocked on Waves 1–4 completion)* +- [ ] 37-05-PLAN.md — Unit tests last & verification gates (Go unit + Postgres integration tests for `album`/`cabana`/`pier`/`surf`, Vitest suites for Media screen/picker/`mediafinder`, `scripts/check-phase37.sh` with local read-only consumer proofs, and `37-VALIDATION.md`) + +### Phase 38: Extensible Journal embed providers + +**Goal:** Replace hardcoded `youtube`-only embed handling in `sm-journal-plugin` and `vue-journal-layer` with a generic, app-extensible embed provider registry so any SummerCMS site can register custom CSP-safe embeds (such as interactive visualizations, calculators, or additional video/audio providers) with SSR static fallback (`` + `
`) and lazy `IntersectionObserver` hydration. Decision note: `.planning/notes/2026-11-26-journal-extensible-embeds.md`. +**Mode:** mvp +**Depends on:** None (independent short phase; pairs well with Phase 37 `album` for fallback images) +**Repos:** `sm-journal-plugin`, `vue-journal-layer` +**Requirements**: TBD +**Success Criteria** (what must be TRUE): + + 1. `sm-journal-plugin` (`classes/format_html.go`) validates `
` against a configurable/registered embed provider map (`youtube` registered by default) and preserves static fallback `` and `
` inside the figure without allowing arbitrary `script`/`style`/`iframe`/`svg`. + 2. The Blog Editor (`assets/src/blogeditor/embed.ts`) reads registered embed providers dynamically rather than hardcoding only `youtube`, preserving existing YouTube authoring unchanged. + 3. `vue-journal-layer` exposes an app-extensible embed provider registry that renders the SSR static fallback unchanged, lazy-hydrates registered providers on viewport entry (`IntersectionObserver`) with `script-src 'self'` CSP compliance, reserves height (no CLS), and exposes `prefers-reduced-motion`. + 4. Unit tests (Go + Vitest, last plan) and README/docs updates pass green. + +**Plans:** 0 plans + +Plans: +- [ ] TBD (run `/msd-discuss-phase 38` then `/msd-plan-phase 38` to break down) diff --git a/.planning/phases/37-media-library-album/37-01-PLAN.md b/.planning/phases/37-media-library-album/37-01-PLAN.md new file mode 100644 index 00000000..2ab1eaeb --- /dev/null +++ b/.planning/phases/37-media-library-album/37-01-PLAN.md @@ -0,0 +1,202 @@ +--- +phase: 37-media-library-album +plan: 01 +type: execute +wave: 1 +depends_on: [] +files_modified: + - modules/album/album.go + - modules/album/migrations.go + - modules/album/models.go + - modules/album/service.go + - modules/album/variants.go + - modules/album/tokens.go + - modules/album/http.go + - modules/album/backfill.go + - modules/album/example_test.go + - modules/album/album_smoke_test.go + - modules/album/README.md + - modules/lagoon/migrations.go + - modules/surf/media.go + - modules/surf/router.go + - README.md + - docs/services/media-library.md + - docs/README.md +autonomous: true +requirements: [] +user_setup: [] +must_haves: + truths: + - "`modules/album` is a core framework module (`git.golem15.com/golem15/summercms/modules/album`) with zero import of `modules/lagoon` (matching `postcard`'s import graph) so `modules/lagoon/migrations.go` registers `{\"summercms.album\", \"media\", album.Migrations}` cleanly without circular imports (D-01)." + - "`album.Migrations` creates `summer_media_folders`, `summer_media_items`, and `summer_media_upload_tokens` with full indexes, FK constraints, unique `(COALESCE(parent_id, 0), slug)`, unique `short_id`, unique `blob_key`, indexed `sha256`, JSONB `variants`, and nullable unique `legacy_file_id` (D-02, D-08, D-09, D-13)." + - "Uploads store originals directly in `blob.Bucket` at `media//.` using `attach.DefaultImageExtensions`, `attach.DefaultFileExtensions`, `attach.IsAllowedImage` (including `attach.MaxImagePixels` decompression-bomb guard), `attach.DiskExtension`, and `attach.UploadWriterOptions`, explicitly rejecting SVG, HTML, and JS uploads (D-03, D-06)." + - "Raster image uploads synchronously generate WebP width variants (`480w`, `960w`, `1600w`, never upscaling past original width) via `modules/lagoon/attach/webp`, store them beside the original at `media//-w.webp`, persist `width`, `height`, `sha256`, and `variants` JSONB, and clean up all written blobs on any error (D-07, D-08)." + - "`PrepareUpload` stores only the SHA-256 hash of a high-entropy single-use token in `summer_media_upload_tokens` (5 min default TTL), and `ConsumeUploadToken` atomically marks `used_at = NOW()` (`WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW()`) before writing bytes so replay is impossible (D-09, D-10)." + - "Deleting an item exposes `DeleteItemInTx(ctx, tx, id) (blobKeys []string, err error)` and `DeleteBlobs(ctx, keys)` so callers wrap deletes in `lagoon.Transaction` + `lagoon.AfterCommit` and rolled-back transactions never delete live blobs (D-12)." + - "`surf.BuildRouter` mounts zero-DB-hit `GET /media/{short_id}/{file}` (strict segment validation, `Cache-Control: public, max-age=31536000, immutable`, `X-Content-Type-Options: nosniff`, sandboxing CSP, stored `Content-Disposition` / `attachment` for non-inline types) and raw `PUT`/`POST /media/upload/{token}` with `MaxBytesReader` and inline throttle (D-06, D-09, D-10)." + - "`album.BackfillMailImages(ctx, db, bucket)` idempotently indexes existing `system_files` rows with `attachment_type = 'System\\Models\\MailImageLibrary' AND field = 'images'` into folder `mail` via `legacy_file_id` without altering or breaking existing `/uploads/...` URLs (D-13)." + - "`modules/album/README.md` (with `**Name:**` mnemonic and standard structure), root `README.md` table row, and `docs/services/media-library.md` (with `src=` compiled examples) pass `summer docs:build --check` and `go test ./cmd/summer -run TestDocsTree` (D-01)." + artifacts: + - path: "modules/album/migrations.go" + provides: "Gormigrate migrations for `summer_media_folders`, `summer_media_items`, and `summer_media_upload_tokens`" + contains: "summer_media_items" + - path: "modules/album/service.go" + provides: "Core `Service` for folders, upload, list/search/filter, metadata update, `DeleteItemInTx`, and URL resolution" + exports: ["Service", "NewService", "UploadInput", "Item", "Folder", "Variant"] + - path: "modules/album/variants.go" + provides: "Synchronous WebP `480w`/`960w`/`1600w` variant generation using `lagoon/attach/webp` and `x/image/draw`" + contains: "webp.Encode" + - path: "modules/album/tokens.go" + provides: "Single-use DB-backed upload token creation and atomic consumption" + contains: "summer_media_upload_tokens" + - path: "modules/album/http.go" + provides: "Zero-DB-hit `/media/{short_id}/{file}` `StaticHandler` and `/media/upload/{token}` `SignedUploadHandler`" + exports: ["StaticHandler", "SignedUploadHandler"] + - path: "modules/surf/media.go" + provides: "`mountMedia` wiring `/media/{short_id}/{file}` and `/media/upload/{token}` into `surf.BuildRouter`" + contains: "mountMedia" + - path: "modules/album/README.md" + provides: "Standard module README with mnemonic and tested examples" + contains: "**Name:**" + key_links: + - from: "modules/lagoon/migrations.go" + to: "modules/album/migrations.go" + via: "`migrationSets` registers `{\"summercms.album\", \"media\", album.Migrations}`" + pattern: "album\\.Migrations" + - from: "modules/surf/router.go" + to: "modules/surf/media.go" + via: "`BuildRouter` calls `mountMedia(r, app)` right after `mountUploads(r, app)`" + pattern: "mountMedia\\(r, app\\)" + - from: "modules/album/service.go" + to: "modules/lagoon/attach" + via: "Reuses `attach.DefaultImageExtensions`, `attach.DefaultFileExtensions`, `attach.IsAllowedImage`, `attach.DiskExtension`, `attach.UploadWriterOptions`" + pattern: "attach\\.IsAllowedImage" + prohibitions: + - "Do NOT import `modules/lagoon` inside `modules/album` (would create a cycle with `modules/lagoon/migrations.go`)." + - "Do NOT allow SVG, HTML, or JS uploads in v1 (D-03)." + - "Do NOT perform automatic deduplication on `sha256` — always create a new row and independent blob key (D-08)." + - "Do NOT hit Postgres on `GET /media/{short_id}/{file}` — public delivery must be zero-DB-hit (D-06)." + - "Do NOT name any consuming application in framework code, READMEs, or `docs/` (`CLAUDE.md`)." +--- + + +**As a** SummerCMS framework developer and site operator, **I want** a core, plugin-agnostic `modules/album` package with Postgres metadata, immutable SEO-slug blob keys, synchronous WebP `srcset` variants, single-use signed upload tokens, and zero-DB-hit `/media/...` serving, **so that** admin screens, Mail Images, Journal, and MCP tools share one reliable media foundation. + +**Scope (Plan 37-01, Wave 1 — Tracer):** Build and wire `modules/album` end to end (migrations in `lagoon`, upload + WebP variants + tokens + backfill, `surf` public static & signed-upload routes, smoke tests, module README, root README row, and `docs/services/media-library.md`). + +*Reversibility:* Public URL path shape `media//.` (D-06) is **costly** once embedded in published content; lock exact segment validation and `Cache-Control: immutable` headers here. + + + +@.planning/phases/37-media-library-album/37-CONTEXT.md +@.planning/phases/37-media-library-album/37-RESEARCH.md +@CLAUDE.md +@AGENTS.md + + + + + + Task 1: Create `modules/album` schema, models, migrations, and wire into `modules/lagoon` + + modules/album/album.go + modules/album/models.go + modules/album/migrations.go + modules/lagoon/migrations.go + + +1. Create `modules/album/album.go` with package doc comment, exported config keys (`media.max_bytes` default `25 << 20`, `media.base64_max_bytes` default `5 << 20`, `media.public_path_prefix` default `"/media"`, `media.serve` default following `storage.uploads.serve`), and `ServiceFrom(app *backpack.App) (*Service, bool)` / `Install(app *backpack.App)` helpers. +2. Create `modules/album/models.go` defining: + - `Folder` (`summer_media_folders`): `ID`, `ParentID *uint`, `Name`, `Slug`, `CreatedAt`, `UpdatedAt`. + - `Variant`: `Width int`, `Height int`, `Key string`, `URL string`, `Size int64`, `ContentType string` with JSON tags. + - `Variants` (`[]Variant`) implementing `driver.Valuer` and `sql.Scanner` for Postgres JSONB (always serializing empty slice as `[]`). + - `Item` (`summer_media_items`): `ID`, `ShortID`, `FolderID *uint`, `BlobKey`, `Slug`, `FileName`, `ContentType`, `FileSize`, `Width *int`, `Height *int`, `SHA256`, `Alt`, `Title`, `Caption`, `Variants`, `LegacyFileID *uint`, `LegacyURL string`, `UploadedBy *uint`, `CreatedAt`, `UpdatedAt`. + - `UploadToken` (`summer_media_upload_tokens`): `ID`, `TokenHash`, `CreatedBy uint`, `FolderID *uint`, `ExpectedFilename`, `ExpectedContentType`, `MaxBytes int64`, `ExpiresAt time.Time`, `UsedAt *time.Time`, `CreatedAt time.Time`. + - Helper methods on `Item`: `IsImage() bool`, `PublicURL(cfg *compass.Config) string`, `AbsolutePublicURL(cfg *compass.Config) (string, error)`, `Srcset(cfg *compass.Config) string`, `AllBlobKeys() []string` (returns original `BlobKey` + all `Variants[i].Key`; skips legacy `/uploads/...` keys if `LegacyFileID != nil`). +3. Create `modules/album/migrations.go` exporting `Migrations []*gormigrate.Migration` creating the three tables with Postgres DDL, indexes (`COALESCE(parent_id, 0), slug` unique index on folders, unique `short_id` & `blob_key`, `(folder_id, created_at DESC)`, `(sha256)`, `(content_type)` on items, unique `token_hash` & `(expires_at)` on tokens), and clean `Rollback` functions. +4. Update `modules/lagoon/migrations.go` (`migrationSets`) to register `{"summercms.album", "media", album.Migrations}` right after `postcard.Migrations`. + + + go vet ./modules/album ./modules/lagoon + + `modules/album` compiles with zero import of `modules/lagoon`, and `lagoon.Migrate` / `lagoon.PendingMigrations` include `summercms.album`. + + + + Task 2: Implement `Service` upload pipeline, synchronous WebP variants, signed upload tokens, delete-in-tx, and Mail Images backfill + + modules/album/service.go + modules/album/variants.go + modules/album/tokens.go + modules/album/backfill.go + + +1. Create `modules/album/variants.go`: + - `VariantWidths = []int{480, 960, 1600}`. + - `GenerateWebPVariants(ctx, bucket, shortID, slug, img, origFormat)` decodes raster bytes once (after `attach.IsAllowedImage` has already verified `image.DecodeConfig` + `attach.MaxImagePixels`), resizes with `golang.org/x/image/draw.CatmullRom.Scale` for each width `< origWidth` (never upscaling), encodes via `webp.Encode`, writes to `bucket` at `media//-w.webp` with `ContentType: webp.ContentType`, and returns `[]Variant` + written keys. On any failure, deletes all partially written keys. +2. Create `modules/album/service.go`: + - `NewService(cfg *compass.Config)` and methods on `*Service`: + - `Upload(ctx, db, bucket, in UploadInput) (*Item, error)`: validates extension (`attach.DefaultFileExtensions`, or `attach.DefaultImageExtensions` when `in.ImageOnly`), sniffs up to 1 MiB ahead, enforces `MaxBytes` (default `media.max_bytes`, 25 MB), enforces `attach.IsAllowedImage` for raster images and refuses SVG/HTML/JS, computes streaming SHA-256, derives canonical extension via `attach.DiskExtension`, generates collision-checked 12-char lowercase `[a-z0-9]` `short_id` + sanitized ASCII slug, writes original blob with `attach.UploadWriterOptions(contentType)` to `media//.`, runs synchronous WebP variant generation for raster images, inserts `summer_media_items` row (no deduplication per D-08), and cleans up all written blobs on any error. + - `EnsureFolder(ctx, db, slug, name string, parentID *uint) (*Folder, error)` (idempotent helper for `"mail"` and `"journal"` default folders). + - `ListFolders`, `CreateFolder`, `UpdateFolder`, `DeleteFolder` (refuses non-empty folder containing items or child folders with `ErrFolderNotEmpty`). + - `ListItems(ctx, db, filter ListFilter) ([]Item, int64, error)` (supports `FolderID`, `Query` ILIKE on `file_name`/`title`/`alt`/`slug`, `Type` `image|file`, `SHA256`, `Page`, `PerPage`). + - `GetItem(ctx, db, id uint)`, `GetItemsByShortIDs(ctx, db, shortIDs []string) (map[string]Item, error)` (single batched query for D-14 inline `srcset` enrichment!). + - `UpdateItem(ctx, db, id uint, patch UpdatePatch)` (updates `alt`, `title`, `caption`, `folder_id` — never mutating `short_id`, `slug`, or `blob_key`). + - `DeleteItemInTx(ctx, tx, id uint) ([]string, error)` + `DeleteBlobs(ctx, bucket, keys []string)` (so `cabana` wraps in `lagoon.Transaction` + `lagoon.AfterCommit` per D-12). +3. Create `modules/album/tokens.go`: + - `PrepareUpload(ctx, db, in PrepareUploadInput) (*PreparedUpload, error)`: validates extension/MIME/max bytes (`<= media.max_bytes`), generates 32-byte crypto/rand base64url token, stores SHA-256 hex in `summer_media_upload_tokens` with 5-minute `ExpiresAt`, returns opaque token + metadata. + - `ConsumeUploadToken(ctx, db, rawToken string) (*UploadToken, error)`: atomically executes `UPDATE summer_media_upload_tokens SET used_at = NOW() WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW() RETURNING ...` (returns `ErrInvalidUploadToken` if 0 rows affected). +4. Create `modules/album/backfill.go`: + - `BackfillMailImages(ctx, db, cfg) (int, error)`: idempotently copies metadata for `system_files` rows with `attachment_type = 'System\\Models\\MailImageLibrary' AND field = 'images'` not yet present in `summer_media_items.legacy_file_id` into folder `"mail"`, preserving their existing `/uploads/...` URL in `legacy_url` without touching or moving any existing blob (D-13). + + + go vet ./modules/album + + All core `album` service, variant, token, and backfill operations compile cleanly. + + + + Task 3: Add `album` HTTP handlers, mount in `modules/surf`, write smoke test + README + `docs/services/media-library.md` + + modules/album/http.go + modules/surf/media.go + modules/surf/router.go + modules/album/album_smoke_test.go + modules/album/example_test.go + modules/album/README.md + README.md + docs/services/media-library.md + docs/README.md + + +1. Create `modules/album/http.go`: + - `StaticHandler(bucket *blob.Bucket, prefix string) http.Handler`: serves `GET`/`HEAD //` with zero DB hits. Strictly validates `short-id` (`^[a-z0-9]{10,16}$`) and `file` (`^[a-z0-9][a-z0-9._-]{0,120}\.[a-z0-9]{1,10}$`, rejecting `..`, `/`, `\`). Sets `Cache-Control: public, max-age=31536000, immutable`, `X-Content-Type-Options: nosniff`, sandboxing CSP, stored `Content-Type`, and `Content-Disposition: attachment` whenever `!attach.IsInlineContentType(ct)`. + - `SignedUploadHandler(app *backpack.App, svc *Service) http.Handler`: handles `PUT`/`POST /media/upload/{token}` — atomically consumes token via `ConsumeUploadToken`, wraps `r.Body` in `http.MaxBytesReader(w, r.Body, token.MaxBytes)`, calls `svc.Upload`, and returns `201 Created` JSON `{data: }`. +2. Create `modules/surf/media.go` and call `mountMedia(r, app)` in `modules/surf/router.go` right after `mountUploads(r, app)`: + - Calls `album.Install(app)` (idempotently publishing `*album.Service` onto `app` if not already published) so `album.ServiceFrom(app)` is always populated for `cabana`, `sm-journal-plugin`, and `SignedUploadHandler`. + - Mounts `GET /{short_id}/{file}` (default `/media`) when `media.serve` is true (or unset and `storage.uploads.serve` is true), owning the prefix against plugin route collisions. + - Mounts raw `PUT` and `POST /upload/{token}` behind inline throttle (`throttle:60,1`) with no admin cookie/CSRF middleware. +3. Add `modules/album/album_smoke_test.go` (in-memory `memblob` smoke test for `StaticHandler` security headers & traversal rejection, WebP variant generation, slug/short_id generation, and SVG/HTML rejection) and `modules/album/example_test.go` with `docs:start`/`docs:end` snippets. +4. Write `modules/album/README.md` (following `CLAUDE.md` module README structure with `**Name:**` mnemonic: *"A holiday photo album where you keep, organize and share your pictures and clippings."*), add `album` row to root `README.md` module table, create `docs/services/media-library.md` with `src=` compiled snippets, and link it in `docs/README.md` (or sidebar). + + + go vet ./modules/album ./modules/surf ./modules/lagoon && go test -short ./modules/album ./modules/surf && go test ./cmd/summer -run TestDocsTree + + Zero-DB-hit `/media/...` and signed upload routes mount cleanly in `surf`, smoke tests pass, and `TestDocsTree` / docs check pass with zero errors. + + + + + +- `go vet ./...` passes. +- `go test -short ./modules/album ./modules/surf ./modules/lagoon` passes. +- `go test ./cmd/summer -run TestDocsTree` passes. + + + +- `modules/album` exists with Postgres migrations wired into `lagoon`, synchronous WebP variants, single-use upload tokens, after-commit delete seam, Mail Images backfill, zero-DB-hit `/media/...` serving in `surf`, smoke tests, and verified README/docs. + + + +After completion, create `.planning/phases/37-media-library-album/37-01-SUMMARY.md` + diff --git a/.planning/phases/37-media-library-album/37-02-PLAN.md b/.planning/phases/37-media-library-album/37-02-PLAN.md new file mode 100644 index 00000000..f27ec883 --- /dev/null +++ b/.planning/phases/37-media-library-album/37-02-PLAN.md @@ -0,0 +1,206 @@ +--- +phase: 37-media-library-album +plan: 02 +type: execute +wave: 2 +depends_on: ["37-01"] +files_modified: + - modules/cabana/backend_screens.go + - modules/cabana/media_routes.go + - modules/cabana/media_mcp.go + - modules/cabana/field_media.go + - modules/cabana/form_schema.go + - modules/cabana/http.go + - modules/cabana/mail_routes.go + - modules/cabana/mail_admin.go + - modules/cabana/token_scopes.go + - modules/cabana/token_scopes_export.go + - modules/cabana/admin_openapi.go + - modules/cabana/token_routes_test.go + - modules/cabana/openapi_conformance_test.go + - modules/pier/pier.go + - modules/surf/pier_on.go + - modules/phrasebook/backend/lang/en/lang.yaml + - modules/phrasebook/backend/lang/pl/lang.yaml + - admin/openapi/admin.json + - admin/src/api/schema.d.ts + - admin/src/api/types.ts + - modules/cabana/README.md + - modules/pier/README.md + - docs/backend/forms.md + - docs/services/mcp.md +autonomous: true +requirements: [] +user_setup: [] +must_haves: + truths: + - "`cabana` registers `media.view_media` and `media.manage_media` permissions (no default role grants) and `media:read` / `media` token scopes under a Media group (`backend::lang.api_tokens.group_media`) visible in Phase 36's `ScopePicker` (D-04, D-11)." + - "`cabana` exposes full Media Library REST endpoints under `{backend.uri}/api/v1/media/*` (folders CRUD, items list/get/upload/base64-upload/update/delete, and `POST /media/uploads/prepare`) gated by `media.view_media` / `media.manage_media` and classified in `token_routes_test.go` so scoped tokens and MCP tools work (D-04, D-05, D-09, D-10, D-11)." + - "`DELETE /media/items/{id}` runs `album.DeleteItemInTx` inside `lagoon.Transaction` and deletes original + WebP variant blobs strictly via `lagoon.AfterCommit` (D-12)." + - "`cabana` compiles `type: mediafinder` YAML fields (`mode: image|file`, `multiple: bool`, `folder: string`) into the form schema and OpenAPI spec (D-05)." + - "`GET /mail/images`, `GET /mail/images/{id}`, and `POST /mail/images` store new uploads into `modules/album` under virtual folder `mail` (running idempotent `BackfillMailImages` on first use) while preserving exact backward-compatible `AdminMailImage` JSON responses and `MailBrandSetting.LogoFileID` resolution (D-13)." + - "`pier` exposes all 7 MCP tools (`media_prepare_upload`, `media_upload`, `media_list`, `media_get`, `media_update`, `media_delete`, `media_create_folder`) bound to `cabana`'s `/media/*` routes under guard `backend`, with zero boot-time `warnUncoveredBackendWriteTools` warnings, and `pier.maxRequestBody` raised to `8 << 20` so 5 MB decoded base64 `media_upload` calls succeed (D-04, D-10)." + - "EN and PL phrasebooks define all `backend::lang.media.*`, `backend::lang.permissions.*media*`, and `backend::lang.api_tokens.*media*` keys; `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` pass `scripts/check-admin-openapi.sh --check`." + artifacts: + - path: "modules/cabana/media_routes.go" + provides: "Admin Media REST handlers (folders, items, multipart upload, base64 upload, prepare-upload, update, delete)" + contains: "mediaPrepareUpload" + - path: "modules/cabana/media_mcp.go" + provides: "Framework `summercms.media` MCP plugin declaring the 7 `media_*` tools" + exports: ["MediaMCPPlugin"] + - path: "modules/cabana/field_media.go" + provides: "YAML compiler for `type: mediafinder` (`mode`, `multiple`, `folder`)" + contains: "mediaFinderType" + - path: "admin/openapi/admin.json" + provides: "Regenerated OpenAPI spec with Media routes and `mediafinder` field attributes" + contains: "/media/items" + - path: "admin/src/api/schema.d.ts" + provides: "Regenerated TypeScript API schema for SPA" + contains: "/media/items" + key_links: + - from: "modules/cabana/media_routes.go" + to: "modules/lagoon/transaction.go" + via: "`mediaItemsDelete` wraps `DeleteItemInTx` in `lagoon.Transaction` + `lagoon.AfterCommit`" + pattern: "lagoon\\.AfterCommit" + - from: "modules/surf/pier_on.go" + to: "modules/cabana/media_mcp.go" + via: "Appends `cabana.MediaMCPPlugin(adminPrefix)` to the plugins slice passed to `pier.Mount`" + pattern: "MediaMCPPlugin" + - from: "modules/cabana/mail_routes.go" + to: "modules/album/service.go" + via: "`mailImagesUpload` stores into `album` folder `mail` and preserves `AdminMailImage` JSON" + pattern: "EnsureFolder.*mail" + prohibitions: + - "Do NOT break existing `AdminMailImage` response fields (`id`, `fileName`, `title`, `url`, `thumbUrl`) or existing `MailBrandSetting.LogoFileID` lookups (D-13)." + - "Do NOT expose `media_upload` without enforcing the decoded 5 MB `media.base64_max_bytes` cap (D-10)." + - "Do NOT skip `scripts/check-admin-openapi.sh` regeneration or leave `token_routes_test.go` / `openapi_conformance_test.go` out of sync." +--- + + +**As an** administrator or MCP agent, **I want** permission- and scope-gated admin REST endpoints, a `type: mediafinder` form field schema, unified backward-compatible Mail Images endpoints, and 7 `media_*` MCP tools (including signed-URL and base64 uploads), **so that** the admin SPA and AI agents can browse, upload, and organize media under Phase 36's granular scope picker. + +**Scope (Plan 37-02, Wave 2):** `cabana` media routes, permissions, `media`/`media:read` token scopes, `type: mediafinder` schema compiler, Mail Images unification onto `album`, `pier` 7-tool MCP integration + 8 MiB request body cap, EN/PL phrasebooks, OpenAPI/TS regeneration, and README/docs updates. + +*Reversibility:* Permission codes (`media.view_media`, `media.manage_media`) and token scopes (`media`, `media:read`) (D-11) are **costly** once stored in roles and OAuth grants; verify exact names and method/permission mappings against `37-CONTEXT.md`. + + + +@.planning/phases/37-media-library-album/37-CONTEXT.md +@.planning/phases/37-media-library-album/37-RESEARCH.md +@CLAUDE.md + + + + + + Task 1: Register media permissions, `media`/`media:read` token scopes, `type: mediafinder`, and `/media/*` REST endpoints in `cabana` + + modules/cabana/backend_screens.go + modules/cabana/token_scopes.go + modules/cabana/token_scopes_export.go + modules/cabana/field_media.go + modules/cabana/form_schema.go + modules/cabana/media_routes.go + modules/cabana/http.go + + +1. In `modules/cabana/backend_screens.go`: + - Export `PermissionViewMedia = "media.view_media"` and `PermissionManageMedia = "media.manage_media"`. + - Register both in `backendScreens.Permissions()` under tab `backend::lang.permissions.tab_media`. + - Implement `pact.HasTokenScopes` on `backendScreens` returning: + - `media:read` (`GET`, `HEAD`; permissions `[media.view_media]`; group `backend::lang.api_tokens.group_media`) + - `media` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`; permissions `[media.view_media, media.manage_media]`; group `backend::lang.api_tokens.group_media`) + - Ensure `cabana.NewTokenScopeMatcher` (in `token_scopes_export.go`) includes `backendScreens` scopes so `pier.Mount`'s `warnUncoveredBackendWriteTools` recognizes `media` as covering all `media_*` write tools. +2. Create `modules/cabana/field_media.go` and hook into `form_schema.go`: + - Support `type: mediafinder` with YAML keys `mode` (`"image"` default or `"file"`), `multiple` (`bool`), and `folder` (`string`). Emit them on `FormField` JSON/OpenAPI. +3. Create `modules/cabana/media_routes.go` and mount in `modules/cabana/http.go` inside the `backend` + `locale.from-principal` group: + - `GET /media/folders`, `POST /media/folders`, `PUT /media/folders/{id}`, `DELETE /media/folders/{id}` + - `GET /media/items`, `GET /media/items/{id}`, `POST /media/items` (multipart), `POST /media/items/base64` (JSON `{filename, content_base64, folder_id?, alt?, title?, caption?}`, decoded size capped at `media.base64_max_bytes` default 5 MB), `PUT /media/items/{id}`, `DELETE /media/items/{id}` (wrapped in `lagoon.Transaction` + `lagoon.AfterCommit` blob cleanup!) + - `POST /media/uploads/prepare` (JSON `{filename, content_type?, folder_id?, max_bytes?}` -> `{data: {upload_url, method: "PUT", expires_at, max_bytes}}` using absolute URL from `app.url` + `media.public_path_prefix` + `/upload/`). + - Gate read routes on `Allows(principal, []string{PermissionViewMedia, PermissionManageMedia})` and write routes on `Allows(principal, []string{PermissionManageMedia})`. Use `requireAjax` on writes (skipped automatically for Bearer/MCP token requests per existing `cabana` middleware rules). + + + go vet ./modules/cabana + + All media permissions, token scopes, `mediafinder` schema compilation, and `/media/*` REST endpoints compile cleanly. + + + + Task 2: Unify `cabana` Mail Images onto `modules/album` and wire 7 `media_*` MCP tools in `pier` + + modules/cabana/mail_routes.go + modules/cabana/mail_admin.go + modules/cabana/media_mcp.go + modules/pier/pier.go + modules/surf/pier_on.go + + +1. Update `modules/cabana/mail_routes.go` & `modules/cabana/mail_admin.go`: + - Run idempotent `album.BackfillMailImages` once (guarded by `sync.Once` / retry-on-error like `mailScreens.ensureSynced`) before listing or resolving mail images. + - `POST /mail/images` uploads into `modules/album` under default folder `"mail"` (`EnsureFolder(ctx, tx, "mail", "Mail", nil)`), returning the exact `AdminMailImage` JSON (`id`, `fileName`, `title`, `url` absolute, `thumbUrl` from smallest WebP variant or original) plus additive `variants`. + - `GET /mail/images` and `GET /mail/images/{id}` read from `summer_media_items` (raster images, folder `"mail"` or all mail-backfilled/uploaded images), preserving exact pagination `AdminMailImagesMeta` and `MailBrandSetting.LogoFileID` resolution (checking both `summer_media_items.id` / `legacy_file_id` and `system_files` fallback so existing brand logos never break). +2. Create `modules/cabana/media_mcp.go`: + - Export `MediaMCPPlugin(adminPrefix string) party.Plugin` with `ID() == "summercms.media"` implementing `pact.HasMCP`. + - Declare all 7 tools bound to `{adminPrefix}/api/v1/media/...` with `Guard: "backend"`: + - `prepare_upload` (`POST .../media/uploads/prepare`, `media.manage_media`) + - `upload` (`POST .../media/items/base64`, `media.manage_media`) + - `list` (`GET .../media/items`, `media.view_media`) + - `get` (`GET .../media/items/{id}`, `media.view_media`) + - `update` (`PUT .../media/items/{id}`, `media.manage_media`) + - `delete` (`DELETE .../media/items/{id}`, `media.manage_media`, `Destructive: true`) + - `create_folder` (`POST .../media/folders`, `media.manage_media`) +3. In `modules/surf/pier_on.go`, when `r.adminMounted` is true, append `cabana.MediaMCPPlugin(r.adminPrefix)` to the plugins slice passed to `pier.Mount`. +4. In `modules/pier/pier.go`, raise `maxRequestBody` from `4 << 20` to `8 << 20` (8 MiB) so a 5 MB decoded base64 `media_upload` JSON-RPC payload (~6.7 MB) is accepted cleanly. + + + go vet -tags summercms_mcp ./modules/cabana ./modules/pier ./modules/surf + + Mail Images unify cleanly onto `album`, and `pier` compiles all 7 `media_*` MCP tools with zero uncovered-scope warnings. + + + + Task 3: Add EN/PL phrasebooks, update OpenAPI/TS schemas, test tables, and docs + + modules/phrasebook/backend/lang/en/lang.yaml + modules/phrasebook/backend/lang/pl/lang.yaml + modules/cabana/admin_openapi.go + modules/cabana/token_routes_test.go + modules/cabana/openapi_conformance_test.go + admin/openapi/admin.json + admin/src/api/schema.d.ts + admin/src/api/types.ts + modules/cabana/README.md + modules/pier/README.md + docs/backend/forms.md + docs/services/mcp.md + + +1. Add complete English and Polish translations in `modules/phrasebook/backend/lang/{en,pl}/lang.yaml`: + - `permissions.tab_media`, `permissions.view_media`, `permissions.manage_media` + - `api_tokens.group_media`, `api_tokens.scope_media`, `api_tokens.scope_media_description`, `api_tokens.scope_media_read`, `api_tokens.scope_media_read_description` + - `media.*` keys for Media screen, folder tree, upload, search, inspector, delete-breaks-URLs warning, picker modal, and `mediafinder` field. +2. Annotate all new `/media/*` routes and structs in `modules/cabana/admin_openapi.go`, add them to `tokenRouteClasses` in `modules/cabana/token_routes_test.go` and `openapi_conformance_test.go`. +3. Run `scripts/check-admin-openapi.sh` to regenerate `admin/openapi/admin.json` and `admin/src/api/schema.d.ts`, and export convenient type aliases in `admin/src/api/types.ts`. +4. Update `modules/cabana/README.md`, `modules/pier/README.md`, `docs/backend/forms.md` (`type: mediafinder`), and `docs/services/mcp.md` (built-in `media_*` tools). + + + scripts/check-admin-openapi.sh --check && go test -short ./modules/cabana -run "TestTokenRouteGates|TestOpenAPIConformance|TestTokenScope" && go test ./cmd/summer -run TestDocsTree + + OpenAPI spec, TS schema, token route gates, conformance tests, phrasebooks, and docs all pass green. + + + + + +- `scripts/check-admin-openapi.sh --check` passes. +- `go test -short -tags summercms_mcp ./modules/cabana ./modules/pier ./modules/surf` passes. +- `go test ./cmd/summer -run TestDocsTree` passes. + + + +- Admin Media REST API, `type: mediafinder` schema, unified backward-compatible Mail Images, 7 `media_*` MCP tools, Phase 36 `media`/`media:read` scopes, EN/PL copy, and OpenAPI/TS schemas are complete and passing. + + + +After completion, create `.planning/phases/37-media-library-album/37-02-SUMMARY.md` + diff --git a/.planning/phases/37-media-library-album/37-03-PLAN.md b/.planning/phases/37-media-library-album/37-03-PLAN.md new file mode 100644 index 00000000..e3bc6e47 --- /dev/null +++ b/.planning/phases/37-media-library-album/37-03-PLAN.md @@ -0,0 +1,134 @@ +--- +phase: 37-media-library-album +plan: 03 +type: execute +wave: 3 +depends_on: ["37-02"] +files_modified: + - admin/src/api/media.ts + - admin/src/components/media/MediaBrowser.vue + - admin/src/components/media/MediaFolderTree.vue + - admin/src/components/media/MediaInspector.vue + - admin/src/components/media/MediaPickerModal.vue + - admin/src/components/form/fields/MediaFinderField.vue + - admin/src/components/form/registry.ts + - admin/src/components/mail/MailImagePicker.vue + - admin/src/views/MediaView.vue + - admin/src/app/router.ts + - admin/src/components/shell/PluginRail.vue + - modules/boardwalk/dist/ +autonomous: true +requirements: [] +user_setup: [] +must_haves: + truths: + - "Administrators holding `media.view_media` or `media.manage_media` see a **Media** navigation item in `PluginRail.vue` leading to `/media` (`MediaView.vue`); administrators without either permission do not see it (D-05, D-11)." + - "`MediaView.vue` / `MediaBrowser.vue` supports virtual folder tree navigation & creation/rename/delete (when `media.manage_media`), grid and list views, debounced search, type filter (`all` / `image` / `file`), drag-and-drop + button upload, metadata inspection/editing (`alt`, `title`, `caption`, folder move), copy public URL, and hard delete with a confirmation dialog warning that deleting breaks published URLs (D-05, D-12)." + - "`MediaPickerModal.vue` is a shared `reka-ui` dialog wrapping `MediaBrowser.vue` in pick/insert mode (`mode: 'image' | 'file'`, `multiple`, `defaultFolder`), and `MailImagePicker.vue` delegates to it for Mail templates/layouts/branding without regressing existing mail insert/choose flows (D-05, D-13)." + - "`MediaFinderField.vue` is registered as `'mediafinder'` in `admin/src/components/form/registry.ts`, displays selected image thumbnail or file chip, opens `MediaPickerModal`, and supports single or multiple selection + clear/remove (D-05)." + - "All API calls use generated OpenAPI types from `admin/src/api/schema.d.ts` / `admin/src/api/types.ts`, `npm --prefix admin run typecheck` and `npm --prefix admin run build` succeed, and rebuilt `modules/boardwalk/dist` passes `scripts/check-admin-dist.sh`." + artifacts: + - path: "admin/src/views/MediaView.vue" + provides: "First-class permission-gated Media Library screen" + contains: "MediaBrowser" + - path: "admin/src/components/media/MediaBrowser.vue" + provides: "Reusable folder tree + grid/list + search + upload + inspector + delete-warning browser" + contains: "MediaFolderTree" + - path: "admin/src/components/media/MediaPickerModal.vue" + provides: "Shared Media Picker modal for Mail Editor, Blog Editor, and `mediafinder`" + contains: "DialogRoot" + - path: "admin/src/components/form/fields/MediaFinderField.vue" + provides: "Reusable `type: mediafinder` form control" + contains: "MediaPickerModal" + - path: "admin/src/components/form/registry.ts" + provides: "Registers `'mediafinder'` in form field renderer map" + contains: "['mediafinder', MediaFinderField]" + key_links: + - from: "admin/src/components/mail/MailImagePicker.vue" + to: "admin/src/components/media/MediaPickerModal.vue" + via: "Delegates mail image picking to `MediaPickerModal` with `mode='image'` and `defaultFolder='mail'`" + pattern: "MediaPickerModal" + - from: "admin/src/app/router.ts" + to: "admin/src/views/MediaView.vue" + via: "Mounts `/media` route inside the admin shell" + pattern: "path: '/media'" + prohibitions: + - "Do NOT hand-maintain duplicate API response types outside `admin/src/api/schema.d.ts` / `admin/src/api/types.ts`." + - "Do NOT omit the published-URL-breakage warning confirmation dialog before hard-deleting a media item (D-12)." + - "Do NOT leave `modules/boardwalk/dist` out of sync with `admin/` (`scripts/check-admin-dist.sh`)." +--- + + +**As a** content editor or administrator, **I want** a first-class **Media** screen in the admin SPA, a reusable `type: mediafinder` form field, and a shared Media Picker modal (reused by Mail Editor), **so that** I can organize folders, upload assets, edit `alt`/`title`/`caption` metadata, copy URLs, and pick media consistently across every screen. + +**Scope (Plan 37-03, Wave 3):** Vue 3 Media Library components (`MediaView`, `MediaBrowser`, `MediaFolderTree`, `MediaInspector`, `MediaPickerModal`, `MediaFinderField`), router & rail navigation entry, `MailImagePicker` unification onto `MediaPickerModal`, and rebuilt `modules/boardwalk/dist`. + + + +@.planning/phases/37-media-library-album/37-CONTEXT.md +@.planning/phases/37-media-library-album/37-RESEARCH.md +@CLAUDE.md + + + + + + Task 1: Build typed Media API helper and reusable `MediaBrowser` / `MediaFolderTree` / `MediaInspector` components + + admin/src/api/media.ts + admin/src/components/media/MediaFolderTree.vue + admin/src/components/media/MediaInspector.vue + admin/src/components/media/MediaBrowser.vue + + +1. Create `admin/src/api/media.ts` wrapping typed `openapi-fetch` calls (`GET/POST/PUT/DELETE /media/folders`, `GET/POST/PUT/DELETE /media/items`, multipart upload helper) using generated types from `schema.d.ts` / `types.ts`. +2. Create `admin/src/components/media/MediaFolderTree.vue`: renders "All Media" root + nested virtual folders with item counts, active selection, and (when `canManage`) create/rename/delete folder actions. +3. Create `admin/src/components/media/MediaInspector.vue`: side panel showing preview (thumbnail for images, file icon + extension badge for non-images), dimensions, byte size, `sha256` (truncated + copy), WebP variant count, copy URL button, editable `alt`/`title`/`caption`/folder move form (when `canManage`), and Delete button opening a confirmation dialog that explicitly warns deleting breaks any published URLs referencing the item (D-12). +4. Create `admin/src/components/media/MediaBrowser.vue`: combines `MediaFolderTree`, toolbar (debounced search, type filter `all|image|file`, grid/list view toggle, upload button + drag-and-drop overlay), paginated item grid/table, and `MediaInspector`. Supports both standalone library mode and selection/picker mode (`selectable`, `multiple`, `mode: 'all' | 'image' | 'file'`, `defaultFolder`). Respects dark-mode tokens and uses `backend::lang.media.*` phrasebook keys. + + + npm --prefix admin run typecheck + + All Media browser subcomponents compile cleanly under `vue-tsc` with zero type errors. + + + + Task 2: Build `MediaView`, `MediaPickerModal`, `MediaFinderField`, unify `MailImagePicker`, wire router/nav, and rebuild `boardwalk/dist` + + admin/src/components/media/MediaPickerModal.vue + admin/src/components/form/fields/MediaFinderField.vue + admin/src/components/form/registry.ts + admin/src/components/mail/MailImagePicker.vue + admin/src/views/MediaView.vue + admin/src/app/router.ts + admin/src/components/shell/PluginRail.vue + modules/boardwalk/dist/ + + +1. Create `admin/src/components/media/MediaPickerModal.vue` using `reka-ui` (`DialogRoot`, `DialogPortal`, `DialogOverlay`, `DialogContent`, `DialogTitle`, `DialogClose`) wrapping `MediaBrowser` in picker mode (`open`, `mode`, `multiple`, `defaultFolder`) and emitting `select` with selected `AdminMediaItem[]` (plus optional `alt` override in insert mode). +2. Create `admin/src/components/form/fields/MediaFinderField.vue` and register `['mediafinder', MediaFinderField]` in `admin/src/components/form/registry.ts` (and add `'mediafinder'` to `groupLabelledTypes`). Supports `field.mode` (`image|file`), `field.multiple`, `field.folder`, preview card(s), pick button opening `MediaPickerModal`, and clear/remove. +3. Refactor `admin/src/components/mail/MailImagePicker.vue` to reuse `MediaPickerModal` (defaulting to folder `mail`, `mode="image"`) while preserving its exact props (`open`, `mode: 'insert' | 'choose'`) and emitted events (`insert: {url, alt}`, `choose: id`) so Mail Template / Layout / Branding forms work identically. +4. Create `admin/src/views/MediaView.vue`, register `{ path: '/media', name: 'media', component: MediaView, meta: { shell: true } }` in `admin/src/app/router.ts`, and add a permission-gated **Media** rail item in `admin/src/components/shell/PluginRail.vue` (visible when `hasPermission('media.view_media') || hasPermission('media.manage_media')`). +5. Run `npm --prefix admin run build`, copy/commit into `modules/boardwalk/dist`, and verify with `scripts/check-admin-dist.sh`. + + + npm --prefix admin run typecheck && npm --prefix admin run test && scripts/check-admin-dist.sh + + `MediaView`, `MediaPickerModal`, `MediaFinderField`, and unified `MailImagePicker` pass typecheck, existing Vitest suites, and `scripts/check-admin-dist.sh`. + + + + + +- `npm --prefix admin run typecheck` passes. +- `npm --prefix admin run test` passes. +- `scripts/check-admin-dist.sh` passes. + + + +- Admin SPA ships the permission-gated Media screen, `type: mediafinder` field, shared `MediaPickerModal` reused by Mail Editor, and verified `modules/boardwalk/dist`. + + + +After completion, create `.planning/phases/37-media-library-album/37-03-SUMMARY.md` + diff --git a/.planning/phases/37-media-library-album/37-04-PLAN.md b/.planning/phases/37-media-library-album/37-04-PLAN.md new file mode 100644 index 00000000..6152017f --- /dev/null +++ b/.planning/phases/37-media-library-album/37-04-PLAN.md @@ -0,0 +1,124 @@ +--- +phase: 37-media-library-album +plan: 04 +type: execute +wave: 4 +depends_on: ["37-02", "37-03"] +files_modified: + - ../sm-journal-plugin/controllers/api/media.go + - ../sm-journal-plugin/controllers/api/posts.go + - ../sm-journal-plugin/classes/enrich_media.go + - ../sm-journal-plugin/assets/src/blogeditor/ + - ../sm-journal-plugin/README.md + - ../vue-journal-layer/ +autonomous: true +requirements: [] +user_setup: [] +must_haves: + truths: + - "`sm-journal-plugin`'s `POST /_journal/api/v1/media/upload` stores new uploads via `modules/album` (into default virtual folder `journal`, or requested subfolder under `journal`) while preserving `{data: {url, path}}` and additively returning `id`, `width`, `height`, `variants`, and `srcset` (D-13)." + - "Existing `/uploads/...` inline image URLs in historical Journal posts remain completely untouched and continue rendering without breakage (D-13)." + - "Stored Journal post `content` and `content_html` remain clean standard `/.\" ...>`; during `serializePost` / `Index` API serialization, `sm-journal-plugin` enriches matching `/...\">` tags with `srcset` and `sizes` from `summer_media_items.variants` using a single batched `WHERE short_id IN ?` query per response (zero N+1) (D-14)." + - "The Journal Blog Editor exposes a \"Choose from Media Library\" action reusing the admin Media Picker / `/api/v1/media/items` alongside direct upload (D-05)." + - "`vue-journal-layer`'s `sanitize-html` allow-list permits `srcset`, `sizes`, `width`, `height`, `loading`, and `decoding` on `` elements so SSR and client hydration preserve inline responsive WebP `srcset` attributes (D-14)." + - "All local cross-repo verification uses temporary `GOWORK` / scratch `modfile` without dirtying submodule pointers or tagging releases (`AGENTS.md` / `CLAUDE.md` rule 5)." + artifacts: + - path: "../sm-journal-plugin/controllers/api/media.go" + provides: "Backward-compatible `/_journal/api/v1/media/upload` backed by `modules/album`" + contains: "album" + - path: "../sm-journal-plugin/classes/enrich_media.go" + provides: "Single-query batched `/...\">` `srcset`/`sizes` HTML enricher" + exports: ["EnrichMediaHTML", "ExtractMediaShortIDs"] + - path: "../sm-journal-plugin/controllers/api/posts.go" + provides: "Batched inline `srcset` enrichment in `Index` and `Show`" + contains: "EnrichMediaHTML" + key_links: + - from: "../sm-journal-plugin/controllers/api/posts.go" + to: "../sm-journal-plugin/classes/enrich_media.go" + via: "Collects all `/media//` IDs across serialized posts, calls `album.GetItemsByShortIDs` once, and enriches each post's `content_html`" + pattern: "EnrichMediaHTML" + - from: "../sm-journal-plugin/controllers/api/media.go" + to: "modules/album/service.go" + via: "Uploads through `album.Service.Upload` into folder `journal`" + pattern: "EnsureFolder.*journal" + prohibitions: + - "Do NOT rewrite stored `content` or `content_html` in Postgres to embed `srcset` (keep stored HTML clean per D-14)." + - "Do NOT query `summer_media_items` per `` or per post inside a loop (must be a single batched query per request per D-14)." + - "Do NOT tag releases or bump `go.mod` to unreleased tags inside this plan (`AGENTS.md` rule 5)." +--- + + +**As a** blog editor and reader on a SummerCMS journal site, **I want** Journal media uploads to go into the unified `modules/album` Media Library, the Blog Editor to pick existing media from the library, and inline `/media//...` post images to automatically render responsive WebP `srcset`/`sizes`, **so that** pillar articles with multiple infographics serve crisp, bandwidth-efficient WebP variants without manual HTML work. + +**Scope (Plan 37-04, Wave 4):** Sibling repo unification in `../sm-journal-plugin` and `../vue-journal-layer`, verified locally against this `summercms.go` checkout via temporary `GOWORK` / scratch `modfile`. + + + +@.planning/phases/37-media-library-album/37-CONTEXT.md +@.planning/phases/37-media-library-album/37-RESEARCH.md +@CLAUDE.md +@AGENTS.md + + + + + + Task 1: Unify `sm-journal-plugin` media upload onto `modules/album` and add single-query batched inline `srcset` enrichment + + ../sm-journal-plugin/controllers/api/media.go + ../sm-journal-plugin/classes/enrich_media.go + ../sm-journal-plugin/controllers/api/posts.go + ../sm-journal-plugin/README.md + + +1. Update `../sm-journal-plugin/controllers/api/media.go`: + - Route `POST /_journal/api/v1/media/upload` through `modules/album` (`EnsureFolder` `"journal"`, plus optional sanitized subfolder when `folder` param is provided). + - Preserve exact backward-compatible JSON keys `{data: {url, path}}` and additively include `id`, `short_id`, `width`, `height`, `variants`, and `srcset`. + - Keep existing validation errors (422 on `folder` or `file` field) intact. +2. Create `../sm-journal-plugin/classes/enrich_media.go`: + - `ExtractMediaShortIDs(htmlDoc string) []string`: tokenizes HTML via `golang.org/x/net/html` and extracts `` from `` (and full `app.url` + `/media//...`). + - `EnrichMediaHTML(htmlDoc string, items map[string]album.Item, cfg *compass.Config) string`: rewrites matching `` start tags in-stream to add `srcset` (from `item.Srcset(cfg)`), `sizes="(max-width: 768px) 100vw, 800px"` (when absent), and `width`/`height` (when absent and known), leaving non-`/media/...` images (including legacy `/uploads/...`) byte-identical. +3. Update `../sm-journal-plugin/controllers/api/posts.go`: + - In `Show` and `Index`, collect all `/media//` references across the post(s) and translations, run **one** batched `album.GetItemsByShortIDs(ctx, db, ids)` query, and pass the map into `serializePost` to enrich serialized `content_html` (without mutating stored DB rows). +4. Update `../sm-journal-plugin/README.md` to document the `album` backing and render-time `srcset` enrichment. + + + tmp=$(mktemp /tmp/phase37-gowork.XXXXXX) && trap 'rm -f "$tmp"' EXIT && printf 'go 1.24\n\nuse (\n\t.\n\t../sm-journal-plugin\n)\n' > "$tmp" && GOWORK="$tmp" go -C ../sm-journal-plugin vet ./... && GOWORK="$tmp" go -C ../sm-journal-plugin test -short ./... + + `sm-journal-plugin` uploads to `album` and enriches inline `/media/...` images with responsive WebP `srcset` in one batched query (verified under temporary `GOWORK` against local `summercms.go` checkout). + + + + Task 2: Wire Blog Editor Media Library picker in `sm-journal-plugin` and `srcset`/`sizes` allow-list in `vue-journal-layer` + + ../sm-journal-plugin/assets/src/blogeditor/ + ../vue-journal-layer/ + + +1. In `../sm-journal-plugin/assets/src/blogeditor/`: + - Add a "Choose from Media Library" action in the Blog Editor image insertion toolbar/popover that fetches/picks from the admin Media Library API (`GET /api/v1/media/items?type=image`) or dispatches the host admin Media Picker modal event, inserting clean `...`. + - Rebuild the Blog Editor bundle per `sm-journal-plugin`'s build script so embedded assets stay in sync. +2. In `../vue-journal-layer/`: + - Inspect the HTML sanitizer (`sanitize-html` config) and ensure `img` `allowedAttributes` explicitly includes `srcset`, `sizes`, `width`, `height`, `loading`, and `decoding` (validating that `srcset` URLs are safe `https:`/`http:` or relative `/media/...` paths, never `javascript:` or `data:`). + - Run `npm --prefix ../vue-journal-layer test` to verify all existing SSR/sanitizer tests pass and add a test case asserting inline `/media//...` `srcset` and `sizes` survive sanitization while unsafe `srcset` schemes are stripped. + + + npm --prefix ../vue-journal-layer test + + Blog Editor can pick from the unified Media Library, and `vue-journal-layer` preserves safe inline `srcset`/`sizes`/`width`/`height` attributes under SSR and sanitization. + + + + + +- Local temporary `GOWORK` test run of `../sm-journal-plugin` passes (`go vet` + `go test -short ./...`), leaving `../sm-journal-plugin/go.mod` clean. +- `npm --prefix ../vue-journal-layer test` passes. + + + +- Journal uploads unify onto `album`, Blog Editor picks from Media Library, inline `/media/...` images render responsive WebP `srcset`/`sizes` with zero N+1 queries, and `vue-journal-layer` preserves them cleanly. + + + +After completion, create `.planning/phases/37-media-library-album/37-04-SUMMARY.md` + diff --git a/.planning/phases/37-media-library-album/37-05-PLAN.md b/.planning/phases/37-media-library-album/37-05-PLAN.md new file mode 100644 index 00000000..64899924 --- /dev/null +++ b/.planning/phases/37-media-library-album/37-05-PLAN.md @@ -0,0 +1,136 @@ +--- +phase: 37-media-library-album +plan: 05 +type: execute +wave: 5 +depends_on: ["37-01", "37-02", "37-03", "37-04"] +files_modified: + - modules/album/album_test.go + - modules/album/album_postgres_test.go + - modules/cabana/media_routes_test.go + - modules/cabana/media_postgres_test.go + - modules/pier/media_mcp_test.go + - modules/surf/media_test.go + - admin/src/components/media/__tests__/MediaBrowser.test.ts + - admin/src/components/media/__tests__/MediaPickerModal.test.ts + - admin/src/components/form/fields/__tests__/MediaFinderField.test.ts + - scripts/check-phase37.sh + - .planning/phases/37-media-library-album/37-VALIDATION.md +autonomous: true +requirements: [] +user_setup: [] +must_haves: + truths: + - "Go unit and Postgres integration tests thoroughly cover `modules/album` (migrations up/down, folder CRUD + non-empty delete refusal, raster upload + synchronous WebP `480w`/`960w`/`1600w` variants without upscaling, non-image `Content-Disposition: attachment`, SVG/HTML/JS rejection, decompression-bomb pixel guard, `sha256` without auto-dedup, atomic single-use upload tokens rejecting replay & expiry, `DeleteItemInTx` + `lagoon.AfterCommit` rollback safety, and idempotent `BackfillMailImages`)." + - "Go tests cover `cabana` media REST endpoints, `media.view_media` / `media.manage_media` permission gates, `media` / `media:read` Phase 36 token scope enforcement, `type: mediafinder` YAML schema validation, backward-compatible `/mail/images` over `album`, `TestTokenRouteGates`, and `TestOpenAPIConformance`." + - "Go tests under `-tags summercms_mcp` verify all 7 `media_*` MCP tools in `pier` (including `media_prepare_upload` -> `PUT /media/upload/{token}` end-to-end and 5 MB base64 `media_upload` succeeding while >5 MB decoded is rejected, plus zero `warnUncoveredBackendWriteTools` warnings at boot)." + - "Go tests in `modules/surf` verify zero-DB-hit `GET /media/{short_id}/{file}` (`Cache-Control: immutable`, `nosniff`, CSP, `Content-Disposition: attachment` for PDFs, traversal rejection) and prefix collision checks." + - "Vitest component tests cover `MediaBrowser` / `MediaView` (folders, search, upload, metadata edit, delete warning dialog), `MediaPickerModal` (including Mail Image picker delegation), and `MediaFinderField` (single + multiple)." + - "`scripts/check-phase37.sh` runs all fail-closed gates: `go vet ./...`, `go test -short ./...`, Postgres tests (Docker), `npm --prefix admin run test` + `typecheck`, `scripts/check-admin-openapi.sh --check`, `scripts/check-admin-dist.sh`, `summer docs:build --check` + `TestDocsTree`, local read-only scratch-modfile consumer proofs for `../sm-journal-plugin` and `../vue-journal-layer`, and no-consumer-name marker check." + - "Zero release tags, zero tag pushes, zero downstream `go.mod`/submodule bumps, and zero changelog posts are performed (`AGENTS.md` / `CLAUDE.md` rule 5)." + artifacts: + - path: "modules/album/album_test.go" + provides: "Docker-free unit tests for `modules/album` variants, slugs, validation, static handler security" + contains: "TestWebPVariants" + - path: "modules/album/album_postgres_test.go" + provides: "Postgres integration tests for migrations, atomic upload tokens, after-commit delete, and Mail backfill" + contains: "TestConsumeUploadTokenSingleUse" + - path: "modules/pier/media_mcp_test.go" + provides: "7-tool `media_*` MCP E2E + signed upload + base64 cap + zero-warning boot tests" + contains: "TestMediaMCPTools" + - path: "scripts/check-phase37.sh" + provides: "Fail-closed Phase 37 verification gate script" + contains: "check-admin-dist.sh" + - path: ".planning/phases/37-media-library-album/37-VALIDATION.md" + provides: "Nyquist validation matrix mapping all Phase 37 success criteria and decisions to passing tests" + contains: "37-VALIDATION" + key_links: + - from: "scripts/check-phase37.sh" + to: "../sm-journal-plugin" + via: "Runs read-only scratch-modfile `go vet` and media/enrichment tests against this local checkout without modifying sibling `go.mod`" + pattern: "sm-journal-plugin" + - from: "scripts/check-phase37.sh" + to: "scripts/check-admin-dist.sh" + via: "Verifies committed `modules/boardwalk/dist` matches fresh admin build" + pattern: "check-admin-dist.sh" + prohibitions: + - "Do NOT run `git tag`, `git push`, consumer `go.mod`/submodule bumps, or `changelog-post.py` (`AGENTS.md` / `CLAUDE.md` rule 5)." + - "Do NOT skip any test without documenting Docker-only `-short` guards properly (`flag.Parse()` + `testing.Short()`)." +--- + + +**As a** maintainer preparing Phase 37 for code review and goal-backward verification, **I want** comprehensive Go unit/Postgres tests, Vitest component tests, a fail-closed `scripts/check-phase37.sh` gate (including read-only local consumer proofs for `sm-journal-plugin` and `vue-journal-layer`), and `37-VALIDATION.md`, **so that** every Phase 37 invariant is proven before `/msd-code-review 37` and `37-VERIFICATION.md`. + +**Scope (Plan 37-05, Wave 5 — Unit Tests Last):** Complete test suites across `album`, `cabana`, `pier`, `surf`, and `admin/`, `scripts/check-phase37.sh`, and `37-VALIDATION.md` (strictly excluding release tagging/publishing per `AGENTS.md`). + + + +@.planning/phases/37-media-library-album/37-CONTEXT.md +@.planning/phases/37-media-library-album/37-RESEARCH.md +@CLAUDE.md +@AGENTS.md + + + + + + Task 1: Write comprehensive Go unit & Postgres tests across `album`, `cabana`, `pier`, and `surf` + + modules/album/album_test.go + modules/album/album_postgres_test.go + modules/cabana/media_routes_test.go + modules/cabana/media_postgres_test.go + modules/pier/media_mcp_test.go + modules/surf/media_test.go + + +1. `modules/album/album_test.go`: unit tests for slug sanitization, `short_id` format, WebP variant generation (`480w`/`960w`/`1600w`, no upscaling on small images, aspect ratio preservation), SVG/HTML/JS rejection, polyglot / decompression-bomb pixel guard rejection, non-image `Content-Disposition: attachment`, `StaticHandler` headers (`Cache-Control: immutable`, `nosniff`, CSP, traversal `..`/slash rejection). +2. `modules/album/album_postgres_test.go` (Docker-backed, skips cleanly under `-short`): migrations up & down, folder hierarchy + unique sibling slug + non-empty folder delete 409, upload + `sha256` non-dedup (two uploads of same bytes create two independent rows/keys), `PrepareUpload` + `ConsumeUploadToken` atomic single-use (second use fails, expired token fails), `DeleteItemInTx` + rolled-back tx keeps blobs while committed tx deletes original + all WebP variants, `GetItemsByShortIDs` batch lookup, and idempotent `BackfillMailImages` preserving legacy `/uploads/...` URLs. +3. `modules/cabana/media_routes_test.go` & `media_postgres_test.go`: `media.view_media` vs `media.manage_media` permission matrix, `media:read` vs `media` token scope enforcement, `type: mediafinder` YAML compile & error cases, backward-compatible `GET/POST /mail/images` over `album`, and `MailBrandSetting.LogoFileID` compatibility. +4. `modules/pier/media_mcp_test.go` (`//go:build summercms_mcp`): tests all 7 `media_*` MCP tools (`media_prepare_upload` -> HTTP `PUT /media/upload/{token}`, `media_upload` base64 within 5 MB and >5 MB rejection, `media_list`, `media_get`, `media_update`, `media_delete`, `media_create_folder`), scope filtering (`media:read` sees only list/get; `media` sees all 7), and asserts zero `warnUncoveredBackendWriteTools` warnings at boot. +5. `modules/surf/media_test.go`: tests `mountMedia` route registration, prefix collision rejection, `/media/{short_id}/{file}` zero-DB-hit serving, and `/media/upload/{token}` raw mount without admin cookie/CSRF. + + + go test -short -tags summercms_mcp ./modules/album ./modules/cabana ./modules/pier ./modules/surf + + All Docker-free Go unit tests pass under `-short` and `-tags summercms_mcp`. + + + + Task 2: Write Vitest component tests, `scripts/check-phase37.sh` fail-closed gate, and `37-VALIDATION.md` + + admin/src/components/media/__tests__/MediaBrowser.test.ts + admin/src/components/media/__tests__/MediaPickerModal.test.ts + admin/src/components/form/fields/__tests__/MediaFinderField.test.ts + scripts/check-phase37.sh + .planning/phases/37-media-library-album/37-VALIDATION.md + + +1. Add Vitest component tests in `admin/`: + - `MediaBrowser.test.ts`: folder tree navigation & create/delete, grid/list toggle, debounced search, upload flow, metadata edit (`alt`/`title`/`caption`), and delete confirmation dialog warning about broken published URLs. + - `MediaPickerModal.test.ts`: image/file pick mode, insert mode, `defaultFolder='mail'` delegation from `MailImagePicker`. + - `MediaFinderField.test.ts`: single and multiple selection, thumbnail/chip display, clear/remove. +2. Create executable `scripts/check-phase37.sh` modeled on `scripts/check-phase35.sh`: + - Stages: `--go` (`go vet ./...`, `go test -short -tags summercms_mcp ./...`, required test names), `--docker` (Postgres tests when Docker is available), `--admin` (Vitest + typecheck + `scripts/check-admin-openapi.sh --check` + `scripts/check-admin-dist.sh`), `--docs` (`TestDocsTree` + `summer docs:build --check`), `--consumers` (read-only scratch-modfile `go vet` + media/enrichment tests in `../sm-journal-plugin`, plus `npm --prefix ../vue-journal-layer test`, verifying sibling git status stays clean), `--marker` (no consuming-app names in framework code/docs). +3. Run `scripts/check-phase37.sh --all` (or with Docker if available) and record the complete Nyquist validation matrix in `.planning/phases/37-media-library-album/37-VALIDATION.md`. + + + chmod +x scripts/check-phase37.sh && scripts/check-phase37.sh --go --admin --docs --consumers --marker + + All Vitest tests, Go tests, OpenAPI, `boardwalk/dist`, docs, and local consumer proofs pass via `scripts/check-phase37.sh`, ready for `/msd-code-review 37` and `37-VERIFICATION.md`. + + + + + +- `scripts/check-phase37.sh --all` (or `--go --admin --docs --consumers --marker` + `--docker` on Docker host) exits 0. +- `git status` shows no dirty submodule pointers or release tags. + + + +- Complete Go + Vitest test coverage, fail-closed `scripts/check-phase37.sh` gate, and `37-VALIDATION.md` are green and ready for `/msd-code-review 37` and goal-backward verification. + + + +After completion, create `.planning/phases/37-media-library-album/37-05-SUMMARY.md` + diff --git a/.planning/phases/37-media-library-album/37-RESEARCH.md b/.planning/phases/37-media-library-album/37-RESEARCH.md new file mode 100644 index 00000000..918efa81 --- /dev/null +++ b/.planning/phases/37-media-library-album/37-RESEARCH.md @@ -0,0 +1,190 @@ +# Phase 37: Media Library (`album`) - Research + +**Researched:** 2026-11-27 +**Domain:** Core Go media library module (`modules/album`), Postgres metadata & virtual folders, synchronous WebP `srcset` variants, zero-DB-hit `/media/...` serving, `cabana`/`boardwalk` admin Media screen + `type: mediafinder` + shared Media Picker modal, `pier` MCP media tools (signed upload URL + base64), and `sm-journal-plugin` / `vue-journal-layer` unification. +**Confidence:** HIGH (all existing APIs, import graph, routes, and schemas verified directly from source). + +--- + +## 1. Existing Codebase & Import Graph Findings + +### 1.1 Go Package Import Graph (No Cycles) +- `modules/lagoon/attach` and `modules/lagoon/attach/webp` do **not** import `modules/lagoon`. +- `modules/lagoon` imports `modules/lagoon/attach` and `modules/postcard` (in `modules/lagoon/migrations.go`). +- `modules/cabana` imports `modules/lagoon`, `modules/lagoon/attach`, `modules/postcard`. +- `modules/surf` imports `modules/cabana` (and `modules/pier` under `summercms_mcp` build tag via `pier_on.go`). +- `modules/pier` imports `modules/cabana`. + +**Architectural rule for `modules/album`:** +- `modules/album` imports `modules/lagoon/attach`, `modules/lagoon/attach/webp`, `modules/backpack`, `modules/compass`, `modules/pact`, `gocloud.dev/blob`, `gorm.io/gorm`, and `github.com/go-gormigrate/gormigrate/v2`. +- `modules/album` does **not** import `modules/lagoon` (matching `modules/postcard`'s exact pattern). +- Therefore: + 1. `modules/lagoon/migrations.go` can import `modules/album` and add `{"summercms.album", "media", album.Migrations}` to `migrationSets()`. + 2. `modules/cabana` and `modules/surf` can import `modules/album` directly. + 3. For `lagoon.AfterCommit` blob cleanup on delete (D-12), `album.Service` exposes both `DeleteItemInTx(ctx, tx, id) (blobKeys []string, err error)` and `DeleteBlobs(ctx, keys)` (plus a convenience `DeleteItem` using `db.Transaction` followed by post-commit blob deletion), so `cabana` wraps `DeleteItemInTx` inside `lagoon.Transaction` + `lagoon.AfterCommit` (or passes an after-commit hook). Rolled-back transactions never delete blobs. + +### 1.2 Reusable `modules/lagoon/attach` & `webp` Primitives +- `attach.DefaultImageExtensions`: `["jpg", "jpeg", "png", "gif", "webp"]` (no SVG, no AVIF/BMP). +- `attach.DefaultFileExtensions`: 37 safe static file extensions (PDF, audio, video, archives, office docs, fonts) explicitly excluding `svg`, `js`, `html`, `css`, `xml`, `swf`. +- `attach.IsAllowedImage(data []byte) bool`: sniffs via `http.DetectContentType`, decodes header via `image.DecodeConfig`, verifies positive dimensions and `int64(w)*int64(h) <= attach.MaxImagePixels` (decompression-bomb guard), and verifies format is `jpeg|png|gif|webp`. +- `attach.DiskExtension(sniffedContentType, clientExt string) string`: canonicalizes extension from sniffed bytes and refuses script-capable extensions (`html`, `svg`, `js`, `php`, etc.). +- `attach.UploadWriterOptions(contentType string) *blob.WriterOptions`: sets `ContentType` and adds `ContentDisposition: "attachment"` for every non-inline MIME type (`!attach.IsInlineContentType(ct)`). +- `attach.AbsolutePublicURL(cfg, blobKey)` & `attach.PublicURLBase()`: resolves S3/CDN `storage.uploads.public_url` vs `app.url` + prefix. +- `webp.Encode(w io.Writer, img image.Image) error`: pure-Go WebP encoding at `webp.Quality = 80`, `webp.ContentType = "image/webp"`. (Resize using `golang.org/x/image/draw` — already in `go.mod` via `attach/thumb.go`, zero new dependencies needed.) + +### 1.3 Static Serving & Routing (`modules/surf`) +- `modules/surf/uploads.go` mounts `GET /{path...}` when `storage.uploads.serve` is true, with `X-Content-Type-Options: nosniff`, sandboxing CSP, and `Content-Disposition: attachment` for non-inline types. +- `modules/album` public media route: + - `GET /media/{short_id}/{file}` (configurable via `media.public_path_prefix`, default `/media`; mounted when `media.serve` is true or `storage.uploads.serve` is true — default `media.serve` follows `storage.uploads.serve` when unset). + - Strict segment validation: `short_id` matches `^[a-z0-9]{10,16}$`, `file` matches `^[a-z0-9][a-z0-9._-]{0,120}\.[a-z0-9]{1,10}$` with no `..`, `/`, or `\`. + - Reads directly from `blob.Bucket` at key `media//` (**zero DB hit**). + - Headers: `Cache-Control: public, max-age=31536000, immutable`, `X-Content-Type-Options: nosniff`, sandboxing `Content-Security-Policy`, stored `Content-Type`, and `Content-Disposition: attachment` when `!attach.IsInlineContentType(ct)`. +- Signed upload route (D-09): + - `PUT /media/upload/{token}` and `POST /media/upload/{token}` mounted as a raw route (no admin cookie/CSRF middleware, because CLI agents call it with the opaque single-use token; rate-limited via inline throttle). + - Body cap enforced by `http.MaxBytesReader` using `min(token.MaxBytes, media.max_bytes)`. + +### 1.4 Admin Backend (`modules/cabana`) +- `backendScreens` pseudo-plugin (`modules/cabana/backend_screens.go`) registers framework permissions, settings, and controllers without mutating the caller's `plugins` slice. +- New permissions (D-11): + - `PermissionViewMedia = "media.view_media"` + - `PermissionManageMedia = "media.manage_media"` + - Declared on `backendScreens.Permissions()` under tab `backend::lang.permissions.tab_media` (with no automatic role grants, matching `backend.manage_users` and mail permissions). +- New token scopes (D-04, D-11): + - Registered via `backendScreens` implementing `pact.HasTokenScopes` (or framework scopes in `token_scopes.go` + `NewTokenScopeMatcher` so `pier`'s boot warning check sees them!): + - `media:read` (`GET`, `HEAD`, permissions: `["media.view_media"]`, group: `backend::lang.api_tokens.group_media`) + - `media` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, permissions: `["media.view_media", "media.manage_media"]`, group: `backend::lang.api_tokens.group_media`) +- Admin Media REST endpoints under `{backend.uri}/api/v1/media/...` (behind `backend` + `locale.from-principal` middleware, with `requireAjax` on writes, classified in `token_routes_test.go` as `classExplicitGate` so both interactive sessions and scoped `media`/`media:read` tokens + MCP tools work!): + - `GET /media/folders` — list folder tree (`media.view_media` or `media.manage_media`) + - `POST /media/folders` — create folder (`media.manage_media`) + - `PUT /media/folders/{id}` — rename/move folder (`media.manage_media`) + - `DELETE /media/folders/{id}` — delete empty folder (`media.manage_media`; refuses non-empty folders with 409) + - `GET /media/items` — paginated list/search/filter by `folder_id`, `q`, `type` (`image|file`), `sha256`, `page`, `per_page` (`media.view_media` or `media.manage_media`) + - `GET /media/items/{id}` — item detail with variants & `srcset` (`media.view_media` or `media.manage_media`) + - `POST /media/items` — multipart upload (`file`, optional `folder_id`, `alt`, `title`, `caption`) (`media.manage_media`) + - `POST /media/items/base64` — JSON base64 upload (`filename`, `content_base64`, optional `folder_id`, `alt`, `title`, `caption`), capped at `media.base64_max_bytes` (default 5 MB decoded) (`media.manage_media`) — bound by `media_upload` MCP tool! + - `POST /media/uploads/prepare` — creates single-use `summer_media_upload_tokens` row (5 min TTL) and returns `{upload_url, method: "PUT", expires_at, max_bytes}` (`media.manage_media`) — bound by `media_prepare_upload` MCP tool! + - `PUT /media/items/{id}` — update `alt`, `title`, `caption`, `folder_id` (`media.manage_media`) + - `DELETE /media/items/{id}` — hard delete DB row + `lagoon.AfterCommit` blob cleanup (`media.manage_media`) +- `type: mediafinder` form field (`modules/cabana/field_media.go`): + - YAML options: `mode: image | file` (default `image`), `multiple: bool` (default `false`), `folder: string` (optional default folder slug). + - Value stored on model: string URL or media item ID (or JSON array when `multiple: true`) — specifically, store the public media URL string (e.g. `/media//.`) or array of URLs so models stay decoupled and WinterCMS-like `mediafinder` conventions work cleanly, while also supporting resolving metadata via `GET /media/items`. +- Mail Images unification (`modules/cabana/mail_routes.go` & `mail_admin.go`, D-13): + - `POST /mail/images` writes into `modules/album` under default virtual folder `"mail"` (auto-created if absent) and returns the exact `AdminMailImage` JSON shape (`{id, fileName, title, url, thumbUrl}`) — plus optional additive `variants` — using absolute public URLs as required by email clients. + - `GET /mail/images` and `GET /mail/images/{id}` read from `album` (scoped to images, with folder `"mail"` prioritized/defaulted) AND stay compatible with existing `MailBrandSetting.LogoFileID` / backfilled rows. + - Idempotent backfill (`album.BackfillMailImages(ctx, db, bucket)`): copies metadata for existing `system_files` rows with `attachment_type = 'System\Models\MailImageLibrary' AND field = 'images'` into `summer_media_items` (folder `"mail"`, keyed by `legacy_file_id` so re-runs are no-ops and existing `/uploads/...` URLs remain untouched and valid). +- All new routes must be added to: + - `modules/cabana/admin_openapi.go` (swag annotations) -> `scripts/check-admin-openapi.sh` + - `modules/cabana/token_routes_test.go` (`tokenRouteClasses`) + - `modules/cabana/openapi_conformance_test.go` + +### 1.5 MCP Tools (`modules/pier`) +- `pier.Mount` (`modules/pier/pier.go`) compiles `pact.HasMCP` from `plugins []party.Plugin` and runs `warnUncoveredBackendWriteTools`. +- By registering a lightweight framework MCP provider plugin (`ID() == "summercms.media"`) in `surf/pier_on.go` (when admin is mounted), `pier`'s `prefixFor("summercms.media")` automatically yields prefix `media_`! +- The 7 MCP tools bind directly to cabana's `{backend.uri}/api/v1/media/...` routes with `Guard: "backend"`: + 1. `media_prepare_upload` -> `POST {api}/media/uploads/prepare` (`media.manage_media`) + 2. `media_upload` -> `POST {api}/media/items/base64` (`media.manage_media`) + 3. `media_list` -> `GET {api}/media/items` (`media.view_media`) + 4. `media_get` -> `GET {api}/media/items/{id}` (`media.view_media`) + 5. `media_update` -> `PUT {api}/media/items/{id}` (`media.manage_media`) + 6. `media_delete` -> `DELETE {api}/media/items/{id}` (`media.manage_media`, `Destructive: true`) + 7. `media_create_folder` -> `POST {api}/media/folders` (`media.manage_media`) +- Because `media` and `media:read` scopes cover `media.view_media` / `media.manage_media` on all HTTP methods, `warnUncoveredBackendWriteTools` emits **zero warnings** at boot! +- Note on `pier.maxRequestBody`: currently `4 << 20` (4 MiB) in `modules/pier/pier.go`! A 5 MB decoded base64 upload is ~6.67 MB encoded in JSON. We MUST raise `pier`'s body limit (or make it configurable / 8 MiB for MCP JSON-RPC calls) so a 5 MB decoded `media_upload` call succeeds without hitting 413! (Huge catch from reading `pier.go` line 38!) + +### 1.6 Admin Vue 3 SPA (`admin/` & `modules/boardwalk/dist`) +- Router (`admin/src/app/router.ts`): add `{ path: '/media', name: 'media', component: MediaView, meta: { shell: true } }`. +- Navigation (`PluginRail.vue` / `useNavigation`): expose a top-level **Media** entry (or rail icon) gated by `media.view_media` / `media.manage_media`. +- Components under `admin/src/components/media/`: + - `MediaBrowser.vue`: reusable folder tree + toolbar (upload button, drag-drop zone, search, type filter, grid/list toggle) + item grid/table + detail/metadata inspector drawer (`alt`, `title`, `caption`, folder move, copy URL, delete with published-URL-breakage confirmation modal). + - `MediaPickerModal.vue`: `reka-ui` `Dialog*` modal wrapping `MediaBrowser` in pick/insert mode (`mode: 'image' | 'file'`, `multiple?: boolean`, `defaultFolder?: string`). + - `MailImagePicker.vue` refactored to delegate to / reuse `MediaPickerModal` (defaulting to folder `mail`, `mode: 'image'`, absolute URLs). +- Form field (`admin/src/components/form/fields/MediaFinderField.vue`, registered as `'mediafinder'` in `admin/src/components/form/registry.ts`): preview thumbnail / file chip, pick from `MediaPickerModal`, clear, reorder/remove when `multiple: true`. +- Rebuilt `modules/boardwalk/dist` verified by `scripts/check-admin-dist.sh`. +- Phrasebook keys added in both `en` and `pl` under `backend::lang.media.*` and `backend::lang.api_tokens.group_media` / `scope_media*`. + +### 1.7 Sibling Repos (`sm-journal-plugin` & `vue-journal-layer`) +- `sm-journal-plugin`: + - `POST /_journal/api/v1/media/upload` (`controllers/api/media.go`): writes new uploads through `modules/album` (into default virtual folder `"journal"`, or requested subfolder under `"journal"`), preserving `{data: {url, path}}` and additively returning `id`, `width`, `height`, `variants`, `srcset`. + - Blog Editor (`assets/src/blogeditor/`): add "Choose from Media Library" action alongside direct upload (opening the admin Media Picker or calling `/api/v1/media/items`). + - Inline `srcset` enrichment (`controllers/api/posts.go` `serializePost` + `classes/enrich_media.go`): + - Stored `content` / `content_html` stays clean `` (D-14). + - During `serializePost` (and `Index` in a single batched query across all posts in the page, never N+1!), parse `` tokens referencing `/media//...`, batch-load matching `summer_media_items` by `short_id` in one `WHERE short_id IN ?` query, and inject `srcset=" 480w, 960w, ..."` + `sizes="(max-width: 768px) 100vw, 800px"` (and `width`/`height` if missing) into the serialized `content_html`. + - `classes/format_html.go` remains strict on write paths (no arbitrary attributes stored). +- `vue-journal-layer`: + - Ensure `sanitize-html` allow-list for rendered `content_html` permits `srcset`, `sizes`, `width`, `height`, `loading`, `decoding` on `` tags so SSR and client hydration preserve the enriched responsive attributes unchanged. + +--- + +## 2. Database Schema Design (`modules/album/migrations.go`) + +Three Postgres tables in `album.Migrations`: + +1. **`summer_media_folders`** + - `id` BIGSERIAL PK + - `parent_id` BIGINT NULL REFERENCES `summer_media_folders(id)` ON DELETE RESTRICT + - `name` VARCHAR(120) NOT NULL + - `slug` VARCHAR(120) NOT NULL + - `created_at`, `updated_at` TIMESTAMPTZ NOT NULL + - Unique index on `(COALESCE(parent_id, 0), slug)` so sibling folder slugs are unique at root and under each parent. + +2. **`summer_media_items`** + - `id` BIGSERIAL PK + - `short_id` VARCHAR(16) NOT NULL UNIQUE (12-char lowercase base32/alphanumeric `[a-z0-9]`, crypto/rand generated, collision-checked) + - `folder_id` BIGINT NULL REFERENCES `summer_media_folders(id)` ON DELETE RESTRICT + - `blob_key` VARCHAR(255) NOT NULL UNIQUE (`media//.`) + - `slug` VARCHAR(120) NOT NULL + - `file_name` VARCHAR(255) NOT NULL + - `content_type` VARCHAR(120) NOT NULL + - `file_size` BIGINT NOT NULL + - `width` INT NULL + - `height` INT NULL + - `sha256` CHAR(64) NOT NULL (indexed for search/inspection, NOT unique per D-08) + - `alt` TEXT NOT NULL DEFAULT '' + - `title` VARCHAR(255) NOT NULL DEFAULT '' + - `caption` TEXT NOT NULL DEFAULT '' + - `variants` JSONB NOT NULL DEFAULT '[]' (`[{width, height, key, url, size, content_type}]`) + - `legacy_file_id` BIGINT NULL UNIQUE (for idempotent Phase 35 `mailImageLibraryMorph` backfill; when set, `public_url` resolves to the preserved `/uploads/...` URL if `blob_key` is legacy, or copies/links safely without breaking existing URLs) + - `uploaded_by` BIGINT NULL (backend user ID) + - `created_at`, `updated_at` TIMESTAMPTZ NOT NULL + - Indexes: `(folder_id, created_at DESC)`, `(sha256)`, `(content_type)`. + +3. **`summer_media_upload_tokens`** + - `id` BIGSERIAL PK + - `token_hash` CHAR(64) NOT NULL UNIQUE (SHA-256 hex of 32-byte random base64url token) + - `created_by` BIGINT NOT NULL + - `folder_id` BIGINT NULL REFERENCES `summer_media_folders(id)` ON DELETE SET NULL + - `expected_filename` VARCHAR(255) NOT NULL + - `expected_content_type` VARCHAR(120) NOT NULL DEFAULT '' + - `max_bytes` BIGINT NOT NULL + - `expires_at` TIMESTAMPTZ NOT NULL + - `used_at` TIMESTAMPTZ NULL + - `created_at` TIMESTAMPTZ NOT NULL + - Index on `(expires_at)` for opportunistic cleanup. + +--- + +## 3. WebP Variant Pipeline (`modules/album/variants.go`) + +- Target widths: `[480, 960, 1600]`. +- Only runs for raster images passing `attach.IsAllowedImage(head)` (which already enforces `attach.MaxImagePixels` via `image.DecodeConfig` before full decode!). +- Decode once into `image.Image` (`jpeg`, `png`, `gif`, `webp` decoders registered). Record original `width` and `height`. +- For each target `w` in `[480, 960, 1600]` where `w < origWidth`: + - Compute proportional `h = max(1, int(math.Round(float64(origHeight)*float64(w)/float64(origWidth))))`. + - Resize with `golang.org/x/image/draw.CatmullRom.Scale(...)`. + - Encode with `webp.Encode(&buf, dst)`. + - Write to `bucket` at `media//-w.webp` with `ContentType: "image/webp"`. +- If the original is smaller than 480px (or already narrow) and not WebP, optionally emit a single WebP at original width so `srcset` still has a WebP option (or keep variants empty when no smaller breakpoint applies — emitting a WebP at original width when `origFormat != "webp"` ensures even small PNG/JPG infographics get WebP delivery!). +- On any failure during variant writing or DB insert, delete all written blob keys before returning the error (no orphan blobs). + +--- + +## 4. Validation Architecture (Nyquist) + +Final plan will carry full unit, Postgres integration, Vitest, OpenAPI, dist, and docs gates plus `scripts/check-phase37.sh`: +- `go vet ./...` and `go test -short ./...` +- Postgres tests (`go test ./modules/album ./modules/cabana ./modules/pier ./modules/surf ./modules/lagoon`) +- `npm --prefix admin run test`, `npm --prefix admin run typecheck` +- `scripts/check-admin-openapi.sh --check` +- `scripts/check-admin-dist.sh` +- `summer docs:build --check` and `go test ./cmd/summer -run TestDocsTree` +- Local cross-repo E2E proofs (`sm-journal-plugin` via temporary `GOWORK` / scratch `modfile`, `vue-journal-layer` via `npm test`) — leaving all submodule pointers clean and cutting zero tags per `AGENTS.md` / `CLAUDE.md` rule 5.