Skip to content

Research, brainstorm, and generate viral video content for Instagram, YouTube, X, and TikTok

Python

Initial commit: Proven Viral Content Automation

unknown00705ce45cc1
diff --git a/.agents/rules/repository.md b/.agents/rules/repository.md
new file mode 100644
index 0000000..9b369b9
--- /dev/null
+++ b/.agents/rules/repository.md
@@ -0,0 +1,5 @@
+# Repository rules (Antigravity)
+
+Follow [AGENTS.md](../../AGENTS.md) for all agent behavior in this repository.
+
+Canonical skills live in `.agents/skills/`. Workflows in `.agents/workflows/` provide slash-command entry points.
diff --git a/.agents/skills/brainstorm/SKILL.md b/.agents/skills/brainstorm/SKILL.md
new file mode 100644
index 0000000..12b263f
--- /dev/null
+++ b/.agents/skills/brainstorm/SKILL.md
@@ -0,0 +1,92 @@
+---
+name: brainstorm
+description: >-
+ Interactive brainstorming for viral video content ideas from a project profile.
+ Builds on or diverges from existing content preferences; updates profile only
+ after user confirmation. Use when the user runs /brainstorm.
+disable-model-invocation: true
+---
+
+# Brainstorm
+
+Interactive creative session to develop viral content ideas beyond or alongside research.
+
+## Before you start
+
+1. List projects: `python scripts/profile_store.py list`
+2. If multiple, ask which project.
+3. Load `projects/<slug>/profile.json` and existing ideas in `ideas/`.
+
+## Opening question
+
+If `content_preferences` exist:
+
+> You have **N content preferences** saved. Would you like to:
+> 1. **Similar ideas** — more content like your existing preferences
+> 2. **Different topics** — explore new angles away from current preferences
+> 3. **Mix** — some familiar, some new
+
+If no preferences yet:
+
+> Let's brainstorm! I'll ask a few questions to find angles that fit **[product]** for **[audience]**. Ready?
+
+## Brainstorm flow
+
+Ask adaptive follow-ups (2–4 rounds):
+
+- "What's a pain point your audience feels daily?" (offer 2–3 from profile)
+- "Which platform do you want to prioritize this session?" (from profile platforms)
+- "Any trending topic you want to ride?" (offer to search if unsure)
+- "Fun or serious tone for this batch?" (from positioning)
+
+After each round, propose 2–3 raw ideas. Refine based on reactions.
+
+## Idea format
+
+Each brainstormed idea should include:
+- Title, hook, concept
+- Platform(s) and content_type_id
+- Draft Magic Hour prompt
+- `requires_input` if assets needed
+
+Save drafts to `projects/<slug>/ideas/` with `"status": "draft"` until user approves.
+
+## Update preferences
+
+Before ending, if user expressed clear direction:
+
+> **Existing preferences:**
+> 1. [pref-001] "Prefer transformation hooks..."
+>
+> Should I:
+> - **Update** an existing preference (show before/after)
+> - **Add** a new preference (show text first)
+> - **Skip** — no profile changes
+
+Only persist after explicit confirmation:
+
+```bash
+python scripts/profile_store.py add-preference --slug <slug> --preference "..." --source brainstorm
+```
+
+For updates/replacements:
+
+```bash
+python scripts/profile_store.py update-preference --slug <slug> --id <pref-id> --preference "..."
+```
+
+## After brainstorm
+
+> Brainstorm complete! **N ideas** saved to `projects/<slug>/ideas/`.
+>
+> What next?
+> 1. **Generate content** — `/generate` to create videos
+> 2. **Research more** — `/research-ideas` for data-backed ideas
+> 3. **Keep brainstorming** — another round
+
+## Rules
+
+- Show existing preferences before proposing changes.
+- Never overwrite preferences without confirmation.
+- Respect include/exclude rules.
+- Do not call Magic Hour API during brainstorm.
diff --git a/.agents/skills/generate/SKILL.md b/.agents/skills/generate/SKILL.md
new file mode 100644
index 0000000..8dd60fa
--- /dev/null
+++ b/.agents/skills/generate/SKILL.md
@@ -0,0 +1,143 @@
+---
+name: generate
+description: >-
+ Generate viral video content via Magic Hour text-to-video API. Builds detailed
+ prompts from project ideas, shows best-effort credit estimate, requires spend
+ confirmation, polls job status, and saves outputs. Use when the user runs
+ /generate or wants to create videos from saved ideas.
+disable-model-invocation: true
+---
+
+# Generate Content
+
+Turn saved content ideas into Magic Hour videos.
+
+## Before you start
+
+### 1. Verify API key
+
+```bash
+python scripts/magichour_video.py check-key
+```
+
+If missing, stop and instruct:
+
+> Magic Hour API key not configured. Add to `.env`:
+> ```
+> MAGIC_HOUR_API_KEY=your_key_here
+> ```
+> Get your [Magic Hour](https://manicule.link/srp) API key. Use coupon code **`FIRSTAPI`** for free credits.
+
+Optional: Magic Hour **docs MCP** (`https://docs.magichour.ai/mcp`) helps look up current models/pricing — it does **not** generate videos.
+
+### 2. Select project
+
+`python scripts/profile_store.py list` — ask if multiple.
+
+### 3. Select idea
+
+List ideas in `projects/<slug>/ideas/`. If none, offer to run `/research-ideas` or `/brainstorm` first.
+
+## Generation workflow
+
+```
+Generate Progress:
+- [ ] API key verified
+- [ ] Project + idea selected
+- [ ] Resolve input dependencies
+- [ ] Build detailed prompt
+- [ ] Preview + credit estimate
+- [ ] User confirms spend
+- [ ] Submit API job
+- [ ] Poll + download
+- [ ] Save manifest
+- [ ] Offer generate more
+```
+
+## Build detailed prompt
+
+Expand the idea into a production-ready Magic Hour prompt (1–2000 chars). See [prompt-templates.md](references/prompt-templates.md).
+
+Include:
+- Scene description (subject, action, environment)
+- Camera movement
+- Lighting / mood
+- Style (cinematic, animated, etc.)
+
+Map params from idea or content type defaults. Validate against current model constraints — see [magichour-api.md](references/magichour-api.md).
+
+## Input dependencies
+
+If `requires_input` is non-empty:
+
+> This idea needs: **[logo.png, product-screenshot.png]**. Please add files to `projects/<slug>/input/` and confirm when ready.
+
+For text-to-video, inputs are usually not required. If using image-to-video in future, handle uploads per Magic Hour docs.
+
+## Preview and credit estimate
+
+```bash
+python scripts/magichour_video.py preview \
+ --project <slug> \
+ --idea ideas/<idea-file>.json
+```
+
+Present to user:
+
+> **Generation preview**
+> - Prompt: [truncated prompt]
+> - Model: [model], [duration]s, [aspect_ratio], [resolution], audio: [on/off]
+> - **Credit estimate (best-effort):** ~[X] credits *(final charge may differ after render)*
+> - Source: Magic Hour pricing docs / create response
+>
+> Proceed? This will spend credits. **(yes / no / adjust params)**
+
+**Never submit without explicit yes.**
+
+## Submit generation
+
+```bash
+python scripts/magichour_video.py generate \
+ --project <slug> \
+ --idea ideas/<idea-file>.json \
+ --confirm-spend
+```
+
+Script will:
+1. POST `/v1/text-to-video`
+2. Poll `GET /v1/video-projects/{id}` (~5s intervals, bounded timeout)
+3. Download MP4 to `projects/<slug>/output/<timestamp>/`
+4. Save manifest with prompts, params, credits_charged, download URL
+
+## After generation
+
+> Video saved to `projects/<slug>/output/<timestamp>/output.mp4`
+> Credits charged: **[final]** (initial estimate was **[initial]**)
+>
+> What next?
+> 1. **Generate another** — pick a different idea or tweak this one
+> 2. **Brainstorm more** — `/brainstorm`
+> 3. **Research more** — `/research-ideas`
+
+## Error handling
+
+| Status | Action |
+|--------|--------|
+| 401 | Invalid API key — check `.env` |
+| 402 | Insufficient credits — link to https://magichour.ai/pricing |
+| 422 | Invalid params — adjust model/duration/resolution |
+| Job error | Show error from API; failed jobs are refunded |
+| Timeout | Suggest checking Developer Hub; offer retry |
+
+## Rules
+
+- Always preview before generate.
+- Always require `--confirm-spend` or explicit user yes.
+- Download promptly — URLs expire (~24h).
+- Do not expose API key in logs or manifests.
+- Re-check model capabilities from docs when params fail validation.
+
+## References
+
+- [Prompt templates](references/prompt-templates.md)
+- [Magic Hour API notes](references/magichour-api.md)
diff --git a/.agents/skills/generate/references/magichour-api.md b/.agents/skills/generate/references/magichour-api.md
new file mode 100644
index 0000000..e54411c
--- /dev/null
+++ b/.agents/skills/generate/references/magichour-api.md
@@ -0,0 +1,94 @@
+# Magic Hour API reference (text-to-video)
+
+Source: https://docs.magichour.ai/api-reference/video-projects/text-to-video
+
+**Re-check official docs before each session** — models, durations, and pricing change.
+
+## Endpoints
+
+| Action | Method | URL |
+|--------|--------|-----|
+| Create | POST | `https://api.magichour.ai/v1/text-to-video` |
+| Poll | GET | `https://api.magichour.ai/v1/video-projects/{id}` |
+
+## Authentication
+
+```
+Authorization: Bearer <MAGIC_HOUR_API_KEY>
+Content-Type: application/json
+```
+
+## Create request
+
+```json
+{
+ "name": "My video",
+ "end_seconds": 8,
+ "aspect_ratio": "9:16",
+ "resolution": "720p",
+ "model": "default",
+ "audio": true,
+ "style": {
+ "prompt": "Your detailed visual prompt here"
+ }
+}
+```
+
+## Create response
+
+```json
+{
+ "id": "project-id",
+ "credits_charged": 450
+}
+```
+
+`credits_charged` is an initial estimate; final value after completion may differ.
+
+## Poll response (complete)
+
+Key fields: `status` (`queued` | `rendering` | `complete` | `error` | `canceled`), `credits_charged`, `downloads[].url`, `downloads[].expires_at`.
+
+## Model constraints (verify dynamically)
+
+Models have discrete duration values, not continuous ranges. Examples (Aug 2026):
+
+| Model | Durations | Ratios | Audio |
+|-------|-----------|--------|-------|
+| kling-3.0 | 3–15 | 16:9, 9:16, 1:1 | Extra credits |
+| ltx-2.3 | 1–10, 15, 20, 25, 30 | all three | No extra |
+| sora-2 | 4, 8, 12, 24, 36, 48, 60 | 16:9, 9:16 | No extra |
+
+`default` model varies by account tier.
+
+## Credit estimation
+
+- No official preflight/estimate-only endpoint.
+- Best-effort: use `credits_charged` from create response after submission, or Magic Hour web calculator: https://magichour.ai/api#api-cost-calculator
+- Label all pre-submit estimates as **best-effort**.
+- Failed jobs are refunded.
+
+## Polling guidance
+
+- Interval: ~5 seconds (10s for longer videos)
+- Always set a max timeout (e.g. 10 minutes)
+- Exponential backoff on 429/rate limits
+- Download URLs expire ~24h — download immediately
+
+## MCP (documentation only)
+
+```json
+{
+ "mcpServers": {
+ "Magic Hour": {
+ "url": "https://docs.magichour.ai/mcp"
+ }
+ }
+}
+```
+
+Use MCP to look up current model list and pricing — not for generation.
+
+## SDK alternative
+
+Magic Hour provides SDKs (Python, Node). This project uses direct HTTP via `scripts/magichour_video.py` for zero-dependency portability.
diff --git a/.agents/skills/generate/references/prompt-templates.md b/.agents/skills/generate/references/prompt-templates.md
new file mode 100644
index 0000000..3e9cbd2
--- /dev/null
+++ b/.agents/skills/generate/references/prompt-templates.md
@@ -0,0 +1,45 @@
+# Prompt templates for Magic Hour text-to-video
+
+Prompts must be 1–2000 characters. Describe **visuals**, not editing instructions.
+
+## Short-form hook
+
+```
+[Subject] [action] in [environment]. [Camera movement]. [Lighting/mood].
+Style: [cinematic/animated/documentary]. [Duration]-second clip.
+```
+
+**Example:**
+```
+A laptop screen glows in a dark room as AI-generated video clips appear in rapid
+sequence. Camera slowly pushes in. Neon blue lighting, cyberpunk mood.
+Style: cinematic tech demo. 8-second clip.
+```
+
+## Product demo visual
+
+```
+Clean [product category] visualization: [specific scene showing the feature].
+Smooth [camera type] movement. Bright, modern lighting. Professional SaaS aesthetic.
+```
+
+## Cinematic B-roll
+
+```
+Wide establishing shot of [location/scene]. [Weather/time of day].
+Slow [pan/dolly/tracking] shot. [Color grade description]. No people.
+```
+
+## Meme / reaction backdrop
+
+```
+Exaggerated [emotion] reaction scene: [character/situation].
+Quick zoom, saturated colors, meme-style composition. Humorous tone.
+```
+
+## Tips
+
+- Avoid text overlays in prompt (add in post-production).
+- Specify camera movement — Magic Hour handles motion well.
+- Match duration to platform (see content-types reference).
+- For audio-enabled generations, describe ambient sound context in prompt text.
diff --git a/.agents/skills/onboarding/SKILL.md b/.agents/skills/onboarding/SKILL.md
new file mode 100644
index 0000000..7171e62
--- /dev/null
+++ b/.agents/skills/onboarding/SKILL.md
@@ -0,0 +1,135 @@
+---
+name: onboarding
+description: >-
+ Conversational onboarding for viral content projects. Collects product/service
+ details, audience, features, competitors, positioning, content rules, and
+ Magic Hour content types; creates projects/<slug>/profile.json. Use when the
+ user runs /onboarding or starts a new viral content project.
+disable-model-invocation: true
+---
+
+# Onboarding
+
+Create a new project profile for viral content automation. Be conversational — offer yes/no confirmations and examples from prior answers or website analysis.
+
+## Before you start
+
+1. Check existing projects: `python scripts/profile_store.py list`
+2. If user wants a new project, proceed. If they want to edit an existing one, load that profile instead.
+
+## Workflow
+
+Copy and track:
+
+```
+Onboarding Progress:
+- [ ] i) Product / Service / project (required)
+- [ ] ii) Target audience (optional)
+- [ ] iii) Features or service types (optional)
+- [ ] iv) Competitors (optional)
+- [ ] v) Positioning (optional)
+- [ ] vi) Content exclusions (optional)
+- [ ] vii) Content inclusions (optional)
+- [ ] viii) Content types (required)
+- [ ] Save profile.json
+- [ ] Suggest next step
+```
+
+## Questions (use verbatim wording)
+
+Ask in order. After each answer, summarize and confirm before moving on.
+
+### i) Describe your Product / Service / project or paste your website (required)
+
+If website pasted:
+- Fetch and analyze the site (title, tagline, features, audience signals).
+- Present inferred product description: "Based on [url], your product looks like: **[summary]**. Correct? (yes / edit)"
+- Wait for confirmation or edits.
+
+If no website:
+- Accept freeform description.
+- Ask: "Is this a **product**, **service**, or **project**?" with examples from their description.
+
+### ii) What is your Target audiance? (optional)
+
+If website was analyzed previously:
+- Show: "From your site, your audience looks like: **[inferred]**. Keep this, or describe your target audience?"
+- Offer yes/no to accept inferred audience.
+
+If website not provided:
+- Ask directly with examples tied to their product (e.g. "Solopreneurs posting on TikTok?" / "B2B SaaS founders?").
+
+### iii) What are the Features of the product / project (if product / project selected), Types of services (If services selected) (optional)
+
+If website was analyzed:
+- Show inferred features/services list. "These features stood out: **[list]**. Keep, add, or replace?"
+
+If not:
+- Ask with 2–3 suggested features based on their description.
+
+### iv) What are the competitors (mention website or name) give them the option to research If theyre not sure (optional)
+
+- Accept names/URLs, or "not sure".
+- If not sure: use web search to suggest 3–5 potential competitors. Present as: "**Competitor A** (site) — brief reason. Add any of these? (yes/no/edit)"
+- Do not save competitors until user confirms.
+
+### v) positioning (how do they want to potray their brand) (give few examples like quirky, fun, serious, humorous and based on their website)
+
+If website analyzed:
+- Suggest 2–3 styles from site tone: "Your site feels **[style]**. Pick one: quirky / fun / serious / humorous / select for me"
+
+If not sure:
+- Offer "select for me" — pick the best fit from product + audience and confirm.
+
+### vi) anything that they want to exclude in the content (for example do not talk about competitors or campare competitors)? (optional)
+
+- Give examples from their niche. Accept skip.
+
+### vii) anything they want to include in the content (for example mock compeititors and generate hilarious memes)
+
+- Give examples aligned with positioning. Accept skip.
+
+### viii) Type of content - based on https://docs.magichour.ai/tools/video/text-to-video capablities
+
+- Present content types mapped to platforms and Magic Hour params. See [content-types.md](references/content-types.md).
+- For each selected type, confirm: platform(s), aspect ratio, duration, audio yes/no.
+- Minimum one content type required.
+
+## Save profile
+
+After all questions confirmed:
+
+```bash
+python scripts/profile_store.py create \
+ --name "<Project Name>" \
+ --profile-json /tmp/profile_payload.json
+```
+
+Or write directly to `projects/<slug>/profile.json` following [profile.schema.json](../../schemas/profile.schema.json).
+
+Create project folders:
+- `research/`, `ideas/`, `calendar/`, `input/`, `output/`
+
+Set `schema_version: "1.0.0"`, timestamps in ISO 8601.
+
+## After onboarding
+
+Ask:
+
+> Onboarding complete! Your profile is saved at `projects/<slug>/profile.json`.
+>
+> What would you like next?
+> 1. **Research content ideas** — `/research-ideas` (data-backed viral ideas)
+> 2. **Brainstorm ideas** — `/brainstorm` (interactive creative session)
+
+## Rules
+
+- Never save unconfirmed inferences from website analysis.
+- Keep questions short; embed examples from prior answers.
+- One project folder per completed onboarding.
+- Do not call Magic Hour API during onboarding.
+
+## References
+
+- [Question examples](references/questions.md)
+- [Content type mapping](references/content-types.md)
diff --git a/.agents/skills/onboarding/references/content-types.md b/.agents/skills/onboarding/references/content-types.md
new file mode 100644
index 0000000..83bbb1d
--- /dev/null
+++ b/.agents/skills/onboarding/references/content-types.md
@@ -0,0 +1,57 @@
+# Content types mapped to Magic Hour text-to-video
+
+Source: https://docs.magichour.ai/tools/video/text-to-video
+
+Always verify current model capabilities from official docs before generation. Do not hardcode pricing.
+
+## Platform defaults
+
+| Platform | Aspect ratio | Typical duration | Notes |
+|----------|--------------|------------------|-------|
+| Instagram Reels | 9:16 | 5–15s | Hook in first 3s |
+| TikTok | 9:16 | 5–15s | Trend-native hooks |
+| YouTube Shorts | 9:16 | 5–15s | Clear payoff |
+| YouTube (long) | 16:9 | 10–60s | B-roll / intro clips |
+| X / Twitter | 16:9 or 1:1 | 5–15s | Autoplay-friendly |
+
+## Suggested content types
+
+Present these during onboarding (user picks ≥1):
+
+### 1. short-form-hook
+- **Label:** Short-form hook video (Reels / TikTok / Shorts)
+- **Platforms:** instagram, tiktok, youtube
+- **Magic Hour:** `aspect_ratio: 9:16`, `end_seconds: 5-8`, `audio: true`
+
+### 2. product-demo
+- **Label:** Product demo / feature showcase
+- **Platforms:** youtube, x
+- **Magic Hour:** `aspect_ratio: 16:9`, `end_seconds: 10-15`, `audio: true`
+
+### 3. cinematic-broll
+- **Label:** Cinematic B-roll / mood clip
+- **Platforms:** youtube, instagram
+- **Magic Hour:** `aspect_ratio: 16:9`, `end_seconds: 8-15`, `audio: false`
+
+### 4. meme-reaction
+- **Label:** Meme / reaction-style clip
+- **Platforms:** tiktok, x, instagram
+- **Magic Hour:** `aspect_ratio: 9:16` or `1:1`, `end_seconds: 4-8`, `audio: true`
+
+### 5. testimonial-visual
+- **Label:** Visual backdrop for testimonial / quote
+- **Platforms:** instagram, youtube
+- **Magic Hour:** `aspect_ratio: 9:16`, `end_seconds: 8-12`, `audio: false`
+
+## Model selection guidance
+
+- Use `model: "default"` unless user specifies otherwise.
+- `default` resolves per account tier (check docs at generation time).
+- Enable `audio: true` for social-native content; disable for silent B-roll.
+- Match `end_seconds` to model-specific allowed durations (see Magic Hour API reference).
+
+## Resolution guidance
+
+- Free tier: typically 480p
+- Paid tiers: 720p default; 1080p/4k where model + account allow
+- Recommend 720p for drafts, 1080p for final posts
diff --git a/.agents/skills/onboarding/references/questions.md b/.agents/skills/onboarding/references/questions.md
new file mode 100644
index 0000000..d446d95
--- /dev/null
+++ b/.agents/skills/onboarding/references/questions.md
@@ -0,0 +1,37 @@
+# Onboarding question examples
+
+## Product / website
+
+**User:** "https://magichour.ai"
+
+**Agent:** "Based on magichour.ai, your product looks like an **AI video generation platform** that turns text into professional videos. Correct? (yes / edit)"
+
+## Audience (with website)
+
+**Agent:** "From your site, your audience looks like **creators and marketers who need fast video content**. Keep this? (yes / modify)"
+
+## Features (with website)
+
+**Agent:** "These features stood out: text-to-video, face swap, API access. Keep this list, or add/remove? (keep / edit)"
+
+## Competitors (not sure)
+
+**Agent:** "Not sure about competitors — I can research. Here are 3 possibilities:
+1. **Runway** — AI video editing
+2. **Pika** — text-to-video
+3. **Synthesia** — AI avatars
+
+Add any? (1,2,3 / none / I'll add my own)"
+
+## Positioning
+
+**Agent:** "Your site feels **professional but approachable**. Pick positioning:
+- Quirky
+- Fun ✓ (recommended)
+- Serious
+- Humorous
+- Select for me"
+
+## Content types
+
+**Agent:** "For TikTok/Reels, I'd suggest **9:16 short hooks (5–8s, audio on)**. For YouTube, **16:9 demos (10–15s)**. Use both? (yes / pick one / customize)"
diff --git a/.agents/skills/research-ideas/SKILL.md b/.agents/skills/research-ideas/SKILL.md
new file mode 100644
index 0000000..536fd31
--- /dev/null
+++ b/.agents/skills/research-ideas/SKILL.md
@@ -0,0 +1,122 @@
+---
+name: research-ideas
+description: >-
+ Research viral content ideas from a project profile for Instagram, YouTube,
+ X, and TikTok. Saves dated research and candidate ideas; appends confirmed
+ content preferences to profile.json. Use when the user runs /research-ideas.
+disable-model-invocation: true
+---
+
+# Research Ideas
+
+Perform thorough, source-backed viral content research based on the project profile.
+
+## Before you start
+
+1. List projects: `python scripts/profile_store.py list`
+2. If multiple projects exist, ask which one to research.
+3. Load `projects/<slug>/profile.json`.
+4. Read existing `content_preferences` — avoid duplicating confirmed preferences.
+
+## Workflow
+
+```
+Research Progress:
+- [ ] Select project
+- [ ] Load profile + preferences
+- [ ] Research per content type / platform
+- [ ] Present ideas for feedback
+- [ ] Save research report
+- [ ] Update preferences (if confirmed)
+- [ ] Suggest next step
+```
+
+## Research process
+
+For each selected `content_type` in the profile:
+
+1. **Trend scan** — Search for current viral formats in the niche (web search, platform trends).
+2. **Competitor scan** — If competitors exist, note what formats they use (without violating exclude rules).
+3. **Profile alignment** — Match ideas to audience, positioning, include/exclude rules.
+4. **Magic Hour feasibility** — Each idea must be achievable via text-to-video. See [platform-guide.md](references/platform-guide.md).
+
+Generate **3–5 ideas per content type**, each with:
+- Title
+- Hook (first 3 seconds)
+- Concept (1–2 sentences)
+- Target platform(s)
+- Why it could go viral (1 sentence)
+- Suggested Magic Hour params (aspect_ratio, duration, audio)
+
+## Present ideas
+
+Format as a numbered list. After each batch:
+
+> Do these ideas fit your vision? You can:
+> - **Keep** specific ideas (e.g. "keep 1 and 3")
+> - **Change** an idea (describe what to adjust)
+> - **Reject all** and I'll refine
+
+## Follow-up on feedback
+
+When user likes or changes ideas, ask:
+
+> Should I save this as a **content preference** for future sessions?
+> Example: "Prefer transformation hooks with humor" — save this? (yes / edit / skip)
+
+If yes, show the preference text before saving. Append to `content_preferences` only after confirmation:
+
+```bash
+python scripts/profile_store.py add-preference \
+ --slug <slug> \
+ --preference "<text>" \
+ --source research-ideas \
+ --topics "topic1,topic2"
+```
+
+## Save research
+
+Write dated report to `projects/<slug>/research/YYYY-MM-DD-research.md`.
+
+Save approved ideas as JSON in `projects/<slug>/ideas/`:
+
+```json
+{
+ "id": "idea-001",
+ "title": "...",
+ "hook": "...",
+ "concept": "...",
+ "platforms": ["tiktok"],
+ "content_type_id": "short-form-hook",
+ "magichour_prompt": "...",
+ "magichour_params": { "aspect_ratio": "9:16", "end_seconds": 8, "audio": true },
+ "requires_input": [],
+ "status": "ready",
+ "created_at": "ISO8601"
+}
+```
+
+## After research
+
+Ask:
+
+> Research saved to `projects/<slug>/research/`.
+>
+> What next?
+> 1. **Create content calendar** — I'll draft a posting schedule from these ideas
+> 2. **Generate content** — `/generate` to create videos with Magic Hour
+> 3. **Research more** — different topics or platforms
+> 4. **Brainstorm** — `/brainstorm` for interactive ideation
+
+## Rules
+
+- Cite sources when claiming trends (link or platform name).
+- Respect `content_rules.exclude` — never suggest excluded topics.
+- Emphasize `content_rules.include` when relevant.
+- Do not call Magic Hour API during research.
+- Show existing preferences before proposing new ones that overlap.
+
+## References
+
+- [Platform research guide](references/platform-guide.md)
+- [Source policy](references/source-policy.md)
diff --git a/.agents/skills/research-ideas/references/platform-guide.md b/.agents/skills/research-ideas/references/platform-guide.md
new file mode 100644
index 0000000..26a8bc6
--- /dev/null
+++ b/.agents/skills/research-ideas/references/platform-guide.md
@@ -0,0 +1,36 @@
+# Platform research guide
+
+## Instagram
+
+- **Formats:** Reels (9:16), carousel-to-Reel teasers
+- **Viral patterns:** Before/after, POV, "day in the life", tutorial hooks
+- **Hook window:** 1–3 seconds
+- **Research queries:** `"[niche] instagram reels viral 2026"`, `"[competitor] instagram reels"`
+
+## YouTube
+
+- **Formats:** Shorts (9:16), long-form B-roll, intros
+- **Viral patterns:** Challenge, reaction, "I tried X for 30 days"
+- **Hook window:** 3–5 seconds for Shorts
+- **Research queries:** `"[niche] youtube shorts viral"`, `"[topic] youtube trend"`
+
+## TikTok
+
+- **Formats:** Native vertical video, duet/stitch bait
+- **Viral patterns:** Trending sounds (note: Magic Hour generates video; add audio in post), POV, skits
+- **Hook window:** 1–2 seconds
+- **Research queries:** `"[niche] tiktok viral format"`, `"tiktok [product category] content ideas"`
+
+## X (Twitter)
+
+- **Formats:** 16:9 or 1:1 clips, GIF-style loops
+- **Viral patterns:** Hot takes, demos, meme reactions
+- **Hook window:** Autoplay first frame must intrigue
+- **Research queries:** `"[niche] twitter video viral"`, `"[competitor] x video posts"`
+
+## Magic Hour alignment
+
+Every idea must map to text-to-video:
+- Describe the **visual scene** in the prompt (not editing instructions).
+- Specify aspect ratio and duration per platform.
+- Flag if idea needs external assets (logo, screenshot) → `requires_input: ["logo.png"]`.
diff --git a/.agents/skills/research-ideas/references/source-policy.md b/.agents/skills/research-ideas/references/source-policy.md
new file mode 100644
index 0000000..8321609
--- /dev/null
+++ b/.agents/skills/research-ideas/references/source-policy.md
@@ -0,0 +1,23 @@
+# Research source policy
+
+## Do
+
+- Search the web for current trends (last 3–6 months).
+- Name the platform or publication when citing a trend.
+- Report contradictions ("TikTok favors X, but YouTube Shorts trend Y").
+- Prefer primary sources: platform blogs, creator case studies, competitor public posts.
+
+## Don't
+
+- Invent viral metrics ("this gets 10M views") without a source.
+- Scrape private or paywalled content.
+- Recommend excluded topics from `content_rules.exclude`.
+- Copy competitor content verbatim — adapt formats, not scripts.
+
+## When sources are thin
+
+Say so explicitly: "Limited public trend data for [niche] — these ideas are based on adjacent categories and your profile."
+
+## Saving preferences
+
+Only persist preferences the user explicitly confirms. Show the exact text before writing to `profile.json`.
diff --git a/.agents/workflows/brainstorm.md b/.agents/workflows/brainstorm.md
new file mode 100644
index 0000000..b54c653
--- /dev/null
+++ b/.agents/workflows/brainstorm.md
@@ -0,0 +1,5 @@
+# Brainstorm workflow
+
+Load and execute: `.agents/skills/brainstorm/SKILL.md`
+
+Use `/brainstorm` for interactive content ideation.
diff --git a/.agents/workflows/generate.md b/.agents/workflows/generate.md
new file mode 100644
index 0000000..75548a3
--- /dev/null
+++ b/.agents/workflows/generate.md
@@ -0,0 +1,5 @@
+# Generate workflow
+
+Load and execute: `.agents/skills/generate/SKILL.md`
+
+Use `/generate` to create Magic Hour videos from saved ideas.
diff --git a/.agents/workflows/onboarding.md b/.agents/workflows/onboarding.md
new file mode 100644
index 0000000..ebb9066
--- /dev/null
+++ b/.agents/workflows/onboarding.md
@@ -0,0 +1,7 @@
+# Onboarding workflow
+
+Load and execute the canonical onboarding skill:
+
+`.agents/skills/onboarding/SKILL.md`
+
+Use `/onboarding` to start conversational project setup.
diff --git a/.agents/workflows/research-ideas.md b/.agents/workflows/research-ideas.md
new file mode 100644
index 0000000..5449a94
--- /dev/null
+++ b/.agents/workflows/research-ideas.md
@@ -0,0 +1,5 @@
+# Research ideas workflow
+
+Load and execute: `.agents/skills/research-ideas/SKILL.md`
+
+Use `/research-ideas` for source-backed viral content research.
diff --git a/.claude/skills/brainstorm/SKILL.md b/.claude/skills/brainstorm/SKILL.md
new file mode 100644
index 0000000..2b30090
--- /dev/null
+++ b/.claude/skills/brainstorm/SKILL.md
@@ -0,0 +1,10 @@
+---
+name: brainstorm
+description: >-
+ Claude Code adapter for brainstorm skill. Delegates to canonical skill.
+disable-model-invocation: true
+---
+
+# Brainstorm (Claude Code)
+
+Read and follow: **[.agents/skills/brainstorm/SKILL.md](../../.agents/skills/brainstorm/SKILL.md)**
diff --git a/.claude/skills/generate/SKILL.md b/.claude/skills/generate/SKILL.md
new file mode 100644
index 0000000..5a1d337
--- /dev/null
+++ b/.claude/skills/generate/SKILL.md
@@ -0,0 +1,10 @@
+---
+name: generate
+description: >-
+ Claude Code adapter for generate skill. Delegates to canonical skill.
+disable-model-invocation: true
+---
+
+# Generate (Claude Code)
+
+Read and follow: **[.agents/skills/generate/SKILL.md](../../.agents/skills/generate/SKILL.md)**
diff --git a/.claude/skills/onboarding/SKILL.md b/.claude/skills/onboarding/SKILL.md
new file mode 100644
index 0000000..059c921
--- /dev/null
+++ b/.claude/skills/onboarding/SKILL.md
@@ -0,0 +1,15 @@
+---
+name: onboarding
+description: >-
+ Claude Code adapter for onboarding skill. Delegates to canonical skill at
+ .agents/skills/onboarding/SKILL.md.
+disable-model-invocation: true
+---
+
+# Onboarding (Claude Code)
+
+Read and follow the canonical skill:
+
+**[.agents/skills/onboarding/SKILL.md](../../.agents/skills/onboarding/SKILL.md)**
+
+Load reference files from `.agents/skills/onboarding/references/` as needed.
diff --git a/.claude/skills/research-ideas/SKILL.md b/.claude/skills/research-ideas/SKILL.md
new file mode 100644
index 0000000..27b98d5
--- /dev/null
+++ b/.claude/skills/research-ideas/SKILL.md
@@ -0,0 +1,10 @@
+---
+name: research-ideas
+description: >-
+ Claude Code adapter for research-ideas skill. Delegates to canonical skill.
+disable-model-invocation: true
+---
+
+# Research Ideas (Claude Code)
+
+Read and follow: **[.agents/skills/research-ideas/SKILL.md](../../.agents/skills/research-ideas/SKILL.md)**
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..d78cbda
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,3 @@
+# Magic Hour API key — required for /generate
+# Get yours at https://manicule.link/srp (coupon FIRSTAPI for free credits)
+MAGIC_HOUR_API_KEY=your_api_key_here
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..1123e33
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,31 @@
+# Environment and secrets
+.env
+.env.local
+.env.*.local
+
+# Local user profile (optional per-agent)
+USER.md
+
+# Python
+__pycache__/
+*.py[cod]
+*.egg-info/
+.venv/
+venv/
+.pytest_cache/
+
+# OS / editor
+.DS_Store
+Thumbs.db
+.idea/
+.vscode/settings.json
+
+# Generated project workspaces (user data)
+projects/*/
+!projects/.gitkeep
+!projects/_example/
+
+# Downloaded media and generation artifacts
+**/output/**/*.mp4
+**/output/**/*.webm
+**/output/**/*.mov
diff --git a/.opencode/commands/brainstorm.md b/.opencode/commands/brainstorm.md
new file mode 100644
index 0000000..f960e0a
--- /dev/null
+++ b/.opencode/commands/brainstorm.md
@@ -0,0 +1,5 @@
+---
+description: Interactive brainstorming for viral content
+---
+
+Load and follow `.agents/skills/brainstorm/SKILL.md`.
diff --git a/.opencode/commands/generate.md b/.opencode/commands/generate.md
new file mode 100644
index 0000000..05e132e
--- /dev/null
+++ b/.opencode/commands/generate.md
@@ -0,0 +1,5 @@
+---
+description: Generate videos via Magic Hour text-to-video API
+---
+
+Load and follow `.agents/skills/generate/SKILL.md`.
diff --git a/.opencode/commands/onboarding.md b/.opencode/commands/onboarding.md
new file mode 100644
index 0000000..60880b0
--- /dev/null
+++ b/.opencode/commands/onboarding.md
@@ -0,0 +1,5 @@
+---
+description: Conversational onboarding for viral content projects
+---
+
+Load and follow `.agents/skills/onboarding/SKILL.md`.
diff --git a/.opencode/commands/research-ideas.md b/.opencode/commands/research-ideas.md
new file mode 100644
index 0000000..272f3a1
--- /dev/null
+++ b/.opencode/commands/research-ideas.md
@@ -0,0 +1,5 @@
+---
+description: Research viral content ideas from project profile
+---
+
+Load and follow `.agents/skills/research-ideas/SKILL.md`.
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..fddcdae
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,79 @@
+# Proven Viral Content Automation
+
+research, brainstorm, and generate viral video content for Instagram, YouTube, X, and TikTok
+
+## Quick start
+
+1. Copy `.env.example` to `.env` and set `MAGIC_HOUR_API_KEY` ([Magic Hour](https://manicule.link/srp) — coupon **`FIRSTAPI`** for free credits).
+2. Run `/onboarding` to create a project profile.
+3. Run `/research-ideas` or `/brainstorm` to develop content ideas.
+4. Run `/generate` to create videos via the Magic Hour API.
+
+## Skills
+
+| Skill | Purpose |
+|-------|---------|
+| `/onboarding` | Conversational setup; creates `projects/<slug>/profile.json` |
+| `/research-ideas` | Source-backed viral content research from profile |
+| `/brainstorm` | Interactive ideation; updates content preferences |
+| `/generate` | Detailed prompts + Magic Hour API generation |
+
+## Project layout
+
+Each onboarded project lives in `projects/<unique-slug>/`:
+
+```
+projects/<slug>/
+├── profile.json # Brand profile + content preferences
+├── research/ # Dated research reports
+├── ideas/ # Saved content ideas
+├── calendar/ # Optional content calendar
+├── input/ # User-uploaded images/videos for generation
+└── output/ # Generated videos and manifests
+```
+
+## Python helpers
+
+```bash
+# List projects
+python scripts/profile_store.py list
+
+# Validate a profile
+python scripts/profile_store.py validate projects/<slug>/profile.json
+
+# Preview generation (no API call)
+python scripts/magichour_video.py preview --project <slug> --idea ideas/<file>.json
+
+# Generate (requires --confirm-spend)
+python scripts/magichour_video.py generate --project <slug> --idea ideas/<file>.json --confirm-spend
+```
+
+## Rules for all agents
+
+1. **Read before write** — Load `projects/<slug>/profile.json` before research, brainstorm, or generate.
+2. **Confirm before persist** — Show inferred or proposed values; save only after user confirmation.
+3. **Multi-project** — If multiple projects exist, ask which one to use.
+4. **API key** — Before `/generate`, verify `MAGIC_HOUR_API_KEY` is set. If missing, direct users to [Magic Hour](https://manicule.link/srp) (coupon **`FIRSTAPI`** for free credits).
+5. **Credits** — Show best-effort credit estimate before generation; require explicit spend confirmation.
+6. **MCP is docs-only** — Magic Hour MCP (`https://docs.magichour.ai/mcp`) provides live documentation, not video generation.
+7. **Follow-up routing** — After each skill, suggest the next step:
+ - onboarding → research or brainstorm
+ - research → generate or calendar
+ - brainstorm → generate
+ - generate → generate more
+
+## Cross-agent compatibility
+
+Canonical skills: `.agents/skills/<name>/SKILL.md`
+
+| Agent | Invocation |
+|-------|------------|
+| Cursor | `/onboarding`, `/research-ideas`, `/brainstorm`, `/generate` |
+| Claude Code | Same; skills symlinked in `.claude/skills/` |
+| Codex | `$onboarding`, `$research-ideas`, etc. |
+| Antigravity | Workflows in `.agents/workflows/` |
+| OpenCode | Commands in `.opencode/commands/` |
+| Hermes | Add repo `.agents/skills` to `skills.external_dirs` |
+| OpenClaw | Skills discovered when repo is workspace |
+
+See [docs/setup.md](docs/setup.md) for per-agent setup.
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..43c994c
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fb88718
--- /dev/null
+++ b/README.md
@@ -0,0 +1,71 @@
+# Proven Viral Content Automation
+
+**Research**, **brainstorm**, and **generate** viral video content for Instagram, YouTube, X, and TikTok.
+
+Works with **Cursor**, **Claude Code**, **Codex**, **Antigravity**, **OpenCode**, **Hermes**, and **OpenClaw**.
+
+## What you get
+
+Four conversational skills that guide you from brand setup to published-ready video:
+
+| Skill | What it does |
+|-------|--------------|
+| `/onboarding` | Conversational Q&A → saves `projects/<slug>/profile.json` |
+| `/research-ideas` | Source-backed viral content research per platform |
+| `/brainstorm` | Interactive ideation; updates content preferences |
+| `/generate` | Detailed prompts → Magic Hour API → downloaded MP4 |
+
+## Quick start
+
+```bash
+git clone https://github.com/swaroop2004/Proven-Viral-Content-System.git
+cd Proven-Viral-Content-Automation
+cp .env.example .env
+python scripts/magichour_video.py check-key
+```
+
+Open in your AI agent and run `/onboarding`.
+
+Full setup: **[docs/setup.md](docs/setup.md)**
+
+## Example workflow
+
+```
+/onboarding → /research-ideas → /generate
+/onboarding → /brainstorm → /generate
+/research-ideas → /generate
+/generate → /generate (create more)
+```
+
+## Preview without spending credits
+
+```bash
+python scripts/magichour_video.py preview \
+ --project _example \
+ --idea ideas/idea-001.json
+```
+
+## Project structure
+
+```
+.agents/skills/ # Canonical skills (onboarding, research-ideas, brainstorm, generate)
+.claude/skills/ # Claude Code adapters
+.agents/workflows/ # Antigravity slash workflows
+.opencode/commands/ # OpenCode slash commands
+scripts/ # Python helpers (profile + Magic Hour API)
+projects/ # User project workspaces (gitignored except _example)
+schemas/ # profile.json JSON schema
+docs/ # Setup and compatibility guide
+AGENTS.md # Persistent agent instructions
+```
+
+## Magic Hour
+
+Get your [Magic Hour](https://manicule.link/srp) API key for video generation. Use coupon code **`FIRSTAPI`** for free credits.
+
+- Copy the key into `.env` as `MAGIC_HOUR_API_KEY`
+- **Docs MCP** (optional, documentation only): `https://docs.magichour.ai/mcp`
+
+## License
+
+MIT — Free to use and distribute
diff --git a/docs/setup.md b/docs/setup.md
new file mode 100644
index 0000000..5e1f402
--- /dev/null
+++ b/docs/setup.md
@@ -0,0 +1,224 @@
+# Setup Guide
+
+Complete setup for **Proven Viral Content Automation** across supported AI coding agents.
+
+## Prerequisites
+
+| Requirement | Notes |
+|-------------|-------|
+| **Python 3.10+** | For profile and generation helpers |
+| **Magic Hour API key** | Required for `/generate` — [Magic Hour](https://manicule.link/srp) (coupon **`FIRSTAPI`** for free credits) |
+| **Git** | Clone this repository |
+
+No pip dependencies — helpers use Python standard library only.
+
+## 1. Clone and configure
+
+```bash
+git clone <your-repo-url>
+cd Proven-Viral-Content-Automation
+cp .env.example .env # Windows: copy .env.example .env
+```
+
+Edit `.env`:
+
+```
+MAGIC_HOUR_API_KEY=your_actual_key_here
+```
+
+Get your key from [Magic Hour](https://manicule.link/srp). Use coupon code **`FIRSTAPI`** for free credits.
+
+Verify:
+
+```bash
+python scripts/magichour_video.py check-key
+```
+
+## 2. Explore the example project
+
+An example profile and idea ship with the repo:
+
+```
+projects/_example/
+├── profile.json
+└── ideas/idea-001.json
+```
+
+Preview generation (no API call, no credits):
+
+```bash
+python scripts/magichour_video.py preview --project _example --idea ideas/idea-001.json
+```
+
+## 3. Run your first workflow
+
+Open the repo in your AI agent and run:
+
+1. **`/onboarding`** — create your brand profile
+2. **`/research-ideas`** or **`/brainstorm`** — develop content ideas
+3. **`/generate`** — create videos (requires API key + spend confirmation)
+
+---
+
+## Per-agent setup
+
+### Cursor
+
+Skills in `.agents/skills/` are discovered automatically.
+
+```
+/onboarding
+/research-ideas
+/brainstorm
+/generate
+```
+
+Optional: add Magic Hour **docs MCP** in Cursor MCP settings:
+
+```json
+{
+ "mcpServers": {
+ "Magic Hour": {
+ "url": "https://docs.magichour.ai/mcp"
+ }
+ }
+}
+```
+
+This provides live API documentation — **not video generation**.
+
+### Claude Code
+
+1. Open repo root.
+2. `CLAUDE.md` imports `AGENTS.md` automatically.
+3. Skills available via `.claude/skills/` adapters → canonical `.agents/skills/`.
+
+```bash
+/onboarding
+```
+
+Add docs MCP:
+
+```bash
+claude mcp add --transport http MagicHour https://docs.magichour.ai/mcp
+```
+
+### OpenAI Codex
+
+1. Open repo root — Codex reads `AGENTS.md`.
+2. Skills discovered from `.agents/skills/`.
+3. Invoke with `$onboarding`, `$research-ideas`, `$brainstorm`, `$generate`.
+
+### Google Antigravity
+
+1. Open repo root.
+2. Rules: `.agents/rules/repository.md` → `AGENTS.md`.
+3. Workflows: `.agents/workflows/*.md` for slash commands.
+4. Skills: `.agents/skills/`.
+
+### OpenCode
+
+1. Open repo root — reads `AGENTS.md`.
+2. Slash commands: `.opencode/commands/*.md`.
+3. Skills also available via native skill tool from `.agents/skills/`.
+
+### Hermes Agent
+
+Add this repo's skills directory to `~/.hermes/config.yaml`:
+
+```yaml
+skills:
+ external_dirs:
+ - /absolute/path/to/Proven-Viral-Content-Automation/.agents/skills
+```
+
+Persistent instructions: Hermes reads `AGENTS.md` from the repo.
+
+### OpenClaw
+
+Set this repository as your OpenClaw workspace. Skills discovered from `.agents/skills/` (or `skills/` with higher precedence).
+
+Workspace files: `AGENTS.md` loaded automatically.
+
+---
+
+## Magic Hour integration
+
+Get your [Magic Hour](https://manicule.link/srp) API key to enable `/generate`. Use coupon code **`FIRSTAPI`** for free credits.
+
+### API (required for generation)
+
+| Endpoint | Purpose |
+|----------|---------|
+| `POST /v1/text-to-video` | Create video job |
+| `GET /v1/video-projects/{id}` | Poll status + download URL |
+
+Generation flow:
+
+```bash
+# Preview (free)
+python scripts/magichour_video.py preview --project <slug> --idea ideas/<file>.json
+
+# Generate (billable — requires confirmation flag)
+python scripts/magichour_video.py generate --project <slug> --idea ideas/<file>.json --confirm-spend
+```
+
+### MCP (optional — documentation only)
+
+The official Magic Hour MCP server exposes **documentation**, not generation APIs.
+
+Use it when you need current model lists, parameter constraints, or pricing docs during a session.
+
+**Do not** configure MCP as a substitute for `MAGIC_HOUR_API_KEY`.
+
+---
+
+## Project data layout
+
+```
+projects/<slug>/
+├── profile.json # Brand profile + content preferences
+├── research/ # Dated research reports (.md)
+├── ideas/ # Content ideas (.json)
+├── calendar/ # Optional posting calendar
+├── input/ # User assets (logos, screenshots)
+└── output/ # Generated videos + manifests
+ └── 20260808T120000Z/
+ ├── manifest.json
+ └── output.mp4
+```
+
+User project folders (except `_example`) are gitignored by default.
+
+---
+
+## Troubleshooting
+
+| Issue | Fix |
+|-------|-----|
+| `MAGIC_HOUR_API_KEY is not configured` | Copy `.env.example` → `.env`, get key from [Magic Hour](https://manicule.link/srp) (coupon **`FIRSTAPI`**) |
+| `401 Unauthorized` | Invalid or expired API key |
+| `402 Payment Required` | Insufficient credits — [add credits](https://magichour.ai/pricing) |
+| `422 Unprocessable` | Invalid model/duration/resolution combo — check Magic Hour docs |
+| `end_seconds not supported` | Pick a duration allowed for the selected model |
+| `Refusing to generate without --confirm-spend` | Agent must get your explicit yes before calling generate |
+| Skills not found | Ensure repo root is workspace; check `.agents/skills/` exists |
+| Windows path issues | Use forward slashes in commands; avoid symlinks |
+
+---
+
+## Privacy
+
+- `.env` and user `projects/*/` data stay local (gitignored).
+- Never commit API keys.
+- Website analysis during onboarding uses public page content only.
+- Generation manifests exclude the API key.
+
+---
+
+## Credit usage transparency
+
+- There is **no estimate-only API**. Pre-generation estimates are labeled **best-effort**.
+- Initial credits appear in the create response; final credits may differ after render.
+- Failed jobs are refunded per Magic Hour policy.
+- Use the [API cost calculator](https://magichour.ai/api#api-cost-calculator) for planning.
diff --git a/projects/.gitkeep b/projects/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/projects/_example/ideas/idea-001.json b/projects/_example/ideas/idea-001.json
new file mode 100644
index 0000000..f7df9c9
--- /dev/null
+++ b/projects/_example/ideas/idea-001.json
@@ -0,0 +1,19 @@
+{
+ "id": "idea-001",
+ "title": "Text to video in 60 seconds",
+ "hook": "I typed one sentence and got this video.",
+ "concept": "Screen-style reveal: prompt appears on screen, then cuts to a cinematic AI-generated clip that matches the prompt. End card: Magic Hour logo + CTA.",
+ "platforms": ["instagram", "tiktok"],
+ "content_type_id": "short-form-hook",
+ "magichour_prompt": "Cinematic tracking shot through a neon-lit city at night, rain reflections on wet pavement, cyberpunk atmosphere, smooth camera movement, 8 seconds",
+ "magichour_params": {
+ "aspect_ratio": "9:16",
+ "end_seconds": 8,
+ "resolution": "720p",
+ "model": "default",
+ "audio": true
+ },
+ "requires_input": [],
+ "status": "ready",
+ "created_at": "2026-08-08T00:00:00Z"
+}
diff --git a/projects/_example/output/sample-preview-manifest.json b/projects/_example/output/sample-preview-manifest.json
new file mode 100644
index 0000000..28831ff
--- /dev/null
+++ b/projects/_example/output/sample-preview-manifest.json
@@ -0,0 +1,22 @@
+{
+ "mode": "preview",
+ "note": "Sample manifest — preview mode does not call the API or spend credits",
+ "project_slug": "_example",
+ "idea_path": "projects/_example/ideas/idea-001.json",
+ "request": {
+ "name": "Text to video in 60 seconds",
+ "end_seconds": 8,
+ "aspect_ratio": "9:16",
+ "resolution": "720p",
+ "model": "default",
+ "audio": true,
+ "style": {
+ "prompt": "Cinematic tracking shot through a neon-lit city at night..."
+ }
+ },
+ "credit_estimate": {
+ "value": null,
+ "confidence": "unknown",
+ "note": "Run generate with --confirm-spend to receive initial credits_charged from API"
+ }
+}
diff --git a/projects/_example/profile.json b/projects/_example/profile.json
new file mode 100644
index 0000000..7bdbc77
--- /dev/null
+++ b/projects/_example/profile.json
@@ -0,0 +1,82 @@
+{
+ "schema_version": "1.0.0",
+ "project_slug": "_example",
+ "project_name": "Magic Hour Demo",
+ "created_at": "2026-08-08T00:00:00Z",
+ "updated_at": "2026-08-08T00:00:00Z",
+ "product": {
+ "description": "Magic Hour is an AI video generation platform that turns text prompts into professional videos in seconds.",
+ "type": "product",
+ "website_url": "https://magichour.ai",
+ "website_analysis": {
+ "inferred_audience": "Creators, marketers, and solopreneurs who need fast video content",
+ "inferred_positioning": "Professional, accessible, speed-focused"
+ }
+ },
+ "target_audience": "Solopreneurs and indie creators who want to post consistently on social without a video team",
+ "features_or_services": [
+ "Text-to-video generation",
+ "Multiple AI models (Kling, Veo, Sora, etc.)",
+ "API access for automation",
+ "Face swap and image-to-video tools"
+ ],
+ "competitors": [
+ {
+ "name": "Runway",
+ "website_url": "https://runwayml.com",
+ "researched": false
+ },
+ {
+ "name": "Pika",
+ "website_url": "https://pika.art",
+ "researched": false
+ }
+ ],
+ "positioning": {
+ "style": "fun",
+ "tone_notes": "Confident but approachable; show results fast",
+ "user_selected": true
+ },
+ "content_rules": {
+ "exclude": ["Direct competitor bashing", "Unverified performance claims"],
+ "include": ["Before/after transformations", "Speed demos", "Creator success stories"]
+ },
+ "platforms": ["instagram", "youtube", "tiktok", "x"],
+ "content_types": [
+ {
+ "id": "short-form-hook",
+ "label": "Short-form hook video (Reels / TikTok / Shorts)",
+ "platforms": ["instagram", "tiktok", "youtube"],
+ "magichour": {
+ "aspect_ratio": "9:16",
+ "end_seconds": 8,
+ "resolution": "720p",
+ "model": "default",
+ "audio": true
+ }
+ },
+ {
+ "id": "product-demo",
+ "label": "Product demo / feature showcase",
+ "platforms": ["youtube", "x"],
+ "magichour": {
+ "aspect_ratio": "16:9",
+ "end_seconds": 15,
+ "resolution": "1080p",
+ "model": "default",
+ "audio": true
+ }
+ }
+ ],
+ "content_preferences": [
+ {
+ "id": "pref-001",
+ "source": "research-ideas",
+ "created_at": "2026-08-08T00:00:00Z",
+ "preference": "Prefer transformation/reveal formats with a strong 3-second hook",
+ "topics": ["AI video creation", "solopreneur productivity"],
+ "formats": ["before-after", "speed-run demo"],
+ "notes": "User confirmed during research session"
+ }
+ ]
+}
diff --git a/projects/_example/research/2026-08-08-research.md b/projects/_example/research/2026-08-08-research.md
new file mode 100644
index 0000000..d07d410
--- /dev/null
+++ b/projects/_example/research/2026-08-08-research.md
@@ -0,0 +1,26 @@
+# Research Report — 2026-08-08
+
+Project: Magic Hour Demo (`_example`)
+
+## Short-form hook (Reels / TikTok / Shorts)
+
+### Idea 1: Text to video in 60 seconds
+- **Hook:** "I typed one sentence and got this video."
+- **Concept:** Prompt on screen → cut to cinematic AI clip → CTA
+- **Why viral:** Speed demos perform well in creator tool niches
+- **Sources:** Adjacent category — AI tool demo trends on TikTok 2026
+
+### Idea 2: Before/after content quality
+- **Hook:** "My old B-roll vs Magic Hour B-roll"
+- **Concept:** Split-screen comparison of stock footage vs AI-generated scene
+- **Why viral:** Transformation format drives shares
+
+## Product demo (YouTube / X)
+
+### Idea 3: API in 3 lines of code
+- **Hook:** "Generate video from Python in 3 lines"
+- **Concept:** Terminal recording + generated clip intercut
+- **Why viral:** Developer audience on X engages with minimal-code demos
+
+## Saved preferences
+- User prefers transformation/reveal formats with strong 3-second hooks
diff --git a/schemas/profile.schema.json b/schemas/profile.schema.json
new file mode 100644
index 0000000..b79f02b
--- /dev/null
+++ b/schemas/profile.schema.json
@@ -0,0 +1,178 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "https://github.com/magichour/proven-viral-content-automation/schemas/profile.schema.json",
+ "title": "Viral Content Project Profile",
+ "description": "Persistent brand and content profile created by /onboarding and updated by /research-ideas and /brainstorm",
+ "type": "object",
+ "required": ["schema_version", "project_slug", "created_at", "updated_at", "product", "content_types"],
+ "additionalProperties": false,
+ "properties": {
+ "schema_version": {
+ "type": "string",
+ "const": "1.0.0"
+ },
+ "project_slug": {
+ "type": "string",
+ "pattern": "^_?[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "description": "Unique folder name under projects/"
+ },
+ "project_name": {
+ "type": "string",
+ "description": "Human-readable project name"
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "product": {
+ "type": "object",
+ "required": ["description", "type"],
+ "additionalProperties": false,
+ "properties": {
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Product, service, or project description"
+ },
+ "type": {
+ "type": "string",
+ "enum": ["product", "service", "project", "other"]
+ },
+ "website_url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "website_analysis": {
+ "type": "object",
+ "additionalProperties": true,
+ "description": "Agent-inferred facts from website (for confirmation only)"
+ }
+ }
+ },
+ "target_audience": {
+ "type": "string",
+ "description": "Target audience description"
+ },
+ "features_or_services": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "Product features or service types"
+ },
+ "competitors": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["name"],
+ "additionalProperties": false,
+ "properties": {
+ "name": { "type": "string" },
+ "website_url": { "type": "string", "format": "uri" },
+ "notes": { "type": "string" },
+ "researched": { "type": "boolean", "default": false }
+ }
+ }
+ },
+ "positioning": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "style": {
+ "type": "string",
+ "description": "e.g. quirky, fun, serious, humorous"
+ },
+ "tone_notes": { "type": "string" },
+ "user_selected": { "type": "boolean" }
+ }
+ },
+ "content_rules": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "exclude": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "Topics or approaches to avoid"
+ },
+ "include": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "Topics or approaches to emphasize"
+ }
+ }
+ },
+ "platforms": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": ["instagram", "youtube", "x", "tiktok"]
+ },
+ "uniqueItems": true
+ },
+ "content_types": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "required": ["id", "label", "platforms"],
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "string" },
+ "label": { "type": "string" },
+ "platforms": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": ["instagram", "youtube", "x", "tiktok"]
+ }
+ },
+ "magichour": {
+ "type": "object",
+ "description": "Suggested Magic Hour parameters for this content type",
+ "additionalProperties": true,
+ "properties": {
+ "aspect_ratio": { "type": "string", "enum": ["16:9", "9:16", "1:1"] },
+ "end_seconds": { "type": "number" },
+ "resolution": { "type": "string" },
+ "model": { "type": "string" },
+ "audio": { "type": "boolean" }
+ }
+ }
+ }
+ }
+ },
+ "content_preferences": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["id", "source", "created_at", "preference"],
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "string" },
+ "source": {
+ "type": "string",
+ "enum": ["research-ideas", "brainstorm", "onboarding"]
+ },
+ "created_at": { "type": "string", "format": "date-time" },
+ "preference": { "type": "string" },
+ "topics": {
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "formats": {
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "notes": { "type": "string" }
+ }
+ }
+ },
+ "onboarding_notes": {
+ "type": "string",
+ "description": "Optional freeform notes from onboarding"
+ }
+ }
+}
diff --git a/scripts/common.py b/scripts/common.py
new file mode 100644
index 0000000..78ff4d1
--- /dev/null
+++ b/scripts/common.py
@@ -0,0 +1,151 @@
+"""Shared utilities for Proven Viral Content Automation."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import tempfile
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+PROJECTS_DIR = REPO_ROOT / "projects"
+SCHEMA_PATH = REPO_ROOT / "schemas" / "profile.schema.json"
+ENV_PATH = REPO_ROOT / ".env"
+
+SLUG_PATTERN = re.compile(r"^_?[a-z0-9]+(?:-[a-z0-9]+)*$")
+
+
+def utc_now_iso() -> str:
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
+
+
+def slugify(name: str) -> str:
+ slug = name.lower().strip()
+ slug = re.sub(r"[^a-z0-9]+", "-", slug)
+ slug = slug.strip("-")
+ return slug or "project"
+
+
+def load_env(path: Path | None = None) -> dict[str, str]:
+ env: dict[str, str] = {}
+ env_file = path or ENV_PATH
+ if not env_file.exists():
+ return env
+ for line in env_file.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, _, value = line.partition("=")
+ env[key.strip()] = value.strip().strip('"').strip("'")
+ return env
+
+
+def get_api_key() -> str | None:
+ key = os.environ.get("MAGIC_HOUR_API_KEY")
+ if key:
+ return key
+ return load_env().get("MAGIC_HOUR_API_KEY")
+
+
+def rel_path(path: Path, base: Path = REPO_ROOT) -> str:
+ try:
+ return str(path.relative_to(base)).replace("\\", "/")
+ except ValueError:
+ return str(path).replace("\\", "/")
+
+
+def read_json(path: Path) -> Any:
+ with path.open(encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def write_json_atomic(path: Path, data: Any) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ encoding="utf-8",
+ dir=path.parent,
+ delete=False,
+ suffix=".tmp",
+ ) as tmp:
+ json.dump(data, tmp, indent=2, ensure_ascii=False)
+ tmp.write("\n")
+ tmp_path = Path(tmp.name)
+ tmp_path.replace(path)
+
+
+def project_dir(slug: str) -> Path:
+ if not SLUG_PATTERN.match(slug):
+ raise ValueError(f"Invalid project slug: {slug}")
+ return PROJECTS_DIR / slug
+
+
+def profile_path(slug: str) -> Path:
+ return project_dir(slug) / "profile.json"
+
+
+def list_projects(*, include_examples: bool = False) -> list[dict[str, str]]:
+ projects: list[dict[str, str]] = []
+ if not PROJECTS_DIR.exists():
+ return projects
+ for entry in sorted(PROJECTS_DIR.iterdir()):
+ if not entry.is_dir():
+ continue
+ if entry.name.startswith("_") and not include_examples:
+ continue
+ profile = entry / "profile.json"
+ if not profile.exists():
+ continue
+ data = read_json(profile)
+ projects.append(
+ {
+ "slug": data.get("project_slug", entry.name),
+ "name": data.get("project_name", entry.name),
+ "updated_at": data.get("updated_at", ""),
+ "path": rel_path(profile),
+ }
+ )
+ return projects
+
+
+def ensure_project_dirs(slug: str) -> Path:
+ root = project_dir(slug)
+ for sub in ("research", "ideas", "calendar", "input", "output"):
+ (root / sub).mkdir(parents=True, exist_ok=True)
+ return root
+
+
+def unique_slug(base: str) -> str:
+ slug = slugify(base)
+ if not (PROJECTS_DIR / slug / "profile.json").exists():
+ return slug
+ counter = 2
+ while (PROJECTS_DIR / f"{slug}-{counter}" / "profile.json").exists():
+ counter += 1
+ return f"{slug}-{counter}"
+
+
+def validate_profile(data: dict[str, Any]) -> list[str]:
+ errors: list[str] = []
+ required = ["schema_version", "project_slug", "created_at", "updated_at", "product", "content_types"]
+ for field in required:
+ if field not in data:
+ errors.append(f"Missing required field: {field}")
+ if data.get("schema_version") != "1.0.0":
+ errors.append("schema_version must be 1.0.0")
+ slug = data.get("project_slug", "")
+ if slug and not SLUG_PATTERN.match(slug):
+ errors.append(f"Invalid project_slug: {slug}")
+ product = data.get("product")
+ if isinstance(product, dict):
+ if not product.get("description"):
+ errors.append("product.description is required")
+ if product.get("type") not in {"product", "service", "project", "other"}:
+ errors.append("product.type must be product, service, project, or other")
+ content_types = data.get("content_types")
+ if not isinstance(content_types, list) or len(content_types) == 0:
+ errors.append("content_types must be a non-empty array")
+ return errors
diff --git a/scripts/magichour_video.py b/scripts/magichour_video.py
new file mode 100644
index 0000000..b81fe37
--- /dev/null
+++ b/scripts/magichour_video.py
@@ -0,0 +1,374 @@
+#!/usr/bin/env python3
+"""Magic Hour text-to-video generation helper."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import time
+import urllib.error
+import urllib.request
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from common import REPO_ROOT, get_api_key, project_dir, read_json, rel_path, utc_now_iso, write_json_atomic
+
+API_BASE = "https://api.magichour.ai/v1"
+CREATE_URL = f"{API_BASE}/text-to-video"
+
+# Best-effort constraints — verify against official docs before production use.
+MODEL_DURATIONS: dict[str, list[int]] = {
+ "default": list(range(3, 16)),
+ "kling-3.0": list(range(3, 16)),
+ "ltx-2.3": list(range(1, 11)) + [15, 20, 25, 30],
+ "sora-2": [4, 8, 12, 24, 36, 48, 60],
+ "wan-2.2": list(range(3, 11)) + [15],
+ "kling-2.5": [5, 10],
+ "veo3.1": [4, 6, 8] + list(range(16, 57, 8)),
+ "veo3.1-lite": [4, 6, 8] + list(range(16, 57, 8)),
+ "seedance-1.5": list(range(4, 13)),
+ "seedance-2.0": list(range(4, 16)),
+ "seedance-2.0-mini": list(range(4, 16)),
+}
+
+VALID_ASPECT_RATIOS = {"16:9", "9:16", "1:1"}
+VALID_RESOLUTIONS = {"480p", "720p", "1080p", "4k"}
+
+POLL_INTERVAL_SEC = 5
+POLL_TIMEOUT_SEC = 600
+
+
+class MagicHourError(Exception):
+ pass
+
+
+def _request(
+ method: str,
+ url: str,
+ *,
+ api_key: str,
+ payload: dict[str, Any] | None = None,
+ timeout: int = 60,
+) -> tuple[int, dict[str, Any] | str]:
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+ data = None
+ if payload is not None:
+ headers["Content-Type"] = "application/json"
+ data = json.dumps(payload).encode("utf-8")
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ body = resp.read().decode("utf-8")
+ if body:
+ return resp.status, json.loads(body)
+ return resp.status, {}
+ except urllib.error.HTTPError as exc:
+ body = exc.read().decode("utf-8", errors="replace")
+ try:
+ parsed = json.loads(body)
+ except json.JSONDecodeError:
+ parsed = body
+ return exc.code, parsed
+
+
+def validate_params(params: dict[str, Any]) -> list[str]:
+ errors: list[str] = []
+ prompt = params.get("prompt", "")
+ if not prompt or not isinstance(prompt, str):
+ errors.append("prompt is required")
+ elif len(prompt) > 2000:
+ errors.append("prompt must be at most 2000 characters")
+ model = params.get("model", "default")
+ end_seconds = params.get("end_seconds")
+ if end_seconds is None:
+ errors.append("end_seconds is required")
+ else:
+ allowed = MODEL_DURATIONS.get(model, MODEL_DURATIONS["default"])
+ if int(end_seconds) not in allowed:
+ errors.append(
+ f"end_seconds {end_seconds} not supported for model {model}. "
+ f"Allowed (best-effort): {allowed[:10]}{'...' if len(allowed) > 10 else ''}"
+ )
+ aspect = params.get("aspect_ratio", "16:9")
+ if aspect not in VALID_ASPECT_RATIOS:
+ errors.append(f"aspect_ratio must be one of {sorted(VALID_ASPECT_RATIOS)}")
+ resolution = params.get("resolution", "720p")
+ if resolution not in VALID_RESOLUTIONS:
+ errors.append(f"resolution must be one of {sorted(VALID_RESOLUTIONS)}")
+ return errors
+
+
+def build_request_body(idea: dict[str, Any], profile: dict[str, Any] | None = None) -> dict[str, Any]:
+ params = dict(idea.get("magichour_params") or {})
+ prompt = idea.get("magichour_prompt") or idea.get("concept") or idea.get("title", "")
+ name = idea.get("title") or f"Generate - {idea.get('id', 'idea')}"
+ body: dict[str, Any] = {
+ "name": name[:200],
+ "end_seconds": params.get("end_seconds", 8),
+ "aspect_ratio": params.get("aspect_ratio", "9:16"),
+ "resolution": params.get("resolution", "720p"),
+ "model": params.get("model", "default"),
+ "audio": bool(params.get("audio", True)),
+ "style": {"prompt": prompt},
+ }
+ return body
+
+
+def build_preview_manifest(
+ slug: str,
+ idea_path: Path,
+ idea: dict[str, Any],
+ profile: dict[str, Any] | None,
+) -> dict[str, Any]:
+ body = build_request_body(idea, profile)
+ validation_errors = validate_params(
+ {
+ "prompt": body["style"]["prompt"],
+ "end_seconds": body["end_seconds"],
+ "aspect_ratio": body["aspect_ratio"],
+ "resolution": body["resolution"],
+ "model": body["model"],
+ }
+ )
+ requires_input = idea.get("requires_input") or []
+ missing_inputs = []
+ if requires_input:
+ input_dir = project_dir(slug) / "input"
+ for filename in requires_input:
+ if not (input_dir / filename).exists():
+ missing_inputs.append(filename)
+ return {
+ "mode": "preview",
+ "project_slug": slug,
+ "idea_path": rel_path(idea_path),
+ "request": body,
+ "validation_errors": validation_errors,
+ "missing_inputs": missing_inputs,
+ "credit_estimate": {
+ "value": None,
+ "confidence": "unknown",
+ "note": (
+ "Best-effort: Magic Hour has no estimate-only API. "
+ "Exact credits are returned on job creation and may adjust after render. "
+ "See https://magichour.ai/api#api-cost-calculator"
+ ),
+ },
+ "generated_at": utc_now_iso(),
+ }
+
+
+def create_video(api_key: str, body: dict[str, Any]) -> dict[str, Any]:
+ status, data = _request("POST", CREATE_URL, api_key=api_key, payload=body)
+ if status >= 400:
+ raise MagicHourError(f"Create failed ({status}): {data}")
+ if not isinstance(data, dict):
+ raise MagicHourError(f"Unexpected create response: {data}")
+ return data
+
+
+def get_video_details(api_key: str, project_id: str) -> dict[str, Any]:
+ url = f"{API_BASE}/video-projects/{project_id}"
+ status, data = _request("GET", url, api_key=api_key)
+ if status >= 400:
+ raise MagicHourError(f"Poll failed ({status}): {data}")
+ if not isinstance(data, dict):
+ raise MagicHourError(f"Unexpected poll response: {data}")
+ return data
+
+
+def poll_until_complete(
+ api_key: str,
+ project_id: str,
+ *,
+ interval: float = POLL_INTERVAL_SEC,
+ timeout: float = POLL_TIMEOUT_SEC,
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ history: list[dict[str, Any]] = []
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ details = get_video_details(api_key, project_id)
+ history.append(
+ {
+ "at": utc_now_iso(),
+ "status": details.get("status"),
+ "credits_charged": details.get("credits_charged"),
+ }
+ )
+ status = details.get("status")
+ if status == "complete":
+ return details, history
+ if status in {"error", "canceled"}:
+ raise MagicHourError(f"Job ended with status {status}: {details}")
+ time.sleep(interval)
+ raise MagicHourError(f"Polling timed out after {timeout}s for project {project_id}")
+
+
+def download_file(url: str, dest: Path) -> Path:
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ dest.write_bytes(resp.read())
+ return dest
+
+
+def output_run_dir(slug: str) -> Path:
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ return project_dir(slug) / "output" / stamp
+
+
+def cmd_check_key(_: argparse.Namespace) -> int:
+ key = get_api_key()
+ if not key or key == "your_api_key_here":
+ print("MAGIC_HOUR_API_KEY is not configured.")
+ print("Copy .env.example to .env and set your API key.")
+ print("Get your Magic Hour API key: https://manicule.link/srp")
+ print("Use coupon code FIRSTAPI for free credits.")
+ return 1
+ print("MAGIC_HOUR_API_KEY is configured.")
+ return 0
+
+
+def _resolve_idea(slug: str, idea_arg: str) -> tuple[Path, dict[str, Any]]:
+ idea_path = Path(idea_arg)
+ if not idea_path.is_absolute():
+ candidate = project_dir(slug) / idea_arg
+ if candidate.exists():
+ idea_path = candidate
+ elif (REPO_ROOT / idea_arg).exists():
+ idea_path = REPO_ROOT / idea_arg
+ if not idea_path.exists():
+ raise FileNotFoundError(f"Idea file not found: {idea_arg}")
+ return idea_path, read_json(idea_path)
+
+
+def cmd_preview(args: argparse.Namespace) -> int:
+ idea_path, idea = _resolve_idea(args.project, args.idea)
+ profile = None
+ profile_file = project_dir(args.project) / "profile.json"
+ if profile_file.exists():
+ profile = read_json(profile_file)
+ manifest = build_preview_manifest(args.project, idea_path, idea, profile)
+ print(json.dumps(manifest, indent=2))
+ if manifest["validation_errors"]:
+ return 1
+ if manifest["missing_inputs"]:
+ print("\nMissing input files:", ", ".join(manifest["missing_inputs"]))
+ return 1
+ return 0
+
+
+def cmd_generate(args: argparse.Namespace) -> int:
+ if not args.confirm_spend:
+ print("Refusing to generate without --confirm-spend (explicit spend confirmation required).")
+ return 1
+ api_key = get_api_key()
+ if not api_key or api_key == "your_api_key_here":
+ print("MAGIC_HOUR_API_KEY is not configured. See: python scripts/magichour_video.py check-key")
+ return 1
+ idea_path, idea = _resolve_idea(args.project, args.idea)
+ profile = None
+ profile_file = project_dir(args.project) / "profile.json"
+ if profile_file.exists():
+ profile = read_json(profile_file)
+ preview = build_preview_manifest(args.project, idea_path, idea, profile)
+ if preview["validation_errors"]:
+ print("Validation errors:")
+ for err in preview["validation_errors"]:
+ print(f" - {err}")
+ return 1
+ if preview["missing_inputs"]:
+ print("Missing input files:", ", ".join(preview["missing_inputs"]))
+ return 1
+ body = preview["request"]
+ run_dir = output_run_dir(args.project)
+ run_dir.mkdir(parents=True, exist_ok=True)
+ manifest: dict[str, Any] = {
+ "mode": "generate",
+ "project_slug": args.project,
+ "idea_path": rel_path(idea_path),
+ "request": body,
+ "started_at": utc_now_iso(),
+ "status_history": [],
+ }
+ try:
+ create_resp = create_video(api_key, body)
+ except MagicHourError as exc:
+ print(str(exc))
+ return 1
+ project_id = create_resp.get("id")
+ initial_credits = create_resp.get("credits_charged")
+ manifest["create_response"] = {
+ "id": project_id,
+ "credits_charged_initial": initial_credits,
+ }
+ print(f"Job created: {project_id} (initial credits: {initial_credits})")
+ try:
+ details, history = poll_until_complete(api_key, project_id)
+ except MagicHourError as exc:
+ manifest["error"] = str(exc)
+ manifest["status_history"] = manifest.get("status_history", [])
+ write_json_atomic(run_dir / "manifest.json", manifest)
+ print(str(exc))
+ return 1
+ manifest["status_history"] = history
+ manifest["final_response"] = {
+ "status": details.get("status"),
+ "credits_charged_final": details.get("credits_charged"),
+ }
+ downloads = details.get("downloads") or []
+ downloaded: list[str] = []
+ for idx, item in enumerate(downloads):
+ url = item.get("url")
+ if not url:
+ continue
+ suffix = ".mp4" if idx == 0 else f"-{idx}.mp4"
+ dest = run_dir / f"output{suffix}"
+ download_file(url, dest)
+ downloaded.append(rel_path(dest))
+ manifest["downloads"] = downloaded
+ manifest["completed_at"] = utc_now_iso()
+ write_json_atomic(run_dir / "manifest.json", manifest)
+ print(json.dumps(manifest, indent=2))
+ return 0
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="Magic Hour text-to-video helper")
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ p_key = sub.add_parser("check-key", help="Verify MAGIC_HOUR_API_KEY is set")
+ p_key.set_defaults(func=cmd_check_key)
+
+ p_preview = sub.add_parser("preview", help="Preview generation manifest (no API call)")
+ p_preview.add_argument("--project", required=True)
+ p_preview.add_argument("--idea", required=True, help="Path to idea JSON under project ideas/")
+ p_preview.set_defaults(func=cmd_preview)
+
+ p_gen = sub.add_parser("generate", help="Submit generation job (billable)")
+ p_gen.add_argument("--project", required=True)
+ p_gen.add_argument("--idea", required=True)
+ p_gen.add_argument(
+ "--confirm-spend",
+ action="store_true",
+ help="Required flag confirming user approved credit spend",
+ )
+ p_gen.set_defaults(func=cmd_generate)
+
+ return parser
+
+
+def main() -> int:
+ parser = build_parser()
+ args = parser.parse_args()
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/profile_store.py b/scripts/profile_store.py
new file mode 100644
index 0000000..c72d27e
--- /dev/null
+++ b/scripts/profile_store.py
@@ -0,0 +1,193 @@
+#!/usr/bin/env python3
+"""Profile persistence for viral content projects."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import uuid
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from common import (
+ ensure_project_dirs,
+ list_projects,
+ profile_path,
+ read_json,
+ unique_slug,
+ utc_now_iso,
+ validate_profile,
+ write_json_atomic,
+)
+
+
+def cmd_list(args: argparse.Namespace) -> int:
+ projects = list_projects(include_examples=args.include_examples)
+ if args.json:
+ print(json.dumps(projects, indent=2))
+ return 0
+ if not projects:
+ print("No projects found. Run /onboarding to create one.")
+ return 0
+ print(f"{'Slug':<24} {'Name':<30} Updated")
+ print("-" * 70)
+ for p in projects:
+ print(f"{p['slug']:<24} {p['name']:<30} {p['updated_at']}")
+ return 0
+
+
+def cmd_validate(args: argparse.Namespace) -> int:
+ path = Path(args.path)
+ data = read_json(path)
+ errors = validate_profile(data)
+ if errors:
+ print("Validation failed:")
+ for err in errors:
+ print(f" - {err}")
+ return 1
+ print(f"Valid profile: {path}")
+ return 0
+
+
+def cmd_create(args: argparse.Namespace) -> int:
+ if args.profile_json:
+ payload = read_json(Path(args.profile_json))
+ else:
+ payload = json.loads(args.profile_inline or "{}")
+ slug = payload.get("project_slug") or unique_slug(args.name)
+ if not payload.get("project_slug"):
+ slug = unique_slug(args.name)
+ payload["project_slug"] = slug
+ payload.setdefault("project_name", args.name)
+ payload.setdefault("schema_version", "1.0.0")
+ now = utc_now_iso()
+ payload.setdefault("created_at", now)
+ payload["updated_at"] = now
+ payload.setdefault("content_preferences", [])
+ errors = validate_profile(payload)
+ if errors:
+ print("Cannot create project — validation errors:")
+ for err in errors:
+ print(f" - {err}")
+ return 1
+ ensure_project_dirs(slug)
+ out = profile_path(slug)
+ write_json_atomic(out, payload)
+ print(json.dumps({"slug": slug, "path": str(out)}, indent=2))
+ return 0
+
+
+def _load_profile(slug: str) -> dict[str, Any]:
+ path = profile_path(slug)
+ if not path.exists():
+ raise FileNotFoundError(f"Project not found: {slug}")
+ return read_json(path)
+
+
+def cmd_add_preference(args: argparse.Namespace) -> int:
+ profile = _load_profile(args.slug)
+ pref_id = args.id or f"pref-{uuid.uuid4().hex[:8]}"
+ entry = {
+ "id": pref_id,
+ "source": args.source,
+ "created_at": utc_now_iso(),
+ "preference": args.preference,
+ }
+ if args.topics:
+ entry["topics"] = [t.strip() for t in args.topics.split(",") if t.strip()]
+ if args.formats:
+ entry["formats"] = [f.strip() for f in args.formats.split(",") if f.strip()]
+ if args.notes:
+ entry["notes"] = args.notes
+ prefs = profile.setdefault("content_preferences", [])
+ prefs.append(entry)
+ profile["updated_at"] = utc_now_iso()
+ errors = validate_profile(profile)
+ if errors:
+ print("Validation failed after update:")
+ for err in errors:
+ print(f" - {err}")
+ return 1
+ write_json_atomic(profile_path(args.slug), profile)
+ print(json.dumps(entry, indent=2))
+ return 0
+
+
+def cmd_update_preference(args: argparse.Namespace) -> int:
+ profile = _load_profile(args.slug)
+ prefs = profile.get("content_preferences", [])
+ found = False
+ for pref in prefs:
+ if pref.get("id") == args.id:
+ if args.preference:
+ pref["preference"] = args.preference
+ if args.topics:
+ pref["topics"] = [t.strip() for t in args.topics.split(",") if t.strip()]
+ if args.formats:
+ pref["formats"] = [f.strip() for f in args.formats.split(",") if f.strip()]
+ if args.notes:
+ pref["notes"] = args.notes
+ pref["updated_at"] = utc_now_iso()
+ found = True
+ break
+ if not found:
+ print(f"Preference not found: {args.id}")
+ return 1
+ profile["updated_at"] = utc_now_iso()
+ write_json_atomic(profile_path(args.slug), profile)
+ print(json.dumps({"updated": args.id}, indent=2))
+ return 0
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="Manage viral content project profiles")
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ p_list = sub.add_parser("list", help="List projects")
+ p_list.add_argument("--json", action="store_true")
+ p_list.add_argument("--include-examples", action="store_true")
+ p_list.set_defaults(func=cmd_list)
+
+ p_validate = sub.add_parser("validate", help="Validate a profile.json")
+ p_validate.add_argument("path")
+ p_validate.set_defaults(func=cmd_validate)
+
+ p_create = sub.add_parser("create", help="Create a project from profile JSON")
+ p_create.add_argument("--name", required=True, help="Human-readable project name")
+ p_create.add_argument("--profile-json", help="Path to full profile payload JSON")
+ p_create.add_argument("--profile-inline", help="Inline JSON string for profile payload")
+ p_create.set_defaults(func=cmd_create)
+
+ p_add = sub.add_parser("add-preference", help="Append a content preference")
+ p_add.add_argument("--slug", required=True)
+ p_add.add_argument("--preference", required=True)
+ p_add.add_argument("--source", default="research-ideas", choices=["research-ideas", "brainstorm", "onboarding"])
+ p_add.add_argument("--id")
+ p_add.add_argument("--topics")
+ p_add.add_argument("--formats")
+ p_add.add_argument("--notes")
+ p_add.set_defaults(func=cmd_add_preference)
+
+ p_upd = sub.add_parser("update-preference", help="Update an existing preference")
+ p_upd.add_argument("--slug", required=True)
+ p_upd.add_argument("--id", required=True)
+ p_upd.add_argument("--preference")
+ p_upd.add_argument("--topics")
+ p_upd.add_argument("--formats")
+ p_upd.add_argument("--notes")
+ p_upd.set_defaults(func=cmd_update_preference)
+
+ return parser
+
+
+def main() -> int:
+ parser = build_parser()
+ args = parser.parse_args()
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/validate_structure.py b/scripts/validate_structure.py
new file mode 100644
index 0000000..5815f96
--- /dev/null
+++ b/scripts/validate_structure.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+"""Validate repository structure, skill frontmatter, and example JSON."""
+
+from __future__ import annotations
+
+import json
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+REQUIRED_SKILLS = ["onboarding", "research-ideas", "brainstorm", "generate"]
+FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---", re.DOTALL)
+
+
+def parse_frontmatter(text: str) -> dict[str, str]:
+ match = FRONTMATTER_RE.match(text)
+ if not match:
+ return {}
+ result: dict[str, str] = {}
+ for line in match.group(1).splitlines():
+ if ":" in line:
+ key, _, value = line.partition(":")
+ result[key.strip()] = value.strip()
+ return result
+
+
+def check_skills(errors: list[str]) -> None:
+ for name in REQUIRED_SKILLS:
+ skill_path = REPO_ROOT / ".agents" / "skills" / name / "SKILL.md"
+ if not skill_path.exists():
+ errors.append(f"Missing skill: {skill_path}")
+ continue
+ meta = parse_frontmatter(skill_path.read_text(encoding="utf-8"))
+ if meta.get("name") != name:
+ errors.append(f"Skill name mismatch in {skill_path}: {meta.get('name')}")
+ if not meta.get("description"):
+ errors.append(f"Missing description in {skill_path}")
+
+
+def check_adapters(errors: list[str]) -> None:
+ for name in REQUIRED_SKILLS:
+ claude = REPO_ROOT / ".claude" / "skills" / name / "SKILL.md"
+ workflow = REPO_ROOT / ".agents" / "workflows" / f"{name}.md"
+ opencode = REPO_ROOT / ".opencode" / "commands" / f"{name}.md"
+ for path in (claude, workflow, opencode):
+ if not path.exists():
+ errors.append(f"Missing adapter: {path}")
+
+
+def check_example_json(errors: list[str]) -> None:
+ profile = REPO_ROOT / "projects" / "_example" / "profile.json"
+ idea = REPO_ROOT / "projects" / "_example" / "ideas" / "idea-001.json"
+ for path in (profile, idea):
+ if not path.exists():
+ errors.append(f"Missing example file: {path}")
+ continue
+ try:
+ json.loads(path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ errors.append(f"Invalid JSON in {path}: {exc}")
+
+
+def main() -> int:
+ errors: list[str] = []
+ check_skills(errors)
+ check_adapters(errors)
+ check_example_json(errors)
+ required_files = [
+ "AGENTS.md",
+ "CLAUDE.md",
+ ".env.example",
+ "schemas/profile.schema.json",
+ "scripts/profile_store.py",
+ "scripts/magichour_video.py",
+ "docs/setup.md",
+ ]
+ for rel in required_files:
+ if not (REPO_ROOT / rel).exists():
+ errors.append(f"Missing required file: {rel}")
+ if errors:
+ print("Structure validation failed:")
+ for err in errors:
+ print(f" - {err}")
+ return 1
+ print("Structure validation passed.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_automation.py b/tests/test_automation.py
new file mode 100644
index 0000000..bd425d1
--- /dev/null
+++ b/tests/test_automation.py
@@ -0,0 +1,198 @@
+"""Tests for Proven Viral Content Automation."""
+
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+SCRIPTS = REPO_ROOT / "scripts"
+sys.path.insert(0, str(SCRIPTS))
+
+from common import ( # noqa: E402
+ PROJECTS_DIR,
+ ensure_project_dirs,
+ list_projects,
+ profile_path,
+ read_json,
+ slugify,
+ unique_slug,
+ validate_profile,
+ write_json_atomic,
+)
+from magichour_video import ( # noqa: E402
+ build_preview_manifest,
+ build_request_body,
+ poll_until_complete,
+ validate_params,
+)
+
+
+SAMPLE_PROFILE = {
+ "schema_version": "1.0.0",
+ "project_slug": "test-brand",
+ "project_name": "Test Brand",
+ "created_at": "2026-08-08T00:00:00Z",
+ "updated_at": "2026-08-08T00:00:00Z",
+ "product": {
+ "description": "A test product for viral content",
+ "type": "product",
+ },
+ "content_types": [
+ {
+ "id": "short-form-hook",
+ "label": "Short hook",
+ "platforms": ["tiktok"],
+ }
+ ],
+}
+
+
+SAMPLE_IDEA = {
+ "id": "idea-test",
+ "title": "Test idea",
+ "magichour_prompt": "A cinematic sunset over the ocean with gentle waves",
+ "magichour_params": {
+ "aspect_ratio": "9:16",
+ "end_seconds": 8,
+ "resolution": "720p",
+ "model": "default",
+ "audio": True,
+ },
+}
+
+
+class ProfileStoreTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self._tmpdir = tempfile.TemporaryDirectory()
+ self.projects_dir = Path(self._tmpdir.name) / "projects"
+ self.projects_dir.mkdir()
+ self._orig = PROJECTS_DIR
+ import common
+
+ common.PROJECTS_DIR = self.projects_dir
+
+ def tearDown(self) -> None:
+ import common
+
+ common.PROJECTS_DIR = self._orig
+ self._tmpdir.cleanup()
+
+ def test_slugify(self) -> None:
+ self.assertEqual(slugify("My Cool Brand!"), "my-cool-brand")
+
+ def test_validate_profile_ok(self) -> None:
+ self.assertEqual(validate_profile(SAMPLE_PROFILE), [])
+
+ def test_validate_profile_missing_fields(self) -> None:
+ bad = {"schema_version": "1.0.0"}
+ errors = validate_profile(bad)
+ self.assertTrue(any("project_slug" in e for e in errors))
+
+ def test_create_and_list_project(self) -> None:
+ slug = "test-brand"
+ ensure_project_dirs(slug)
+ write_json_atomic(profile_path(slug), SAMPLE_PROFILE)
+ projects = list_projects()
+ self.assertEqual(len(projects), 1)
+ self.assertEqual(projects[0]["slug"], slug)
+
+ def test_unique_slug_collision(self) -> None:
+ slug = unique_slug("Acme Co")
+ ensure_project_dirs(slug)
+ write_json_atomic(profile_path(slug), {**SAMPLE_PROFILE, "project_slug": slug})
+ slug2 = unique_slug("Acme Co")
+ self.assertNotEqual(slug, slug2)
+
+ def test_atomic_write(self) -> None:
+ slug = "atomic-test"
+ ensure_project_dirs(slug)
+ path = profile_path(slug)
+ write_json_atomic(path, SAMPLE_PROFILE)
+ loaded = read_json(path)
+ self.assertEqual(loaded["project_slug"], "test-brand")
+
+
+class MagicHourVideoTests(unittest.TestCase):
+ def test_validate_params_ok(self) -> None:
+ errors = validate_params(
+ {
+ "prompt": "A test prompt",
+ "end_seconds": 8,
+ "aspect_ratio": "9:16",
+ "resolution": "720p",
+ "model": "default",
+ }
+ )
+ self.assertEqual(errors, [])
+
+ def test_validate_params_bad_duration(self) -> None:
+ errors = validate_params(
+ {
+ "prompt": "Test",
+ "end_seconds": 7,
+ "aspect_ratio": "9:16",
+ "resolution": "720p",
+ "model": "kling-2.5",
+ }
+ )
+ self.assertTrue(any("end_seconds" in e for e in errors))
+
+ def test_build_request_body(self) -> None:
+ body = build_request_body(SAMPLE_IDEA)
+ self.assertEqual(body["aspect_ratio"], "9:16")
+ self.assertIn("prompt", body["style"])
+
+ def test_preview_manifest(self) -> None:
+ idea_path = Path("ideas/idea-test.json")
+ manifest = build_preview_manifest("_example", idea_path, SAMPLE_IDEA, None)
+ self.assertEqual(manifest["mode"], "preview")
+ self.assertIn("credit_estimate", manifest)
+
+ def test_poll_complete(self) -> None:
+ responses = [
+ {"status": "queued", "credits_charged": 100},
+ {"status": "rendering", "credits_charged": 100},
+ {
+ "status": "complete",
+ "credits_charged": 120,
+ "downloads": [{"url": "https://example.com/out.mp4"}],
+ },
+ ]
+
+ def fake_get(_key: str, _pid: str) -> dict:
+ return responses.pop(0)
+
+ with mock.patch("magichour_video.get_video_details", side_effect=fake_get):
+ with mock.patch("magichour_video.time.sleep"):
+ details, history = poll_until_complete("key", "proj-1", interval=0, timeout=30)
+ self.assertEqual(details["status"], "complete")
+ self.assertEqual(len(history), 3)
+
+ def test_poll_error_status(self) -> None:
+ with mock.patch(
+ "magichour_video.get_video_details",
+ return_value={"status": "error", "error": "render failed"},
+ ):
+ with self.assertRaises(Exception):
+ poll_until_complete("key", "proj-1", interval=0, timeout=5)
+
+
+class ExampleProjectTests(unittest.TestCase):
+ def test_example_profile_valid(self) -> None:
+ path = REPO_ROOT / "projects" / "_example" / "profile.json"
+ data = read_json(path)
+ self.assertEqual(validate_profile(data), [])
+
+ def test_example_idea_json(self) -> None:
+ path = REPO_ROOT / "projects" / "_example" / "ideas" / "idea-001.json"
+ data = read_json(path)
+ self.assertIn("magichour_prompt", data)
+
+
+if __name__ == "__main__":
+ unittest.main()