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] OK, nächster schritt. Bleib dran unsere Hochwertige content maschine zu bauen.


Question: "content maschine" OR "Content Maschine" OR "shorts" OR "short-form" OR "growth engine"


social-media-shorts-growth-engine

---
name: social-media-shorts-growth-engine
description: Design and operate a growth-oriented short-form video engine for YouTube Shorts, TikTok, Instagram Reels, and adjacent channels, with human approval before posting.
version: 1.0.0
tags: [shorts, tiktok, youtube-shorts, reels, content-strategy, growth, monetization, approval-workflow]
---

# Social-Media Shorts Growth Engine

Use this skill when the user wants to build, improve, or operate an automated/semi-automated system for short-form social media content: YouTube Shorts, TikTok, Instagram Reels, Facebook Reels, Pinterest, LinkedIn video, or similar.

## Core principle

Do **not** treat the task as “make videos.” Treat it as a **growth engine**:

1. Generate many sharply positioned ideas.
2. Score hooks and scripts before rendering.
3. Produce previews.
4. Send the user a review package.
5. Post only after explicit approval.
6. Capture analytics.
7. Feed performance back into the next batch.

A technically correct content generator that produces generic content is failure with extra rendering time. Charming, but still failure.

## Recommended workflow

### 1. Define content pillars

Start with 2–4 pillars, not a vague infinite topic pool. For each pillar define:

- audience
- positioning
- tone
- hook patterns
- visual rules
- no-go topics
- platform fit
- monetization angle

Example pillar structure:

```json
{
  "pillar": "ai_life_systems",
  "positioning": "AI as a servant for ordinary life systems, never as values or authority.",
  "tone": ["clear", "useful", "values-first", "non-hype"],
  "hook_patterns": ["AI is a bad god, but a good servant."],
  "visual_rules": ["screen-recording friendly", "human remains in control"],
  "no_go": ["fake earnings", "overpromising automation"]
}
```

### 2. Build a testbatch before building a full automation platform

For a new channel or unvalidated strategy, create a small batch first:

- 3 ideas per pillar
- 6 short growth candidates, usually 20–45 seconds
- 1–3 monetization-length candidates, usually 60+ seconds where the platform rewards length
- one clear hypothesis per idea

Each idea should include:

- id
- pillar
- title
- platform target
- duration
- hook
- script outline
- visual concept
- caption
- CTA
- quality score
- risk/policy notes

### 3. Add a script quality gate

Before rendering, score each draft for:

- hook strength in the first 1–2 seconds
- novelty / non-generic angle
- emotional pull
- clarity
- retention risk
- comment/share potential
- AI-slop risk
- policy/copyright risk

Render only drafts above the threshold, e.g. 8/10.

### 4. Use a human approval loop

Default to semi-automatic operation first. Send a Telegram review package with:

- preview video or script draft
- pillar and format
- title
- duration
- hook
- caption
- hashtags
- quality score
- policy notes
- suggested platforms

Recommended approval commands:

- `Freigabe alle`
- `Freigabe YouTube`
- `Freigabe TikTok`
- `Freigabe Instagram`
- `Ablehnen`
- `Ändern: <requested change>`

If approval is ambiguous, do not post. Ask once in the project topic.

### 5. Keep platform strategy separate from rendering

Rendering code should not hardcode content strategy. Keep separate config files for:

- niches/pillars
- platforms
- script formats
- visual styles
- approval workflow
- analytics schema

This lets the same renderer support different formats and prevents prompt spaghetti. Prompt spaghetti is still spaghetti even if it is wearing a YAML hat.

## Platform notes

### YouTube Shorts

- Shorts can be vertical or square and up to 3 minutes long.
- YouTube Partner Program Shorts route typically requires 1,000 subscribers and 10M valid public Shorts views in the last 90 days.
- Alternative longform YPP route: 1,000 subscribers and 4,000 valid public watch hours in the last 12 months.
- Shorts views in the Shorts feed do not count toward the 4,000 longform watch hours.
- Practical early growth tests often work best at 20–45 seconds; longer Shorts need a strong story or payoff.

### TikTok

- Creator Rewards availability depends on country/account eligibility.
- TikTok Creator Rewards generally requires a non-business account in good standing, 10,000 followers, and 100,000 authentic views in the last 30 days before joining, subject to country availability and current terms.
- Reward-eligible videos generally need to be at least 1 minute long and meet quality/originality criteria.
- This creates a strategy split:
  - 20–45s for growth and format discovery.
  - 60–75s for monetization candidates once a format works.

### Instagram / Facebook Reels

Useful for republishing 9:16 assets and testing share/save behavior. Treat direct payout as volatile; prefer indirect monetization through audience, affiliate, newsletter, or products.

### LinkedIn / X / Pinterest

Use selectively:

- LinkedIn: AI/productivity/workflows.
- X: AI demos, build-in-public, technical positioning.
- Pinterest: evergreen checklists, routines, faith/life prompts.

## Repository scaffold

A clean shorts-engine repo can start as:

```text
AutoShortsBot/
  autoshorts/
    config/
    ideas/
    scripting/
    rendering/
    review/
    publishing/
    analytics/
  configs/
    niches/
    platforms/
  data/
    drafts/
    performance/
  scripts/
  tests/
  README.md
  .gitignore
  pyproject.toml
```

Never commit:

- `.env`
- OAuth tokens
- API keys
- generated credentials
- rendered videos or large media outputs unless explicitly intended
- raw analytics exports with sensitive account data

## Implementation quality

When coding the engine, prefer TDD for deterministic parts:

- testbatch validation
- duration classification
- review formatting
- analytics import
- approval command parsing
- platform metadata generation

Rendering and external API calls can be integration-tested separately.

## Pitfalls

- **Generic advice content:** “4 tips to be healthier/productive” is usually too weak unless the hook, identity, or story is sharp.
- **AI-image slop:** avoid generated images containing fake UI text, gibberish signs, distorted hands/faces, or abstract generic graphs. These damage trust fast.
- **Too much automation too soon:** validate scripts and formats before building posting APIs.
- **No analytics loop:** producing content without tracking retention, likes, shares, comments, and follows is blind output.
- **Mixed language drift:** decide language per channel or per pillar before rendering. Mixed English/German drafts are fine for ideation, not final voiceover unless intentional.

## References

- `references/autoshortsbot-case-study.md` — case-study details from the AutoShortsBot setup: first testbatch shape, repo scaffold, and approval loop.

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


shortform-growth-automation

---
name: shortform-growth-automation
description: "Design and operate semi-automatic pipelines for YouTube Shorts, TikTok, Instagram Reels, and similar shortform growth: niche strategy, test batches, human review loops, monetization constraints, and analytics feedback."
version: 1.0.0
author: Hermes Agent
license: MIT
metadata:
  hermes:
    tags: [shorts, tiktok, youtube-shorts, instagram-reels, growth, social-media, content-automation, monetization]
    related_skills: [youtube-content, google-workspace, github-repo-management]
---

# Shortform Growth Automation

Use this skill when building, reviewing, or improving systems that generate shortform social-media videos, especially semi-automated pipelines for YouTube Shorts, TikTok, Instagram Reels, Facebook Reels, or repurposed longform content.

