Navigate back to the previous page in browser history. Requires browser_navigate to be called first.

Click on an element identified by its ref ID from the snapshot (e.g., '@e5'). The ref IDs are shown in square brackets in the snapshot output. Requires browser_navigate and browser_snapshot to be called first.

The element reference from the snapshot (e.g., '@e5', '@e12')

Get browser console output and JavaScript errors from the current page. Returns console.log/warn/error/info messages and uncaught JS exceptions. Use this to detect silent JavaScript errors, failed API calls, and application warnings. Requires browser_navigate to be called first. When 'expression' is provided, evaluates JavaScript in the page context and returns the result — use this for DOM inspection, reading page state, or extracting data programmatically.

If true, clear the message buffers after reading

JavaScript expression to evaluate in the page context. Runs in the browser like DevTools console — full access to DOM, window, document. Return values are serialized to JSON. Example: 'document.title' or 'document.querySelectorAll("a").length'

Get a list of all images on the current page with their URLs and alt text. Useful for finding images to analyze with the vision tool. Requires browser_navigate to be called first.

Navigate to a URL in the browser. Initializes the session and loads the page. Must be called before other browser tools. For plain-text endpoints — URLs ending in .md, .txt, .json, .yaml, .yml, .csv, .xml, raw.githubusercontent.com, or any documented API endpoint — prefer curl via the terminal tool or web_extract; the browser stack is overkill and much slower for these. Use browser tools when you need to interact with a page (click, fill forms, dynamic content). Returns a compact page snapshot with interactive elements and ref IDs — no need to call browser_snapshot separately after navigating.

The URL to navigate to (e.g., 'https://example.com')

Press a keyboard key. Useful for submitting forms (Enter), navigating (Tab), or keyboard shortcuts. Requires browser_navigate to be called first.

Key to press (e.g., 'Enter', 'Tab', 'Escape', 'ArrowDown')

Scroll the page in a direction. Use this to reveal more content that may be below or above the current viewport. Requires browser_navigate to be called first.

Direction to scroll

Get a text-based snapshot of the current page's accessibility tree. Returns interactive elements with ref IDs (like @e1, @e2) for browser_click and browser_type. full=false (default): compact view with interactive elements. full=true: complete page content. Snapshots over 8000 chars are truncated or LLM-summarized. Requires browser_navigate first. Note: browser_navigate already returns a compact snapshot — use this to refresh after interactions that change the page, or with full=true for complete content.

If true, returns complete page content. If false (default), returns compact view with interactive elements only.

Type text into an input field identified by its ref ID. Clears the field first, then types the new text. Requires browser_navigate and browser_snapshot to be called first.

The element reference from the snapshot (e.g., '@e3')

The text to type into the field

Take a screenshot of the current page and analyze it with vision AI. Use this when you need to visually understand what's on the page - especially useful for CAPTCHAs, visual verification challenges, complex layouts, or when the text snapshot doesn't capture important visual information. Returns both the AI analysis and a screenshot_path that you can share with the user by including MEDIA:<screenshot_path> in your response. Requires browser_navigate to be called first.

What you want to know about the page visually. Be specific about what you're looking for.

If true, overlay numbered [N] labels on interactive elements. Each [N] maps to ref @eN for subsequent browser commands. Useful for QA and spatial reasoning about page layout.

clarify

Ask the user a question when you need clarification, feedback, or a decision before proceeding. Supports two modes:

1. **Multiple choice** — provide up to 4 choices. The user picks one or types their own answer via a 5th 'Other' option.
2. **Open-ended** — omit choices entirely. The user types a free-form response.

Use this tool when:
- The task is ambiguous and you need the user to choose an approach
- You want post-task feedback ('How did that work out?')
- You want to offer to save a skill or update memory
- A decision has meaningful trade-offs the user should weigh in on

Do NOT use this tool for simple yes/no confirmation of dangerous commands (the terminal tool handles that). Prefer making a reasonable default choice yourself when the decision is low-stakes.

The question to present to the user.

Choices:
Up to 4 answer choices. Omit this parameter entirely to ask an open-ended question. When provided, the UI automatically appends an 'Other (type your answer)' option.

cronjob

Manage scheduled cron jobs with a single compressed tool.

Use action='create' to schedule a new job from a prompt or one or more skills.
Use action='list' to inspect jobs.
Use action='update', 'pause', 'resume', 'remove', or 'run' to manage an existing job.

To stop a job the user no longer wants: first action='list' to find the job_id, then action='remove' with that job_id. Never guess job IDs — always list first.

Jobs run in a fresh session with no current-chat context, so prompts must be self-contained.
If skills are provided on create, the future cron run loads those skills in order, then follows the prompt as the task instruction.
On update, passing skills=[] clears attached skills.

NOTE: The agent's final response is auto-delivered to the target. Put the primary
user-facing content in the final response. Cron jobs run autonomously with no user
present — they cannot ask questions or request clarification.

Important safety rule: cron-run sessions should not recursively schedule more cron jobs.

One of: create, list, update, pause, resume, remove, run

Required for update/pause/resume/remove/run

For create: the full self-contained prompt. If skills are also provided, this becomes the task instruction paired with those skills.

For create/update: '30m', 'every 2h', '0 9 * * *', or ISO timestamp

Optional human-friendly name

Optional repeat count. Omit for defaults (once for one-shot, forever for recurring).

Omit this parameter to auto-deliver back to the current chat and topic (recommended). Auto-detection preserves thread/topic context. Only set explicitly when the user asks to deliver somewhere OTHER than the current conversation. Values: 'origin' (same as omitting), 'local' (no delivery, save only), 'all' (fan out to every connected home channel), or platform:chat_id:thread_id for a specific destination. Combine with comma: 'origin,all' delivers to the origin plus every other connected channel. Examples: 'telegram:-1001234567890:17585', 'discord:#engineering', 'sms:+15551234567', 'all'. WARNING: 'platform:chat_id' without :thread_id loses topic targeting. 'all' resolves at fire time, so a job created before a channel was wired up will pick it up automatically once connected.

Optional ordered list of skill names to load before executing the cron prompt. On update, pass an empty array to clear attached skills.

Optional per-job model override. If provider is omitted, the current main provider is pinned at creation time so the job stays stable.

Provider name (e.g. 'openrouter', 'anthropic', or 'custom:<name>' for a provider defined in custom_providers config — always include the ':<name>' suffix, never pass the bare 'custom'). Omit to use and pin the current provider.

Model name (e.g. 'anthropic/claude-sonnet-4', 'claude-sonnet-4')

Optional path to a script that runs each tick. In the default mode its stdout is injected into the agent's prompt as context (data-collection / change-detection pattern). With no_agent=True, the script IS the job and its stdout is delivered verbatim (classic watchdog pattern). Relative paths resolve under ~/.hermes/scripts/. ``.sh``/``.bash`` extensions run via bash, everything else via Python. On update, pass empty string to clear.

Default: False (LLM-driven job — the agent runs the prompt each tick). Set True to skip the LLM entirely: the scheduler just runs ``script`` on schedule and delivers its stdout verbatim. No tokens, no agent loop, no model override honoured.

REQUIREMENTS when True: ``script`` MUST be set (``prompt`` and ``skills`` are ignored).

DELIVERY SEMANTICS when True: (a) non-empty stdout is sent verbatim as the message; (b) EMPTY stdout means SILENT — nothing is sent to the user and they won't see anything happened, so design your script to stay quiet when there's nothing to report (the watchdog pattern); (c) non-zero exit / timeout sends an error alert so a broken watchdog can't fail silently.

WHEN TO USE True: recurring script-only pings where the script itself produces the exact message text (memory/disk/GPU watchdogs, threshold alerts, heartbeats, CI notifications, API pollers with a fixed output shape). WHEN TO USE False (default): anything that needs reasoning — summarize a feed, draft a daily briefing, pick interesting items, rephrase data for a human, follow conditional logic based on content.

Optional job ID or list of job IDs whose most recent completed output is injected into the prompt as context before each run. Use this to chain cron jobs: job A collects data, job B processes it. Each entry must be a valid job ID (from cronjob action='list'). Note: injects the most recent completed output — does not wait for upstream jobs running in the same tick. On update, pass an empty array to clear.

Optional list of toolset names to restrict the job's agent to (e.g. ["web", "terminal", "file", "delegation"]). When set, only tools from these toolsets are loaded, significantly reducing input token overhead. When omitted, all default tools are loaded. Infer from the job's prompt — e.g. use "web" if it calls web_search, "terminal" if it runs scripts, "file" if it reads files, "delegation" if it calls delegate_task. On update, pass an empty array to clear.

Optional absolute path to run the job from. When set, AGENTS.md / CLAUDE.md / .cursorrules from that directory are injected into the system prompt, and the terminal/file/code_exec tools use it as their working directory — useful for running a job inside a specific project repo. Must be an absolute path that exists. When unset (default), preserves the original behaviour: no project context files, tools use the scheduler's cwd. On update, pass an empty string to clear. Jobs with workdir run sequentially (not parallel) to keep per-job directories isolated.

Spawn one or more subagents to work on tasks in isolated contexts. Each subagent gets its own conversation, terminal session, and toolset. Only the final summary is returned -- intermediate tool results never enter your context window.

TWO MODES (one of 'goal' or 'tasks' is required):
1. Single task: provide 'goal' (+ optional context, toolsets)
2. Batch (parallel): provide 'tasks' array with up to 3 items concurrently for this user (configured via delegation.max_concurrent_children in config.yaml). All run in parallel and results are returned together. Nested delegation is OFF for this user (max_spawn_depth=1): every child is a leaf and cannot delegate further. Raise delegation.max_spawn_depth in config.yaml to enable nesting.

WHEN TO USE delegate_task:
- Reasoning-heavy subtasks (debugging, code review, research synthesis)
- Tasks that would flood your context with intermediate data
- Parallel independent workstreams (research A and B simultaneously)

WHEN NOT TO USE (use these instead):
- Mechanical multi-step work with no reasoning needed -> use execute_code
- Single tool call -> just call the tool directly
- Tasks needing user interaction -> subagents cannot use clarify
- Durable long-running work that must outlive the current turn -> use cronjob (action='create') or terminal(background=True, notify_on_complete=True) instead. delegate_task runs SYNCHRONOUSLY inside the parent turn: if the parent is interrupted (user sends a new message, /stop, /new) the child is cancelled with status='interrupted' and its work is discarded. Children cannot continue in the background.

