After experimenting with autonomous MCP agents (like kagent with a Gmail MCP server) running against local LLMs in Ollama, I kept running into the same reliability wall: small-to-medium local models (8B–14B) struggle when asked to handle inbox polling, tool selection, JSON argument schemas, draft creation, and memory management all inside one open-ended agent loop.

I decided to split deterministic plumbing from probabilistic text generation using four services I already run (or can deploy cleanly) on my home Kubernetes cluster via ArgoCD:

  1. n8n (+ its bundled PostgreSQL) for deterministic Gmail polling, state tracking, and workflow orchestration
  2. Ollama (on an AMD GPU node) for local embeddings (nomic-embed-text:v1.5) and drafting/triage (gemma4:12b)
  3. Qdrant for long-term vector memory storing deduplicated drafting style and triage rules
  4. Open WebUI as the single human-in-the-loop chat interface (no Telegram, Slack, Mem0, or gmail-mcp servers required)

Everything below is deployed 100% declaratively and idempotently via ArgoCD (including Qdrant collections, PostgreSQL tables, Open WebUI Pipe functions, n8n credentials, and workflows) so a full cluster reset requires zero manual setup.

Goal and Architecture

The workflow I wanted to build covers the full human-in-the-loop learning cycle:

  1. Monitor my Gmail inbox on a schedule (every 4 hours).
  2. Query long-term memory (Qdrant) before deciding what to do with each new email.
  3. Triage each message into one of three actions:
    • Draft (draft): Generate a tailored reply using learned style rules, create a Gmail draft on the thread, and notify me in Open WebUI.
    • Summarize only (summarize_only): For ads, newsletters, and automated notifications, skip creating a Gmail draft and post a concise summary in Open WebUI.
    • Auto-trash (auto_trash): Only when an explicit learned triage rule authorizes it, move the email to Gmail Trash (recoverable for 30 days) and still post a review chat in Open WebUI.
  4. Reply directly inside that Open WebUI chat to refine drafts in-place, trash/restore emails, or teach new style and content-conditional triage rules.
  5. Automatically extract only reusable rules (ignoring one-off edits like dates or meeting times), deduplicate them (ADD / UPDATE / NOOP), and store them in Qdrant so future emails benefit immediately.
  6. Post a lightweight heartbeat log to a single Open WebUI chat when a run completes with zero new emails, and immediately alert me in Open WebUI if any workflow node fails.

architecture-diagram.jpg

Component Layout in Kubernetes

Each service lives in its own namespace, managed by a separate ArgoCD Application using Kustomize + Helm (overlays/home):

Component Namespace Internal Cluster Endpoint External / Internal URL Role
Ollama ollama http://ollama.ollama.svc.cluster.local:11434 ollama.internal AMD GPU inference (gemma4:12b, nomic-embed-text:v1.5)
Qdrant qdrant http://qdrant.qdrant.svc.cluster.local:6333 ClusterIP only Long-term vector memory (email_draft_memory, 768-dim Cosine)
n8n + PostgreSQL n8n http://n8n.n8n.svc.cluster.local:5678 / n8n-postgresql.n8n.svc.cluster.local:5432 https://n8nh.domain.com Workflow engine + short-term session state (email_draft_sessions, email_assistant_meta)
Open WebUI + Redis open-webui http://open-webui.open-webui.svc.cluster.local:80 https://chath.domain.com Chat UI + custom email_draft_assistant Pipe Function

Why no separate Mem0 service and no gmail-mcp server?

  • No Mem0: Qdrant + a narrow two-step Ollama JSON prompt inside n8n (extract reusable rule → search top-3 similar rules → decide ADD/UPDATE/NOOP) gives the exact same deduplicated memory pipeline without running a fifth service—and every memory decision is inspectable step-by-step in n8n’s execution history.
  • No gmail-mcp: n8n handles Google OAuth2 natively (automatically refreshing 1-hour access tokens from a long-lived refresh_token) and invokes the Gmail REST API deterministically.

Step 1: Ollama on AMD GPU

Ollama is deployed in the ollama namespace pinned to my AMD GPU node (gpu-node) with OLLAMA_KEEP_ALIVE=-1 so the models stay warm in VRAM between runs:

# k8s-ollama/overlays/home/values.yaml
ollama:
  gpu:
    enabled: true
    type: amd
nodeSelector:
  kubernetes.io/hostname: gpu-node
securityContext:
  privileged: true
