The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix: support LFS contributions and published brand icons
lefarcen420b7c78af86
diff --git a/.gitattributes b/.gitattributesindex 206fa73e..2c8a3e5c 100644--- a/.gitattributes+++ b/.gitattributes@@ -3,3 +3,5 @@# Integrity manifests describe exact third-party bytes, including license newlines.library/**/vendor/** -texttemplate-library/**/vendor/** -text+# Optional contribution media; existing imported small images keep their original Git bytes.+library/templates/catalog/*/source/assets/lfs/** filter=lfs diff=lfs merge=lfs -textdiff --git a/.gitignore b/.gitignoreindex 3639b7d5..f07770bc 100644--- a/.gitignore+++ b/.gitignore@@ -19,6 +19,5 @@ node_modules/.artifacts/studio/build/-# Reference videos and duplicate archives stay at CMS URLs.-library/templates/catalog/**/*.mp4+# Duplicate download archives are not contribution source.library/templates/catalog/**/*.zipdiff --git a/README.md b/README.mdindex ef4b0361..c4bdf99c 100644--- a/README.md+++ b/README.md@@ -419,7 +419,7 @@ Open the `studioUrl` or `previewUrl` printed by `npm start`, then open **TemplatSelect a template and choose **Recreate template** to copy the instruction for your agent. Keep projects and credentials outside the checkout; `MOTION_DATA_DIR` selects the workspace.-Source checkouts load templates from `library/templates/catalog/`. The local Studio and MCP use the same files; `openmotion_list_templates` returns a searchable local index, and `openmotion_get_template` returns local guide content and absolute source paths. Larger images and videos use existing CMS links. Local edits appear on the next catalog read.+Source checkouts load templates from `library/templates/catalog/`. The local Studio and MCP use the same files; `openmotion_list_templates` returns a searchable local index, and `openmotion_get_template` returns local guide content and absolute source paths. Imported large images and videos retain existing CMS links; new contribution media can use Git LFS. Local edits appear on the next catalog read.The plugin root is this checkout: `.codex-plugin/plugin.json` loads its `skills/` and `.mcp.json`, which launches the root `mcp.ts`. Start stdio with `npm run mcp` or use an absolute path in [manual MCP configuration](#manual-mcp). [Local template workflow](docs/template-repository.md#run-from-a-local-clone).diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex 44da10b3..11f767f3 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -20,7 +20,7 @@ Model Gateway remains a shared media-generation backend for MCP, using local Cod- The project sidebar opens as a modal drawer over the editor at every viewport size. It starts closed, leaves the editor dimensions unchanged, and closes via its button, outside click or Escape. The header toggle remains mounted for focus restoration; privacy, theme and language settings live in the drawer footer. Error and empty-session views retain a drawer toggle so users can select an existing project or create one. Project rows show names without dates; the heading offers a New project button instead of a count. Creation uses the existing save and revision guards before opening the blank project.- An empty, loaded root composition shows a centered import/drop prompt over the mounted preview and hides transport controls, including the placeholder duration. The empty state requires both no timeline clips and no authored preview content; loading, failed previews and nested compositions retain their existing states. Import uses the existing timeline gateway and file-drop pipeline. The empty timeline retains its drop target and ruler, with a muted dashed track sketch instead of a duplicate import prompt or button. Empty timelines disable zoom controls. A confirmed empty composition blocks new exports at both the settings button and the shared editor render-start handler, while existing export history remains available. Properties distinguish no content from no selection; small panel empty states share muted text and icon sizing. Preview zoom percentage and Fit sit in the MVP preview header, outside the picture. Clicking the percentage opens 50%, 75%, 100%, 150% and 200% presets in a compact opaque menu. The MVP hides the corner position navigator; existing zoom gestures and Fit remain available. Browser fullscreen is unavailable in the MVP, including its playback button and keyboard entry; workspace preview expansion remains available. Playback controls respond to their own container width: secondary-button gaps narrow below 420px, and speed/loop controls hide below 420px so timecode, play/pause and volume remain on one row. Preview and track volume use upward floating vertical sliders, opened by hover or keyboard focus; clicking the speaker still toggles mute. Editor controls share one neutral hover background for both ordinary and selected states, including visible keyboard focus and highlighted menu items. Primary Export actions retain their dark action hover surface. Disabled controls share one foreground token without per-control opacity, and never gain hover feedback. Official catalog/template surfaces and timeline clip bodies retain their existing presentation. The enabled play/pause icon uses the same action-color token as the header Export background, including hover.- The composition list places the full video first, preserves the remaining clip order, and marks the live preview target. Queued, loading, missing and failed covers share a muted gray OD placeholder without failure text; decoded covers replace it automatically. A confirmed empty root is omitted from this list using the same loaded-preview content check; when no clips remain, the panel shows a brief empty state. The MVP omits the duplicate preview breadcrumb; composition switching and existing return shortcuts remain available.-- The editor header keeps the OpenDesign logo, drawer toggle and template library on the left (the English entry is Template; Chinese remains 模板库), centers the editable project name, and places undo/redo and export on the right. Clearing the title and committing with blur or Enter saves the localized Untitled default; Escape cancels. A logo-only community link sits immediately before Export and opens the public Discord community in every interface language, with a localized accessible tooltip; external links open separately from the editor. Undo, redo and version history form one visual group with 4px internal gaps; the history group and community retain a 16px button gap. The community-to-Export button gap is 12px (18px from the 16px community icon to the Export edge), shifting only community and the three history icons right by 4px while Export and the other header content stay fixed. A decorative 1px by 16px divider in the shared border color sits between history and community without moving the buttons; it hides with the history group on narrow screens. Transient save/error status remains available. Workspace and export failures show concise causes and available next steps, with raw diagnostics behind expandable, copyable details. Workspace connection failures use a persistent single-line feedback toast at the top center with a Reconnecting status and no buttons or diagnostic details. The Reconnecting ellipsis animates without changing the toast width; reduced-motion preferences keep it static. Automatic polling waits 1.8 seconds after each completed attempt and removes the toast on recovery; it has no overall retry limit or explicit per-request timeout and does not start a stopped service. Other notice dismissal does not bypass write guards. Editor toasts stack at the top center; editor, connection and template-copy feedback share a top-layer host above native dialogs and ordinary overlays, without taking focus. Template-copy feedback retains its existing placement and three-second lifetime; identical notices replace their previous instance. Error toasts use the compact neutral feedback surface and concise recognized causes, with a dismiss button and no details icon or expandable diagnostics. Detailed error panels retain their diagnostic controls. Informational toasts disappear after three seconds without a close control; actionable error notices remain dismissible and do not auto-expire. Save-queue pauses use a brief, localized feedback toast without paths, diagnostics or a retry action; it expires after three seconds without clearing the write guard or claiming that failed edits were saved. The template library reuses the website catalog layout: brand/use-case/video-type facets, configured featured templates, search and sorting, without site navigation, promotional hero or footer. Repository metadata drives the source-checkout list; published CMS metadata and cache updates drive installations without the source catalog. The catalog selects the editor locale from a shared multilingual publication, falling back to English and then the Resource default; template-copy prompts support the same eleven UI languages. Previews, author/source links and editable-project opening remain available. The detail view keeps the motion.md download action (`motionDocumentUrl`) above its guide content (`styleDescription`, `reviewFocus`, `motionGuideUrl`). Recreate opens a separate prompt dialog; copied instructions never occupy the guide area.+- The editor header keeps the OpenDesign logo, drawer toggle and template library on the left (the English entry is Template; Chinese remains 模板库), centers the editable project name, and places undo/redo and export on the right. Clearing the title and committing with blur or Enter saves the localized Untitled default; Escape cancels. A logo-only community link sits immediately before Export and opens the public Discord community in every interface language, with a localized accessible tooltip; external links open separately from the editor. Undo, redo and version history form one visual group with 4px internal gaps; the history group and community retain a 16px button gap. The community-to-Export button gap is 12px (18px from the 16px community icon to the Export edge), shifting only community and the three history icons right by 4px while Export and the other header content stay fixed. A decorative 1px by 16px divider in the shared border color sits between history and community without moving the buttons; it hides with the history group on narrow screens. Transient save/error status remains available. Workspace and export failures show concise causes and available next steps, with raw diagnostics behind expandable, copyable details. Workspace connection failures use a persistent single-line feedback toast at the top center with a Reconnecting status and no buttons or diagnostic details. The Reconnecting ellipsis animates without changing the toast width; reduced-motion preferences keep it static. Automatic polling waits 1.8 seconds after each completed attempt and removes the toast on recovery; it has no overall retry limit or explicit per-request timeout and does not start a stopped service. Other notice dismissal does not bypass write guards. Editor toasts stack at the top center; editor, connection and template-copy feedback share a top-layer host above native dialogs and ordinary overlays, without taking focus. Template-copy feedback retains its existing placement and three-second lifetime; identical notices replace their previous instance. Error toasts use the compact neutral feedback surface and concise recognized causes, with a dismiss button and no details icon or expandable diagnostics. Detailed error panels retain their diagnostic controls. Informational toasts disappear after three seconds without a close control; actionable error notices remain dismissible and do not auto-expire. Save-queue pauses use a brief, localized feedback toast without paths, diagnostics or a retry action; it expires after three seconds without clearing the write guard or claiming that failed edits were saved. The template library reuses the website catalog layout: brand/use-case/video-type facets, configured featured templates, search and sorting, without site navigation, promotional hero or footer. Published brand metadata supplies catalog logos in both repository and CMS modes, with bundled legacy fallbacks and an initial when a logo fails. Repository metadata drives the source-checkout list; published CMS metadata and cache updates drive installations without the source catalog. The catalog selects the editor locale from a shared multilingual publication, falling back to English and then the Resource default; template-copy prompts support the same eleven UI languages. Previews, author/source links and editable-project opening remain available. The detail view keeps the motion.md download action (`motionDocumentUrl`) above its guide content (`styleDescription`, `reviewFocus`, `motionGuideUrl`). Recreate opens a separate prompt dialog; copied instructions never occupy the guide area.- The asset panel shows only the current project, with compact search/import controls, type filters, and a dedicated scrollable list. User-uploaded audio rows in My assets show full filenames with their original extensions and wrap long names within the panel; the generic Audio label is omitted, while duration and specific BGM/SFX/Voice labels remain when available. Official library sources are unchanged. Official animation-library cards reuse the composition list’s muted gray OD placeholder when preview media is absent or all available preview media fail; healthy posters and videos retain their existing behavior, and catalog entries remain available. Assets referenced by the current composition carry an In use badge (已使用 in Chinese); unused assets have no badge. MVP My assets deletion invokes the existing file-deletion handler directly from the menu, without a second confirmation; the full editor retains its confirmation. This does not introduce a new undo mechanism or alter official catalog assets. Usage filtering is omitted; used assets still sort first within each type. In both My assets and the official animation library, hover plays only the card thumbnail, while clicking opens a centered modal preview over a gray full-editor backdrop. The modal reuses Studio-styled playback, volume and speed controls; its play button stays centered, and speed/loop controls hide below 420px to avoid overlap. Volume and loop icons are 16px inside 28px buttons, and playback speed text is 12px; closing it restores access to the paused composition; previewing media does not add it to the project. The global cache view remains in source but has no editor entry in the MVP.- All supported content-insertion drops share persistent timeline feedback, including project images/video/audio, the composition list, official catalog items dropped on the timeline or preview, and local files dropped on the timeline or editor shell. Accepted drops immediately show a transient loading clip, including in an empty timeline; it remains until the saved clip appears, and failures remain dismissible at the placement. A local-file batch shows an upload placeholder immediately, then hands off without an empty frame to separate placeholders for the accepted uploaded paths; rejected files retain the upload handler's existing error feedback. Uploads retain the existing single multipart request. Catalog insertion buttons and overlays use the same state instead of progress toasts. Feedback starts at the requested time, reserves space between pending drops, and settles to the saved host identity, duration and placement once metadata and native collision resolution finish. Repeated drops remain independent. Composition insertions and catalog installs queue their writes; switching composition or project invalidates queued insertions and old selection changes. Known drag metadata bypasses duration probing, and concurrent requests for the same project asset share one in-flight probe without coalescing insertions. Unreadable durations fail visibly instead of inserting a five-second clip. Placeholders never enter project source or undo history. Drops on the Assets panel import files without inserting timeline content and retain that panel's importing state.- Panel positions are fixed. Export settings and render history live in a compact popover below the header Export button, outside the right panel. Both side groups can temporarily collapse into 48px vertical icon rails, giving their width to preview; the rail toggle restores the previous width and tab, while a module icon opens that module. Collapse does not remove panels or remount the player. Opening the MVP starts both sides collapsed and the timeline at 30% of the available dock height (subject to minimum sizes); users can then drag the divider to enlarge or reduce it. The fixed layout reserves at least 360px for preview, 260px for each expanded side panel. Side availability retains the existing conservative breakpoints, independently of the resizable minimums: below 740px both side groups and rails hide; from 740px to 1011px only one side can expand; wider hosts allow both only when their requested widths leave the preview floor intact. Opening a side through a toggle, module shortcut or programmatic activation uses the same fit check and closes the opposite side when necessary. Shrinking the host collapses expanded sides when they no longer fit; widening restores collapsed rails without automatically reopening panels. At widths smaller than the preview floor, preview uses the available workspace. Remembered expanded side widths remain available when reopening a side. Divider hover and drag change only the thin line to green. Divider resizing and per-project expanded-size persistence remain; panel movement, closing and layout presets are absent. Preview alone can temporarily expand within the editor workspace, keeping the host chat visible and the player mounted. Its header button or Escape restores the previous layout and playback position; expansion is not persisted across reloads.@@ -231,7 +231,7 @@ flowchart LR## Repository template contribution boundary-The public motion guidance catalog has unpacked text source, local images at most 100 KB, existing CMS rendition links for larger images, stable IDs and eleven-locale metadata in `library/templates/catalog/`. Reference videos and duplicate ZIP downloads remain in the existing CMS. Contributors open HTML examples directly and refresh source manifest hashes after edits; viewing linked images requires internet access. Original large-image identities and CMS rendition identities remain distinct in metadata. The policy job validates staged source, metadata, archive identity, manifest hashes, size budgets, the 100 KB local image/font limit and remote asset identities and new Git history. A CMS-compatible metadata exporter produces review files without upload credentials. Source checkouts default to this repository catalog. Studio and MCP use the same reader; local template Tools return a JSONL index, actual Markdown content and absolute source paths without starting a backend. Studio serves allowed guide files and small assets through local read-only routes. The source is resolved from the loaded plugin, not the caller working directory, and local edits are read on the next request. Explicit CMS mode and installations without catalog files retain publication caching. Catalog payloads and developer tools remain excluded from application distribution; website builds and installed releases continue to consume CMS publications. Reference guidance remains distinct from verified editable projects. See [the contribution/publication boundary](../template-repository.md).+The public motion guidance catalog has unpacked text source, local images at most 100 KB, existing CMS rendition links for larger images, stable IDs and eleven-locale metadata in `library/templates/catalog/`. Reference videos and duplicate ZIP downloads remain in the existing CMS. Contributors open HTML examples directly and refresh source manifest hashes after edits; viewing linked images requires internet access. Original large-image identities and CMS rendition identities remain distinct in metadata. New video/audio and large images/fonts can use Git LFS under each template's `source/assets/lfs/`, without CMS credentials or a required imported archive identity; optional `localMedia` provides local preview/poster paths. Pointer identities and staged LFS attributes are checked without downloading media, with 50 MiB per-file and 150 MiB per-template media limits. Clones can skip media and pull one template; local serving rejects unresolved pointers with a scoped pull command and verifies downloaded media hashes. Existing small imported assets remain ordinary Git. Remote LFS availability and independent external-account acceptance are separate checks. The policy job validates staged source, metadata, archive identity, manifest hashes, size budgets, the 100 KB local image/font limit and remote asset identities and new Git history. A CMS-compatible metadata exporter produces review files without upload credentials. Source checkouts default to this repository catalog. Studio and MCP use the same reader; local template Tools return a JSONL index, actual Markdown content and absolute source paths without starting a backend. Studio serves allowed guide files and small assets through local read-only routes. The source is resolved from the loaded plugin, not the caller working directory, and local edits are read on the next request. Explicit CMS mode and installations without catalog files retain publication caching. Catalog payloads and developer tools remain excluded from application distribution; website builds and installed releases continue to consume CMS publications. Reference guidance remains distinct from verified editable projects. See [the contribution/publication boundary](../template-repository.md).## 数据与边界diff --git a/docs/template-repository.md b/docs/template-repository.mdindex c0e8f68b..4598f3fe 100644--- a/docs/template-repository.md+++ b/docs/template-repository.md@@ -1,11 +1,11 @@# Repository-managed motion templates-The source of 286 published motion guidance templates lives in [the repository catalog](https://github.com/nexu-io/openmotion/tree/main/library/templates/catalog): guides, HTML examples, code, measurements and small images. Larger images use existing public CMS rendition links. Reference videos and duplicate ZIP downloads keep their public CMS URLs. Contributors need no CMS credentials to edit or preview. Viewing linked images requires internet access.+The source of 286 published motion guidance templates lives in [the repository catalog](https://github.com/nexu-io/openmotion/tree/main/library/templates/catalog): guides, HTML examples, code, measurements and small images. Larger images use existing public CMS rendition links. Reference videos and duplicate ZIP downloads keep their public CMS URLs. These existing links are migration inputs, not a requirement to upload new contributions to CMS. Contributors can add their own media through Git LFS without CMS access. Viewing existing linked images requires internet access.## Run from a local clone```sh-git clone https://github.com/nexu-io/openmotion.git+GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/nexu-io/openmotion.gitcd openmotionnpm cinpm run build:studio@@ -19,7 +19,7 @@ Keep user projects and credentials outside the checkout; `MOTION_DATA_DIR` can s- Source checkouts default to `MOTION_TEMPLATE_SOURCE=repository`. Studio search and MCP read `library/templates/catalog/` directly, without downloading the CMS catalog. A malformed local catalog fails explicitly.- `openmotion_list_templates` returns `source=repository`, an absolute JSONL `indexPath`, total and a hash-based `catalogVersion`. Search that file locally; each repository entry includes `localSource` paths.- `openmotion_get_template` reads local `TEMPLATE.md` instructions and returns `motionDocument={path, content}` plus absolute paths to metadata, Markdown, examples and the manifest. It does not need a running editor/backend to read repository templates.-- Studio uses the same repository reader and serves guides/small assets from `/api/template-source/<id>/<path>`. Linked large images and videos still need network access. Local changes are read on the next request; refresh the manifest after source edits.+- Studio uses the same repository reader and serves guides and downloaded media from `/api/template-source/<id>/<path>`. Linked large images and videos still need network access. Local changes are read on the next request; refresh the manifest after source edits.- An installation without the repository catalog defaults to `cms`, retaining the existing DEV/prod publication and cache behavior. Explicitly set `MOTION_TEMPLATE_SOURCE=cms` to inspect a CMS publication from a checkout. `MOTION_TEMPLATE_ENV` selects the CMS environment; it does not override repository mode.These imported guidance packages are not verified complete Studio projects. Read their motion rules and examples when authoring a new project; only entries with actual editable project files can use direct template-copy creation. Copied Agent prompts use the connected local plugin in all eleven supported interface languages.@@ -27,8 +27,8 @@ These imported guidance packages are not verified complete Studio projects. Read## Layout and storage- `catalog.json` records the imported publication URL/hash, ordered stable IDs, eleven locale slots and collection facets.-- Each `<id>/template.json` holds shared metadata, exact per-locale differences, `sourceArchive` (original CMS ZIP URL, byte length and SHA-256) and optional `remoteAssets` (original file identity plus CMS rendition URL, byte length and SHA-256).-- `<id>/TEMPLATE.md` explains usage, status and attribution. `<id>/source/` contains unpacked text source and images at most 100 KB. `source/manifest.json` records source paths, sizes and hashes, including the original identities of remotely linked images. `template.json.remoteAssets` maps those omitted originals to existing CMS renditions; HTML and Markdown references use the CMS URLs directly.+- Each `<id>/template.json` holds shared metadata, exact per-locale differences, optional `sourceArchive` (required only when retaining an imported CMS package URL) and optional `remoteAssets` (original file identity plus CMS rendition URL, byte length and SHA-256).+- `<id>/TEMPLATE.md` explains usage, status and attribution. `<id>/source/` contains unpacked text source, small ordinary-Git assets and optional LFS media under `assets/lfs/`. `source/manifest.json` records source paths, sizes and hashes, including the original identities of remotely linked images. `template.json.remoteAssets` maps those omitted originals to existing CMS renditions; HTML and Markdown references use the CMS URLs directly.- Images/fonts at most 100 KB use ordinary Git under `source/assets/`. The import keeps 1,419 images totaling 65.2 MB; 236 larger originals (32.5 MB) remain in CMS packages and use existing CMS WebP rendition links in the guides. Those renditions total 12.6 MB and are fetched by the browser when viewed. Source, metadata and local images total about 104 MB. Reference videos total 1.34 GB and remain remote. Keeping ZIP downloads remote avoids another 97.7 MB of duplicate files.All sizes above use decimal MB/GB. The initial import preserves published IDs, ordering, eleven locales, pending conversion state and empty project-file manifests. Guidance and authored examples remain distinct from verified editable Studio projects. Original-language source is accompanied by localized catalog metadata and existing translated download links; the source is not claimed to be translated into every locale.@@ -41,21 +41,47 @@ All sizes above use decimal MB/GB. The initial import preserves published IDs, o4. Stage changes, run `npm run templates:check -- <full-base-sha>` and `node --test tests/template-library.test.ts`. The checker reads the Git index, so unstaged files cannot conceal a staged violation.5. Open a PR against `main` with the exact ID, purpose, rights and actual preview/adaptation checks. Technical checks do not establish human visual acceptance.-For a new entry, create `template.json`, `TEMPLATE.md`, `source/motion.md`, `source/manifest.json` and `source/preview.html`; register its stable ID in `catalog.json` and provide every locale slot. Keep guide-only entries' project file lists empty until actual executable project files are supplied and verified through the existing contract.+For a new entry, no CMS URL or `sourceArchive` is required. Create `template.json`, `TEMPLATE.md`, `source/motion.md`, `source/manifest.json` and `source/preview.html`; register its stable ID in `catalog.json` and provide every locale slot. Keep guide-only entries' project file lists empty until actual executable project files are supplied and verified through the existing contract.-## Checks and budgets+## Contribute media without CMS access++Install [Git LFS](https://git-lfs.com/) and run `git lfs install --local` in your checkout. Put video, audio, large images and fonts under `<id>/source/assets/lfs/`. The repository's `.gitattributes` already tracks that directory; do not hand-write pointer files. Small images/fonts at most 100 KB may remain in ordinary Git under `source/assets/`, preserving the initial import's storage choice. Use LFS for new media when practical.++Reference contributed media with relative paths from HTML/Markdown. Optional `template.json.localMedia` selects locally served catalog previews and posters, for example:++```json+"localMedia": {+ "preview": "assets/lfs/reference.mp4",+ "poster": "assets/lfs/poster.webp"+}+```++Refresh the source manifest before staging, then push to your fork and open a PR. A normal `git push` uploads LFS objects through its pre-push hook; no CMS account or maintainer upload is required. The manifest records the real media's SHA-256 and size, whether the checkout contains downloaded bytes or only a canonical pointer.-Code/documentation files are limited to 1 MiB each, local image/font assets to 100 KB (100,000 bytes), and the catalog to 128 MiB. Small images/fonts belong in `source/assets/`; videos, audio, archives, generated output, symlinks and disguised binary source are rejected. The checker validates metadata, IDs/locales, required files, CMS archive identity and source manifest hashes. It also checks newly added history for oversized blobs or video/audio/archives that were subsequently deleted. Existing product assets and old history are outside this policy's scope.+Clone with `GIT_LFS_SKIP_SMUDGE=1` as above to avoid downloading every template. Before previewing one template, download only its media:++```sh+git lfs install --local --skip-smudge+git lfs pull --include="library/templates/catalog/<id>/source/assets/lfs/**" --exclude=""+```++Replace `<id>` with the selected template ID. If the clone came from a fork, pull from the remote containing that contribution's LFS objects. A missing LFS file is not usable media: the local source API returns `TEMPLATE_LFS_NOT_FETCHED` with the scoped pull command. Downloaded media must match its source manifest. No implicit CMS upload, automatic format conversion or background LFS download is performed.++## Checks and budgets-Large images/fonts use CMS links instead of LFS. Record the original file identity and verified CMS rendition identity in `template.json.remoteAssets`; replace relative source references with those URLs. Keep remote original entries in `source/manifest.json`: `templates:manifest` preserves them while refreshing local file hashes. The checker rejects duplicate local/remote paths, stale original hashes, malformed CMS URLs and LFS pointers. Review the budget before expanding it instead of silently raising limits.+- Ordinary Git: text at most 1 MiB per file; small images/fonts at most 100 KB (100,000 bytes); catalog Git contents at most 128 MiB, including pointer bytes.+- LFS: at most 50 MiB per media file and 150 MiB total locally stored media per template, counting the sizes declared by pointers rather than their tiny Git blobs.+- LFS media must live in `source/assets/lfs/`, have a canonical pointer and matching staged LFS attributes, and match the real media identity recorded in `source/manifest.json`.+- Raw video/audio in Git, oversized ordinary images, archives, generated output, symlinks, disguised binary source and unregistered files fail validation. New Git history is checked even when a large/raw file was subsequently deleted. Existing product assets and old history are outside this policy.+- Existing verified CMS links remain supported. Their original identities stay in `remoteAssets` and the source manifest; they must not duplicate a local file. New contributions need no CMS package URL.-CI's **Template library policy** job runs on every PR without media downloads or publishing credentials. Making it a required merge check is a separate branch-protection setting; this change does not configure it.+CI's **Template library policy** job checks metadata, staged content, pointers, manifest identities, budgets and new Git history without downloading media or using publication credentials. It does not establish remote LFS object availability. Reviewers must fetch the contribution's LFS media and preview it before acceptance; hosting quotas and a full independent external-account fork/push/review check remain operational acceptance tasks. Making this CI check required is a separate branch-protection setting; this change does not configure it.## Source to publication`npm run templates:export -- .artifacts/catalog-candidate.json` reconstructs the public CMS publication shape from repository metadata, including all eleven locales, ordering and collection facets. The initial export was deeply compared with the public snapshot for all 286 entries.-Export writes a file only. The imported publication identity remains for comparison; changed content requires a new identity through the normal content workflow. Package reviewed source, upload it through the existing CMS file workflow, update `sourceArchive` plus affected localized download URLs/hashes, then publish and check the resulting catalog with the existing website/plugin workflow. A metadata export does not prove that edited source has been uploaded.+Export writes a file only. The imported publication identity remains for comparison; changed content requires a new identity through the normal content workflow. CMS publication remains an internal maintainer operation, never a prerequisite for contributing or locally previewing a template. When publishing through the current CMS-backed website/install channel, package reviewed source, upload it through the existing CMS file workflow, update `sourceArchive` plus affected localized download URLs/hashes, then publish and check the resulting catalog with the existing website/plugin workflow. A metadata export does not prove that edited source has been uploaded.Source Studio and MCP consume repository edits locally. Website builds and installations without this catalog continue to consume the active CMS publication; their DEV/prod selection and caching remain in place. Merging repository source does not publish CMS content or change installed releases. The catalog and development tools are excluded from the positive application distribution list, so npm installation does not include the additional 104 MB.diff --git a/editor-server.ts b/editor-server.tsindex 9abc556a..911b6646 100644--- a/editor-server.ts+++ b/editor-server.ts@@ -4,7 +4,7 @@ import path from 'node:path';import type { IncomingMessage, ServerResponse } from 'node:http';import { pluginRoot } from './hyperframes.ts';-const mime: Record<string, string> = { '.jpg': 'image/jpeg', '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json', '.map': 'application/json', '.ttf': 'font/ttf', '.woff2': 'font/woff2', '.txt': 'text/plain' };+const mime: Record<string, string> = { '.jpg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json', '.map': 'application/json', '.ttf': 'font/ttf', '.woff2': 'font/woff2', '.txt': 'text/plain' };/** Only application bundle and design-system files are exposed, never Studio source or project files. */export async function serveEditorFile(url: URL, res: ServerResponse): Promise<boolean> {diff --git a/library/templates/catalog/README.md b/library/templates/catalog/README.mdindex fe47801b..89e214ef 100644--- a/library/templates/catalog/README.md+++ b/library/templates/catalog/README.md@@ -1,6 +1,6 @@# Motion template catalog-Browse and edit 286 published motion guidance templates. Guides, HTML examples and small images are here. Images over 100 KB load from existing public CMS links. Reference videos and original ZIP downloads stay at their existing CMS URLs.+Browse and edit 286 published motion guidance templates. Guides, HTML examples and small images are here. Images over 100 KB load from existing public CMS links. Imported reference videos and original ZIP downloads stay at their existing CMS URLs. New contribution media can use Git LFS without a CMS account; see [media contribution and download instructions](../../../docs/template-repository.md#contribute-media-without-cms-access).## Try one template@@ -35,12 +35,14 @@ The checker reads staged contents. The base SHA also enables checks of new Git h| --- | --- || Code, documentation and measurements | Ordinary Git, at most 1 MiB per file || Small images/fonts | Ordinary Git under `source/assets/`, at most 100 KB (100,000 bytes) per asset |-| Images/fonts over 100 KB | Existing public CMS links; retain original and rendition identities in `template.json.remoteAssets` |+| Images/fonts over 100 KB | Git LFS under `source/assets/lfs/`; existing imported CMS links retain their recorded identities || Complete catalog in ordinary Git | At most 128 MiB; initial import is about 104 MB |-| Video, audio and original ZIP downloads | CMS links; rejected in Git, including LFS pointers |+| Video and audio | Git LFS under `source/assets/lfs/`; existing imported references retain CMS links |+| LFS media budgets | At most 50 MiB per file and 150 MiB total local media per template |+| Original ZIP downloads | Existing links only; archives are not contribution source || Exports, dependencies and generated output | Outside catalog source; use ignored `.artifacts/` for local output |-The import keeps 1,419 small images (65.2 MB) in Git and links 236 larger originals (32.5 MB) through existing CMS WebP renditions. These renditions are 12.6 MB in total and load when viewing affected guides; the original JPGs remain in the published packages. No LFS installation or asset-download command is needed.+The import keeps 1,419 small images (65.2 MB) in Git and links 236 larger originals (32.5 MB) through existing CMS WebP renditions. These renditions are 12.6 MB in total and load when viewing affected guides; the original JPGs remain in the published packages. New LFS media needs Git LFS and a scoped pull before preview; contributors do not need a CMS account. See [the download and contribution steps](../../../docs/template-repository.md#contribute-media-without-cms-access).Submit PRs against `main`. CI runs **Template library policy** without CMS publishing credentials or media downloads. Repository branch protection must separately require the job to prevent merging a failed check.diff --git a/prism-templates.ts b/prism-templates.tsindex 56ee4a0d..6878bf4b 100644--- a/prism-templates.ts+++ b/prism-templates.ts@@ -6,7 +6,7 @@ import { catalogLocale } from './shared/template-locale.ts';import { templateConfig } from './shared/template-config.ts';import { libraryTemplates, templateRecipe } from './template-catalog.ts';import { copyTemplate } from './template-library.ts';-import { loadRepositoryCatalog, readRepositoryFile, repositoryCatalogRoot } from './shared/repository-template-catalog.ts';+import { loadRepositoryCatalog, lfsPointer, maxLfsAssetBytes, readRepositoryFile, repositoryCatalogRoot, repositoryMediaFile } from './shared/repository-template-catalog.ts';type TemplateFile = { path: string; url: string; bytes: number; sha256: string };type PrismTemplate = {@@ -19,7 +19,7 @@ type PrismTemplate = {};type Publication = {resourceId: string; environment: string; channel: string; publicationId: string;- defaultLocale: string; content: Record<string, { templates: PrismTemplate[] }>;+ defaultLocale: string; content: Record<string, { templates: PrismTemplate[]; brands?: { name: string; logoUrl: string }[] }>;};type Snapshot = { etag: string | null; publication: Publication; repository?: Awaited<ReturnType<typeof loadRepositoryCatalog>> };export type EditableTemplate = GalleryTemplate & { files?: TemplateFile[]; catalogVersion?: string; conversionStatus?: string; conversionNotes?: string };@@ -122,25 +122,35 @@ export class TemplateCatalog {}private templates(snapshot: Snapshot, requested = this.locale): EditableTemplate[] {- const remote: EditableTemplate[] = [...this.entries(snapshot.publication, requested)].sort((a, b) => a.sortOrder - b.sortOrder).map(item => ({- id: item.templateId, title: item.original.templateName, subtitle: item.original.category || 'Motion',- description: item.original.summary || '', kind: 'prism' as const, collection: 'example' as const,- tags: [item.original.promotionalUseCases, item.original.visualPresentation, item.original.motionTags].filter(Boolean).flatMap(value => value.split(/[,,·]/).map(tag => tag.trim()).filter(Boolean)),- duration: Number(item.original.durationSeconds) || undefined,- author: item.original.author || item.original.attributionNickname || '',- sourceUrl: item.original.sourceUrl, previewUrl: item.previewUrl, posterUrl: item.coverUrl,- files: item.files, catalogVersion: snapshot.repository?.version ?? snapshot.publication.publicationId,- conversionStatus: item.conversionStatus, conversionNotes: item.conversionNotes,- motionDocumentUrl: snapshot.repository ? `/api/template-source/${item.templateId}/motion.md` : item.motionDocumentUrl,- motionGuideUrl: snapshot.repository ? `/api/template-source/${item.templateId}/preview.html` : item.motionGuideUrl,- ...(snapshot.repository ? { localSource: snapshot.repository.sources.get(item.templateId) } : {}),- projectFileUrl: item.projectFileUrl, authorAvatarUrl: item.authorAvatarUrl,- styleDescription: item.original.styleDescription, reviewFocus: item.original.reviewFocus,- brand: item.brand, uses: splitTags(item.original.promotionalUseCases), styles: splitTags(item.original.visualPresentation),- industries: item.industries ?? [], creationModels: item.creationModels ?? [], colors: item.colors ?? [],- width: item.width, height: item.height, sortOrder: item.sortOrder, featuredOrder: item.featuredOrder ?? null,- hasHtmlProject: item.files.some(file => file.path === 'index.html'),- }));+ const locale = catalogLocale(Object.keys(snapshot.publication.content), requested, snapshot.publication.defaultLocale);+ const brands = new Map([+ ...(snapshot.publication.content.en?.brands ?? []),+ ...(snapshot.publication.content[locale]?.brands ?? []),+ ].map(brand => [brand.name, brand.logoUrl]));+ const remote: EditableTemplate[] = [...this.entries(snapshot.publication, requested)].sort((a, b) => a.sortOrder - b.sortOrder).map(item => {+ const localMedia = snapshot.repository?.records.get(item.templateId)?.localMedia;+ const localUrl = (name: string) => `/api/template-source/${item.templateId}/${name.split('/').map(encodeURIComponent).join('/')}`;+ return {+ id: item.templateId, title: item.original.templateName, subtitle: item.original.category || 'Motion',+ description: item.original.summary || '', kind: 'prism' as const, collection: 'example' as const,+ tags: [item.original.promotionalUseCases, item.original.visualPresentation, item.original.motionTags].filter(Boolean).flatMap(value => value.split(/[,,·]/).map(tag => tag.trim()).filter(Boolean)),+ duration: Number(item.original.durationSeconds) || undefined,+ author: item.original.author || item.original.attributionNickname || '',+ sourceUrl: item.original.sourceUrl, previewUrl: localMedia?.preview ? localUrl(localMedia.preview) : item.previewUrl,+ posterUrl: localMedia?.poster ? localUrl(localMedia.poster) : item.coverUrl,+ files: item.files, catalogVersion: snapshot.repository?.version ?? snapshot.publication.publicationId,+ conversionStatus: item.conversionStatus, conversionNotes: item.conversionNotes,+ motionDocumentUrl: snapshot.repository ? `/api/template-source/${item.templateId}/motion.md` : item.motionDocumentUrl,+ motionGuideUrl: snapshot.repository ? `/api/template-source/${item.templateId}/preview.html` : item.motionGuideUrl,+ ...(snapshot.repository ? { localSource: snapshot.repository.sources.get(item.templateId) } : {}),+ projectFileUrl: item.projectFileUrl, authorAvatarUrl: item.authorAvatarUrl,+ styleDescription: item.original.styleDescription, reviewFocus: item.original.reviewFocus,+ brand: item.brand, brandLogoUrl: brands.get(item.brand ?? ''), uses: splitTags(item.original.promotionalUseCases), styles: splitTags(item.original.visualPresentation),+ industries: item.industries ?? [], creationModels: item.creationModels ?? [], colors: item.colors ?? [],+ width: item.width, height: item.height, sortOrder: item.sortOrder, featuredOrder: item.featuredOrder ?? null,+ hasHtmlProject: item.files.some(file => file.path === 'index.html'),+ };+ });return [...remote, ...builtinTemplates];}@@ -190,7 +200,14 @@ export class TemplateCatalog {if (!/^[a-z][a-z0-9-]+$/.test(id) || !catalog.templateIds.includes(id)) throw new Error('Repository template not found');const manifest = JSON.parse((await readRepositoryFile(this.repositoryRoot, id + '/source/manifest.json')).toString());if (name !== 'manifest.json' && !manifest.files.some((file: { path: string }) => file.path === name)) throw new Error('Repository template source file not found');- return readRepositoryFile(this.repositoryRoot, id + '/source/' + name);+ const media = name.startsWith('assets/') && repositoryMediaFile.test(name);+ const bytes = await readRepositoryFile(this.repositoryRoot, id + '/source/' + name, media ? maxLfsAssetBytes : 1024 * 1024);+ if (lfsPointer(bytes)) throw Object.assign(new Error(`Template media is not downloaded. Run git lfs pull --include="library/templates/catalog/${id}/source/assets/lfs/**" --exclude="" from the checkout.`), { code: 'TEMPLATE_LFS_NOT_FETCHED' });+ if (media) {+ const expected = manifest.files.find((file: { path: string }) => file.path === name);+ if (expected.bytes !== bytes.length || expected.sha256 !== hash(bytes)) throw new Error('Template media does not match its source manifest');+ }+ return bytes;}private async downloadFile(file: TemplateFile): Promise<Buffer> {diff --git a/scripts/check-template-library.ts b/scripts/check-template-library.tsindex e33d3f2c..2d75d820 100644--- a/scripts/check-template-library.ts+++ b/scripts/check-template-library.ts@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';import { isUtf8 } from 'node:buffer';import { spawnSync } from 'node:child_process';import { isMain } from '../shared/entry.ts';+import { lfsPointer, maxLfsAssetBytes, maxTemplateAssetBytes, repositoryMediaFile } from '../shared/repository-template-catalog.ts';import {digest,assetFile,@@ -16,9 +17,8 @@ import {} from './template-library.ts';export const scope = 'library/templates/catalog/';-const videoOrArchive = /\.(?:mp4|mov|webm|m4v|avi|mp3|wav|ogg|m4a|aac|flac|zip|gz|tgz|tar|7z|motion)$/i;-const pointerPattern =- /^version https:\/\/git-lfs.github.com\/spec\/v1\noid sha256:([a-f0-9]{64})\nsize ([1-9][0-9]*)\n$/;+const archiveFile = /\.(?:zip|gz|tgz|tar|7z|motion)$/i;+const lfsPath = /^[^/]+\/source\/assets\/lfs\//;type IndexedFile = { name: string; mode: string; oid: string; bytes: Buffer };export function git(args: string[], cwd: string, input?: Buffer | string): Buffer {@@ -70,6 +70,7 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {oids.filter((oid) => sizes.get(oid)! <= maxFileBytes),);const files = new Map<string, IndexedFile>();+ const assetTotals = new Map<string, number>();let total = 0;const attributeOutput = git(['check-attr', '--cached', '-z', '--stdin', 'filter'],@@ -101,22 +102,34 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {errors.push(`${label}: invalid path`);}if (- videoOrArchive.test(label) ||+ archiveFile.test(label) ||/(?:^|\/)(?:node_modules|renders|dist|build|\.cache)(?:\/|$)/.test(label))- errors.push(`${label}: keep videos, audio, archives and generated outputs in CMS/outside Git`);- const pointer = pointerPattern.exec(bytes.toString());+ errors.push(`${label}: archives and generated outputs do not belong in template source`);+ const pointer = lfsPointer(bytes);const filter = filters.get(file.name);- if (pointer || filter === 'lfs') errors.push(`${label}: use CMS links for large assets instead of LFS`);+ const media = repositoryMediaFile.test(label);+ if (media) {+ const id = label.split('/')[0];+ assetTotals.set(id, (assetTotals.get(id) ?? 0) + (pointer?.bytes ?? size));+ }+ if (pointer || filter === 'lfs' || bytes.toString().startsWith('version https://git-lfs.github.com/spec/v1')) {+ if (!pointer || filter !== 'lfs' || !lfsPath.test(label) || !media)+ errors.push(`${label}: require a valid LFS pointer and staged LFS attributes in source/assets/lfs/`);+ if (pointer && pointer.bytes > maxLfsAssetBytes) errors.push(`${label}: LFS asset exceeds 50 MiB`);+ }else if (assetFile.test(label)) {- if (size > maxLocalAssetBytes) errors.push(`${label}: asset exceeds 100 KB; use a CMS link`);+ if (size > maxLocalAssetBytes) errors.push(`${label}: asset exceeds 100 KB; move it to source/assets/lfs/`);if (!/^[^/]+\/source\/assets\//.test(label))errors.push(`${label}: images/fonts belong in <id>/source/assets/`);- } else if (!isUtf8(bytes) || bytes.includes(0) || !textFile.test(label))+ } else if (media) errors.push(`${label}: video/audio must use Git LFS in source/assets/lfs/`);+ else if (!isUtf8(bytes) || bytes.includes(0) || !textFile.test(label))errors.push(`${label}: unsupported source or disguised binary content`);}if (total > 128 * 1024 * 1024)errors.push('Catalog Git contents exceed 128 MiB; review the catalog budget before expanding');+ for (const [id, bytes] of assetTotals)+ if (bytes > maxTemplateAssetBytes) errors.push(`${id}: template assets exceed 150 MiB`);const parse = (name: string) => {const file = files.get(scope + name);assert(file, 'Missing ' + name);@@ -145,13 +158,10 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {safePath(id);const record: TemplateRecord = parse(id + '/template.json');validateRecord(record, id, manifest.publication.locales);- assert(record.sourceArchive, 'Missing imported package identity');- validateArchive(record.sourceArchive);- assert.equal(- record.sourceArchive.url,- record.entry.motionDocumentUrl,- 'Archive must match primary package URL',- );+ if (record.sourceArchive) {+ validateArchive(record.sourceArchive);+ assert.equal(record.sourceArchive.url, record.entry.motionDocumentUrl, 'Archive must match primary package URL');+ } else assert(!record.entry.motionDocumentUrl, 'Imported package URL requires sourceArchive identity');for (const required of ['TEMPLATE.md','source/motion.md',@@ -166,6 +176,8 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {.filter((name) => name.startsWith(sourcePrefix) && name !== sourcePrefix + 'manifest.json').map((name) => name.slice(sourcePrefix.length)).sort();+ for (const name of Object.values(record.localMedia ?? {}))+ assert(sourcePaths.includes(name), 'Local media must be registered in the source manifest: ' + name);assert.deepEqual(sourceManifest.files.map((file: { path: string }) => file.path).sort(),[...sourcePaths, ...remoteAssets.keys()].sort(),@@ -184,8 +196,9 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {continue;}assert(source, 'Missing source/asset: ' + file.path);+ const pointer = lfsPointer(source.bytes);assert(- source.bytes.length === file.bytes && digest(source.bytes) === file.sha256,+ (pointer?.bytes ?? source.bytes.length) === file.bytes && (pointer?.sha256 ?? digest(source.bytes)) === file.sha256,'Source manifest mismatch: ' + file.path + '; run templates:manifest, then stage',);}@@ -220,17 +233,22 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {if (type !== 'blob') continue;if (Number(size) > maxFileBytes)errors.push(`History blob ${oid}: exceeds 1 MiB, even if deleted later`);- else if (videoOrArchive.test(names.get(oid) ?? ''))- errors.push(`History blob ${oid}: video/audio/archive must remain in CMS, even if deleted later`);- else if (assetFile.test(names.get(oid) ?? '') && Number(size) > maxLocalAssetBytes)- errors.push(- `History blob ${oid}: asset exceeds 100 KB; remove it from new history and use a CMS link`,- );- else if (!assetFile.test(names.get(oid) ?? '')) small.push(oid);+ else small.push(oid);}- for (const [oid, bytes] of blobs(cwd, small))- if (!isUtf8(bytes) || bytes.includes(0))+ for (const [oid, bytes] of blobs(cwd, small)) {+ const name = (names.get(oid) ?? '').slice(scope.length), pointer = lfsPointer(bytes);+ if (archiveFile.test(name)) errors.push(`History blob ${oid}: archives must stay outside source, even if deleted later`);+ else if (pointer) {+ if (!lfsPath.test(name) || !repositoryMediaFile.test(name) || pointer.bytes > maxLfsAssetBytes)+ errors.push(`History blob ${oid}: invalid LFS media path or size`);+ } else if (repositoryMediaFile.test(name) && !assetFile.test(name))+ errors.push(`History blob ${oid}: video/audio must use LFS, even if deleted later`);+ else if (assetFile.test(name)) {+ if (bytes.length > maxLocalAssetBytes || lfsPath.test(name))+ errors.push(`History blob ${oid}: asset exceeds 100 KB or bypasses LFS; remove it from new history`);+ } else if (!isUtf8(bytes) || bytes.includes(0))errors.push(`History blob ${oid}: raw binary media must be removed from new commits`);+ }}}return errors;@@ -242,6 +260,6 @@ if (isMain(import.meta.url)) {process.exitCode = 1;} elseconsole.log(- 'PASS: template metadata, localized identities, source, small local assets, CMS links and requested Git history',+ 'PASS: template metadata, source, small assets, LFS pointers/budgets, existing CMS links and requested Git history',);}diff --git a/scripts/template-library.ts b/scripts/template-library.tsindex 3d9cb497..3601398c 100644--- a/scripts/template-library.ts+++ b/scripts/template-library.ts@@ -4,14 +4,14 @@ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';import { inflateRawSync } from 'node:zlib';-import { loadRepositoryCatalog } from '../shared/repository-template-catalog.ts';+import { loadRepositoryCatalog, lfsPointer, repositoryAssetFile, repositoryMediaFile } from '../shared/repository-template-catalog.ts';import { isMain } from '../shared/entry.ts';export const catalogRoot = fileURLToPath(new URL('../library/templates/catalog/', import.meta.url));export const textFile = /\.(?:md|json|html?|css|[cm]?[jt]sx?|txt|ya?ml|toml|xml)$/i;export const maxFileBytes = 1024 * 1024;export const maxLocalAssetBytes = 100_000;-export const assetFile = /\.(?:png|jpe?g|webp|avif|gif|ico|woff2?|ttf|otf|psd|blend)$/i;+export const assetFile = repositoryAssetFile;const maxArchiveBytes = 50 * 1024 * 1024;const maxUnpackedBytes = 150 * 1024 * 1024;export const digest = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');@@ -30,6 +30,7 @@ export type TemplateRecord = {locales: Record<string, Partial<Entry>>;sourceArchive?: ArchiveLock;remoteAssets?: RemoteAsset[];+ localMedia?: { preview?: string; poster?: string };};export type CatalogManifest = {schemaVersion: number;@@ -75,6 +76,12 @@ export function validateRecord(record: TemplateRecord, id: string, locales: stri'Template locale set must match catalog',);const remoteAssets = record.remoteAssets ?? [];+ for (const [kind, name] of Object.entries(record.localMedia ?? {})) {+ safePath(name);+ assert(name.startsWith('assets/') && repositoryMediaFile.test(name), 'Local media must be in source/assets/');+ assert(kind === 'preview' || kind === 'poster', 'Unknown local media role');+ if (kind === 'poster') assert(assetFile.test(name), 'Local poster must be an image');+ }assert(Array.isArray(remoteAssets), 'Invalid remote assets');const remotePaths = new Set<string>();for (const asset of remoteAssets) {@@ -341,11 +348,9 @@ export async function refreshManifest(id: string, root = catalogRoot): Promise<vfor (const name of await sourceFiles(source)) {if (name === 'manifest.json') continue;const bytes = await readFile(path.join(source, safePath(name)));- assert(- !bytes.toString().startsWith('version https://git-lfs.github.com/spec/v1'),- 'Use CMS links for large assets instead of LFS',- );- files.push({ path: name, bytes: bytes.length, sha256: digest(bytes) });+ const pointer = lfsPointer(bytes);+ assert(!bytes.toString().startsWith('version https://git-lfs.github.com/spec/v1') || pointer, 'Malformed Git LFS pointer');+ files.push({ path: name, ...(pointer ?? { bytes: bytes.length, sha256: digest(bytes) }) });}assert.equal(new Set(files.map((file) => file.path)).size,diff --git a/server.ts b/server.tsindex e9c90f8b..d82fde98 100644--- a/server.ts+++ b/server.ts@@ -407,13 +407,17 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =const templateSource = url.pathname.match(/^\/api\/template-source\/([a-z][a-z0-9-]+)\/(.+)$/);if (templateSource && req.method === 'GET') {const name = decodeURIComponent(templateSource[2]);- const mime: Record<string, string> = { '.html': 'text/html', '.md': 'text/plain', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.avif': 'image/avif', '.gif': 'image/gif', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf' };+ const mime: Record<string, string> = { '.html': 'text/html', '.md': 'text/plain', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.avif': 'image/avif', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.m4v': 'video/mp4', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac' };const type = mime[path.extname(name).toLowerCase()];if (!type) return json(res, 404, { error: 'Unknown template source file' });try {const bytes = await templateCatalogFor(store.directory).sourceFile(templateSource[1], name);res.writeHead(200, { 'Content-Type': type, 'Content-Length': bytes.length }); res.end(bytes); return;- } catch { return json(res, 404, { error: 'Template source file not found' }); }+ } catch (error) {+ if ((error as { code?: string }).code === 'TEMPLATE_LFS_NOT_FETCHED')+ return json(res, 409, { code: 'TEMPLATE_LFS_NOT_FETCHED', error: (error as Error).message });+ return json(res, 404, { error: 'Template source file not found' });+ }}if (url.pathname === '/api/template-catalog' && req.method === 'GET') return json(res, 200, await templateCatalogFor(store.directory).page({locale: url.searchParams.get('locale') || undefined,diff --git a/shared/catalog.ts b/shared/catalog.tsindex e6a48487..86ec30b4 100644--- a/shared/catalog.ts+++ b/shared/catalog.ts@@ -18,7 +18,7 @@ export type GalleryTemplate = {variants?: GalleryTemplate[];motionDocumentUrl?: string; motionGuideUrl?: string; projectFileUrl?: string; authorAvatarUrl?: string;styleDescription?: string; reviewFocus?: string;- brand?: string; uses?: string[]; styles?: string[]; industries?: string[];+ brand?: string; brandLogoUrl?: string; uses?: string[]; styles?: string[]; industries?: string[];creationModels?: string[]; colors?: string[]; width?: number; height?: number;sortOrder?: number; featuredOrder?: number | null; hasHtmlProject?: boolean;localSource?: LocalTemplateSource;diff --git a/shared/repository-template-catalog.ts b/shared/repository-template-catalog.tsindex e8265f39..35740a7a 100644--- a/shared/repository-template-catalog.ts+++ b/shared/repository-template-catalog.ts@@ -5,6 +5,16 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';export const repositoryCatalogRoot = fileURLToPath(new URL('../library/templates/catalog/', import.meta.url));+export const maxLfsAssetBytes = 50 * 1024 * 1024;+export const maxTemplateAssetBytes = 150 * 1024 * 1024;+export const repositoryAssetFile = /\.(?:png|jpe?g|webp|avif|gif|ico|svg|woff2?|ttf|otf|psd|blend)$/i;+export const repositoryMediaFile = /\.(?:png|jpe?g|webp|avif|gif|ico|svg|woff2?|ttf|otf|psd|blend|mp4|mov|webm|m4v|avi|mp3|wav|ogg|m4a|aac|flac)$/i;+export function lfsPointer(bytes: Buffer): { sha256: string; bytes: number } | null {+ if (bytes.length > 1024) return null;+ const match = /^version https:\/\/git-lfs.github.com\/spec\/v1\noid sha256:([a-f0-9]{64})\nsize ([1-9][0-9]*)\n$/.exec(bytes.toString());+ if (!match || !Number.isSafeInteger(Number(match[2]))) return null;+ return { sha256: match[1], bytes: Number(match[2]) };+}export type PublishedTemplate = {templateId: string;original: Record<string, string>;@@ -30,7 +40,7 @@ export type LocalTemplateSource = {manifestPath: string;};-export async function readRepositoryFile(root: string, relative: string): Promise<Buffer> {+export async function readRepositoryFile(root: string, relative: string, limit = 1024 * 1024): Promise<Buffer> {assert(relative &&!/[\\\x00-\x1f:]/.test(relative) &&@@ -43,8 +53,8 @@ export async function readRepositoryFile(root: string, relative: string): Promisassert.equal(await realpath(filename), filename, 'Repository templates must not follow symlinks');const info = await lstat(filename);assert(- info.isFile() && info.size <= 1024 * 1024,- 'Repository template file must be a regular file at most 1 MiB',+ info.isFile() && info.size <= limit,+ 'Repository template file must be a regular file within its size limit',);return readFile(filename);}diff --git a/studio/src/motion/TemplateLibraryDialog.test.tsx b/studio/src/motion/TemplateLibraryDialog.test.tsxindex 8dcd04d1..6c472602 100644--- a/studio/src/motion/TemplateLibraryDialog.test.tsx+++ b/studio/src/motion/TemplateLibraryDialog.test.tsx@@ -39,6 +39,18 @@ it('shows featured/order and combines website facets without site chrome', asyncawait act(async () => button('清除筛选').click());expect(host.querySelectorAll('[data-template-id]')).toHaveLength(3);});+it('uses published brand logos and falls back to initials when a logo fails', async () => {+ vi.stubGlobal('fetch', vi.fn(async (url: string) => Response.json(url.endsWith('/integration') ? {} : {+ items: [{ ...items[0], brand: 'Notion', brandLogoUrl: 'https://example.com/notion.svg' }], catalogVersion: 'logos', next: null, total: 1,+ })));+ await mount();+ const brand = [...host.querySelectorAll<HTMLButtonElement>('aside button')].find(el => el.textContent?.includes('Notion'))!;+ const image = brand.querySelector('img')!;+ expect(image?.getAttribute('src')).toBe('https://example.com/notion.svg');+ await act(async () => image.dispatchEvent(new Event('error')));+ expect(brand.querySelector('img')).toBeNull();+ expect(brand.textContent).toContain('NNotion');+});it('copies the requested remote DEV prompt and preserves editable opening', async () => {const onOpen = await mount();await act(async () => button('First').click());diff --git a/studio/src/motion/TemplateLibraryDialog.tsx b/studio/src/motion/TemplateLibraryDialog.tsxindex 08ab4808..6451bcf8 100644--- a/studio/src/motion/TemplateLibraryDialog.tsx+++ b/studio/src/motion/TemplateLibraryDialog.tsx@@ -13,6 +13,13 @@ import kimiLogo from './template-brands/kimi.png';import pondLogo from './template-brands/pond.svg';const brandLogos: Record<string, string> = {Figma: figmaLogo, Lovable: lovableLogo, Linear: linearLogo, Firecrawl: firecrawlLogo, Kimi: kimiLogo, Pond: pondLogo};+function BrandIcon({ name, url }: { name: string; url?: string }) {+ const [failedUrl, setFailedUrl] = useState<string>();+ return <span className={styles.brandIcon} aria-hidden="true">{url && url !== failedUrl+ ? <img src={url} alt="" loading="lazy" onError={() => setFailedUrl(url)} />+ : name.slice(0, 1)}</span>;+}+type Props = { returnFocus?: HTMLElement | null; open: boolean; busy: boolean; error: string; onClose: () => void; onOpen: (id: string) => void };type Facet = 'brand' | 'uses' | 'styles' | 'industries' | 'creationModels' | 'colors' | 'ratio' | 'duration';const facets: [Facet, string][] = [@@ -122,6 +129,7 @@ export function TemplateLibraryDialog(props: Props) {return () => { controller.abort(); clearInterval(timer); };}, [props.open, attempt, locale]);const available = useMemo(() => facets.map(([key, label]) => ({ key, label, values: [...new Set(catalog.flatMap(item => values(item, key)))] })).filter(facet => facet.values.length), [catalog]);+ const logos = useMemo(() => new Map(catalog.flatMap(item => item.brand && item.brandLogoUrl ? [[item.brand, item.brandLogoUrl]] : [])), [catalog]);const hasFilters = Boolean(query || Object.values(selected).some(items => items?.length));const visible = useMemo(() => catalog.filter(item => {const text = [item.id, item.title, item.description, item.author, ...item.tags, ...facets.flatMap(([key]) => values(item, key))].join(' ').toLocaleLowerCase();@@ -167,7 +175,7 @@ export function TemplateLibraryDialog(props: Props) {<button className={styles.all} aria-current={!hasFilters ? 'page' : undefined} onClick={reset}>{t('All templates')}<span>{catalog.length}</span></button>{available.filter(facet => ['brand', 'uses', 'styles', 'industries', 'creationModels'].includes(facet.key)).map(facet => <details key={facet.key} open={facet.key === 'brand'}><summary>{t(facet.label)}</summary>{facet.values.slice(0, facet.key === 'brand' && !moreBrands ? 5 : undefined).map(value => <button key={value} aria-pressed={selected[facet.key]?.includes(value) ?? false} onClick={() => toggle(facet.key, value)}>- {facet.key === 'brand' && <span className={styles.brandIcon} aria-hidden="true">{brandLogos[value] ? <img src={brandLogos[value]} alt="" /> : value.slice(0, 1)}</span>}<span>{facet.key === 'brand' ? value : t(value)}</span><small>{catalog.filter(item => values(item, facet.key).includes(value)).length}</small>+ {facet.key === 'brand' && <BrandIcon name={value} url={logos.get(value) ?? brandLogos[value]} />}<span>{facet.key === 'brand' ? value : t(value)}</span><small>{catalog.filter(item => values(item, facet.key).includes(value)).length}</small></button>)}{facet.key === 'brand' && facet.values.length > 5 && <button onClick={() => setMoreBrands(!moreBrands)}>{t(moreBrands ? 'Show less' : 'Show more')}</button>}</details>)}diff --git a/tests/prism-templates.test.ts b/tests/prism-templates.test.tsindex 2c032a2e..66f46566 100644--- a/tests/prism-templates.test.ts+++ b/tests/prism-templates.test.ts@@ -154,12 +154,14 @@ test('gallery carries Prism facets and ordering without leaking project files',const directory = await mkdtemp(path.join(tmpdir(), 'motion-library-facets-'));t.after(() => rm(directory, { recursive: true, force: true }));const data = publication();+ Object.assign(data.content['zh-CN'], { brands: [{ name: 'Figma', logoUrl: 'https://example.com/figma.svg' }] });Object.assign(data.content['zh-CN'].templates[0], { motionDocumentUrl: 'https://example.com/motion.zip', motionGuideUrl: 'https://example.com/guide', brand: 'Figma', featuredOrder: 0, creationModels: ['Model A'], colors: ['blue'], industries: ['Design'], width: 1920, height: 1080 });Object.assign(data.content['zh-CN'].templates[0].original, { promotionalUseCases: 'Launch, Demo', visualPresentation: 'UI, Typography' });const catalog = new TemplateCatalog(directory, { fetch: async () => Response.json(data) });const { items } = await catalog.page({ category: 'all' });assert.equal(items[0].motionDocumentUrl, 'https://example.com/motion.zip'); assert.equal(items[0].motionGuideUrl, 'https://example.com/guide');assert.equal(items[0].brand, 'Figma'); assert.equal(items[0].featuredOrder, 0);+ assert.equal(items[0].brandLogoUrl, 'https://example.com/figma.svg');assert.deepEqual(items[0].uses, ['Launch', 'Demo']); assert.deepEqual(items[0].styles, ['UI', 'Typography']);assert.deepEqual(items[0].creationModels, ['Model A']); assert.equal(items[0].hasHtmlProject, true);assert.equal('files' in items[0], false);diff --git a/tests/repository-template-runtime.test.ts b/tests/repository-template-runtime.test.tsindex efbb7239..1a44bf55 100644--- a/tests/repository-template-runtime.test.ts+++ b/tests/repository-template-runtime.test.ts@@ -5,6 +5,7 @@ import { execFileSync } from 'node:child_process';import { tmpdir } from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { createHash } from 'node:crypto';import { TemplateCatalog } from '../prism-templates.ts';import { repositoryCatalogRoot, readRepositoryFile } from '../shared/repository-template-catalog.ts';import { WorkspaceStore } from '../workspace.ts';@@ -74,6 +75,22 @@ test('local source reads reject traversal, unlisted files and symlink escape', aawait assert.rejects(f.catalog.sourceFile(f.id, 'motion.md'), /symlinks/);});+test('repository media works without CMS, refuses missing LFS bytes and verifies downloaded contents', async t => {+ const f = await fixture(t), bytes = Buffer.alloc(1024 * 1024 + 1, 42);+ const sha256 = createHash('sha256').update(bytes).digest('hex');+ await mkdir(path.join(f.folder, 'source/assets/lfs'), { recursive: true });+ const relative = 'assets/lfs/reference.mp4', filename = path.join(f.folder, 'source', relative);+ await f.save(f.id + '/source/manifest.json', { files: [{ path: 'motion.md' }, { path: 'preview.html' }, { path: relative, bytes: bytes.length, sha256 }] });+ Object.assign(f.record, { localMedia: { preview: relative } }); await f.save(f.id + '/template.json', f.record);+ await writeFile(filename, `version https://git-lfs.github.com/spec/v1\noid sha256:${sha256}\nsize ${bytes.length}\n`);+ assert.equal((await f.catalog.page()).items[0].previewUrl, `/api/template-source/${f.id}/${relative}`);+ await assert.rejects(f.catalog.sourceFile(f.id, relative), { code: 'TEMPLATE_LFS_NOT_FETCHED' });+ await writeFile(filename, bytes);+ assert.deepEqual(await f.catalog.sourceFile(f.id, relative), bytes);+ await writeFile(filename, Buffer.alloc(bytes.length, 0));+ await assert.rejects(f.catalog.sourceFile(f.id, relative), /does not match/);+});+test('HTTP gallery and guide routes use the same repository source; copied prompts use the connected plugin', async t => {const work = await mkdtemp(path.join(tmpdir(), 'openmotion-local-http-')); t.after(() => rm(work, { recursive: true, force: true }));t.mock.method(globalThis, 'fetch', async () => { throw new Error('Unexpected network'); });diff --git a/tests/server.test.ts b/tests/server.test.tsindex 1034fc5d..b7d5d9a5 100644--- a/tests/server.test.ts+++ b/tests/server.test.ts@@ -5,10 +5,11 @@ import { transport } from './http.ts';import { handler } from '../server.ts';import { Readable, Writable } from 'node:stream';import type { IncomingMessage, ServerResponse } from 'node:http';+import { readdir } from 'node:fs/promises';test('wrapper serves the locally built Motion editor and hides local source/runtime files', () => fixture(async store => {const request = transport(store);- const html = await (await request('/')).text(); assert.match(html, /OpenDesign/);+ const html = await (await request('/')).text(); assert.match(html, /data-motion-studio/);assert.doesNotMatch(html, /<iframe/);const script = html.match(/src="(\/editor-assets\/[^\"]+\.js)"/)![1];const module = await request(script); assert.equal(module.status, 200);@@ -16,6 +17,10 @@ test('wrapper serves the locally built Motion editor and hides local source/runtfor (const url of ['/workspace.ts', '/.motion-data/project/index.html', '/node_modules/hyperframes/package.json', '/web/render.ts', '/studio/src/main.tsx', '/web/app.ts']) assert.equal((await request(url)).status, 404);assert.equal((await request('/web/design-system/fonts.css')).status, 200);assert.equal((await request('/design-system')).status, 200);+ const png = (await readdir(new URL('../studio/build/editor-assets/', import.meta.url))).find(file => file.endsWith('.png'))!;+ assert(png, 'The bundle contains the Kimi brand fallback');+ const image = await request('/editor-assets/' + png);+ assert.equal(image.status, 200); assert.equal(image.headers.get('content-type'), 'image/png');assert.equal((await request('/api/studio')).status, 503);}));test('HTTP source writes use the same revision contract and reject stale saves', () => fixture(async store => {diff --git a/tests/template-library.test.ts b/tests/template-library.test.tsindex 72aef552..c993d08a 100644--- a/tests/template-library.test.ts+++ b/tests/template-library.test.ts@@ -4,6 +4,7 @@ import { readFile, readdir } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';import test from 'node:test';+import { spawnSync } from 'node:child_process';import { zip } from '../scripts/package.ts';import { checkTemplateLibrary, git, scope } from '../scripts/check-template-library.ts';import { catalogRoot, cmsUrl, digest, exportCatalog, importCatalog, refreshManifest, safePath, unzip, validateRecord } from '../scripts/template-library.ts';@@ -88,20 +89,79 @@ test('edited source must refresh its manifest before staging a valid contributioassert.match(checkTemplateLibrary(f.root).join('\n'), /coverage mismatch/);await refreshManifest(f.id, f.catalog); f.stage(); assert.deepEqual(checkTemplateLibrary(f.root), []);});-test('video files, even LFS video pointers, and disguised binary text are rejected', t => {+test('raw videos, malformed pointers and disguised binary source are rejected', t => {const f = fixture(t);writeFileSync(path.join(f.directory, 'source/binary.txt'), Buffer.from([0, 1, 255]));- writeFileSync(path.join(f.directory, 'source/assets/video.mp4'), `version https://git-lfs.github.com/spec/v1\noid sha256:${'a'.repeat(64)}\nsize 2000\n`);- f.stage(); const errors = checkTemplateLibrary(f.root).join('\n'); assert.match(errors, /disguised binary/); assert.match(errors, /keep videos/);+ writeFileSync(path.join(f.directory, 'source/assets/video.mp4'), Buffer.from([0, 1, 255]));+ f.stage(); const errors = checkTemplateLibrary(f.root).join('\n');+ assert.match(errors, /disguised binary/); assert.match(errors, /video\/audio must use Git LFS/);});-test('large local images and LFS pointers are rejected in favor of CMS links', t => {+test('large ordinary images are rejected; valid LFS assets pass without downloading or CMS uploads', async t => {const large = fixture(t, 100001); large.stage();assert.match(checkTemplateLibrary(large.root).join('\n'), /asset exceeds 100 KB/);const f = fixture(t);- writeFileSync(path.join(f.root, '.gitattributes'), `${scope}**/assets/*.jpg filter=lfs diff=lfs merge=lfs -text\n`);- writeFileSync(path.join(f.directory, 'source/assets/frame.jpg'), `version https://git-lfs.github.com/spec/v1\noid sha256:${'a'.repeat(64)}\nsize 2000\n`);- f.sourceManifest.files[0].bytes = 2000; f.sourceManifest.files[0].sha256 = 'a'.repeat(64); f.json('source/manifest.json', f.sourceManifest);- f.stage(); assert.match(checkTemplateLibrary(f.root).join('\n'), /CMS links for large assets instead of LFS/);+ mkdirSync(path.join(f.directory, 'source/assets/lfs'), { recursive: true });+ writeFileSync(path.join(f.root, '.gitattributes'), `${scope}*/source/assets/lfs/** filter=lfs diff=lfs merge=lfs -text\n`);+ const name = 'source/assets/lfs/video.mp4';+ writeFileSync(path.join(f.directory, name), `version https://git-lfs.github.com/spec/v1\noid sha256:${'a'.repeat(64)}\nsize 2000000\n`);+ delete (f.record as any).sourceArchive; delete (f.record.entry as any).motionDocumentUrl; delete (f.record.entry as any).previewUrl;+ Object.assign(f.record, { localMedia: { preview: 'assets/lfs/video.mp4' } });+ f.json('template.json', f.record);+ await refreshManifest(f.id, f.catalog); f.stage();+ const manifest = JSON.parse(await readFile(path.join(f.directory, 'source/manifest.json'), 'utf8'));+ assert.deepEqual(manifest.files.find(file => file.path === 'assets/lfs/video.mp4'), { path: 'assets/lfs/video.mp4', bytes: 2000000, sha256: 'a'.repeat(64) });+ assert.deepEqual(checkTemplateLibrary(f.root), []);+ git(['commit', '-qm', 'Initial source'], f.root); const base = git(['rev-parse', 'HEAD'], f.root).toString().trim();+ writeFileSync(path.join(f.directory, name), `version https://git-lfs.github.com/spec/v1\noid sha256:${'b'.repeat(64)}\nsize 2000001\n`);+ await refreshManifest(f.id, f.catalog); f.stage(); git(['commit', '-qm', 'Update LFS media'], f.root);+ assert.deepEqual(checkTemplateLibrary(f.root, base), []);+ writeFileSync(path.join(f.root, '.gitattributes'), ''); f.stage();+ assert.match(checkTemplateLibrary(f.root).join('\n'), /staged LFS attributes/);+});+test('LFS budgets, pointer hashes and required filtering cannot be bypassed by checkout contents', async t => {+ const f = fixture(t);+ mkdirSync(path.join(f.directory, 'source/assets/lfs'), { recursive: true });+ writeFileSync(path.join(f.root, '.gitattributes'), `${scope}*/source/assets/lfs/** filter=lfs diff=lfs merge=lfs -text\n`);+ const save = (name: string, size: number) => writeFileSync(path.join(f.directory, 'source/assets/lfs', name), `version https://git-lfs.github.com/spec/v1\noid sha256:${'a'.repeat(64)}\nsize ${size}\n`);+ save('video.mp4', 50 * 1024 * 1024 + 1); await refreshManifest(f.id, f.catalog); f.stage();+ assert.match(checkTemplateLibrary(f.root).join('\n'), /LFS asset exceeds 50 MiB/);+ for (let i = 0; i < 4; i++) save(`clip-${i}.mp4`, 40 * 1024 * 1024);+ await refreshManifest(f.id, f.catalog); f.stage();+ assert.match(checkTemplateLibrary(f.root).join('\n'), /template assets exceed 150 MiB/);+ save('video.mp4', 1234); f.stage();+ assert.match(checkTemplateLibrary(f.root).join('\n'), /Source manifest mismatch/);+ writeFileSync(path.join(f.directory, 'source/assets/lfs/video.mp4'), 'raw video with no clean filter'); f.stage();+ assert.match(checkTemplateLibrary(f.root).join('\n'), /valid LFS pointer/);+});+test('real Git LFS pushes media and supports a pointer-only clone followed by a scoped pull', {+ skip: spawnSync('git', ['lfs', 'version']).status !== 0,+}, async t => {+ const f = fixture(t);+ git(['config', 'core.hooksPath', '.git/hooks'], f.root);+ git(['lfs', 'install', '--local', '--skip-smudge'], f.root);+ writeFileSync(path.join(f.root, '.gitattributes'), `${scope}*/source/assets/lfs/** filter=lfs diff=lfs merge=lfs -text\n`);+ mkdirSync(path.join(f.directory, 'source/assets/lfs'), { recursive: true });+ const name = scope + f.id + '/source/assets/lfs/video.mp4';+ const bytes = Buffer.alloc(2 * 1024 * 1024, 42);+ writeFileSync(path.join(f.root, name), bytes);+ await refreshManifest(f.id, f.catalog);+ git(['add', '.'], f.root);+ assert.deepEqual(checkTemplateLibrary(f.root), []);+ assert.match(git(['show', ':' + name], f.root).toString(), /oid sha256:/);+ git(['commit', '-qm', 'Contribute local LFS media'], f.root);+ const remote = f.root + '-remote.git', clone = f.root + '-clone';+ t.after(() => { rmSync(remote, { recursive: true, force: true }); rmSync(clone, { recursive: true, force: true }); });+ git(['init', '--bare', remote], f.root);+ git(['remote', 'add', 'origin', remote], f.root);+ git(['push', '-u', 'origin', 'main'], f.root);+ git(['symbolic-ref', 'HEAD', 'refs/heads/main'], remote);+ git(['-c', 'filter.lfs.smudge=git-lfs smudge --skip -- %f', '-c', 'filter.lfs.process=git-lfs filter-process --skip', 'clone', remote, clone], f.root);+ assert.match((await readFile(path.join(clone, name), 'utf8')), /version https:\/\/git-lfs/);+ git(['lfs', 'install', '--local', '--skip-smudge'], clone);+ git(['lfs', 'pull', '--include=' + scope + f.id + '/source/assets/lfs/**', '--exclude='], clone);+ const downloaded = await readFile(path.join(clone, name));+ assert.equal(downloaded.length, bytes.length); assert.equal(digest(downloaded), digest(bytes));+ assert.deepEqual(checkTemplateLibrary(clone), []);});test('verified remote renditions replace large original files, preserve provenance and survive source edits', async t => {const f = fixture(t, 100001);@@ -137,8 +197,8 @@ test('adding then deleting large blobs and videos cannot hide new Git history grrmSync(path.join(f.directory, 'source/assets/large.jpg'));f.stage(); git(['commit', '-qm', 'Remove unwanted data'], f.root);assert.deepEqual(checkTemplateLibrary(f.root), []);- const errors = checkTemplateLibrary(f.root, base).join('\n'); assert.match(errors, /exceeds 1 MiB, even if deleted/); assert.match(errors, /video\/audio\/archive must remain in CMS/);- assert.match(errors, /asset exceeds 100 KB; remove it from new history/);+ const errors = checkTemplateLibrary(f.root, base).join('\n'); assert.match(errors, /exceeds 1 MiB, even if deleted/); assert.match(errors, /video\/audio must use LFS/);+ assert.match(errors, /asset exceeds 100 KB or bypasses LFS; remove it from new history/);});test('metadata and unregistered directories cannot bypass template validation', t => {const f = fixture(t); f.record.templateId = 'wrong'; f.json('template.json', f.record);