IMPORTANT:
- Subagents have NO memory of your conversation. Pass all relevant info (file paths, error messages, constraints) via the 'context' field.
- If the user is writing in a non-English language, or asked for output in a specific language / tone / style, say so in 'context' (e.g. "respond in Chinese", "return output in Japanese"). Otherwise subagents default to English and their summaries will contaminate your final reply with the wrong language.
- Subagent summaries are SELF-REPORTS, not verified facts. A subagent that claims "uploaded successfully" or "file written" may be wrong. For operations with external side-effects (HTTP POST/PUT, remote writes, file creation at shared paths, publishing), require the subagent to return a verifiable handle (URL, ID, absolute path, HTTP status) and verify it yourself — fetch the URL, stat the file, read back the content — before telling the user the operation succeeded.
- Leaf subagents (role='leaf', the default) CANNOT call: delegate_task, clarify, memory, send_message, execute_code.
- Orchestrator subagents (role='orchestrator') retain delegate_task so they can spawn their own workers, but still cannot use clarify, memory, send_message, or execute_code. Orchestrators are bounded by max_spawn_depth=1 for this user and can be disabled globally via delegation.orchestrator_enabled=false.
- Each subagent gets its own terminal session (separate working directory and state).
- Results are always returned as an array, one entry per task.

What the subagent should accomplish. Be specific and self-contained -- the subagent knows nothing about your conversation history.

Background information the subagent needs: file paths, error messages, project structure, constraints. The more specific you are, the better the subagent performs.

Toolsets to enable for this subagent. Default: inherits your enabled toolsets. Available toolsets: 'browser', 'computer_use', 'cronjob', 'discord', 'discord_admin', 'feishu_doc', 'feishu_drive', 'file', 'homeassistant', 'image_gen', 'kanban', 'search', 'session_search', 'skills', 'spotify', 'terminal', 'todo', 'tts', 'video', 'video_gen', 'vision', 'web', 'x_search', 'yuanbao'. Common patterns: ['terminal', 'file'] for code work, ['web'] for research, ['browser'] for web interaction, ['terminal', 'file', 'web'] for full-stack tasks.

Task goal

Task-specific context

Toolsets for this specific task. Available: 'browser', 'computer_use', 'cronjob', 'discord', 'discord_admin', 'feishu_doc', 'feishu_drive', 'file', 'homeassistant', 'image_gen', 'kanban', 'search', 'session_search', 'skills', 'spotify', 'terminal', 'todo', 'tts', 'video', 'video_gen', 'vision', 'web', 'x_search', 'yuanbao'. Use 'web' for network access, 'terminal' for shell, 'browser' for web interaction.

Per-task ACP command override (e.g. 'copilot'). Overrides the top-level acp_command for this task only. Do NOT set unless the user explicitly told you an ACP CLI is installed.

Per-task ACP args override. Leave empty unless acp_command is set.

Per-task role override. See top-level 'role' for semantics.

Batch mode: tasks to run in parallel (up to 3 for this user, set via delegation.max_concurrent_children). Each gets its own subagent with isolated context and terminal session. When provided, top-level goal/context/toolsets are ignored.

Role of the child agent. 'leaf' (default) = focused worker, cannot delegate further. 'orchestrator' = can use delegate_task to spawn its own workers. Nesting is OFF for this user (max_spawn_depth=1); 'orchestrator' is silently forced to 'leaf'. Raise delegation.max_spawn_depth in config.yaml to enable.

Override ACP command for child agents (e.g. 'copilot'). When set, children use ACP subprocess transport instead of inheriting the parent's transport. Requires an ACP-compatible CLI (currently GitHub Copilot CLI via 'copilot --acp --stdio'). See agent/copilot_acp_client.py for the implementation. IMPORTANT: Do NOT set this unless the user has explicitly told you a specific ACP-compatible CLI is installed and configured. Leave empty to use the parent's default transport (Hermes subagents).

Arguments for the ACP command (default: ['--acp', '--stdio']). Only used when acp_command is set. Leave empty unless acp_command is explicitly provided.

Run a Python script that can call Hermes tools programmatically. Use this when you need 3+ tool calls with processing logic between them, need to filter/reduce large tool outputs before they enter your context, need conditional branching (if X then Y else Z), or need to loop (fetch N pages, process N files, retry on failure).

Use normal tool calls instead when: single tool call with no processing, you need to see the full result and apply complex reasoning, or the task requires interactive user input.

Available via `from hermes_tools import ...`:

  read_file(path: str, offset: int = 1, limit: int = 500) -> dict
    Lines are 1-indexed. Returns {"content": "...", "total_lines": N}
  write_file(path: str, content: str) -> dict
    Always overwrites the entire file.
  search_files(pattern: str, target="content", path=".", file_glob=None, limit=50) -> dict
    target: "content" (search inside files) or "files" (find files by name). Returns {"matches": [...]}
  patch(path: str, old_string: str, new_string: str, replace_all: bool = False) -> dict
    Replaces old_string with new_string in the file.
  terminal(command: str, timeout=None, workdir=None) -> dict
    Foreground only (no background/pty). Returns {"output": "...", "exit_code": N}

Limits: 5-minute timeout, 50KB stdout cap, max 50 tool calls per script. terminal() is foreground-only (no background or pty).

Scripts run in the session's working directory with the active venv's python, so project deps (pandas, etc.) and relative paths work like in terminal().

Print your final result to stdout. Use Python stdlib (json, re, math, csv, datetime, collections, etc.) for processing between tool calls.

Also available (no import needed — built into hermes_tools):
  json_parse(text: str) — json.loads with strict=False; use for terminal() output with control chars
  shell_quote(s: str) — shlex.quote(); use when interpolating dynamic strings into shell commands
  retry(fn, max_attempts=3, delay=2) — retry with exponential backoff for transient failures

Python code to execute. Import tools with `from hermes_tools import terminal, ...` and print your final result to stdout.

Generate high-quality images from text prompts. The underlying backend (FAL, OpenAI, etc.) and model are user-configured and not selectable by the agent. Returns either a URL or an absolute file path in the `image` field; display it with markdown ![description](url-or-path) and the gateway will deliver it.

The text prompt describing the desired image. Be detailed and descriptive.

The aspect ratio of the generated image. 'landscape' is 16:9 wide, 'portrait' is 16:9 tall, 'square' is 1:1.

memory

Save durable information to persistent memory that survives across sessions. Memory is injected into future turns, so keep it compact and focused on facts that will still matter later.