extraEnv:
  - name: OLLAMA_MAX_LOADED_MODELS
    value: "3"
  - name: OLLAMA_NUM_PARALLEL
    value: "2"
  - name: OLLAMA_KEEP_ALIVE
    value: "-1"
persistentVolume:
  enabled: true
  size: 100Gi
  storageClass: managed-nfs-storage

Make sure both the chat model (gemma4:12b) and the 768-dimensional embedding model (nomic-embed-text:v1.5) are pulled.

Verify Step 1

> k get po,svc,pvc -n ollama
NAME                          READY   STATUS    RESTARTS      AGE
pod/ollama-54c9f54556-9jjvm   1/1     Running   5 (28h ago)   23d

NAME             TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)     AGE
service/ollama   ClusterIP   10.233.16.172   <none>        11434/TCP   113d

> k exec -n ollama deploy/ollama -- ollama list
NAME                     ID              SIZE      MODIFIED
nomic-embed-text:v1.5    0a109f422b47    274 MB    29 hours ago
gemma4:12b               6114515d63c1    8.0 GB    29 hours ago

Step 2: Qdrant Vector Store with Declarative Collection Init

Qdrant is deployed via its official Helm chart in the qdrant namespace backed by a 10Gi rook-ceph (ceph-block) PVC:

# k8s-qdrant/overlays/home/values.yaml
replicaCount: 1
persistence:
  enabled: true
  size: 10Gi
resources:
  requests:
    cpu: 250m
    memory: 512Mi
  limits:
    cpu: 1000m
    memory: 2Gi
service:
  type: ClusterIP
  ports:
    - name: http
      port: 6333
      targetPort: 6333

To keep collection creation declarative and idempotent on resets, I added an ArgoCD PostSync Job that creates the email_draft_memory collection (768 dimensions, Cosine distance for nomic-embed-text:v1.5) if missing, and creates keyword payload indexes on sender_email, sender_domain, category, and scope:

# k8s-qdrant/overlays/home/qdrant-init-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: qdrant-init-collections
  namespace: qdrant
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 3
  ttlSecondsAfterFinished: 600
  template:
    spec:
      restartPolicy: OnFailure
      containers:
        - name: init-collections
          image: curlimages/curl:8.11.1
          command: ["/bin/sh", "-c"]
          args:
            - |
              set -eu
              QDRANT_URL="http://qdrant.qdrant.svc.cluster.local:6333"
              COLLECTION="email_draft_memory"

              until curl -sf "${QDRANT_URL}/readyz" >/dev/null 2>&1; do sleep 2; done

              STATUS=$(curl -s -o /dev/null -w "%{http_code}" "${QDRANT_URL}/collections/${COLLECTION}")
              if [ "$STATUS" != "200" ]; then
                curl -sf -X PUT "${QDRANT_URL}/collections/${COLLECTION}" \
                  -H 'Content-Type: application/json' \
                  -d '{"vectors": {"size": 768, "distance": "Cosine"}}'
              fi

              for field in sender_email sender_domain category scope; do
                curl -sf -X PUT "${QDRANT_URL}/collections/${COLLECTION}/index?wait=true" \
                  -H 'Content-Type: application/json' \
                  -d "{\"field_name\": \"${field}\", \"field_schema\": \"keyword\"}"
              done

Include qdrant-init-job.yaml under resources: in k8s-qdrant/overlays/home/kustomization.yaml.

ArgoCD Note: ArgoCD automated sync only fires when a non-hook resource diffs against the live cluster. If Qdrant is already running and your commit only adds a PostSync Hook Job, trigger a one-time manual sync (argocd app sync qdrant-home or in the ArgoCD UI) so the Job executes immediately; on any future fresh deploy it runs automatically.

Verify Step 2

Confirm the Job succeeded and Qdrant reports a green collection with all four keyword payload indexes:

> k get jobs,po -n qdrant
NAME                                STATUS     COMPLETIONS   DURATION   AGE
job.batch/qdrant-init-collections   Complete   1/1           10s        52s

NAME                                READY   STATUS      RESTARTS       AGE
pod/qdrant-0                        1/1     Running     10 (30h ago)   59d
pod/qdrant-init-collections-tm4h9   0/1     Completed   0              52s

