{
  "name": "App Wizard Academy — Review Pipeline",
  "nodes": [
    {
      "parameters": {
        "rule": { "interval": [{ "field": "hours", "hoursInterval": 24 }] }
      },
      "id": "daily-schedule",
      "name": "Daily Schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [-700, 0]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT id, site_id, url, title, word_count, last_reviewed_at FROM pages WHERE last_reviewed_at IS NULL OR last_reviewed_at < now() - interval '7 days' ORDER BY last_reviewed_at ASC NULLS FIRST LIMIT 20;",
        "options": {}
      },
      "id": "get-pages-due",
      "name": "Get Pages Due For Review",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [-460, 0],
      "credentials": {
        "postgres": { "id": "REPLACE_WITH_YOUR_CREDENTIAL_ID", "name": "YOUR_POSTGRES_OR_SUPABASE_CREDENTIAL" }
      }
    },
    {
      "parameters": { "options": {} },
      "id": "loop-pages",
      "name": "Loop Over Pages",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [-220, 0]
    },
    {
      "parameters": {
        "url": "={{ $json.url }}",
        "sendHeaders": true,
        "headerParameters": { "parameters": [{ "name": "User-Agent", "value": "EmpireEngine-Reviewer/1.0" }] },
        "options": { "response": { "response": { "responseFormat": "text" } }, "timeout": 15000 }
      },
      "id": "fetch-page",
      "name": "Fetch Page Content",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [20, 0],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const fetchedHtml = $input.item.json.data ?? $input.item.json.body ?? '';\nconst page = $('Loop Over Pages').item.json;\n\nconst plainText = String(fetchedHtml).replace(/<script[\\s\\S]*?<\\/script>/gi, '').replace(/<style[\\s\\S]*?<\\/style>/gi, '').replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').trim();\nconst wordCount = plainText.split(/\\s+/).filter(Boolean).length;\nconst truncated = plainText.length > 12000 ? plainText.slice(0, 12000) + '\\n\\n[... truncated ...]' : plainText;\n\nconst prompt = `You are a strict quality reviewer for a small content website. Your job is to find real problems — not invent them.\n\nPAGE METADATA:\n- Title: ${page.title ?? '(no title)'}\n- URL: ${page.url}\n- Word count (estimated): ${wordCount}\n- Last reviewed: ${page.last_reviewed_at ?? 'never'}\n\nCURRENT CONTENT (truncated to ~3k tokens):\n\"\"\"\n${truncated}\n\"\"\"\n\nReturn JSON ONLY (no prose, no markdown fences) matching this schema exactly:\n\n{\n  \"score\": integer 0-100,\n  \"severity\": \"low\" | \"medium\" | \"high\" | \"critical\",\n  \"findings\": [\n    { \"category\": \"freshness\" | \"depth\" | \"structure\" | \"ctas\" | \"links\" | \"statistics\" | \"claims\" | \"length\" | \"other\", \"finding\": \"what is wrong, 1-2 sentences\", \"suggestion\": \"how to fix it, 1-2 sentences\" }\n  ]\n}\n\nSCORING RULES:\n- 90-100: Excellent, no issues.\n- 75-89: Good, minor polish only.\n- 60-74: Needs work — missing content or weak claims.\n- 40-59: Poor — multiple real problems.\n- 0-39: Critical — false data, invented statistics, or dangerously misleading.\n\nMANDATORY CHECKS:\n1. FAKE OR UNSOURCED STATISTICS — flag any specific number/percentage with no cited source. Category \"statistics\", severity high or critical.\n2. EXAGGERATED CLAIMS — flag superlatives with no evidence (\"the best\", \"guaranteed\", \"#1\"). Category \"claims\".\n3. SHORT PAGE — under 400 words is a mandatory \"length\" finding, severity high.\n4. FRESHNESS — flag undated temporal language (\"recently\", \"this year\"). Category \"freshness\".\n5. DEPTH — flag vague, surface-level content that teaches nothing actionable.\n\nCRITICAL RULE: invented statistics or deliberately false claims must score below 40 and severity \"critical\".\n\nOutput ONLY the JSON object.`;\n\nreturn { json: { prompt, page_id: page.id, page_url: page.url } };"
      },
      "id": "build-prompt",
      "name": "Build Reviewer Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [260, 0]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "http://localhost:11434/api/generate",
        "sendHeaders": true,
        "headerParameters": { "parameters": [{ "name": "Content-Type", "value": "application/json" }] },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ model: \"qwen2.5:3b\", prompt: $json.prompt, stream: false, format: \"json\", options: { temperature: 0.1, num_predict: 1500 } }) }}",
        "options": { "timeout": 120000 }
      },
      "id": "call-ollama",
      "name": "Call Ollama (Local)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [500, 0],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const ollamaResp = $input.item.json;\nconst built = $('Build Reviewer Prompt').item.json;\nconst rawText = ollamaResp?.response ?? '';\nlet parsed; let parseError = null;\ntry { parsed = JSON.parse(rawText); } catch (e) { parseError = e.message; }\n\nconst validSeverities = ['low','medium','high','critical'];\nconst looksValid = parsed && Number.isInteger(parsed.score) && parsed.score >= 0 && parsed.score <= 100 && validSeverities.includes(parsed.severity) && Array.isArray(parsed.findings);\n\nif (!looksValid) {\n  return { json: { page_id: built.page_id, score: 0, severity: 'high', findings: [{ category: 'parse_error', finding: parseError || 'Reviewer response did not match schema.', suggestion: `Raw: ${String(rawText).slice(0,300)}` }] } };\n}\nreturn { json: { page_id: built.page_id, score: parsed.score, severity: parsed.severity, findings: parsed.findings } };"
      },
      "id": "parse-response",
      "name": "Parse Reviewer Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [740, 0]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "=UPDATE pages SET last_reviewed_at = now(), last_review_score = {{ $json.score }} WHERE id = '{{ $json.page_id }}'::uuid;",
        "options": {}
      },
      "id": "update-page",
      "name": "Update Page",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [980, 0],
      "credentials": {
        "postgres": { "id": "REPLACE_WITH_YOUR_CREDENTIAL_ID", "name": "YOUR_POSTGRES_OR_SUPABASE_CREDENTIAL" }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 2 },
          "conditions": [
            { "leftValue": "={{ $('Parse Reviewer Response').item.json.severity }}", "rightValue": "high", "operator": { "type": "string", "operation": "equals" } },
            { "leftValue": "={{ $('Parse Reviewer Response').item.json.severity }}", "rightValue": "critical", "operator": { "type": "string", "operation": "equals" } }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "id": "if-severity",
      "name": "IF Severity High/Critical",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [1220, 0]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "=INSERT INTO escalations (page_id, severity, findings, status) VALUES ('{{ $('Parse Reviewer Response').item.json.page_id }}'::uuid, '{{ $('Parse Reviewer Response').item.json.severity }}', '{{ JSON.stringify($('Parse Reviewer Response').item.json.findings).replace(/'/g, \"''\") }}'::jsonb, 'open');",
        "options": {}
      },
      "id": "insert-escalation",
      "name": "Insert Escalation",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1460, -80],
      "credentials": {
        "postgres": { "id": "REPLACE_WITH_YOUR_CREDENTIAL_ID", "name": "YOUR_POSTGRES_OR_SUPABASE_CREDENTIAL" }
      }
    }
  ],
  "connections": {
    "Daily Schedule": { "main": [[{ "node": "Get Pages Due For Review", "type": "main", "index": 0 }]] },
    "Get Pages Due For Review": { "main": [[{ "node": "Loop Over Pages", "type": "main", "index": 0 }]] },
    "Loop Over Pages": { "main": [[], [{ "node": "Fetch Page Content", "type": "main", "index": 0 }]] },
    "Fetch Page Content": { "main": [[{ "node": "Build Reviewer Prompt", "type": "main", "index": 0 }]] },
    "Build Reviewer Prompt": { "main": [[{ "node": "Call Ollama (Local)", "type": "main", "index": 0 }]] },
    "Call Ollama (Local)": { "main": [[{ "node": "Parse Reviewer Response", "type": "main", "index": 0 }]] },
    "Parse Reviewer Response": { "main": [[{ "node": "Update Page", "type": "main", "index": 0 }]] },
    "Update Page": { "main": [[{ "node": "IF Severity High/Critical", "type": "main", "index": 0 }]] },
    "IF Severity High/Critical": {
      "main": [
        [{ "node": "Insert Escalation", "type": "main", "index": 0 }],
        [{ "node": "Loop Over Pages", "type": "main", "index": 0 }]
      ]
    },
    "Insert Escalation": { "main": [[{ "node": "Loop Over Pages", "type": "main", "index": 0 }]] }
  },
  "active": false,
  "settings": { "executionOrder": "v1" },
  "versionId": "empire-engine-review-pipeline-v1",
  "meta": { "instanceId": "empire-engine-template" },
  "id": "empire-engine-review-pipeline",
  "tags": []
}
