⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v0.3.1

motion-sticker-pack

kobingogo@kobingogo⭐ 66 stars· last commit 2mo ago· 0 open issues

Create an animated sticker pack from a supplied character image or a text-defined character by collecting a style and Emoji or short reaction descriptions, generating and approving a static sheet, then routing video generation, cleanup, splitting, and packaging. Also process existing static sheets or grid videos. Use for animated emoji or sticker-pack production, not for designing a separate character identity artifact or general video editing.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 66 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Motion Sticker Pack|动态表情包制作器

ci English · MIT · Release notes

把一张角色图或一段角色描述,变成经过静图确认、可审计、可打包的循环动态表情包。

motion-sticker-pack 是面向 Codex 的 Agent Skill。默认交付透明 PNG、lossless Animated WebP、兼容 GIF、处理报告和 ZIP;普通用户不需要手动运行脚本。

30 秒开始

在 Codex 中安装 Skill 后上传角色图,发送:

$motion-sticker-pack
用附件角色做 3×3 动态表情包。
风格选 soft-plush,表情是:开心、喜欢、委屈、惊讶、亲亲、谢谢、加油、困困、点赞。
先给我确认静图,再生成动画。每格独立、小幅、可循环。

没有角色图也可以直接描述角色;流程会直接生成完整静图板,不先制造一张中间角色图。

交互顺序:

  1. 提供图片或角色描述。
  2. 选择风格和表情。
  3. 检查静态网格。
  4. 明确回复“确认,继续”。
  5. 选择可用的视频路线。
  6. 下载 WebP/GIF/PNG 与 ZIP。

三档动态路线

档位路线结果与成本
AI 视频native-video / Grok / xAI / Kling / Seedance / Wan / FAL真实面部和肢体动作;可能产生调用费用
真实关键姿势keypose-local生图生成 anticipation/peak/recovery,本地编排;有真实姿势变化
轻动效light-motion-local零生成成本,只做小幅仿射循环;不承诺新肢体或表情动作

transform-local 和 keyframe-local 仍作为旧配置兼容别名,但新 route 统一输出 light-motion-local。

没有视频或本地图像能力时,prompt-only 只交付提示词和审计文件,不会伪造媒体。

16 个风格效果图

下面是同一只狐狸、同一套服装与配饰的 16 张静态风格探索图,适合直接横向比较视觉方向。它们是风格效果参考,不等同于动态路线证据;真实九格处理、GIF、Animated WebP、layout、route、processing 和 provenance 证据见 gallery/。

最近生成的动态表情包 GIF

下面是最近完成的“暖尾狐狸”九宫格案例:9 个独立表情均为原始 240×240、8 fps、3 秒可循环 GIF,已通过透明度、边界和编码检查。完整来源与 SHA-256 记录见 manifest.json;13 个风格的长期验证证据仍见 gallery/。

社死阴阳怪气吃瓜

查看或验证选择器:

python3 scripts/style_selector.py --format markdown
python3 scripts/style_selector.py --format core
python3 scripts/style_selector.py --style clay-cute
python3 scripts/style_selector.py --style soft-plush
python3 scripts/style_selector.py --verify-only

其中 cute 是兼容保留的规范 ID,soft-plush 是推荐的可读别名;两者解析到同一份真实验证证据。

v0.3.1 的核心目录目标为 16 个方向;--format core 会同时显示已验证和待受控验证的状态,普通 --format markdown 只显示已通过证据门槛的风格。待受控验证的核心风格可以在用户明确指定时编译,但会在合同中标记为未验证。核心目录之外的文化媒介、印刷、复古 UI 或混合风格,请使用 custom 描述,不会被硬编码成未经验证的 preset。

$motion-sticker-pack
风格 custom:水墨留白、干湿笔触,保留角色身份;不要添加整格背景。

完整证据见 gallery/,完整 gallery 媒体按版本发布到 GitHub Releases。旧版完整案例包已迁移至 GitHub Release asset。

静图与透明度

首选 GPT-image-2 等能返回真实 Alpha 的图像工具。静图请求按输入模式选择:参考图路线先生成不透明纯绿 #00FF00 源图,文字定义路线先尝试透明 RGBA PNG;两者都必须经过本地像素检查,失败时才进行一次有界重试。

  • 棋盘格是可见背景,不是透明度。
  • 不假设模型真的返回了请求的 3×3;必须重新检测实际布局。
  • 低于 0.75 的布局置信度需要人工确认。
  • 静图确认后,图片或 layout 的任一字节变化都会使审批哈希失效。

自动幕布

Grok 路线保持严格 #00FF00 合同。

非 Grok 路线会从绿、蓝、品红、青四个候选中计算前景冲突,选择距离主体颜色最远的幕布。候选分数、每个 Provider 的颜色和确定性铺底输入都记录在 video-task.json 与 artifact-manifest.json。用户仍可显式传入 --key-color。

统一输出

所有新本地路线默认:

  • 240×240;
  • 8fps;
  • lossless Animated WebP 为首选;
  • GIF 为兼容格式;
  • PNG 为干净首帧;
  • 编号按实际检测布局的 row-major 顺序;
  • 同一个 delivered/ 目录与一个 sticker-pack.zip。
works/<character-slug>/delivered/
├── 01.webp … NN.webp
├── 01.gif  … NN.gif
├── 01.png  … NN.png
├── preview.png
├── layout.json
├── processing.json
├── job-state.json
├── prompts.json
├── route.json
├── attempt-ledger.json
├── artifact-manifest.json
└── sticker-pack.zip

完整规范见 output contract。

安全与审计

  • 静图审批由 SHA-256 绑定。
  • 付费 attempt 首次只提交一次;用户主动要求再次生成时,必须先创建绑定当前输入和 route 的重试批准,不会静默重放。
  • xAI request id 支持恢复同一个远端任务。
  • 输出目录采用可恢复事务,拒绝输入/输出重叠。
  • artifact-manifest.json 记录静图、提示词、pose、route、视频和交付的依赖谱系。
  • 每个原生视频帧都经过幕布、Alpha、跨格实例与编码后 QC。

更多说明:Routing and audit。

安装

在 Codex 对话中安装(推荐)

在 Codex 中发送以下消息:

$skill-installer
请从 GitHub 仓库 `kobingogo/motion-sticker-pack` 安装 `motion-sticker-pack` Skill。
Skill 位于仓库根目录(路径 `.`),安装名设为 `motion-sticker-pack`。

安装器完成后,在下一轮 Codex 消息中发送 $motion-sticker-pack 验证;例如:

$motion-sticker-pack
确认已加载该 Skill,并告诉我可用的入口和当前版本。

如果发送 $skill-installer 后提示未找到该 Skill,可发送下面的兜底请求(需要当前 Codex 会话具备终端权限):

请不要调用 `$skill-installer`。请直接从
https://github.com/kobingogo/motion-sticker-pack.git 获取仓库,并将包含 `SKILL.md` 的仓库根目录安装到
`$CODEX_HOME/skills/motion-sticker-pack`;如果未设置 `$CODEX_HOME`,使用 `~/.codex/skills/motion-sticker-pack`。
安装完成后报告实际路径,并在下一轮消息中加载该 Skill。

本地脚本环境(可选)

如果只在 Codex 对话中调用,使用上面的安装流程即可。需要本地运行脚本或参与开发时,再执行:

git clone ht

// HOW IT'S BUILT

// FILES