> k exec -n n8n deploy/n8n -- wget -qO- http://qdrant.qdrant.svc.cluster.local:6333/collections/email_draft_memory | jq '{status: .result.status, vectors: .result.config.params.vectors, payload_schema: (.result.payload_schema | keys)}'
{
  "status": "green",
  "vectors": {
    "size": 768,
    "distance": "Cosine"
  },
  "payload_schema": [
    "category",
    "scope",
    "sender_domain",
    "sender_email"
  ]
}

Step 3: Open WebUI and the Declarative Pipe Function

Open WebUI (0.13.4) runs in the open-webui namespace pointing at http://ollama.ollama.svc.cluster.local:11434.

Because Open WebUI is normally a user-initiated chat UI, I bridged it to n8n in both directions:

  1. n8n → Open WebUI: Workflow A calls POST http://open-webui.open-webui.svc.cluster.local/api/v1/chats/new (using an Open WebUI admin API key) to create a sidebar chat assigned to the model email_draft_assistant.
  2. Open WebUI → n8n: A lightweight Python Pipe Function (email_draft_assistant.py) receives chat_id from __metadata__ and forwards my chat reply to http://n8n.n8n.svc.cluster.local:5678/webhook/email-draft-feedback.

Two critical details in the Pipe Function (both learned the hard way during testing):

  • Make pipe async def and wrap the blocking HTTP request in asyncio.to_thread(...) so a 20-second Ollama call doesn’t block Open WebUI’s event loop and cause Redis timeouts.
  • Short-circuit Open WebUI’s internal background tasks (__task__, __metadata__.get("task"), and ### Task: prompts such as automatic follow-up/title/tag generation) so Open WebUI doesn’t send "Suggest 3-5 follow-ups" to n8n as fake user feedback.
# k8s-open-webui/overlays/home/functions/email_draft_assistant.py
"""
title: Email Draft Assistant
author: homelab
version: 1.1.0
description: Routes chat replies to n8n Workflow B to update Gmail drafts in-place and learn reusable drafting preferences in Qdrant.
"""

import asyncio
import json
import urllib.error
import urllib.request
from typing import Optional
from pydantic import BaseModel, Field


class Pipe:
    class Valves(BaseModel):
        N8N_WEBHOOK_URL: str = Field(
            default="http://n8n.n8n.svc.cluster.local:5678/webhook/email-draft-feedback",
            description="Internal n8n webhook URL for Workflow B.",
        )
        REQUEST_TIMEOUT: int = Field(
            default=180,
            description="HTTP timeout in seconds waiting for Ollama rewrite & memory extraction.",
        )

    def __init__(self):
        self.valves = self.Valves()

    def _post_to_n8n(self, payload: bytes) -> str:
        req = urllib.request.Request(
            self.valves.N8N_WEBHOOK_URL,
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, timeout=self.valves.REQUEST_TIMEOUT) as resp:
                raw = resp.read().decode("utf-8")
                data = json.loads(raw)
                return str(data["reply"]) if isinstance(data, dict) and "reply" in data else raw
        except urllib.error.HTTPError as e:
            return f"n8n webhook returned HTTP {e.code}: {e.read().decode('utf-8', errors='replace')}"
        except Exception as e:
            return f"Failed to reach n8n webhook ({self.valves.N8N_WEBHOOK_URL}): {e}"

    async def pipe(
        self,
        body: dict,
        __user__: Optional[dict] = None,
        __metadata__: Optional[dict] = None,
        __task__: Optional[str] = None,
    ) -> str:
        metadata = __metadata__ or {}
        task = __task__ or metadata.get("task")

        user_feedback = ""
        for msg in reversed(body.get("messages", [])):
            if msg.get("role") == "user":
                content = msg.get("content", "")
                user_feedback = str(content).strip() if not isinstance(content, list) else " ".join(
                    p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"
                ).strip()
                break

        # Ignore Open WebUI internal background tasks (follow-ups, titles, tags)
        if task or user_feedback.startswith("### Task:") or "\n### Task:" in user_feedback:
            task_str = str(task or "").lower()
            if "follow_up" in task_str or "follow-up" in user_feedback.lower():
                return json.dumps({"follow_ups": []})
            if "tag" in task_str:
                return json.dumps({"tags": []})
            return ""

        chat_id = metadata.get("chat_id", "")
        if not chat_id:
            return "Could not determine `chat_id`. Reply inside a draft/summary chat created by n8n."

        payload = json.dumps({
            "chat_id": chat_id,
            "feedback": user_feedback,
            "user": (__user__ or {}).get("email", ""),
        }).encode("utf-8")

        return await asyncio.to_thread(self._post_to_n8n, payload)

To keep the Pipe synced declaratively via ArgoCD, I mounted email_draft_assistant.py via a Kustomize configMapGenerator (openwebui-functions) and added a PostSync Job (pipe-sync-job.yaml) that creates/updates the function via Open WebUI’s REST API (/api/v1/functions/create or /api/v1/functions/id/email_draft_assistant/update) and toggles it active using an admin API key generated under Settings → Account → API Keys.

Verify Step 3

> k get jobs -n open-webui | grep openwebui-pipe-sync
openwebui-pipe-sync          Complete   1/1           8s         31s

> k exec -n open-webui open-webui-0 -- python3 -c 'import sqlite3; con=sqlite3.connect("/app/backend/data/webui.db"); print(con.execute("SELECT id, name, type, is_active FROM function").fetchall())'
[('email_draft_assistant', 'Email Draft Assistant', 'pipe', 1)]

Step 4: n8n, PostgreSQL State Schema, Credentials, and Workflows

4.1 PostgreSQL State Schema (PostSync Job)

To avoid long-lived n8n Wait executions and prevent collisions across concurrent email threads, short-term correlation state lives in n8n’s bundled PostgreSQL database:

-- k8s-n8n/overlays/home/sql/init-email-drafts.sql
DO $$
BEGIN
    CREATE TYPE draft_status AS ENUM (
        'DRAFTED',
        'REVISING',
        'APPROVED_SENT',
        'ARCHIVED'
    );
EXCEPTION
    WHEN duplicate_object THEN NULL;
END $$;

CREATE TABLE IF NOT EXISTS email_draft_sessions (
    id                 UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    gmail_thread_id    VARCHAR(64) NOT NULL,
    gmail_message_id   VARCHAR(64) NOT NULL UNIQUE,
    gmail_draft_id     VARCHAR(64) NOT NULL,
    sender_email       TEXT NOT NULL,
    sender_domain      TEXT GENERATED ALWAYS AS (split_part(sender_email, '@', 2)) STORED,
    subject            TEXT NOT NULL,
    email_category     VARCHAR(64),
    openwebui_chat_id  VARCHAR(64) NOT NULL UNIQUE,
    inbound_summary    TEXT NOT NULL,
    current_draft_body TEXT NOT NULL,
    revision_count     INT NOT NULL DEFAULT 0,
    status             draft_status NOT NULL DEFAULT 'DRAFTED',
    created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at         TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_gmail_thread_status
    ON email_draft_sessions (gmail_thread_id, status);

CREATE TABLE IF NOT EXISTS email_assistant_meta (
    key        TEXT PRIMARY KEY,
    value      TEXT NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

An ArgoCD PostSync Job (db-init-job.yaml running postgres:16-alpine) mounts this SQL via ConfigMap n8n-db-init-sql, waits for pg_isready, and runs psql -v ON_ERROR_STOP=1 -f /sql/init-email-drafts.sql.

4.2 Credentials Bundle Secret

n8n imports three credentials declaratively from a Kubernetes Secret (n8n-app-credentials) stored in my private GitOps repo:

# k8s-n8n/overlays/home/n8n-app-credentials-secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: n8n-app-credentials
  namespace: n8n
type: Opaque
stringData:
  credentials.json: |
    [
      {
        "id": "gmail-oauth-cred",
        "name": "Gmail Account",
        "type": "gmailOAuth2",
        "data": {
          "clientId": "<GOOGLE_OAUTH_CLIENT_ID>",
          "clientSecret": "<GOOGLE_OAUTH_CLIENT_SECRET>",
          "scope": "https://mail.google.com/",
          "oauthTokenData": {
            "refresh_token": "<GOOGLE_OAUTH_REFRESH_TOKEN>",
            "token_type": "Bearer"
          }
        }
      },
      {
        "id": "n8n-postgres-cred",
        "name": "n8n PostgreSQL",
        "type": "postgres",
        "data": {
          "host": "n8n-postgresql.n8n.svc.cluster.local",
          "database": "n8n",
          "user": "n8n",
          "password": "<DB_PASSWORD>",
          "port": 5432,
          "ssl": "disable"
        }
      },
      {
        "id": "openwebui-api-cred",
        "name": "Open WebUI API",
        "type": "httpHeaderAuth",
        "data": {
          "name": "Authorization",
          "value": "Bearer <OPENWEBUI_API_KEY>"
        }
      }
    ]

4.3 Helm Values and Hash-Gated InitContainer

In k8s-n8n/overlays/home/values.yaml, three details make GitOps rollouts completely painless:

  1. strategy: { type: Recreate, rollingUpdate: null } — prevents FailedAttachVolume deadlocks when replacing the pod attached to the ReadWriteOnce Ceph PVC.
  2. Minting an initial Gmail access_token — @n8n/client-oauth2 throws Unable to sign without access token if oauthTokenData.access_token is empty on first run, before n8n’s 401 refresh handler ever executes. The import-workflows initContainer uses Node’s built-in fetch to exchange refresh_token for a real initial access_token before calling n8n import:credentials.
  3. SHA-256 hash gating on /home/node/.n8n — stores .imported-creds.sha256 and .imported-workflows.sha256 on the PVC so normal pod restarts skip re-importing (avoiding unnecessary OAuth calls and preventing n8n import:workflow from unpublishing active workflows), while Git changes or full cluster resets automatically re-import.
# k8s-n8n/overlays/home/values.yaml (excerpt)
strategy:
  type: Recreate
  rollingUpdate: null

main:
  count: 1
  editorBaseUrl: "https://n8nh.domain.com"
  volumes:
    - name: workflows
      configMap:
        name: n8n-workflows
    - name: credentials
      secret:
        secretName: n8n-app-credentials
  initContainers:
    - name: import-workflows
      image: "n8nio/n8n:2.40.5"
      command: ["/bin/sh", "-c"]
      args:
        - |
          set -eu
          CREDS_HASH_FILE="/home/node/.n8n/.imported-creds.sha256"
          WF_HASH_FILE="/home/node/.n8n/.imported-workflows.sha256"

          CREDS_HASH=$(sha256sum /credentials/credentials.json | awk '{print $1}')
          if [ ! -f "$CREDS_HASH_FILE" ] || [ "$(cat "$CREDS_HASH_FILE")" != "$CREDS_HASH" ]; then
            node -e '
              const fs = require("fs");
              (async () => {
                const creds = JSON.parse(fs.readFileSync("/credentials/credentials.json", "utf8"));
                for (const c of creds) {
                  if (c.type === "gmailOAuth2" && c.data?.oauthTokenData?.refresh_token && !c.data.oauthTokenData.access_token) {
                    const res = await fetch("https://oauth2.googleapis.com/token", {
                      method: "POST",
                      headers: { "Content-Type": "application/x-www-form-urlencoded" },
                      body: new URLSearchParams({
                        client_id: c.data.clientId,
                        client_secret: c.data.clientSecret,
                        refresh_token: c.data.oauthTokenData.refresh_token,
                        grant_type: "refresh_token",
                      }),
                    });
                    if (!res.ok) throw new Error("Token exchange failed: HTTP " + res.status);
                    const tok = await res.json();
                    c.data.oauthTokenData = {
                      ...c.data.oauthTokenData,
                      access_token: tok.access_token,
                      expires_in: tok.expires_in || 3599,
                      token_type: tok.token_type || "Bearer",
                    };
                  }
                }
                fs.writeFileSync("/tmp/credentials.json", JSON.stringify(creds));
              })().catch(err => { console.error(err); process.exit(1); });
            '
            n8n import:credentials --input=/tmp/credentials.json
            rm -f /tmp/credentials.json
            echo "$CREDS_HASH" > "$CREDS_HASH_FILE"
          fi

          WF_HASH=$(sha256sum /workflows/*.json | sha256sum | awk '{print $1}')
          if [ ! -f "$WF_HASH_FILE" ] || [ "$(cat "$WF_HASH_FILE")" != "$WF_HASH" ]; then
            n8n import:workflow --separate --input=/workflows/
            echo "$WF_HASH" > "$WF_HASH_FILE"
          fi
      env:
        - name: N8N_PORT
          value: "5678"

And in k8s-n8n/overlays/home/kustomization.yaml, leaving both disableNameSuffixHash: true and namespace: n8n commented out on n8n-workflows lets Kustomize append a content hash (n8n-workflows-<hash>) and automatically rewrite Deployment/n8n’s volume reference—so pushing a workflow JSON change triggers an automatic pod rollout, while non-workflow changes do not:

# k8s-n8n/overlays/home/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

helmCharts:
- name: n8n
  repo: https://community-charts.github.io/helm-charts
  version: "1.24.42"
  releaseName: n8n
  namespace: n8n
  valuesFile: values.yaml

resources:
- route.yaml
- n8n-app-credentials-secret.yaml
- db-init-job.yaml

configMapGenerator:
- name: n8n-workflows
  # namespace: n8n
  # options:
  #   disableNameSuffixHash: true
  files:
  - workflows/workflow-a-inbound-draft.json
  - workflows/workflow-b-chat-feedback.json
  - workflows/workflow-c-error-notifier.json
- name: n8n-db-init-sql
  namespace: n8n
  options:
    disableNameSuffixHash: true
  files:
  - sql/init-email-drafts.sql

4.4 The Three n8n Workflows

  1. Workflow A (email-drafter-inbound, 39 nodes) — Inbound Triage, Drafting, & Heartbeat
    • Schedule Trigger (every 4 hours) → Get Unread Emails (in:inbox is:unread -from:me, alwaysOutputData: true) → Normalize Emails (extracts sender, domain, List-Unsubscribe, no-reply hints).
    • Idempotency (Check Existing Session → Filter New vs No-Op): Queries email_draft_sessions and filters by exact gmail_message_id / active gmail_thread_id sets (never by array index!).
    • If 0 new emails: Updates a single Email Assistant — Run Status chat in Open WebUI (tracked via email_assistant_meta, keeping the last 30 entries) with a timestamped ✅ heartbeat.
    • For each new email: Embeds with nomic-embed-text:v1.5 → searches Qdrant email_draft_memory (matching sender_email, sender_domain, category, global) before triage → gemma4:12b returns JSON { email_category, recommended_action, triage_reason, inbound_summary } with a code-level safety guard that blocks auto_trash unless an explicit learned triage rule exists.
    • Routes into 3 branches:
      • draft: gemma4:12b generates reply using matched style rules → Gmail REST POST /users/me/drafts → Open WebUI Draft: ... chat → Postgres insert (DRAFTED).
      • summarize_only: Skips drafting → Open WebUI Summary [<category>]: ... chat → Postgres insert (ARCHIVED, empty draft ID).
      • auto_trash: Gmail REST POST /users/me/messages/{id}/trash → Open WebUI Auto-Trashed [<category>]: ... review chat → Postgres insert (ARCHIVED).

n8n-workflow-a.png

  1. Workflow B (email-drafter-chat-feedback, 33 nodes) — Chat Feedback, In-Place Draft Rewrite, & Memory Learning
    • Webhook (POST /webhook/email-draft-feedback) ← called by the Open WebUI email_draft_assistant Pipe.
    • Postgres Lookup by openwebui_chat_id resolves the exact gmail_message_id and gmail_draft_id.
    • Action Router (Switch):
      • done / approve / lgtm → marks APPROVED_SENT (no LLM call).
      • archive / ignore → marks ARCHIVED (no LLM call).
      • delete / trash → moves email to Gmail Trash (POST /messages/{id}/trash) + runs triage rule extraction on any guidance included after delete.
      • restore / untrash → recovers email from Gmail Trash (POST /messages/{id}/untrash) + updates the triage rule in Qdrant.
      • Summary-only chat feedback (gmail_draft_id == '') → runs triage rule learning directly.
      • Draft revision feedback → gemma4:12b rewrites the draft → Gmail REST PUT /users/me/drafts/{id} updates the existing draft in-place → updates Postgres revision_count → runs rule extraction.
    • Memory Pipeline (gemma4:12b + nomic-embed-text:v1.5 + Qdrant): Extracts only reusable style or triage rules (ignoring one-off edits like dates/times), embeds the rule, searches top-3 similar rules in Qdrant, asks gemma4:12b to choose ADD, UPDATE <existing_id>, or NOOP, upserts to Qdrant, and replies inline in Open WebUI.

n8n-workflow-b.png

  1. Workflow C (email-drafter-error-notifier, 3 nodes) — Failure Alerting
    • Linked via "errorWorkflow": "email-drafter-error-notifier" in both Workflow A and Workflow B.
    • Error Trigger → Format Error Chat → POST /api/v1/chats/new creates a ⚠️ ERROR: <Workflow> (<Failed Node>) chat in Open WebUI with the error message, stack top lines, timestamp, and direct execution link in n8n.

Verify Step 4

Verify the pod rollout, PostSync DB Job, imported workflows, credentials, tables, and cross-namespace connectivity from n8n:

> k get po,jobs -n n8n
NAME                             READY   STATUS      RESTARTS       AGE
pod/n8n-7c94c8c54c-ljgk5         1/1     Running     0              36s
pod/n8n-db-init-email-drafts-... 0/1     Completed   0              15s
pod/n8n-postgresql-0             1/1     Running     10 (33h ago)   59d

> k logs -n n8n deploy/n8n -c import-workflows
Preparing credentials (minting initial Gmail access_token from refresh_token)...
Importing credentials...
Successfully imported 3 credentials.
Importing workflows...
Successfully imported 3 workflows.

> k exec -n n8n n8n-postgresql-0 -- env PGPASSWORD=<db-password> psql -U n8n -d n8n \
  -c 'SELECT id, name, active FROM workflow_entity;' \
  -c 'SELECT id, name, type FROM credentials_entity;' \
  -c '\dt email*'
              id              |                   name                   | active
------------------------------+------------------------------------------+--------
 email-drafter-chat-feedback  | Email Drafter B - Chat Feedback & Memory | t
 email-drafter-inbound        | Email Drafter A - Inbound Triage & Draft | t
 email-drafter-error-notifier | Email Drafter C - Error Notifier         | f

         id         |      name      |      type
--------------------+----------------+----------------
 gmail-oauth-cred   | Gmail Account  | gmailOAuth2
 n8n-postgres-cred  | n8n PostgreSQL | postgres
 openwebui-api-cred | Open WebUI API | httpHeaderAuth

               List of relations
 Schema |         Name         | Type  | Owner
--------+----------------------+-------+-------
 public | email_assistant_meta | table | n8n
 public | email_draft_sessions | table | n8n

Finally, open https://n8nh.domain.com and Publish Workflow A and Workflow B (Workflow C runs automatically on errors without needing to be published).

Seeing It Work: End-to-End Examples

Example 1: Iterative Draft Feedback & Memory Recall

  1. First email arrives from user@fake.com (“How about lunch tomorrow?”):

    • Workflow A creates Gmail draft r1234567890123456789 and opens a chat titled Draft: How about lunch tomorrow? (user@fake.com) in Open WebUI.
  2. Giving mixed feedback in Open WebUI (a one-off scheduling detail + a reusable style rule):

    “Suggest 12:30 PM at Main Street Cafe, and for emails from user@fake.com always keep replies casual, under 2 sentences, and sign off with ‘- A’.”

    • Workflow B rewrites the draft for 12:30 PM at Main Street Cafe, updates the Gmail draft in-place, and stores only the reusable rule in Qdrant (dropping "12:30 PM at Main Street Cafe").
  3. Second email arrives from the same sender (“Hey let’s make sure to get that lunch.”):

    • Workflow A automatically retrieves the rule from Qdrant and produces the exact preferred tone and sign-off on the very first draft:
### New Gmail Draft Ready
**From:** user@fake.com
**Subject:** Hey let's make sure to get that lunch.
**Category:** `personal` | **Draft ID:** `r9876543210987654321`
**Summary:** Alex is asking if you are still available to meet for lunch next week.

**Applied Memory Rules:**
- keep replies casual, under 2 sentences, and sign off with '- A'

---
**Proposed Draft:**
---text
Yeah, I'm still free, so just let me know what day works best for you!

- A
---

openwebui-draft-memory-recall.png

Example 2: Content-Conditional Triage & Auto-Trash Review Chats

Not every email from a domain should be treated identically—for example, linkedin.com sends both noisy feed digests and important coworker/connection requests.

  1. When a LinkedIn feed digest arrived, Workflow A classified it as automated and opened a Summary [automated] chat (with no Gmail draft).
  2. In that chat, I replied with a conditional rule:

    “delete — for linkedin.com emails, auto-delete feed digests, suggested posts, and promotional updates, but keep and summarize connection requests, coworker invitations, and direct messages.”

  3. When a subsequent LinkedIn career-insight promo arrived (messages-noreply@linkedin.com), Workflow A matched the rule, moved it to Gmail Trash, and posted an Auto-Trashed review card in Open WebUI:
### Auto-Trashed Email (Matched Learned Rule)
**From:** messages-noreply@linkedin.com
**Subject:**  Engineer: Acme Corp hired near you
**Label / Category:** `advertisement`
**Reason:** Rule 1 specifies auto-deleting promotional updates and feed digests; this is a LinkedIn career insight update.
**Matched Triage Rules:**
- auto-delete feed digests, suggested posts, and promotional updates; keep and summarize connection requests, coworker invitations, and direct messages

openwebui-autotrash-and-status.png

Similarly, a monthly billing email (ebill@billing.example.com — “Your Monthly Billing Statement is Ready”) landed as a Summary [finance] chat without creating a draft, where I taught a global rule to summarize and auto-delete routine FYI statements while keeping overdue/failed-payment alerts in my inbox.

Querying Qdrant confirms all three structured rules stored cleanly in email_draft_memory:

> k exec -n n8n deploy/n8n -- wget -qO- \
  --header="Content-Type: application/json" \
  --post-data='{"limit":10,"with_payload":true,"with_vector":false}' \
  http://qdrant.qdrant.svc.cluster.local:6333/collections/email_draft_memory/points/scroll | jq '.result.points[].payload'
{
  "rule": "keep replies casual, under 2 sentences, and sign off with '- A'",
  "scope": "sender",
  "category": "scheduling",
  "sender_email": "user@fake.com",
  "sender_domain": "fake.com"
}
{
  "rule": "auto-delete feed digests, suggested posts, and promotional updates; keep and summarize connection requests, coworker invitations, and direct messages",
  "rule_type": "triage",
  "action_policy": "auto_trash",
  "scope": "domain",
  "category": "automated",
  "sender_domain": "linkedin.com"
}
{
  "rule": "summarize key details (sender, account, amount/due date) and auto-delete routine FYI monthly billing statements and statement-ready or autopay notifications; summarize only overdue notices, failed payments, or bills requiring manual action",
  "rule_type": "triage",
  "action_policy": "auto_trash",
  "scope": "global",
  "category": "billing_statement"
}

Example 3: Heartbeat Run Log & Error Alerts

When the 4-hour cron completes with no new unread emails, Workflow A appends a single timestamped line to Email Assistant — Run Status (keeping the last 30 runs):

### Email Assistant — Run Status Log
_Automatic heartbeat when Workflow A completes with no new emails to process (last 30 runs kept)._

✅ **Nov 27, 2026, 10:28 PM (UTC):** Inbox check succeeded — **0 unread messages**.

Troubleshooting & Lessons Learned

A few real snags we hit and fixed along the way:

  1. n8n Init:0/1 FailedAttachVolume deadlock: The community n8n chart defaults to strategy.type: RollingUpdate, which deadlocks on a ReadWriteOnce (ceph-block) PVC because the new pod cannot mount the volume while the old pod is still running. Setting strategy: { type: Recreate, rollingUpdate: null } fixed it permanently.
  2. Unable to sign without access token on imported gmailOAuth2 credentials: @n8n/client-oauth2 throws before sending a request if oauthTokenData.access_token is empty, so n8n’s automatic 401 → refresh_token flow never triggers. Minting an initial access_token from refresh_token inside the import-workflows initContainer solved this cleanly.
  3. --activeState=fromJson fails in single-instance n8n: n8n import:workflow --activeState=fromJson is only supported in queue/multi-main mode. Dropping that flag and gating imports with a SHA-256 hash file on the PVC ensures normal pod restarts never unpublish workflows.
  4. Open WebUI background follow-up tasks overwriting Gmail drafts: Right after receiving a reply from the Pipe, Open WebUI sent an internal "### Task: Suggest 3-5 follow-up questions" request to the same Pipe model, which hit n8n and overwrote the Gmail draft with {"follow_ups": [...]}. Guarding on __task__ / ### Task: and making pipe async def with asyncio.to_thread(...) fixed both the phantom webhook calls and Redis event-loop timeouts.
  5. Multi-item Postgres alwaysOutputData: true index shifting: When 2 unread emails entered Check Existing Session (one new with 0 DB rows, one existing with 1 DB row), Postgres dropped the 0-row item and output a 1-element array—shifting index 1 down to index 0 and causing the new email to be skipped. Matching Postgres results strictly by key (Set of gmail_message_id and active gmail_thread_id) instead of array index eliminated the bug completely.
  6. Kustomize ConfigMap hash rewrites with Helm charts: Removing disableNameSuffixHash: true alone wasn’t enough for Kustomize to rewrite Deployment/n8n’s workflows volume reference because the Helm chart omits metadata.namespace on the Deployment. Commenting out namespace: n8n on the n8n-workflows configMapGenerator aligned the namespaces so Kustomize rewrites the Deployment automatically and triggers rollouts only when a workflow JSON changes.