## Core principle

Treat the system as a **growth engine**, not merely a video generator. A working renderer is only useful if it produces content with strong hooks, retention, identity, and feedback loops.

## Recommended workflow

1. **Define content pillars**
   - Start with 2-4 clear pillars, not a random topic list.
   - For each pillar define: audience, promise, tone, no-go topics, hook patterns, CTA patterns, visual rules.
   - Prefer identity-rich pillars such as `AI as a servant`, `Faith and focus`, `Life systems for overloaded adults` over generic advice like “health tips”.

2. **Build a test batch before automation**
   - Create a small batch, e.g. 9 ideas: 3 per pillar.
   - Include a mix of short growth candidates and longer monetization candidates.
   - Each idea should include: id, pillar, title, platform target, duration, hook, script outline, visual concept, caption, CTA, quality score, and risk notes.

3. **Score scripts before rendering**
   - Hook in the first 1-2 seconds.
   - Clear emotional or practical pain point.
   - Novelty: avoid “4 tips everyone has heard”.
   - Retention path: pattern interrupt every 2-3 seconds.
   - Comment/share trigger.
   - Platform/policy risk.
   - AI-slop risk: visual gibberish, generic stock-feel, impossible UI/text.

4. **Use a human approval loop first**
   - Semi-automatic beats fully automatic at the start.
   - Send drafts/previews to Telegram with: video or script, title, caption, hashtags, duration, target platforms, quality score, and risk notes.
   - Do not post publicly without explicit approval commands such as `Freigabe alle`, `Freigabe YouTube`, `Freigabe TikTok`, `Ablehnen`, or `Ändern: ...`.

5. **Render only after tone is validated**
   - First validate the script voice and niche fit.
   - Then build rendering templates.
   - Otherwise you risk creating polished clips with mediocre text — a beautifully engineered waste of time.

6. **Close the analytics loop**
   - Store per-video metadata and performance: platform, pillar, format, hook, duration, views after 2h/24h/7d, likes, comments, shares, follows, retention if available.
   - Use this to choose the next batch; do not produce blind forever.

## Platform strategy

- **YouTube Shorts:** good primary channel; supports vertical/square Shorts up to 3 minutes. For growth, test 20-45s and selected 60-75s pieces.
- **TikTok:** growth can come from short videos, but Creator Rewards candidates must be 1 minute or longer. Test both short growth clips and 61-75s monetization candidates.
- **Instagram Reels:** strong secondary distribution for the same approved assets; especially good for lifestyle, faith, and save/share formats.
- **Facebook Reels:** useful later for faith/family/life content and older audiences.
- **LinkedIn:** consider only for AI/productivity content, not general FaithTok unless carefully framed.
- **Pinterest:** useful later for evergreen checklist-style content and indirect monetization.

See `references/platform-monetization.md` for concise platform requirements captured from official sources during setup work.

## Visual rules

- Avoid AI-generated images with readable text, fake app UIs, logos, or interface details; these often produce gibberish and reduce trust.
- Prefer real B-roll, screen recordings, kinetic captions, simple cards, and recurring templates.
- First frame must stop the swipe: large hook text, concrete visual tension, or a recognizable human/scene.
- Keep a consistent brand texture: fonts, caption style, color, recurring intro logic, and thumbnail-like first frame.

## Repo setup pattern

For a new shortform automation repo, scaffold around separable concerns:

```text
autoshorts/
  config/
  ideas/
  scripting/
  rendering/
  review/
  publishing/
  analytics/
configs/
  niches/
  platforms/
data/
  drafts/
  performance/
docs/
tests/
```

Commit configs, validation code, draft JSON, and documentation. Do **not** commit `.env`, OAuth tokens, generated credentials, raw downloaded secrets, or generated media outputs.

See `references/autoshortsbot-initialization.md` for a concrete project bootstrap pattern and testbatch schema.

## Pitfalls

- Generic “tips” content is usually too weak unless it has a sharp hook, specific audience, and strong identity.
- 90-second explainer videos often underperform for new accounts; prefer 20-45s growth tests and selected 61-75s monetization tests.
- Do not optimize only for platform payouts early; first find repeatable follower growth.
- TikTok Creator Rewards eligibility can vary by country/account and should be verified in-app before depending on it.
- Do not auto-post during early exploration; use approval-gated previews until the user trusts the channel voice and quality.


Question: "content maschine" OR "Content Maschine" OR "shorts" OR "short-form" OR "growth engine"

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]

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

stions?\nCreator Rewards Program Terms\n\nLast Update: Apr 2025\n\n\n\n\nWhat is Creator Rewards Program?\n\nCreator Rewards Program is a newly designed rewards feature for creators to monetise their content on TikTok. You can find more information here.\n\nAfter joining Creator Rewards Program and connecting a payment method, you can collect higher Rewards from TikTok for eligible videos of a duration of at least 1 minute. For more information on video el
…[truncated]


Explanation:
**Inspecting memory card status**

I need to figure out the next step. It’s important that I inspect the memory card, along with reviewing the README and the current status. I wonder if there are any issues to address or if everything's working well. By checking those details, I can make sure I'm on the right track. Let's see what's in the README and how the memory card is performing!


     1|# 33 AutoShortsBot
     2|_Last updated: 2026-05-22_
     3|
     4|## Purpose
     5|Durable project card for **AutoShortsBot**: automated creation of social-media shorts.
     6|
     7|## Load when
     8|- Work concerns the AutoShortsBot project, its architecture, code, repository, automations, or content-generation pipeline.
     9|- User asks to continue planning or implementation of automated Social-Media-Shorts generation.
    10|
    11|## Stable facts
    12|- Telegram topic/session: **AutoShortsBot**, `JARVIS Command Center`, thread id `4850`.
    13|- Topic target: `telegram:-1003907117629:4850`.
    14|- User requested that AutoShortsBot project discussion be handled as its own session and answered only in this topic.
    15|- GitHub repository: `https://github.com/Gamexgit/AutoShortsBot`.
    16|- Repository status at project start: empty.
    17|- Future AutoShortsBot code should be stored in this repository.
    18|- Fine-grained GitHub token location: Google Drive file named `Github_AutoShortsBot_Token`.
    19|- Local GitHub token cache: `~/.hermes/secrets/github_autoshortsbot_token` with file mode `0600`; contains the token only, never print it.
    20|- Existing prototype script roots: `~/.hermes/scripts/Auto_Shorts_Bot` and `~/.hermes/scripts/Auto_Video_Bot`.
    21|- Initial content directions from Sir: life optimisation, AI. Christian faith / FaithTok was considered but is paused for now because mixing religion and AI is sensitive.
    22|
    23|## Secret-handling rules
    24|- Do not print, paste, or store the raw token in chat, repo, or memory.
    25|- Retrieve the token only when needed for GitHub operations, use it as an environment variable/runtime secret, and redact command output.
    26|- Never commit credentials, generated secrets, local `.env` files, or token files.
    27|
    28|## Initial project direction
    29|- Build a system for automated creation of Social-Media-Shorts.
    30|- Keep implementation artifacts in the AutoShortsBot GitHub repo once code is created.
    31|


     1|# AutoShortsBot
     2|
     3|AutoShortsBot is a growth-oriented pipeline for creating social-media shorts with a human approval loop.
     4|
     5|## Current phase
     6|
     7|Phase 1 prepares a semi-automatic testbatch workflow:
     8|
     9|1. Generate/curate scripts for three content pillars.
    10|2. Score each idea before rendering.
    11|3. Render previews locally.
    12|4. Send drafts/previews to Telegram for approval.
    13|5. Post manually or semi-automatically only after approval.
    14|6. Capture analytics and feed results back into the next batch.
    15|
    16|## Content pillars
    17|
    18|- `life_optimization` — practical micro-systems for overloaded adults.
    19|- `ai_life_systems` — AI as a servant for better life systems.
    20|- `faithtok` — Christian encouragement for overloaded modern life.
    21|
    22|## First testbatch
    23|
    24|The first batch contains 9 ideas:
    25|
    26|- 3 Life Optimization
    27|- 3 AI Life Systems
    28|- 3 FaithTok
    29|
    30|Most are short growth candidates; selected items are 60+ seconds for TikTok Creator Rewards testing.
    31|
    32|## Secrets
    33|
    34|Do not commit secrets, `.env` files, OAuth tokens, generated credentials, or produced media files. Runtime secrets stay outside the repository.
    35|


     1|[project]
     2|name = "autoshortsbot"
     3|version = "0.1.0"
     4|description = "Growth-oriented pipeline for automated social-media shorts with human approval."
     5|requires-python = ">=3.11"
     6|dependencies = ["Pillow>=10.0"]
     7|
     8|[project.optional-dependencies]
     9|dev = ["pytest>=8.0"]
    10|
    11|[tool.pytest.ini_options]
    12|pythonpath = ["."]
    13|testpaths = ["tests"]
    14|
    15|[tool.ruff]
    16|line-length = 100
    17|target-version = "py311"
    18|


