{
  "name": "App Wizard Academy — Drafter (All Sites)",
  "nodes": [
    {
      "id": "n1",
      "name": "Weekly Schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [-660, 0],
      "parameters": {
        "rule": { "interval": [{ "field": "cronExpression", "expression": "0 16 * * 1" }] }
      }
    },
    {
      "id": "n2",
      "name": "Load Sites Under Cap",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [-430, 90],
      "credentials": {
        "postgres": { "id": "REPLACE_WITH_YOUR_CREDENTIAL_ID", "name": "YOUR_POSTGRES_OR_SUPABASE_CREDENTIAL" }
      },
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT sc.id AS site_uuid, sc.name AS site_name, sc.repo AS site_repo,\n       COALESCE((SELECT count(*) FROM drafts d WHERE d.site_id = sc.id AND d.status = 'pending'), 0) AS open_drafts,\n       COALESCE((SELECT json_agg(title) FROM (SELECT title FROM drafts WHERE site_id = sc.id ORDER BY created_at DESC LIMIT 20) x), '[]'::json) AS recent_titles\nFROM site_config sc\nWHERE sc.agent_system_enabled = true\nORDER BY sc.name ASC;",
        "options": {}
      }
    },
    {
      "id": "n3",
      "name": "Filter Under Cap",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [-210, 90],
      "parameters": {
        "jsCode": "const CAP = 3;\nconst n = parseInt($json.open_drafts, 10) || 0;\nif (n >= CAP) return [];\nreturn [{ json: $json }];"
      }
    },
    {
      "id": "n4",
      "name": "Build Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [10, 90],
      "parameters": {
        "jsCode": "const site = $json;\nconst recent = Array.isArray(site.recent_titles) ? site.recent_titles.filter(Boolean) : [];\nconst avoid = recent.length ? (\"Avoid these existing titles: \" + recent.join(\"; \")) : \"No existing titles yet.\";\nconst system = \"You write ONE short page draft for a small niche website. Return ONLY a JSON object with keys: title, slug, content_markdown. content_markdown should be 300-500 words, plain and useful, no filler.\";\nconst user = \"Website: \" + site.site_name + \". Write one genuinely useful, non-duplicate page. \" + avoid;\nconst body = {\n  model: \"deepseek/deepseek-r1:free\",\n  messages: [ { role: \"system\", content: system }, { role: \"user\", content: user } ],\n  response_format: { type: \"json_object\" },\n  temperature: 0.7,\n  max_tokens: 900\n};\nreturn [{ json: Object.assign({}, site, { requestBody: body }) }];"
      }
    },
    {
      "id": "n5",
      "name": "Call OpenRouter (Free Model)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [230, 90],
      "parameters": {
        "method": "POST",
        "url": "https://openrouter.ai/api/v1/chat/completions",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            { "name": "Authorization", "value": "=Bearer {{$env.OPENROUTER_API_KEY}}" },
            { "name": "Content-Type", "value": "application/json" }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.requestBody) }}",
        "options": { "timeout": 60000 }
      }
    },
    {
      "id": "n6",
      "name": "Parse & Build Insert",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [450, 90],
      "parameters": {
        "jsCode": "const site = $('Load Sites Under Cap').item.json;\nconst resp = $json;\nlet obj = null;\ntry {\n  const c = resp.choices && resp.choices[0] && resp.choices[0].message ? resp.choices[0].message.content : \"\";\n  obj = typeof c === \"string\" ? JSON.parse(c) : c;\n} catch (e) { obj = null; }\nif (!obj || !obj.title || !obj.slug) { return []; }\nfunction esc(s){ return String(s).replace(/'/g, \"''\"); }\nconst sql = \"INSERT INTO drafts (site_id, title, slug, content_markdown, status) VALUES ('\" + site.site_uuid + \"'::uuid, '\" + esc(obj.title) + \"', '\" + esc(obj.slug) + \"', '\" + esc(obj.content_markdown || \"\") + \"', 'pending') RETURNING id;\";\nreturn [{ json: { insertSql: sql, site_name: site.site_name, title: obj.title } }];"
      }
    },
    {
      "id": "n7",
      "name": "Insert Draft",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [670, 90],
      "credentials": {
        "postgres": { "id": "REPLACE_WITH_YOUR_CREDENTIAL_ID", "name": "YOUR_POSTGRES_OR_SUPABASE_CREDENTIAL" }
      },
      "parameters": {
        "operation": "executeQuery",
        "query": "={{ $json.insertSql }}",
        "options": {}
      }
    }
  ],
  "connections": {
    "Weekly Schedule": {
      "main": [[{ "node": "Load Sites Under Cap", "type": "main", "index": 0 }]]
    },
    "Load Sites Under Cap": {
      "main": [[{ "node": "Filter Under Cap", "type": "main", "index": 0 }]]
    },
    "Filter Under Cap": {
      "main": [[{ "node": "Build Prompt", "type": "main", "index": 0 }]]
    },
    "Build Prompt": {
      "main": [[{ "node": "Call OpenRouter (Free Model)", "type": "main", "index": 0 }]]
    },
    "Call OpenRouter (Free Model)": {
      "main": [[{ "node": "Parse & Build Insert", "type": "main", "index": 0 }]]
    },
    "Parse & Build Insert": {
      "main": [[{ "node": "Insert Draft", "type": "main", "index": 0 }]]
    }
  },
  "active": false,
  "settings": { "executionOrder": "v1" },
  "versionId": "empire-engine-drafter-all-sites-v1",
  "meta": { "instanceId": "empire-engine-template" },
  "id": "empire-engine-drafter-all-sites",
  "tags": []
}