220 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md29 KB4174ff78bb86upstream ↗
    ---
    name: motion-sticker-pack
    description: Create an animated sticker pack from a supplied character image or a text-defined character by collecting a style and Emoji or short reaction descriptions, generating and approving a static sheet, then routing video generation, cleanup, splitting, and packaging. Also process existing static sheets or grid videos. Use for animated emoji or sticker-pack production, not for designing a separate character identity artifact or general video editing.
    ---
    
    # Motion Sticker Pack|动态表情包制作器
    
    Create a usable animated sticker pack, not merely a video preview. Preserve the supplied character identity and produce independently looping stickers, transparent first frames, a machine-readable report, and a ZIP.
    
    ## IP identity and prompt principles
    
    - Before writing a generation prompt, inspect the supplied image and derive the IP's visible identity features: face, hair or fur, silhouette and proportions, colors, clothing, accessories, existing props, pose language, scene cues, and overall mood.
    - Build the prompt from those observed features plus the user's selected style and reactions. Preserve the supplied IP's appearance and source-specific details by default; change them only when the user asks for a change.
    - Unless the user requests another presentation, use the default static-sheet treatment: a 3×3 illustrated reaction-card grid with no white border or heavy outline, subtle local background accents in each cell, and a consistent overall color tone. This changes the visual treatment, not the transparent-alpha and cell-isolation requirements.
    - Interpret each Emoji or text reaction semantically. Offer a compact choice for short reaction text: default to avoiding text, while allowing the user to opt in. This is a preference, not a rejection gate—if the model adds text despite the default, keep the sheet eligible for review and let the user decide whether to keep it. When it helps the expression read clearly, add a small number of matching decorative accents—such as hearts, music notes, sparkles, tears, blush marks, sweat drops, motion lines, or stars—using the selected style's visual language. Use them selectively rather than forcing the same accents into every cell, and do not turn them into unrelated large props.
    - Do not add unsolicited moral, modesty, sexualization, age, wardrobe, pose-cleanup, or scene-removal instructions. In particular, do not insert wording such as “改成得体、日常、非性感化的简化服装” or “不要保留汽车、夜景、原照片背景或暧昧姿势” unless the user explicitly requests that transformation.
    - Keep the source reference label neutral (for example, `所附图像` or `附件中的角色参考图`). Do not encode an unrequested redesign into `reference_label`.
    - A transparent sticker sheet may require removing the source background as a technical canvas operation, but do not otherwise remove existing clothing, props, setting cues, or pose characteristics unless requested. If the user wants the original scene retained, preserve it within each cell where technically feasible.
    
    ## Pre-generation fidelity check
    
    Before writing a prompt or an intake/confirmation message, explicitly check that no unrequested transformation has been introduced. Remove any wording or instruction that asks to make the character more “得体、日常、非露骨、非性感化”, to simplify or replace clothing, clean up the pose, remove scene cues, or make the result “适合公开分享”. These are not defaults. Preserve the supplied character's observed appearance, clothing, pose language, props, setting cues, and mood unless the user requests a change or a higher-priority platform safety rule requires one. If a safety-driven change is required, state only the necessary constraint and do not broaden it into an aesthetic redesign.
    
    ## Ambiguous-request confirmation
    
    - When the user supplies a character image but does not specify a style, reactions, or both, do not generate immediately. First present a concise confirmation card with the proposed defaults: `3D 卡通风`, the illustrated reaction-card treatment, a practical set of nine chat reactions (`开心、喜欢、委屈、惊讶、亲亲、谢谢、加油、困困、点赞`), and the default `3×3` layout.
    - When no character image is supplied, accept a named or text-defined character and use the same intake defaults when style or reactions are missing. After confirmation, generate the complete static sheet directly. Do not insert a separate single-character concept image, identity card, or character-approval stage.
    - State that the prompt will be derived from the image's observed IP features and the selected style, with the character's appearance and source details preserved by default. Do not add redesign or moralizing constraints.
    - Accept either an explicit confirmation (`确认` / `开始生成`) or a revision such as `风格改为写实还原` or `表情改为 🎸😍🥹😘🥰`. After a revision, show the updated summary and wait for confirmation again. Once confirmed, generate the static sheet directly, then follow the normal layout inspection and static-review gate before any video generation.
    - If the user already supplied both a clear style and reactions, skip this intake confirmation and proceed to static generation. The post-generation static-review approval before video remains mandatory.
    
    ## Non-negotiable invariants
    
    - Treat the image model's requested grid as a preference, not observed fact. After image generation, inspect the returned sheet and write `detected_layout`; every later stage must use that result.
    - Compile every static request with `image_generation_request.arguments.background` and `image_generation_request.arguments.output_format`. Select the background policy by input mode: reference-image generation uses an opaque, uniform `#00FF00` source first because the current Codex image_gen runtime does not reliably return native Alpha with a reference image; text-defined generation uses transparent-first because it can emit native Alpha. Pass the resolved fields when the callable `image_gen` schema exposes them; when it does not, omit only unsupported fields and record them in `static-generation.json`. In both modes, inspect returned pixels, reject checkerboards and non-uniform backgrounds, and locally convert only an accepted native Alpha or uniform key to the final real Alpha sheet. Do not override the reference-image policy by merely adding a transparent prompt.
    - Express layout unambiguously as `columns × rows`. Derive `count = columns * rows`; never mix 3×3 with 12 items or 4×3 with 9 items.
    - If automatic layout confidence is below `0.75`, inspect the overlay/report and confirm or override the grid before animation or cropping.
    - When this Skill generated the static illustrated-card sheet, never generate video until the user explicitly approves that exact sheet. Regeneration invalidates the old approval and all downstream artifacts.
    - Persist the review revision with `scripts/manage_job_state.py`. Hash verification is mandatory before bundled Provider execution; a conversational “approved” flag alone is insufficient.
    - Keep the camera fixed. Each cell moves only inside its own bounds. Do not invent characters, new captions, large props, scenery, or cross-cell effects. Preserve any text or symbols already present in the approved source, including when they were model-generated. Small semantic reaction accents are allowed when they support the requested emotion and remain inside the cell. Preserve source elements when they already exist in the approved source unless the user asks to remove them or transparent-sheet/cell-isolation requirements make that technically necessary.
    - Do not trust a video model or adapter's claimed transparency. Decode the returned video with the local Alpha probe. Prefer real alpha when detected; otherwise use a uniform key that contrasts with the character (chroma such as green or magenta, not a near-black or near-white plate) and deterministic local matting.
    - For Grok image-to-video, the output contract is stricter: use `#00FF00`, never a checkerboard or simulated transparency. The input sent to Grok must already have real alpha (or a verified uniform green plate), and `scripts/grok_build_video_adapter.py` must pass every native returned frame through background QC. Each execution makes exactly one Grok call (`max_retries: 0`) and must never fall through to local animation. A user-requested new execution is allowed only after a separate, explicit retry approval bound to the same approved inputs and route; it is never an implicit replay.
    - For Grok image-to-video, compile a compact execution prompt from the approved per-cell `tile-plan.json`: keep the grid dimensions, identity lock, fixed-camera rule, one action per cell, green-screen contract, and loop timing, while removing repeated prose. Keep the final adapter instruction below 3,800 UTF-8 bytes so Grok's 4,096-byte CLI limit is not reached; reject early with a local validation error if a custom tile plan still exceeds the budget.
    - Never put credentials in prompts, config files, reports, command arguments, or logs. Configuration refers to environment-variable names only.
    - Keep every generated artifact for one character under `works/<character-slug>/` in this skill directory. Do not write new job files to the skill root or a shared `work/` folder. Resolve the directory with `scripts/character_workspace.py --name <角色名>` before static generation.
    - Treat `assets/sticker-production.default.json` as the single editable production-default file. Validate it with `scripts/sticker_production_config.py`; copy it into each work directory as `sticker-production.json` so generation and post-processing use the same immutable job snapshot. Do not duplicate duration, size, fps, color-budget, key-color, or GIF-budget defaults in prompts or scripts.
    - Treat each static image-generation attempt as a billable, non-idempotent operation. Before calling the image tool, claim it with `scripts/static_generation_guard.py claim`; immediately before the call, mark it `invoked`. After the call, resolve the result before considering any retry. The current image tool may return a top-level `image_url` and `output_hint`, a data URL/image bytes, or an image block under `content`; absence of `content` alone is never a failure. Copy or materialize the first usable result to `static-sheet-source.png`, then mark the attempt `accept`. Only an explicit provider failure with no artifact, or a local normalization/QC rejection recorded with `reject`, may unlock the bounded fallback attempt. Keep `static-generation-attempts.json` beside `static-generation.json`.
    
    ## Workflow
    
    1. Inspect the input and choose an entry mode:
       - personal IP handoff → read [references/personal-ip-handoff.md](references/personal-ip-handoff.md), run `scripts/import_personal_handoff.py <handoff.json> --work-dir <work_dir>`, and use the imported `character.json` as the job-local identity/style/reaction manifest; never copy the original photo or edit the personal card;
       - character reference → read [references/intake-and-approval.md](references/intake-and-approval.md); if the request is vague, present the default proposal and wait for confirmation before generating the static sticker sheet;
       - named or text-defined character without an image → compile that definition and generate the full static sheet directly; do not generate a separate character image first;
       - static sheet → detect the actual grid;
       - grid video → obtain the source sheet/layout or extract a representative frame with `ffmpeg -y -i input.mp4 -frames:v 1 representative-frame.png`, then detect the grid;
       - separate static stickers → do not invent a grid; run `scripts/process_independent_stickers.py <input-dir> <output-dir> --manifest <work_dir>/artifact-manifest.json`;
       - user-supplied static sheet → create state with `--source-type user-supplied` and skip the explicit approve step; it is already the selected source.
    2. Choose a short character name and resolve the work directory with `scripts/character_workspace.py --name <角色名>`. For a personal handoff, import first and keep the received `handoff.json` plus `character.json` in that work directory; use the verified absolute `anchor`, `resolved_style`, and `resolved_reactions` from `character.json`, and do not route through the generic photo intake. For other entry modes, compile the confirmed style and reactions into `<work_dir>/static-prompt.json`: use `--reference-image <source-image>` when supplied, or `--character-description <definition>` when no image exists. The no-image route goes straight to one complete sheet. Inspect the callable `image_gen` schema and run `scripts/prepare_image_gen_call.py`, repeating `--supported-argument` for its exposed fields. The compiled contract automatically selects opaque-green-first for reference images and transparent-first for text-defined characters; `static-generation.json` records the source mode, resolved policy, passed/omitted fields, bounded retry, and single-call execution protocol. Create the attempt ledger and claim attempt 1 with `scripts/static_generation_guard.py`; mark it `invoked` immediately before the one image call. Resolve the returned object in this order: top-level `image_url`/`output_hint`, top-level data URL or bytes, then `content` image block. Do not call again merely because the host did not render the result. Save the first usable raw result as `<work_dir>/static-sheet-source.png` and mark it accepted. A reference-image request must use a backend that accepts that exact image; a text-defined request may use text-only generation.
    3. Run `scripts/normalize_static_sheet.py <work_dir>/static-sheet-source.png <work_dir>/static-sheet.png --report <work_dir>/static-alpha.json`. Native alpha is preserved for text-defined generation when present. Reference-image generation is expected to be opaque: accept only a uniform, high-contrast chroma key (normally `#00FF00`) suitable for deterministic local matting. Simulated checkerboards/two-tone previews, light plates, gradients, scenery, and ambiguous backgrounds fail closed. If local normalization rejects the accepted raw result, mark attempt 1 `reject` with the QC reason, then claim and invoke the recorded opaque fallback exactly once; never replay an unresolved attempt. Save the retry result as the new raw source, mark it accepted, and re-run normalization; if it still fails, stop and request regeneration rather than sending the bad sheet to video. Inspect only the normalized `<work_dir>/static-sheet.png` with `scripts/inspect_sticker_sheet.py`, then create the hash-bound `static-review` state.
    4. For a generated or regenerated sheet, show the normalized sheet, detected layout, `text_policy`, and `static-alpha.json` warnings. If text appeared, report it as an observation only; do not reject or auto-regenerate for that reason. Offer `确认,继续生成视频` or `重新生成`. Stop and wait. Do not route or call video generation while the sheet is unapproved. For a user-supplied sheet, report the detected layout and continue without asking for a duplicate approval.
    5. After explicit approval of a generated sheet, record it with `scripts/manage_job_state.py approve`; for a user-supplied sheet, use the already `static-approved` state created with `--source-type user-supplied`. In both cases use the exact source image. For animation prompt rules, read [references/prompt-contract.md](references/prompt-contract.md) and write a `tile-plan.json` with exactly one vision-informed entry per detected cell. Compile it with `scripts/prompt_compiler.py`. Do not use generic motions unless explicitly accepting the lower-quality fallback.
    6. For backend discovery and selection, read [references/runtime-routing.md](references/runtime-routing.md). Inspect callable tools/skills in the current runtime first and record their exact names, reference-image support, video support, and cost status in `<work_dir>/runtime-tools.json`. Then run `scripts/prepare_workflow.py --character <角色名> --skill-root /Users/bingo/Documents/ChatGPT/motion-sticker-pack` when working from this repository, so `video-providers.json`, `video-task.json`, and `artifact-manifest.json` land in the same `works/<slug>/` directory; use `--provider <id>` and repeated `--fallback-provider <id>` for task-level selection instead of editing the shared template. Use those same files for probe, route, and execute. Routing creates `attempt-ledger.json`; review the route `preflight` before any external execution.
    7. Execute the selected mode:
       - `native-video` (`native-tool` in provider configuration): run `manage_job_state.py verify` first, then use a callable local Agent video tool with the approved image and `prompts.json`; after the host call returns, register that exact video through `scripts/execute_video_route.py --native-video <host-video>`, which applies the common QC, result receipt, ledger, and Manifest path;
       - `external-video`: execute one selected AI SDK or command route with `scripts/execute_video_route.py`; never execute all attempts automatically and never delete/edit `attempt-ledger.json` to replay an attempt. A failed/rejected/uncertain attempt needs either explicit selection of the next numbered route or a user-requested, hash-bound retry approval passed with `--retry-approval`; the latter is a new billable execution. Only a submitted/uncertain xAI attempt with a persisted request ID may use `--resume`, which continues that same remote request. When Grok is required, set `provider: grok-build-local` and `allow_fallback: false`; a failed green-screen QC is a failed Grok job, not permission to use local animation;
       - `keypose-local`: when image generation is callable but video is not, compile `scripts/compile_keypose_plan.py` with the approved image/layout/state, validate generated 2×2 pose sheets with `scripts/prepare_keyposes.py --plan <keypose-plan>`, then assemble the exact four contract poses per sticker with `scripts/render_keypose_pack.py --image <approved-sheet> --state <job-state> --plan <keypose-plan> --preparation-report <keypose-preparation>`. Read [references/keypose-workflow.md](references/keypose-workflow.md) for the auditable flow;
       - `light-motion-local`: run `manage_job_state.py verify`, then use `scripts/light_motion_fallback.py --state <job-state>` only as the zero-generation-cost affine fallback. Describe it as light motion, never as synthesized character articulation. Accept `transform-local` only as a deprecated configuration alias;
       - `postprocess-only`: process a supplied video without generation. If no layout is supplied, extract a representative frame first with `ffmpeg -y -i input.mp4 -frames:v 1 representative-frame.png`, then inspect it.
       - `prompt-only`: when no video or local image-processing capability exists, run `scripts/assemble_prompt_only.py`, deliver its prompt artifacts, and stop without claiming a generated video.
    8. Split and matte a grid video with `scripts/process_emoji_grid.py --layout <layout.json> --settings <work_dir>/sticker-production.json`. Probe the actual returned duration, select the matching configured profile, and run native-frame matting, instance assignment, and safety QC before duration sampling. Whole-grid registration is disabled by default because per-frame integer correction can create micro-jitter; use `--registration auto` only when visual inspection confirms actual camera drift. Request duration comes from `generation.provider_duration_seconds`; the shipped map is `grok-build-local: 6` and `xai-direct: 3`, with both outputs at 240×240 and 8 fps. A direct API result matching 3 seconds is preserved as-is and is never duration-compressed. For Grok, preserve the complete 6-second result as the root version and also create `3s/` from the initial 24 sampled frames. Record endpoint pose difference for audit, but do not reject or retime the 3-second derivative when the first and last poses differ. Never replace or discard the full Grok result. First run `--trial` for the configured cell (default `01`) and require both Grok variants to pass encoded-frame and 1 MiB GIF-budget checks. If they pass, reuse the same source grid video for the complete pack—never make a second Grok call. Later full-pack GIF overages are warnings rather than pack blockers; encoded-frame failures remain hard failures. Grok grid inputs are repacked from each cell's real Alpha bounding box with at least a 10% two-sided green corridor. Animated WebP stays lossless; GIF gets an adaptive binary-alpha threshold; both are decoded again for hard frame QC before packaging. A seam crossing is not itself a failure. Treat a balanced, inseparable cross-cell component as a bad native-frame run; only a short bounded run (up to 0.2 seconds) may be repaired from temporally adjacent safe frames, with frame numbers recorded in `processing.json`. Longer or identity-ambiguous merges remain withheld. Only an inseparable merge is withheld, while successful cells and the failure report remain deliverable.
    9. Read [references/output-contract.md](references/output-contract.md) before delivery. Run `scripts/assemble_delivery.py --cleanup-media-dir` so media and `job-state.json`, `prompts.json`, and `route.json` are collected into one canonical delivery directory and ZIP, then the intermediate media directory is removed only after packaging succeeds. Composite each GIF onto a light background before showing it. Report any low-confidence layout, alpha damage, interior holes, loop discontinuity, residual hold jitter, provider fallback, or failed cell instead of hiding it.
    
    When processing generated video, pass `--manifest <work_dir>/artifact-manifest.json` to `process_emoji_grid.py` so accepted processed outputs extend the job's SHA-256 lineage.
    
    Grid layout safety is a hard default: target each cell's combined foreground bounding box at approximately 70%–75% of the cell, never above 75% in the static prompt contract or video repack, and keep at least a 10% two-sided corridor. The static sheet prompt records this contract; Grok/keypose/local input preparation enforces the 75% maximum even when a source cell is fuller.
    
    For public style evidence, keep `gallery/styles/<id>/provenance.json` in sync
    with the media by running `scripts/build_gallery_provenance.py --verify-only`.
    Legacy gallery cases are allowed only with an explicit `legacy-evidence-partial`
    status and a declared approval/manifest gap.
    
    ## Routing behavior
    
    Use this fixed order unless the user explicitly selects a provider:
    
    1. callable native/local image-to-video capability;
    2. configured external providers that satisfy the task, in configured priority order;
    3. key-pose generation plus local assembly;
    4. transform-only local animation when key-pose generation is unavailable;
    5. prompt-and-plan-only output when neither video nor local image processing is possible. Deliver the prompts and route artifacts and stop without claiming a generated video.
    
    Before the first external-provider call, state which provider will receive the image and that the request may incur charges, unless the user already explicitly selected that provider and authorized external generation. Run only attempt 1; a later route attempt requires a failed prior result and another explicit execution step. If the user actively asks to retry after a failed, rejected, or uncertain attempt, pause for a retry approval card naming the provider, explaining that a new request may incur another charge, and asking for an explicit confirmation. After confirmation, create a hash-bound retry approval with `scripts/manage_job_state.py approve-video-retry`, then pass it as `--retry-approval` to the executor. A plain request to continue, silence, or an earlier static approval is not retry authorization.
    
    Retry only another configured route or the affected sticker. Do not repeatedly charge the same external provider without a clear transient failure and a bounded attempt count.
    
    For a Grok-mandated task, the route must be explicit (`provider: grok-build-local`, `allow_fallback: false`, `max_retries: 0`). One approved sheet produces one Grok video; no local route and no automatic paid regeneration is eligible as a substitute. Read generation duration from `generation.provider_duration_seconds` for the executing provider and resolution from the job's `sticker-production.json` snapshot (shipped defaults: Grok 6 seconds, xAI 3 seconds, 720p). Preserve the complete returned Grok duration, add the configured 3-second derivative, and apply only the configured uniform 8 fps sampling after native-frame QC. A direct 3-second API result remains a single full-duration output.
    
    ## Included commands
    
    ```bash
    python3 scripts/character_workspace.py --name '小黑猫'
    python3 scripts/compile_static_prompt.py --style 3d --expressions '🎸😍🥹😘🥰' --layout 3x3 --reference-image source.png --output works/小黑猫/static-prompt.json
    python3 scripts/compile_static_prompt.py --style 3d --expressions '开心、喜欢、委屈、惊讶、亲亲、谢谢、加油、困困、点赞' --layout 3x3 --character-description '金发、深色西装、红领带的公众人物漫画形象' --output works/角色/static-prompt.json
    python3 scripts/prepare_image_gen_call.py --static-prompt works/小黑猫/static-prompt.json --supported-argument prompt --supported-argument referenced_image_paths --output works/小黑猫/static-generation.json
    python3 scripts/normalize_static_sheet.py works/小黑猫/static-sheet-source.png works/小黑猫/static-sheet.png --report works/小黑猫/static-alpha.json
    python3 scripts/inspect_sticker_sheet.py works/小黑猫/static-sheet.png --output works/小黑猫/layout.json --overlay works/小黑猫/layout-overlay.png
    python3 scripts/manage_job_state.py create --image works/小黑猫/static-sheet.png --layout works/小黑猫/layout.json --static-prompt works/小黑猫/static-prompt.json --output works/小黑猫/job-state.json
    python3 scripts/manage_job_state.py approve --state works/小黑猫/job-state.json --image works/小黑猫/static-sheet.png --layout works/小黑猫/layout.json --confirmed-by-user
    python3 scripts/prompt_compiler.py --layout works/小黑猫/layout.json --tile-plan works/小黑猫/tile-plan.json --static-prompt works/小黑猫/static-prompt.json --output works/小黑猫/prompts.json
    python3 scripts/prepare_workflow.py --character '小黑猫' --image "$PWD/works/小黑猫/static-sheet.png" --layout "$PWD/works/小黑猫/layout.json" --prompts "$PWD/works/小黑猫/prompts.json" --state "$PWD/works/小黑猫/job-state.json" --tile-plan "$PWD/works/小黑猫/tile-plan.json"
    python3 scripts/probe_video_capabilities.py --config works/小黑猫/video-providers.json --tool-manifest works/小黑猫/runtime-tools.json --output works/小黑猫/capabilities.json
    python3 scripts/route_video_provider.py --config works/小黑猫/video-providers.json --capabilities works/小黑猫/capabilities.json --task works/小黑猫/video-task.json --output works/小黑猫/route.json
    python3 scripts/execute_video_route.py --config works/小黑猫/video-providers.json --task works/小黑猫/video-task.json --route works/小黑猫/route.json --attempt 1 --output works/小黑猫/video-result.json
    python3 scripts/process_emoji_grid.py animation.mp4 works/小黑猫/trial --layout works/小黑猫/layout.json --settings works/小黑猫/sticker-production.json --trial
    python3 scripts/process_emoji_grid.py animation.mp4 works/小黑猫/output --layout works/小黑猫/layout.json --settings works/小黑猫/sticker-production.json --trial-report works/小黑猫/trial/processing.json
    python3 scripts/render_keypose_pack.py keyposes works/小黑猫/output --image works/小黑猫/static-sheet.png --state works/小黑猫/job-state.json --layout works/小黑猫/layout.json --plan works/小黑猫/keypose-plan/keypose-plan.json --preparation-report works/小黑猫/keyposes/keypose-preparation.json --fps 8 --size 240 --manifest works/小黑猫/artifact-manifest.json
    python3 scripts/light_motion_fallback.py works/小黑猫/static-sheet.png works/小黑猫/output --state works/小黑猫/job-state.json --layout works/小黑猫/layout.json --fps 8 --size 240 --manifest works/小黑猫/artifact-manifest.json
    python3 scripts/process_independent_stickers.py stickers works/小黑猫/output --fps 8 --size 240 --manifest works/小黑猫/artifact-manifest.json
    python3 scripts/assemble_prompt_only.py --static-prompt works/小黑猫/static-prompt.json --tile-plan works/小黑猫/tile-plan.json --prompts works/小黑猫/prompts.json --route works/小黑猫/route.json --output works/小黑猫/prompt-only
    python3 scripts/assemble_delivery.py --media-dir works/小黑猫/output --audit-dir works/小黑猫 --output works/小黑猫/delivered --require-job-state --require-prompts --require-route --cleanup-media-dir
    ```
    
    Use paths relative to this skill directory when invoked from elsewhere. On Windows, run the same scripts with `py -3` (or `python`) if `python3` is not on PATH; `prepare_workflow.py` rewrites example `python3` adapter commands to the current interpreter.
    
  • benchmarks/README.md861 Be6c5a81c70a2upstream ↗
    # Reproducible benchmark
    
    `cases.json` is the public contract for the production benchmark proposed in
    the competitive analysis. It deliberately separates cases that can be
    reproduced with local fixtures from cases that still require a real image or
    provider run. A case must not be marked `verified` until its input, route,
    processing report, and artifact-manifest lineage are stored together.
    
    Run the deterministic coverage first:
    
    ```bash
    python3 scripts/check_benchmark.py
    python3 -m unittest discover -s tests -v
    ```
    
    Real-run cases must be recorded with the same flat fields as a normal delivery:
    `input_type`, `route_id`, `model`, `approval_sha256`, `native_frame_count`,
    `successful_cells`, `withheld_cells`, `output_size_bytes`, and the manifest
    artifact id. Credentials, signed URLs, and raw personal images never belong
    in this benchmark directory.
    
  • docs/advanced/README.md690 Bf3ef99c9f4c0upstream ↗
    # Advanced documentation
    
    - [Providers and ZDR](providers-and-zdr.md): Grok Build, xAI direct, AI SDK providers, credentials, and storage constraints.
    - [Routing and audit](routing-and-audit.md): capability discovery, paid-attempt idempotency, approval hashes, and artifact lineage.
    - [CLI reference](cli-reference.md): low-level commands for debugging or integrating the workflow.
    - [Repository maintenance](repository-maintenance.md): media policy, Release assets, release gating, and history-slimming evaluation.
    - [Adversarial audit](../adversarial-audit.md): threat-oriented implementation review.
    
    The normative machine-facing contracts remain under [references/](../../references/).
    
  • gallery/README.md1.7 KBffb8fb1472b4upstream ↗
    # Verified style gallery
    
    This directory contains compact evidence, not full sticker packs. Every listed
    style includes one original 240×240 static PNG and one original 240×240 animated GIF,
    the detected 3×3 layout, the selected generation route, the processing report,
    and a compact `provenance.json` record from the same nine-cell run. The complete
    240×240 GIF and lossless Animated WebP files are distributed as the versioned
    `motion-sticker-pack-gallery-v{version}.zip` Release asset; their hashes remain
    in `release-manifest.json` and each style's provenance record.
    
    The static PNG is a representative cell from each source case, not a
    controlled same-character comparison across styles. Use it to verify that the
    route produced a real nine-cell output; do not treat the gallery as a quality
    ranking of the presets.
    
    Some retained v0.2 evidence was encoded at 6fps; all new local routes use the
    canonical V0.3 profile of 240×240 at 8fps.
    
    Legacy cases are marked `legacy-evidence-partial` in `provenance.json` when
    their original approval state or artifact manifest was not preserved. The
    record lists that gap explicitly; a route/task hash is never presented as a
    user approval hash. New cases should emit `audited-complete` provenance from
    the same approved workflow.
    
    Run:
    
    ```bash
    python3 scripts/style_selector.py --format markdown
    python3 scripts/style_selector.py --style clay-cute
    python3 scripts/style_selector.py --verify-only
    ```
    
    Full legacy case packs and promotional renders are distributed as the
    `motion-sticker-pack-legacy-gallery-2026-09.zip` GitHub Release asset. The
    compact evidence and original GIF previews here stay in Git so preset claims
    remain reviewable in CI.
    
  • README.md13 KB53356ebce511upstream ↗
    # Motion Sticker Pack|动态表情包制作器
    
    [![ci](https://github.com/kobingogo/motion-sticker-pack/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/kobingogo/motion-sticker-pack/actions/workflows/ci.yml)
    [English](README.en.md) · [MIT](LICENSE) · [Release notes](RELEASE_NOTES.md)
    
    把一张角色图或一段角色描述,变成经过静图确认、可审计、可打包的循环动态表情包。
    
    `motion-sticker-pack` 是面向 Codex 的 Agent Skill。默认交付透明 PNG、lossless Animated WebP、兼容 GIF、处理报告和 ZIP;普通用户不需要手动运行脚本。
    
    ## 30 秒开始
    
    在 Codex 中安装 Skill 后上传角色图,发送:
    
    ```text
    $motion-sticker-pack
    用附件角色做 3×3 动态表情包。
    风格选 soft-plush,表情是:开心、喜欢、委屈、惊讶、亲亲、谢谢、加油、困困、点赞。
    先给我确认静图,再生成动画。每格独立、小幅、可循环。
    ```
    
    没有角色图也可以直接描述角色;流程会直接生成完整静图板,不先制造一张中间角色图。
    
    交互顺序:
    
    1. 提供图片或角色描述。
    2. 选择风格和表情。
    3. 检查静态网格。
    4. 明确回复“确认,继续”。
    5. 选择可用的视频路线。
    6. 下载 WebP/GIF/PNG 与 ZIP。
    
    ## 三档动态路线
    
    | 档位 | 路线 | 结果与成本 |
    |---|---|---|
    | AI 视频 | `native-video` / Grok / xAI / Kling / Seedance / Wan / FAL | 真实面部和肢体动作;可能产生调用费用 |
    | 真实关键姿势 | `keypose-local` | 生图生成 anticipation/peak/recovery,本地编排;有真实姿势变化 |
    | 轻动效 | `light-motion-local` | 零生成成本,只做小幅仿射循环;不承诺新肢体或表情动作 |
    
    `transform-local` 和 `keyframe-local` 仍作为旧配置兼容别名,但新 route 统一输出 `light-motion-local`。
    
    没有视频或本地图像能力时,`prompt-only` 只交付提示词和审计文件,不会伪造媒体。
    
    ## 16 个风格效果图
    
    下面是同一只狐狸、同一套服装与配饰的 16 张静态风格探索图,适合直接横向比较视觉方向。它们是风格效果参考,不等同于动态路线证据;真实九格处理、GIF、Animated WebP、layout、route、processing 和 provenance 证据见 [gallery/](gallery/README.md)。
    
    <table><tr><th width="140">ID</th><th>风格</th><th width="180">同一角色效果图</th></tr>
    <tr><td><code>3d</code></td><td>统一 3D</td><td><img src="docs/assets/style-exploration/fox/01-3d.png" width="128" alt="3D 风格狐狸效果图"></td></tr>
    <tr><td><code>realistic</code></td><td>电影感写实</td><td><img src="docs/assets/style-exploration/fox/02-realistic.png" width="128" alt="电影感写实狐狸效果图"></td></tr>
    <tr><td><code>hand-drawn</code></td><td>暖色手绘</td><td><img src="docs/assets/style-exploration/fox/03-hand-drawn.png" width="128" alt="暖色手绘狐狸效果图"></td></tr>
    <tr><td><code>chibi</code></td><td>虹彩 Q 版</td><td><img src="docs/assets/style-exploration/fox/04-chibi.png" width="128" alt="虹彩 Q 版狐狸效果图"></td></tr>
    <tr><td><code>manga</code></td><td>国潮漫画</td><td><img src="docs/assets/style-exploration/fox/05-manga.png" width="128" alt="国潮漫画狐狸效果图"></td></tr>
    <tr><td><code>pixel-art</code></td><td>精细像素</td><td><img src="docs/assets/style-exploration/fox/06-pixel-art.png" width="128" alt="精细像素狐狸效果图"></td></tr>
    <tr><td><code>cute</code>(别名 <code>soft-plush</code>)</td><td>软萌毛绒</td><td><img src="docs/assets/style-exploration/fox/07-cute.png" width="128" alt="软萌毛绒狐狸效果图"></td></tr>
    <tr><td><code>caricature-3d</code></td><td>夸张 3D 肖像</td><td><img src="docs/assets/style-exploration/fox/08-caricature-3d.png" width="128" alt="夸张 3D 肖像狐狸效果图"></td></tr>
    <tr><td><code>fashion-realistic</code></td><td>时尚写实</td><td><img src="docs/assets/style-exploration/fox/09-fashion-realistic.png" width="128" alt="时尚写实狐狸效果图"></td></tr>
    <tr><td><code>mascot-toy</code></td><td>品牌玩具吉祥物</td><td><img src="docs/assets/style-exploration/fox/10-mascot-toy.png" width="128" alt="品牌玩具狐狸效果图"></td></tr>
    <tr><td><code>clay-cute</code></td><td>软陶萌宠</td><td><img src="docs/assets/style-exploration/fox/11-clay-cute.png" width="128" alt="软陶萌宠狐狸效果图"></td></tr>
    <tr><td><code>fantasy-plush</code></td><td>奇幻毛绒</td><td><img src="docs/assets/style-exploration/fox/12-fantasy-plush.png" width="128" alt="奇幻毛绒狐狸效果图"></td></tr>
    <tr><td><code>kawaii-anime</code></td><td>日系萌系</td><td><img src="docs/assets/style-exploration/fox/13-kawaii-anime.png" width="128" alt="日系萌系狐狸效果图"></td></tr>
    <tr><td><code>retro-halftone</code></td><td>复古漫画网点风(探索)</td><td><img src="docs/assets/style-exploration/fox/14-retro-halftone.png" width="128" alt="复古漫画网点狐狸效果图"></td></tr>
    <tr><td><code>ink-wash-meme</code></td><td>水墨 Meme 风(探索)</td><td><img src="docs/assets/style-exploration/fox/15-ink-wash-meme.png" width="128" alt="水墨 Meme 狐狸效果图"></td></tr>
    <tr><td><code>emoji-hybrid</code></td><td>Emoji 混合风(探索)</td><td><img src="docs/assets/style-exploration/fox/16-emoji-hybrid.png" width="128" alt="Emoji 混合狐狸效果图"></td></tr></table>
    其中 `retro-halftone`、`ink-wash-meme` 和 `emoji-hybrid` 属于受控验证前的风格探索,不应被当作已验证的动态 Provider 路线。
    
    ## 最近生成的动态表情包 GIF
    
    下面是最近完成的“暖尾狐狸”九宫格案例:9 个独立表情均为原始 240×240、8 fps、3 秒可循环 GIF,已通过透明度、边界和编码检查。完整来源与 SHA-256 记录见 [`manifest.json`](docs/assets/recent-sticker-pack/manifest.json);13 个风格的长期验证证据仍见 [gallery/](gallery/README.md)。
    
    | 社死 | 阴阳怪气 | 吃瓜 |
    |---|---|---|
    | <img src="docs/assets/recent-sticker-pack/fox-01.gif" width="180" alt="暖尾狐狸社死动态表情"> | <img src="docs/assets/recent-sticker-pack/fox-02.gif" width="180" alt="暖尾狐狸阴阳怪气动态表情"> | <img src="docs/assets/recent-sticker-pack/fox-03.gif" width="180" alt="暖尾狐狸吃瓜动态表情"> |
    | <img src="docs/assets/recent-sticker-pack/fox-04.gif" width="180" alt="暖尾狐狸摆烂动态表情"> | <img src="docs/assets/recent-sticker-pack/fox-05.gif" width="180" alt="暖尾狐狸收到动态表情"> | <img src="docs/assets/recent-sticker-pack/fox-06.gif" width="180" alt="暖尾狐狸冲鸭动态表情"> |
    | <img src="docs/assets/recent-sticker-pack/fox-07.gif" width="180" alt="暖尾狐狸破防动态表情"> | <img src="docs/assets/recent-sticker-pack/fox-08.gif" width="180" alt="暖尾狐狸疑惑动态表情"> | <img src="docs/assets/recent-sticker-pack/fox-09.gif" width="180" alt="暖尾狐狸撒娇动态表情"> |
    
    查看或验证选择器:
    
    ```bash
    python3 scripts/style_selector.py --format markdown
    python3 scripts/style_selector.py --format core
    python3 scripts/style_selector.py --style clay-cute
    python3 scripts/style_selector.py --style soft-plush
    python3 scripts/style_selector.py --verify-only
    ```
    
    其中 `cute` 是兼容保留的规范 ID,`soft-plush` 是推荐的可读别名;两者解析到同一份真实验证证据。
    
    v0.3.1 的核心目录目标为 16 个方向;`--format core` 会同时显示已验证和待受控验证的状态,普通 `--format markdown` 只显示已通过证据门槛的风格。待受控验证的核心风格可以在用户明确指定时编译,但会在合同中标记为未验证。核心目录之外的文化媒介、印刷、复古 UI 或混合风格,请使用 `custom` 描述,不会被硬编码成未经验证的 preset。
    
    ```text
    $motion-sticker-pack
    风格 custom:水墨留白、干湿笔触,保留角色身份;不要添加整格背景。
    ```
    
    完整证据见 [gallery/](gallery/README.md),完整 gallery 媒体按版本发布到 [GitHub Releases](https://github.com/kobingogo/motion-sticker-pack/releases)。旧版完整案例包已迁移至 [GitHub Release asset](https://github.com/kobingogo/motion-sticker-pack/releases/download/v0.2.0/motion-sticker-pack-legacy-gallery-2026-09.zip)。
    
    ## 静图与透明度
    
    首选 GPT-image-2 等能返回真实 Alpha 的图像工具。静图请求按输入模式选择:参考图路线先生成不透明纯绿 `#00FF00` 源图,文字定义路线先尝试透明 RGBA PNG;两者都必须经过本地像素检查,失败时才进行一次有界重试。
    
    - 棋盘格是可见背景,不是透明度。
    - 不假设模型真的返回了请求的 3×3;必须重新检测实际布局。
    - 低于 0.75 的布局置信度需要人工确认。
    - 静图确认后,图片或 layout 的任一字节变化都会使审批哈希失效。
    
    ## 自动幕布
    
    Grok 路线保持严格 `#00FF00` 合同。
    
    非 Grok 路线会从绿、蓝、品红、青四个候选中计算前景冲突,选择距离主体颜色最远的幕布。候选分数、每个 Provider 的颜色和确定性铺底输入都记录在 `video-task.json` 与 `artifact-manifest.json`。用户仍可显式传入 `--key-color`。
    
    ## 统一输出
    
    所有新本地路线默认:
    
    - 240×240;
    - 8fps;
    - lossless Animated WebP 为首选;
    - GIF 为兼容格式;
    - PNG 为干净首帧;
    - 编号按实际检测布局的 row-major 顺序;
    - 同一个 `delivered/` 目录与一个 `sticker-pack.zip`。
    
    ```text
    works/<character-slug>/delivered/
    ├── 01.webp … NN.webp
    ├── 01.gif  … NN.gif
    ├── 01.png  … NN.png
    ├── preview.png
    ├── layout.json
    ├── processing.json
    ├── job-state.json
    ├── prompts.json
    ├── route.json
    ├── attempt-ledger.json
    ├── artifact-manifest.json
    └── sticker-pack.zip
    ```
    
    完整规范见 [output contract](references/output-contract.md)。
    
    ## 安全与审计
    
    - 静图审批由 SHA-256 绑定。
    - 付费 attempt 首次只提交一次;用户主动要求再次生成时,必须先创建绑定当前输入和 route 的重试批准,不会静默重放。
    - xAI request id 支持恢复同一个远端任务。
    - 输出目录采用可恢复事务,拒绝输入/输出重叠。
    - `artifact-manifest.json` 记录静图、提示词、pose、route、视频和交付的依赖谱系。
    - 每个原生视频帧都经过幕布、Alpha、跨格实例与编码后 QC。
    
    更多说明:[Routing and audit](docs/advanced/routing-and-audit.md)。
    
    ## 安装
    
    ### 在 Codex 对话中安装(推荐)
    
    在 Codex 中发送以下消息:
    
    ```text
    $skill-installer
    请从 GitHub 仓库 `kobingogo/motion-sticker-pack` 安装 `motion-sticker-pack` Skill。
    Skill 位于仓库根目录(路径 `.`),安装名设为 `motion-sticker-pack`。
    ```
    
    安装器完成后,在下一轮 Codex 消息中发送 `$motion-sticker-pack` 验证;例如:
    
    ```text
    $motion-sticker-pack
    确认已加载该 Skill,并告诉我可用的入口和当前版本。
    ```
    
    如果发送 `$skill-installer` 后提示未找到该 Skill,可发送下面的兜底请求(需要当前 Codex 会话具备终端权限):
    
    ```text
    请不要调用 `$skill-installer`。请直接从
    https://github.com/kobingogo/motion-sticker-pack.git 获取仓库,并将包含 `SKILL.md` 的仓库根目录安装到
    `$CODEX_HOME/skills/motion-sticker-pack`;如果未设置 `$CODEX_HOME`,使用 `~/.codex/skills/motion-sticker-pack`。
    安装完成后报告实际路径,并在下一轮消息中加载该 Skill。
    ```
    
    ### 本地脚本环境(可选)
    
    如果只在 Codex 对话中调用,使用上面的安装流程即可。需要本地运行脚本或参与开发时,再执行:
    
    ```bash
    git clone https://github.com/kobingogo/motion-sticker-pack.git
    cd motion-sticker-pack
    python3 -m pip install -r requirements.txt
    npm ci --ignore-scripts
    ```
    
    Skill 的执行合同见 [SKILL.md](SKILL.md)。
    
    ## 高级文档
    
    - [Provider、凭据与 ZDR](docs/advanced/providers-and-zdr.md)
    - [路由、ledger 与 artifact manifest](docs/advanced/routing-and-audit.md)
    - [完整 CLI 参考](docs/advanced/cli-reference.md)
    - [仓库媒体策略、Release gate 与历史瘦身评估](docs/advanced/repository-maintenance.md)
    - [风格库策略与 v0.4 候选](docs/advanced/style-library.md)
    - [提示词合同](references/prompt-contract.md)
    - [关键姿势工作流](references/keypose-workflow.md)
    - [对抗性审计](docs/adversarial-audit.md)
    
    ## 开发验证
    
    ```bash
    python3 -m unittest discover -s tests -v
    npm test
    python3 scripts/style_selector.py --verify-only
    python3 scripts/check_repository_policy.py
    ```
    
    CI 在 Python 3.10/3.12 和 Node 22 上运行。正式版本只能通过 [release workflow](.github/workflows/release.yml) 从通过完整验证的 `main` 创建 tag 和 Release。
    
    ## License
    
    MIT。角色肖像、商标和生成媒体的使用权由使用者自行确认。
    
  • scripts/animation_export.py8.7 KB21bb70294788upstream ↗
    #!/usr/bin/env python3
    """Encode looping sticker animations as WebP and GIF."""
    
    from __future__ import annotations
    
    import shutil
    import subprocess
    import tempfile
    from pathlib import Path
    
    import numpy as np
    from PIL import Image
    
    GIF_ALPHA_THRESHOLD = 128
    GIF_ALPHA_CANDIDATES = (96, 128, 160, 192)
    
    
    def frame_duration_ms(fps: float) -> int:
        if fps < 1:
            raise ValueError("fps must be at least 1")
        return max(20, round(1000 / fps))
    
    
    def frame_durations_ms(frame_count: int, fps: float) -> list[int]:
        """Return millisecond frame durations whose total tracks the source clock."""
        if frame_count < 1:
            raise ValueError("frame_count must be at least 1")
        if fps < 1:
            raise ValueError("fps must be at least 1")
        boundaries = [round(index * 1000 / fps) for index in range(frame_count + 1)]
        return [max(1, right - left) for left, right in zip(boundaries, boundaries[1:])]
    
    
    def choose_gif_alpha_threshold(
        images: list[Image.Image], candidates: tuple[int, ...] = GIF_ALPHA_CANDIDATES
    ) -> tuple[int, dict]:
        """Choose a binary-alpha cutoff that balances fringe retention and erosion."""
        if not images:
            raise ValueError("GIF threshold selection requires at least one frame")
        scores: list[dict] = []
        if not candidates or any(not 1 <= value <= 254 for value in candidates):
            raise ValueError("GIF alpha threshold candidates must be between 1 and 254")
        for threshold in candidates:
            fringe = erosion = residual_green = 0.0
            coverages = []
            for image in images:
                rgba = np.asarray(image.convert("RGBA"), dtype=np.uint8)
                alpha = rgba[:, :, 3]
                visible = alpha >= threshold
                intended = alpha >= 128
                fringe += float(np.mean(visible & (alpha < 128)))
                erosion += float(np.count_nonzero(intended & ~visible) / max(1, np.count_nonzero(intended)))
                rgb = rgba[:, :, :3].astype(np.int16)
                green = rgb[:, :, 1] - np.maximum(rgb[:, :, 0], rgb[:, :, 2])
                residual_green += float(np.mean(visible & (green > 8)))
                coverages.append(float(np.mean(visible)))
            score = (
                2.0 * fringe / len(images)
                + 1.25 * erosion / len(images)
                + 2.0 * residual_green / len(images)
                + 0.25 * float(np.std(coverages))
            )
            scores.append({"threshold": threshold, "score": round(score, 8)})
        selected = min(scores, key=lambda item: (item["score"], abs(item["threshold"] - 128)))
        return int(selected["threshold"]), {"selected": selected, "candidates": scores}
    
    
    def encode_webp(frame_paths: list[Path], target: Path, fps: float) -> None:
        if not frame_paths:
            raise ValueError("animation encoding requires at least one frame")
        frames = [Image.open(path).convert("RGBA") for path in frame_paths]
        try:
            frames[0].save(
                target,
                save_all=True,
                append_images=frames[1:],
                duration=frame_durations_ms(len(frames), fps),
                loop=0,
                lossless=True,
                method=4,
            )
        finally:
            for frame in frames:
                frame.close()
    
    
    def encode_webp_images(
        images: list[Image.Image], target: Path, fps: float, *, lossless: bool = True,
        quality: int = 85, method: int = 4, loop: int = 0,
    ) -> None:
        if not images:
            raise ValueError("animation encoding requires at least one frame")
        converted = [image.convert("RGBA") for image in images]
        converted[0].save(
            target,
            save_all=True,
            append_images=converted[1:],
            duration=frame_durations_ms(len(converted), fps),
            loop=loop,
            lossless=lossless,
            quality=quality,
            method=method,
        )
    
    
    def encode_gif(
        frame_paths: list[Path], target: Path, fps: float, alpha_threshold: int = GIF_ALPHA_THRESHOLD,
        max_colors: int = 256, dither: str = "none", optimize_delta_frames: bool = True,
        loop: int = 0,
    ) -> None:
        if not frame_paths:
            raise ValueError("animation encoding requires at least one frame")
        if not 1 <= alpha_threshold <= 254:
            raise ValueError("alpha_threshold must be between 1 and 254")
        if not 2 <= max_colors <= 256:
            raise ValueError("max_colors must be between 2 and 256")
        if dither not in {"none", "bayer"}:
            raise ValueError("dither must be none or bayer")
        if shutil.which("ffmpeg"):
            try:
                _encode_gif_ffmpeg(
                    frame_paths, target, fps, alpha_threshold, max_colors, dither,
                    optimize_delta_frames, loop,
                )
                return
            except (OSError, subprocess.CalledProcessError, RuntimeError):
                pass
        _encode_gif_pillow(
            frame_paths, target, frame_durations_ms(len(frame_paths), fps), alpha_threshold, max_colors, loop
        )
    
    
    def encode_gif_images(
        images: list[Image.Image], target: Path, fps: float, alpha_threshold: int = GIF_ALPHA_THRESHOLD,
        max_colors: int = 256, dither: str = "none", optimize_delta_frames: bool = True,
        loop: int = 0,
    ) -> None:
        if not images:
            raise ValueError("animation encoding requires at least one frame")
        with tempfile.TemporaryDirectory(prefix="motion-sticker-gif-") as temporary:
            paths = []
            for index, image in enumerate(images, start=1):
                path = Path(temporary) / f"{index:04d}.png"
                image.convert("RGBA").save(path)
                paths.append(path)
            encode_gif(
                paths, target, fps, alpha_threshold, max_colors, dither, optimize_delta_frames, loop
            )
    
    
    def _encode_gif_ffmpeg(
        frame_paths: list[Path], target: Path, fps: float, alpha_threshold: int,
        max_colors: int, dither: str, optimize_delta_frames: bool, loop: int,
    ) -> None:
        with tempfile.TemporaryDirectory(prefix="motion-sticker-gif-ff-") as temporary:
            root = Path(temporary)
            for index, source in enumerate(frame_paths, start=1):
                destination = root / f"{index:04d}.png"
                try:
                    destination.hardlink_to(source)
                except OSError:
                    shutil.copyfile(source, destination)
            palette_colors = min(255, max_colors)
            palette_dither = "none" if dither == "none" else "bayer:bayer_scale=3"
            diff_mode = ":diff_mode=rectangle" if optimize_delta_frames else ""
            command = [
                "ffmpeg",
                "-y",
                "-hide_banner",
                "-loglevel",
                "error",
                "-framerate",
                str(fps),
                "-i",
                str(root / "%04d.png"),
                "-vf",
                f"split[s0][s1];[s0]palettegen=reserve_transparent=1:max_colors={palette_colors}[p];"
                f"[s1][p]paletteuse=dither={palette_dither}{diff_mode}:alpha_threshold={alpha_threshold}",
                "-loop",
                str(loop),
                str(target),
            ]
            completed = subprocess.run(command, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if completed.returncode or not target.is_file() or target.stat().st_size <= 0:
                detail = completed.stderr.decode("utf-8", errors="replace").strip()
                raise RuntimeError(detail or "ffmpeg GIF encoding failed")
    
    
    def _rgba_to_transparent_gif(
        image: Image.Image, alpha_threshold: int, max_colors: int
    ) -> Image.Image:
        rgba = image.convert("RGBA")
        alpha = rgba.getchannel("A")
        mask = alpha.point(lambda value: 255 if value < alpha_threshold else 0)
        opaque_colors = max(1, min(255, max_colors - 1))
        quantized = rgba.convert("RGB").quantize(colors=opaque_colors, method=Image.Quantize.FASTOCTREE)
        palette = list(quantized.getpalette() or [])
        palette.extend([0] * max(0, 768 - len(palette)))
        pixels = bytearray(quantized.tobytes())
        for index, flag in enumerate(mask.tobytes()):
            if flag:
                pixels[index] = 255
        result = Image.frombytes("P", quantized.size, bytes(pixels))
        result.putpalette(palette[:768])
        result.info["transparency"] = 255
        return result
    
    
    def _encode_gif_pillow(
        frame_paths: list[Path], target: Path, duration_ms: int | list[int], alpha_threshold: int,
        max_colors: int, loop: int,
    ) -> None:
        converted: list[Image.Image] = []
        originals: list[Image.Image] = []
        try:
            for path in frame_paths:
                rgba = Image.open(path).convert("RGBA")
                originals.append(rgba)
                converted.append(_rgba_to_transparent_gif(rgba, alpha_threshold, max_colors))
            converted[0].save(
                target,
                save_all=True,
                append_images=converted[1:],
                duration=duration_ms,
                loop=loop,
                disposal=2,
                transparency=255,
                optimize=False,
            )
        finally:
            for image in converted + originals:
                image.close()
    
  • scripts/artifact_manifest.py7.3 KBf2c4f5b37bbdupstream ↗
    #!/usr/bin/env python3
    """Append-only, hash-bound lineage manifest for workflow artifacts."""
    
    from __future__ import annotations
    
    import argparse
    import hashlib
    import json
    from pathlib import Path
    from typing import Any, Iterable
    
    from attempt_ledger import atomic_write_json, file_sha256, ledger_lock, utc_now
    from config_contract import ContractError
    
    
    def read_manifest(path: Path) -> dict[str, Any]:
        try:
            value = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise ContractError(f"cannot read artifact manifest from {path}: {exc}") from exc
        if value.get("version") != 1 or not isinstance(value.get("artifacts"), list):
            raise ContractError("artifact manifest must be a version 1 object with artifacts")
        return value
    
    
    def initialize_manifest(path: Path, workspace: Path) -> dict[str, Any]:
        now = utc_now()
        manifest = {
            "version": 1,
            "workspace": str(workspace.expanduser().resolve()),
            "created_at": now,
            "updated_at": now,
            "artifacts": [],
        }
        atomic_write_json(path, manifest)
        return manifest
    
    
    def artifact_id(path: Path, sha256: str) -> str:
        path_digest = hashlib.sha256(str(path).encode("utf-8")).hexdigest()[:16]
        return f"sha256:{sha256}:{path_digest}:{path.name}"
    
    
    def record_artifact(
        manifest_path: Path,
        artifact_path: Path,
        *,
        kind: str,
        stage: str,
        dependencies: Iterable[str] = (),
        workspace: Path | None = None,
    ) -> str:
        artifact = artifact_path.expanduser().resolve()
        if not artifact.is_file():
            raise ContractError(f"artifact does not exist or is not a file: {artifact}")
        digest = file_sha256(artifact)
        identifier = artifact_id(artifact, digest)
        dependency_ids = sorted(set(dependencies))
        with ledger_lock(manifest_path):
            if manifest_path.is_file():
                manifest = read_manifest(manifest_path)
            else:
                manifest = initialize_manifest(manifest_path, workspace or manifest_path.parent)
            known = {item.get("id") for item in manifest["artifacts"] if isinstance(item, dict)}
            missing = [item for item in dependency_ids if item not in known]
            if missing:
                raise ContractError(f"artifact dependencies are not present in the manifest: {missing}")
            existing = next((item for item in manifest["artifacts"] if item.get("id") == identifier), None)
            if existing is not None:
                if existing.get("path") != str(artifact):
                    raise ContractError("artifact id collision")
                if not existing.get("current", True):
                    for prior in manifest["artifacts"]:
                        if prior.get("path") == str(artifact):
                            prior["current"] = False
                    existing["current"] = True
                    existing["reactivated_at"] = utc_now()
                    manifest["updated_at"] = utc_now()
                    atomic_write_json(manifest_path, manifest)
                return identifier
            for prior in manifest["artifacts"]:
                if prior.get("path") == str(artifact) and prior.get("current", True):
                    prior["current"] = False
            manifest["artifacts"].append(
                {
                    "id": identifier,
                    "path": str(artifact),
                    "sha256": digest,
                    "bytes": artifact.stat().st_size,
                    "kind": kind,
                    "stage": stage,
                    "dependencies": dependency_ids,
                    "recorded_at": utc_now(),
                    "current": True,
                }
            )
            manifest["updated_at"] = utc_now()
            atomic_write_json(manifest_path, manifest)
        return identifier
    
    
    def verify_manifest(path: Path) -> dict[str, Any]:
        manifest = read_manifest(path)
        known: set[str] = set()
        for item in manifest["artifacts"]:
            if not isinstance(item, dict):
                raise ContractError("artifact entries must be objects")
            identifier = item.get("id")
            artifact = Path(str(item.get("path", "")))
            if not isinstance(identifier, str) or not identifier:
                raise ContractError("artifact entry is missing id")
            if identifier in known:
                raise ContractError(f"duplicate artifact id: {identifier}")
            if item.get("current", True):
                if not artifact.is_absolute() or not artifact.is_file():
                    raise ContractError(f"artifact is missing: {artifact}")
                if file_sha256(artifact) != item.get("sha256"):
                    raise ContractError(f"artifact hash mismatch: {artifact}")
            dependencies = item.get("dependencies")
            if not isinstance(dependencies, list) or any(value not in known for value in dependencies):
                raise ContractError(f"artifact has missing or forward dependencies: {identifier}")
            known.add(identifier)
        return {"valid": True, "artifacts": len(known), "manifest": str(path.resolve())}
    
    
    def retire_artifacts_under(path: Path, root: Path) -> int:
        """Mark cleaned intermediate artifacts below root as historical, never delete them."""
    
        root = root.expanduser().resolve()
        with ledger_lock(path):
            manifest = read_manifest(path)
            changed = 0
            for item in manifest["artifacts"]:
                if not item.get("current", True):
                    continue
                artifact = Path(str(item.get("path", "")))
                try:
                    artifact.relative_to(root)
                except ValueError:
                    continue
                item["current"] = False
                item["retired_at"] = utc_now()
                changed += 1
            if changed:
                manifest["updated_at"] = utc_now()
                atomic_write_json(path, manifest)
        return changed
    
    
    def main() -> int:
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers(dest="command", required=True)
        record = subparsers.add_parser("record")
        record.add_argument("--manifest", type=Path, required=True)
        record.add_argument("--artifact", type=Path, required=True)
        record.add_argument("--kind", required=True)
        record.add_argument("--stage", required=True)
        record.add_argument("--dependency", action="append", default=[])
        verify = subparsers.add_parser("verify")
        verify.add_argument("--manifest", type=Path, required=True)
        retire = subparsers.add_parser("retire-under")
        retire.add_argument("--manifest", type=Path, required=True)
        retire.add_argument("--root", type=Path, required=True)
        show = subparsers.add_parser("show")
        show.add_argument("--manifest", type=Path, required=True)
        args = parser.parse_args()
        if args.command == "record":
            result: Any = {
                "id": record_artifact(
                    args.manifest,
                    args.artifact,
                    kind=args.kind,
                    stage=args.stage,
                    dependencies=args.dependency,
                )
            }
        elif args.command == "verify":
            result = verify_manifest(args.manifest)
        elif args.command == "retire-under":
            result = {
                "manifest": str(args.manifest.resolve()),
                "root": str(args.root.expanduser().resolve()),
                "retired": retire_artifacts_under(args.manifest, args.root),
            }
        else:
            result = read_manifest(args.manifest)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/assemble_delivery.py6.2 KB0c7238ef88e3upstream ↗
    #!/usr/bin/env python3
    """Assemble media and audit artifacts into the final delivery directory and ZIP."""
    
    from __future__ import annotations
    
    import argparse
    import json
    import re
    import shutil
    import zipfile
    from pathlib import Path
    
    from output_safety import (
        DELIVERY_VARIANT_DIRECTORY,
        begin_output_transaction,
        validate_archive_name,
    )
    from artifact_manifest import retire_artifacts_under
    
    
    MEDIA_RE = re.compile(r"^\d{2,}\.(?:png|webp|gif)$")
    BASE_REPORTS = ("layout.json", "processing.json")
    OPTIONAL_MEDIA_REPORTS = ("sticker-production.json",)
    AUDIT_REPORTS = (
        "artifact-manifest.json",
        "attempt-ledger.json",
        "video-retry-approval.json",
        "job-state.json",
        "prompts.json",
        "route.json",
        "static-prompt.json",
        "static-generation.json",
        "static-generation-attempts.json",
        "static-alpha.json",
        "video-result.json",
        "keypose-plan.json",
        "keypose-preparation.json",
        "static-cells.json",
    )
    
    
    def locate_audit_report(audit_dir: Path, name: str) -> Path | None:
        """Find a canonical report at the audit root or in a workflow subdirectory."""
        direct = audit_dir / name
        if direct.is_file():
            return direct
        candidates = sorted(
            (path for path in audit_dir.rglob(name) if path.is_file()),
            key=lambda path: (len(path.relative_to(audit_dir).parts), str(path)),
        )
        if not candidates:
            return None
        nearest_depth = len(candidates[0].relative_to(audit_dir).parts)
        nearest = [path for path in candidates if len(path.relative_to(audit_dir).parts) == nearest_depth]
        if len(nearest) > 1:
            raise ValueError(
                f"ambiguous audit report {name!r}; choose one canonical copy at the audit root: "
                + ", ".join(str(path) for path in nearest)
            )
        return nearest[0]
    
    
    def main() -> int:
        parser = argparse.ArgumentParser()
        parser.add_argument("--media-dir", type=Path, required=True)
        parser.add_argument("--audit-dir", type=Path, required=True)
        parser.add_argument("--output", type=Path, required=True)
        parser.add_argument("--zip-name", default="sticker-pack.zip")
        parser.add_argument("--require-job-state", action="store_true")
        parser.add_argument("--require-prompts", action="store_true")
        parser.add_argument("--require-route", action="store_true")
        parser.add_argument(
            "--cleanup-media-dir",
            action="store_true",
            help="remove the intermediate media directory after the final delivery ZIP succeeds",
        )
        parser.add_argument("--overwrite", action="store_true")
        args = parser.parse_args()
        archive_name = validate_archive_name(args.zip_name)
        media_dir = args.media_dir.expanduser().resolve()
        audit_dir = args.audit_dir.expanduser().resolve()
        output = args.output.expanduser().resolve()
        if not media_dir.is_dir() or not audit_dir.is_dir():
            raise ValueError("media-dir and audit-dir must be directories")
        if args.cleanup_media_dir and (
            media_dir in {audit_dir, output}
            or output.is_relative_to(media_dir)
            or media_dir.is_relative_to(output)
        ):
            raise ValueError("cleanup-media-dir requires separate sibling media and output directories")
    
        media = sorted(path for path in media_dir.iterdir() if path.is_file() and MEDIA_RE.fullmatch(path.name))
        if not media:
            raise ValueError("media-dir contains no numbered PNG/WebP/GIF artifacts")
        for name in BASE_REPORTS:
            if not (media_dir / name).is_file():
                raise FileNotFoundError(media_dir / name)
        required = {
            "job-state.json": args.require_job_state,
            "prompts.json": args.require_prompts,
            "route.json": args.require_route,
        }
        audit = [audit_dir / name for name, must_exist in required.items() if must_exist]
        for path in audit:
            if not path.is_file():
                raise FileNotFoundError(path)
    
        output_transaction = begin_output_transaction(
            output,
            overwrite=args.overwrite,
            archive_names={archive_name},
            protected_paths=[media_dir, audit_dir],
        )
        output = output_transaction.output
        names = [path.name for path in media] + list(BASE_REPORTS)
        for path in media:
            shutil.copyfile(path, output / path.name)
        for name in BASE_REPORTS:
            shutil.copyfile(media_dir / name, output / name)
        for name in OPTIONAL_MEDIA_REPORTS:
            source = media_dir / name
            if source.is_file():
                shutil.copyfile(source, output / name)
                names.append(name)
        preview = media_dir / "preview.png"
        if preview.is_file():
            shutil.copyfile(preview, output / preview.name)
            names.append(preview.name)
        variant_directories = sorted(
            path for path in media_dir.iterdir()
            if path.is_dir() and DELIVERY_VARIANT_DIRECTORY.fullmatch(path.name)
        )
        for source in variant_directories:
            target = output / source.name
            target.mkdir(parents=True)
            for path in sorted(source.rglob("*")):
                if not path.is_file() or path.suffix.lower() == ".zip":
                    continue
                relative = path.relative_to(source)
                destination = target / relative
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(path, destination)
                names.append(str(destination.relative_to(output)))
        for name in AUDIT_REPORTS:
            source = locate_audit_report(audit_dir, name)
            if source is not None:
                shutil.copyfile(source, output / name)
                names.append(name)
        if args.cleanup_media_dir and (output / "artifact-manifest.json").is_file():
            # The delivery copy must remain verifiable after intermediate media is
            # removed. Retire historical media references before it enters the ZIP.
            retire_artifacts_under(output / "artifact-manifest.json", media_dir)
        with zipfile.ZipFile(output / archive_name, "w", zipfile.ZIP_DEFLATED) as bundle:
            for name in names:
                bundle.write(output / name, arcname=name)
        output_transaction.commit()
        if args.cleanup_media_dir:
            shutil.rmtree(media_dir)
        print(json.dumps({"output": str(output), "zip": str(output / archive_name), "files": names}, ensure_ascii=False))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/assemble_prompt_only.py3.1 KBcd9e1ad49183upstream ↗
    #!/usr/bin/env python3
    """Deliver auditable prompt artifacts when no video or local image processing is available."""
    
    from __future__ import annotations
    
    import argparse
    import json
    import shutil
    import zipfile
    from pathlib import Path
    
    from output_safety import begin_output_transaction, validate_archive_name
    
    
    def main() -> int:
        parser = argparse.ArgumentParser()
        parser.add_argument("--static-prompt", type=Path, required=True)
        parser.add_argument("--tile-plan", type=Path, required=True)
        parser.add_argument("--prompts", type=Path, required=True)
        parser.add_argument("--route", type=Path, required=True)
        parser.add_argument("--output", type=Path, required=True)
        parser.add_argument("--zip-name", default="prompt-only.zip")
        parser.add_argument("--overwrite", action="store_true")
        args = parser.parse_args()
        archive_name = validate_archive_name(args.zip_name)
        sources = {
            "static-prompt.json": args.static_prompt,
            "tile-plan.json": args.tile_plan,
            "prompts.json": args.prompts,
            "route.json": args.route,
        }
        for source in sources.values():
            if not source.expanduser().is_file():
                raise FileNotFoundError(source)
        route = json.loads(args.route.expanduser().read_text(encoding="utf-8"))
        if not isinstance(route, dict):
            raise ValueError("route must be a JSON object")
        selected = route.get("selected")
        attempts = route.get("attempts")
        preflight = route.get("preflight")
        selected_id = selected.get("id") if isinstance(selected, dict) else None
        if selected_id != "prompt-only" or attempts not in ([], None):
            raise ValueError("prompt-only delivery requires a route that selected prompt-only with no executable attempts")
        if isinstance(preflight, dict) and preflight.get("selected_provider") not in {None, "prompt-only"}:
            raise ValueError("prompt-only delivery does not match route preflight")
        output_transaction = begin_output_transaction(
            args.output,
            overwrite=args.overwrite,
            archive_names={archive_name},
            protected_paths=sources.values(),
        )
        output = output_transaction.output
        names = list(sources)
        for name, source in sources.items():
            shutil.copyfile(source.expanduser().resolve(), output / name)
        manifest = {
            "version": 1,
            "mode": "prompt-only",
            "generated_video": False,
            "message": "No video or local image-processing capability was available; deliver prompts and stop.",
            "outputs": names + ["prompt-only.json", archive_name],
        }
        (output / "prompt-only.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        names.append("prompt-only.json")
        with zipfile.ZipFile(output / archive_name, "w", zipfile.ZIP_DEFLATED) as bundle:
            for name in names:
                bundle.write(output / name, arcname=name)
        output_transaction.commit()
        print(json.dumps({"output": str(output), "zip": str(output / archive_name), "generated_video": False}, ensure_ascii=False))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/attempt_ledger.py16 KBa9cb2e88101fupstream ↗
    #!/usr/bin/env python3
    """Immutable-attempt ledger for billable video-provider execution."""
    
    from __future__ import annotations
    
    import argparse
    import hashlib
    import json
    import os
    import tempfile
    import uuid
    from contextlib import contextmanager
    from datetime import datetime, timezone
    from pathlib import Path
    from typing import Any, Iterator
    
    from config_contract import ContractError, object_sha256
    
    
    STATUSES = {"planned", "running", "submitted", "succeeded", "failed", "rejected", "uncertain"}
    TERMINAL_STATUSES = {"succeeded", "failed", "rejected"}
    
    
    def utc_now() -> str:
        return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
    
    
    def file_sha256(path: Path) -> str:
        digest = hashlib.sha256()
        with path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()
    
    
    def atomic_write_json(path: Path, value: dict[str, Any]) -> None:
        path.parent.mkdir(parents=True, exist_ok=True)
        descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
        temporary = Path(temporary_name)
        try:
            with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
                json.dump(value, handle, ensure_ascii=False, indent=2)
                handle.write("\n")
                handle.flush()
                os.fsync(handle.fileno())
            temporary.replace(path)
        except Exception:
            temporary.unlink(missing_ok=True)
            raise
    
    
    def read_json(path: Path) -> dict[str, Any]:
        try:
            value = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise ContractError(f"cannot read attempt ledger JSON from {path}: {exc}") from exc
        if not isinstance(value, dict):
            raise ContractError("attempt ledger must be a JSON object")
        return value
    
    
    def _transition(entry: dict[str, Any], status: str, **details: Any) -> None:
        if status not in STATUSES:
            raise ContractError(f"invalid attempt transition status: {status}")
        event = {"status": status, "at": utc_now(), **details}
        entry.setdefault("events", []).append(event)
        entry["status"] = status
        entry["updated_at"] = event["at"]
    
    
    def _pid_is_alive(pid: int) -> bool:
        if pid <= 0:
            return False
        try:
            os.kill(pid, 0)
        except ProcessLookupError:
            return False
        except PermissionError:
            return True
        return True
    
    
    @contextmanager
    def ledger_lock(path: Path) -> Iterator[None]:
        lock_path = path.with_name(f".{path.name}.lock")
        for _ in range(2):
            try:
                descriptor = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
                break
            except FileExistsError:
                try:
                    lock = json.loads(lock_path.read_text(encoding="utf-8"))
                    pid = int(lock.get("pid", 0))
                except (OSError, ValueError, json.JSONDecodeError):
                    pid = 0
                if _pid_is_alive(pid):
                    raise ContractError(f"attempt ledger is locked by active process {pid}")
                lock_path.unlink(missing_ok=True)
        else:
            raise ContractError("could not acquire attempt ledger lock")
        try:
            os.write(descriptor, json.dumps({"pid": os.getpid(), "created_at": utc_now()}).encode("utf-8"))
            os.close(descriptor)
            yield
        finally:
            try:
                os.close(descriptor)
            except OSError:
                pass
            lock_path.unlink(missing_ok=True)
    
    
    def validate_ledger(ledger: dict[str, Any], route: dict[str, Any] | None = None) -> dict[str, Any]:
        if ledger.get("version") != 1:
            raise ContractError("attempt ledger version must be 1")
        attempts = ledger.get("attempts")
        if not isinstance(attempts, list):
            raise ContractError("attempt ledger attempts must be an array")
        numbers: set[int] = set()
        for entry in attempts:
            if not isinstance(entry, dict):
                raise ContractError("attempt ledger entries must be objects")
            number = entry.get("attempt")
            if not isinstance(number, int) or isinstance(number, bool) or number < 1 or number in numbers:
                raise ContractError("attempt ledger attempt numbers must be unique positive integers")
            numbers.add(number)
            if entry.get("status") not in STATUSES:
                raise ContractError(f"attempt {number} has an invalid status")
            events = entry.get("events")
            if not isinstance(events, list) or not events or any(
                not isinstance(event, dict) or event.get("status") not in STATUSES for event in events
            ):
                raise ContractError(f"attempt {number} must have an immutable status event history")
            if events[-1]["status"] != entry["status"]:
                raise ContractError(f"attempt {number} status differs from its last event")
            if not isinstance(entry.get("provider"), str) or not entry["provider"]:
                raise ContractError(f"attempt {number} is missing provider")
        if route is not None:
            if ledger.get("route_sha256") != object_sha256(route):
                raise ContractError("attempt ledger belongs to a different route")
            if ledger.get("task_sha256") != route.get("task_sha256"):
                raise ContractError("attempt ledger task hash differs from the route")
            if ledger.get("config_sha256") != route.get("config_sha256"):
                raise ContractError("attempt ledger config hash differs from the route")
        return ledger
    
    
    def initialize_ledger(path: Path, route: dict[str, Any]) -> dict[str, Any]:
        if route.get("version") != 1 or not isinstance(route.get("attempts"), list):
            raise ContractError("route must be a version 1 object with attempts")
        now = utc_now()
        ledger = {
            "version": 1,
            "route_sha256": object_sha256(route),
            "task_sha256": route.get("task_sha256"),
            "config_sha256": route.get("config_sha256"),
            "created_at": now,
            "updated_at": now,
            "attempts": [
                {
                    "attempt": item["attempt"],
                    "provider": item["id"],
                    "driver": item.get("driver"),
                    "execution": item.get("execution"),
                    "status": "planned",
                    "cost_status": "not-started",
                    "resumable": item["id"] == "xai-direct",
                    "retry_count": 0,
                    "events": [{"status": "planned", "at": now}],
                }
                for item in route["attempts"]
            ],
        }
        validate_ledger(ledger, route)
        atomic_write_json(path, ledger)
        return ledger
    
    
    def progress_path_for(ledger_path: Path, attempt: int) -> Path:
        return ledger_path.with_name(f"{ledger_path.stem}.attempt-{attempt}.progress.json")
    
    
    def archive_ledger(path: Path) -> list[Path]:
        """Move a superseded ledger and its progress files to timestamped audit paths.
    
        The caller must hold ``ledger_lock(path)`` so route rollover and execution
        cannot race. Nothing is deleted.
        """
    
        if not path.is_file():
            return []
        stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
        counter = 0
        while True:
            suffix = f"-{counter}" if counter else ""
            archive = path.with_name(f"{path.stem}.archive-{stamp}{suffix}{path.suffix}")
            if not archive.exists():
                break
            counter += 1
        os.replace(path, archive)
        archived = [archive]
        for progress in sorted(path.parent.glob(f"{path.stem}.attempt-*.progress.json")):
            tail = progress.name[len(path.stem):]
            destination = archive.with_name(f"{archive.stem}{tail}")
            os.replace(progress, destination)
            archived.append(destination)
        return archived
    
    
    def _progress(path: Path) -> dict[str, Any]:
        if not path.is_file():
            return {}
        try:
            value = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise ContractError(f"cannot read attempt progress file {path}: {exc}") from exc
        if not isinstance(value, dict):
            raise ContractError("attempt progress must be a JSON object")
        return value
    
    
    def claim_attempt(
        path: Path,
        route: dict[str, Any],
        attempt: int,
        result_path: Path,
        *,
        resume: bool = False,
        retry_approval_sha256: str | None = None,
    ) -> dict[str, Any]:
        with ledger_lock(path):
            ledger = validate_ledger(read_json(path), route) if path.is_file() else initialize_ledger(path, route)
            entries = [entry for entry in ledger["attempts"] if entry["attempt"] == attempt]
            if len(entries) != 1:
                raise ContractError(f"attempt ledger has no unique attempt {attempt}")
            entry = entries[0]
            prior_entries = [item for item in ledger["attempts"] if item["attempt"] < attempt]
            if prior_entries:
                prior = max(prior_entries, key=lambda item: item["attempt"])
                if prior["status"] not in {"failed", "rejected", "uncertain"}:
                    raise ContractError(
                        f"attempt {attempt} cannot start before attempt {prior['attempt']} reaches a terminal failure state"
                    )
            progress = _progress(progress_path_for(path, attempt))
            if entry["status"] == "running":
                owner_pid = int(entry.get("owner_pid", 0) or 0)
                if _pid_is_alive(owner_pid):
                    raise ContractError(
                        f"attempt {attempt} is actively owned by process {owner_pid}; concurrent execution is blocked"
                    )
                _transition(
                    entry,
                    "submitted" if progress.get("request_id") else "uncertain",
                    reason="reconciled-interrupted-running-attempt",
                )
                ledger["updated_at"] = utc_now()
                atomic_write_json(path, ledger)
            if entry["status"] in {"submitted", "uncertain"} and progress.get("request_id"):
                entry["request_id"] = str(progress["request_id"])
            if entry["status"] == "succeeded":
                stored_result = Path(str(entry.get("result", {}).get("path", "")))
                expected_hash = entry.get("result", {}).get("sha256")
                if stored_result != result_path.resolve() or not stored_result.is_file():
                    raise ContractError("completed attempt result is missing or was requested at a different path")
                if file_sha256(stored_result) != expected_hash:
                    raise ContractError("completed attempt result hash no longer matches the ledger")
                return {"idempotent": True, "entry": entry, "resume_request_id": None}
            resume_request_id = entry.get("request_id")
            replay = entry["status"] != "planned"
            if not replay and retry_approval_sha256:
                raise ContractError("retry approval can only be used for a prior execution")
            if replay and not retry_approval_sha256 and not resume:
                raise ContractError(
                    f"attempt {attempt} is already {entry['status']}; explicit user approval is required to retry"
                )
            if retry_approval_sha256 and any(
                event.get("retry_approval_sha256") == retry_approval_sha256
                for event in entry.get("events", [])
            ):
                raise ContractError("retry approval has already been consumed")
            if resume:
                if not entry.get("resumable") or entry["status"] not in {"submitted", "uncertain"}:
                    raise ContractError("attempt is not in a resumable state")
                if not isinstance(resume_request_id, str) or not resume_request_id:
                    raise ContractError("resumable attempt has no provider request id")
            elif entry["status"] not in {"planned", "failed", "rejected", "uncertain"}:
                raise ContractError(f"attempt {attempt} cannot be retried from state {entry['status']}")
            transition_details: dict[str, Any] = {"resumed": resume}
            if replay:
                transition_details.update(
                    {
                        "retry": True,
                        "confirmed_by_user": True,
                        "retry_approval_sha256": retry_approval_sha256,
                    }
                )
                entry["retry_count"] = int(entry.get("retry_count", 0)) + 1
            _transition(entry, "running", **transition_details)
            entry["cost_status"] = "possible"
            entry["started_at"] = entry.get("started_at") or utc_now()
            entry["last_started_at"] = utc_now()
            entry["resume_count"] = int(entry.get("resume_count", 0)) + (1 if resume else 0)
            entry["result_path"] = str(result_path.resolve())
            entry["owner_pid"] = os.getpid()
            entry["execution_id"] = str(uuid.uuid4())
            transition_details["execution_id"] = entry["execution_id"]
            entry["events"][-1].update(transition_details)
            ledger["updated_at"] = utc_now()
            atomic_write_json(path, ledger)
            return {"idempotent": False, "entry": entry, "resume_request_id": resume_request_id}
    
    
    def finish_attempt(
        path: Path,
        route: dict[str, Any],
        attempt: int,
        status: str,
        *,
        result_path: Path | None = None,
        generated_path: Path | None = None,
        error: str | None = None,
        request_id: str | None = None,
    ) -> dict[str, Any]:
        if status not in TERMINAL_STATUSES | {"submitted", "uncertain"}:
            raise ContractError(f"cannot finish attempt with status {status!r}")
        with ledger_lock(path):
            ledger = validate_ledger(read_json(path), route)
            entry = next((item for item in ledger["attempts"] if item["attempt"] == attempt), None)
            if entry is None:
                raise ContractError(f"attempt ledger has no attempt {attempt}")
            if entry["status"] == "succeeded" and status != "succeeded":
                raise ContractError("a succeeded attempt cannot transition to another state")
            if entry["status"] != "running":
                raise ContractError(f"attempt {attempt} cannot finish from state {entry['status']}")
            owner_pid = int(entry.get("owner_pid", 0) or 0)
            if owner_pid and owner_pid != os.getpid():
                raise ContractError(f"attempt {attempt} is owned by process {owner_pid}")
            progress = _progress(progress_path_for(path, attempt))
            effective_request_id = request_id or progress.get("request_id") or entry.get("request_id")
            event_details: dict[str, Any] = {}
            if error:
                event_details["error"] = error[:2000]
            if effective_request_id:
                event_details["request_id"] = str(effective_request_id)
            _transition(entry, status, **event_details)
            if effective_request_id:
                entry["request_id"] = str(effective_request_id)
            if error:
                entry["error"] = error[:2000]
            if result_path is not None and result_path.is_file():
                entry["result"] = {"path": str(result_path.resolve()), "sha256": file_sha256(result_path)}
            if generated_path is not None and generated_path.is_file():
                entry["generated"] = {
                    "path": str(generated_path.resolve()),
                    "sha256": file_sha256(generated_path),
                    "bytes": generated_path.stat().st_size,
                }
            if status == "succeeded":
                entry["cost_status"] = "completed"
                entry["completed_at"] = utc_now()
            elif status in {"failed", "rejected"}:
                entry["cost_status"] = "possible"
                entry["completed_at"] = utc_now()
            else:
                entry["cost_status"] = "unknown"
            entry.pop("owner_pid", None)
            ledger["updated_at"] = utc_now()
            atomic_write_json(path, ledger)
            return entry
    
    
    def main() -> int:
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers(dest="command", required=True)
        init = subparsers.add_parser("init")
        init.add_argument("--ledger", type=Path, required=True)
        init.add_argument("--route", type=Path, required=True)
        show = subparsers.add_parser("show")
        show.add_argument("--ledger", type=Path, required=True)
        args = parser.parse_args()
        if args.command == "init":
            route = read_json(args.route)
            with ledger_lock(args.ledger):
                if args.ledger.exists():
                    ledger = validate_ledger(read_json(args.ledger), route)
                else:
                    ledger = initialize_ledger(args.ledger, route)
        else:
            ledger = validate_ledger(read_json(args.ledger))
        print(json.dumps(ledger, ensure_ascii=False, indent=2))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/build_gallery_provenance.py6.7 KB3ca278a83d91upstream ↗
    #!/usr/bin/env python3
    """Build or verify compact provenance records for public Gallery cases.
    
    Gallery media predates the audited workflow in some repositories.  Those cases
    must remain useful evidence without pretending that an approval state or an
    artifact manifest was preserved.  The generated record therefore carries an
    explicit completeness status and a list of missing historical fields.
    """
    
    from __future__ import annotations
    
    import argparse
    import hashlib
    import json
    from pathlib import Path
    from typing import Any
    
    
    ROOT = Path(__file__).resolve().parents[1]
    DEFAULT_INDEX = ROOT / "gallery" / "index.json"
    DEFAULT_MANIFEST = ROOT / "gallery" / "release-manifest.json"
    
    
    def sha256_file(path: Path) -> str:
        digest = hashlib.sha256()
        with path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()
    
    
    def read_json(path: Path) -> dict[str, Any]:
        value = json.loads(path.read_text(encoding="utf-8"))
        if not isinstance(value, dict):
            raise ValueError(f"expected an object in {path}")
        return value
    
    
    def build_record(index_path: Path, entry: dict[str, Any], manifest_path: Path | None = None) -> dict[str, Any]:
        gallery_dir = index_path.parent / "styles" / str(entry["gallery"])
        manifest_path = manifest_path or index_path.parent / "release-manifest.json"
        manifest = read_json(manifest_path)
        release_entries = {item.get("gallery"): item for item in manifest.get("styles", [])}
        release_entry = release_entries.get(entry["gallery"])
        if not isinstance(release_entry, dict) or release_entry.get("id") != entry["id"]:
            raise ValueError(f"release manifest has no entry for {entry['gallery']}")
        route = read_json(gallery_dir / "route.json")
        processing = read_json(gallery_dir / "processing.json")
        layout = read_json(gallery_dir / "layout.json")
        selected = route.get("selected") if isinstance(route.get("selected"), dict) else {}
        layout_value = layout.get("detected_layout", layout)
        cells = processing.get("cells", [])
        successful_cells = int(processing.get("successful_cells", len(cells)))
        requested_cells = int(layout_value.get("count", 0))
        withheld_cells = [
            str(cell.get("id"))
            for cell in cells
            if isinstance(cell, dict) and cell.get("status") in {"withheld", "rejected"}
        ]
        media = list(release_entry.get("files", []))
        total_bytes = sum(int(record["bytes"]) for record in media)
        missing_historical = ["approval_hash", "artifact_manifest"]
        try:
            manifest_reference = str(manifest_path.relative_to(ROOT))
        except ValueError:
            manifest_reference = str(manifest_path)
        return {
            "version": 1,
            "case_status": "legacy-evidence-partial",
            "style_id": entry["id"],
            "gallery_id": entry["gallery"],
            "source_case": entry.get("source_case"),
            # Keep the required benchmark fields flat so downstream tooling does
            # not need to understand the richer human-facing sections below.
            "input_type": "legacy-gallery-case",
            "route": selected.get("id"),
            "route_id": selected.get("id"),
            "model": selected.get("model"),
            "approval_sha256": None,
            "native_frame_count": processing.get("frames_per_animation"),
            "successful_cells": successful_cells,
            "withheld_cells": withheld_cells,
            "output_size_bytes": total_bytes,
            "input": {
                "type": "legacy-gallery-case",
                "source_case": entry.get("source_case"),
            },
            "route_details": {
                "id": selected.get("id"),
                "driver": selected.get("driver"),
                "provider": selected.get("provider"),
                "model": selected.get("model"),
                "config_sha256": route.get("config_sha256"),
                "task_sha256": route.get("task_sha256"),
            },
            "media_delivery": {
                "type": "release-asset",
                "asset_name_template": manifest.get(
                    "asset_name_template", "motion-sticker-pack-gallery-v{version}.zip"
                ),
                "manifest": manifest_reference,
            },
            "approval": {
                "sha256": None,
                "status": "not-preserved",
                "reason": "This legacy public case predates hash-bound static approval records; do not treat route/task hashes as approval proof.",
            },
            "native": {
                "source_size": processing.get("source_size"),
                "fps": processing.get("output_fps"),
                "frames_per_animation": processing.get("frames_per_animation"),
            },
            "cells": {
                "requested": requested_cells,
                "successful": successful_cells,
                "withheld": withheld_cells,
                "quality_warnings": processing.get("warnings", []),
            },
            "outputs": {
                "media_bytes": total_bytes,
                "files": media,
            },
            "artifact_manifest": {
                "status": "not-preserved",
                "path": None,
            },
            "missing_historical_fields": missing_historical,
        }
    
    
    def verify_record(path: Path, index_path: Path, entry: dict[str, Any]) -> None:
        record = read_json(path)
        expected = build_record(index_path, entry)
        if record != expected:
            raise ValueError(f"provenance is stale or does not match current media: {path}")
    
    
    def main() -> int:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--index", type=Path, default=DEFAULT_INDEX)
        parser.add_argument("--write", action="store_true", help="write one provenance.json per Gallery style")
        parser.add_argument("--verify-only", action="store_true")
        args = parser.parse_args()
        index_path = args.index.expanduser().resolve()
        document = read_json(index_path)
        entries = document.get("styles")
        if not isinstance(entries, list) or not entries:
            raise ValueError("gallery index must contain a non-empty styles array")
        for entry in entries:
            if not isinstance(entry, dict) or not isinstance(entry.get("gallery"), str):
                raise ValueError("gallery entries must contain a gallery id")
            target = index_path.parent / "styles" / entry["gallery"] / "provenance.json"
            record = build_record(index_path, entry)
            if args.write:
                target.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
            if args.verify_only or not args.write:
                if not target.is_file():
                    raise FileNotFoundError(target)
                verify_record(target, index_path, entry)
        print(json.dumps({"valid": True, "styles": len(entries), "mode": "write" if args.write else "verify"}, ensure_ascii=False))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/build_gallery_release.py4.6 KB34ee3cd97f20upstream ↗
    #!/usr/bin/env python3
    """Build and verify the full gallery media Release asset."""
    
    from __future__ import annotations
    
    import argparse
    import hashlib
    import json
    from pathlib import Path
    from zipfile import ZIP_STORED, ZipFile, ZipInfo
    
    
    ROOT = Path(__file__).resolve().parents[1]
    MEDIA_FILES = ("static.png", "motion.gif", "motion.webp")
    DEFAULT_INDEX = ROOT / "gallery" / "index.json"
    DEFAULT_MANIFEST = ROOT / "gallery" / "release-manifest.json"
    
    
    def sha256_file(path: Path) -> str:
        digest = hashlib.sha256()
        with path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()
    
    
    def read_json(path: Path) -> dict:
        value = json.loads(path.read_text(encoding="utf-8"))
        if not isinstance(value, dict):
            raise ValueError(f"expected an object in {path}")
        return value
    
    
    def build_manifest(index_path: Path, source_root: Path) -> dict:
        index = read_json(index_path)
        styles = []
        for entry in index.get("styles", []):
            gallery_id = str(entry["gallery"])
            style_dir = source_root / gallery_id
            files = []
            for name in MEDIA_FILES:
                path = style_dir / name
                if not path.is_file():
                    raise FileNotFoundError(path)
                files.append(
                    {
                        "path": f"gallery/styles/{gallery_id}/{name}",
                        "sha256": sha256_file(path),
                        "bytes": path.stat().st_size,
                    }
                )
            styles.append({"id": entry["id"], "gallery": gallery_id, "files": files})
        return {
            "version": 1,
            "asset_name_template": "motion-sticker-pack-gallery-v{version}.zip",
            "media_files": list(MEDIA_FILES),
            "styles": styles,
        }
    
    
    def verify_manifest(manifest: dict, index_path: Path, source_root: Path) -> None:
        expected = build_manifest(index_path, source_root)
        if manifest.get("version") != 1:
            raise ValueError("gallery release manifest version must be 1")
        if manifest.get("media_files") != list(MEDIA_FILES):
            raise ValueError("gallery release manifest media_files are invalid")
        if manifest.get("styles") != expected["styles"]:
            raise ValueError("gallery release manifest does not match the full media source")
    
    
    def write_zip(output: Path, index_path: Path, manifest_path: Path, source_root: Path) -> None:
        manifest = read_json(manifest_path)
        verify_manifest(manifest, index_path, source_root)
        output.parent.mkdir(parents=True, exist_ok=True)
        files: list[tuple[str, Path]] = [
            ("gallery/index.json", index_path),
            ("gallery/release-manifest.json", manifest_path),
        ]
        for style in manifest["styles"]:
            for record in style["files"]:
                archive_path = str(record["path"])
                files.append((archive_path, source_root / style["gallery"] / Path(archive_path).name))
        with ZipFile(output, "w", compression=ZIP_STORED) as archive:
            for archive_path, source in files:
                if not source.is_file():
                    raise FileNotFoundError(source)
                info = ZipInfo(archive_path)
                info.date_time = (1980, 1, 1, 0, 0, 0)
                info.compress_type = ZIP_STORED
                info.external_attr = 0o100644 << 16
                archive.writestr(info, source.read_bytes())
    
    
    def main() -> int:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--source-root", type=Path, required=True)
        parser.add_argument("--index", type=Path, default=DEFAULT_INDEX)
        parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
        parser.add_argument("--manifest-output", type=Path)
        parser.add_argument("--output", type=Path)
        args = parser.parse_args()
        generated = build_manifest(args.index.resolve(), args.source_root.resolve())
        if args.manifest_output:
            args.manifest_output.write_text(json.dumps(generated, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        if args.manifest.is_file():
            verify_manifest(read_json(args.manifest.resolve()), args.index.resolve(), args.source_root.resolve())
        elif not args.manifest_output:
            raise FileNotFoundError(args.manifest)
        if args.output:
            manifest_path = args.manifest_output.resolve() if args.manifest_output else args.manifest.resolve()
            write_zip(args.output.resolve(), args.index.resolve(), manifest_path, args.source_root.resolve())
        print(json.dumps({"valid": True, "styles": len(generated["styles"]), "asset": str(args.output) if args.output else None}, ensure_ascii=False))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/character_workspace.py3.1 KB43bcec7d08f5upstream ↗
    #!/usr/bin/env python3
    """Resolve a per-character generated-asset directory under works/<slug>/."""
    
    from __future__ import annotations
    
    import argparse
    import json
    import re
    import unicodedata
    from pathlib import Path
    
    
    WINDOWS_RESERVED = {
        "con",
        "prn",
        "aux",
        "nul",
        *(f"com{index}" for index in range(1, 10)),
        *(f"lpt{index}" for index in range(1, 10)),
    }
    ILLEGAL = re.compile(r'[<>:"/\\|?*\x00-\x1f]+')
    
    
    def character_slug(name: str) -> str:
        text = unicodedata.normalize("NFC", name).strip()
        text = ILLEGAL.sub("-", text)
        text = text.replace("..", "-")
        text = re.sub(r"[\s._]+", "-", text)
        text = re.sub(r"-{2,}", "-", text).strip("-.")
        if not text:
            text = "unnamed"
        if text.casefold() in WINDOWS_RESERVED:
            text = f"_{text}"
        return text[:80]
    
    
    def character_workspace(skill_root: Path, name: str) -> Path:
        slug = character_slug(name)
        if slug in {".", ".."}:
            raise ValueError("invalid character slug")
        works_root = skill_root.expanduser().resolve() / "works"
        path = (works_root / slug).resolve()
        try:
            path.relative_to(works_root)
        except ValueError as exc:
            raise ValueError("character workspace escaped works/") from exc
        if path == works_root:
            raise ValueError("character workspace escaped works/")
        return path
    
    
    def write_character_manifest(work: Path, name: str) -> dict:
        work.mkdir(parents=True, exist_ok=True)
        path = work / "character.json"
        if path.is_file():
            try:
                existing = json.loads(path.read_text(encoding="utf-8"))
            except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
                raise ValueError(f"existing character manifest is invalid: {path}") from exc
            if not isinstance(existing, dict):
                raise ValueError(f"existing character manifest must be a JSON object: {path}")
            expected_slug = character_slug(name)
            existing_slug = existing.get("slug")
            if existing_slug is not None and existing_slug != expected_slug:
                raise ValueError(
                    f"existing character manifest belongs to slug {existing_slug!r}, not {expected_slug!r}"
                )
            # Personal-IP handoffs carry identity, anchor, style, and reaction data
            # here.  Re-initializing a workflow must never erase that source of truth.
            return existing
        record = {"name": unicodedata.normalize("NFC", name).strip(), "slug": character_slug(name)}
        path.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        return record
    
    
    def main() -> int:
        parser = argparse.ArgumentParser()
        parser.add_argument("--name", required=True)
        parser.add_argument("--skill-root", type=Path, default=Path(__file__).resolve().parents[1])
        args = parser.parse_args()
        skill_root = args.skill_root.expanduser().resolve()
        work = character_workspace(skill_root, args.name)
        record = write_character_manifest(work, args.name)
        print(json.dumps({"work_dir": str(work), **record}, ensure_ascii=False))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/check_benchmark.py1.6 KB2d2f5b26695fupstream ↗
    #!/usr/bin/env python3
    """Validate the public benchmark case contract without running paid routes."""
    
    from __future__ import annotations
    
    import json
    from pathlib import Path
    
    
    ROOT = Path(__file__).resolve().parents[1]
    REQUIRED_IDS = {
        "hair", "green-garment", "white-garment", "transparent-decor", "cross-cell",
        "12-cell-layout", "independent-stickers", "long-bad-frame", "provider-interruption",
    }
    VALID_STATUSES = {"fixture-covered", "real-run-required"}
    
    
    def validate(path: Path = ROOT / "benchmarks" / "cases.json") -> dict:
        value = json.loads(path.read_text(encoding="utf-8"))
        cases = value.get("cases") if isinstance(value, dict) else None
        if value.get("version") != 1 or not isinstance(cases, list):
            raise ValueError("benchmark cases must be a version 1 object with a cases array")
        ids = {case.get("id") for case in cases if isinstance(case, dict)}
        if ids != REQUIRED_IDS:
            raise ValueError(f"benchmark cases must cover exactly {sorted(REQUIRED_IDS)}")
        for case in cases:
            if not isinstance(case, dict) or case.get("status") not in VALID_STATUSES:
                raise ValueError("each benchmark case needs a valid status")
            if not isinstance(case.get("route"), str) or not isinstance(case.get("acceptance"), list) or not case["acceptance"]:
                raise ValueError(f"benchmark case {case.get('id')!r} is missing route or acceptance criteria")
        return {"valid": True, "cases": len(cases), "real_run_required": sum(case["status"] == "real-run-required" for case in cases)}
    
    
    if __name__ == "__main__":
        print(json.dumps(validate(), ensure_ascii=False))
    
  • scripts/check_repository_policy.py2.5 KB48e7931ac1cdupstream ↗
    #!/usr/bin/env python3
    """Fail CI when public trust-surface and repository-size policies regress."""
    
    from __future__ import annotations
    
    import subprocess
    from pathlib import Path
    
    
    ROOT = Path(__file__).resolve().parents[1]
    README_MIN = 150
    README_MAX = 220
    MAX_TRACKED_MEDIA_BYTES = 12 * 1024 * 1024
    FORBIDDEN_PREFIXES = ("examples/", "promo-v020/", "works/")
    MEDIA_SUFFIXES = {".png", ".gif", ".webp", ".mp4", ".mov", ".zip", ".wav", ".mp3"}
    
    
    def tracked_files() -> list[Path]:
        completed = subprocess.run(
            ["git", "ls-files", "-z"],
            cwd=ROOT,
            check=True,
            capture_output=True,
        )
        return [Path(item.decode("utf-8")) for item in completed.stdout.split(b"\0") if item]
    
    
    def main() -> int:
        errors = []
        for name in ("README.md", "README.en.md"):
            lines = len((ROOT / name).read_text(encoding="utf-8").splitlines())
            if not README_MIN <= lines <= README_MAX:
                errors.append(f"{name} must contain {README_MIN}-{README_MAX} lines; got {lines}")
        readme = (ROOT / "README.md").read_text(encoding="utf-8")
        if "actions/workflows/ci.yml/badge.svg" not in readme:
            errors.append("README.md is missing the main CI status badge")
        tracked = tracked_files()
        forbidden = [str(path) for path in tracked if str(path).startswith(FORBIDDEN_PREFIXES)]
        if forbidden:
            errors.append(f"generated/legacy media directories are tracked: {forbidden[:8]}")
        release_only_gallery_media = [
            str(path)
            for path in tracked
            if len(path.parts) == 4
            and path.parts[:2] == ("gallery", "styles")
            and path.name in {"motion.webp"}
        ]
        if release_only_gallery_media:
            errors.append(f"release-only gallery media must not be tracked: {release_only_gallery_media[:8]}")
        media = [path for path in tracked if path.suffix.lower() in MEDIA_SUFFIXES]
        media_bytes = sum((ROOT / path).stat().st_size for path in media if (ROOT / path).is_file())
        if media_bytes > MAX_TRACKED_MEDIA_BYTES:
            errors.append(
                f"tracked compact media exceeds {MAX_TRACKED_MEDIA_BYTES} bytes: {media_bytes}"
            )
        if not (ROOT / ".github" / "workflows" / "release.yml").is_file():
            errors.append("release workflow gate is missing")
        if errors:
            raise SystemExit("\n".join(errors))
        print(
            f"repository policy ok: {len(media)} compact media files, "
            f"{media_bytes} bytes, README bounds enforced"
        )
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/compile_keypose_plan.py15 KB9cc97c681ef3upstream ↗
    #!/usr/bin/env python3
    """Compile an auditable per-sticker key-pose generation plan.
    
    The plan is deliberately separate from rendering: image generation can happen
    in any approved tool, while this script records the exact source cells,
    motion intent, and the four-pose contract consumed by ``prepare_keyposes.py``.
    """
    
    from __future__ import annotations
    
    import argparse
    import json
    import re
    from pathlib import Path
    
    from artifact_manifest import record_artifact
    from manage_job_state import read_state, verify_state
    from output_safety import begin_output_transaction
    
    
    def natural_key(path: Path) -> list[tuple[int, object]]:
        return [(0, int(part)) if part.isdigit() else (1, part.casefold()) for part in re.split(r"(\d+)", path.name) if part]
    
    
    def sha256_file(path: Path) -> str:
        import hashlib
    
        digest = hashlib.sha256()
        with path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()
    
    
    def parse_reactions(value: str) -> list[str]:
        """Accept a JSON/list file, newline-delimited text, or a compact CSV."""
        candidate = Path(value).expanduser()
        if candidate.is_file():
            payload = json.loads(candidate.read_text(encoding="utf-8"))
            if isinstance(payload, dict):
                payload = payload.get("reactions") or payload.get("expressions")
            if not isinstance(payload, list):
                raise ValueError("reaction file must contain a JSON array or a reactions array")
            values = payload
        else:
            values = re.split(r"\s*[,|]\s*|\s*\n\s*", value.strip())
        reactions = [str(item).strip() for item in values if str(item).strip()]
        if not reactions:
            raise ValueError("at least one reaction is required")
        if any(len(item) > 100 for item in reactions):
            raise ValueError("each reaction must be at most 100 characters")
        return reactions
    
    
    def load_motions(path: Path | None, count: int) -> list[str] | None:
        if path is None:
            return None
        payload = json.loads(path.read_text(encoding="utf-8"))
        if isinstance(payload, dict):
            payload = payload.get("motions") or payload.get("tiles")
        if isinstance(payload, list) and payload and isinstance(payload[0], dict):
            payload = [item.get("motion") for item in payload]
        if not isinstance(payload, list) or len(payload) != count:
            raise ValueError(f"motion file must contain exactly {count} items")
        motions = [str(item).strip() for item in payload]
        if any(not item or len(item) > 200 for item in motions):
            raise ValueError("each motion must be 1-200 characters")
        return motions
    
    
    def suggested_motion(reaction: str) -> str:
        lowered = reaction.casefold()
        rules = [
            (("喜欢你", "喜欢", "爱你"), "抱住现有红心,轻轻眨眼并向观众靠近一点,再回到起始姿势"),
            (("委屈", "哭", "伤心", "泪"), "先抿嘴并让耳朵下垂,眨眼让一滴泪滑落形成清晰峰值,再恢复"),
            (("真的假的", "惊", "震惊", "疑惑"), "先抬眉睁大眼,再让头部轻微后仰形成疑惑峰值,随后回正"),
            (("亲亲", "飞吻", "亲"), "保持现有嘟嘴,手掌向前做一次小幅飞吻,随后收回"),
            (("谢谢", "感谢"), "双手合十并轻轻鞠躬一次,金色光点短暂闪亮后恢复"),
            (("加油", "打气"), "保持现有握拳姿势,拳头小幅上提并让耳朵竖起,再恢复"),
            (("点赞", "赞"), "保持现有竖起拇指,拇指小幅上提并让眼睛变亮,再恢复"),
            (("哭", "😭", "伤心"), "收紧眼睛和嘴角形成更明显的哭泣峰值,再恢复"),
            (("笑", "开心", "😄", "😂"), "先轻微吸气,再让笑脸和脸颊形成清晰峰值,回到原表情"),
            (("庆祝", "🎉", "胜利"), "手臂先收拢蓄力,再抬到庆祝峰值,随后放松"),
            (("惊", "😱", "🤯", "震惊"), "身体和眉眼小幅后缩形成惊讶峰值,再回到起始姿势"),
            (("睡", "😴", "困"), "眼皮和头部缓慢下沉到打盹峰值,再抬回起始姿势"),
        ]
        for tokens, motion in rules:
            if any(token.casefold() in lowered for token in tokens):
                return motion
        return "依据该格现有表情和身体结构做一个小幅、可读的原地动作,随后回到起始姿势"
    
    
    def build_prompt(index: int, reaction: str, motion: str) -> str:
        return f"""使用附带的第 {index:02d} 格贴纸作为唯一角色和风格参考,反应主题为“{reaction}”。意图动作:{motion}。
    
    输出一个固定镜头、固定角色比例的 2 列 × 2 行姿势页,四个象限按左上、右上、左下、右下依次对应 START、ANTICIPATION、ACTION PEAK、RECOVERY。保留角色身份、五官、服装、颜色、材质、已有道具和可见文字;不要凭反应词新增道具、人物、肢体、场景或字幕。角色中心和脚底基线固定,动作必须来自真实的面部或关节姿势变化,禁止整层平移、旋转、缩放、弹跳或摇摆。
    
    文字硬约束:画面内禁止出现任何姿势标签、象限标签、说明文字、英文、数字或新的中文文字;禁止渲染 “START”、 “ANTICIPATION”、 “ACTION PEAK”、 “RECOVERY” 及其中文翻译。只保留参考贴纸中已经存在的反应字样,且不得改写、复制或移动它们。四个象限只放姿势本身,不要在象限顶部或底部添加标题。
    
    四格之间使用连续、均匀、不透明的纯绿色 #00FF00,横向和纵向中心安全沟各至少占画布的 10%,每格主体与本格道具的整体前景包围盒目标约占所在格 70%–75%。禁止棋盘格、渐变、纹理、阴影、描边和发光。每格主体留出安全边距,不得越过格子边界。只输出没有任何标签的 2×2 PNG 姿势页;本地流程会把纯色背景转换为真实 Alpha。"""
    
    
    def main() -> int:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--input-dir", type=Path, required=True, help="numbered source cells, e.g. 01.png … NN.png")
        parser.add_argument("--output-dir", type=Path, required=True)
        parser.add_argument("--reactions", required=True, help="reaction list, text file, or JSON array file")
        parser.add_argument("--motions-file", type=Path)
        parser.add_argument("--image", type=Path, help="approved static sheet used as the keypose anchor")
        parser.add_argument("--layout", type=Path, help="detected layout for the approved static sheet")
        parser.add_argument("--state", type=Path, help="hash-bound approved job state")
        parser.add_argument("--source-report", type=Path, help="approved-static-cells report produced from the approved sheet")
        parser.add_argument("--manifest", type=Path, help="artifact-manifest.json for hash lineage")
        parser.add_argument("--workspace", type=Path, help="manifest workspace; defaults to the manifest parent")
        parser.add_argument("--overwrite", action="store_true")
        args = parser.parse_args()
    
        approval_inputs = (args.image, args.layout, args.state)
        if any(value is not None for value in approval_inputs) and not all(value is not None for value in approval_inputs):
            raise ValueError("image, layout, and state must be supplied together")
        if args.manifest and not all(value is not None for value in approval_inputs):
            raise ValueError("an audited keypose plan requires --image, --layout, and --state")
        if args.manifest and args.source_report is None:
            raise ValueError("an audited keypose plan requires --source-report from the approved static sheet")
        approval = None
        if all(value is not None for value in approval_inputs):
            image = args.image.expanduser().resolve()
            layout = args.layout.expanduser().resolve()
            state = args.state.expanduser().resolve()
            verify_state(read_state(state), image, layout)
            approval = {
                "image": str(image),
                "image_sha256": sha256_file(image),
                "layout": str(layout),
                "layout_sha256": sha256_file(layout),
                "state": str(state),
                "state_sha256": sha256_file(state),
            }
    
        source_dir = args.input_dir.expanduser().resolve()
        if not source_dir.is_dir():
            raise ValueError("input-dir must be a directory")
        sources = sorted((path for path in source_dir.iterdir() if path.is_file() and path.suffix.lower() == ".png"), key=natural_key)
        if not 1 <= len(sources) <= 48:
            raise ValueError("input-dir must contain between 1 and 48 PNG cells")
        reactions = parse_reactions(args.reactions)
        if len(reactions) != len(sources):
            raise ValueError(f"reaction count {len(reactions)} does not match source cell count {len(sources)}")
        source_report = None
        if args.source_report:
            source_report_path = args.source_report.expanduser().resolve(strict=True)
            source_report = json.loads(source_report_path.read_text(encoding="utf-8"))
            if not isinstance(source_report, dict) or source_report.get("version") != 1 or source_report.get("mode") != "approved-static-cells":
                raise ValueError("source-report must be a version 1 approved-static-cells report")
            if source_report.get("count") is not None and int(source_report["count"]) != len(sources):
                raise ValueError("source-report count does not match source cells")
            if approval is not None:
                for key, expected in (
                    ("source_image_sha256", approval["image_sha256"]),
                    ("layout_sha256", approval["layout_sha256"]),
                    ("state_sha256", approval["state_sha256"]),
                ):
                    if source_report.get(key) != expected:
                        raise ValueError("source-report is not derived from the approved static revision")
            report_cells = source_report.get("cells")
            if not isinstance(report_cells, list) or [Path(str(item.get("path"))).name for item in report_cells] != [path.name for path in sources]:
                raise ValueError("source-report cells do not match the source directory")
            for source, report_cell in zip(sources, report_cells):
                if report_cell.get("sha256") != sha256_file(source):
                    raise ValueError(f"source cell {source.name} does not match the approved-static-cells report")
        motions = load_motions(args.motions_file, len(sources))
        protected = [source_dir]
        if args.motions_file:
            protected.append(args.motions_file.expanduser().resolve())
        if args.manifest:
            protected.append(args.manifest.expanduser().resolve())
        protected.extend(path.expanduser().resolve() for path in approval_inputs if path is not None)
        transaction = begin_output_transaction(args.output_dir, overwrite=args.overwrite, protected_paths=protected)
        output = transaction.output
        prompts_dir = output / "prompts"
        prompts_dir.mkdir(parents=True, exist_ok=True)
        digits = max(2, len(str(len(sources))))
        tiles = []
        for index, (source, reaction) in enumerate(zip(sources, reactions), start=1):
            motion = motions[index - 1] if motions else suggested_motion(reaction)
            prompt_path = prompts_dir / f"{index:0{digits}d}.txt"
            prompt_path.write_text(build_prompt(index, reaction, motion) + "\n", encoding="utf-8")
            tiles.append({
                "id": f"{index:0{digits}d}",
                "reaction": reaction,
                "source_cell": str(source),
                "source_sha256": sha256_file(source),
                "motion": motion,
                "prompt": str(prompt_path.relative_to(output)),
                "expected_pose_sheet": f"{index:0{digits}d}.png",
                "layout": {"columns": 2, "rows": 2, "count": 4},
                "poses": ["start", "anticipation", "peak", "recovery"],
            })
        plan = {
            "version": 1,
            "mode": "keypose-local",
            "source_count": len(sources),
            "pose_count_per_sticker": 4,
            "motion_source": "vision-reviewed-overrides" if motions else "reaction-semantic-suggestion-requires-visual-review",
            "approval": approval,
            "source_cells_report": str(args.source_report.expanduser().resolve()) if args.source_report else None,
            "tiles": tiles,
            "pose_sheet_text_policy": "preserve-approved-text-only; forbid-pose-labels-and-new-text",
            "forbidden_fallbacks": ["whole-layer-translation", "whole-layer-rotation", "whole-layer-scale", "bounce", "shake", "sway"],
        }
        (output / "keypose-plan.json").write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        transaction.commit()
        manifest_result = None
        if args.manifest:
            manifest = args.manifest.expanduser().resolve()
            workspace = args.workspace.expanduser().resolve() if args.workspace else manifest.parent
            approval_ids = []
            if approval is not None:
                approval_ids = [
                    record_artifact(manifest, path, kind=kind, stage="keypose-planned", workspace=workspace)
                    for path, kind in (
                        (args.image, "static-sheet"),
                        (args.layout, "layout"),
                        (args.state, "approval-state"),
                    )
                ]
            source_report_ids = []
            if args.source_report:
                source_report_ids = [
                    record_artifact(
                        manifest,
                        args.source_report.expanduser().resolve(),
                        kind="approved-static-cells-report",
                        stage="keypose-planned",
                        dependencies=approval_ids,
                        workspace=workspace,
                    )
                ]
            source_ids = [
                record_artifact(
                    manifest,
                    source,
                    kind="keypose-source-cell",
                    stage="keypose-planned",
                    dependencies=[*approval_ids, *source_report_ids],
                    workspace=workspace,
                )
                for source in sources
            ]
            prompt_ids = [
                record_artifact(
                    manifest,
                    prompts_dir / f"{index:0{digits}d}.txt",
                    kind="keypose-prompt",
                    stage="keypose-planned",
                    dependencies=[source_ids[index - 1]],
                )
                for index in range(1, len(sources) + 1)
            ]
            plan_id = record_artifact(
                manifest,
                output / "keypose-plan.json",
                kind="keypose-plan",
                stage="keypose-planned",
                dependencies=[*source_ids, *prompt_ids],
            )
            manifest_result = {"path": str(manifest), "plan_artifact_id": plan_id}
        print(json.dumps({"plan": str((output / 'keypose-plan.json').resolve()), "count": len(sources), "artifact_manifest": manifest_result}, ensure_ascii=False))
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/compile_static_prompt.py28 KB0111b76b2bd9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/config_contract.py24 KB02cb17964e6eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/execute_video_route.py24 KBc335b4c76634upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/generate_promo_bgm.py4.7 KBf68a60bcbd52upstream ↗
    #!/usr/bin/env python3
    """Generate a small, license-free playful bed for the promo composition."""
    
    from __future__ import annotations
    
    import argparse
    import wave
    from pathlib import Path
    
    import numpy as np
    
    
    SR = 48_000
    BPM = 120
    BEAT = 60.0 / BPM
    
    
    def env(length: int, attack: float, release: float) -> np.ndarray:
        out = np.ones(length, dtype=np.float64)
        a = min(length, max(1, int(attack * SR)))
        r = min(length, max(1, int(release * SR)))
        out[:a] = np.linspace(0.0, 1.0, a, endpoint=False)
        out[-r:] *= np.linspace(1.0, 0.0, r, endpoint=False)
        return out
    
    
    def add_tone(track: np.ndarray, start: float, duration: float, freq: float, amp: float, kind: str = "sine") -> None:
        first = max(0, int(start * SR))
        last = min(len(track), int((start + duration) * SR))
        if last <= first:
            return
        t = np.arange(last - first, dtype=np.float64) / SR
        phase = 2.0 * np.pi * freq * t
        if kind == "triangle":
            wave_data = 2.0 * np.abs(2.0 * ((freq * t) % 1.0) - 1.0) - 1.0
        else:
            wave_data = np.sin(phase)
        track[first:last] += amp * wave_data * env(last - first, 0.012, min(0.18, duration * 0.4))
    
    
    def add_noise(track: np.ndarray, start: float, duration: float, amp: float) -> None:
        first = max(0, int(start * SR))
        last = min(len(track), int((start + duration) * SR))
        if last <= first:
            return
        rng = np.random.default_rng(7)
        noise = rng.standard_normal(last - first)
        track[first:last] += amp * noise * env(last - first, 0.002, min(0.08, duration * 0.7))
    
    
    def build(duration: float) -> np.ndarray:
        n = int(duration * SR)
        track = np.zeros(n, dtype=np.float64)
        roots = [261.63, 196.00, 220.00, 174.61]  # C, G, Am, F
        thirds = [329.63, 246.94, 261.63, 220.00]
        fifths = [392.00, 293.66, 329.63, 261.63]
        arp_offsets = [0, 1, 2, 1, 3, 2, 1, 0]
        melody = [
            392.00, 440.00, 523.25, 440.00, 392.00, 329.63, 392.00, 0.0,
            392.00, 440.00, 587.33, 523.25, 440.00, 392.00, 329.63, 0.0,
        ]
    
        bars = int(np.ceil(duration / (BEAT * 4)))
        for bar in range(bars):
            bar_start = bar * BEAT * 4
            chord = bar % 4
            root = roots[chord]
    
            # Quiet pad: enough harmonic motion to make the cut feel intentional.
            for note, level in ((root, 0.035), (thirds[chord], 0.022), (fifths[chord], 0.018)):
                add_tone(track, bar_start, BEAT * 4, note, level, "sine")
    
            # Bouncy bass and a small arpeggio pattern.
            for beat in range(4):
                add_tone(track, bar_start + beat * BEAT, 0.28, root / 2, 0.085, "triangle")
            chord_notes = [root, thirds[chord], fifths[chord], root * 2]
            for step, offset in enumerate(arp_offsets):
                add_tone(track, bar_start + step * BEAT / 2, 0.16, chord_notes[offset], 0.032, "triangle")
    
            # Soft rhythm: kick, clap and hats, kept deliberately behind the visuals.
            for beat in range(4):
                beat_start = bar_start + beat * BEAT
                add_tone(track, beat_start, 0.12, 95.0, 0.055, "sine")
                add_noise(track, beat_start + BEAT / 2, 0.065, 0.016)
            for eighth in range(8):
                add_noise(track, bar_start + eighth * BEAT / 2 + 0.04, 0.018, 0.007)
    
            # A simple, sparse top line leaves the text readable.
            for step in range(8):
                note = melody[(bar * 2 + step) % len(melody)]
                if note:
                    add_tone(track, bar_start + step * BEAT / 2, 0.18, note, 0.026, "sine")
    
        # Tiny chimes at the five gallery hand-offs add a sense of response.
        for start, base in zip((12.0, 18.0, 24.0, 30.0, 36.0), (523.25, 587.33, 659.25, 783.99, 880.0)):
            add_tone(track, start, 0.28, base, 0.095, "sine")
            add_tone(track, start + 0.14, 0.38, base * 1.25, 0.045, "sine")
    
        fade_in = min(n, int(0.8 * SR))
        fade_out = min(n, int(1.0 * SR))
        track[:fade_in] *= np.linspace(0.0, 1.0, fade_in, endpoint=False)
        track[-fade_out:] *= np.linspace(1.0, 0.0, fade_out, endpoint=False)
        peak = float(np.max(np.abs(track))) or 1.0
        return (track / peak * 0.82).astype(np.float32)
    
    
    def main() -> None:
        parser = argparse.ArgumentParser()
        parser.add_argument("--output", required=True)
        parser.add_argument("--duration", type=float, default=42.0)
        args = parser.parse_args()
        output = Path(args.output)
        output.parent.mkdir(parents=True, exist_ok=True)
        mono = build(args.duration)
        stereo = np.column_stack((mono, np.roll(mono, int(0.006 * SR))))
        stereo[0, 1] = 0.0
        pcm = np.clip(stereo * 32767.0, -32768, 32767).astype(np.int16)
        with wave.open(str(output), "wb") as handle:
            handle.setnchannels(2)
            handle.setsampwidth(2)
            handle.setframerate(SR)
            handle.writeframes(pcm.tobytes())
    
    
    if __name__ == "__main__":
        main()
    
  • scripts/grok_build_video_adapter.py18 KB0e07f7916d00upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/import_personal_handoff.py19 KB11a9f53f489eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/inspect_sticker_sheet.py9.4 KBcdfe04c83ee4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/interpolate_keypose_frames.py16 KBfd606e6ee15cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/keyframe_fallback.py9.6 KBeb0c01f25c29upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/light_motion_fallback.py198 Bed110bdf7791upstream ↗
    #!/usr/bin/env python3
    """Compatibility-friendly entry point for zero-generation-cost light motion."""
    
    from keyframe_fallback import main
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
    
  • scripts/local_upload_receiver.py5.7 KB3cd4bfe4862eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/manage_job_state.py9.1 KB01aa545c9770upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/normalize_static_sheet.py15 KB7cc663b458a1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/output_profile.py142 B40f0799bdbdbupstream ↗
    """Canonical media defaults shared by every local sticker route."""
    
    DEFAULT_OUTPUT_SIZE = 240
    DEFAULT_OUTPUT_FPS = 8
    MAX_OUTPUT_SIZE = 2048
    
    
  • scripts/output_safety.py11 KB85f0896c8098upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/prepare_image_gen_call.py9.6 KB66279f85e8f2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/prepare_keyposes.py15 KB0bc78a26fda4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/prepare_webp_frames.py2.3 KBc5073117baa7upstream ↗
    #!/usr/bin/env python3
    """Decode animated WebP stickers with Pillow and flatten alpha onto an X-safe background."""
    
    from __future__ import annotations
    
    import argparse
    import re
    from pathlib import Path
    
    from PIL import Image, ImageOps
    
    
    GROUPS = ("black-cat", "child", "gold-dress-girl", "musk-3d", "trump")
    BACKGROUND = (18, 19, 22)  # #121316, matching the X-ready MP4 treatment
    CANVAS_SIZE = (512, 512)
    ART_SIZE = (420, 420)
    
    
    def numeric_key(path: Path) -> tuple[int, str]:
        match = re.match(r"(\d+)", path.stem)
        return (int(match.group(1)) if match else 999, path.name)
    
    
    def flatten_frame(frame: Image.Image) -> Image.Image:
        rgba = frame.convert("RGBA")
        fitted = ImageOps.contain(rgba, ART_SIZE, method=Image.Resampling.LANCZOS)
        canvas = Image.new("RGB", CANVAS_SIZE, BACKGROUND)
        x = (CANVAS_SIZE[0] - fitted.width) // 2
        y = (CANVAS_SIZE[1] - fitted.height) // 2
        canvas.paste(fitted.convert("RGB"), (x, y), fitted.getchannel("A"))
        return canvas
    
    
    def main() -> None:
        parser = argparse.ArgumentParser()
        parser.add_argument("--source-root", type=Path, required=True)
        parser.add_argument("--frames-root", type=Path, required=True)
        args = parser.parse_args()
    
        total = 0
        for group in GROUPS:
            sources = sorted((args.source_root / group).glob("*.webp"), key=numeric_key)
            if not sources:
                raise SystemExit(f"No WebP files found for {group}")
    
            for index, source in enumerate(sources, start=1):
                output_dir = args.frames_root / group / f"{index:02d}"
                output_dir.mkdir(parents=True, exist_ok=True)
                with Image.open(source) as animated:
                    frame_count = getattr(animated, "n_frames", 1)
                    if frame_count < 2:
                        print(f"{group}/{index:02d}: 1 frame (static source)")
                    for frame_index in range(frame_count):
                        animated.seek(frame_index)
                        flatten_frame(animated).save(
                            output_dir / f"frame-{frame_index:03d}.png",
                            format="PNG",
                        )
                    print(f"{group}/{index:02d}: {frame_count} frames from {source.name}")
                    total += 1
    
        print(f"Prepared {total} sticker sources in {args.frames_root}")
    
    
    if __name__ == "__main__":
        main()
    
  • scripts/prepare_workflow.py16 KB3504c713cf93upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/probe_video_capabilities.py9.4 KB3cfd76743a27upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/process_emoji_grid.py82 KB1d0cd67b804dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/process_independent_stickers.py7.4 KB34fb2d227317upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/prompt_compiler.py8.9 KB758baad18438upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/render_keypose_pack.py16 KB5b09e7c0303aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/route_video_provider.py14 KBb7574d2df105upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/screen_selector.py4.1 KB7b95a910bc35upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/split_approved_static.py4.4 KB3e092e742029upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/static_generation_guard.py9.5 KB401400946146upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/sticker_production_config.py12 KBf8629de9cfa0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/style_selector.py12 KBcaa480217de4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/video_adapter_common.py5.9 KBa4209f8c1539upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/video_background_qc.py24 KB57c7b1a2aefdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/video_gateway.mjs21 KBcf03899ec34fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/xai_rest_video_adapter.py14 KB816f766ec4c2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/artifact-manifest.schema.json1.4 KBd92d2c28de43upstream ↗
    {
      "$schema": "https://json-schema.org/draft/2020-12/schema",
      "$id": "https://local.invalid/motion-sticker-pack/artifact-manifest.schema.json",
      "title": "Motion Sticker Pack artifact lineage manifest",
      "type": "object",
      "additionalProperties": false,
      "required": ["version", "workspace", "created_at", "updated_at", "artifacts"],
      "properties": {
        "version": {"const": 1},
        "workspace": {"type": "string", "minLength": 1},
        "created_at": {"type": "string"},
        "updated_at": {"type": "string"},
        "artifacts": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "required": ["id", "path", "sha256", "bytes", "kind", "stage", "dependencies", "recorded_at", "current"],
            "properties": {
              "id": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}:.+$"},
              "path": {"type": "string", "minLength": 1},
              "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
              "bytes": {"type": "integer", "minimum": 0},
              "kind": {"type": "string", "minLength": 1},
              "stage": {"type": "string", "minLength": 1},
              "dependencies": {"type": "array", "items": {"type": "string"}, "uniqueItems": true},
              "recorded_at": {"type": "string"},
              "reactivated_at": {"type": "string"},
              "retired_at": {"type": "string"},
              "current": {"type": "boolean"}
            }
          }
        }
      }
    }
    
  • references/attempt-ledger.schema.json3.2 KB828e2e0ce2a1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/intake-and-approval.md10 KBa1b453d6a342upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/keypose-workflow.md4.5 KB222eec019914upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/output-contract.md11 KB43e07bca836fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/personal-ip-handoff.md4.6 KBc9daae0ad59cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/prompt-contract.md8.1 KB8cc8eb9b6a77upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/prompt-optimization.md1.8 KB827929c23d81upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/runtime-routing.md12 KB038b80b7cd08upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/sticker-production.schema.json4.8 KBe48bbce52d85upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/style-presets.json14 KB59ab320603f4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/video-providers.schema.json2.8 KB421e63073ffbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • references/video-task.schema.json4.1 KBb1e9a0e425f1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • assets/sticker-production.default.json1.9 KB32e79c0fe352upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • assets/tile-plan.example.json1.0 KBc6abb6b0f194upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • assets/tool-manifest.example.json376 B8a8a4c71ed0dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • assets/video-providers.example.json4.0 KBe47e409ebfc0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • assets/video-task.example.json1.4 KB0fbccca5d018upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/workflows/ci.yml1.6 KBf140d6d87d78upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/workflows/release.yml3.6 KB30ae809cb0a0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .gitignore1.1 KB9e7f5f607511upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .playwright-cli/console-2026-08-28T12-12-00-104Z.log125 Bd3eca5da0881upstream ↗
    [     659ms] [ERROR] Failed to load resource: the server responded with a status of 403 () @ chrome-error://chromewebdata/:0
    
  • .playwright-cli/console-2026-08-28T12-12-07-255Z.log136 B6b588043aad6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .playwright-cli/console-2026-08-28T12-16-25-107Z.log143 B8ab218da45daupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .playwright-cli/page-2026-08-28T12-12-08-539Z.yml0 Be69de29bb2d1upstream ↗
  • .playwright-cli/page-2026-08-28T12-16-25-545Z.yml3.3 KB8a093009c8a3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • agents/openai.yaml396 B0349b42299a6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • benchmarks/cases.json1.8 KBca4a70a8f4b9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • CONTRIBUTING.md714 B139c10876ff0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/advanced/cli-reference.md6.1 KBb4a312145e1eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/advanced/providers-and-zdr.md3.2 KBa6951cdef1faupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/advanced/repository-maintenance.md3.1 KB93425761afa6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/advanced/routing-and-audit.md2.7 KB7fb628017396upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/advanced/style-library.md5.3 KB5a46513e5996upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/adversarial-audit.md5.3 KBc69f20c21b92upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-01.gif428 KB915d4ef7d469upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-02.gif432 KBbfb05407e47dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-03.gif493 KBdfd1d293744fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-04.gif421 KB4886e2c98c12upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-05.gif480 KB12301cc652d2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-06.gif475 KB0591648cdebbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-07.gif449 KB2a804c9cc08eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-08.gif399 KBbc6d9453ea42upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/fox-09.gif440 KB1b570538dda8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/recent-sticker-pack/manifest.json1.4 KBea85d40639faupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/01-3d.png76 KB552494782b00upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/02-realistic.png89 KB2f3c0f377b8aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/03-hand-drawn.png119 KB769dd0a6fe25upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/04-chibi.png81 KB76eabd1d31a7upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/05-manga.png129 KB29d6f574d8aaupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/06-pixel-art.png55 KBd14ec8592705upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/07-cute.png84 KBfd5cc895da67upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/08-caricature-3d.png80 KB8af5f4ae2c6aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/09-fashion-realistic.png84 KBe8add29cc753upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/10-mascot-toy.png68 KB048d72c55bc4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/11-clay-cute.png85 KBb63311b0917eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/12-fantasy-plush.png98 KB73382face8ffupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/13-kawaii-anime.png73 KB5db5154a18c7upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/14-retro-halftone.png91 KBf8feac2c6f7bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/15-ink-wash-meme.png85 KB7dff137d4224upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/16-emoji-hybrid.png73 KBf25d221d3b72upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/assets/style-exploration/fox/manifest.json1.8 KB0d387e27d4aeupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/index.json1.5 KB880eb310887aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/release-manifest.json8.8 KBad28e3bfbc87upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/caricature-3d/layout.json201 Be9e480af95bcupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/caricature-3d/motion.gif546 KBc93e9ba34f17upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/caricature-3d/processing.json4.9 KB35d6e08cc91fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/caricature-3d/provenance.json3.1 KB37a2225b932dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/caricature-3d/route.json2.6 KB58efd1ad97d3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/caricature-3d/static.png51 KBd2c1acd19de2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/cinematic-realistic/layout.json236 Be1afa0652118upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/cinematic-realistic/motion.gif383 KB269dcedf503dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/cinematic-realistic/processing.json23 KBcc40a44b7060upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/cinematic-realistic/provenance.json2.2 KBc3c33d8ea2a4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/cinematic-realistic/route.json1.9 KB1fe2e22de441upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/cinematic-realistic/static.png46 KB66cdca08652bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/clay-cute/layout.json204 Bcdac86cde9e5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/clay-cute/motion.gif327 KB50d5477d5918upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/clay-cute/processing.json23 KB608227e17b7cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/clay-cute/provenance.json2.1 KBa63787ee3fbeupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/clay-cute/route.json2.1 KBb516e4d4b2f1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/clay-cute/static.png66 KB42b9ebad93e0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fantasy-plush/layout.json204 Bf74f9940e3f3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fantasy-plush/motion.gif326 KB7a366155deb4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fantasy-plush/processing.json35 KBd783727cf429upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fantasy-plush/provenance.json2.2 KB6e77ff884da8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fantasy-plush/route.json1.9 KB33ce7e78bf68upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fantasy-plush/static.png30 KB439d700f890aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fashion-realistic/layout.json188 Ba203abe3d3bfupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fashion-realistic/motion.gif600 KB2fcb759a7abbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fashion-realistic/processing.json3.7 KBbc1eebdba838upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fashion-realistic/provenance.json2.5 KB14520312c8f9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fashion-realistic/route.json2.4 KBe28a8f157a18upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/fashion-realistic/static.png42 KB8db4126bb16eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/hand-drawn/layout.json207 Beccc65596b5bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/hand-drawn/motion.gif369 KB6bcfe5886b34upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/hand-drawn/processing.json23 KBe8fa9a6d7c61upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/hand-drawn/provenance.json2.1 KBf7f7447a7244upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/hand-drawn/route.json2.1 KBfee2b93330f0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/hand-drawn/static.png87 KBdc8ef94f5e0dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/iridescent-chibi/layout.json207 B7cc2003f0554upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/iridescent-chibi/motion.gif333 KBa5ffeba36ff5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/iridescent-chibi/processing.json23 KB735f314f77e8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/iridescent-chibi/provenance.json2.2 KBdba9261e505fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/iridescent-chibi/route.json2.1 KB85da0ea53f2cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/iridescent-chibi/static.png56 KB70a226022e7aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/kawaii-anime/layout.json207 Ba4d658d17df9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/kawaii-anime/motion.gif224 KBdc1d8cf4d09fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/kawaii-anime/processing.json21 KBeff7b7d11855upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/kawaii-anime/provenance.json2.2 KBdedf7ef08db6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/kawaii-anime/route.json2.0 KB861710392ff5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/kawaii-anime/static.png54 KB0d6939b57091upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/manga-cel/layout.json207 B283d6d7e8381upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/manga-cel/motion.gif440 KB16cf7151b310upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/manga-cel/processing.json23 KB144bb934386cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/manga-cel/provenance.json2.1 KB66df11a66da0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/manga-cel/route.json2.1 KBf8bf3e86ab38upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/manga-cel/static.png98 KB26bcef2fdc94upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/mascot-toy/layout.json201 Bc1a3ddfc34d4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/mascot-toy/motion.gif246 KBdc370fbb8313upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/mascot-toy/processing.json35 KBdedd6b7fea9bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/mascot-toy/provenance.json2.2 KB4b2db2f93334upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/mascot-toy/route.json2.0 KB2d6bdf813f9cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/mascot-toy/static.png26 KB474a2814462dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/pixel-art/layout.json207 B14e342f02394upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/pixel-art/motion.gif307 KBb6c00e24500aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/pixel-art/processing.json23 KB920319ac1c6dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/pixel-art/provenance.json2.1 KBf72509242215upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/pixel-art/route.json2.1 KB9a59ef454910upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/pixel-art/static.png50 KBc1ef25abe4beupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/plush-toy/layout.json223 B740e9573cf6cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/plush-toy/motion.gif423 KBef04a76a42dfupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/plush-toy/processing.json3.9 KB94c567c4badbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/plush-toy/provenance.json2.6 KBc934d0cfa1b5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/plush-toy/route.json2.5 KB61185ab3f0e5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/plush-toy/static.png58 KB14ccb7ca3bb1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/soft-plush/layout.json204 B64d7405d636dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/soft-plush/motion.gif449 KB552fd59a1059upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/soft-plush/processing.json5.1 KB46e23eae288aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/soft-plush/provenance.json2.7 KB70ea794651d6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/soft-plush/route.json1.9 KB498415d2ace0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • gallery/styles/soft-plush/static.png38 KB32cbc6bf6924upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • LICENSE1.0 KBd7e7870d95d3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • package-lock.json7.6 KBa759ac42f16fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • package.json970 B06a98ae23535upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • process_emoji_grid.py413 B1abaf019071eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • README.en.md13 KB166d27e426eaupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • RELEASE_NOTES.md12 KBa0de1a79d3cfupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • requirements.txt62 Bb0e4b9e67b22upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • SECURITY.md1.3 KB94e70ef664f6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests-node/video_gateway.test.mjs15 KB98f017bbee2aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_adversarial_contracts.py50 KBc33d8202d595upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_animation_export.py4.8 KB392fbfc30bf7upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_benchmark_contract.py538 B157030ccd642upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_character_workspace.py4.0 KB8ecd1d451b6cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_documentation.py3.1 KB6365e95854ccupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_gallery_provenance.py1.2 KB04bcc1d5d21dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_grid_detection.py14 KBb5dad8ef4967upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_keyframe_fallback.py1.1 KB180c35ca3ebeupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_keypose_pipeline.py13 KB84d6fd3b7202upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_media_integration.py16 KB7ffde4f17014upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_personal_handoff.py7.4 KB8b15d5143d94upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_prompt_and_router.py11 KBffe5ce696646upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_static_generation_guard.py3.4 KB7e08c976ea4fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_static_prompt.py22 KB3051b01edd5dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_static_sheet_alpha.py5.8 KBdf0221901e76upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_sticker_production_config.py5.5 KB2c308a57c0f5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_style_gallery.py2.5 KB21f386c66e10upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_video_background_qc.py8.3 KBa40c4b60e609upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_workflow_tools.py16 KB002e72e26866upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/kobingogo-motion-sticker-pack.md

// REPO STATS

66 stars
0 open issues
Last commit: 2mo ago