{
 "name": "The Rubber Stamp Test: gate (human in the loop pattern)",
 "nodes": [
  {
   "parameters": {
    "httpMethod": "POST",
    "path": "rubber-stamp-gate",
    "responseMode": "responseNode",
    "options": {}
   },
   "id": "w1",
   "name": "Aktion einreichen (Webhook)",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    300
   ],
   "webhookId": "7d1e4a52-0c3b-4f6a-9d21-6c0000000201",
   "notes": "POST {lang, card:{facts:{amount, order_total, kind_group, recipients, internal, known_domain, to_domain, items, idem_key, executed[], ask, policy_max, exception, order_status, irreversible, hour}, quote}}"
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "/* Der Durchwinker-Test / The Rubber Stamp Test / Il test del timbro: the deterministic gate (rules G01-G08).\n * Pure functions, ES2017, no dependencies, no AI: pasteable into an n8n Code node.\n *   const r = dwGate(card.facts, [card.quote]);   // -> { verdict: 'ok'|'block'|'review', rule, hits, why:{de,en,it} }\n * verdict 'block'  = auto-reject (a hard rule fired), 'review' = a human decides (soft rule), 'ok' = auto-approve.\n * A gate only knows the facts it is given. It does NOT know a changed IBAN or a customer with the same name: see the blind spots. */\nconst DW_RULE_NAME = {\n  G01: { de: 'Ungewöhnlicher Betrag', en: 'Unusual amount', it: 'Importo anomalo' },\n  G02: { de: 'Falscher Empfänger', en: 'Wrong recipient', it: 'Destinatario sbagliato' },\n  G03: { de: 'Zu großer Umfang', en: 'Scope too large', it: 'Portata eccessiva' },\n  G04: { de: 'Eingeschleuste Anweisung', en: 'Injected instruction', it: 'Istruzione iniettata' },\n  G05: { de: 'Duplikat', en: 'Duplicate', it: 'Duplicato' },\n  G06: { de: 'Richtlinienverstoß', en: 'Policy violation', it: 'Violazione di policy' },\n  G07: { de: 'Veralteter Kontext', en: 'Stale context', it: 'Contesto scaduto' },\n  G08: { de: 'Unumkehrbar und nachts', en: 'Irreversible and at night', it: 'Irreversibile e di notte' }\n};\nconst DW_INJECT = [\n  /ignor(e|iere|a)\\s+(all(e|es)?\\s+|tutte\\s+le\\s+)?(previous|prior|above|bisherigen|vorherigen|istruzioni)/i,\n  /\\b(system|sistema)\\s*:/i,\n  /admin[- ]?mode|admin[- ]?modus|modalit[àa]\\s+amministratore/i,\n  /als\\s+ki[- ]assistent|as\\s+an\\s+ai\\s+assistant|come\\s+assistente\\s+ai/i,\n  /do\\s+not\\s+confirm|nichts\\s+an\\s+den\\s+kunden|non\\s+confermare\\s+nulla/i,\n  /you\\s+are\\s+now|du\\s+bist\\s+jetzt|ora\\s+sei\\s+in/i\n];\nfunction dwNum(n, lang) {\n  const s = String(Math.round(Number(n)));\n  const sep = lang === 'en' ? ',' : '.';\n  return s.replace(/\\B(?=(\\d{3})+(?!\\d))/g, sep);\n}\nfunction dwLev(a, b) {\n  const m = a.length, n = b.length;\n  if (!m) return n;\n  if (!n) return m;\n  let prev = [];\n  for (let j = 0; j <= n; j++) prev[j] = j;\n  for (let i = 1; i <= m; i++) {\n    const cur = [i];\n    for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));\n    prev = cur;\n  }\n  return prev[n];\n}\nfunction dwLookalike(known, sent) {\n  if (!known || !sent || known === sent) return false;\n  const k = known.toLowerCase(), s = sent.toLowerCase();\n  if (k === s) return false;\n  const kl = k.split('.')[0], sl = s.split('.')[0];\n  return dwLev(kl, sl) <= 2 || (kl === sl && k !== s);\n}\nconst DW_ALLOWED_CHANGE = ['refund', 'credit', 'voucher'];\n/* returns every rule that fired: [{ id, v: 'block'|'review', p: {...params for the text} }] */\nfunction dwHits(f, quotes) {\n  const hits = [];\n  f = f || {};\n  // G04 injected instruction in untrusted text\n  const text = (quotes || []).filter(Boolean).join(' \\n ');\n  if (text && DW_INJECT.some(function (re) { return re.test(text); })) hits.push({ id: 'G04', v: 'block', p: {} });\n  // G05 the same action was already executed (idempotency key)\n  if (f.idem_key && Array.isArray(f.executed) && f.executed.indexOf(f.idem_key) >= 0) hits.push({ id: 'G05', v: 'block', p: { key: f.idem_key } });\n  // G07 the order or case is already closed in the system of record\n  if (f.order_status && ['refunded', 'cancelled', 'closed'].indexOf(f.order_status) >= 0) hits.push({ id: 'G07', v: 'block', p: { status: f.order_status } });\n  // G01 amount: more than the order value = block, 1000 EUR or more = a human looks\n  if (typeof f.amount === 'number' && typeof f.order_total === 'number' && f.kind_group === 'money_back') {\n    if (f.amount > f.order_total) hits.push({ id: 'G01', v: 'block', p: { amount: f.amount, total: f.order_total } });\n    else if (f.amount >= 1000) hits.push({ id: 'G01', v: 'review', p: { amount: f.amount, total: f.order_total } });\n  }\n  // G02 recipient: lookalike domain or mass mail to outsiders = block, mass mail inside the company = a human looks\n  if (f.to_domain && f.known_domain && dwLookalike(f.known_domain, f.to_domain)) hits.push({ id: 'G02', v: 'block', p: { sent: f.to_domain, known: f.known_domain, kind: 'look' } });\n  else if (typeof f.recipients === 'number' && f.recipients > 50) {\n    if (f.internal) hits.push({ id: 'G02', v: 'review', p: { n: f.recipients, kind: 'internal' } });\n    else hits.push({ id: 'G02', v: 'block', p: { n: f.recipients, kind: 'mass' } });\n  }\n  // G03 scope: more than 5000 items = block, 1000..5000 = a human looks\n  if (typeof f.items === 'number') {\n    if (f.items > 5000) hits.push({ id: 'G03', v: 'block', p: { n: f.items } });\n    else if (f.items >= 1000) hits.push({ id: 'G03', v: 'review', p: { n: f.items } });\n  }\n  // G06 policy: above the limit = block, unless a written special approval exists = a human looks\n  if (typeof f.ask === 'number' && typeof f.policy_max === 'number' && f.ask > f.policy_max)\n    hits.push({ id: 'G06', v: f.exception ? 'review' : 'block', p: { ask: f.ask, max: f.policy_max, unit: f.unit || '%', exc: f.exception || '' } });\n  // G08 irreversible and outside working hours (before 06:00, from 22:00) = a human decides\n  if (f.irreversible && typeof f.hour === 'number' && (f.hour < 6 || f.hour >= 22)) hits.push({ id: 'G08', v: 'review', p: { hour: f.hour } });\n  return hits;\n}\nfunction dwWhyOne(h, lang) {\n  const p = h.p || {};\n  const N = function (x) { return dwNum(x, lang); };\n  const T = {\n    G01: {\n      block: { de: 'Der Betrag (' + N(p.amount) + ' €) liegt über dem Warenwert (' + N(p.total) + ' €).', en: 'The amount (€' + N(p.amount) + ') is above the goods value (€' + N(p.total) + ').', it: \"L'importo (\" + N(p.amount) + ' €) supera il valore della merce (' + N(p.total) + ' €).' },\n      review: { de: 'Ab 1.000 € prüft ein Mensch, auch wenn der Betrag zum Warenwert passt (' + N(p.amount) + ' €).', en: 'From €1,000 a human checks, even if the amount matches the goods value (€' + N(p.amount) + ').', it: \"Da 1.000 € in su controlla una persona, anche se l'importo corrisponde al valore della merce (\" + N(p.amount) + ' €).' }\n    },\n    G02: {\n      look: { de: 'Die Domain ' + p.sent + ' sieht aus wie ' + p.known + ', ist aber eine andere.', en: 'The domain ' + p.sent + ' looks like ' + p.known + ' but is a different one.', it: 'Il dominio ' + p.sent + ' somiglia a ' + p.known + ' ma è un altro.' },\n      mass: { de: N(p.n) + ' externe Empfänger auf einmal.', en: N(p.n) + ' external recipients at once.', it: N(p.n) + ' destinatari esterni in una volta.' },\n      internal: { de: N(p.n) + ' interne Empfänger auf einmal: ein Mensch prüft Text und Verteiler.', en: N(p.n) + ' internal recipients at once: a human checks the text and the list.', it: N(p.n) + ' destinatari interni in una volta: una persona controlla testo e lista.' }\n    },\n    G03: {\n      block: { de: N(p.n) + ' Elemente auf einmal löschen (Grenze: 5.000).', en: 'Deleting ' + N(p.n) + ' items at once (limit: 5,000).', it: 'Eliminare ' + N(p.n) + ' elementi in una volta (limite: 5.000).' },\n      review: { de: N(p.n) + ' Elemente: ab 1.000 prüft ein Mensch den Umfang.', en: N(p.n) + ' items: from 1,000 a human checks the scope.', it: N(p.n) + ' elementi: da 1.000 in su una persona controlla la portata.' }\n    },\n    G04: { block: { de: 'Der ungeprüfte Kundentext enthält eine Anweisung an die KI.', en: 'The unchecked customer text contains an instruction to the AI.', it: \"Il testo non verificato del cliente contiene un'istruzione per l'AI.\" } },\n    G05: { block: { de: 'Dieselbe Aktion (' + p.key + ') wurde schon ausgeführt.', en: 'The same action (' + p.key + ') has already been executed.', it: \"La stessa azione (\" + p.key + ') è già stata eseguita.' } },\n    G06: {\n      block: { de: N(p.ask) + (p.unit === 'years' ? ' Jahre' : ' %') + ' liegen über der Richtlinie (' + N(p.max) + (p.unit === 'years' ? ' Jahr' : ' %') + '), eine Freigabe fehlt.', en: N(p.ask) + (p.unit === 'years' ? ' years' : '%') + ' is above the policy (' + N(p.max) + (p.unit === 'years' ? ' year' : '%') + '), no approval on file.', it: N(p.ask) + (p.unit === 'years' ? ' anni' : '%') + ' superano la regola (' + N(p.max) + (p.unit === 'years' ? ' anno' : '%') + '), manca un\\'autorizzazione.' },\n      review: { de: 'Über der Richtlinie, aber Sonderfreigabe ' + p.exc + ' liegt vor: ein Mensch bestätigt.', en: 'Above the policy, but special approval ' + p.exc + ' is on file: a human confirms.', it: \"Sopra la regola, ma c'è l'autorizzazione speciale \" + p.exc + ': una persona conferma.' }\n    },\n    G07: {\n      block: {\n        de: 'Im System steht der Status «' + ({ refunded: 'erstattet', cancelled: 'storniert', closed: 'abgeschlossen' }[p.status] || p.status) + '»: Die Anfrage beruht auf veralteten Daten.',\n        en: 'The system says “' + p.status + '”: the request is based on stale data.',\n        it: 'Nel sistema lo stato è «' + ({ refunded: 'rimborsato', cancelled: 'annullato', closed: 'chiuso' }[p.status] || p.status) + '»: la richiesta si basa su dati scaduti.'\n      }\n    },\n    G08: { review: { de: 'Nicht umkehrbar und um ' + p.hour + ' Uhr: nachts entscheidet ein Mensch.', en: 'Irreversible and at ' + p.hour + ':00: at night a human decides.', it: 'Irreversibile e alle ' + p.hour + ':00: di notte decide una persona.' } }\n  };\n  const byRule = T[h.id] || {};\n  const key = h.id === 'G02' ? h.p.kind : h.v;\n  const o = byRule[key] || byRule[h.v] || {};\n  return o[lang] || o.en || '';\n}\n/* the decision: first hard hit wins, otherwise a soft hit, otherwise ok */\nfunction dwGate(f, quotes) {\n  const hits = dwHits(f, quotes);\n  const hard = hits.filter(function (h) { return h.v === 'block'; });\n  const soft = hits.filter(function (h) { return h.v === 'review'; });\n  const main = hard[0] || soft[0] || null;\n  const why = { de: '', en: '', it: '' };\n  if (main) ['de', 'en', 'it'].forEach(function (l) { why[l] = dwWhyOne(main, l); });\n  return { verdict: hard.length ? 'block' : (soft.length ? 'review' : 'ok'), rule: main ? main.id : null, hits: hits.map(function (h) { return h.id; }), why: why };\n}\n\n// ---- wiring (n8n): POST { \"lang\": \"de|en|it\", \"card\": { \"facts\": { ... }, \"quote\": \"untrusted text, optional\" } }\nconst b = ($('Aktion einreichen (Webhook)').first().json.body) || {};\nconst lang = ['de', 'en', 'it'].indexOf(b.lang) >= 0 ? b.lang : 'en';\nconst c = b.card || {};\nconst g = dwGate(c.facts || {}, [c.quote || '']);\nreturn [{ json: { verdict: g.verdict, rule: g.rule, rules: g.hits, why: g.why[lang], ruleName: g.rule ? DW_RULE_NAME[g.rule][lang] : '' } }];\n"
   },
   "id": "c1",
   "name": "Gate G01-G08",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    240,
    300
   ],
   "notes": "Acht feste Regeln G01-G08, deterministisch, keine KI. Drei Urteile: ok, block, review."
  },
  {
   "parameters": {
    "rules": {
     "values": [
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "r_ok",
          "leftValue": "={{ $json.verdict }}",
          "rightValue": "ok",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "ok"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "r_bl",
          "leftValue": "={{ $json.verdict }}",
          "rightValue": "block",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "block"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "r_rv",
          "leftValue": "={{ $json.verdict }}",
          "rightValue": "review",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "review"
      }
     ]
    },
    "options": {}
   },
   "id": "sw",
   "name": "Urteil?",
   "type": "n8n-nodes-base.switch",
   "typeVersion": 3.2,
   "position": [
    480,
    300
   ]
  },
  {
   "parameters": {},
   "id": "ok",
   "name": "Auto-OK",
   "type": "n8n-nodes-base.noOp",
   "typeVersion": 1,
   "position": [
    740,
    140
   ],
   "notes": "Hier die Aktion ausführen (Stripe, Gmail, ...). Das Gate hat nichts gefunden: nicht dasselbe wie «sicher»."
  },
  {
   "parameters": {},
   "id": "bl",
   "name": "Auto-Block",
   "type": "n8n-nodes-base.noOp",
   "typeVersion": 1,
   "position": [
    740,
    300
   ],
   "notes": "Harte Regel: Aktion nicht ausführen, Grund protokollieren."
  },
  {
   "parameters": {},
   "id": "hu",
   "name": "Menschen fragen (mit Grund)",
   "type": "n8n-nodes-base.noOp",
   "typeVersion": 1,
   "position": [
    740,
    460
   ],
   "notes": "Hier z. B. Slack oder Telegram «Senden und auf Antwort warten» einhängen und den Grund (Feld why) anzeigen."
  },
  {
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify($json) }}",
    "options": {
     "responseCode": 200
    }
   },
   "id": "r1",
   "name": "Urteil senden",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    980,
    300
   ]
  },
  {
   "parameters": {
    "content": "## The Rubber Stamp Test: the gate\nA deterministic gate in front of an AI agent's actions. **Code node** with eight rules, **Switch** with three exits: *ok* (run it), *block* (hard rule), *review* (ask a human, with the reason).\n\nG01 unusual amount · G02 wrong recipient · G03 scope too large · G04 injected instruction · G05 duplicate · G06 policy violation · G07 stale context · G08 irreversible at night.\n\n**Use it:** import, activate, `curl -X POST <webhook-url> -H 'Content-Type: application/json' -d '{\"lang\":\"en\",\"card\":{\"facts\":{\"kind_group\":\"money_back\",\"amount\":4800,\"order_total\":48}}}'`.\n\n**Limits:** it only sees the facts you give it. A changed IBAN or a customer with the same name has no rule here, so *ok* means *no rule fired*, not *safe*. Thresholds (1,000 / 5,000 / 50 / 06:00-22:00) are examples: set your own.",
    "height": 400,
    "width": 560,
    "color": 5
   },
   "id": "s1",
   "name": "Hinweis",
   "type": "n8n-nodes-base.stickyNote",
   "typeVersion": 1,
   "position": [
    -40,
    -140
   ]
  }
 ],
 "connections": {
  "Aktion einreichen (Webhook)": {
   "main": [
    [
     {
      "node": "Gate G01-G08",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Gate G01-G08": {
   "main": [
    [
     {
      "node": "Urteil?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Urteil?": {
   "main": [
    [
     {
      "node": "Auto-OK",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Auto-Block",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Menschen fragen (mit Grund)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Auto-OK": {
   "main": [
    [
     {
      "node": "Urteil senden",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Auto-Block": {
   "main": [
    [
     {
      "node": "Urteil senden",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Menschen fragen (mit Grund)": {
   "main": [
    [
     {
      "node": "Urteil senden",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "active": false,
 "settings": {
  "executionOrder": "v1",
  "timezone": "Europe/Berlin",
  "saveDataSuccessExecution": "none",
  "saveDataErrorExecution": "none",
  "saveManualExecutions": false
 },
 "pinData": {}
}