WHEN TO SAVE (do this proactively, don't wait to be asked):
- User corrects you or says 'remember this' / 'don't do that again'
- User shares a preference, habit, or personal detail (name, role, timezone, coding style)
- You discover something about the environment (OS, installed tools, project structure)
- You learn a convention, API quirk, or workflow specific to this user's setup
- You identify a stable fact that will be useful again in future sessions

PRIORITY: User preferences and corrections > environment facts > procedural knowledge. The most valuable memory prevents the user from having to repeat themselves.

Do NOT save task progress, session outcomes, completed-work logs, or temporary TODO state to memory; use session_search to recall those from past transcripts.
If you've discovered a new way to do something, solved a problem that could be necessary later, save it as a skill with the skill tool.

TWO TARGETS:
- 'user': who the user is -- name, role, preferences, communication style, pet peeves
- 'memory': your notes -- environment facts, project conventions, tool quirks, lessons learned

ACTIONS: add (new entry), replace (update existing -- old_text identifies it), remove (delete -- old_text identifies it).

SKIP: trivial/obvious info, things easily re-discovered, raw data dumps, and temporary task state.

The action to perform.

Which memory store: 'memory' for personal notes, 'user' for user profile.

The entry content. Required for 'add' and 'replace'.

Short unique substring identifying the entry to replace or remove.

patch

Targeted find-and-replace edits in files. Use this instead of sed/awk in terminal. Uses fuzzy matching (9 strategies) so minor whitespace/indentation differences won't break it. Returns a unified diff. Auto-runs syntax checks after editing.

REPLACE MODE (mode='replace', default): find a unique string and replace it. REQUIRED PARAMETERS: mode, path, old_string, new_string.
PATCH MODE (mode='patch'): apply V4A multi-file patches for bulk changes. REQUIRED PARAMETERS: mode, patch.

Edit mode. 'replace' (default): requires path + old_string + new_string. 'patch': requires patch content only.

REQUIRED when mode='replace'. File path to edit.

REQUIRED when mode='replace'. Exact text to find and replace. Must be unique in the file unless replace_all=true. Include surrounding context lines to ensure uniqueness.

REQUIRED when mode='replace'. Replacement text. Pass empty string '' to delete the matched text.

Replace all occurrences instead of requiring a unique match (default: false)

REQUIRED when mode='patch'. V4A format patch content. Format:
*** Begin Patch
*** Update File: path/to/file
@@ context hint @@
 context line
-removed line
+added line
*** End Patch

process

Manage background processes started with terminal(background=true). Actions: 'list' (show all), 'poll' (check status + new output), 'log' (full output with pagination), 'wait' (block until done or timeout), 'kill' (terminate), 'write' (send raw stdin data without newline), 'submit' (send data + Enter, for answering prompts), 'close' (close stdin/send EOF).

list poll log wait kill write submit close

Action to perform on background processes

Process session ID (from terminal background output). Required for all actions except 'list'.

Text to send to process stdin (for 'write' and 'submit' actions)

Max seconds to block for 'wait' action. Returns partial output on timeout.

Line offset for 'log' action (default: last 200 lines)

Max lines to return for 'log' action

Read a text file with line numbers and pagination. Use this instead of cat/head/tail in terminal. Output format: 'LINE_NUM|CONTENT'. Suggests similar filenames if not found. Use offset and limit for large files. Reads exceeding ~100K characters are rejected; use offset and limit to read specific sections of large files. NOTE: Cannot read images or binary files — use vision_analyze for images.

Path to the file to read (absolute, relative, or ~/path)

Line number to start reading from (1-indexed, default: 1)

Maximum number of lines to read (default: 500, max: 2000)

Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents.

Content search (target='content'): Regex search inside files. Output modes: full matches with line numbers, file paths only, or match counts.

File search (target='files'): Find files by glob pattern (e.g., '*.py', '*config*'). Also use this instead of ls — results sorted by modification time.

Regex pattern for content search, or glob pattern (e.g., '*.py') for file search

'content' searches inside file contents, 'files' searches for files by name

Directory or file to search in (default: current working directory)

Filter files by pattern in grep mode (e.g., '*.py' to only search Python files)

Maximum number of results to return (default: 50)

Skip first N results for pagination (default: 0)

Output format for grep mode: 'content' shows matching lines with line numbers, 'files_only' lists file paths, 'count' shows match counts per file

Number of context lines before and after each match (grep mode only)

Send a message to a connected messaging platform, or list available targets.

IMPORTANT: When the user asks to send to a specific channel or person (not just a bare platform name), call send_message(action='list') FIRST to see available targets, then send to the correct one.
If the user just says a platform name like 'send to telegram', send directly to the home channel without listing first.

Action to perform. 'send' (default) sends a message. 'list' returns all available channels/contacts across connected platforms.

Delivery target. Format: 'platform' (uses home channel), 'platform:#channel-name', 'platform:chat_id', or 'platform:chat_id:thread_id' for Telegram topics and Discord threads. Examples: 'telegram', 'telegram:-1001234567890:17585', 'discord:999888777:555444333', 'discord:#bot-home', 'slack:#engineering', 'signal:+155****4567', 'matrix:!roomid:server.org', 'matrix:@user:server.org', 'yuanbao:direct:<account_id>' (DM), 'yuanbao:group:<group_code>' (group chat)

The message text to send. To send an image or file, include MEDIA:<local_path> (e.g. 'MEDIA:/tmp/hermes/cache/img_xxx.jpg') in the message — the platform will deliver it as a native media attachment.

Search your long-term memory of past conversations, or browse recent sessions. This is your recall -- every past session is searchable, and this tool summarizes what happened.

TWO MODES:
1. Recent sessions (no query): Call with no arguments to see what was worked on recently. Returns titles, previews, and timestamps. Zero LLM cost, instant. Start here when the user asks what were we working on or what did we do recently.
2. Keyword search (with query): Search for specific topics across all past sessions. Returns LLM-generated summaries of matching sessions.

USE THIS PROACTIVELY when:
- The user says 'we did this before', 'remember when', 'last time', 'as I mentioned'
- The user asks about a topic you worked on before but don't have in current context
- The user references a project, person, or concept that seems familiar but isn't in memory
- You want to check if you've solved a similar problem before
- The user asks 'what did we do about X?' or 'how did we fix Y?'

Don't hesitate to search when it is actually cross-session -- it's fast and cheap. Better to search and confirm than to guess or ask the user to repeat themselves.

Search syntax: keywords joined with OR for broad recall (elevenlabs OR baseten OR funding), phrases for exact match ("docker networking"), boolean (python NOT java), prefix (deploy*). IMPORTANT: Use OR between keywords for best results — FTS5 defaults to AND which misses sessions that only mention some terms. If a broad OR query returns nothing, try individual keyword searches in parallel. Returns summaries of the top matching sessions.

Search query — keywords, phrases, or boolean expressions to find in past sessions. Omit this parameter entirely to browse recent sessions instead (returns titles, previews, timestamps with no LLM cost).

Optional: only search messages from specific roles (comma-separated). E.g. 'user,assistant' to skip tool outputs.

Max sessions to summarize (default: 3, max: 5).

Manage skills (create, update, delete). Skills are your procedural memory — reusable approaches for recurring task types. New skills go to ~/.hermes/skills/; existing skills can be modified wherever they live.

Actions: create (full SKILL.md + optional category), patch (old_string/new_string — preferred for fixes), edit (full SKILL.md rewrite — major overhauls only), delete, write_file, remove_file.

On delete, pass `absorbed_into=<umbrella>` when you're merging this skill's content into another one, or `absorbed_into=""` when you're pruning it with no forwarding target. This lets the curator tell consolidation from pruning without guessing, so downstream consumers (cron jobs that reference the old skill name, etc.) get updated correctly. The target you name in `absorbed_into` must already exist — create/patch the umbrella first, then delete.

Create when: complex task succeeded (5+ calls), errors overcome, user-corrected approach worked, non-trivial workflow discovered, or user asks you to remember a procedure.
Update when: instructions stale/wrong, OS-specific failures, missing steps or pitfalls found during use. If you used a skill and hit issues not covered by it, patch it immediately.

After difficult/iterative tasks, offer to save as a skill. Skip for simple one-offs. Confirm with user before creating/deleting.

Good skills: trigger conditions, numbered steps with exact commands, pitfalls section, verification steps. Use skill_view() to see format examples.

Pinned skills are protected from deletion only — skill_manage(action='delete') will refuse with a message pointing the user to `hermes curator unpin <name>`. Patches and edits go through on pinned skills so you can still improve them as pitfalls come up; pin only guards against irrecoverable loss.

create patch edit delete write_file remove_file

The action to perform.

Skill name (lowercase, hyphens/underscores, max 64 chars). Must match an existing skill for patch/edit/delete/write_file/remove_file.

Full SKILL.md content (YAML frontmatter + markdown body). Required for 'create' and 'edit'. For 'edit', read the skill first with skill_view() and provide the complete updated text.

Text to find in the file (required for 'patch'). Must be unique unless replace_all=true. Include enough surrounding context to ensure uniqueness.

Replacement text (required for 'patch'). Can be empty string to delete the matched text.

For 'patch': replace all occurrences instead of requiring a unique match (default: false).

Optional category/domain for organizing the skill (e.g., 'devops', 'data-science', 'mlops'). Creates a subdirectory grouping. Only used with 'create'.

Path to a supporting file within the skill directory. For 'write_file'/'remove_file': required, must be under references/, templates/, scripts/, or assets/. For 'patch': optional, defaults to SKILL.md if omitted.

Content for the file. Required for 'write_file'.

For 'delete' only — declares intent so the curator can tell consolidation from pruning without guessing. Pass the umbrella skill name when this skill's content was merged into another (the target must already exist). Pass an empty string when the skill is truly stale and being pruned with no forwarding target. Omitting the arg on delete is supported for backward compatibility but downstream tooling (e.g. cron-job skill reference rewriting) will have to guess at intent.

Skills allow for loading information about specific tasks and workflows, as well as scripts and templates. Load a skill's full content or access its linked files (references, templates, scripts). First call returns SKILL.md content plus a 'linked_files' dict showing available references/templates/scripts. To access those, call again with file_path parameter.

The skill name (use skills_list to see available skills). For plugin-provided skills, use the qualified form 'plugin:skill' (e.g. 'superpowers:writing-plans').

OPTIONAL: Path to a linked file within the skill (e.g., 'references/api.md', 'templates/config.yaml', 'scripts/validate.py'). Omit to get the main SKILL.md content.

List available skills (name + description). Use skill_view(name) to load full content.

Optional category filter to narrow results

terminal

Execute shell commands on a Linux environment. Filesystem usually persists between calls.

Do NOT use cat/head/tail to read files — use read_file instead.
Do NOT use grep/rg/find to search — use search_files instead.
Do NOT use ls to list directories — use search_files(target='files') instead.
Do NOT use sed/awk to edit files — use patch instead.
Do NOT use echo/cat heredoc to create files — use write_file instead.
Reserve terminal for: builds, installs, git, processes, scripts, network, package managers, and anything that needs a shell.

Foreground (default): Commands return INSTANTLY when done, even if the timeout is high. Set timeout=300 for long builds/scripts — you'll still get the result in seconds if it's fast. Prefer foreground for short commands.
Background: Set background=true to get a session_id. Two patterns:
  (1) Long-lived processes that never exit (servers, watchers).
  (2) Long-running tasks with notify_on_complete=true — you can keep working on other things and the system auto-notifies you when the task finishes. Great for test suites, builds, deployments, or anything that takes more than a minute.
For servers/watchers, do NOT use shell-level background wrappers (nohup/disown/setsid/trailing '&') in foreground mode. Use background=true so Hermes can track lifecycle and output.
After starting a server, verify readiness with a health check or log signal, then run tests in a separate terminal() call. Avoid blind sleep loops.
Use process(action="poll") for progress checks, process(action="wait") to block until done.
Working directory: Use 'workdir' for per-command cwd.
PTY mode: Set pty=true for interactive CLI tools (Codex, Claude Code, Python REPL).

Do NOT use vim/nano/interactive tools without pty=true — they hang without a pseudo-terminal. Pipe git output to cat if it might page.

The command to execute on the VM

Run the command in the background. Two patterns: (1) Long-lived processes that never exit (servers, watchers). (2) Long-running tasks paired with notify_on_complete=true — you can keep working and get notified when the task finishes. For short commands, prefer foreground with a generous timeout instead.

Max seconds to wait (default: 180, foreground max: 600). Returns INSTANTLY when command finishes — set high for long tasks, you won't wait unnecessarily. Foreground timeout above 600s is rejected; use background=true for longer commands.

Working directory for this command (absolute path). Defaults to the session working directory.

Run in pseudo-terminal (PTY) mode for interactive CLI tools like Codex, Claude Code, or Python REPL. Only works with local and SSH backends. Default: false.

When true (and background=true), you'll be automatically notified exactly once when the process finishes. **This is the right choice for almost every long-running task** — tests, builds, deployments, multi-item batch jobs, anything that takes over a minute and has a defined end. Use this and keep working on other things; the system notifies you on exit. MUTUALLY EXCLUSIVE with watch_patterns — when both are set, watch_patterns is dropped.

Strings to watch for in background process output. HARD RATE LIMIT: at most 1 notification per 15 seconds per process — matches arriving inside the cooldown are dropped. After 3 consecutive 15-second windows with dropped matches, watch_patterns is automatically disabled for that process and promoted to notify_on_complete behavior (one notification on exit, no more mid-process spam). USE ONLY for truly rare, one-shot mid-process signals on LONG-LIVED processes that will never exit on their own — e.g. ['Application startup complete'] on a server so you know when to hit its endpoint, or ['migration done'] on a daemon. DO NOT use for: (1) end-of-run markers like 'DONE'/'PASS' — use notify_on_complete instead; (2) error patterns like 'ERROR'/'Traceback' in loops or multi-item batch jobs — they fire on every iteration and you'll hit the strike limit fast; (3) anything you'd ever combine with notify_on_complete. When in doubt, choose notify_on_complete. MUTUALLY EXCLUSIVE with notify_on_complete — set one, not both.

Convert text to speech audio. Returns a MEDIA: path that the platform delivers as native audio. Compatible providers render as a voice bubble on Telegram; otherwise audio is sent as a regular attachment. In CLI mode, saves to ~/voice-memos/. Voice and provider are user-configured (built-in providers like edge/openai or custom command providers under tts.providers.<name>), not model-selected.

The text to convert to speech. Provider-specific character caps apply and are enforced automatically (OpenAI 4096, xAI 15000, MiniMax 10000, ElevenLabs 5k-40k depending on model); over-long input is truncated.

Optional custom file path to save the audio. Defaults to ~/.hermes/audio_cache/<timestamp>.mp3

todo

Manage your task list for the current session. Use for complex tasks with 3+ steps or when the user provides multiple tasks. Call with no parameters to read the current list.

Writing:
- Provide 'todos' array to create/update items
- merge=false (default): replace the entire list with a fresh plan
- merge=true: update existing items by id, add any new ones

Each item: {id: string, content: string, status: pending|in_progress|completed|cancelled}
List order is priority. Only ONE item in_progress at a time.
Mark items completed immediately when done. If something fails, cancel it and add a revised item.

Always returns the full current list.

Task items to write. Omit to read current list.

Unique item identifier

Task description

Current status

true: update existing items by id, add new ones. false (default): replace the entire list.

Load an image into the conversation so you can see it. Accepts a URL, local file path, or data URL. When your active model has native vision, the image is attached to your context directly and you read the pixels yourself on the next turn — call this any time the user references an image (filepath in their message, URL in tool output, screenshot from the browser, etc.). For non-vision models, falls back to an auxiliary vision model that returns a text description.

Image URL (http/https), local file path, or data: URL to load.

Your specific question or request about the image. Optional context the model uses on the next turn after seeing the image.

Write content to a file, completely replacing existing content. Use this instead of echo/cat heredoc in terminal. Creates parent directories automatically. OVERWRITES the entire file — use 'patch' for targeted edits. Auto-runs syntax checks on .py/.json/.yaml/.toml and other linted languages; only NEW errors introduced by this write are surfaced (pre-existing errors are filtered out).

Path to the file to write (will be created if it doesn't exist, overwritten if it does)

Complete content to write to the file


[M G] Aspect ratio stimmt nicht, bzw oben und unten sind schwarze balken und das sichtbare bild ist in der höhe zusammengestaucht.


Explanation:
**Considering video response**

I think I need to respond regarding the previous video, but I might need more context about AutoShorts. Maybe I should ask the user for clarification? I could suggest a fix using ffmpeg, but I wonder if that's necessary given the current situation. The user mentioned aspect ratio, which is important for social media shorts. It could be useful to explore skills related to social media shorts or growth while addressing this.


social-media-shorts-automation

---
name: social-media-shorts-automation
description: Design, generate, review, publish, and optimize automated short-form social videos across YouTube Shorts, TikTok, Instagram Reels, and related channels.
version: 1.0.0
tags: [shorts, tiktok, youtube-shorts, reels, creator-monetization, content-automation, social-media]
---

# Social-Media Shorts Automation

Reference note: see `references/controlled-pilot-production-v2.md` for the controlled first-video workflow: resource tiers, media-generation gates, pilot package shape, Wan prompt planning without generation, and no auto-posting. See `references/pilot-preview-render-v2.md` for the next approval step: `APPROVED_FOR_PREVIEW_RENDER`, EdgeTTS preview audio, time/word cue generation, deterministic 9:16 animatic MP4, checksums, and Telegram media delivery without Wan/AI-image/platform side effects. See `references/static-active-word-captions-and-final-pilot-render.md` for the corrected caption style and controlled final pilot render pattern: static 3–7 word phrase segments with only the active spoken word highlighted, hash-bound final render gates, one Wan text-free background layer, deterministic overlays, and draft-only manual posting packages. If a final render is rejected as preview-overlay-dominated or not visual-first, follow `references/visual-first-final-render-repair.md`: mark the render rejected/not-postable, fix Wan output parsing, enforce final overlay limits, produce only a short visual proof under `APPROVED_FOR_VISUAL_PROOF`, and do not run another full final until the visual direction is accepted. If even the visual proof is rejected as abstract/generic/dark or “blind T2V”, switch to `references/keyframe-first-final-visuals.md`: plan and approve start/end/style keyframes first, then run only a short I2V/first-last-frame proof with minimal renderer-owned overlays. If the user says the production method itself is wrong, keyframes are not I2V-ready, or an animatic was incorrectly substituted for a failed Wan proof, follow `references/visual-production-reset-i2v-first.md`: reject/audit the proof, stop content rendering, run technical I2V sanity first, then generate at most three styleframes for direction review. If deterministic layout proofs are useful as composition blueprints but rejected as too wireframe/PowerPoint for final style, switch to `references/premium-ai-styleframe-direction.md`: use the layouts only as mechanism blueprints, generate at most 3 tightly briefed premium text-free AI styleframes, deliver a contact sheet with verified media metadata, and keep Wan/I2V/endframes/full-final blocked until style direction approval. If those premium styleframes are better quality but still too abstract, switch to `references/real-life-premium-styleframes.md`: anchor the mechanism in a realistic work/meeting/desk scene, keep all readable overlays renderer-owned, generate at most 3 new real-life styleframes plus contact sheet, and still block Wan/I2V/endframes/full-final until explicit approval. If the user approves one or more real-life styleframe directions but wants to compare A/B/C before Wan, use `references/prerelease-animatic-preview.md`: build only a small AI-keyframe + deterministic-motion animatic per approved direction, reuse existing voiceover/captions, deliver MP4/contact/QA sheets with metadata, and keep Wan/I2V/final/posting blocked. If the user then rejects the renderer-added circles/arrows/labels/boxes/decision-target markers as destroying the premium look, switch to `references/clean-image-cut-no-overlay-pilot.md`: render only AI images + voiceover + clean subtitles, with a hard subtitles-only NoOverlayPolicy and no Wan/I2V/full-final/posting. If the user performs a strategic reset because the pilot is pretty but semantically weak, stop optimizing that candidate and follow `references/proof-short-real-problem-reset.md`: archive the old pilot as a learning case, enforce the Pretty Empty Visual Blocker, and build a screen/mockup-led Proof Short around an immediately visible real viewer problem before any premium/Wan production. If the next review focuses on image provider quality/provenance or subtitles running off-screen, follow `references/image-provider-audit-and-caption-safezone.md`: audit the configured image provider/model/tier from config + provider registry + cache metadata, run at most one neutral capability test, keep UI/invoice mockups deterministic, and add tested caption layout safe-zone bounds before re-rendering. If an approved Proof Short feels too visually flat and the user asks why no AI images were used, follow `references/proof-short-ai-visual-upgrade.md`: use AI images as a controlled text-free atmosphere/background/keyframe layer while keeping invoices, emails, payment routes, labels, facts, and captions deterministic renderer-owned. For the concrete rendering/QA pattern — small 2–3 keyframe pass, contact-sheet inspection, discard pseudo-text frames, blur/darken/subordinate AI backgrounds, and report used/discarded keyframes — see `references/proof-short-ai-background-rendering-qa.md`. For the follow-up A/B test where the user asks whether pure KI images can match or beat hybrid mockups, see `references/clean-ai-cut-vs-hybrid-mechanism.md`: compare clean image-only premium feel against mechanism clarity, keep word-aligned subtitles, and consider `90% clean AI images + 10% minimal deterministic mechanism` as the likely next style.

Use this skill when building or operating systems that generate short-form social videos, especially faceless or semi-automated pipelines for YouTube Shorts, TikTok, Instagram Reels, Facebook Reels, Pinterest video pins, X video, or LinkedIn video.

## Core principle

Treat the system as a **Shorts Growth Engine** / **semi-automatic Retention Studio**, not merely a renderer. A working video generator can still fail if it produces generic, low-retention, AI-slop content. Optimize for audience identity, hook quality, retention mechanics, visual mechanism reveals, platform fit, and analytics feedback. For the user's strongest strategic direction, see `references/retention-studio-strategy.md`.

For this user's AutoShorts workflows, approval previews should be German for concept comprehension, while final social-media videos should remain English unless explicitly changed. Treat preview legibility as a quality gate: readable font sizes, pixel-width-aware line wrapping, no clipped words, and no overcrowded cards.

For the user's TrueTraceShorts / AutoShortsBot strategy, do **not** default to a narrow AI/prompt-tips channel. The current strategic direction is broader: explain hidden digital everyday mechanisms — AI, work, attention, decisions, scams, productivity, workflows, social search — and end each video with one small system rule that fixes the outcome. Use the frame `Trace the hidden system. Fix the outcome.` AI should remain an important pillar, but normally only about 30–40% of the topic mix, not the whole product. See `references/truetrace-strategic-neuausrichtung.md`.

When the user asks to start implementation work on this strategy, especially “Sprint 1: Strategic Spine Refactor”, follow `references/truetrace-strategic-spine-refactor-v2.md`: implement a side-effect-free V2 spine in parallel to existing V1 models, with mandatory strategic fields, hard quality gates, anti-AI-slop blockers, hash/version-bound ReviewPackageV2, and tests before integration with renderers or platform workflows.

When the user asks for “Sprint 1.5” or to make the V2 spine operational without production, follow `references/truetrace-v2-operational-bridge.md`: first secure/commit the Sprint-1 baseline, then add only minimal side-effect-free bridges (`to_candidate_v2`, `workflow_v2`, `demo_review_batch_v2`), deterministic ReviewPackageV2 JSON, strict approval parsing, calibrated non-generous scoring, anti-example/human-texture gates, minimal manual claim/disclosure stubs, LinkedIn manual metadata, and a Remotion-as-later-spike note. Keep it capped at 3 demo candidates and avoid rendering, platform APIs, dashboards, auto-posting, or 30-day batches.

## Retention-Studio / Mechanism-Reveal Pipeline

For quality-first automated Shorts, especially Hidden Money & AI Systems concepts, prefer the pipeline documented in `references/retention-studio-pipeline-pattern.md`:

```text
strategy → scored ideas → mechanism explainer → shot plan → keyframe/I2V prompt plan → seeded clip jobs → clip review → deterministic final renderer
```

When implementing a new repo or core pipeline, first scaffold the approval-first typed artifact chain in `references/approval-first-retention-studio-core.md`:

```text
ContentPillar → ContentBrief → ScriptDraft → VideoCandidate → TestBatch → ReviewBatch → Telegram ReviewDelivery → ShotPlan
```

Hard rule for this class: AI-video clips provide photorealistic texture and motion only. Captions, numbers, labels, arrows, UI text, price/risk/margin layers, and factual claims are renderer-owned. Final content should keep `static_card_limit = 0`, use visual changes every 1–2 seconds, and reject technically successful clips that do not serve the retention beat.

Before video generation, build an inspectable content-to-review spine: `ContentBrief → ScriptDraft → CandidateDraft → VideoCandidate → TestBatch → ReviewBatch → Telegram ReviewDelivery`. Keep it deterministic, side-effect free, and human-approval-first so hooks, retention beats, visual concepts, policy notes, and review copy can be optimized before spending GPU/API time. See `references/content-to-review-pipeline.md` for the implementation pattern and guardrails.

Hard rule for this class: AI-video clips provide photorealistic texture and motion only. Captions, numbers, labels, arrows, UI text, price/risk/margin layers, and factual claims are renderer-owned. Final content should keep `static_card_limit = 0`, use visual changes every 1–2 seconds, and reject technically successful clips that do not serve the retention beat.

## Recommended workflow

1. **Define channel position**
   - Niche(s): e.g. life optimization, AI life systems, Christian faith/FaithTok.
   - Target audience and emotional problem.
   - Language and tone.
   - Whether the brand is faceless, AI-persona-led, or creator-led.
   - No-go topics and theological/ethical boundaries if faith-related.

2. **Generate test ideas before code-heavy automation**
   - Create 20–30 candidate ideas across 2–4 content pillars.
   - For each: hook, script kernel, visual concept, caption, CTA, risk/quality score.
   - Select a small first batch (e.g. 3 per pillar) for real testing.
   - Before renderers or external AI APIs, add a deterministic content-development core: `ContentPillar → ContentBrief → ScriptDraft → CandidateDraft → VideoCandidate`. See `references/content-development-core.md`.

3. **Use hook-first, retention-led scripting**
   - First 1–2 seconds must contain a clear tension, identity statement, pain point, contrarian line, or immediate self-recognition.
   - Prefer one idea per video over generic “4 tips” unless the list format is the explicit series.
   - Avoid generic advice viewers have already heard unless framed with a new angle, concrete payoff, or strong story.
   - For TrueTraceShorts, prefer the structure `visible fail → identification → mechanism → fix → before/after → memorable takeaway` over generic AI-tip narration. Every video must answer: what goes wrong, why it happens, what rule fixes it, what sentence sticks, why viewers save/share it, and why they follow the series.
   - For unvalidated first pilots, apply the `Pretty Empty Visual Blocker`: if the first frame is beautiful but does not show a concrete viewer pain without voiceover, block the concept and switch to a Proof Short. Do not keep polishing abstract AI visuals, glass metaphors, or generic laptop B-roll before validating the real problem. See `references/proof-short-real-problem-reset.md`.
   - After a Proof Short concept is approved for usefulness/clarity, do not interpret `ProofShortMode` as a permanent ban on AI images. If the user wants the video “aufgepeppt”, add a controlled AI visual-upgrade layer: 2–3 text-free premium backgrounds/keyframes, while all invoice/email/UI/payment-route text, labels, facts, captions, claims, and red-flag overlays remain deterministic renderer-owned. See `references/proof-short-ai-visual-upgrade.md`.
   - Reward hooks with direct address, specificity, open loops, tension, and a visible payoff; reject slow intros such as “In this video...”.
   - See `references/retention-led-shorts.md` for scoring signals, penalties, and voiceover finalization rules.

4. **Quality gate before rendering**
   Score drafts on:
   - hook strength
   - novelty
   - emotional pull
   - clarity
   - retention risk
   - comment/share potential
   - AI-slop risk
   - platform/policy risk
   - first-frame clarity
   - mechanism value
   - practical payoff
   - save/share/follow reason
   - trust/human texture
   - series fit and saturation defense
   Render only drafts above the chosen threshold, e.g. 8/10.
   For TrueTraceShorts, use the 100-point scoring and hard blockers in `references/truetrace-strategic-neuausrichtung.md`: block generic AI hooks, pure text first frames, unsourced claims, missing before/after, missing human texture, unclear AI disclosure, and candidates too similar to recent videos.

5. **Visual strategy**
   - Avoid obvious AI artifacts, fake UI text, illegible generated lettering, generic charts, and soulless stock visuals.
   - Prefer high-contrast kinetic captions, visible hook text in first seconds, relatable B-roll, screen recordings for AI/tutorial content, phone/screen close-ups, before/after transformations, cards, and timer visuals.
   - Use pattern interrupts every 2–3 seconds for retention.
   - Before rendering, generate a shot plan from the finalized voiceover: first-frame hook, pattern interrupt, core explanation, screen/card visual, CTA, caption beats, and asset type.
   - Before writing a renderer, convert shot plans into deterministic render manifests: machine-readable timeline items, asset placeholders, caption tracks, style constraints, and approval constraints. See `references/render-manifest-pipeline.md`.
   - Treat this as a deterministic intermediate artifact, not optional prose. See `references/retention-render-planning.md` for the five-scene shot-plan pattern and renderer-facing fields.
   - For the first video output, build a manifest-driven preview renderer before any AI-video or polished asset pipeline: first create a side-effect-free local preview plan, then write deterministic PNG scene cards, then build a side-effect-free FFmpeg concat plan, and only then call FFmpeg from an explicit renderer boundary. The boundary should report side effects such as `write_png`, `write_concat`, `call_ffmpeg`, and `write_mp4`; keep generated PNG/MP4 artifacts out of Git. See `references/manifest-preview-renderer.md`.
   - When the user rejects static/slideshow output, add an `asset_plan.v2` layer that maps each scene to motion-led local asset modes such as `cinematic_ai_video`, `screen_recording_simulation`, `mechanism_animation`, or `kinetic_text_overlay` with no baked text. If the user requires a free workflow, do not depend on paid video-credit tools; use local procedural motion and optional free NVIDIA LLM text refinement. See `references/ai-video-asset-planning.md`.
   - For hybrid workflows, add an imported-clip assembly layer: provider handoff prompts create short manual AI-video clips, humans drop them into deterministic `data/imported_ai_clips/<slug>/scene_XX.mp4` paths, and the final renderer combines imported clips with local mechanism animations/captions. See `references/imported-ai-clip-assembly.md`.
   - For local Wan2.2 quality workflows, prefer keyframe/image-to-video over raw text-to-video: generate/select a clean keyframe, run native Wan2.2 I2V variants, review clips bluntly for subject clarity/motion/artifacts, then add all labels/numbers/captions via deterministic renderer. See `references/wan-i2v-retention-studio.md`.
   - For final renders, Wan must carry the visual scene, not merely provide a blurred/looped background underneath preview cards. Use full-bleed, scene-specific Wan clips, minimal renderer-owned overlays, and a final overlay policy that blocks preview frames, large UI cards/textboxes, debug bars, and overlay overload. If architecture is rejected, create a short visual proof first; see `references/visual-first-final-render-repair.md`.
   - If a visual proof still looks like blind text-to-video or random abstract AI output, stop T2V and move to a keyframe-first workflow: generate/approve 1–2 text-free start/end/style keyframes for the scene, then attempt only a short Wan I2V/first-last-frame proof. See `references/keyframe-first-final-visuals.md`.
   - When using NVIDIA Build/API Catalog for keyframes, prefer hosted `ai.api.nvidia.com` calls before considering self-hosted NIM deployment; implement a configurable model fallback chain, store the key as a runtime secret, and inspect/clean logos, emblems, license plates, and fake text before I2V. See `references/nvidia-keyframe-generation.md`.

6. **Social-media draft and content-preview approval packages before TTS/rendering polish**
   - Before TTS, platform APIs, or polished video generation, build a typed `SocialMediaDraft` from the approved candidate plus render manifest/preview.
   - Include platform targets, title variants, caption, hashtags, CTA, hook, duration, quality/risk summary, and preview reference.
   - Render this into a Telegram-safe approval message and wrap it in a side-effect-free delivery plan with `requires_human_approval=True` and `side_effects=()`.
   - After a local MP4 timing preview exists, combine the MP4 path plus social draft review into a side-effect-free content preview approval package. This package should carry `approval_language=de`, `final_video_language=en`, explicit approval commands, no external calls, and no side effects.
   - Add local demo CLIs that print metadata first, then review text; draft-only CLIs must not write files, call renderers, call Telegram, or access credentials. MP4 preview CLIs may write local artifacts and call FFmpeg only at explicit renderer boundaries that report side effects.
   - See `references/social-draft-approval-package.md` and `references/content-automation-patterns.md` for concrete artifact sequence, user-specific language rules, and external workflow patterns.

7. **Human approval loop before posting**
   - Send preview to the user through the requested channel, usually Telegram.
   - Include: video or preview reference, title, caption, hashtags, platform recommendation, duration, quality/risk score.
   - When sending multiple preview videos, verify and label distinct artifacts before delivery: candidate ID/title, absolute path, duration, and preferably checksum/hash. If several previews are visually similar timing cards, do not spam them as separate unlabeled media; send a concise indexed list first or bundle with clear labels so the user can tell them apart.
   - Wait for explicit approval such as `Freigabe alle`, `Freigabe YouTube`, `Freigabe TikTok`, `Ablehnen`, or `Ändern: ...`.
   - Do not publish automatically unless the user has explicitly authorized that workflow.

8. **TTS / voice layer after draft approval**
   - Treat TTS as a later layer, not the starting point for a first post draft.
   - Decide voice, final voiceover script, words-per-second, scene timing, caption sync, audio format, provider, and separate voice approval only after the social draft package is reviewable.
   - This avoids spending TTS/rendering effort on unapproved hooks, captions, or platform positioning.
  - For final-near previews, keep one copy source of truth: final voiceover → script draft/retention beats → shot plan → top card text → scene captions → subtitle track → TTS audio. Do not mix old approval-card text with new spoken/subtitle text.
  - If the user says the result is too abstract/abgehoben, rewrite around a concrete beginner-friendly everyday failure example before polishing visuals. Prefer “one weird email arrives” / missing field / unclear request / wrong confident action over jargon such as `exception path`, `input boundary`, or `output standard`. See `references/beginner-friendly-audio-caption-alignment.md`.
  - If the user says subtitles are irritating or not simultaneous with voiceover, treat this as a blocking quality issue: use forced alignment or provider word-boundary events before sending another final-near clip. For EdgeTTS previews, request `boundary='WordBoundary'` and render active-word highlights from those offsets; do not merely distribute words evenly over sentence SRT durations. For this user's AutoShorts/TrueTraceShorts default, do **not** show one word alone and do **not** slide a changing word-window every word. Use static phrase segments: keep 3–7 words fixed on screen while only the currently spoken word highlights/pulses left-to-right; replace the full segment only at a sentence/phrase boundary. See `references/static-active-word-captions-and-final-pilot-render.md`.
  - If the user says the ending is confusing, rushed, or does not offer a real solution, treat this as a content-blocking issue, not a minor copy tweak. Rewrite the final third so non-technical viewers are explicitly walked through the concrete action: what to close/avoid, what to open/check instead, how they know it worked, and the memorable rule/fazit. Avoid vague imperatives like “open the service yourself” unless immediately unpacked with a concrete example such as “close the invite; open the calendar/work app from the normal icon or bookmark; if the meeting is real, it will still be there.”
  - If deterministic layouts explain the mechanism but look like wireframes/PowerPoint, do not promote them to final style.
  - If deterministic layouts explain the mechanism but look like wireframes/PowerPoint, do not promote them to final style. Treat them as composition blueprints and run a small, tightly prompted premium AI styleframe pass instead: AI supplies glassmorphism/product-film quality and atmosphere; the renderer still owns labels, arrows, captions, facts, and final assembly. See `references/premium-ai-styleframe-direction.md`.
  - If premium AI styleframes improve quality but still feel like abstract SaaS symbolism, do not continue iterating abstract funnels/rings. Move to real-life anchored work scenes: desk/laptop, empty meeting room/glass board, or project table/work evidence, with only subtle glass/holographic mechanism overlays. See `references/real-life-premium-styleframes.md`.
  - If real-life styleframe directions are accepted but the user has not approved Wan/I2V yet, insert a pre-release animatic comparison step rather than jumping to endframes or video generation. Create small per-direction AI keyframe sets, deterministic push-ins/crossfades, existing voiceover, static active-word captions, contact sheets, and QA frame sheets; report Telegram delivery metadata. See `references/prerelease-animatic-preview.md`.
If the user rejects the added visual explanation overlays as making the result look like a technical explainer board, treat this as a hard style failure. For the clean pilot, use only AI images, voiceover, and clean subtitles; block circles, arrows, labels, boxes, connector lines, decision-target markers, debug/diagram elements, and caption boxes/bars. See `references/clean-image-cut-no-overlay-pilot.md`. If the user then asks whether pure KI-Bilder can achieve the same or better effect, run an A/B proof against the hybrid version and assess premium look vs mechanism clarity; the likely final style may be `90% clean AI images + 10% minimal renderer-owned mechanism`. See `references/clean-ai-cut-vs-hybrid-mechanism.md`.
  - For mechanism-reveal final renders, use the hybrid pattern in `references/final-motion-hybrid-rendering.md`: ChatGPT Image/Codex or similar tools create text-free scene backgrounds only; deterministic renderer owns cards, labels, arrows, subtitles, and FFmpeg assembly. Use compact phrase-boundary subtitle cues before 1080 export.

9. **Publish and measure**
   Track at minimum:
   - platform, video id/url, niche, format, hook, duration
   - views at 2h/24h/7d
   - likes, comments, shares, saves, follows
   - retention metrics if available
   Use results to generate the next batch.

## Platform duration/monetization notes

See `references/preview-media-delivery-guardrails.md` for avoiding duplicate-looking/unlabeled preview-video spam in Telegram review workflows.

See `references/truetrace-strategic-spine-refactor-v2.md` for implementing the new TrueTraceShorts strategy in code: V2 strategic models, hard gates, anti-AI-slop blockers, SeriesRegistry, 100-point scoring, hash-bound ReviewPackageV2, and deterministic five-candidate examples without rendering or platform side effects. See `references/truetrace-v2-operational-bridge.md` for the next implementation step: secure the Sprint-1 commit, add minimal side-effect-free bridge/workflow/CLI modules, deterministic ReviewPackageV2 JSON, strict approval parsing, calibrated scoring, anti-example/human-texture gates, manual claim/disclosure stubs, LinkedIn manual metadata, and Remotion-as-later-spike documentation without production expansion.

See `references/audio-caption-preview-pipeline.md` for the approval-first EdgeTTS + ASS subtitles + FFmpeg review-MP4 pipeline, including actual-audio-duration probing and the explicit `preserve_video` vs `trim_to_audio` duration-mode guardrail. See `references/pilot-preview-render-v2.md` for the stricter first-pilot preview pattern: preview-only approval state, EdgeTTS sentence SRT to preview word cues when forced alignment is unavailable, deterministic card/diagram animatic rendering, SHA256/duration verification, and Telegram media delivery while Wan/AI-image/platform calls remain blocked. See `references/static-active-word-captions-and-final-pilot-render.md` for the corrected Hormozi-style caption behaviour and the one-render final pilot review-package checklist. See `references/word-boundary-caption-sync-and-solution-gate.md` for the stronger EdgeTTS `WordBoundary` timing pattern and the explicit solution/fazit gate for Proof Shorts.

See `references/final-motion-hybrid-rendering.md` for the final-near hybrid renderer pattern: ChatGPT Image/Codex or other AI tools provide text-free background/keyframe texture while deterministic renderer overlays own text, arrows, labels, captions, and final assembly. For quick prototypes, prefer ChatGPT Image/Codex backgrounds before local Qwen/ComfyUI unless privacy/cost/local-only constraints dominate. After a 1080 export, create a side-effect-free final approval package with media path, SHA256, platform metadata, social copy, quality notes, and approval commands before any delivery or platform step.

See `references/visual-first-final-render-repair.md` for the repaired final-render architecture after a rejected pilot: mark rejected renders as not-postable, avoid preview-board overlays, enforce `FinalOverlayPolicy`, validate ComfyUI/Wan output histories robustly, and use `APPROVED_FOR_VISUAL_PROOF` for one short visual proof before any second full final.

See `references/hybrid-scene-backgrounds-codex.md` for the concrete ChatGPT Image/Codex scene-background workflow: side-effect-free `SceneBackgroundPlan`, per-scene text-free backgrounds, renderer-owned overlays, and visual QA before review delivery. Prefer this over local Qwen/ComfyUI when the user allows Codex image generation and local GPU should be reserved for video/model work.

See `references/monetization-and-approval-notes.md` for current working notes captured from official YouTube/TikTok docs and the recommended approval/posting setup. See `references/retention-led-shorts.md` for retention scoring signals, no-faith/adjacent-pillar handling, and voiceover finalization rules. See `references/render-manifest-pipeline.md` for the script → shot plan → render manifest → renderer sequence that prevents generic AI slideshow output. See `references/manifest-preview-renderer.md` for the first deterministic Pillow/FFmpeg preview-renderer pattern. See `references/local-preview-frame-writer.md` for the staged `LocalPreviewPlan → PNG scene cards → FFmpeg concat plan` boundary before MP4 rendering. See `references/social-draft-approval-package.md` for the typed first-post approval package to build before TTS or platform APIs. See `references/content-automation-patterns.md` for public workflow patterns, queue/status/cost tracking, versioned approval, synthetic-content disclosure, originality gates, and the user's German-preview/English-final rule. See `references/ai-video-asset-planning.md` for motion-led final-render asset planning with Kling/Hailuo/Runway-style clips and screen simulations. See `references/imported-ai-clip-assembly.md` for hybrid assembly where manually generated provider clips are imported into a deterministic local renderer. See `references/nvidia-keyframe-generation.md` for NVIDIA-hosted keyframe generation, model fallback, secret handling, and pre-I2V logo/plate cleanup. Re-check official docs before making business-critical decisions because platform programs change often.

## Project/repo hygiene for automated video bots

- Keep source code in Git; keep generated videos, assets, `.env`, OAuth tokens, API keys, and downloaded secrets out of Git.
- Use `.gitignore` aggressively for outputs, media caches, local credentials, and temp files.
- Store platform credentials as runtime secrets; never print raw tokens.
- Build the repo as modular components: idea generation, scripting, rendering, review, publishing, analytics.
- For approval-first Retention Studio implementations, use a typed side-effect-free core before real I/O: `ContentBrief`, `ScriptDraft`, `VideoCandidate`, review batches, Telegram delivery plans, then shot plans. See `references/approval-first-retention-studio-core.md`.

## Sensitive-content positioning

When AI/productivity automation is the primary brand, be cautious about mixing in religious/FaithTok, health, finance, or other high-trust themes. If the user flags the combination as sensitive, pause that pillar rather than forcing it into the same testbatch. Replace it with a safer adjacent pillar (for example `attention_design`) and document the paused pillar in config so it can be revisited only with explicit approval and a separate brand strategy.

## Pitfalls

- Do not send several generated preview videos as unlabeled media attachments just because they are distinct files. Telegram/mobile previews can make timing-card MP4s look identical. Verify uniqueness (path + title + hash/duration) and provide labels or an indexed summary; if the user complains about duplicate-looking media, stop resending, verify artifacts, and continue the pipeline.
- Do not let final-near preview layers drift apart: if the top field, voiceover, and subtitles do not say the same thing, rebuild the render plan from one final script source before sending another clip.
- Do not make broad-audience AI-system shorts sound like architecture lectures. For early-AI users, convert abstract workflow concepts into concrete everyday failures first, then reveal the principle.
- Do not over-optimize renderer quality before testing whether the content format earns retention.
- Do not keep iterating a polished pilot when the user identifies the core failure as “pretty but semantically weak.” Archive it as a learning case, preserve what worked, and restart with a Proof Short whose first second shows a real visible fail and an immediately useful rule.
- Do not overcorrect from “validate with Proof Shorts” into “never use AI images.” Once the real problem/rule is approved, AI images can legitimately improve perceived quality as text-free atmosphere, backgrounds, keyframes, or thumbnails. Keep factual UI/document/payment layers deterministic; use AI for polish, not truth.
- Do not let German approval previews become unreadable technical cards: use pixel-width-aware wrapping, readable fonts, limited line counts, visual checks for clipped/overcrowded text, and hard mobile safe-zone tests for captions/highlights before delivery.
- Do not confuse approval language with final audience language. For this user, approval previews are German by default; final social videos remain English unless explicitly changed.
- Do not copy public automation workflows wholesale: keep their queue/status/cost tracking and template structure, but remove blind auto-publishing until a human approval/version lock exists.
- Do not mass-generate repetitive shorts without originality/inauthentic-content gates; this can harm monetization/account health and create AI slop.
- Do not jump directly from a script idea to ComfyUI/Wan/Qwen/Image/video generation. First build and inspect the content-to-review spine so weak hooks, generic scripts, policy issues, and static visual concepts are killed before render time.
- Do not assume local Qwen/ComfyUI is the best first image step for every final-near short. If the user permits ChatGPT Image/Codex, use it for text-free scene backgrounds/keyframes when the deterministic renderer owns labels/captions and local GPU should be saved for video/model work. When provider quality matters, verify the actual `image_gen.provider`/model from config and the image cache filenames/metadata rather than guessing; for premium styleframes prefer the highest available reasonable GPT Image tier, but keep fake invoice/email/UI/payment-route mockups deterministic.
- Do not create a parallel candidate path for content experiments; convert content artifacts into the existing candidate factory input so IDs, hashtags, duration classes, quality gates, and pillar/platform validation stay centralized.
- Do not use `x or default` for optional content/script overrides in factories; explicit blank strings and zero durations must pass through to validation so tests can catch them.
- Do not assume TikTok monetization rules match YouTube: TikTok Creator Rewards emphasizes 1min+ eligible videos, while shorter videos may still be better for growth.
- Do not treat a keyframe animatic as a successful Wan/I2V proof. If ComfyUI/Wan I2V fails or history contains no valid video output, label any fallback MP4 as `not_wan` / composition-review-only and block full-final progression.
- Do not treat deterministic layout proofs as the final premium visual style when the user asked for a high-end social-video look. Layouts are for mechanism composition; after approval, use a tightly scoped premium AI styleframe pass with strict negative prompts and verified delivery before endframes/Wan.
- Do not mistake premium abstract glassmorphism for an approved final direction if the user wants a credible everyday work scene. When the user says the motif is still too abstract, switch to real-life work-scene styleframes with laptop/tablet/meeting-room/project-table anchors; keep motion graphics subtle and renderer-owned.
- If the user rejects the production method itself, do not keep iterating content visuals. Reject/audit the proof, run a technical I2V sanity test with a trivial non-content image, and only after it passes generate a small set of styleframes for direction review; see `references/visual-production-reset-i2v-first.md`.
- Do not keep trying blind text-to-video after the user rejects a proof as abstract, dark, generic, or semantically ungrounded. Move to keyframe-first planning, review the keyframes, then run at most one short I2V/first-last-frame proof.
- Do not publish religious or health-adjacent content with overconfident claims; preserve humility, nuance, and platform safety.
- Do not rely on platform payout as the only monetization path; plan indirect monetization such as newsletter, templates, affiliates, digital products, or services.

To view linked files, call skill_view(name, file_path) where file_path is e.g. 'references/api.md' or 'assets/config.yaml'


Explanation:
**Inspecting file paths**

I need to acknowledge that there might be a problem here. The user mentioned an aspect is wrong, which means I might need to inspect the actual file. It seems there could be a recent path that’s unknown to me. Should I use the session search? I notice there’s no prior context in this current session. They referred to an artifact from before, possibly from "M G." I’ll find the recent work with a session search.


[IMPORTANT: You are running as a scheduled cron job. DELIVER...

Subtitle-Sync und Video-Fazit #7

[M G] Die subtitles sind nicht genau gleichzeitig mit dem vo...

[IMPORTANT: The user has invoked the "health-management" ski...

Showing 3 most recent sessions. Use a keyword query to search specific topics.


Question: aspect ratio OR schwarze Balken OR final_near OR subtitles OR video


Question: aspect ratio OR schwarze Balken OR final_near OR subtitles OR video

Summary:
[Raw preview — summarization unavailable]
...[earlier conversation truncated]...

rue, "name": "social-media-shorts-automation", "description": "Design, generate, review, publish, and optimize automated short-form social videos across YouTube Shorts, TikTok, Instagram Reels, and related channels.", "tags": ["shorts", "tiktok", "youtube-shorts", "reels", "creator-monetization", "content-automation", "social-media"], "related_skills": [], "content": "---\nname: social-media-shorts-automation\ndescription: Design, generate, review, publish
…[truncated]

Summary:
[Raw preview — summarization unavailable]
...[earlier conversation truncated]...

 ich bauen:

```text
autoshorts/ideas/factory.py
```

Ziel:

- aus Pillar + Rohidee einen `VideoCandidate` erzeugen
- automatische ID-Generierung
- Standard-Hashtags aus Pillar/Plattform ableiten
- Dauerklasse prüfen:
  - growth short: 20–45s
  - monetization candidate: 60–75s
- Hypothesis erzwingen
- direkt validierten Candidate zurückgeben

Dann können wir aus Content-Strategie tatsächlich Kandidaten erzeugen, statt sie nur manuell zu modellieren.

[USER
…[truncated]

Summary:
[Raw preview — summarization unavailable]
...[earlier conversation truncated]...

plan['id']}-{_slug(plan['title'])}.md\"\n   165|        path.write_text(format_shot_plan(plan), encoding=\"utf-8\")\n   166|        paths.append(path)\n   167|    return paths\n   168|", "total_lines": 167, "file_size": 6678, "truncated": false, "is_binary": false, "is_image": false}

[TOOL]: {"total_count": 15, "files": ["/home/agent/jarvis_runtime/AutoShortsBot/scripts/generate_shot_plans.py", "/home/agent/jarvis_runtime/AutoShortsBot/autoshorts/shot_pla
…[truncated]


Explanation:
**Inspecting repo files**

I need to inspect the files in the repository. My current working directory is hermes-agent, but I think the autos runtime might be relevant too. So, I'll search for recent mp4 files. It makes sense to use the search_files function to do that. Just need to make sure I get the right search parameters to pull up those files efficiently. Let's see what I can find!


Explanation:
**Diagnosing video metadata**

I need to diagnose the video metadata, which involves using the terminal command `ffprobe`. It’s a handy tool for analyzing video files, helping me gather important information about the video’s properties. I’ll run the command to see details such as codec, resolution, frame rate, bit rate, and other relevant data. This will allow me to understand the video file better and address any potential issues. Let’s get started!

terminal

python - <<'PY'
import subprocess, json, pathlib
paths = sorted(pathlib.Path('/home/agent/jarvis_runtime/AutoShortsBot').rglob('*.mp4'), key=lambda p:p.stat().st_mtime, reverse=True)[:12]
for p in paths:
    cmd=['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=width,height,sample_aspect_ratio,display_aspect_ratio','-show_entries','format=duration','-of','json',str(p)]
    data=json.loads(subprocess.check_output(cmd))
    s=data['streams'][0]; dur=float(data.get('format',{}).get('duration',0))
    print(f"{p}\n  {s.get('width')}x{s.get('height')} SAR={s.get('sample_aspect_ratio')} DAR={s.get('display_aspect_ratio')} duration={dur:.2f}s")
PY


Output:
/home/agent/jarvis_runtime/AutoShortsBot/data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_02/seed_303.mp4
  416x736 SAR=None DAR=None duration=5.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_02/seed_202.mp4
  416x736 SAR=None DAR=None duration=5.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_02/seed_101.mp4
  416x736 SAR=None DAR=None duration=5.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_01/seed_303.mp4
  416x736 SAR=None DAR=None duration=5.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_01/seed_202.mp4
  416x736 SAR=None DAR=None duration=5.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_01/seed_101.mp4
  416x736 SAR=None DAR=None duration=5.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/comfyui_outputs/autoshorts_native_wan22_rabbit_i2v_crop_5s_00001_.mp4
  416x736 SAR=None DAR=None duration=4.90s
/home/agent/jarvis_runtime/AutoShortsBot/data/comfyui_outputs/autoshorts_native_wan22_rabbit_i2v_5s_00001_.mp4
  416x736 SAR=None DAR=None duration=4.90s
/home/agent/jarvis_runtime/AutoShortsBot/data/comfyui_outputs/autoshorts_native_wan22_house_jump_5s_00001_.mp4
  416x736 SAR=None DAR=None duration=4.90s
/home/agent/jarvis_runtime/AutoShortsBot/data/comfyui_outputs/autoshorts_wan22_scene01_bright_416x736_00001_.mp4
  416x736 SAR=None DAR=None duration=2.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/comfyui_outputs/autoshorts_wan22_scene01_416x736_tiled_00001_.mp4
  416x736 SAR=None DAR=None duration=2.08s
/home/agent/jarvis_runtime/AutoShortsBot/data/comfyui_outputs/autoshorts_scene01_gpu_480x832_00001_.mp4
  480x832 SAR=None DAR=None duration=2.75s


Explanation:
**Analyzing assembly issues**

The user mentions black bars and squashed height, and they’re asking about the source dimensions. I need to consider if the final assembly is causing black bars due to Telegram. I'll search for final_motion renders to see how they're looking. I think I might need code for assembly that uses the 1080x1920 resolution. Alright, I'll look into options for scaling or padding to fix this issue!


     1|"""Run generated Wan2.2 I2V clip jobs through ComfyUI."""
     2|
     3|from __future__ import annotations
     4|
     5|import json
     6|from datetime import datetime, timezone
     7|from pathlib import Path
     8|from typing import Any
     9|
    10|from autoshorts.i2v_clip_jobs import build_native_wan22_i2v_workflow
    11|
    12|
    13|def _utc_now() -> str:
    14|    return datetime.now(timezone.utc).isoformat()
    15|
    16|
    17|def _empty_summary(total: int) -> dict[str, int]:
    18|    return {"total": total, "succeeded": 0, "skipped": 0, "failed": 0}
    19|
    20|
    21|def _skip_result(job: dict[str, Any], reason: str) -> dict[str, Any]:
    22|    return {
    23|        "job_id": job["job_id"],
    24|        "scene_id": job["scene_id"],
    25|        "seed": job["seed"],
    26|        "status": "skipped",
    27|        "reason": reason,
    28|        "keyframe_path": job["keyframe_path"],
    29|        "output_path": job["output_path"],
    30|    }
    31|
    32|
    33|def _success_result(job: dict[str, Any], client_result: dict[str, Any]) -> dict[str, Any]:
    34|    return {
    35|        "job_id": job["job_id"],
    36|        "scene_id": job["scene_id"],
    37|        "seed": job["seed"],
    38|        "status": "success",
    39|        "prompt_id": client_result.get("prompt_id"),
    40|        "output_path": client_result.get("output_path", job["output_path"]),
    41|    }
    42|
    43|
    44|def _failed_result(job: dict[str, Any], error: Exception | dict[str, Any]) -> dict[str, Any]:
    45|    detail = error if isinstance(error, dict) else {"error": type(error).__name__, "message": str(error)}
    46|    return {
    47|        "job_id": job["job_id"],
    48|        "scene_id": job["scene_id"],
    49|        "seed": job["seed"],
    50|        "status": "failed",
    51|        "detail": detail,
    52|        "keyframe_path": job["keyframe_path"],
    53|        "output_path": job["output_path"],
    54|    }
    55|
    56|
    57|def run_i2v_clip_jobs(
    58|    package: dict[str, Any],
    59|    *,
    60|    client: Any,
    61|    limit: int | None = None,
    62|    dry_run: bool = False,
    63|    poll_seconds: float = 5,
    64|    timeout_seconds: int = 900,
    65|) -> dict[str, Any]:
    66|    """Run clip jobs from a package and return a structured run report."""
    67|    jobs = package.get("jobs", [])[:limit]
    68|    summary = _empty_summary(len(jobs))
    69|    results: list[dict[str, Any]] = []
    70|
    71|    for job in jobs:
    72|        keyframe_path = Path(job["keyframe_path"])
    73|        if not keyframe_path.exists():
    74|            summary["skipped"] += 1
    75|            results.append(_skip_result(job, "missing_keyframe"))
    76|            continue
    77|        if Path(job["output_path"]).exists():
    78|            summary["skipped"] += 1
    79|            results.append(_skip_result(job, "output_exists"))
    80|            continue
    81|        if dry_run:
    82|            summary["skipped"] += 1
    83|            results.append(_skip_result(job, "dry_run_ready"))
    84|            continue
    85|
    86|        workflow = build_native_wan22_i2v_workflow(job, uploaded_image_name=job["remote_image_name"])
    87|        try:
    88|            client_result = client.run_i2v_workflow(
    89|                workflow=workflow,
    90|                keyframe_path=keyframe_path,
    91|                remote_image_name=job["remote_image_name"],
    92|                output_path=Path(job["output_path"]),
    93|                poll_seconds=poll_seconds,
    94|                timeout_seconds=timeout_seconds,
    95|            )
    96|            if client_result.get("status") == "success":
    97|                summary["succeeded"] += 1
    98|                results.append(_success_result(job, client_result))
    99|            else:
   100|                summary["failed"] += 1
   101|                results.append(_failed_result(job, client_result))
   102|        except Exception as exc:  # pragma: no cover - tested through behavior shape, not specific network exception
   103|            summary["failed"] += 1
   104|            results.append(_failed_result(job, exc))
   105|
   106|    return {
   107|        "schema_version": "i2v_run_report.v1",
   108|        "created_at": _utc_now(),
   109|        "video": package.get("video", {}),
   110|        "summary": summary,
   111|        "results": results,
   112|    }
   113|
   114|
   115|def write_run_report(report: dict[str, Any], output_file: Path) -> Path:
   116|    """Write an I2V run report as JSON."""
   117|    output_file.parent.mkdir(parents=True, exist_ok=True)
   118|    output_file.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
   119|    return output_file
   120|


     1|"""Build executable Wan2.2 I2V clip jobs from prompt plans."""
     2|
     3|from __future__ import annotations
     4|
     5|import json
     6|from pathlib import Path
     7|from typing import Any
     8|
     9|
    10|NATIVE_WAN22_CLIENT_ID = "autoshorts-i2v"
    11|
    12|
    13|def _video_slug(prompt_plan: dict[str, Any]) -> str:
    14|    return prompt_plan["video"]["id"]
    15|
    16|
    17|def _scene_keyframe_path(keyframe_root: Path, video_slug: str, scene_id: str) -> Path:
    18|    return keyframe_root / video_slug / f"{scene_id}.png"
    19|
    20|
    21|def _scene_output_path(output_root: Path, video_slug: str, scene_id: str, seed: int) -> Path:
    22|    return output_root / video_slug / scene_id / f"seed_{seed}.mp4"
    23|
    24|
    25|def build_i2v_clip_jobs(
    26|    prompt_plan: dict[str, Any],
    27|    keyframe_root: Path,
    28|    output_root: Path,
    29|    seeds: list[int],
    30|) -> list[dict[str, Any]]:
    31|    """Create seeded clip jobs for each Wan2.2 I2V scene."""
    32|    video_slug = _video_slug(prompt_plan)
    33|    jobs: list[dict[str, Any]] = []
    34|    for scene in prompt_plan["scenes"]:
    35|        for seed in seeds:
    36|            scene_id = scene["scene_id"]
    37|            keyframe_path = _scene_keyframe_path(keyframe_root, video_slug, scene_id)
    38|            output_path = _scene_output_path(output_root, video_slug, scene_id, seed)
    39|            jobs.append(
    40|                {
    41|                    "schema_version": "i2v_clip_job.v1",
    42|                    "job_id": f"{scene_id}_seed_{seed}",
    43|                    "video_id": video_slug,
    44|                    "scene_id": scene_id,
    45|                    "purpose": scene["purpose"],
    46|                    "seed": seed,
    47|                    "status": "ready" if keyframe_path.exists() else "needs_keyframe",
    48|                    "keyframe_path": str(keyframe_path),
    49|                    "output_path": str(output_path),
    50|                    "remote_image_name": f"{video_slug}_{scene_id}.png",
    51|                    "prompt_spec": scene,
    52|                    "review": {
    53|                        "human_review_required": True,
    54|                        "criteria": [
    55|                            "subject clear in first 0.5s",
    56|                            "motion supports retention beat",
    57|                            "no baked text/logos/watermarks",
    58|                            "no distracting deformation/flicker",
    59|                            "clean space remains for captions",
    60|                        ],
    61|                    },
    62|                }
    63|            )
    64|    return jobs
    65|
    66|
    67|def _filename_prefix(job: dict[str, Any]) -> str:
    68|    return f"autoshorts_{job['video_id']}_{job['scene_id']}_seed_{job['seed']}"
    69|
    70|
    71|def build_native_wan22_i2v_workflow(job: dict[str, Any], uploaded_image_name: str) -> dict[str, Any]:
    72|    """Build an API-format native ComfyUI Wan2.2 I2V workflow for a clip job."""
    73|    spec = job["prompt_spec"]
    74|    comfy = spec["comfyui"]
    75|    width = int(comfy["resolution"]["width"])
    76|    height = int(comfy["resolution"]["height"])
    77|    return {
    78|        "1": {
    79|            "class_type": "UNETLoader",
    80|            "inputs": {"unet_name": comfy["model"], "weight_dtype": "default"},
    81|        },
    82|        "2": {
    83|            "class_type": "CLIPLoader",
    84|            "inputs": {"clip_name": comfy["text_encoder"], "type": "wan", "device": "default"},
    85|        },
    86|        "3": {
    87|            "class_type": "CLIPTextEncode",
    88|            "inputs": {"clip": ["2", 0], "text": spec["i2v_motion_prompt"]},
    89|        },
    90|        "4": {
    91|            "class_type": "CLIPTextEncode",
    92|            "inputs": {"clip": ["2", 0], "text": spec["negative_prompt"]},
    93|        },
    94|        "5": {"class_type": "VAELoader", "inputs": {"vae_name": comfy["vae"]}},
    95|        "6": {"class_type": "LoadImage", "inputs": {"image": uploaded_image_name}},
    96|        "7": {
    97|            "class_type": "ImageScale",
    98|            "inputs": {
    99|                "image": ["6", 0],
   100|                "upscale_method": "lanczos",
   101|                "width": width,
   102|                "height": height,
   103|                "crop": "disabled",
   104|            },
   105|        },
   106|        "8": {
   107|            "class_type": "Wan22ImageToVideoLatent",
   108|            "inputs": {
   109|                "vae": ["5", 0],
   110|                "width": width,
   111|                "height": height,
   112|                "length": int(comfy["frames"]),
   113|                "batch_size": 1,
   114|                "start_image": ["7", 0],
   115|            },
   116|        },
   117|        "9": {
   118|            "class_type": "KSampler",
   119|            "inputs": {
   120|                "model": ["1", 0],
   121|                "seed": int(job["seed"]),
   122|                "steps": int(comfy["steps"]),
   123|                "cfg": float(comfy["cfg"]),
   124|                "sampler_name": "uni_pc",
   125|                "scheduler": "simple",
   126|                "positive": ["3", 0],
   127|                "negative": ["4", 0],
   128|                "latent_image": ["8", 0],
   129|                "denoise": 1.0,
   130|            },
   131|        },
   132|        "10": {"class_type": "VAEDecode", "inputs": {"samples": ["9", 0], "vae": ["5", 0]}},
   133|        "11": {"class_type": "CreateVideo", "inputs": {"images": ["10", 0], "fps": float(comfy["fps"])}},
   134|        "12": {
   135|            "class_type": "SaveVideo",
   136|            "inputs": {
   137|                "video": ["11", 0],
   138|                "filename_prefix": _filename_prefix(job),
   139|                "format": "mp4",
   140|                "codec": "h264",
   141|            },
   142|        },
   143|    }
   144|
   145|
   146|def write_i2v_clip_jobs(
   147|    prompt_plan: dict[str, Any],
   148|    output_file: Path,
   149|    keyframe_root: Path,
   150|    generated_clip_root: Path,
   151|    seeds: list[int],
   152|) -> Path:
   153|    """Write a clip-job package JSON."""
   154|    output_file.parent.mkdir(parents=True, exist_ok=True)
   155|    package = {
   156|        "schema_version": "i2v_clip_jobs.v1",
   157|        "video": prompt_plan["video"],
   158|        "strategy": prompt_plan["strategy"],
   159|        "keyframe_root": str(keyframe_root),
   160|        "generated_clip_root": str(generated_clip_root),
   161|        "jobs": build_i2v_clip_jobs(prompt_plan, keyframe_root, generated_clip_root, seeds),
   162|    }
   163|    output_file.write_text(json.dumps(package, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
   164|    return output_file
   165|


Explanation:
**Evaluating image scaling**

I noticed that when using Aha ImageScale, if the source image's aspect ratio isn't exact, it stretches the image to 416x736, which results in a squashed appearance. I wonder if the black bars I see are displayed by ComfyUI. I should check the keyframe dimensions to understand what's going on better. I think using an identify function might help clarify these details. This seems like a technical puzzle to solve!

python - <<'PY'
from PIL import Image
from pathlib import Path
for p in sorted(Path('/home/agent/jarvis_runtime/AutoShortsBot/data/keyframes/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann').glob('*.png')):
    im=Image.open(p)
    print(p.name, im.size, im.size[0]/im.size[1])
PY


Output:
scene_01.png (416, 736) 0.5652173913043478
scene_02.png (416, 736) 0.5652173913043478
variant_1.png (768, 1344) 0.5714285714285714
variant_2.png (768, 1344) 0.5714285714285714
variant_3.png (768, 1344) 0.5714285714285714


Explanation:
**Evaluating video settings**

I’m noticing that with keyframes set for a close of 9:16, my final clips have a ratio of 416/736, which is 0.5652, while 9/16 gives 0.5625. That seems acceptable. I wonder if there are black bars because maybe ComfyUI CreateVideo lacks a display aspect ratio (DAR)? It's possible Telegram is interpreting square pixels. I should visualize this with a screenshot and might need to use ffmpeg to extract a frame for better clarity.

mkdir -p /tmp/autoshorts_aspect_check && for f in data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_01/seed_101.mp4 data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_02/seed_101.mp4; do b=$(basename $(dirname "$f")); ffmpeg -y -hide_banner -loglevel error -i "$f" -vf "select=eq(n\,10)" -frames:v 1 "/tmp/autoshorts_aspect_check/${b}.png"; done
python - <<'PY'
from PIL import Image
for name in ['scene_01.png','scene_02.png']:
    im=Image.open('/tmp/autoshorts_aspect_check/'+name)
    print(name, im.size, im.getbbox())
PY


Output:
scene_01.png (416, 736) (0, 0, 416, 736)
scene_02.png (416, 736) (0, 0, 416, 736)


Explanation:
**Investigating visual details**

I’m thinking I need to take a closer look at the black bars visually. Maybe using vision or some sort of visual inspection could help me see what’s going on with them. There’s definitely something there that I need to explore. I’m curious about if there's a specific way I should approach this observation. It could be important to understand the context or reason for these black bars as well!

Question: Does this frame have black bars at top/bottom or visible aspect ratio squeezing? Describe briefly.


Image loaded into your context — you can see it natively now. Use your built-in vision to answer the user.

Question: Does this frame have black bars at top/bottom or visible aspect ratio squeezing? Describe briefly.


Question: MEDIA OR generated_clips OR seed_101 OR seed_202 OR seed_303 OR hidden-money-systems


Question: MEDIA OR generated_clips OR seed_101 OR seed_202 OR seed_303 OR hidden-money-systems

Summary:
[Raw preview — summarization unavailable]
...[earlier conversation truncated]...

56|\n   157|\n   158|def write_shot_plans(finals: list[dict[str, Any]], output_dir: Path) -> list[Path]:\n   159|    \"\"\"Write one Markdown shot plan per finalized script.\"\"\"\n   160|    output_dir.mkdir(parents=True, exist_ok=True)\n   161|    paths: list[Path] = []\n   162|    for final in finals:\n   163|        plan = build_shot_plan(final)\n   164|        path = output_dir / f\"{plan['id']}-{_slug(plan['title'])}.md\"\n   165|        path.write_t
…[truncated]


mkdir -p data/aspect_fixed/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann
python - <<'PY'
import subprocess, pathlib, json, hashlib
root=pathlib.Path('data/generated_clips/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann')
outroot=pathlib.Path('data/aspect_fixed/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann')
inputs=sorted(root.glob('scene_*/seed_101.mp4'))
# build corrected mobile-safe 1080x1920 versions for the seed_101 proof pair
for src in inputs:
    out=outroot / f'{src.parent.name}_{src.stem}_1080x1920_sar1.mp4'
    vf='scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1,setdar=9/16,format=yuv420p'
    cmd=['ffmpeg','-y','-hide_banner','-loglevel','error','-i',str(src),'-vf',vf,'-c:v','libx264','-preset','veryfast','-crf','18','-movflags','+faststart','-an',str(out)]
    subprocess.check_call(cmd)
    meta=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=width,height,sample_aspect_ratio,display_aspect_ratio','-show_entries','format=duration','-of','json',str(out)]))
    h=hashlib.sha256(out.read_bytes()).hexdigest()[:12]
    s=meta['streams'][0]
    print(f'{out}\n  {s["width"]}x{s["height"]} SAR={s.get("sample_aspect_ratio")} DAR={s.get("display_aspect_ratio")} sha={h}')
PY


Output:
data/aspect_fixed/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_01_seed_101_1080x1920_sar1.mp4
  1080x1920 SAR=1:1 DAR=9:16 sha=73b1b6b50d78
data/aspect_fixed/hidden-money-systems-warum-ein-billiges-auto-teuer-sein-kann/scene_02_seed_101_1080x1920_sar1.mp4
  1080x1920 SAR=1:1 DAR=9:16 sha=031d84d9ee44