Skip to content

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.

[OPEND-5244] chore: slim clones and prepare final PR media before squash merge (#344)

open-design-crew[bot]c7212ad34330
diff --git a/.gitattributes b/.gitattributes
index 2c8a3e5c..5982dd8d 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -5,3 +5,9 @@ library/**/vendor/** -text
template-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 -text
+
+# Optional full-length reference films and standalone template archives.
+docs/readme/**/*.mp4 filter=lfs diff=lfs merge=lfs -text
+examples/**/*.mp4 filter=lfs diff=lfs merge=lfs -text
+library/**/*.mp4 filter=lfs diff=lfs merge=lfs -text
+library/**/*.motion filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 96dcf384..c03395d3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,12 +46,23 @@ jobs:
uses: actions/setup-node@v6
with:
node-version: '26.11.1'
- - name: Check template data, storage policy and added history
+ - name: Require Squash merges for sanitized media history
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ # GraphQL variables are passed through gh fields, not expanded by the shell.
+ # shellcheck disable=SC2016
+ gh api graphql -f owner="$GITHUB_REPOSITORY_OWNER" -f repo="${GITHUB_REPOSITORY#*/}" \
+ -f query='query($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed } }' \
+ --jq '.data.repository | if .squashMergeAllowed and (.mergeCommitAllowed | not) and (.rebaseMergeAllowed | not) then "Squash-only merge policy confirmed" else error("Enable Squash merge only before accepting cleaned media PRs") end'
+ - name: Check the final merge tree and media policy
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
run: |
if [[ "$BASE_SHA" =~ ^0+$ ]]; then unset BASE_SHA; fi
- npm run templates:check
+ npm run templates:check -- --final-tree
+ npm run storage:check -- --final-tree
+ node --test tests/repository-storage.test.ts tests/media-transfer.test.ts
node --test tests/template-library.test.ts
maintainability:
@@ -101,12 +112,22 @@ jobs:
steps:
- name: Checkout
uses: actions/[email protected]
+ - name: Cache optional LFS media
+ uses: actions/cache@v4
+ with:
+ path: .git/lfs/objects
+ key: optional-lfs-${{ runner.os }}-${{ hashFiles('**/*.mp4', '**/*.motion', '!library/templates/catalog/**') }}
+ restore-keys: optional-lfs-${{ runner.os }}-
- name: Setup pinned Node
uses: actions/setup-node@v6
with:
node-version: '26.11.1'
cache: npm
cache-dependency-path: package-lock.json
+ - name: Download full-bundle media explicitly
+ run: |
+ git lfs pull --include="docs/readme/**,library/**,examples/**" --exclude="library/templates/catalog/**"
+ npm run media:pull
- name: Restore rendering package downloads
uses: actions/cache@v4
with:
diff --git a/.github/workflows/motion-candidate.yml b/.github/workflows/motion-candidate.yml
index 29251aa6..1a195f98 100644
--- a/.github/workflows/motion-candidate.yml
+++ b/.github/workflows/motion-candidate.yml
@@ -64,6 +64,17 @@ jobs:
path: source
ref: ${{ steps.source.outputs.source_sha }}
persist-credentials: false
+ - name: Cache optional LFS media
+ uses: actions/cache@v4
+ with:
+ path: source/.git/lfs/objects
+ key: optional-lfs-${{ runner.os }}-${{ hashFiles('source/**/*.mp4', 'source/**/*.motion', '!source/library/templates/catalog/**') }}
+ restore-keys: optional-lfs-${{ runner.os }}-
+ - name: Download full-bundle media explicitly
+ working-directory: source
+ run: |
+ git lfs pull --include="docs/readme/**,library/**,examples/**" --exclude="library/templates/catalog/**"
+ node scripts/repository-media.ts
- name: Scan tracked source before dependency installation
run: |
node control/.github/scripts/motion-scan.mjs install "$RUNNER_TEMP/scanner"
diff --git a/.github/workflows/prepare-pr-media.yml b/.github/workflows/prepare-pr-media.yml
new file mode 100644
index 00000000..d41d3af7
--- /dev/null
+++ b/.github/workflows/prepare-pr-media.yml
@@ -0,0 +1,52 @@
+name: Prepare PR media
+
+# Manual, final-review preparation only. Never execute pull_request code with credentials.
+on:
+ workflow_dispatch:
+ inputs:
+ pull_number:
+ description: 'Reviewed PR number; prepare its final media before Squash merge'
+ required: true
+ type: string
+
+permissions:
+ contents: read
+
+concurrency:
+ group: prepare-media-${{ inputs.pull_number }}
+ cancel-in-progress: false
+
+jobs:
+ prepare:
+ if: github.ref == 'refs/heads/main' && github.repository == 'nexu-io/openmotion'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ steps:
+ - name: Checkout trusted control code only
+ uses: actions/[email protected]
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: actions/setup-node@v6
+ with:
+ node-version: '26.11.1'
+ - name: Verify required credentials are configured
+ env:
+ OPENMOTION_MEDIA_MAINTAINER_TOKEN: ${{ secrets.OPENMOTION_MEDIA_MAINTAINER_TOKEN }}
+ AWS_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_RELEASES_AK }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_RELEASES_SK }}
+ run: |
+ test -n "$OPENMOTION_MEDIA_MAINTAINER_TOKEN" || { echo 'Configure the maintainer token for original-PR branch edits.'; exit 1; }
+ test -n "$AWS_ACCESS_KEY_ID" && test -n "$AWS_SECRET_ACCESS_KEY"
+ aws --version
+ - name: Transfer, verify and update the original PR
+ env:
+ MEDIA_PR: ${{ inputs.pull_number }}
+ OPENMOTION_MEDIA_MAINTAINER_TOKEN: ${{ secrets.OPENMOTION_MEDIA_MAINTAINER_TOKEN }}
+ AWS_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_RELEASES_AK }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_RELEASES_SK }}
+ AWS_EC2_METADATA_DISABLED: 'true'
+ AWS_PAGER: ''
+ MOTION_R2_ENDPOINT: ${{ vars.CLOUDFLARE_R2_RELEASES_URL }}
+ MOTION_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_RELEASES_BUCKET }}
+ run: node scripts/prepare-pr-media.ts "$MEDIA_PR" --apply
diff --git a/.lfsconfig b/.lfsconfig
new file mode 100644
index 00000000..2cf1bce1
--- /dev/null
+++ b/.lfsconfig
@@ -0,0 +1,2 @@
+[lfs]
+ fetchexclude = *
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 21130b8b..5079457a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -17,7 +17,7 @@ Designers, creators, prompt authors and engineers are all welcome. The [OpenMoti
Use the [entry checklist](library/ENTRY_TEMPLATE.md), link the new entry from its collection, and preserve sources and licenses. Label references, recipes and editable examples accurately. Adding a folder does not register it in Studio, the MCP workflow registry or the default five-Skill installation. Packaging uses an explicit file list.
-For published motion guidance source and locale metadata, use the [catalog contribution loop](https://github.com/nexu-io/openmotion/tree/main/library/templates/catalog#change-a-template). Keep videos at CMS URLs; stage changes before running the scoped storage-policy check.
+For published motion guidance source and locale metadata, use the [catalog contribution loop](https://github.com/nexu-io/openmotion/tree/main/library/templates/catalog#change-a-template). Stage changes before running the storage-policy check. New media needs no CMS account; maintainers prepare final media on the original PR before Squash merge.
## PR workflow
@@ -34,3 +34,7 @@ Use the PR Actions summary to review new duplicate fragments and unused code or
Only deliberately public documentation belongs here. Do not commit credentials, internal links, private plans, workstation paths or user projects. Distribution uses the positive list in `scripts/distribution.ts`; newly shipped files require an explicit decision. Preserve all upstream attribution and license notices. Do not add telemetry or publish a package without a separate decision.
Contributions are licensed under the repository's [Apache-2.0 license](LICENSE); vendored components retain their own terms. This migration branch is for review only and must not be merged or published automatically.
+
+## Repository media and size
+
+Keep embedded README previews directly readable. Full videos and optional template archives use Git LFS with downloads excluded by default. Follow [storage, scoped downloads and contribution checks](docs/repository-storage.md); run `npm run storage:check` after staging. For contributed media, use the documented **Prepare PR media** Action after final review; contributors do not need upload credentials.
diff --git a/README.md b/README.md
index c4bdf99c..0929d8e9 100644
--- a/README.md
+++ b/README.md
@@ -408,13 +408,15 @@ If MCP tools are missing or fail to connect, use the installed [connection diagn
Use Git, npm and **Node.js 26.11.1**. Source-based preview and export also need Chrome/Chromium and FFmpeg/FFprobe. [Runtime setup](docs/usage.md)
```sh
-git clone https://github.com/nexu-io/openmotion.git
+git clone --depth 1 https://github.com/nexu-io/openmotion.git
cd openmotion
npm ci
npm run build:studio
npm start
```
+Full reference videos and optional template archives download through Git LFS only when requested. README images/GIFs and built-in templates remain available directly. See [clone size and optional media downloads](docs/repository-storage.md).
+
Open the `studioUrl` or `previewUrl` printed by `npm start`, then open **Template library**. Startup reuses a compatible service for the same workspace or selects an available local port. The service keeps running in the background after the launcher exits.
Select 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.
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 42a20af1..dc9384be 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -75,7 +75,7 @@ Motion Design 的资源单位进一步明确为“创作规则 + Agent 方法 +
### README 与示例资源闭环
-[本地资源契约](../readme/RESOURCES.md)覆盖英文、简体中文和日文 README(共四个文件)及其场景、对比、精选集合页中的完整视频、GIF、封面和贡献者头像,以及六个 Motion Design 工程、四个展示组件、三个 Studio 原生模板和 Presenter Tech 包需要的素材、浏览器脚本与字体。页面展示媒体使用仓库文件;外部官方活动可通过明确标记的链接跳转观看。品牌案例的来源与校验值另见 [展示清单](../readme/brand-showcase/manifest.json),架构图的封面同款视觉、创作流程与 Motion.md 内部品牌层级见[图示及生成记录](../readme/diagrams/ARTWORK.md);文字架构继续保留可检索的模块职责与边界。校验脚本检查本地引用和哈希,捕获器阻断非本机网络请求。所有分发格式继续使用正向清单。894 条发现目录仍是索引,不能把精选资源闭环写成整个目录已镜像;工具初次安装、云模型与原作者网站也不属于离线资源承诺。
+[本地资源契约](../readme/RESOURCES.md)覆盖英文、简体中文和日文 README(共四个文件)及其场景、对比、精选集合页中的完整视频、GIF、封面和贡献者头像,以及六个 Motion Design 工程、四个展示组件、三个 Studio 原生模板和 Presenter Tech 包需要的素材、浏览器脚本与字体。Embedded README images and GIFs remain ordinary Git files. Full reference/demo videos and the optional Presenter Tech archive retain their paths and exact identities in Git LFS, with downloads excluded by default and scoped pulls documented in [repository storage](../repository-storage.md). Complete bundles hydrate those resources explicitly and reject unresolved pointers; selected Library handoffs require downloaded media. Existing offline resource guarantees apply after that hydration. Shallow clones avoid old history; this migration does not rewrite it. Transferred optional media is registered in `repository-media.json` and can be fetched by scope with `media:pull`; existing LFS media and its immutable legacy recovery pin remain supported. External official campaigns remain explicitly linked.品牌案例的来源与校验值另见 [展示清单](../readme/brand-showcase/manifest.json),架构图的封面同款视觉、创作流程与 Motion.md 内部品牌层级见[图示及生成记录](../readme/diagrams/ARTWORK.md);文字架构继续保留可检索的模块职责与边界。校验脚本检查本地引用和哈希,捕获器阻断非本机网络请求。所有分发格式继续使用正向清单。894 条发现目录仍是索引,不能把精选资源闭环写成整个目录已镜像;工具初次安装、云模型与原作者网站也不属于离线资源承诺。
### 创作资源与贡献架构
@@ -232,7 +232,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. 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).
+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 the final merge tree, metadata, archive identity, manifest hashes, size budgets, the 100 KB local image/font limit and remote asset identities after confirming Squash-only repository settings. A maintainer-started Prepare PR media Action runs trusted main code, reads PR blobs as data, uploads final changed media to immutable public R2 keys and hash-verifies public downloads before appending a cleanup commit to the original PR. Fork edits require a maintainer user token and contributor permission; the default CI token is insufficient. Source manifests retain original identities, guide links become public URLs and Studio/MCP share these remote-media records. Upload failures or PR changes stop the write; the Action never approves or merges the PR. CI and required review run on the cleanup commit before ordinary Squash merge. This replaces repeated draft uploads with a final-review preparation; no automatic upload is triggered by contributor pushes. Workflow registration, token setup and a real fork/R2 activation check remain necessary before operational use. 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/readme/RESOURCES.md b/docs/readme/RESOURCES.md
index e6adce5e..27f19728 100644
--- a/docs/readme/RESOURCES.md
+++ b/docs/readme/RESOURCES.md
@@ -2,6 +2,8 @@
Embedded README images and previews are local files shared by the English, Simplified Chinese and Japanese editions. Current Motion template cards link to their public detail pages. Presenter references have no online template link. The repository also retains earlier films and editable resources for reuse and attribution.
+Full reference videos and the optional template archive use Git LFS at the same paths. Embedded README images and GIFs remain in ordinary Git and display without LFS downloads. Fetch the desired media before watching complete videos, materializing an optional Library profile, or verifying full resource hashes; see [scoped download commands](../repository-storage.md#download-only-what-you-need).
+
## Retained local collection
| Resource | Local entry | Integrity and reuse |
@@ -30,8 +32,9 @@ Node, a WebGL-capable browser, FFmpeg and the Presenter Tech Python/Node executi
Run from the repository root:
```sh
+git lfs pull --include="docs/readme/**,library/**,examples/**" --exclude="library/templates/catalog/**"
node scripts/check-readme-resources.mjs
-node --test tests/readme-resources.test.ts tests/openmotion-design-remix.test.ts
+node --test tests/readme-resources.test.ts tests/motion-design-remix.test.ts
```
The deterministic checks reject embedded remote images, remote video links, missing local references and changed resource hashes. The Motion Design capture helper blocks external requests while rendering. New documentation/resource files also need an explicit entry in `scripts/distribution.ts`. Preserve source credits and third-party licenses; update the relevant manifest when intentionally changing a file. A source URL in a manifest is provenance, not a runtime fallback.
diff --git a/docs/readme/brand-showcase/rea-dual-role.mp4 b/docs/readme/brand-showcase/rea-dual-role.mp4
index cd922d94..30682404 100644
Binary files a/docs/readme/brand-showcase/rea-dual-role.mp4 and b/docs/readme/brand-showcase/rea-dual-role.mp4 differ
diff --git a/docs/readme/brand-showcase/rea-unboxing.mp4 b/docs/readme/brand-showcase/rea-unboxing.mp4
index 5df5687a..bd0483f2 100644
Binary files a/docs/readme/brand-showcase/rea-unboxing.mp4 and b/docs/readme/brand-showcase/rea-unboxing.mp4 differ
diff --git a/docs/readme/media/M1128-clip.mp4 b/docs/readme/media/M1128-clip.mp4
index a6a394d1..4c3ea167 100644
Binary files a/docs/readme/media/M1128-clip.mp4 and b/docs/readme/media/M1128-clip.mp4 differ
diff --git a/docs/readme/media/M1139-clip.mp4 b/docs/readme/media/M1139-clip.mp4
index 8ce0c9ea..ec99fa4a 100644
Binary files a/docs/readme/media/M1139-clip.mp4 and b/docs/readme/media/M1139-clip.mp4 differ
diff --git a/docs/readme/media/M945-clip.mp4 b/docs/readme/media/M945-clip.mp4
index 64b4fc2f..37c823d9 100644
Binary files a/docs/readme/media/M945-clip.mp4 and b/docs/readme/media/M945-clip.mp4 differ
diff --git a/docs/readme/media/aiwithsachi-reference.mp4 b/docs/readme/media/aiwithsachi-reference.mp4
index f37f137a..a2c6c642 100644
Binary files a/docs/readme/media/aiwithsachi-reference.mp4 and b/docs/readme/media/aiwithsachi-reference.mp4 differ
diff --git a/docs/readme/media/app-showcase.mp4 b/docs/readme/media/app-showcase.mp4
index 149fcd6d..67441379 100644
Binary files a/docs/readme/media/app-showcase.mp4 and b/docs/readme/media/app-showcase.mp4 differ
diff --git a/docs/readme/media/aurora.mp4 b/docs/readme/media/aurora.mp4
index 9e4ec000..635931fc 100644
Binary files a/docs/readme/media/aurora.mp4 and b/docs/readme/media/aurora.mp4 differ
diff --git a/docs/readme/media/dan-martell-tools-reference.mp4 b/docs/readme/media/dan-martell-tools-reference.mp4
index 6e903719..cd069937 100644
Binary files a/docs/readme/media/dan-martell-tools-reference.mp4 and b/docs/readme/media/dan-martell-tools-reference.mp4 differ
diff --git a/docs/readme/media/glass-shard-title.mp4 b/docs/readme/media/glass-shard-title.mp4
index 3f6502f4..1b4cf9ab 100644
Binary files a/docs/readme/media/glass-shard-title.mp4 and b/docs/readme/media/glass-shard-title.mp4 differ
diff --git a/docs/readme/media/harpercarrollai-reference.mp4 b/docs/readme/media/harpercarrollai-reference.mp4
index 284cb260..43249cce 100644
Binary files a/docs/readme/media/harpercarrollai-reference.mp4 and b/docs/readme/media/harpercarrollai-reference.mp4 differ
diff --git a/docs/readme/media/hundred-days-story-reference.mp4 b/docs/readme/media/hundred-days-story-reference.mp4
index dc03d66f..521e7939 100644
Binary files a/docs/readme/media/hundred-days-story-reference.mp4 and b/docs/readme/media/hundred-days-story-reference.mp4 differ
diff --git a/docs/readme/media/jake-figma-draw-reference.mp4 b/docs/readme/media/jake-figma-draw-reference.mp4
index 85df1a85..5624790b 100644
Binary files a/docs/readme/media/jake-figma-draw-reference.mp4 and b/docs/readme/media/jake-figma-draw-reference.mp4 differ
diff --git a/docs/readme/media/jake-lovable-reference.mp4 b/docs/readme/media/jake-lovable-reference.mp4
index b2f76147..5ba2c688 100644
Binary files a/docs/readme/media/jake-lovable-reference.mp4 and b/docs/readme/media/jake-lovable-reference.mp4 differ
diff --git a/docs/readme/media/jake-pond-reference.mp4 b/docs/readme/media/jake-pond-reference.mp4
index 1e9a672c..dca67416 100644
Binary files a/docs/readme/media/jake-pond-reference.mp4 and b/docs/readme/media/jake-pond-reference.mp4 differ
diff --git a/docs/readme/media/kevinstratvert-reference.mp4 b/docs/readme/media/kevinstratvert-reference.mp4
index 94c04504..450ac052 100644
Binary files a/docs/readme/media/kevinstratvert-reference.mp4 and b/docs/readme/media/kevinstratvert-reference.mp4 differ
diff --git a/docs/readme/media/khris-sheer-founder-reference.mp4 b/docs/readme/media/khris-sheer-founder-reference.mp4
index 79347426..14fd6301 100644
Binary files a/docs/readme/media/khris-sheer-founder-reference.mp4 and b/docs/readme/media/khris-sheer-founder-reference.mp4 differ
diff --git a/docs/readme/media/nyc-paris-flight.mp4 b/docs/readme/media/nyc-paris-flight.mp4
index 3d1c05de..0f59c3c2 100644
Binary files a/docs/readme/media/nyc-paris-flight.mp4 and b/docs/readme/media/nyc-paris-flight.mp4 differ
diff --git a/docs/readme/media/presenter-caption-remake.mp4 b/docs/readme/media/presenter-caption-remake.mp4
index 954ccd3f..ca500afe 100644
Binary files a/docs/readme/media/presenter-caption-remake.mp4 and b/docs/readme/media/presenter-caption-remake.mp4 differ
diff --git a/docs/readme/media/remix-authorize-once-reference.mp4 b/docs/readme/media/remix-authorize-once-reference.mp4
index 07cfcfc1..0a7c637e 100644
Binary files a/docs/readme/media/remix-authorize-once-reference.mp4 and b/docs/readme/media/remix-authorize-once-reference.mp4 differ
diff --git a/docs/readme/media/remix-cyera-reference.mp4 b/docs/readme/media/remix-cyera-reference.mp4
index 3621fe38..d8422d2d 100644
Binary files a/docs/readme/media/remix-cyera-reference.mp4 and b/docs/readme/media/remix-cyera-reference.mp4 differ
diff --git a/docs/readme/media/remix-elevenlabs-reception-reference.mp4 b/docs/readme/media/remix-elevenlabs-reception-reference.mp4
index aad84e98..aed4739b 100644
Binary files a/docs/readme/media/remix-elevenlabs-reception-reference.mp4 and b/docs/readme/media/remix-elevenlabs-reception-reference.mp4 differ
diff --git a/docs/readme/media/remix-firecrawl-reference.mp4 b/docs/readme/media/remix-firecrawl-reference.mp4
index c93e934a..783ed5eb 100644
Binary files a/docs/readme/media/remix-firecrawl-reference.mp4 and b/docs/readme/media/remix-firecrawl-reference.mp4 differ
diff --git a/docs/readme/media/remix-glyph-reference.mp4 b/docs/readme/media/remix-glyph-reference.mp4
index 7df86690..5d122613 100644
Binary files a/docs/readme/media/remix-glyph-reference.mp4 and b/docs/readme/media/remix-glyph-reference.mp4 differ
diff --git a/docs/readme/media/remix-iskra-light-reference.mp4 b/docs/readme/media/remix-iskra-light-reference.mp4
index f59d736e..4aedcced 100644
Binary files a/docs/readme/media/remix-iskra-light-reference.mp4 and b/docs/readme/media/remix-iskra-light-reference.mp4 differ
diff --git a/docs/readme/media/remix-kimi-k3-reference.mp4 b/docs/readme/media/remix-kimi-k3-reference.mp4
index ae92644c..5e8e6df1 100644
Binary files a/docs/readme/media/remix-kimi-k3-reference.mp4 and b/docs/readme/media/remix-kimi-k3-reference.mp4 differ
diff --git a/docs/readme/media/remix-linear-loops-reference.mp4 b/docs/readme/media/remix-linear-loops-reference.mp4
index 98e66da7..70bc0b4a 100644
Binary files a/docs/readme/media/remix-linear-loops-reference.mp4 and b/docs/readme/media/remix-linear-loops-reference.mp4 differ
diff --git a/docs/readme/media/ugc-rachelll-reference.mp4 b/docs/readme/media/ugc-rachelll-reference.mp4
index 335baf57..417614ed 100644
Binary files a/docs/readme/media/ugc-rachelll-reference.mp4 and b/docs/readme/media/ugc-rachelll-reference.mp4 differ
diff --git a/docs/readme/studio-tour.mp4 b/docs/readme/studio-tour.mp4
index b5dfb564..dbb93ed2 100644
Binary files a/docs/readme/studio-tour.mp4 and b/docs/readme/studio-tour.mp4 differ
diff --git a/docs/readme/studio-tour.zh-CN.mp4 b/docs/readme/studio-tour.zh-CN.mp4
index 4647ed39..8b1ca62c 100644
Binary files a/docs/readme/studio-tour.zh-CN.mp4 and b/docs/readme/studio-tour.zh-CN.mp4 differ
diff --git a/docs/repository-storage.md b/docs/repository-storage.md
new file mode 100644
index 00000000..5059084f
--- /dev/null
+++ b/docs/repository-storage.md
@@ -0,0 +1,89 @@
+# Repository size and optional media
+
+Source, template guides, small assets, browser dependencies and the images/GIFs embedded in the README remain in ordinary Git. Full reference/demo videos and the optional Presenter Tech `.motion` archive use Git LFS at their existing paths. Their bytes, source credits and integrity manifests are unchanged.
+
+## Clone and run
+
+```sh
+git clone --depth 1 https://github.com/nexu-io/openmotion.git
+cd openmotion
+npm ci
+npm run build:studio
+npm start
+```
+
+`--depth 1` avoids downloading old history. Omit it when you need the history, or run `git fetch --unshallow` later. This migration does not rewrite shared history: a full clone still downloads the large ordinary Git objects in old commits.
+
+The checked-in `.lfsconfig` excludes LFS downloads by default. Normal clones with Git LFS installed keep pointers until you request the media. Without Git LFS installed, pointers remain ordinary text files. GitHub README images and GIFs, local README previews, built-in Studio templates and repository catalog source do not need these optional downloads. This does not make linked CMS references available offline.
+
+## Download only what you need
+
+Install [Git LFS](https://git-lfs.com/), then initialize it in the checkout:
+
+```sh
+git lfs install --local
+```
+
+Choose one scope and override the default exclusion explicitly:
+
+```sh
+# Reference films for one optional Library Skill.
+git lfs pull --include="library/skills/openmotion-design-remix/**" --exclude=""
+
+# Presenter Tech archive and its full preview video.
+git lfs pull --include="library/templates/presenter-tech/**" --exclude=""
+
+# Full README reference films; embedded images/GIFs already work without this.
+git lfs pull --include="docs/readme/**" --exclude=""
+
+# Everything needed for complete plugin/platform bundles and resource verification.
+git lfs pull --include="docs/readme/**,library/**,examples/**" --exclude="library/templates/catalog/**"
+```
+
+For a contributed catalog template, use the [template-specific pull command](template-repository.md#contribute-media-without-cms-access). LFS objects are fetched from the selected remote; reviewing a fork contribution requires the remote that holds its objects. A pointer is not playable video or an executable archive. Full bundles and Library Skill copying refuse unresolved pointers with a download command. Fetch the selected Motion Design profile before materializing it. Once fetched, those resources retain their existing offline behavior.
+
+## Prepare final PR media before merging
+
+Contributors edit their original PR normally. A new catalog video, audio file or large image/font can be committed under `<id>/source/assets/` (at most 50 MiB per file). Git LFS remains a supported input, not a required account or separate upload step. Keep small imported assets and existing README previews in ordinary Git. Raw media can make the policy check red until final preparation; do not repeatedly transfer every draft update.
+
+After the content review, a maintainer opens **Actions → Prepare PR media → Run workflow**, selects `main` and enters the original PR number. This performs one final preparation:
+
+1. Lock the current PR commit and check maintainer identity, fork edit permission and Squash-only repository settings.
+2. Build and validate a cleanup commit without running PR code, hooks, dependencies or `.lfsconfig`.
+3. Upload only changed media to immutable `open-motion/media/sha256/` keys in the public R2 bucket. Read the public objects back and verify their SHA-256 and sizes.
+4. Push one cleanup commit to the original PR. Catalog media becomes `template.json.remoteAssets`; relative guide references become public URLs. Other optional media is registered in `repository-media.json`, with its local path ignored by Git.
+5. Wait for the new commit's CI and any renewed review required by branch rules, then use **Squash and merge**. The workflow does not merge or approve the PR.
+
+The PR author stays unchanged. On a personal-account fork, the contributor must enable **Allow edits from maintainers**. Missing permission, a changed PR head, failed upload, wrong public bytes or a rejected push stops preparation. Failed attempts can leave harmless immutable objects in storage; they do not merge anything. Reruns reuse already verified objects. If the contributor edits media after preparation, process that new revision before merging.
+
+### One-time maintainer setup
+
+- Merge this workflow into `main` to register its manual Actions entry.
+- Configure **Squash merge only**: enable Squash merging and disable merge commits and rebase merging. CI verifies these settings before accepting sanitized PR trees. Existing history is unchanged.
+- Add Actions secret `OPENMOTION_MEDIA_MAINTAINER_TOKEN` for a maintainer user identity with upstream write access and access to allowed fork edits. A classic PAT with `public_repo` access is suitable for public repositories; organization SSO and token policies still apply. A base-repository installation token or default `GITHUB_TOKEN` cannot edit an arbitrary fork. Do not store a token in a checked-in file.
+- The workflow reuses the existing `CLOUDFLARE_R2_RELEASES_AK` / `CLOUDFLARE_R2_RELEASES_SK` secrets and bucket/endpoint variables. It writes only under the media prefix and never publishes an application or changes installation guides. No contributor receives these credentials.
+
+Only a maintainer starts the Action after review. There is no upload on PR open, push or approval, no contribution label, replacement PR or contributor-applied patch. Ordinary PR CI has no storage or maintainer token. The workflow checks out only its trusted main commit and reads PR blobs as data.
+
+For a read-only local preview of the plan, use `npm run media:prepare -- <PR-number>` with GitHub CLI authentication. `--apply` performs the same transfer/write operation using the maintainer identity and configured AWS CLI credentials; use the Action to reuse the repository's R2 credentials.
+
+### Read and package transferred media
+
+Catalog search and MCP detail read local source and return the public preview/poster URL. They do not download media in the background. HTML and Markdown use public asset URLs. Reading the logical source asset through the local API downloads and verifies its bounded body.
+
+Other optional media retains its local logical path in `repository-media.json`. Fetch one scope or the complete legacy set:
+
+```sh
+npm run media:pull -- library/skills/openmotion-design-remix
+npm run media:pull
+```
+
+Only those registered files are downloaded, with size/hash verification and atomic replacement. These commands do not fetch all catalog media. Legacy files still in LFS need the scoped pulls above. Full bundles and resource verification explicitly fetch both stores; npm application packages exclude showcase and optional Library payloads.
+
+### Checks and history
+
+Stage changes, then run `npm run templates:check` and `npm run storage:check` to validate the final tree. Ordinary Git checkout contents are limited to 320 MiB; newly staged ordinary files above 1 MiB fail. Catalog small assets are limited to 100 KB, media files to 50 MiB and total assets per template to 150 MiB. Metadata, source manifests, canonical URLs, identities and duplicate local/remote storage are checked without downloading media.
+
+PR CI uses `--final-tree` with the PR base to check the final merge tree after verifying Squash-only settings. Passing a base SHA to the local checkers additionally checks every intermediate branch commit; that stricter history audit intentionally rejects raw files added and later removed. It is not the merge gate for this final-preparation flow. Squash commits the sanitized final tree; merge/rebase would retain the intermediate media, so they must stay disabled.
+
+The existing LFS migration reduces ordinary Git content by approximately 291 MB. Optional downloads restore that size locally; full clones retain old binary history. Preparation only transfers media changed in the selected PR. This implementation does not claim the existing 71 LFS resources have already been transferred to R2, nor does it rewrite history or configure branch protection. Actual public R2 and an independent contributor-fork write remain activation checks after workflow registration and token setup.
diff --git a/docs/template-repository.md b/docs/template-repository.md
index 4598f3fe..cd3c0b82 100644
--- a/docs/template-repository.md
+++ b/docs/template-repository.md
@@ -1,17 +1,19 @@
# 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. 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.
+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 without CMS access; maintainers transfer final media to public storage once before Squash merge. Git LFS is also accepted as an input. Viewing existing linked images requires internet access.
## Run from a local clone
```sh
-GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/nexu-io/openmotion.git
+GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 https://github.com/nexu-io/openmotion.git
cd openmotion
npm ci
npm run build:studio
npm start
```
+The repository also skips optional LFS media by default; see [repository storage and scoped downloads](repository-storage.md). Shallow clones omit old history; run `git fetch --unshallow` before checks that need an unavailable base commit.
+
Open the `studioUrl` or `previewUrl` printed by `npm start`. Startup reuses a compatible service for the same workspace. On macOS, the shared editor selects a local port dynamically; other platforms try `PORT` (default 4173) and the next nine ports, skipping occupied ones. If all ten are occupied and no compatible service is found, startup reports an error. The launcher exits after reporting the URL; the service keeps running in the background. MCP uses the same startup logic and actual service address when configured for the same `MOTION_DATA_DIR`.
Keep user projects and credentials outside the checkout; `MOTION_DATA_DIR` can select a separate workspace. The plugin root is the cloned `openmotion/` directory: `.codex-plugin/plugin.json` points to `skills/` and `.mcp.json`; that file launches the root `mcp.ts`. For a manual MCP client, launch `node --experimental-strip-types /absolute/openmotion/mcp.ts`, or use `npm run mcp` from the checkout. The repository path is resolved from the loaded plugin, not the caller's working directory.
@@ -28,7 +30,7 @@ These imported guidance packages are not verified complete Studio projects. Read
- `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, 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.
+- `<id>/TEMPLATE.md` explains usage, status and attribution. `<id>/source/` contains unpacked text source, small ordinary-Git assets and optional contribution media under `assets/`. `source/manifest.json` records source paths, sizes and hashes, including the original identities of remotely linked images. `template.json.remoteAssets` maps omitted originals to existing CMS renditions or exact public R2 objects; HTML and Markdown references use the public 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.
@@ -38,44 +40,34 @@ All sizes above use decimal MB/GB. The initial import preserves published IDs, o
1. Select a stable ID in the catalog. Open its `source/preview.html` in a browser; demo files and small images are local; larger reference images load from CMS links. `TEMPLATE.md` links the separate reference video.
2. Edit source and/or `template.json`. Preserve attribution and actual media permission notes; do not assign a blanket license to third-party references.
3. After source edits, run `npm run templates:manifest -- <id>` to update local file hashes. Preview the affected examples.
-4. 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.
+4. Stage changes, run `npm run templates:check` 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, 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.
## 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:
+Add media under `<id>/source/assets/` and reference it by a relative path from the template's HTML/Markdown. No CMS or S3 account is required. Keep small images/fonts at most 100 KB in ordinary Git. For a larger file, commit the actual file (at most 50 MiB), or use the existing LFS path under `assets/lfs/`. Refresh the source manifest and open the original PR normally. Optional `template.json.localMedia` selects a logical preview/poster path:
```json
-"localMedia": {
- "preview": "assets/lfs/reference.mp4",
- "poster": "assets/lfs/poster.webp"
-}
+"localMedia": { "preview": "assets/reference.mp4", "poster": "assets/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.
+When the final content is reviewed, a maintainer runs **Actions → Prepare PR media** once for that PR. It uploads changed media, verifies public downloads, replaces the files with links/identities and adds a cleanup commit to the same PR. The original author is retained. Personal forks must enable **Allow edits from maintainers**. There is no upload on every draft push, no replacement PR and no patch for the contributor to apply.
-Clone with `GIT_LFS_SKIP_SMUDGE=1` as above to avoid downloading every template. Before previewing one template, download only its media:
+Raw large files can fail CI before preparation. After cleanup, wait for the new commit's CI and required review, then Squash merge. If the contributor later revises media, prepare that revision again. See [the maintainer entry, one-time setup and failure behavior](repository-storage.md#prepare-final-pr-media-before-merging).
+
+Transferred media is publicly linked in HTML/Markdown, catalog previews and MCP detail. The original path, bytes and SHA-256 remain in `remoteAssets` and `source/manifest.json`. Public R2 bytes retain the original hash; existing CMS rendition/original pairs retain their separate identities. Network access is required to view linked media. Existing LFS-only contributions remain readable after their scoped pull:
```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
-- 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.
+The final tree permits source text at most 1 MiB, ordinary images/fonts at most 100 KB, catalog Git content at most 128 MiB, media at most 50 MiB per file and 150 MiB total assets per template. Metadata, manifests, small assets, LFS pointers/attributes and remote identities must agree. Archives, generated output, symlinks, disguised binary source and unregistered files fail validation. A transferred asset must not also remain in Git.
-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.
+CI validates the final merge tree without media downloads or upload credentials, and requires Squash-only repository settings. Local checks with an explicit base SHA still provide a stricter intermediate-history audit. Technical checks do not replace rights review, actual media playback or visual acceptance. Configuring branch protection remains a separate repository decision.
## Source to publication
diff --git a/examples/brand-studies/anthropic/comparison.mobile.mp4 b/examples/brand-studies/anthropic/comparison.mobile.mp4
index 897a1c7a..e43caf2c 100644
Binary files a/examples/brand-studies/anthropic/comparison.mobile.mp4 and b/examples/brand-studies/anthropic/comparison.mobile.mp4 differ
diff --git a/examples/brand-studies/anthropic/comparison.mp4 b/examples/brand-studies/anthropic/comparison.mp4
index 6fd64eee..49b3f95d 100644
Binary files a/examples/brand-studies/anthropic/comparison.mp4 and b/examples/brand-studies/anthropic/comparison.mp4 differ
diff --git a/examples/brand-studies/anthropic/film.mp4 b/examples/brand-studies/anthropic/film.mp4
index 609e184b..ed6a9260 100644
Binary files a/examples/brand-studies/anthropic/film.mp4 and b/examples/brand-studies/anthropic/film.mp4 differ
diff --git a/examples/brand-studies/deepseek/comparison.mobile.mp4 b/examples/brand-studies/deepseek/comparison.mobile.mp4
index 46b9b04c..c8106a6f 100644
Binary files a/examples/brand-studies/deepseek/comparison.mobile.mp4 and b/examples/brand-studies/deepseek/comparison.mobile.mp4 differ
diff --git a/examples/brand-studies/deepseek/comparison.mp4 b/examples/brand-studies/deepseek/comparison.mp4
index 80b50762..da4c3946 100644
Binary files a/examples/brand-studies/deepseek/comparison.mp4 and b/examples/brand-studies/deepseek/comparison.mp4 differ
diff --git a/examples/brand-studies/deepseek/film.mp4 b/examples/brand-studies/deepseek/film.mp4
index 046202f3..b5f2537d 100644
Binary files a/examples/brand-studies/deepseek/film.mp4 and b/examples/brand-studies/deepseek/film.mp4 differ
diff --git a/examples/brand-studies/kimi/comparison.mobile.mp4 b/examples/brand-studies/kimi/comparison.mobile.mp4
index c5682d0c..3fc6c15a 100644
Binary files a/examples/brand-studies/kimi/comparison.mobile.mp4 and b/examples/brand-studies/kimi/comparison.mobile.mp4 differ
diff --git a/examples/brand-studies/kimi/comparison.mp4 b/examples/brand-studies/kimi/comparison.mp4
index f20bfe05..0a8e5239 100644
Binary files a/examples/brand-studies/kimi/comparison.mp4 and b/examples/brand-studies/kimi/comparison.mp4 differ
diff --git a/examples/brand-studies/kimi/film.mp4 b/examples/brand-studies/kimi/film.mp4
index 5309252b..e65434a6 100644
Binary files a/examples/brand-studies/kimi/film.mp4 and b/examples/brand-studies/kimi/film.mp4 differ
diff --git a/examples/brand-studies/stripe/comparison.mobile.mp4 b/examples/brand-studies/stripe/comparison.mobile.mp4
index 1a7e26ee..d96587eb 100644
Binary files a/examples/brand-studies/stripe/comparison.mobile.mp4 and b/examples/brand-studies/stripe/comparison.mobile.mp4 differ
diff --git a/examples/brand-studies/stripe/comparison.mp4 b/examples/brand-studies/stripe/comparison.mp4
index f87ebafe..128fe1a8 100644
Binary files a/examples/brand-studies/stripe/comparison.mp4 and b/examples/brand-studies/stripe/comparison.mp4 differ
diff --git a/examples/brand-studies/stripe/film.mp4 b/examples/brand-studies/stripe/film.mp4
index 9fa0b44f..190c04de 100644
Binary files a/examples/brand-studies/stripe/film.mp4 and b/examples/brand-studies/stripe/film.mp4 differ
diff --git a/examples/motion-studies/comparison.mobile.mp4 b/examples/motion-studies/comparison.mobile.mp4
index 79101cd8..38823182 100644
Binary files a/examples/motion-studies/comparison.mobile.mp4 and b/examples/motion-studies/comparison.mobile.mp4 differ
diff --git a/examples/motion-studies/comparison.mp4 b/examples/motion-studies/comparison.mp4
index b6435f8d..0ece2da7 100644
Binary files a/examples/motion-studies/comparison.mp4 and b/examples/motion-studies/comparison.mp4 differ
diff --git a/examples/motion-studies/film.mp4 b/examples/motion-studies/film.mp4
index ab8d1179..d4f2dbf8 100644
Binary files a/examples/motion-studies/film.mp4 and b/examples/motion-studies/film.mp4 differ
diff --git a/examples/motion-studies/signoff.mp4 b/examples/motion-studies/signoff.mp4
index d2745af4..f244d840 100644
Binary files a/examples/motion-studies/signoff.mp4 and b/examples/motion-studies/signoff.mp4 differ
diff --git a/examples/reference-reveal/comparison.mp4 b/examples/reference-reveal/comparison.mp4
index 6b0a842d..36c90e0b 100644
Binary files a/examples/reference-reveal/comparison.mp4 and b/examples/reference-reveal/comparison.mp4 differ
diff --git a/examples/reference-reveal/film.mp4 b/examples/reference-reveal/film.mp4
index 257ed736..62a4de17 100644
Binary files a/examples/reference-reveal/film.mp4 and b/examples/reference-reveal/film.mp4 differ
diff --git a/examples/reference-reveal/graph-cut.mp4 b/examples/reference-reveal/graph-cut.mp4
index e13625f6..9737f114 100644
Binary files a/examples/reference-reveal/graph-cut.mp4 and b/examples/reference-reveal/graph-cut.mp4 differ
diff --git a/examples/wing-construction/comparison.mp4 b/examples/wing-construction/comparison.mp4
index 7675b34c..222366d3 100644
Binary files a/examples/wing-construction/comparison.mp4 and b/examples/wing-construction/comparison.mp4 differ
diff --git a/examples/wing-construction/film.mp4 b/examples/wing-construction/film.mp4
index 3b71aa8a..ffeb88d3 100644
Binary files a/examples/wing-construction/film.mp4 and b/examples/wing-construction/film.mp4 differ
diff --git a/library/skills/openmotion-design-remix/assets/canopy-part-title/reference.mp4 b/library/skills/openmotion-design-remix/assets/canopy-part-title/reference.mp4
index 3cfcc60b..6c1cf2bf 100644
Binary files a/library/skills/openmotion-design-remix/assets/canopy-part-title/reference.mp4 and b/library/skills/openmotion-design-remix/assets/canopy-part-title/reference.mp4 differ
diff --git a/library/skills/openmotion-design-remix/assets/code-3d-extrude/reference.mp4 b/library/skills/openmotion-design-remix/assets/code-3d-extrude/reference.mp4
index bd0ad0f0..e3bb078b 100644
Binary files a/library/skills/openmotion-design-remix/assets/code-3d-extrude/reference.mp4 and b/library/skills/openmotion-design-remix/assets/code-3d-extrude/reference.mp4 differ
diff --git a/library/skills/openmotion-design-remix/assets/code-particle-assemble/reference.mp4 b/library/skills/openmotion-design-remix/assets/code-particle-assemble/reference.mp4
index f9f61ef7..b56d1fdb4 100644
Binary files a/library/skills/openmotion-design-remix/assets/code-particle-assemble/reference.mp4 and b/library/skills/openmotion-design-remix/assets/code-particle-assemble/reference.mp4 differ
diff --git a/library/skills/openmotion-design-remix/assets/liquid-glass-widgets/reference.mp4 b/library/skills/openmotion-design-remix/assets/liquid-glass-widgets/reference.mp4
index 938468c4..bbdb106d 100644
Binary files a/library/skills/openmotion-design-remix/assets/liquid-glass-widgets/reference.mp4 and b/library/skills/openmotion-design-remix/assets/liquid-glass-widgets/reference.mp4 differ
diff --git a/library/skills/openmotion-design-remix/assets/ui-3d-reveal/reference.mp4 b/library/skills/openmotion-design-remix/assets/ui-3d-reveal/reference.mp4
index bbe2fb8f..fa7d306f 100644
Binary files a/library/skills/openmotion-design-remix/assets/ui-3d-reveal/reference.mp4 and b/library/skills/openmotion-design-remix/assets/ui-3d-reveal/reference.mp4 differ
diff --git a/library/skills/openmotion-design-remix/assets/wireframe-portal-title/reference.mp4 b/library/skills/openmotion-design-remix/assets/wireframe-portal-title/reference.mp4
index c8efd313..208618ce 100644
Binary files a/library/skills/openmotion-design-remix/assets/wireframe-portal-title/reference.mp4 and b/library/skills/openmotion-design-remix/assets/wireframe-portal-title/reference.mp4 differ
diff --git a/library/skills/openmotion-design-remix/previews/canopy-part-title.mp4 b/library/skills/openmotion-design-remix/previews/canopy-part-title.mp4
index 855faba7..abef35ae 100644
Binary files a/library/skills/openmotion-design-remix/previews/canopy-part-title.mp4 and b/library/skills/openmotion-design-remix/previews/canopy-part-title.mp4 differ
diff --git a/library/skills/openmotion-design-remix/previews/code-3d-extrude.mp4 b/library/skills/openmotion-design-remix/previews/code-3d-extrude.mp4
index bf0e9c2b..08191324 100644
Binary files a/library/skills/openmotion-design-remix/previews/code-3d-extrude.mp4 and b/library/skills/openmotion-design-remix/previews/code-3d-extrude.mp4 differ
diff --git a/library/skills/openmotion-design-remix/previews/code-particle-assemble.mp4 b/library/skills/openmotion-design-remix/previews/code-particle-assemble.mp4
index 94fe82a8..cd2d88e2 100644
Binary files a/library/skills/openmotion-design-remix/previews/code-particle-assemble.mp4 and b/library/skills/openmotion-design-remix/previews/code-particle-assemble.mp4 differ
diff --git a/library/skills/openmotion-design-remix/previews/liquid-glass-widgets.mp4 b/library/skills/openmotion-design-remix/previews/liquid-glass-widgets.mp4
index 1ad9f91f..fa1ab05e 100644
Binary files a/library/skills/openmotion-design-remix/previews/liquid-glass-widgets.mp4 and b/library/skills/openmotion-design-remix/previews/liquid-glass-widgets.mp4 differ
diff --git a/library/skills/openmotion-design-remix/previews/ui-3d-reveal.mp4 b/library/skills/openmotion-design-remix/previews/ui-3d-reveal.mp4
index 22bc58d8..107683b0 100644
Binary files a/library/skills/openmotion-design-remix/previews/ui-3d-reveal.mp4 and b/library/skills/openmotion-design-remix/previews/ui-3d-reveal.mp4 differ
diff --git a/library/skills/openmotion-design-remix/previews/wireframe-portal-title.mp4 b/library/skills/openmotion-design-remix/previews/wireframe-portal-title.mp4
index d2253e0d..ab2cd239 100644
Binary files a/library/skills/openmotion-design-remix/previews/wireframe-portal-title.mp4 and b/library/skills/openmotion-design-remix/previews/wireframe-portal-title.mp4 differ
diff --git a/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-reference.mp4 b/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-reference.mp4
index b2786945..05e5915c 100644
Binary files a/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-reference.mp4 and b/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-reference.mp4 differ
diff --git a/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-result.mp4 b/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-result.mp4
index c4ca1335..fdef7e50 100644
Binary files a/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-result.mp4 and b/library/skills/openmotion-presenter-story/assets/ali-abdaal-workflow-result.mp4 differ
diff --git a/library/skills/openmotion-presenter-story/assets/careerwithriya-reference.mp4 b/library/skills/openmotion-presenter-story/assets/careerwithriya-reference.mp4
index ef18bd2c..a9e46891 100644
Binary files a/library/skills/openmotion-presenter-story/assets/careerwithriya-reference.mp4 and b/library/skills/openmotion-presenter-story/assets/careerwithriya-reference.mp4 differ
diff --git a/library/skills/openmotion-presenter-story/assets/careerwithriya-result.mp4 b/library/skills/openmotion-presenter-story/assets/careerwithriya-result.mp4
index 83fa998d..429aa23c 100644
Binary files a/library/skills/openmotion-presenter-story/assets/careerwithriya-result.mp4 and b/library/skills/openmotion-presenter-story/assets/careerwithriya-result.mp4 differ
diff --git a/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-reference.mp4 b/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-reference.mp4
index c93af23f..08515098 100644
Binary files a/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-reference.mp4 and b/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-reference.mp4 differ
diff --git a/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-result.mp4 b/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-result.mp4
index 458d5c9b..a51eee7e 100644
Binary files a/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-result.mp4 and b/library/skills/openmotion-presenter-story/assets/john-tagudin-capso-result.mp4 differ
diff --git a/library/templates/presenter-tech/README.md b/library/templates/presenter-tech/README.md
index 5210e715..46dbb445 100644
--- a/library/templates/presenter-tech/README.md
+++ b/library/templates/presenter-tech/README.md
@@ -1,5 +1,7 @@
# Presenter Tech · 科技风口播模板
+In a source checkout, download the optional archive and demo first: `git lfs pull --include="library/templates/presenter-tech/**" --exclude=""` from the repository root. Complete bundles include the downloaded bytes.
+
**A local OpenMotion Library template package for presenter-led explainers, animated keywords and visual demonstrations.** Editable source, input schemas, fonts, native sound recipes and the runner are included in [presenter-tech.motion](presenter-tech.motion). The `.motion` file is a ZIP archive; keep the original and create a separate working copy.
**1920 × 1080 · 60 fps · landscape.** Replace the presenter, topic, wording, screen assets and measured captions. Use the supplied template runner through your Agent. This library package is separate from the three templates opened directly in Studio; it does not add general `.motion` importing to Studio.
diff --git a/library/templates/presenter-tech/presenter-tech.motion b/library/templates/presenter-tech/presenter-tech.motion
index 85d11917..a5a81368 100644
Binary files a/library/templates/presenter-tech/presenter-tech.motion and b/library/templates/presenter-tech/presenter-tech.motion differ
diff --git a/library/templates/presenter-tech/preview.mp4 b/library/templates/presenter-tech/preview.mp4
index 2d530d36..f8c427a5 100644
Binary files a/library/templates/presenter-tech/preview.mp4 and b/library/templates/presenter-tech/preview.mp4 differ
diff --git a/package.json b/package.json
index e2ee9c00..af9343c9 100644
--- a/package.json
+++ b/package.json
@@ -29,9 +29,12 @@
"catalog:covers": "node --experimental-strip-types scripts/cache-template-covers.ts",
"catalog:metadata": "node --experimental-strip-types scripts/sync-template-metadata.ts",
"export:adapters": "node --experimental-strip-types scripts/export-adapters.ts",
+ "storage:check": "node --experimental-strip-types scripts/check-repository-storage.ts",
"templates:check": "node --experimental-strip-types scripts/check-template-library.ts",
"templates:export": "node --experimental-strip-types scripts/template-library.ts export",
- "templates:manifest": "node --experimental-strip-types scripts/template-library.ts manifest"
+ "templates:manifest": "node --experimental-strip-types scripts/template-library.ts manifest",
+ "media:prepare": "node --experimental-strip-types scripts/prepare-pr-media.ts",
+ "media:pull": "node --experimental-strip-types scripts/repository-media.ts"
},
"dependencies": {
"@base-ui/react": "1.7.0",
diff --git a/prism-templates.ts b/prism-templates.ts
index 6878bf4b..1c747406 100644
--- a/prism-templates.ts
+++ b/prism-templates.ts
@@ -7,6 +7,7 @@ import { templateConfig } from './shared/template-config.ts';
import { libraryTemplates, templateRecipe } from './template-catalog.ts';
import { copyTemplate } from './template-library.ts';
import { loadRepositoryCatalog, lfsPointer, maxLfsAssetBytes, readRepositoryFile, repositoryCatalogRoot, repositoryMediaFile } from './shared/repository-template-catalog.ts';
+import { downloadMedia, validateMediaLock } from './shared/repository-media.ts';
type TemplateFile = { path: string; url: string; bytes: number; sha256: string };
type PrismTemplate = {
@@ -128,8 +129,13 @@ export class TemplateCatalog {
...(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('/')}`;
+ const record = snapshot.repository?.records.get(item.templateId);
+ const localMedia = record?.localMedia;
+ const localUrl = (name: string) => {
+ const remote = record.remoteAssets?.find((asset: { source: { path: string } }) => asset.source.path === name);
+ if (remote) { validateMediaLock({ path: name, ...remote }); return remote.url; }
+ return `/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,
@@ -200,6 +206,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');
+ const record = JSON.parse((await readRepositoryFile(this.repositoryRoot, id + '/template.json')).toString());
+ const remote = record.remoteAssets?.find((asset: { source: { path: string } }) => asset.source.path === name);
+ if (remote) {
+ const lock = { path: name, ...remote };
+ const expected = manifest.files.find((file: { path: string }) => file.path === name);
+ if (expected.bytes !== lock.bytes || expected.sha256 !== lock.sha256) throw new Error('Transferred media does not match its source manifest');
+ return downloadMedia(lock, this.request);
+ }
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' });
diff --git a/repository-media.json b/repository-media.json
new file mode 100644
index 00000000..910fbc9f
--- /dev/null
+++ b/repository-media.json
@@ -0,0 +1,4 @@
+{
+ "schemaVersion": 1,
+ "files": []
+}
diff --git a/scripts/check-readme-resources.mjs b/scripts/check-readme-resources.mjs
index d330209e..50c34ea2 100644
--- a/scripts/check-readme-resources.mjs
+++ b/scripts/check-readme-resources.mjs
@@ -12,7 +12,7 @@ export const resourceDocuments = [
];
const remote = /^(?:https?:)?\/\//i;
-export async function checkDocument(file) {
+export async function checkDocument(file, mediaURLs = new Set()) {
const text = await readFile(file, 'utf8');
const refs = [...text.matchAll(/(?:src|srcset)="([^"]+)"|!\[[^\]]*\]\(([^)]+)\)|\]\(([^)]+)\)|href="([^"]+)"/g)];
let checked = 0;
@@ -20,7 +20,7 @@ export async function checkDocument(file) {
const url = match.slice(1).find(Boolean);
const embedded = Boolean(match[1] || match[2]);
const media = /\.(?:mp4|webm|mov|gif|png|jpe?g|svg|woff2?|ttf|mp3|wav)(?:[?#]|$)/i.test(url);
- assert(!(remote.test(url) && (embedded || media)), `${file}: external display/media dependency: ${url}`);
+ assert(!(remote.test(url) && (embedded || media) && !mediaURLs.has(url)), `${file}: external display/media dependency: ${url}`);
if (/^(?:https?:|mailto:|#|data:)/i.test(url)) continue;
const target = path.resolve(path.dirname(file), decodeURIComponent(url.split('#')[0].split('?')[0]));
await stat(target).catch(() => { throw new Error(`${file}: missing local reference: ${url}`); });
@@ -31,7 +31,9 @@ export async function checkDocument(file) {
export async function verifyResources(root = fileURLToPath(new URL('../', import.meta.url))) {
let links = 0, hashes = 0;
- for (const doc of resourceDocuments) links += await checkDocument(path.join(root, doc));
+ const { validateMediaManifest } = await import('../shared/repository-media.ts');
+ const optional = validateMediaManifest(JSON.parse(await readFile(path.join(root, 'repository-media.json'), 'utf8')));
+ for (const doc of resourceDocuments) links += await checkDocument(path.join(root, doc), new Set(optional.files.map(file => file.url)));
const manifests = [
['docs/readme/live-product/manifest.json', '', 'files'],
['docs/readme/live-templates/manifest.json', '', 'files'],
@@ -47,6 +49,8 @@ export async function verifyResources(root = fileURLToPath(new URL('../', import
const file = path.resolve(root, base, entry.file);
assert(file.startsWith(path.resolve(root) + path.sep), 'Resource escapes checkout');
const bytes = await readFile(file);
+ assert(!bytes.subarray(0, 128).toString().startsWith('version https://git-lfs.github.com/spec/v1'),
+ `${entry.file}: media is not downloaded. Run git lfs pull --include="docs/readme/**,library/**,examples/**" --exclude="library/templates/catalog/**" before verifying full resource hashes.`);
assert.equal(createHash('sha256').update(bytes).digest('hex'), entry.sha256, `Changed resource: ${entry.file}`);
if (entry.bytes !== undefined) assert.equal(bytes.length, entry.bytes, `Changed size: ${entry.file}`);
hashes++;
diff --git a/scripts/check-repository-storage.ts b/scripts/check-repository-storage.ts
new file mode 100644
index 00000000..b1e85a2c
--- /dev/null
+++ b/scripts/check-repository-storage.ts
@@ -0,0 +1,89 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { isMain } from '../shared/entry.ts';
+import { lfsPointer, maxLfsAssetBytes, repositoryMediaFile } from '../shared/repository-template-catalog.ts';
+import { validateMediaManifest } from '../shared/repository-media.ts';
+
+const maxGitFileBytes = 1024 * 1024;
+const maxCheckoutBytes = 320 * 1024 * 1024;
+function git(cwd: string, args: string[], input?: string) {
+ const result = spawnSync('git', args, { cwd, input, maxBuffer: 32 * 1024 * 1024 });
+ assert.equal(result.status, 0, result.stderr?.toString() || result.error?.message);
+ return result.stdout;
+}
+
+/** Inspect the index and newly introduced history, without downloading LFS media. */
+export function checkRepositoryStorage(cwd: string, base?: string, options: { finalTreeOnly?: boolean } = {}) {
+ if (base) assert(/^[a-f0-9]{40}$/.test(base), 'Use a full base commit SHA');
+ const errors: string[] = [];
+ const entries = git(cwd, ['ls-files', '--stage', '-z']).toString().split('\0').filter(Boolean).map(line => {
+ const match = /^(\d+) ([a-f0-9]+) 0\t([\s\S]+)$/.exec(line);
+ assert(match, 'Resolve index conflicts before checking storage');
+ return { mode: match[1], oid: match[2], name: match[3] };
+ });
+ const oids = [...new Set(entries.map(entry => entry.oid))];
+ const sizes = new Map(git(cwd, ['cat-file', '--batch-check=%(objectname) %(objectsize)'], oids.join('\n') + '\n')
+ .toString().trim().split('\n').filter(Boolean).map(line => {
+ const [oid, size] = line.split(' ');
+ return [oid, Number(size)] as const;
+ }));
+ const attributes = git(cwd, ['check-attr', '--cached', '-z', '--stdin', 'filter'], entries.map(entry => entry.name).join('\0') + '\0').toString().split('\0');
+ const filters = new Map<string, string>();
+ for (let i = 0; i + 2 < attributes.length; i += 3) filters.set(attributes[i], attributes[i + 2]);
+ const small = oids.filter(oid => sizes.get(oid)! <= 1024);
+ const output = small.length ? git(cwd, ['cat-file', '--batch'], small.join('\n') + '\n') : Buffer.alloc(0);
+ const contents = new Map<string, Buffer>();
+ let offset = 0;
+ for (const oid of small) {
+ const end = output.indexOf(10, offset);
+ const size = sizes.get(oid)!;
+ contents.set(oid, output.subarray(end + 1, end + 1 + size));
+ offset = end + size + 2;
+ }
+ const changed = new Set(git(cwd, ['diff', '--cached', '--name-only', '-z', '--diff-filter=AM', ...(base ? [base] : [])]).toString().split('\0'));
+ let gitBytes = 0, lfsBytes = 0, lfsFiles = 0;
+ for (const entry of entries) {
+ const size = sizes.get(entry.oid)!;
+ gitBytes += size;
+ if (size > maxGitFileBytes && changed.has(entry.name)) errors.push(`${entry.name}: staged ordinary Git file exceeds 1 MiB; use LFS or Prepare PR media`);
+ const bytes = contents.get(entry.oid), pointer = bytes && lfsPointer(bytes);
+ if (filters.get(entry.name) !== 'lfs' && !pointer && !bytes?.toString().startsWith('version https://git-lfs.github.com/spec/v1')) continue;
+ if (!pointer || filters.get(entry.name) !== 'lfs' || !['100644', '100755'].includes(entry.mode)) {
+ errors.push(`${entry.name}: require a canonical LFS pointer and staged LFS attributes`);
+ continue;
+ }
+ if (!repositoryMediaFile.test(entry.name) && !/\.motion$/i.test(entry.name)) errors.push(`${entry.name}: LFS is for media and optional template archives`);
+ if (pointer.bytes > maxLfsAssetBytes) errors.push(`${entry.name}: LFS file exceeds 50 MiB`);
+ lfsBytes += pointer.bytes;
+ lfsFiles++;
+ }
+ if (gitBytes > maxCheckoutBytes) errors.push('Ordinary Git checkout exceeds 320 MiB; move optional media to LFS or review the budget');
+ if (base && !options.finalTreeOnly) {
+ const objects = git(cwd, ['rev-list', '--objects', 'HEAD', '--not', base]).toString().trim().split('\n').filter(Boolean);
+ if (objects.length) {
+ const metadata = git(cwd, ['cat-file', '--batch-check=%(objectname) %(objecttype) %(objectsize)'], objects.map(line => line.split(' ')[0]).join('\n') + '\n').toString().trim().split('\n');
+ for (const line of metadata) {
+ const [oid, type, size] = line.split(' ');
+ if (type === 'blob' && Number(size) > maxGitFileBytes) errors.push(`History blob ${oid}: new ordinary Git file exceeds 1 MiB, even if later deleted; use Git LFS for media`);
+ }
+ }
+ }
+ const manifest = entries.find(entry => entry.name === 'repository-media.json');
+ if (manifest) {
+ try {
+ const media = validateMediaManifest(JSON.parse(git(cwd, ['cat-file', 'blob', manifest.oid]).toString()));
+ for (const file of media.files)
+ if (entries.some(entry => entry.name === file.path)) errors.push(`${file.path}: transferred media must not also be stored in Git`);
+ } catch (error) { errors.push((error as Error).message); }
+ }
+ return { errors, gitBytes, lfsBytes, lfsFiles };
+}
+
+if (isMain(import.meta.url)) {
+ const args = process.argv.slice(2), finalTreeOnly = args.includes('--final-tree');
+ const base = args.filter(arg => arg !== '--final-tree');
+ assert(base.length <= 1, 'Usage: check-repository-storage.ts [base-sha] [--final-tree]');
+ const result = checkRepositoryStorage(process.cwd(), base[0] || process.env.BASE_SHA, { finalTreeOnly });
+ console.log(JSON.stringify(result, null, 2));
+ if (result.errors.length) process.exitCode = 1;
+}
diff --git a/scripts/check-template-library.ts b/scripts/check-template-library.ts
index 2d75d820..5a111e00 100644
--- a/scripts/check-template-library.ts
+++ b/scripts/check-template-library.ts
@@ -42,7 +42,7 @@ function blobs(cwd: string, oids: string[]): Map<string, Buffer> {
}
/** Read Git's index, not smudged files or unstaged changes. No media downloads or npm dependencies. */
-export function checkTemplateLibrary(cwd: string, base?: string): string[] {
+export function checkTemplateLibrary(cwd: string, base?: string, options: { finalTreeOnly?: boolean } = {}): string[] {
const errors: string[] = [];
const staged = git(['ls-files', '--stage', '-z', '--', scope], cwd)
.toString()
@@ -172,12 +172,14 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {
const sourceManifest = parse(id + '/source/manifest.json');
const sourcePrefix = scope + id + '/source/';
const remoteAssets = new Map((record.remoteAssets ?? []).map((asset) => [asset.source.path, asset]));
+ if (remoteAssets.size && (assetTotals.get(id) ?? 0) + [...remoteAssets.values()].reduce((sum, asset) => sum + asset.source.bytes, 0) > maxTemplateAssetBytes)
+ errors.push(`${id}: template assets exceed 150 MiB including remote media`);
const sourcePaths = [...files.keys()]
.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(sourcePaths.includes(name) || remoteAssets.has(name), 'Media must be registered in the source manifest: ' + name);
assert.deepEqual(
sourceManifest.files.map((file: { path: string }) => file.path).sort(),
[...sourcePaths, ...remoteAssets.keys()].sort(),
@@ -209,7 +211,7 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {
} catch (error) {
errors.push((error as Error).message);
}
- if (base) {
+ if (base && !options.finalTreeOnly) {
assert(/^[a-f0-9]{40}$/.test(base), 'Base must be a full commit SHA');
git(['rev-parse', '--verify', `${base}^{commit}`], cwd);
const objects = git(['rev-list', '--objects', `${base}..HEAD`, '--', scope], cwd)
@@ -254,7 +256,10 @@ export function checkTemplateLibrary(cwd: string, base?: string): string[] {
return errors;
}
if (isMain(import.meta.url)) {
- const errors = checkTemplateLibrary(process.cwd(), process.argv[2] || process.env.BASE_SHA || undefined);
+ const args = process.argv.slice(2), finalTreeOnly = args.includes('--final-tree');
+ const base = args.filter(arg => arg !== '--final-tree');
+ assert(base.length <= 1, 'Usage: check-template-library.ts [base-sha] [--final-tree]');
+ const errors = checkTemplateLibrary(process.cwd(), base[0] || process.env.BASE_SHA || undefined, { finalTreeOnly });
if (errors.length) {
console.error(errors.join('\n'));
process.exitCode = 1;
diff --git a/scripts/distribution.ts b/scripts/distribution.ts
index e000242c..ed59ec1d 100644
--- a/scripts/distribution.ts
+++ b/scripts/distribution.ts
@@ -1,4 +1,4 @@
-import { lstat, readdir } from 'node:fs/promises';
+import { lstat, open, readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { packagedSkills } from '../shared/workflow.ts';
@@ -474,7 +474,7 @@ export const distributionDocuments = [
...['brandkit', 'presenter-story', 'motion-design-remix'].flatMap(name => ['library/skills/' + name + '/SKILL.md', 'library/skills/' + name + '/agents/openai.yaml']),
...['openmotion-brandkit', 'openmotion-presenter-story', 'openmotion-design-remix'].map(name => 'library/skills/' + name + '/agents/openai.yaml'),
...localReadmeResourceFiles,
- 'README.md', 'README.zh-CN.md', 'CONTRIBUTING.md', 'CONTRIBUTING.zh-CN.md', 'AGENTS.md', 'CLAUDE.md', 'docs/README.md',
+ 'README.md', 'README.zh-CN.md', 'CONTRIBUTING.md', 'CONTRIBUTING.zh-CN.md', 'AGENTS.md', 'CLAUDE.md', 'docs/README.md', 'repository-media.json',
'docs/product/architecture.md', 'docs/product/changes.md', 'docs/product/media-generation-design.md', 'docs/product/studio-vision.md',
'tracking/README.md', 'tracking/INTEGRATION.md', 'tracking/posthog-geoip.hog',
'docs/agent-adapters.md', 'docs/browser-runtime.md', 'docs/design-system.md', 'docs/editor-fork.md',
@@ -525,7 +525,7 @@ export const distributionDocuments = [
'library/components/README.md', 'library/components/title-reveal/README.md',
'library/design-systems/ink-water/MOTION_DESIGN.md', 'library/brandkits/openmotion/BRANDKIT.md',
'docs/motion-design-examples.md', 'docs/motion-design-examples.zh-CN.md', ...motionDesignRemixFiles, ...presenterStoryFiles, ...presenterTechFiles,
- 'docs/skills.md', 'docs/template-catalog.md', 'docs/template-repository.md', 'docs/test-packages.md', 'docs/templates/requirement.md',
+ 'docs/skills.md', 'docs/template-catalog.md', 'docs/template-repository.md', 'docs/repository-storage.md', 'docs/test-packages.md', 'docs/templates/requirement.md',
];
export async function distributionFiles(profile: string): Promise<string[]> {
@@ -541,6 +541,7 @@ export async function distributionFiles(profile: string): Promise<string[]> {
'scripts/install-onboarding.mjs', 'scripts/onboarding-catalog.ts', 'scripts/install-library-skill.mjs',
'scripts/diagnostics.mjs', 'scripts/diagnostic-redaction.mjs', 'scripts/zip.mjs',
'scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts',
+ 'scripts/repository-media.ts',
'shared/workflow-entry.js', 'studio/LICENSE', 'studio/README.md', 'template-library/LICENSE', 'shared/editor-launch.pl',
'tracking/core.ts', 'tracking/node.ts', 'tracking/browser.ts', 'tracking/events.ts',
];
@@ -559,6 +560,26 @@ export async function distributionFiles(profile: string): Promise<string[]> {
for (const skill of packagedSkills) await walk('skills/' + skill, /\.(?:md|mjs|ts|py|json|ya?ml)$/);
await walk('studio/build', /\.(?:html|js|css|json|svg|png|jpg|webp|woff2?|ttf|txt)$/);
await walk('studio/public', /\.(?:html|js|css|json|svg|png|jpg|webp|woff2?|ttf|txt)$/);
- for (const file of files) if (!(await lstat(path.join(root, file))).isFile()) throw new Error('Distribution requires a regular file: ' + file);
+ for (const file of files) {
+ const info = await lstat(path.join(root, file)).catch(error => {
+ if (error.code === 'ENOENT' && /\.(?:mp4|motion)$/.test(file)) throw new Error(`Optional media is missing: ${file}. Run npm run media:pull for transferred files, or the scoped LFS pull in docs/repository-storage.md.`);
+ throw error;
+ });
+ if (!info.isFile()) throw new Error('Distribution requires a regular file: ' + file);
+ }
return [...new Set(files)].sort();
}
+
+// Complete bundles must never turn unresolved LFS pointers into installed media.
+export async function requireDownloadedMedia(files: string[], directory = root): Promise<void> {
+ for (const name of files) {
+ if (!/\.(?:mp4|mov|webm|m4v|avi|mp3|wav|ogg|m4a|aac|flac|motion)$/i.test(name)) continue;
+ const file = await open(path.join(directory, name), 'r');
+ try {
+ const header = Buffer.alloc(128);
+ await file.read(header, 0, header.length, 0);
+ if (header.toString().startsWith('version https://git-lfs.github.com/spec/v1'))
+ throw new Error(`Media not downloaded: ${name}. Run git lfs pull --include="${name}" --exclude="" from the source checkout before packaging or copying it.`);
+ } finally { await file.close(); }
+ }
+}
diff --git a/scripts/install-library-skill.mjs b/scripts/install-library-skill.mjs
index 413db624..9750c546 100644
--- a/scripts/install-library-skill.mjs
+++ b/scripts/install-library-skill.mjs
@@ -3,6 +3,7 @@ import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:f
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
+import { validateMediaManifest } from '../shared/repository-media.ts';
const source = fileURLToPath(new URL('../library/skills/', import.meta.url));
const aliases = { brandkit: 'openmotion-brandkit', 'presenter-story': 'openmotion-presenter-story', 'motion-design-remix': 'openmotion-design-remix' };
@@ -14,7 +15,10 @@ async function snapshot(directory, relative = '') {
if (item.isDirectory()) Object.assign(files, await snapshot(directory, name));
else {
assert(item.isFile(), 'Unsupported Skill entry: ' + name);
- files[name] = createHash('sha256').update(await readFile(path.join(directory, name))).digest('hex');
+ const bytes = await readFile(path.join(directory, name));
+ assert(!bytes.subarray(0, 128).toString().startsWith('version https://git-lfs.github.com/spec/v1'),
+ 'Skill media is not downloaded. Run git lfs pull --include="library/skills/**" --exclude="" before installing a Library Skill.');
+ files[name] = createHash('sha256').update(bytes).digest('hex');
}
}
return files;
@@ -26,6 +30,13 @@ export async function installLibrarySkill(name, destination) {
const canonical = aliases[name] ?? name;
assert(Object.values(aliases).includes(canonical), 'Unknown Library Skill: ' + name);
assert(destination, 'An explicit destination skills directory is required');
+ const media = validateMediaManifest(JSON.parse(await readFile(new URL('../repository-media.json', import.meta.url), 'utf8')));
+ for (const file of media.files.filter(file => file.path.startsWith('library/skills/' + canonical + '/'))) {
+ const bytes = await readFile(new URL('../' + file.path, import.meta.url)).catch(() => {
+ throw new Error('Optional Skill media is missing. Run npm run media:pull -- library/skills/' + canonical);
+ });
+ assert(bytes.length === file.bytes && createHash('sha256').update(bytes).digest('hex') === file.sha256, 'Optional Skill media does not match repository-media.json');
+ }
const directory = path.resolve(destination), names = canonical === name ? [canonical] : [canonical, name];
await mkdir(directory, { recursive: true });
const missing = [];
diff --git a/scripts/package.ts b/scripts/package.ts
index 10326164..bfccc02b 100644
--- a/scripts/package.ts
+++ b/scripts/package.ts
@@ -3,7 +3,7 @@ import { readFile, mkdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
-import { distributionFiles } from './distribution.ts';
+import { distributionFiles, requireDownloadedMedia } from './distribution.ts';
import { zip } from './zip.mjs';
export { zip } from './zip.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
@@ -20,6 +20,7 @@ async function main() {
await check();
const manifest = JSON.parse(await readFile(path.join(root, '.codex-plugin/plugin.json'), 'utf8'));
const files = await distributionFiles(profile);
+ await requireDownloadedMedia(files);
let commit: string | null;
try { commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); }
catch { commit = JSON.parse(await readFile(path.join(root, 'shared/build-info.json'), 'utf8')).commit; }
diff --git a/scripts/prepare-pr-media.ts b/scripts/prepare-pr-media.ts
new file mode 100644
index 00000000..d9133ed8
--- /dev/null
+++ b/scripts/prepare-pr-media.ts
@@ -0,0 +1,291 @@
+import assert from 'node:assert/strict';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { isMain } from '../shared/entry.ts';
+import { checkTemplateLibrary } from './check-template-library.ts';
+import { checkRepositoryStorage } from './check-repository-storage.ts';
+import { lfsPointer } from '../shared/repository-template-catalog.ts';
+import { boundedMediaBody, mediaDigest, mediaKey, mediaOrigin, maxMediaBytes, downloadMedia, validateMediaLock, validateMediaManifest, type MediaLock } from '../shared/repository-media.ts';
+export type CleanupChange = { path: string; content: string | null };
+export type CleanupPlan = { schemaVersion: 1; sourceSHA: string; pullNumber: number; changes: CleanupChange[]; media: MediaLock[] };
+
+const execute = promisify(execFile);
+const repository = 'nexu-io/openmotion';
+export type TreeFile = { path: string; mode: string; sha: string; size: number; type: string };
+type Inputs = { head: TreeFile[]; base: TreeFile[]; sourceSHA: string; pullNumber: number };
+type Transfer = (file: MediaLock, bytes: Buffer) => Promise<void>;
+const textFile = /\.(?:md|html?|css|json|[cm]?[jt]sx?|txt|ya?ml)$/i;
+const mediaFile = /\.(?:mp4|mov|webm|m4v|avi|mp3|wav|ogg|m4a|aac|flac|png|jpe?g|webp|avif|gif|woff2?|ttf|otf|motion)$/i;
+const videoOrAudio = /\.(?:mp4|mov|webm|m4v|avi|mp3|wav|ogg|m4a|aac|flac|motion)$/i;
+const catalogAsset = /^library\/templates\/catalog\/([a-z][a-z0-9-]+)\/source\/(assets\/[\w/.@+ -]+)$/;
+const jsonBytes = (value: unknown) => Buffer.from(JSON.stringify(value, null, 2) + '\n');
+
+export async function finalizeMediaCleanup(plan: CleanupPlan, upload: () => Promise<void>, currentHead: () => Promise<string>, push: () => Promise<void>) {
+ await upload();
+ assert.equal(await currentHead(), plan.sourceSHA, 'PR changed during upload; rerun against its new head');
+ await push();
+}
+
+function replaceReference(text: string, relative: string, url: string) {
+ const spellings = new Set([relative, relative.split('/').map(encodeURIComponent).join('/')]);
+ for (const spelling of spellings) {
+ const escaped = spelling.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ text = text.replace(new RegExp(`(^|[\\s"'(=])(?:\\./)?${escaped}(?=[\\s"')?#]|$)`, 'gm'), (_, prefix: string) => prefix + url);
+ }
+ return text;
+}
+
+/** Prepare only source/media edits; no PR code, hooks, dependencies or configuration is executed. */
+export async function prepareMediaCleanup(inputs: Inputs, read: (file: TreeFile) => Promise<Buffer>, transfer?: Transfer): Promise<CleanupPlan> {
+ const files = new Map(inputs.head.filter(file => file.type === 'blob').map(file => [file.path, file]));
+ const previous = new Map(inputs.base.map(file => [file.path, file.sha]));
+ const originals = new Map<string, Buffer>(), edits = new Map<string, Buffer | null>();
+ const load = async (name: string) => {
+ if (!originals.has(name)) {
+ const file = files.get(name);
+ assert(file?.mode === '100644' || file?.mode === '100755', 'Require regular source file: ' + name);
+ originals.set(name, await read(file));
+ }
+ return originals.get(name)!;
+ };
+ const candidates = inputs.head.filter(file => file.type === 'blob' && previous.get(file.path) !== file.sha && mediaFile.test(file.path) &&
+ /^(?:library|docs\/readme|examples)\//.test(file.path) && (videoOrAudio.test(file.path) || file.size > (catalogAsset.test(file.path) ? 100_000 : 1024 * 1024)));
+ assert(candidates.length <= 100, 'Too many media files; split this PR');
+ let total = 0;
+ const locks: MediaLock[] = [];
+ if (!candidates.length) return { schemaVersion: 1, sourceSHA: inputs.sourceSHA, pullNumber: inputs.pullNumber, changes: [], media: [] };
+ for (const file of candidates) {
+ assert(['100644', '100755'].includes(file.mode), 'Media must not be a symlink or submodule');
+ if (file.path.startsWith('library/templates/catalog/')) assert(catalogAsset.test(file.path) && !file.path.endsWith('.motion'), 'Catalog media must be in source/assets/; archives are not source');
+ assert(file.size <= maxMediaBytes, 'Git blob exceeds 50 MiB: ' + file.path);
+ const raw = await load(file.path), pointer = lfsPointer(raw);
+ assert(!raw.toString('utf8', 0, 64).startsWith('version https://git-lfs.github.com/spec/v1') || pointer, 'Malformed LFS pointer: ' + file.path);
+ const bytes = pointer?.bytes ?? raw.length;
+ assert(bytes > 0 && bytes <= maxMediaBytes, 'Media exceeds 50 MiB: ' + file.path);
+ total += bytes;
+ assert(total <= 320 * 1024 * 1024, 'PR transfer exceeds 320 MiB; split it');
+ const sha256 = pointer?.sha256 ?? mediaDigest(raw);
+ locks.push({ path: file.path, bytes, sha256, url: mediaOrigin + '/' + mediaKey(sha256, file.path) });
+ validateMediaLock(locks.at(-1)!);
+ }
+ const manifestName = 'repository-media.json';
+ const manifest = files.has(manifestName) ? validateMediaManifest(JSON.parse((await load(manifestName)).toString())) : { schemaVersion: 1 as const, files: [] as MediaLock[] };
+ const templates = new Map<string, MediaLock[]>();
+ const previousURLs = new Map<string, string>();
+ for (const lock of locks) {
+ edits.set(lock.path, null);
+ const match = catalogAsset.exec(lock.path);
+ if (match) templates.set(match[1], [...(templates.get(match[1]) ?? []), lock]);
+ else {
+ manifest.files = manifest.files.filter(file => file.path !== lock.path);
+ manifest.files.push(lock);
+ }
+ }
+ for (const [id, media] of templates) {
+ const prefix = `library/templates/catalog/${id}/`, recordName = prefix + 'template.json';
+ const record = JSON.parse((await load(recordName)).toString());
+ const remote = new Map((record.remoteAssets ?? []).map((asset: { source: { path: string } }) => [asset.source.path, asset]));
+ for (const lock of media) {
+ const sourcePath = lock.path.slice((prefix + 'source/').length);
+ const previous: any = remote.get(sourcePath);
+ if (previous) previousURLs.set(previous.url, lock.url);
+ remote.set(sourcePath, { url: lock.url, bytes: lock.bytes, sha256: lock.sha256, source: { path: sourcePath, bytes: lock.bytes, sha256: lock.sha256 } });
+ }
+ record.remoteAssets = [...remote.values()];
+ edits.set(recordName, jsonBytes(record));
+ }
+ for (const file of inputs.head) {
+ if (file.type !== 'blob' || !textFile.test(file.path) || file.size > 1024 * 1024 ||
+ !(/^(?:docs\/|README(?:\.[\w-]+)?\.md$)/.test(file.path) || [...templates.keys()].some(id => file.path.startsWith(`library/templates/catalog/${id}/source/`))) || /\/(?:vendor|node_modules)\//.test(file.path) || /\/(?:manifest|template)\.json$/.test(file.path)) continue;
+ const original = await load(file.path);
+ let text = original.toString();
+ for (const lock of locks) text = replaceReference(text, path.posix.relative(path.posix.dirname(file.path), lock.path), lock.url);
+ for (const [previous, current] of previousURLs) text = replaceReference(text, previous, current);
+ if (text !== original.toString()) edits.set(file.path, Buffer.from(text));
+ }
+ for (const [id, media] of templates) {
+ const prefix = `library/templates/catalog/${id}/source/`, name = prefix + 'manifest.json';
+ const sourceManifest = JSON.parse((await load(name)).toString());
+ const entries = new Map(sourceManifest.files.map((file: { path: string }) => [file.path, file]));
+ for (const lock of media) entries.set(lock.path.slice(prefix.length), { path: lock.path.slice(prefix.length), bytes: lock.bytes, sha256: lock.sha256 });
+ for (const [filename, bytes] of edits) if (filename.startsWith(prefix) && bytes) entries.set(filename.slice(prefix.length), { path: filename.slice(prefix.length), bytes: bytes.length, sha256: mediaDigest(bytes) });
+ sourceManifest.files = [...entries.values()].sort((a: any, b: any) => a.path.localeCompare(b.path));
+ edits.set(name, jsonBytes(sourceManifest));
+ }
+ if (locks.some(lock => !catalogAsset.test(lock.path))) {
+ manifest.files.sort((a, b) => a.path.localeCompare(b.path));
+ validateMediaManifest(manifest);
+ edits.set(manifestName, jsonBytes(manifest));
+ let ignore = files.has('.gitignore') ? (await load('.gitignore')).toString() : '';
+ for (const file of manifest.files) if (!ignore.split('\n').includes('/' + file.path)) ignore += '\n/' + file.path;
+ edits.set('.gitignore', Buffer.from(ignore.trimEnd() + '\n'));
+ }
+ const changes: CleanupChange[] = [];
+ for (const [name, bytes] of edits) {
+ const original = files.has(name) ? await load(name) : null;
+ if (original && bytes?.equals(original)) continue;
+ changes.push({ path: name, content: bytes?.toString('base64') ?? null });
+ }
+ // Finish building every metadata edit before publishing anything.
+ for (const lock of locks) if (transfer) await transfer(lock, originals.get(lock.path)!);
+ return { schemaVersion: 1, sourceSHA: inputs.sourceSHA, pullNumber: inputs.pullNumber, changes, media: locks };
+}
+
+/** Conditional immutable writes and public byte verification; never overwrite an existing key. */
+export async function publishMedia(lock: MediaLock, bytes: Buffer, options: { endpoint: string; bucket: string; run?: (args: string[]) => Promise<void>; fetcher?: typeof fetch }) {
+ assert.equal(bytes.length, lock.bytes); assert.equal(mediaDigest(bytes), lock.sha256);
+ const endpoint = new URL(options.endpoint);
+ assert(endpoint.protocol === 'https:' && endpoint.hostname.endsWith('.r2.cloudflarestorage.com') && endpoint.pathname === '/' && !endpoint.username && !endpoint.password && !endpoint.search && !endpoint.hash && !endpoint.port, 'Require the configured R2 HTTPS endpoint');
+ assert(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(options.bucket), 'Invalid media bucket');
+ validateMediaLock(lock);
+ const fetcher = options.fetcher ?? fetch;
+ const response = await fetcher(lock.url, { method: 'HEAD', redirect: 'error', signal: AbortSignal.timeout(30_000) });
+ if (response.status !== 404) {
+ assert.equal(response.status, 200, 'Cannot determine whether immutable media already exists');
+ await downloadMedia(lock, fetcher); return;
+ }
+ const directory = await mkdtemp(path.join(tmpdir(), 'openmotion-media-upload-'));
+ try {
+ const file = path.join(directory, 'media'); await writeFile(file, bytes);
+ const args = ['--endpoint-url', endpoint.origin, '--region', 'auto', 's3api', 'put-object', '--bucket', options.bucket,
+ '--key', mediaKey(lock.sha256, lock.path), '--body', file, '--if-none-match', '*', '--content-type', contentType(lock.path), '--cache-control', 'public, max-age=31536000, immutable'];
+ try {
+ if (options.run) await options.run(args);
+ else await execute('aws', args, { timeout: 180_000, env: { ...process.env, AWS_PAGER: '', AWS_EC2_METADATA_DISABLED: 'true' } });
+ } catch (error) { if (!/PreconditionFailed|\(412\)/.test(String(error))) throw error; }
+ await downloadMedia(lock, fetcher);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+}
+
+function contentType(name: string) {
+ const types: Record<string, string> = { mp4: 'video/mp4', m4v: 'video/mp4', avi: 'video/x-msvideo', m4a: 'audio/mp4', aac: 'audio/aac', flac: 'audio/flac', webm: 'video/webm', mov: 'video/quicktime', mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', avif: 'image/avif', gif: 'image/gif', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf' };
+ return types[path.extname(name).slice(1).toLowerCase()] ?? 'application/octet-stream';
+}
+
+export async function preparePullRequest(pullNumber: number, apply: boolean) {
+ assert(Number.isSafeInteger(pullNumber) && pullNumber > 0, 'Use a PR number');
+ if (apply && process.env.GITHUB_ACTIONS === 'true') {
+ assert.equal(process.env.GITHUB_EVENT_NAME, 'workflow_dispatch', 'Media transfer requires a maintainer-started workflow');
+ assert.equal(process.env.GITHUB_REF, 'refs/heads/main', 'Run the trusted media preparation workflow from main');
+ assert.equal(process.env.GITHUB_REPOSITORY, repository);
+ assert.equal(process.env.GITHUB_WORKFLOW_REF, repository + '/.github/workflows/prepare-pr-media.yml@refs/heads/main');
+ assert(process.env.OPENMOTION_MEDIA_MAINTAINER_TOKEN, 'Configure OPENMOTION_MEDIA_MAINTAINER_TOKEN before starting media preparation');
+ }
+ // The maintainer's own GitHub identity retains access to allow-maintainer-edits forks.
+ const token = process.env.OPENMOTION_MEDIA_MAINTAINER_TOKEN || (await execute('gh', ['auth', 'token'])).stdout.trim();
+ const api = async (route: string, target = repository) => {
+ assert(/^[\w.-]+\/[\w.-]+$/.test(target), 'Invalid GitHub repository');
+ const response = await fetch('https://api.github.com/repos/' + target + '/' + route, {
+ headers: { authorization: 'Bearer ' + token, accept: 'application/vnd.github+json' }, redirect: 'error', signal: AbortSignal.timeout(30_000),
+ });
+ assert(response.ok, `GitHub read failed: HTTP ${response.status}`);
+ return response.json() as Promise<any>;
+ };
+ const pr = await api('pulls/' + pullNumber);
+ assert(!apply || !pr.draft, 'Finish the content review and mark the PR ready before preparing media');
+ assert(pr.state === 'open' && pr.base.ref === 'main' && pr.head.repo, 'Require an open PR targeting main');
+ assert(pr.head.repo.full_name === repository || pr.maintainer_can_modify, 'Ask the contributor to enable Allow edits by maintainers on the original PR');
+ const settings = await fetch('https://api.github.com/repos/' + repository, { headers: { authorization: 'Bearer ' + token }, redirect: 'error' }).then(response => response.json()) as any;
+ assert(settings.permissions?.push, 'The configured GitHub identity must have maintainer write access');
+ assert(settings.allow_squash_merge && !settings.allow_merge_commit && !settings.allow_rebase_merge, 'Configure Squash merge only before transferring media; other merge methods retain intermediate large blobs');
+ const head = await api(`git/trees/${pr.head.sha}?recursive=1`, pr.head.repo.full_name), base = await api(`git/trees/${pr.base.sha}?recursive=1`);
+ assert(!head.truncated && !base.truncated, 'GitHub tree truncated; split this PR');
+ const read = async (file: TreeFile) => {
+ assert(file.size <= maxMediaBytes, 'Git blob exceeds media budget');
+ const response = await fetch(`https://api.github.com/repos/${pr.head.repo.full_name}/git/blobs/${file.sha}`, { headers: { authorization: 'Bearer ' + token, accept: 'application/vnd.github.raw+json' }, redirect: 'error', signal: AbortSignal.timeout(120_000) });
+ assert(response.ok, `GitHub blob unavailable: ${file.path}`);
+ const bytes = await boundedMediaBody(response, file.size); assert.equal(bytes.length, file.size);
+ return bytes;
+ };
+ const transfer: Transfer = async (lock, raw) => {
+ let bytes = raw;
+ if (lfsPointer(raw)) {
+ const response = await fetch(`https://github.com/${pr.head.repo.full_name}.git/info/lfs/objects/batch`, {
+ method: 'POST', headers: { authorization: 'Basic ' + Buffer.from('x-access-token:' + token).toString('base64'), 'content-type': 'application/vnd.git-lfs+json', accept: 'application/vnd.git-lfs+json' },
+ body: JSON.stringify({ operation: 'download', transfers: ['basic'], objects: [{ oid: lock.sha256, size: lock.bytes }] }), redirect: 'error', signal: AbortSignal.timeout(30_000),
+ });
+ assert(response.ok, 'Cannot resolve existing LFS media');
+ const batch: any = await response.json(), action = batch.objects?.[0]?.actions?.download;
+ assert(action, 'LFS object is not available on the contributor remote');
+ const url = new URL(action.href);
+ assert(url.protocol === 'https:' && /(?:\.githubusercontent\.com|\.amazonaws\.com)$/.test(url.hostname) && !url.username && !url.password, 'Unexpected GitHub LFS download origin');
+ const download = await fetch(url, { headers: action.header, redirect: 'error', signal: AbortSignal.timeout(120_000) });
+ bytes = await boundedMediaBody(download, lock.bytes);
+ }
+ await publishMedia(lock, bytes, { endpoint: process.env.MOTION_R2_ENDPOINT ?? 'https://64ad4569ffd912432d6b86d5656484c4.r2.cloudflarestorage.com', bucket: process.env.MOTION_R2_BUCKET ?? 'open-design-releases' });
+ };
+ const inputs = { head: head.tree, base: base.tree, sourceSHA: pr.head.sha, pullNumber };
+ const plan = await prepareMediaCleanup(inputs, read);
+ const changed = new Map(inputs.base.map((file: TreeFile) => [file.path, file.sha]));
+ for (const file of inputs.head) if (file.type === 'blob' && file.sha !== changed.get(file.path) && file.size > 1024 * 1024)
+ assert(plan.media.some(lock => lock.path === file.path), 'Non-media Git blob exceeds 1 MiB: ' + file.path);
+ console.log(JSON.stringify({ pullNumber, sourceSHA: plan.sourceSHA, files: plan.media.length, bytes: plan.media.reduce((sum, file) => sum + file.bytes, 0), apply }, null, 2));
+ if (!apply || !plan.media.length) return plan;
+ // Finish validation/planning first. Failed uploads leave the PR unchanged.
+ await pushCleanup(plan, pr.head.repo.full_name, pr.head.ref, token, async push => finalizeMediaCleanup(plan, async () => {
+ for (const lock of plan.media) await transfer(lock, await read(inputs.head.find((file: TreeFile) => file.path === lock.path)!));
+ }, async () => (await api('pulls/' + pullNumber)).head.sha, push));
+ if (process.env.GITHUB_STEP_SUMMARY) await writeFile(process.env.GITHUB_STEP_SUMMARY,
+ `Prepared original PR #${pullNumber}: ${plan.media.length} media files were uploaded and publicly hash-verified.\n\nThe cleanup commit retains the original PR and contributor. Wait for CI and review of the new commit, then use Squash and merge. No PR was merged by this workflow.\n`, { flag: 'a' });
+ return plan;
+}
+
+type GitRunner = (args: string[], input?: string, authenticated?: boolean) => Promise<string>;
+
+export async function commitCleanup(plan: CleanupPlan, git: GitRunner, directory: string, identity: { login: string; id: number }) {
+ assert(/^[a-f0-9]{40}$/.test(plan.sourceSHA), 'Invalid PR source SHA');
+ await git(['update-ref', 'HEAD', plan.sourceSHA]);
+ await git(['read-tree', plan.sourceSHA]);
+ for (const change of plan.changes) {
+ if (change.content === null) await git(['update-index', '--force-remove', '--', change.path]);
+ else {
+ const oid = await git(['hash-object', '-w', '--stdin'], Buffer.from(change.content, 'base64').toString());
+ const existing = await git(['ls-files', '--stage', '--', change.path]);
+ const mode = existing.startsWith('100755 ') ? '100755' : '100644';
+ await git(['update-index', '--add', '--cacheinfo', mode, oid, change.path]);
+ }
+ }
+ const errors = [...checkTemplateLibrary(directory), ...checkRepositoryStorage(directory).errors];
+ assert.deepEqual(errors, [], 'Sanitized PR failed final-tree validation: ' + errors.join('\n'));
+ const tree = await git(['write-tree']);
+ assert(/^[\w-]+$/.test(identity.login) && Number.isSafeInteger(identity.id) && identity.id > 0, 'Invalid maintainer identity');
+ return git(['-c', 'user.name=' + identity.login, '-c', `user.email=${identity.id}+${identity.login}@users.noreply.github.com`,
+ 'commit-tree', tree, '-p', plan.sourceSHA], 'chore: replace reviewed media with verified public links\n');
+}
+
+async function pushCleanup(plan: CleanupPlan, headRepository: string, branch: string, token: string, finish: (push: () => Promise<void>) => Promise<void>) {
+ assert(/^[\w.-]+\/[\w.-]+$/.test(headRepository), 'Invalid contributor repository');
+ const directory = await mkdtemp(path.join(tmpdir(), 'openmotion-media-commit-'));
+ const git = async (args: string[], input?: string, authenticated = false) => {
+ // git never checks out or executes contributor files, hooks, filters or .lfsconfig.
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_COUNT: authenticated ? '1' : '0',
+ ...(authenticated ? { GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader', GIT_CONFIG_VALUE_0: 'AUTHORIZATION: basic ' + Buffer.from('x-access-token:' + token).toString('base64') } : {}) };
+ const child = execFile('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'credential.helper=', ...args], { cwd: directory, env, timeout: 180_000, maxBuffer: 1024 * 1024 });
+ if (input !== undefined) child.stdin?.end(input);
+ return new Promise<string>((resolve, reject) => {
+ let output = '', error = ''; child.stdout?.on('data', chunk => output += chunk); child.stderr?.on('data', chunk => error += chunk);
+ child.on('error', reject); child.on('close', code => code === 0 ? resolve(output.trim()) : reject(new Error('Git operation failed: ' + error)));
+ });
+ };
+ try {
+ await git(['-c', 'init.templateDir=', 'init', '-q']);
+ await git(['fetch', '--depth=1', 'https://github.com/' + repository + '.git', `refs/pull/${plan.pullNumber}/head`], undefined, true);
+ assert.equal(await git(['rev-parse', 'FETCH_HEAD']), plan.sourceSHA, 'PR changed before cleanup commit');
+ const response = await fetch('https://api.github.com/user', { headers: { authorization: 'Bearer ' + token }, redirect: 'error' });
+ assert(response.ok, 'Cannot resolve the maintainer identity');
+ const identity: any = await response.json();
+ const commit = await commitCleanup(plan, git, directory, identity);
+ // This also checks fork write access before storage is touched. Nothing is pushed.
+ await git(['push', '--dry-run', 'https://github.com/' + headRepository + '.git', `${commit}:refs/heads/${branch}`], undefined, true);
+ await finish(async () => { await git(['push', 'https://github.com/' + headRepository + '.git', `${commit}:refs/heads/${branch}`], undefined, true); });
+ } finally { await rm(directory, { recursive: true, force: true }); }
+}
+
+if (isMain(import.meta.url)) {
+ const [number, flag, extra] = process.argv.slice(2);
+ assert(!extra && (!flag || flag === '--apply'), 'Usage: prepare-pr-media.ts <PR-number> [--apply]');
+ await preparePullRequest(Number(number), flag === '--apply');
+}
diff --git a/scripts/repository-media.ts b/scripts/repository-media.ts
new file mode 100644
index 00000000..83fd0dc9
--- /dev/null
+++ b/scripts/repository-media.ts
@@ -0,0 +1,45 @@
+import assert from 'node:assert/strict';
+import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { isMain } from '../shared/entry.ts';
+import { downloadMedia, mediaDigest, mediaPath, validateMediaManifest } from '../shared/repository-media.ts';
+
+const root = fileURLToPath(new URL('../', import.meta.url));
+
+async function safeDestination(directory: string, name: string): Promise<string> {
+ mediaPath(name);
+ let current = directory;
+ for (const part of name.split('/')) {
+ current = path.join(current, part);
+ const info = await lstat(current).catch(error => { if (error.code !== 'ENOENT') throw error; return undefined; });
+ assert(!info?.isSymbolicLink(), 'Media operations must not follow symlinks');
+ }
+ return current;
+}
+
+export async function pullMedia(directory = root, prefix?: string, fetcher: typeof fetch = fetch) {
+ const manifest = validateMediaManifest(JSON.parse(await readFile(path.join(directory, 'repository-media.json'), 'utf8')));
+ if (prefix) mediaPath(prefix.replace(/\/$/, ''));
+ const selected = manifest.files.filter(file => !prefix || file.path === prefix || file.path.startsWith(prefix.replace(/\/$/, '') + '/'));
+ assert(!prefix || selected.length, 'No media matches the selected path');
+ for (const file of selected) {
+ const destination = await safeDestination(directory, file.path);
+ const present = await readFile(destination).catch(error => { if (error.code !== 'ENOENT') throw error; });
+ if (present && present.length === file.bytes && mediaDigest(present) === file.sha256) continue;
+ const bytes = await downloadMedia(file, fetcher);
+ await mkdir(path.dirname(destination), { recursive: true });
+ // Exclusive temporary file creation also prevents following a pre-existing symlink.
+ const temporary = destination + '.download-' + process.pid;
+ await writeFile(temporary, bytes, { flag: 'wx' });
+ try { await rename(temporary, destination); }
+ finally { await rm(temporary, { force: true }); }
+ }
+ return { selected: selected.length };
+}
+
+if (isMain(import.meta.url)) {
+ const [prefix, extra] = process.argv.slice(2);
+ assert(!extra, 'Usage: repository-media.ts [path-prefix]');
+ console.log(JSON.stringify(await pullMedia(root, prefix)));
+}
diff --git a/scripts/template-library.ts b/scripts/template-library.ts
index 3601398c..ae1500b7 100644
--- a/scripts/template-library.ts
+++ b/scripts/template-library.ts
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
import { inflateRawSync } from 'node:zlib';
import { loadRepositoryCatalog, lfsPointer, repositoryAssetFile, repositoryMediaFile } from '../shared/repository-template-catalog.ts';
import { isMain } from '../shared/entry.ts';
+import { mediaOrigin, validateMediaLock } from '../shared/repository-media.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;
@@ -65,6 +66,16 @@ export function cmsUrl(value: unknown): string {
);
return value;
}
+export function publicAssetUrl(value: unknown): string {
+ assert(typeof value === 'string', 'Missing public asset URL');
+ if (value.startsWith(mediaOrigin + '/')) {
+ const match = /\/([a-f0-9]{64})\.([a-z0-9]+)$/.exec(value);
+ assert(match, 'Invalid public media URL');
+ validateMediaLock({ path: 'asset.' + match[2], url: value, sha256: match[1], bytes: 1 });
+ return value;
+ }
+ return cmsUrl(value);
+}
export function validateRecord(record: TemplateRecord, id: string, locales: string[]): void {
assert(
/^[a-z][a-z0-9-]+$/.test(id) && record.templateId === id && record.entry.templateId === id,
@@ -85,19 +96,26 @@ export function validateRecord(record: TemplateRecord, id: string, locales: stri
assert(Array.isArray(remoteAssets), 'Invalid remote assets');
const remotePaths = new Set<string>();
for (const asset of remoteAssets) {
- validateArchive(asset);
+ publicAssetUrl(asset.url);
const source = asset.source;
safePath(source.path);
assert(
- source.path.startsWith('assets/') && assetFile.test(source.path),
- 'Remote assets must be images/fonts in source/assets/',
+ source.path.startsWith('assets/') && repositoryMediaFile.test(source.path),
+ 'Remote assets must be media in source/assets/',
);
assert(
Number.isSafeInteger(source.bytes) &&
- source.bytes > maxLocalAssetBytes &&
+ source.bytes > 0 && source.bytes <= maxArchiveBytes &&
/^[a-f0-9]{64}$/.test(source.sha256),
'Invalid original remote asset identity',
);
+ if (asset.url.startsWith(mediaOrigin + '/')) {
+ validateMediaLock({ path: source.path, ...asset });
+ assert(asset.bytes === source.bytes && asset.sha256 === source.sha256, 'Transferred media must retain its original identity');
+ } else {
+ validateArchive(asset);
+ assert(assetFile.test(source.path) && source.bytes > maxLocalAssetBytes, 'CMS renditions represent large original images/fonts');
+ }
assert(!remotePaths.has(source.path), 'Duplicate remote asset path');
remotePaths.add(source.path);
}
@@ -109,12 +127,12 @@ export function validateRecord(record: TemplateRecord, id: string, locales: stri
);
assert(Array.isArray(item.files), 'Missing project file manifest');
for (const key of ['previewUrl', 'coverUrl', 'motionDocumentUrl', 'motionGuideUrl', 'projectFileUrl']) {
- if (item[key]) cmsUrl(item[key]);
+ if (item[key]) publicAssetUrl(item[key]);
}
assert.equal(item.previewUrl, record.entry.previewUrl, 'Reference video must be shared across locales');
for (const file of item.files) {
safePath(file.path);
- cmsUrl(file.url);
+ publicAssetUrl(file.url);
assert(
Number.isSafeInteger(file.bytes) && file.bytes > 0 && /^[a-f0-9]{64}$/.test(file.sha256),
'Invalid project file lock',
@@ -344,8 +362,12 @@ export async function refreshManifest(id: string, root = catalogRoot): Promise<v
const source = path.join(root, id, 'source');
const manifest = await json(path.join(source, 'manifest.json'));
const record: TemplateRecord = await json(path.join(root, id, 'template.json'));
- const files: FileLock[] = (record.remoteAssets ?? []).map((asset) => asset.source);
- for (const name of await sourceFiles(source)) {
+ const names = await sourceFiles(source);
+ // Reintroduced R2 media is a draft revision; final preparation replaces its old remote identity.
+ const files: FileLock[] = (record.remoteAssets ?? [])
+ .filter(asset => !(asset.url.startsWith(mediaOrigin + '/') && names.includes(asset.source.path)))
+ .map(asset => asset.source);
+ for (const name of names) {
if (name === 'manifest.json') continue;
const bytes = await readFile(path.join(source, safePath(name)));
const pointer = lfsPointer(bytes);
diff --git a/scripts/test-package.mjs b/scripts/test-package.mjs
index 36cc8fd2..8ef0b95e 100644
--- a/scripts/test-package.mjs
+++ b/scripts/test-package.mjs
@@ -6,7 +6,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
import { releaseProfile } from '../shared/mcp-registry.ts';
-import { distributionFiles } from './distribution.ts';
+import { distributionFiles, requireDownloadedMedia } from './distribution.ts';
import { packageTemplateConfig } from '../shared/template-config.ts';
import { checkReleaseVersion, testVersion } from './release-version.mjs';
export { checkReleaseVersion, testVersion } from './release-version.mjs';
@@ -74,7 +74,9 @@ export async function build(target, version, profile = releaseProfile, templateE
const directory = path.join(root, 'dist', version), name = `OpenMotion-Codex-${version}-${target}${suffix}`;
const stage = path.join(directory, name), runtime = path.join(root, '.artifacts', 'test-runtime', target, 'runtime');
await mkdir(directory, { recursive: true }); await mkdir(stage);
- for (const file of await distributionFiles(profile)) {
+ const files = await distributionFiles(profile);
+ await requireDownloadedMedia(files);
+ for (const file of files) {
await mkdir(path.dirname(path.join(stage, file)), { recursive: true });
await cp(path.join(root, file), path.join(stage, file));
}
diff --git a/shared/repository-media.ts b/shared/repository-media.ts
new file mode 100644
index 00000000..d9c6ccd4
--- /dev/null
+++ b/shared/repository-media.ts
@@ -0,0 +1,66 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+
+export const mediaOrigin = 'https://releases.open-design.ai';
+export const mediaPrefix = 'open-motion/media/sha256/';
+export const maxMediaBytes = 50 * 1024 * 1024;
+export type MediaLock = { path: string; url: string; bytes: number; sha256: string };
+export type MediaManifest = { schemaVersion: 1; files: MediaLock[] };
+export const mediaDigest = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');
+
+export function mediaPath(name: string): string {
+ assert(typeof name === 'string' && name.length < 500 && /^[\w/.@+ -]+$/.test(name) &&
+ !name.startsWith('/') && name.split('/').every(part => part && part !== '.' && part !== '..' && part !== '.git'), 'Unsafe media path');
+ return name;
+}
+
+export function mediaKey(sha256: string, name: string): string {
+ assert(/^[a-f0-9]{64}$/.test(sha256), 'Invalid media SHA-256');
+ const extension = /\.(mp4|mov|webm|m4v|avi|mp3|wav|ogg|m4a|aac|flac|png|jpe?g|webp|avif|gif|woff2?|ttf|otf|motion)$/i.exec(name)?.[1].toLowerCase();
+ assert(extension, 'Unsupported transfer media type');
+ return mediaPrefix + sha256 + '.' + extension;
+}
+
+export function validateMediaLock(file: MediaLock): void {
+ mediaPath(file.path);
+ assert(Number.isSafeInteger(file.bytes) && file.bytes > 0 && file.bytes <= maxMediaBytes, 'Media exceeds 50 MiB or has invalid size');
+ assert.equal(file.url, mediaOrigin + '/' + mediaKey(file.sha256, file.path), 'Require an immutable public media URL matching its SHA-256');
+}
+
+export function validateMediaManifest(value: MediaManifest): MediaManifest {
+ assert(value.schemaVersion === 1 && Array.isArray(value.files), 'Invalid repository media manifest');
+ const paths = new Set<string>();
+ for (const file of value.files) {
+ validateMediaLock(file);
+ assert(/^(?:docs\/readme|library|examples)\//.test(file.path) && !file.path.startsWith('library/templates/catalog/'), 'Catalog media belongs in template.json.remoteAssets');
+ assert(!paths.has(file.path), 'Duplicate repository media path');
+ paths.add(file.path);
+ }
+ return value;
+}
+
+/** Read a bounded stream; never follow redirects or accept partial/corrupt media. */
+export async function boundedMediaBody(response: Response, limit: number): Promise<Buffer> {
+ assert.equal(response.status, 200, `Media download returned HTTP ${response.status}`);
+ assert(response.body, 'Missing media body');
+ const chunks: Buffer[] = [];
+ let length = 0;
+ for await (const chunk of response.body) {
+ length += chunk.length;
+ if (length > limit) {
+ throw new Error('Media response exceeds its declared size');
+ }
+ chunks.push(Buffer.from(chunk));
+ }
+ const bytes = Buffer.concat(chunks);
+ return bytes;
+}
+
+export async function downloadMedia(file: MediaLock, fetcher: typeof fetch = fetch): Promise<Buffer> {
+ validateMediaLock(file);
+ const response = await fetcher(file.url, { redirect: 'error', signal: AbortSignal.timeout(120_000) });
+ const bytes = await boundedMediaBody(response, file.bytes);
+ assert.equal(bytes.length, file.bytes, 'Media size mismatch');
+ assert.equal(mediaDigest(bytes), file.sha256, 'Media SHA-256 mismatch');
+ return bytes;
+}
diff --git a/tests/library-install.test.mjs b/tests/library-install.test.mjs
index ede09fce..96419980 100644
--- a/tests/library-install.test.mjs
+++ b/tests/library-install.test.mjs
@@ -4,6 +4,7 @@ import { cp, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
import { installLibrarySkill } from '../scripts/install-library-skill.mjs';
const pairs = { brandkit: 'openmotion-brandkit', 'presenter-story': 'openmotion-presenter-story', 'motion-design-remix': 'openmotion-design-remix' };
@@ -63,6 +64,44 @@ test('installation preserves customized dependencies and does not leave a partia
await assert.rejects(installLibrarySkill('../foreign', root), /Unknown Library Skill/);
});
+// Legacy single-folder recovery intentionally retains its original raw-media snapshot.
+// Compare hydrated content trees so changing media storage does not change the pin.
+function hydratedSkillTree(relative) {
+ const run = (args, input) => {
+ const result = spawnSync('git', args, { encoding: 'utf8', input });
+ assert.equal(result.status, 0, result.stderr);
+ return result.stdout.trim();
+ };
+ const entries = run(['ls-tree', '-r', '-z', `HEAD:${relative}`]).split('\0').filter(Boolean);
+ for (const file of JSON.parse(readFileSync(new URL('../repository-media.json', import.meta.url), 'utf8')).files) {
+ if (!file.path.startsWith(relative + '/')) continue;
+ const name = file.path.slice(relative.length + 1);
+ if (!entries.some(entry => entry.split('\t')[1] === name))
+ entries.push(`100644 blob ${run(['hash-object', '--no-filters', file.path])}\t${name}`);
+ }
+ const directories = new Map([['', []]]);
+ for (const entry of entries) {
+ const [metadata, name] = entry.split('\t');
+ let [mode, type, oid] = metadata.split(' ');
+ if (name.endsWith('.mp4')) oid = run(['hash-object', '--no-filters', relative + '/' + name]);
+ let directory = path.posix.dirname(name);
+ if (directory === '.') directory = '';
+ let ancestor = directory;
+ while (ancestor) {
+ if (!directories.has(ancestor)) directories.set(ancestor, []);
+ ancestor = path.posix.dirname(ancestor);
+ if (ancestor === '.') ancestor = '';
+ }
+ directories.get(directory).push(`${mode} ${type} ${oid}\t${path.posix.basename(name)}\0`);
+ }
+ for (const directory of [...directories.keys()].sort((a, b) => b.split('/').length - a.split('/').length || b.length - a.length)) {
+ const tree = run(['mktree', '--missing', '-z'], directories.get(directory).join(''));
+ if (!directory) return tree;
+ const parent = path.posix.dirname(directory);
+ directories.get(parent === '.' ? '' : parent).push(`040000 tree ${tree}\t${path.posix.basename(directory)}\0`);
+ }
+}
+
test('a generic single-folder alias installation includes matching pinned dependency recovery', async t => {
const root = await isolated(t);
for (const [old, canonical] of Object.entries(pairs)) {
@@ -79,8 +118,6 @@ test('a generic single-folder alias installation includes matching pinned depend
'openmotion-design-remix': '18dc7b5af383fac1eacd1dfdab87bf31af76efa3',
};
assert.equal(match[2], 'af755bcdd7f8af257186ff8723aedf78b176577a');
- const tree = spawnSync('git', ['rev-parse', `HEAD:library/skills/${canonical}`], { encoding: 'utf8' });
- assert.equal(tree.status, 0, tree.stderr);
- assert.equal(tree.stdout.trim(), trees[canonical], 'Pinned fallback workflow and all resources must match this version');
+ assert.equal(hydratedSkillTree(`library/skills/${canonical}`), trees[canonical], 'Pinned fallback workflow and all hydrated resources must match this version');
}
});
diff --git a/tests/media-transfer.test.ts b/tests/media-transfer.test.ts
new file mode 100644
index 00000000..770fcb47
--- /dev/null
+++ b/tests/media-transfer.test.ts
@@ -0,0 +1,179 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { commitCleanup, finalizeMediaCleanup, prepareMediaCleanup, preparePullRequest, publishMedia, type TreeFile } from '../scripts/prepare-pr-media.ts';
+import { pullMedia } from '../scripts/repository-media.ts';
+import { downloadMedia, mediaDigest, mediaKey, mediaOrigin, validateMediaManifest, type MediaLock } from '../shared/repository-media.ts';
+import { refreshManifest } from '../scripts/template-library.ts';
+
+const sourceSHA = 'a'.repeat(40), prefix = 'library/templates/catalog/motion-demo/';
+function fixture() {
+ const bytes = Buffer.alloc(128, 42), video = prefix + 'source/assets/reference.mp4';
+ const record = { templateId: 'motion-demo', entry: { templateId: 'motion-demo', original: { templateName: 'Demo' }, files: [] }, locales: { en: {} }, localMedia: { preview: 'assets/reference.mp4' } };
+ const contents = new Map<string, Buffer>([
+ [video, bytes],
+ [prefix + 'source/motion.md', Buffer.from('# Demo\n[Reference](assets/reference.mp4)\n')],
+ [prefix + 'source/preview.html', Buffer.from('<video src="assets/reference.mp4"></video>')],
+ [prefix + 'TEMPLATE.md', Buffer.from('# Usage')],
+ [prefix + 'template.json', Buffer.from(JSON.stringify(record))],
+ ['library/templates/catalog/catalog.json', Buffer.from(JSON.stringify({ schemaVersion: 1, publication: { defaultLocale: 'en', locales: ['en'] }, templateIds: ['motion-demo'] }))],
+ ['repository-media.json', Buffer.from('{"schemaVersion":1,"files":[]}')],
+ ['.gitignore', Buffer.from('.artifacts/\n')],
+ ]);
+ contents.set(prefix + 'source/manifest.json', Buffer.from(JSON.stringify({ files: [...contents].filter(([name]) => name.startsWith(prefix + 'source/')).map(([name, bytes]) => ({ path: name.slice((prefix + 'source/').length), bytes: bytes.length, sha256: mediaDigest(bytes) })) })));
+ const tree = (): TreeFile[] => [...contents].map(([name, bytes]) => ({ path: name, type: 'blob', mode: '100644', sha: createHash('sha1').update(bytes).digest('hex'), size: bytes.length }));
+ const read = async (file: TreeFile) => contents.get(file.path)!;
+ const inputs = () => ({ head: tree(), base: [], sourceSHA, pullNumber: 42 });
+ return { bytes, video, contents, tree, read, inputs };
+}
+
+async function isolated(t: { after: (fn: () => Promise<void>) => void }) {
+ const directory = await mkdtemp(path.join(tmpdir(), 'openmotion-media-test-'));
+ t.after(() => rm(directory, { recursive: true, force: true }));
+ return directory;
+}
+
+function git(directory: string, args: string[], input?: string): string {
+ const result = spawnSync('git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: directory, input, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr); return result.stdout.trim();
+}
+
+test('final preparation keeps the PR, original media identity and roles while replacing guide links', async () => {
+ const f = fixture();
+ const plan = await prepareMediaCleanup(f.inputs(), f.read);
+ assert.equal(plan.pullNumber, 42); assert.equal(plan.sourceSHA, sourceSHA); assert.equal(plan.media.length, 1);
+ assert.equal(plan.changes.find(change => change.path === f.video)!.content, null);
+ const value = (name: string) => Buffer.from(plan.changes.find(change => change.path === name)!.content!, 'base64').toString();
+ const record = JSON.parse(value(prefix + 'template.json'));
+ assert.equal(record.localMedia.preview, 'assets/reference.mp4');
+ assert.deepEqual(record.remoteAssets[0].source, { path: 'assets/reference.mp4', bytes: f.bytes.length, sha256: mediaDigest(f.bytes) });
+ assert(value(prefix + 'source/preview.html').includes(plan.media[0].url));
+ const manifest = JSON.parse(value(prefix + 'source/manifest.json'));
+ assert.equal(manifest.files.find((file: any) => file.path === 'preview.html').sha256, mediaDigest(Buffer.from(value(prefix + 'source/preview.html'))));
+ assert(f.contents.has(f.video), 'Planning never changes the original files');
+ assert.equal((await prepareMediaCleanup({ ...f.inputs(), base: f.tree() }, f.read)).media.length, 0, 'Unchanged media is not reuploaded');
+});
+
+test('cleanup accepts LFS as an input and records legacy paths for verified optional downloads', async () => {
+ const f = fixture(), name = 'docs/readme/demo.mp4';
+ f.contents.set(name, Buffer.from(`version https://git-lfs.github.com/spec/v1\noid sha256:${mediaDigest(f.bytes)}\nsize ${f.bytes.length}\n`));
+ const plan = await prepareMediaCleanup(f.inputs(), f.read);
+ const manifest = validateMediaManifest(JSON.parse(Buffer.from(plan.changes.find(change => change.path === 'repository-media.json')!.content!, 'base64').toString()));
+ assert.equal(manifest.files[0].path, name); assert.equal(manifest.files[0].sha256, mediaDigest(f.bytes));
+ assert(Buffer.from(plan.changes.find(change => change.path === '.gitignore')!.content!, 'base64').toString().includes('/' + name));
+});
+
+test('encoded filenames and a later revision of prepared media retain working references', async t => {
+ const f = fixture(), name = prefix + 'source/assets/ref one.mp4';
+ f.contents.set(name, f.bytes);
+ f.contents.set(prefix + 'source/preview.html', Buffer.from('<video src="assets/ref%20one.mp4"></video>'));
+ const first = await prepareMediaCleanup(f.inputs(), f.read);
+ for (const change of first.changes) {
+ if (change.content === null) f.contents.delete(change.path);
+ else f.contents.set(change.path, Buffer.from(change.content, 'base64'));
+ }
+ const before = f.tree(), oldURL = first.media.find(file => file.path === name)!.url;
+ assert(f.contents.get(prefix + 'source/preview.html')!.toString().includes(oldURL));
+ const revised = Buffer.alloc(129, 43); f.contents.set(name, revised);
+ const directory = await isolated(t);
+ for (const [file, bytes] of f.contents) { await mkdir(path.dirname(path.join(directory, file)), { recursive: true }); await writeFile(path.join(directory, file), bytes); }
+ await refreshManifest('motion-demo', path.join(directory, 'library/templates/catalog'));
+ const manifest = JSON.parse(await readFile(path.join(directory, prefix + 'source/manifest.json'), 'utf8'));
+ assert.equal(manifest.files.filter((file: any) => file.path === 'assets/ref one.mp4').length, 1);
+ assert.equal(manifest.files.find((file: any) => file.path === 'assets/ref one.mp4').sha256, mediaDigest(revised));
+ const next = await prepareMediaCleanup({ ...f.inputs(), base: before }, f.read);
+ const guide = Buffer.from(next.changes.find(change => change.path === prefix + 'source/preview.html')!.content!, 'base64').toString();
+ assert(!guide.includes(oldURL)); assert(guide.includes(next.media[0].url));
+});
+
+test('invalid input and a failed transfer cannot publish cleanup or mutate the input', async () => {
+ const f = fixture(); let uploaded = false;
+ const bad = f.inputs(); bad.head.find(file => file.path === f.video)!.mode = '120000';
+ await assert.rejects(prepareMediaCleanup(bad, f.read, async () => { uploaded = true; })); assert.equal(uploaded, false);
+ const tooLarge = f.inputs(); tooLarge.head.find(file => file.path === f.video)!.size = 50 * 1024 * 1024 + 1;
+ await assert.rejects(prepareMediaCleanup(tooLarge, f.read, async () => { uploaded = true; }), /50 MiB/); assert.equal(uploaded, false);
+ await assert.rejects(prepareMediaCleanup(f.inputs(), f.read, async () => { throw Error('Upload failed'); }), /Upload failed/);
+ assert(f.contents.has(f.video));
+});
+
+test('failed upload, changed PR head and rejected write never report a completed PR update', async () => {
+ const f = fixture(), plan = await prepareMediaCleanup(f.inputs(), f.read); let pushed = false;
+ const push = async () => { pushed = true; };
+ await assert.rejects(finalizeMediaCleanup(plan, async () => { throw Error('Upload failed'); }, async () => sourceSHA, push), /Upload failed/);
+ assert.equal(pushed, false);
+ await assert.rejects(finalizeMediaCleanup(plan, async () => {}, async () => 'b'.repeat(40), push), /PR changed/);
+ assert.equal(pushed, false);
+ await assert.rejects(finalizeMediaCleanup(plan, async () => {}, async () => sourceSHA, async () => { throw Error('Write access denied'); }), /Write access denied/);
+ await finalizeMediaCleanup(plan, async () => {}, async () => sourceSHA, push); assert.equal(pushed, true);
+});
+
+test('public writes are conditional, confined to the media prefix and verified before success', async () => {
+ const f = fixture(), lock = (await prepareMediaCleanup(f.inputs(), f.read)).media[0]; let stored = false, puts = 0;
+ const fetcher = async (_: any, options?: any) => new Response(options?.method === 'HEAD' ? null : new Uint8Array(f.bytes), { status: stored ? 200 : 404 });
+ const options = { endpoint: 'https://example.r2.cloudflarestorage.com', bucket: 'test-media', fetcher: fetcher as typeof fetch, run: async (args: string[]) => {
+ assert.equal(args[args.indexOf('--key') + 1], mediaKey(lock.sha256, lock.path));
+ assert.equal(args[args.indexOf('--if-none-match') + 1], '*');
+ assert.equal(mediaDigest(await readFile(args[args.indexOf('--body') + 1])), lock.sha256);
+ puts++; stored = true;
+ } };
+ await publishMedia(lock, f.bytes, options); assert.equal(puts, 1);
+ await publishMedia(lock, f.bytes, options); assert.equal(puts, 1);
+ await assert.rejects(publishMedia(lock, Buffer.alloc(f.bytes.length), options), /Assertion/);
+ await assert.rejects(publishMedia(lock, f.bytes, { ...options, fetcher: (async () => new Response(new Uint8Array(Buffer.alloc(lock.bytes)), { status: 200 })) as typeof fetch }), /SHA-256 mismatch/);
+});
+
+test('optional media pulls restore exact bytes, reuse valid files and reject corrupt bodies and symlinks', async t => {
+ const directory = await isolated(t), bytes = Buffer.alloc(128, 42), sha256 = mediaDigest(bytes);
+ const lock: MediaLock = { path: 'docs/readme/demo.mp4', bytes: bytes.length, sha256, url: mediaOrigin + '/' + mediaKey(sha256, 'demo.mp4') };
+ await writeFile(path.join(directory, 'repository-media.json'), JSON.stringify({ schemaVersion: 1, files: [lock] }));
+ let requests = 0;
+ const fetcher = (async () => { requests++; return new Response(new Uint8Array(bytes)); }) as typeof fetch;
+ assert.deepEqual(await pullMedia(directory, 'docs/readme', fetcher), { selected: 1 });
+ await pullMedia(directory, undefined, fetcher); assert.equal(requests, 1);
+ assert.deepEqual(await readFile(path.join(directory, lock.path)), bytes);
+ await assert.rejects(downloadMedia(lock, (async () => new Response(new Uint8Array(Buffer.alloc(129)))) as typeof fetch), /exceeds/);
+ await assert.rejects(downloadMedia(lock, (async () => new Response(new Uint8Array(Buffer.alloc(128)))) as typeof fetch), /SHA-256/);
+ await rm(path.join(directory, lock.path));
+ await symlink(path.join(directory, 'repository-media.json'), path.join(directory, lock.path));
+ await assert.rejects(pullMedia(directory, undefined, fetcher), /symlinks/);
+});
+
+test('a real cleanup commit passes final-tree policy and Squash keeps raw contribution blobs out of main', async t => {
+ const directory = await isolated(t), f = fixture();
+ git(directory, ['-c', 'init.templateDir=', 'init', '-b', 'main']);
+ git(directory, ['config', 'user.name', 'Contributor']); git(directory, ['config', 'user.email', '[email protected]']);
+ const write = async (name: string, bytes: Buffer) => { await mkdir(path.dirname(path.join(directory, name)), { recursive: true }); await writeFile(path.join(directory, name), bytes); };
+ // The base already has the template; the contributor adds its final media in the PR.
+ for (const [name, bytes] of f.contents) if (name !== f.video) await write(name, bytes);
+ git(directory, ['add', '.']); git(directory, ['commit', '-qm', 'Template source']);
+ const base = git(directory, ['rev-parse', 'HEAD']);
+ git(directory, ['checkout', '-qb', 'contribution']);
+ await write(f.video, f.bytes); git(directory, ['add', '.']); git(directory, ['commit', '-qm', 'Add reviewed reference']);
+ const original = git(directory, ['rev-parse', 'HEAD']), rawOID = git(directory, ['rev-parse', 'HEAD:' + f.video]);
+ const plan = await prepareMediaCleanup({ ...f.inputs(), sourceSHA: original }, f.read);
+ const commit = await commitCleanup(plan, async (args, input) => git(directory, args, input), directory, { login: 'Maintainer', id: 123 });
+ assert.equal(git(directory, ['rev-parse', commit + '^']), original);
+ git(directory, ['update-ref', 'refs/heads/contribution', commit]);
+ git(directory, ['reset', '--hard', commit]);
+ git(directory, ['checkout', 'main']); git(directory, ['merge', '--squash', 'contribution']); git(directory, ['commit', '-qm', 'Accept original contribution']);
+ assert.equal(git(directory, ['rev-parse', 'HEAD^']), base);
+ assert(!git(directory, ['rev-list', '--objects', 'main']).split('\n').some(line => line.startsWith(rawOID)), 'Raw PR media must not be reachable from main');
+ assert.equal(git(directory, ['show', original + ':library/templates/catalog/motion-demo/template.json']).includes('Demo'), true);
+});
+
+test('fork write access and workflow trust are checked before any media transfer', async t => {
+ const oldActions = process.env.GITHUB_ACTIONS;
+ process.env.GITHUB_ACTIONS = 'false';
+ t.after(() => { if (oldActions === undefined) delete process.env.GITHUB_ACTIONS; else process.env.GITHUB_ACTIONS = oldActions; });
+ const old = process.env.OPENMOTION_MEDIA_MAINTAINER_TOKEN;
+ process.env.OPENMOTION_MEDIA_MAINTAINER_TOKEN = 'test-token';
+ t.after(() => { if (old === undefined) delete process.env.OPENMOTION_MEDIA_MAINTAINER_TOKEN; else process.env.OPENMOTION_MEDIA_MAINTAINER_TOKEN = old; });
+ let reads = 0;
+ t.mock.method(globalThis, 'fetch', async () => { reads++; return Response.json({ state: 'open', draft: false, base: { ref: 'main' }, head: { repo: { full_name: 'contributor/fork' } }, maintainer_can_modify: false }); });
+ await assert.rejects(preparePullRequest(42, true), /Allow edits by maintainers/);
+ assert.equal(reads, 1);
+});
diff --git a/tests/repository-storage.test.ts b/tests/repository-storage.test.ts
new file mode 100644
index 00000000..344bbd97
--- /dev/null
+++ b/tests/repository-storage.test.ts
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { checkRepositoryStorage } from '../scripts/check-repository-storage.ts';
+import { requireDownloadedMedia } from '../scripts/distribution.ts';
+
+function git(root: string, args: string[]) {
+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr); return result.stdout.trim();
+}
+function fixture(t: { after: (fn: () => void) => void }) {
+ const root = mkdtempSync(path.join(tmpdir(), 'openmotion-storage-'));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ git(root, ['-c', 'init.templateDir=', 'init', '-b', 'main']);
+ git(root, ['config', 'user.name', 'Storage test']); git(root, ['config', 'user.email', '[email protected]']);
+ git(root, ['config', 'core.hooksPath', '/dev/null']);
+ const write = (name: string, data: string | Buffer) => {
+ mkdirSync(path.dirname(path.join(root, name)), { recursive: true }); writeFileSync(path.join(root, name), data);
+ };
+ const stage = () => git(root, ['-c', 'filter.lfs.process=', '-c', 'filter.lfs.clean=cat', '-c', 'filter.lfs.required=false', 'add', '.']);
+ write('README.md', '# Source'); stage(); git(root, ['commit', '-qm', 'Initial source']);
+ return { root, write, stage, base: git(root, ['rev-parse', 'HEAD']) };
+}
+const pointer = (bytes = 2000000) => `version https://git-lfs.github.com/spec/v1\noid sha256:${'a'.repeat(64)}\nsize ${bytes}\n`;
+
+test('storage checks staged pointer identities and attributes independently of downloaded working files', t => {
+ const f = fixture(t);
+ f.write('.gitattributes', 'docs/readme/**/*.mp4 filter=lfs diff=lfs merge=lfs -text\n');
+ f.write('docs/readme/demo.mp4', pointer()); f.stage();
+ f.write('docs/readme/demo.mp4', Buffer.alloc(2 * 1024 * 1024));
+ const result = checkRepositoryStorage(f.root, f.base);
+ assert.deepEqual(result.errors, []); assert.equal(result.lfsFiles, 1); assert.equal(result.lfsBytes, 2000000);
+ f.write('.gitattributes', ''); f.stage();
+ assert.match(checkRepositoryStorage(f.root).errors.join('\n'), /exceeds 1 MiB/);
+ f.write('docs/readme/demo.mp4', pointer()); f.stage();
+ assert.match(checkRepositoryStorage(f.root).errors.join('\n'), /staged LFS attributes/);
+ f.write('.gitattributes', 'docs/readme/**/*.mp4 filter=lfs diff=lfs merge=lfs -text\n');
+ f.write('docs/readme/demo.mp4', pointer(50 * 1024 * 1024 + 1)); f.stage();
+ assert.match(checkRepositoryStorage(f.root).errors.join('\n'), /exceeds 50 MiB/);
+});
+
+test('new raw large blobs fail both before commit and after deletion from new history', t => {
+ const f = fixture(t);
+ f.write('demo.mp4', Buffer.alloc(1024 * 1024 + 1)); f.stage();
+ assert.match(checkRepositoryStorage(f.root, f.base).errors.join('\n'), /staged ordinary Git file exceeds/);
+ git(f.root, ['commit', '-qm', 'Add raw media']); rmSync(path.join(f.root, 'demo.mp4'));
+ f.stage(); git(f.root, ['commit', '-qm', 'Delete raw media']);
+ assert.match(checkRepositoryStorage(f.root, f.base).errors.join('\n'), /even if later deleted/);
+ assert.deepEqual(checkRepositoryStorage(f.root, f.base, { finalTreeOnly: true }).errors, [], 'Squash accepts a sanitized final tree');
+ f.write('still-large.mp4', Buffer.alloc(1024 * 1024 + 1)); f.stage(); git(f.root, ['commit', '-qm', 'Unclean final tree']);
+ assert.match(checkRepositoryStorage(f.root, f.base, { finalTreeOnly: true }).errors.join('\n'), /ordinary Git file exceeds/, 'Committed large files in the final tree must still fail');
+});
+
+test('bundle construction refuses a pointer instead of silently shipping it as a video', async t => {
+ const f = fixture(t); f.write('demo.mp4', pointer());
+ await assert.rejects(requireDownloadedMedia(['demo.mp4'], f.root), /git lfs pull --include="demo.mp4" --exclude=""/);
+ f.write('demo.mp4', Buffer.from([0, 1, 2, 255]));
+ await requireDownloadedMedia(['demo.mp4'], f.root);
+});
+
+test('repository LFS defaults keep a normal clone small and a scoped pull restores exact media', {
+ skip: spawnSync('git', ['lfs', 'version']).status !== 0,
+}, t => {
+ const f = fixture(t);
+ git(f.root, ['config', 'core.hooksPath', '.git/hooks']);
+ git(f.root, ['lfs', 'install', '--local']);
+ f.write('.lfsconfig', readFileSync(new URL('../.lfsconfig', import.meta.url)));
+ f.write('.gitattributes', 'docs/readme/**/*.mp4 filter=lfs diff=lfs merge=lfs -text\n');
+ const bytes = Buffer.alloc(2 * 1024 * 1024, 42);
+ f.write('docs/readme/demo.mp4', bytes); git(f.root, ['add', '.']);
+ git(f.root, ['commit', '-qm', 'Optional LFS media']);
+ 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(f.root, ['init', '--bare', remote]); git(f.root, ['remote', 'add', 'origin', remote]);
+ git(f.root, ['push', 'origin', 'main']); git(remote, ['symbolic-ref', 'HEAD', 'refs/heads/main']);
+ git(f.root, ['-c', 'filter.lfs.process=git-lfs filter-process', '-c', 'filter.lfs.required=true', 'clone', remote, clone]);
+ assert.match(readFileSync(path.join(clone, 'docs/readme/demo.mp4'), 'utf8'), /^version https:\/\/git-lfs/);
+ git(clone, ['lfs', 'install', '--local']);
+ git(clone, ['lfs', 'pull', '--include=docs/readme/**', '--exclude=']);
+ const downloaded = readFileSync(path.join(clone, 'docs/readme/demo.mp4'));
+ assert.equal(downloaded.length, bytes.length);
+ assert.equal(createHash('sha256').update(downloaded).digest('hex'), createHash('sha256').update(bytes).digest('hex'));
+});
diff --git a/tests/repository-template-runtime.test.ts b/tests/repository-template-runtime.test.ts
index 1a44bf55..2d01b374 100644
--- a/tests/repository-template-runtime.test.ts
+++ b/tests/repository-template-runtime.test.ts
@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
+import { mediaKey, mediaOrigin } from '../shared/repository-media.ts';
import { TemplateCatalog } from '../prism-templates.ts';
import { repositoryCatalogRoot, readRepositoryFile } from '../shared/repository-template-catalog.ts';
import { WorkspaceStore } from '../workspace.ts';
@@ -91,6 +92,24 @@ test('repository media works without CMS, refuses missing LFS bytes and verifies
await assert.rejects(f.catalog.sourceFile(f.id, relative), /does not match/);
});
+test('transferred PR media appears in Studio and detail without downloading and verifies bytes on source access', async t => {
+ const f = await fixture(t), bytes = Buffer.alloc(128, 42), sha256 = createHash('sha256').update(bytes).digest('hex');
+ const relative = 'assets/reference.mp4', url = mediaOrigin + '/' + mediaKey(sha256, relative);
+ Object.assign(f.record, { localMedia: { preview: relative }, remoteAssets: [{ url, bytes: bytes.length, sha256, source: { path: relative, bytes: bytes.length, sha256 } }] });
+ await f.save(f.id + '/template.json', f.record);
+ await f.save(f.id + '/source/manifest.json', { files: [{ path: 'motion.md' }, { path: 'preview.html' }, { path: relative, bytes: bytes.length, sha256 }] });
+ let calls = 0, corrupt = false;
+ const catalog = new TemplateCatalog(f.work, { source: 'repository', repositoryRoot: f.root, fetch: async requested => {
+ calls++; assert.equal(requested, url); return new Response(new Uint8Array(corrupt ? Buffer.alloc(bytes.length) : bytes));
+ } });
+ assert.equal((await catalog.page()).items[0].previewUrl, url);
+ assert.equal((await catalog.detail(f.id)).previewUrl, url);
+ assert.equal(calls, 0, 'Search and MCP detail must not fetch remote media');
+ assert.deepEqual(await catalog.sourceFile(f.id, relative), bytes);
+ corrupt = true;
+ await assert.rejects(catalog.sourceFile(f.id, relative), /SHA-256 mismatch/);
+});
+
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'); });