Explanation:
**Planning the next steps**

I need to think about building the next step now that we've generated previews. It seems like sending a preview review package might be a good idea, especially since the user wants me to keep going with the building process. I could implement the Telegram review package generator or look into the analytics schema. Additionally, I should inspect tests to see what’s left on my to-do list.


     1|"""Deterministic preview renderer for AutoShortsBot render manifests.
     2|
     3|This v1 renderer intentionally uses manifest-driven cards/placeholders instead of
     4|AI-generated video. It renders a simple vertical MP4 suitable for timing and
     5|approval review before investing in polished assets.
     6|"""
     7|
     8|from __future__ import annotations
     9|
    10|import shutil
    11|import subprocess
    12|import tempfile
    13|import textwrap
    14|from pathlib import Path
    15|from typing import Any
    16|
    17|from PIL import Image, ImageDraw, ImageFont
    18|
    19|BACKGROUND_BY_TYPE = {
    20|    "kinetic_text": ((19, 23, 38), (79, 70, 229)),
    21|    "screen_recording": ((15, 23, 42), (14, 165, 233)),
    22|    "card_animation": ((17, 24, 39), (245, 158, 11)),
    23|    "stock_broll": ((28, 25, 23), (34, 197, 94)),
    24|    "generated_background": ((24, 24, 27), (168, 85, 247)),
    25|}
    26|
    27|
    28|def _font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
    29|    candidates = [
    30|        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    31|        "/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf",
    32|    ]
    33|    for path in candidates:
    34|        if Path(path).exists():
    35|            return ImageFont.truetype(path, size=size)
    36|    return ImageFont.load_default()
    37|
    38|
    39|def _wrap_text(text: str, width_chars: int) -> str:
    40|    return "\n".join(textwrap.wrap(" ".join(text.split()), width=width_chars))
    41|
    42|
    43|def _text_block_size(draw: ImageDraw.ImageDraw, text: str, font: Any, spacing: int) -> tuple[int, int]:
    44|    lines = text.splitlines() or [""]
    45|    boxes = [draw.textbbox((0, 0), line, font=font) for line in lines]
    46|    width = max((box[2] - box[0] for box in boxes), default=0)
    47|    height = sum(box[3] - box[1] for box in boxes) + spacing * max(0, len(lines) - 1)
    48|    return int(width), int(height)
    49|
    50|
    51|def _fit_text_block(
    52|    draw: ImageDraw.ImageDraw,
    53|    text: str,
    54|    max_width: int,
    55|    max_height: int,
    56|    max_lines: int,
    57|    preferred_size: int,
    58|    min_size: int,
    59|    bold: bool,
    60|) -> dict[str, Any]:
    61|    """Choose a readable font size and wrapping that fits a text box."""
    62|    cleaned = " ".join(text.split())
    63|    for size in range(preferred_size, min_size - 1, -1):
    64|        wrap_chars = max(10, round(max_width / (size * 0.54)))
    65|        wrapped = _wrap_text(cleaned, wrap_chars)
    66|        lines = wrapped.splitlines()
    67|        font = _font(size, bold=bold)
    68|        spacing = max(4, round(size * 0.25))
    69|        block_width, block_height = _text_block_size(draw, wrapped, font, spacing)
    70|        if len(lines) <= max_lines and block_width <= max_width and block_height <= max_height:
    71|            return {
    72|                "text": wrapped,
    73|                "font": font,
    74|                "font_size": size,
    75|                "line_count": len(lines),
    76|                "spacing": spacing,
    77|            }
    78|
    79|    fallback_font = _font(min_size, bold=bold)
    80|    fallback_chars = max(10, round(max_width / (min_size * 0.54)))
    81|    fallback = _wrap_text(cleaned, fallback_chars)
    82|    return {
    83|        "text": fallback,
    84|        "font": fallback_font,
    85|        "font_size": min_size,
    86|        "line_count": len(fallback.splitlines()),
    87|        "spacing": max(4, round(min_size * 0.25)),
    88|    }
    89|
    90|
    91|def _gradient(width: int, height: int, start: tuple[int, int, int], end: tuple[int, int, int]) -> Image.Image:
    92|    image = Image.new("RGB", (width, height), start)
    93|    draw = ImageDraw.Draw(image)
    94|    for y in range(height):
    95|        ratio = y / max(1, height - 1)
    96|        color = tuple(round(start[i] * (1 - ratio) + end[i] * ratio) for i in range(3))
    97|        draw.line([(0, y), (width, y)], fill=color)
    98|    return image
    99|
   100|
   101|def _draw_multiline_center(
   102|    draw: ImageDraw.ImageDraw,
   103|    xy: tuple[int, int],
   104|    text: str,
   105|    font: Any,
   106|    fill: tuple[int, int, int],
   107|    spacing: int = 8,
   108|) -> None:
   109|    lines = text.splitlines()
   110|    line_boxes = [draw.textbbox((0, 0), line, font=font) for line in lines]
   111|    line_heights = [box[3] - box[1] for box in line_boxes]
   112|    total_height = sum(line_heights) + spacing * max(0, len(lines) - 1)
   113|    y = xy[1] - total_height // 2
   114|    for line, box, line_height in zip(lines, line_boxes, line_heights):
   115|        line_width = box[2] - box[0]
   116|        draw.text((xy[0] - line_width // 2, y), line, font=font, fill=fill)
   117|        y += line_height + spacing
   118|
   119|
   120|def _render_scene_image(
   121|    item: dict[str, Any], manifest: dict[str, Any], width: int, height: int
   122|) -> tuple[Image.Image, dict[str, int]]:
   123|    start, end = BACKGROUND_BY_TYPE.get(item["type"], ((24, 24, 27), (64, 64, 64)))
   124|    image = _gradient(width, height, start, end)
   125|    draw = ImageDraw.Draw(image)
   126|
   127|    margin = round(width * 0.075)
   128|    title_font = _font(max(18, round(width * 0.06)), bold=True)
   129|    label_font = _font(max(12, round(width * 0.032)), bold=False)
   130|    small_font = _font(max(12, round(width * 0.034)), bold=False)
   131|
   132|    # Safe area and content card.
   133|    card_top = round(height * 0.18)
   134|    card_bottom = round(height * 0.78)
   135|    draw.rounded_rectangle(
   136|        [margin, card_top, width - margin, card_bottom],
   137|        radius=round(width * 0.04),
   138|        fill=(255, 255, 255),
   139|        outline=(226, 232, 240),
   140|        width=max(2, width // 180),
   141|    )
   142|
   143|    draw.text((margin, round(height * 0.055)), manifest["video"]["id"], font=label_font, fill=(226, 232, 240))
   144|    draw.text((margin, round(height * 0.09)), item["type"].replace("_", " ").upper(), font=title_font, fill=(255, 255, 255))
   145|
   146|    scene_label = item["id"].replace("_", " ").upper()
   147|    draw.text((margin * 1.4, card_top + margin), scene_label, font=small_font, fill=(71, 85, 105))
   148|
   149|    main_fit = _fit_text_block(
   150|        draw,
   151|        item["text"],
   152|        max_width=width - margin * 4,
   153|        max_height=round(height * 0.24),
   154|        max_lines=4,
   155|        preferred_size=max(22, round(width * 0.078)),
   156|        min_size=max(18, round(width * 0.063)),
   157|        bold=True,
   158|    )
   159|    _draw_multiline_center(
   160|        draw,
   161|        (width // 2, round(height * 0.45)),
   162|        main_fit["text"],
   163|        main_fit["font"],
   164|        (15, 23, 42),
   165|        spacing=main_fit["spacing"],
   166|    )
   167|
   168|    retention_fit = _fit_text_block(
   169|        draw,
   170|        item.get("retention_goal", ""),
   171|        max_width=width - margin * 4,
   172|        max_height=round(height * 0.14),
   173|        max_lines=3,
   174|        preferred_size=max(14, round(width * 0.048)),
   175|        min_size=max(12, round(width * 0.041)),
   176|        bold=False,
   177|    )
   178|    _draw_multiline_center(
   179|        draw,
   180|        (width // 2, round(height * 0.69)),
   181|        retention_fit["text"],
   182|        retention_fit["font"],
   183|        (71, 85, 105),
   184|        spacing=retention_fit["spacing"],
   185|    )
   186|
   187|    timing = f"{item['start_ms'] / 1000:.1f}s – {(item['start_ms'] + item['duration_ms']) / 1000:.1f}s"
   188|    draw.text((margin, height - round(height * 0.075)), timing, font=label_font, fill=(226, 232, 240))
   189|    draw.text((width - margin - draw.textlength("PREVIEW", font=label_font), height - round(height * 0.075)), "PREVIEW", font=label_font, fill=(226, 232, 240))
   190|    return image, {
   191|        "main_font_size": main_fit["font_size"],
   192|        "main_line_count": main_fit["line_count"],
   193|        "retention_font_size": retention_fit["font_size"],
   194|        "retention_line_count": retention_fit["line_count"],
   195|    }
   196|
   197|
   198|def build_preview_frames(manifest: dict[str, Any], width: int = 540, height: int = 960) -> list[dict[str, Any]]:
   199|    """Build one representative image per visual timeline item."""
   200|    visual_items = [item for item in manifest["timeline"] if item["track"] == "visual"]
   201|    frames: list[dict[str, Any]] = []
   202|    for item in visual_items:
   203|        image, typography = _render_scene_image(item, manifest, width, height)
   204|        frames.append(
   205|            {
   206|                "scene_id": item["id"],
   207|                "start_ms": item["start_ms"],
   208|                "duration_ms": item["duration_ms"],
   209|                "text": item["text"],
   210|                "typography": typography,
   211|                "image": image,
   212|            }
   213|        )
   214|    return frames
   215|
   216|
   217|def write_frame_images(frames: list[dict[str, Any]], output_dir: Path) -> list[Path]:
   218|    """Write preview frames as numbered PNG files."""
   219|    output_dir.mkdir(parents=True, exist_ok=True)
   220|    paths: list[Path] = []
   221|    for index, frame in enumerate(frames, start=1):
   222|        path = output_dir / f"frame_{index:03d}_{frame['scene_id']}.png"
   223|        frame["image"].save(path)
   224|        paths.append(path)
   225|    return paths
   226|
   227|
   228|def _write_concat_file(frames: list[dict[str, Any]], image_paths: list[Path], concat_path: Path) -> None:
   229|    lines: list[str] = []
   230|    for frame, image_path in zip(frames, image_paths):
   231|        seconds = max(0.5, frame["duration_ms"] / 1000)
   232|        lines.append(f"file '{image_path.as_posix()}'")
   233|        lines.append(f"duration {seconds:.3f}")
   234|    if image_paths:
   235|        lines.append(f"file '{image_paths[-1].as_posix()}'")
   236|    concat_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
   237|
   238|
   239|def render_preview_video(
   240|    manifest: dict[str, Any],
   241|    output_path: Path,
   242|    width: int = 540,
   243|    height: int = 960,
   244|    fps: int = 24,
   245|) -> dict[str, Any]:
   246|    """Render a manifest-driven preview MP4 using Pillow frames and ffmpeg."""
   247|    ffmpeg = shutil.which("ffmpeg")
   248|    if not ffmpeg:
   249|        raise RuntimeError("ffmpeg is required to render preview MP4 files")
   250|
   251|    output_path.parent.mkdir(parents=True, exist_ok=True)
   252|    frames = build_preview_frames(manifest, width=width, height=height)
   253|    with tempfile.TemporaryDirectory(prefix="autoshorts_preview_") as tmp:
   254|        tmp_dir = Path(tmp)
   255|        image_paths = write_frame_images(frames, tmp_dir / "frames")
   256|        concat_path = tmp_dir / "concat.txt"
   257|        _write_concat_file(frames, image_paths, concat_path)
   258|        command = [
   259|            ffmpeg,
   260|            "-y",
   261|            "-f",
   262|            "concat",
   263|            "-safe",
   264|            "0",
   265|            "-i",
   266|            str(concat_path),
   267|            "-vf",
   268|            f"fps={fps},format=yuv420p",
   269|            "-movflags",
   270|            "+faststart",
   271|            str(output_path),
   272|        ]
   273|        completed = subprocess.run(command, check=True, capture_output=True, text=True)
   274|    return {
   275|        "output_path": output_path,
   276|        "frame_count": len(frames),
   277|        "fps": fps,
   278|        "stderr": completed.stderr,
   279|    }
   280|


     1|"""Renderer manifest generation for retention-led AutoShortsBot videos."""
     2|
     3|from __future__ import annotations
     4|
     5|import json
     6|from pathlib import Path
     7|from typing import Any
     8|
     9|from autoshorts.script_drafts import _slug
    10|
    11|RESOLUTION = {"width": 1080, "height": 1920}
    12|ASPECT_RATIO = "9:16"
    13|FPS = 30
    14|
    15|
    16|ASSET_REQUIREMENT_HINTS = {
    17|    "kinetic_text": "Generated by renderer from text and style instructions.",
    18|    "screen_recording": "Needs captured or synthesized vertical screen recording; avoid fake unreadable UI text.",
    19|    "card_animation": "Generated by renderer from concise text cards; animate one idea per beat.",
    20|    "stock_broll": "Needs human/phone/context B-roll; avoid generic corporate stock feel.",
    21|    "generated_background": "Optional abstract background only; must not become the main content.",
    22|}
    23|
    24|
    25|def _duration_ms(start: int, end: int) -> int:
    26|    return max(500, (int(end) - int(start)) * 1000)
    27|
    28|
    29|def _placeholder(asset_type: str, video_id: str, scene: int) -> str:
    30|    return f"placeholder://{video_id}/scene-{scene:02d}/{asset_type}"
    31|
    32|
    33|def _visual_style(scene: dict[str, Any]) -> dict[str, Any]:
    34|    base = {
    35|        "safe_area_pct": 8,
    36|        "font": "bold_sans",
    37|        "caption_case": "sentence",
    38|        "motion": "push_zoom" if scene["scene"] == 1 else "cut_or_slide",
    39|        "contrast": "high",
    40|    }
    41|    if scene["asset_type"] == "card_animation":
    42|        base.update({"layout": "minimal_cards", "max_words_on_screen": 18})
    43|    elif scene["asset_type"] == "screen_recording":
    44|        base.update({"layout": "screen_plus_caption", "blur_sensitive_ui": True})
    45|    elif scene["asset_type"] == "stock_broll":
    46|        base.update({"layout": "broll_under_caption", "pace": "fast_cut"})
    47|    return base
    48|
    49|
    50|def _visual_timeline_items(plan: dict[str, Any]) -> list[dict[str, Any]]:
    51|    video_id = plan["id"]
    52|    items: list[dict[str, Any]] = []
    53|    for scene in plan["scenes"]:
    54|        items.append(
    55|            {
    56|                "id": f"scene_{scene['scene']:02d}",
    57|                "track": "visual",
    58|                "type": scene["asset_type"],
    59|                "asset_ref": _placeholder(scene["asset_type"], video_id, scene["scene"]),
    60|                "start_ms": int(scene["start"]) * 1000,
    61|                "duration_ms": _duration_ms(scene["start"], scene["end"]),
    62|                "text": scene["on_screen_text"],
    63|                "visual_direction": scene["visual_direction"],
    64|                "retention_goal": scene["retention_goal"],
    65|                "style": _visual_style(scene),
    66|            }
    67|        )
    68|    return items
    69|
    70|
    71|def _caption_timeline_items(plan: dict[str, Any]) -> list[dict[str, Any]]:
    72|    beats = plan.get("caption_beats", [])
    73|    total_ms = int(plan["estimated_seconds"]) * 1000
    74|    items: list[dict[str, Any]] = []
    75|    for index, beat in enumerate(beats):
    76|        start_ms = int(beat["start"]) * 1000
    77|        next_start_ms = int(beats[index + 1]["start"]) * 1000 if index + 1 < len(beats) else total_ms
    78|        items.append(
    79|            {
    80|                "id": f"caption_{index + 1:02d}",
    81|                "track": "captions",
    82|                "type": "kinetic_caption",
    83|                "start_ms": start_ms,
    84|                "duration_ms": max(750, next_start_ms - start_ms),
    85|                "text": beat["text"],
    86|                "style": {
    87|                    "safe_area_pct": 8,
    88|                    "position": "lower_third",
    89|                    "max_chars_per_line": 28,
    90|                    "highlight_keywords": True,
    91|                },
    92|            }
    93|        )
    94|    return items
    95|
    96|
    97|def _asset_requirements(plan: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
    98|    requirements: dict[str, list[dict[str, Any]]] = {key: [] for key in ASSET_REQUIREMENT_HINTS}
    99|    for scene in plan["scenes"]:
   100|        asset_type = scene["asset_type"]
   101|        requirements.setdefault(asset_type, []).append(
   102|            {
   103|                "scene": scene["scene"],
   104|                "asset_ref": _placeholder(asset_type, plan["id"], scene["scene"]),
   105|                "brief": scene["visual_direction"],
   106|                "hint": ASSET_REQUIREMENT_HINTS.get(asset_type, "Provide asset matching the visual direction."),
   107|            }
   108|        )
   109|    return requirements
   110|
   111|
   112|def build_render_manifest(plan: dict[str, Any]) -> dict[str, Any]:
   113|    """Convert a human shot plan into a structured renderer contract."""
   114|    timeline = _visual_timeline_items(plan) + _caption_timeline_items(plan)
   115|    track_order = {"visual": 0, "captions": 1}
   116|    timeline.sort(key=lambda item: (item["start_ms"], track_order.get(item["track"], 99), item["id"]))
   117|    return {
   118|        "schema_version": "render_manifest.v1",
   119|        "video": {
   120|            "id": plan["id"],
   121|            "title": plan["title"],
   122|            "pillar": plan["pillar"],
   123|            "duration_ms": int(plan["estimated_seconds"]) * 1000,
   124|            "aspect_ratio": ASPECT_RATIO,
   125|            "resolution": RESOLUTION,
   126|            "fps": FPS,
   127|        },
   128|        "timeline": timeline,
   129|        "asset_requirements": _asset_requirements(plan),
   130|        "render_constraints": {
   131|            "avoid_static_slideshow": True,
   132|            "pattern_interrupt_every_seconds": 3,
   133|            "first_frame_hook_required": True,
   134|            "max_words_per_visual_card": 18,
   135|            "human_approval_required_before_publish": True,
   136|        },
   137|        "production_notes": plan.get("production_notes", []),
   138|    }
   139|
   140|
   141|def write_render_manifests(plans: list[dict[str, Any]], output_dir: Path) -> list[Path]:
   142|    """Write render manifests as pretty JSON files."""
   143|    output_dir.mkdir(parents=True, exist_ok=True)
   144|    paths: list[Path] = []
   145|    for plan in plans:
   146|        manifest = build_render_manifest(plan)
   147|        path = output_dir / f"{plan['id']}-{_slug(plan['title'])}.json"
   148|        path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
   149|        paths.append(path)
   150|    return paths
   151|


     1|import json
     2|from pathlib import Path
     3|
     4|from autoshorts.preview_renderer import (
     5|    build_preview_frames,
     6|    render_preview_video,
     7|    write_frame_images,
     8|)
     9|
    10|
    11|def _manifest() -> dict:
    12|    path = Path("data/render_manifests/testbatch_002_top3/ai-004-stop-asking-ai-to-think-for-you.json")
    13|    return json.loads(path.read_text(encoding="utf-8"))
    14|
    15|
    16|def test_build_preview_frames_creates_one_frame_per_visual_scene():
    17|    manifest = _manifest()
    18|
    19|    frames = build_preview_frames(manifest, width=540, height=960)
    20|
    21|    visual_count = sum(1 for item in manifest["timeline"] if item["track"] == "visual")
    22|    assert len(frames) == visual_count
    23|    assert frames[0]["scene_id"] == "scene_01"
    24|    assert frames[0]["start_ms"] == 0
    25|    assert frames[0]["duration_ms"] > 0
    26|    assert frames[0]["image"].size == (540, 960)
    27|    assert frames[0]["text"] == manifest["timeline"][0]["text"]
    28|
    29|
    30|def test_preview_frames_keep_main_text_readable_and_consistent():
    31|    manifest = _manifest()
    32|
    33|    frames = build_preview_frames(manifest, width=540, height=960)
    34|
    35|    main_sizes = [frame["typography"]["main_font_size"] for frame in frames]
    36|    retention_sizes = [frame["typography"]["retention_font_size"] for frame in frames]
    37|    assert min(main_sizes) >= 34
    38|    assert max(main_sizes) - min(main_sizes) <= 8
    39|    assert min(retention_sizes) >= 22
    40|    assert all(frame["typography"]["main_line_count"] <= 4 for frame in frames)
    41|    assert all(frame["typography"]["retention_line_count"] <= 3 for frame in frames)
    42|
    43|
    44|def test_write_frame_images_outputs_png_contact_sheet_inputs(tmp_path):
    45|    manifest = _manifest()
    46|    frames = build_preview_frames(manifest, width=270, height=480)
    47|
    48|    paths = write_frame_images(frames, tmp_path)
    49|
    50|    assert len(paths) == 5
    51|    assert all(path.suffix == ".png" for path in paths)
    52|    assert paths[0].read_bytes().startswith(b"\x89PNG")
    53|
    54|
    55|def test_render_preview_video_writes_mp4_with_ffmpeg(tmp_path):
    56|    manifest = _manifest()
    57|
    58|    result = render_preview_video(manifest, tmp_path / "preview.mp4", width=270, height=480, fps=12)
    59|
    60|    assert result["output_path"].suffix == ".mp4"
    61|    assert result["output_path"].exists()
    62|    assert result["output_path"].stat().st_size > 1000
    63|    assert result["frame_count"] == 5
    64|


     1|# Telegram Review Loop
     2|
     3|AutoShortsBot is semi-automatic first. No public posting happens without explicit approval.
     4|
     5|## Draft package sent to Telegram
     6|
     7|Each candidate should include:
     8|
     9|- preview video or script draft
    10|- pillar and format
    11|- title
    12|- duration
    13|- hook
    14|- caption
    15|- hashtags
    16|- quality score
    17|- policy notes
    18|- suggested platforms
    19|
    20|## Approval commands
    21|
    22|- `Freigabe alle`
    23|- `Freigabe YouTube`
    24|- `Freigabe TikTok`
    25|- `Freigabe Instagram`
    26|- `Ablehnen`
    27|- `Ändern: <requested change>`
    28|
    29|## Safety rule
    30|
    31|If approval is ambiguous, do not post. Ask once in the AutoShortsBot Telegram topic.
    32|


Explanation:
**Considering review package implementation**

I’m thinking it’d be great to implement a review package generator. It could be useful to send previews too! First, I need to gather the code and run some tests to ensure everything works as planned. Let's take a careful look at the data structure of the final scripts and drafts. I want to make sure every detail is spot on! Let’s get started on this.


     1|{
     2|  "name": "testbatch_002_retention_probe_no_faith",
     3|  "objective": "Test high-retention Life Optimization, AI Life Systems, and Attention Design ideas while pausing religious/FaithTok themes.",
     4|  "approval_mode": "telegram_required_before_posting",
     5|  "research_basis": "docs/retention_research.md",
     6|  "ideas": [
     7|    {
     8|      "id": "life-004",
     9|      "pillar": "life_optimization",
    10|      "title": "You do not need more discipline",
    11|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    12|      "duration_seconds": 38,
    13|      "hook": "You do not need more discipline. You need a smaller first step.",
    14|      "script_outline": "Challenge the discipline myth, show the two-minute starter, give one concrete example, close the loop: action creates clarity, not the other way around.",
    15|      "visual_concept": "Pattern interrupt: messy desk becomes one tiny next action with timer and captions.",
    16|      "caption": "Stop worshipping discipline. Shrink the first step.",
    17|      "cta": "Comment START if you want the template.",
    18|      "quality_score": 10,
    19|      "risk_notes": "No health claims; practical productivity framing."
    20|    },
    21|    {
    22|      "id": "life-005",
    23|      "pillar": "life_optimization",
    24|      "title": "Your to-do list is an anxiety museum",
    25|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    26|      "duration_seconds": 42,
    27|      "hook": "Your to-do list might not be a plan. It might be an anxiety museum.",
    28|      "script_outline": "Turn one overwhelming list into three buckets: do today, schedule later, delete. The payoff is one next action, not a prettier list.",
    29|      "visual_concept": "Before/after: chaotic paper list split into three labelled cards, fast cuts, large captions.",
    30|      "caption": "A list is not a plan until it chooses what you will ignore.",
    31|      "cta": "Which task belongs in delete?",
    32|      "quality_score": 9,
    33|      "risk_notes": "Avoid clinical anxiety language beyond metaphor."
    34|    },
    35|    {
    36|      "id": "life-006",
    37|      "pillar": "life_optimization",
    38|      "title": "The calendar exposes the lie",
    39|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    40|      "duration_seconds": 33,
    41|      "hook": "Your values are not in your notes app. They are in your calendar.",
    42|      "script_outline": "Show the gap between stated priorities and scheduled time. Pick one value, block 20 minutes this week, and protect it like a meeting.",
    43|      "visual_concept": "Calendar screen recording, one red empty week, one protected green block; crisp captions.",
    44|      "caption": "If it matters, it eventually needs a time block.",
    45|      "cta": "What value needs a calendar block this week?",
    46|      "quality_score": 9,
    47|      "risk_notes": "No personal calendar data shown."
    48|    },
    49|    {
    50|      "id": "ai-004",
    51|      "pillar": "ai_life_systems",
    52|      "title": "Stop asking AI to think for you",
    53|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    54|      "duration_seconds": 41,
    55|      "hook": "Stop asking AI to think for you. Ask it to argue with you.",
    56|      "script_outline": "Use AI as a challenger: list assumptions, find weak spots, suggest alternatives, then you decide. Better thinking, not outsourced thinking.",
    57|      "visual_concept": "Screen recording with prompt cards: assumptions, weak spots, alternatives, decision; human checkmark at end.",
    58|      "caption": "AI is more useful as a critic than as a guru.",
    59|      "cta": "Comment CRITIC if you want the prompt.",
    60|      "quality_score": 10,
    61|      "risk_notes": "Keep human decision authority explicit."
    62|    },
    63|    {
    64|      "id": "ai-005",
    65|      "pillar": "ai_life_systems",
    66|      "title": "The 4-box prompt for mental overload",
    67|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    68|      "duration_seconds": 61,
    69|      "hook": "If your brain has 47 tabs open, paste the mess into this 4-box prompt.",
    70|      "script_outline": "Brain dump to AI, ask for four boxes: tasks, worries, decisions, later. Then ask for one next action under two minutes. Show exact prompt structure.",
    71|      "visual_concept": "Before/after screen recording: chaotic paragraph becomes four clean cards; timer starts at the end.",
    72|      "caption": "Do not ask AI for motivation. Ask it for structure.",
    73|      "cta": "Comment RESET and I will turn this into a template.",
    74|      "quality_score": 10,
    75|      "risk_notes": "Not therapy; frame as organisation aid."
    76|    },
    77|    {
    78|      "id": "ai-006",
    79|      "pillar": "ai_life_systems",
    80|      "title": "A real AI assistant needs an approval gate",
    81|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    82|      "duration_seconds": 75,
    83|      "hook": "The most important part of an AI assistant is not the model. It is the approval gate.",
    84|      "script_outline": "Explain memory, tools, draft actions, and human approval before side effects. Show why powerful automation without confirmation becomes risk, not leverage.",
    85|      "visual_concept": "Animated system diagram: request, memory, tools, draft, approval gate, action; red stop line before posting/sending.",
    86|      "caption": "Automation without approval is not intelligence. It is liability.",
    87|      "cta": "Should I build this as a series?",
    88|      "quality_score": 10,
    89|      "risk_notes": "No secrets or real private data in visuals."
    90|    },
    91|    {
    92|      "id": "attention-001",
    93|      "pillar": "attention_design",
    94|      "title": "Your phone wins before breakfast",
    95|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
    96|      "duration_seconds": 36,
    97|      "hook": "If you touch your phone before your feet touch the floor, your day already has an owner.",
    98|      "script_outline": "Show morning phone reflex, then replace it with a 60-second no-input rule: stand up, water, light, one sentence plan.",
    99|      "visual_concept": "Close-up phone alarm, thumb reaches, freeze-frame, hard cut to water/light/notebook; bold captions.",
   100|      "caption": "Your first input shapes your first hour.",
   101|      "cta": "Try the no-input minute tomorrow.",
   102|      "quality_score": 10,
   103|      "risk_notes": "Avoid shame; frame as experiment."
   104|    },
   105|    {
   106|      "id": "attention-002",
   107|      "pillar": "attention_design",
   108|      "title": "The algorithm does not need you happy",
   109|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
   110|      "duration_seconds": 67,
   111|      "hook": "The algorithm does not need you happy. It needs you to stay.",
   112|      "script_outline": "Explain attention incentives without conspiracy. Then give three design moves: greyscale, remove default apps, set a leaving cue before opening feeds.",
   113|      "visual_concept": "Fast phone UI montage, greyscale switch, app removal, timer/leaving cue; not static slideshow.",
   114|      "caption": "Design beats willpower when the feed is engineered better than your intentions.",
   115|      "cta": "Which app gets moved off your home screen today?",
   116|      "quality_score": 10,
   117|      "risk_notes": "Do not imply specific hidden manipulation; speak generally about incentives."
   118|    },
   119|    {
   120|      "id": "attention-003",
   121|      "pillar": "attention_design",
   122|      "title": "The 5-second rule for opening any app",
   123|      "platform_target": ["youtube_shorts", "tiktok", "instagram_reels"],
   124|      "duration_seconds": 31,
   125|      "hook": "Before you open any app, give it a job description.",
   126|      "script_outline": "Pause for five seconds, say why you are opening it, set exit condition, then open. If there is no job, do not hire the app.",
   127|      "visual_concept": "Hand hovers over app, text overlay 'What is the job?', five-second countdown, exit condition card.",
   128|      "caption": "Apps become tools again when they need a job description.",
   129|      "cta": "Comment the app that steals the most time.",
   130|      "quality_score": 9,
   131|      "risk_notes": "No platform attack; behaviour-design framing."
   132|    }
   133|  ]
   134|}
   135|


     1|# Stop asking AI to think for you
     2|
     3|- ID: `ai-004`
     4|- Pillar: `ai_life_systems`
     5|- Target duration: 41s
     6|- Estimated voiceover duration: 43s
     7|- Word count: 104
     8|- Platform note: Growth Short
     9|
    10|## Voiceover
    11|
    12|Stop asking AI to think for you. Ask it to argue with you. Most people use AI like a vending machine: type a question, get a confident answer, move on. That is the weakest use case. Try this instead: paste your idea and ask, what assumptions am I making? What is the weakest part? What would a smart critic disagree with? Now AI is not replacing your thinking. It is putting resistance against lazy thinking. You still decide. You still own the consequence. But you arrive sharper, because the first version had to survive a fight. Comment CRITIC if you want the exact prompt.
    13|
    14|## Caption beats
    15|
    16|- 00s: Stop asking AI to think for you.
    17|- 03s: Ask it to argue with you.
    18|- 06s: Most people use AI like a vending machine: type a question, get a confident answer, move on.
    19|- 09s: That is the weakest use case.
    20|- 12s: Try this instead: paste your idea and ask, what assumptions am I making?
    21|- 15s: What is the weakest part?
    22|- 18s: What would a smart critic disagree with?
    23|- 21s: Now AI is not replacing your thinking.
    24|- 24s: It is putting resistance against lazy thinking.
    25|- 27s: You still decide.
    26|- 30s: You still own the consequence.
    27|- 33s: But you arrive sharper, because the first version had to survive a fight.
    28|- 36s: Comment CRITIC if you want the exact prompt.
    29|
    30|## Visual concept
    31|
    32|Screen recording with prompt cards: assumptions, weak spots, alternatives, decision; human checkmark at end.
    33|
    34|## Caption
    35|
    36|AI is more useful as a critic than as a guru.
    37|
    38|## CTA
    39|
    40|Comment CRITIC if you want the prompt.
    41|
    42|## Production notes
    43|
    44|- First frame must show the hook as large kinetic caption text.
    45|- Use motion or a visual state change in the first 1-2 seconds.
    46|- Avoid static AI slideshow visuals; use screen recordings, cards, timer, or before/after cuts.
    47|- Show the human approval/decision moment; do not imply AI has final authority.
    48|


     1|"""Deterministic voiceover finalizer for curated AutoShortsBot ideas."""
     2|
     3|from __future__ import annotations
     4|
     5|import re
     6|from pathlib import Path
     7|from typing import Any
     8|
     9|from autoshorts.script_drafts import _slug
    10|
    11|TOP3_CUSTOM_VOICEOVERS = {
    12|    "ai-004": """Stop asking AI to think for you. Ask it to argue with you. Most people use AI like a vending machine: type a question, get a confident answer, move on. That is the weakest use case. Try this instead: paste your idea and ask, what assumptions am I making? What is the weakest part? What would a smart critic disagree with? Now AI is not replacing your thinking. It is putting resistance against lazy thinking. You still decide. You still own the consequence. But you arrive sharper, because the first version had to survive a fight. Comment CRITIC if you want the exact prompt.""",
    13|    "ai-005": """If your brain has 47 tabs open, paste the mess into this four-box prompt. Do not ask AI to motivate you. Ask it to sort the noise. First, dump everything: tasks, worries, random reminders, half-decisions, all of it. Then ask AI: split this into four boxes. Box one: tasks I can actually do. Box two: worries I cannot solve right now. Box three: decisions I need to make. Box four: later, not today. Then ask one final question: what is the next action that takes less than two minutes? That is the whole trick. You are not looking for a perfect life plan. You are looking for one clean handle on the chaos. When the output appears, do only the two-minute action first. If it still feels too big, shrink it again. Momentum beats clarity. Comment RESET if you want me to turn this into a copy-paste template.""",
    14|    "attention-002": """The algorithm does not need you happy. It needs you to stay. That does not mean every app is evil. It means the incentives are not the same as yours. You want focus, sleep, actual progress, maybe a quiet brain for once. The feed wants one more swipe. So stop fighting a machine with vibes. Change the design. First, turn your phone to greyscale when you need deep work. Second, remove your worst app from the home screen. Do not delete it if that feels dramatic. Just make it less automatic. Third, before you open a feed, set a leaving cue: one search, three videos, or five minutes. If there is no exit rule, the app owns the exit. This is not about becoming a monk. It is about making your phone slightly less talented at stealing your day. Which app gets moved off your home screen today?""",
    15|}
    16|
    17|
    18|def _word_count(text: str) -> int:
    19|    return len(re.findall(r"\b[\w'-]+\b", text))
    20|
    21|
    22|def _estimate_seconds(word_count: int, words_per_minute: int = 145) -> int:
    23|    return round(word_count / words_per_minute * 60)
    24|
    25|
    26|def _generic_voiceover(idea: dict[str, Any]) -> str:
    27|    """Fallback finalizer for non-custom ideas."""
    28|    return (
    29|        f"{idea['hook']} "
    30|        f"Here is the useful part. {idea['script_outline']} "
    31|        f"Do not turn this into another idea you save and forget. Try the smallest version today. "
    32|        f"{idea['cta']}"
    33|    )
    34|
    35|
    36|def _caption_beats(voiceover: str, duration: int) -> list[dict[str, Any]]:
    37|    sentences = [part.strip() for part in re.split(r"(?<=[.!?])\s+", voiceover) if part.strip()]
    38|    if not sentences:
    39|        return []
    40|    step = max(2, round(duration / len(sentences)))
    41|    beats: list[dict[str, Any]] = []
    42|    current = 0
    43|    for sentence in sentences:
    44|        beats.append({"start": current, "text": sentence})
    45|        current += step
    46|    return beats
    47|
    48|
    49|def _production_notes(idea: dict[str, Any], estimated_seconds: int) -> list[str]:
    50|    notes = [
    51|        "First frame must show the hook as large kinetic caption text.",
    52|        "Use motion or a visual state change in the first 1-2 seconds.",
    53|        "Avoid static AI slideshow visuals; use screen recordings, cards, timer, or before/after cuts.",
    54|    ]
    55|    if estimated_seconds >= 60:
    56|        notes.append("Keep this version above 60 seconds for TikTok Creator Rewards testing.")
    57|    if idea["pillar"] == "ai_life_systems":
    58|        notes.append("Show the human approval/decision moment; do not imply AI has final authority.")
    59|    if idea["pillar"] == "attention_design":
    60|        notes.append("Avoid moral panic; frame as attention design and defaults.")
    61|    return notes
    62|
    63|
    64|def finalize_voiceover(idea: dict[str, Any]) -> dict[str, Any]:
    65|    """Create a final spoken script and production metadata for one idea."""
    66|    voiceover = TOP3_CUSTOM_VOICEOVERS.get(idea["id"], _generic_voiceover(idea)).strip()
    67|    word_count = _word_count(voiceover)
    68|    estimated_seconds = _estimate_seconds(word_count)
    69|    platform_note = "TikTok Rewards Candidate" if int(idea["duration_seconds"]) >= 60 else "Growth Short"
    70|
    71|    return {
    72|        "id": idea["id"],
    73|        "pillar": idea["pillar"],
    74|        "title": idea["title"],
    75|        "target_seconds": int(idea["duration_seconds"]),
    76|        "estimated_seconds": estimated_seconds,
    77|        "platform_note": platform_note,
    78|        "word_count": word_count,
    79|        "voiceover": voiceover,
    80|        "caption_beats": _caption_beats(voiceover, estimated_seconds),
    81|        "visual_concept": idea["visual_concept"],
    82|        "caption": idea["caption"],
    83|        "cta": idea["cta"],
    84|        "production_notes": _production_notes(idea, estimated_seconds),
    85|    }
    86|
    87|
    88|def format_final_script(final: dict[str, Any]) -> str:
    89|    """Format final voiceover package as Markdown."""
    90|    beats = "\n".join(f"- {beat['start']:02d}s: {beat['text']}" for beat in final["caption_beats"])
    91|    notes = "\n".join(f"- {note}" for note in final["production_notes"])
    92|    return f"""# {final['title']}
    93|
    94|- ID: `{final['id']}`
    95|- Pillar: `{final['pillar']}`
    96|- Target duration: {final['target_seconds']}s
    97|- Estimated voiceover duration: {final['estimated_seconds']}s
    98|- Word count: {final['word_count']}
    99|- Platform note: {final['platform_note']}
   100|
   101|## Voiceover
   102|
   103|{final['voiceover']}
   104|
   105|## Caption beats
   106|
   107|{beats}
   108|
   109|## Visual concept
   110|
   111|{final['visual_concept']}
   112|
   113|## Caption
   114|
   115|{final['caption']}
   116|
   117|## CTA
   118|
   119|{final['cta']}
   120|
   121|## Production notes
   122|
   123|{notes}
   124|"""
   125|
   126|
   127|def write_final_scripts(
   128|    batch: dict[str, Any], output_dir: Path, selected_ids: list[str] | None = None
   129|) -> list[Path]:
   130|    """Write final voiceover scripts for selected ideas."""
   131|    selected = set(selected_ids or [])
   132|    output_dir.mkdir(parents=True, exist_ok=True)
   133|    paths: list[Path] = []
   134|    for idea in batch.get("ideas", []):
   135|        if selected and idea["id"] not in selected:
   136|            continue
   137|        final = finalize_voiceover(idea)
   138|        path = output_dir / f"{final['id']}-{_slug(final['title'])}.md"
   139|        path.write_text(format_final_script(final), encoding="utf-8")
   140|        paths.append(path)
   141|    return paths
   142|