๐Ÿ— KeyzHub
19Keys ยท community archive
19608 bytes raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#!/usr/bin/env python3
"""
verify_email_marketing.py โ€” the email-strategist master's real verify gate.

Scores ONE deliverable file against the discipline rubric defined in
growth-masters/email-marketing/MANUAL.md ยง8.1, for the deliverable type
declared in the file's frontmatter. Exits 0 if the artifact meets the
standard, 1 if it fails, printing every named check that failed.

python3 stdlib only. No network, no LLM call โ€” this is a mechanical linter,
not a judgment call. It exists to catch the tells named in MANUAL.md ยง8.2
(open rates as success, unclosed loops, fake scarcity, multi-CTA emails,
blasting the whole list, skipping Layer 0, cherry-picked numbers, cadence
without freshness, corporate-blast tone).

Usage:
    python3 verify_email_marketing.py <path/to/deliverable.md>
"""

import re
import sys
from pathlib import Path

# ---------------------------------------------------------------------------
# House-voice banned vocabulary (mirrors ~/.claude/skills/brand-bible/skill.md
# "Absolute forbiddens" table). Case-insensitive substring match.
# ---------------------------------------------------------------------------
BANNED_VOCAB = [
    "โ€”",  # em-dash
    "delve",
    "leverage",
    "leveraging",
    "utilize",
    "paradigm shift",
    "in today's fast-paced world",
    "in conclusion",
    "it's worth noting",
    "it's important to note",
    "whilst",
    "moreover",
    "furthermore",
    "nevertheless",
    "vibrant tapestry",
    "rich tapestry",
    "bustling",
    "navigate the complexities",
    "a plethora of",
    "a myriad of",
    "foster",
    "empower",
    "empowerment",
    "seamless",
    "streamline",
    "robust",
    "holistic",
    "synergy",
    "cutting-edge",
    "ever-evolving",
    "multifaceted",
    "testament to",
]

URGENCY_WORDS = [
    "closes", "closing", "only", "last chance", "limited", "hurry",
    "deadline", "act now", "ends soon", "spots left", "running out",
    "expires", "final hours", "don't miss",
]

PRODUCT_LEDE_WORDS = [
    "ziion", "passport", "buy now", "purchase", "discount", "% off",
    "offer", "$", "price", "sale", "cart", "checkout", "order now",
]

GOAL_TAGS = {"orient", "story", "proof", "soft-pitch", "pitch"}

REQUIRED_ECOM_FLOWS = {
    "welcome", "browse-abandon", "cart-abandon", "post-purchase", "winback"
}

REQUIRED_AUDIT_ITEMS = {
    "spf": ["spf"],
    "dkim": ["dkim"],
    "dmarc": ["dmarc"],
    "one-click unsubscribe": ["one-click unsubscribe", "one click unsubscribe", "rfc 8058"],
    "spam-rate": ["spam-rate", "spam rate", "postmaster"],
    "list-hygiene": ["list-hygiene", "list hygiene", "sunset"],
    "warm-up plan": ["warm-up", "warmup", "warm up"],
}


# ---------------------------------------------------------------------------
# Generic helpers
# ---------------------------------------------------------------------------

def md_links(s):
    return re.findall(r'\[([^\]]+)\]\(([^)]+)\)', s or "")


def distinct_link_targets(s):
    """Number of distinct link destinations โ€” repeating the SAME CTA target
    twice in a body (reinforcement) is not a multi-CTA violation; two
    DIFFERENT destinations is (Fogg: one prompt, one action)."""
    return len({url for _, url in md_links(s)})


def word_count(s):
    return len(re.findall(r'\S+', s or ""))


def read_frontmatter_type(text):
    m = re.search(r'^---\s*\n(.*?)\n---\s*\n', text, re.DOTALL | re.MULTILINE)
    if not m:
        return None
    block = m.group(1)
    tm = re.search(r'^\s*type:\s*([a-z0-9_-]+)\s*$', block, re.MULTILINE | re.IGNORECASE)
    return tm.group(1).lower() if tm else None


def strip_frontmatter(text):
    return re.sub(r'^---\s*\n.*?\n---\s*\n', '', text, count=1, flags=re.DOTALL | re.MULTILINE)


def split_sections(text, header_pattern):
    """Split text into (header_line, body_text) chunks on a heading regex."""
    matches = list(re.finditer(header_pattern, text, re.MULTILINE))
    sections = []
    for i, m in enumerate(matches):
        start = m.end()
        end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
        sections.append((m.group(0).strip(), text[start:end]))
    return sections


def parse_fields(block_text):
    """Parse 'Key: value' lines up to a 'Body:' marker; everything after is body."""
    lines = block_text.splitlines()
    fields = {}
    body_lines = []
    in_body = False
    for line in lines:
        if not in_body:
            stripped = line.strip()
            if stripped.lower().startswith("body:"):
                in_body = True
                rest = stripped[5:].strip()
                if rest:
                    body_lines.append(rest)
                continue
            if not stripped:
                continue
            m = re.match(r'^([A-Za-z][A-Za-z _-]*):\s*(.*)$', stripped)
            if m:
                key = m.group(1).strip().lower().replace(" ", "_").replace("-", "_")
                fields[key] = m.group(2).strip()
        else:
            body_lines.append(line)
    body = "\n".join(body_lines).strip()
    return fields, body


def check_compliance(fields, idx, label, failures):
    unsub = fields.get("unsubscribe", "")
    postal = fields.get("postaladdress", "") or fields.get("postal_address", "")
    if "{{" not in unsub or "}}" not in unsub:
        failures.append(f"{label} {idx}: missing unsubscribe merge tag")
    if "{{" not in postal or "}}" not in postal:
        failures.append(f"{label} {idx}: missing postal-address merge tag")


def has_banned_vocab(text):
    low = text.lower()
    hits = []
    for w in BANNED_VOCAB:
        needle = w.lower()
        if needle == "โ€”":
            if "โ€”" in text:
                hits.append("em-dash")
        elif needle in low:
            hits.append(w)
    return hits


# ---------------------------------------------------------------------------
# Rubric: welcome-sequence
# ---------------------------------------------------------------------------

def check_welcome_sequence(text):
    failures = []
    sections = split_sections(text, r'^##\s*Email\s+(\d+)\s*$')
    if not sections:
        return ["no '## Email N' blocks found"]
    n = len(sections)
    if not (5 <= n <= 7):
        failures.append(f"sequence has {n} emails; must define 5-7")

    loops_opened = {}
    loops_closed = set()
    pitch_count = 0
    delivers_lead_magnet = False

    for idx, (header, block) in enumerate(sections, start=1):
        fields, body = parse_fields(block)

        for req in ("day", "subject", "goal", "cta"):
            if not fields.get(req):
                failures.append(f"email {idx}: missing required field '{req}'")

        subject = fields.get("subject", "")
        if subject and word_count(subject) > 9:
            failures.append(f"email {idx}: subject exceeds 9 words ('{subject}')")

        goal = fields.get("goal", "").lower()
        if goal and goal not in GOAL_TAGS:
            failures.append(f"email {idx}: invalid goal tag '{goal}' (must be one of {sorted(GOAL_TAGS)})")
        if goal == "pitch":
            pitch_count += 1
            if idx < 3:
                failures.append(f"email {idx}: hard pitch before email 3")

        loopopen = fields.get("loopopen", "none").lower()
        loopclose = fields.get("loopclose", "none").lower()
        if loopopen not in ("", "none"):
            loops_opened[loopopen] = idx
        if loopclose not in ("", "none"):
            loops_closed.add(loopclose)

        check_compliance(fields, idx, "email", failures)

        n_targets = distinct_link_targets(fields.get("cta", "") + "\n" + body)
        if n_targets != 1:
            failures.append(f"email {idx}: expected exactly 1 CTA link target, found {n_targets} (multi-CTA fails)")

        if idx == 1:
            delivers = fields.get("delivers", "").lower()
            if "lead-magnet" in delivers or "lead_magnet" in delivers:
                delivers_lead_magnet = True

    if not delivers_lead_magnet:
        failures.append("email 1 does not deliver the promised lead-magnet link (missing 'Delivers: lead-magnet')")

    if pitch_count != 1:
        failures.append(f"expected exactly 1 hard-pitch email (goal: pitch), found {pitch_count}")

    unclosed = sorted(lid for lid in loops_opened if lid not in loops_closed)
    if unclosed:
        failures.append(f"loop(s) opened and never closed: {unclosed}")

    return failures


# ---------------------------------------------------------------------------
# Rubric: launch-sequence
# ---------------------------------------------------------------------------

def check_launch_sequence(text):
    failures = []
    sections = split_sections(text, r'^##\s*Email\s+(\d+)\s*$')
    if not sections:
        return ["no '## Email N' blocks found"]

    counts = {"prelaunch": 0, "cart-open": 0, "proof": 0, "objection": 0, "deadline": 0, "post-close": 0}
    deadlines_seen = set()
    offers = set()

    for idx, (header, block) in enumerate(sections, start=1):
        fields, body = parse_fields(block)
        phase = fields.get("phase", "").lower()
        if phase in counts:
            counts[phase] += 1
        else:
            failures.append(f"email {idx}: missing/invalid Phase field ('{phase}')")

        if phase == "deadline":
            dl = fields.get("deadline", "")
            if not dl:
                failures.append(f"email {idx}: deadline-phase email missing 'Deadline' value")
            else:
                deadlines_seen.add(dl)

        offer = fields.get("offer", "")
        if offer:
            offers.add(offer)

        combined = (body + " " + fields.get("subject", "")).lower()
        has_urgency_language = any(w in combined for w in URGENCY_WORDS)
        urgency_tag = fields.get("urgency", "").lower()
        if has_urgency_language:
            if not urgency_tag.startswith("real:") or not urgency_tag.split(":", 1)[1].strip():
                failures.append(f"email {idx}: urgency language present but not tagged '[real:mechanism]'")

        check_compliance(fields, idx, "email", failures)

        n_targets = distinct_link_targets(fields.get("cta", "") + "\n" + body)
        if n_targets > 1:
            failures.append(f"email {idx}: multiple CTA link targets found ({n_targets})")

    if counts["prelaunch"] < 2:
        failures.append(f"only {counts['prelaunch']} prelaunch value email(s); need >=2")
    if counts["cart-open"] < 1:
        failures.append("missing cart-open email")
    if counts["proof"] < 1:
        failures.append("missing proof/social-proof email (need >=1)")
    if counts["objection"] < 1:
        failures.append("missing objection/FAQ email (need >=1)")
    if counts["deadline"] < 2:
        failures.append(f"only {counts['deadline']} deadline-day email(s); need >=2")
    if counts["post-close"] < 1:
        failures.append("missing post-close email")
    if len(deadlines_seen) > 1:
        failures.append(f"mismatched deadlines across deadline emails: {sorted(deadlines_seen)}")
    if len(offers) > 1:
        failures.append(f"multiple offers found ({sorted(offers)}); single offer per sequence required")

    return failures


# ---------------------------------------------------------------------------
# Rubric: ecom-flow-set
# ---------------------------------------------------------------------------

def check_ecom_flow_set(text):
    failures = []
    sections = split_sections(text, r'^##\s*Flow:\s*([a-zA-Z0-9_-]+)\s*$')
    if not sections:
        return ["no '## Flow: <name>' blocks found"]

    found_flows = set()
    for header, block in sections:
        m = re.match(r'^##\s*Flow:\s*([a-zA-Z0-9_-]+)', header, re.IGNORECASE)
        flowname = m.group(1).lower() if m else "unknown"
        found_flows.add(flowname)
        fields, body = parse_fields(block)

        if not fields.get("trigger"):
            failures.append(f"flow '{flowname}': missing Trigger event name")
        if not fields.get("exit"):
            failures.append(f"flow '{flowname}': missing Exit/suppression condition")
        if not fields.get("emails"):
            failures.append(f"flow '{flowname}': missing Emails count/timing offsets")
        if not fields.get("metric"):
            failures.append(f"flow '{flowname}': missing success Metric")
        if not fields.get("benchmark"):
            failures.append(f"flow '{flowname}': missing Benchmark reference")

    missing = REQUIRED_ECOM_FLOWS - found_flows
    if missing:
        failures.append(f"missing required flow(s): {sorted(missing)}")

    return failures


# ---------------------------------------------------------------------------
# Rubric: daily-email
# ---------------------------------------------------------------------------

def check_daily_email(text):
    failures = []
    sections = split_sections(text, r'^##\s*Email\s+(\d+)\s*$')
    if not sections:
        return ["no '## Email 1' block found"]
    if len(sections) != 1:
        failures.append(f"daily-email must be a single email; found {len(sections)} blocks")

    fields, body = parse_fields(sections[0][1])

    subject = fields.get("subject", "")
    if not subject:
        failures.append("missing Subject field")
    elif word_count(subject) > 9:
        failures.append(f"subject exceeds 9 words ('{subject}')")

    paragraphs = [p.strip() for p in re.split(r'\n\s*\n', body) if p.strip()]
    first_para = paragraphs[0] if paragraphs else ""
    if any(w in first_para.lower() for w in PRODUCT_LEDE_WORDS):
        failures.append("first paragraph mentions the product/hard-sells (hard-sell-first fails; lede must be story/observation)")

    if not fields.get("pivot"):
        failures.append("missing 'Pivot:' field (the bridge line from story to point)")

    n_targets = distinct_link_targets(fields.get("cta", "") + "\n" + body)
    if n_targets != 1:
        failures.append(f"expected exactly 1 CTA link target, found {n_targets} (multi-CTA fails)")

    wc = word_count(body)
    if wc > 350:
        failures.append(f"body is {wc} words; must be <=350")

    hits = has_banned_vocab(subject + " " + body)
    if hits:
        failures.append(f"house-voice check failed โ€” banned vocabulary found: {sorted(set(hits))}")

    check_compliance(fields, 1, "email", failures)

    return failures


# ---------------------------------------------------------------------------
# Rubric: reactivation-campaign
# ---------------------------------------------------------------------------

def check_reactivation_campaign(text):
    failures = []

    header_end = re.search(r'^##\s*Email\s+1\s*$', text, re.MULTILINE)
    preamble = text[: header_end.start()] if header_end else text
    pre_fields, _ = parse_fields(preamble)

    segment = pre_fields.get("segment", "")
    if not segment:
        failures.append("missing top-level 'Segment:' explicit inactivity rule")
    elif not re.search(r'\d+\s*d(ay)?s?', segment.lower()):
        failures.append(f"'Segment:' rule does not state an explicit day-based inactivity window ('{segment}')")

    sunset = pre_fields.get("sunset", "")
    if not sunset:
        failures.append("missing top-level 'Sunset:' rule for non-responders")

    deliverability_note = pre_fields.get("deliverabilitynote", "") or pre_fields.get("deliverability_note", "")
    if not deliverability_note:
        failures.append("missing top-level 'DeliverabilityNote:' explaining sender-reputation protection")

    sections = split_sections(text, r'^##\s*Email\s+(\d+)\s*$')
    if not sections:
        return failures + ["no '## Email N' blocks found"]

    n = len(sections)
    if not (2 <= n <= 3):
        failures.append(f"reactivation arc has {n} emails; must define 2-3")

    for idx, (header, block) in enumerate(sections, start=1):
        fields, body = parse_fields(block)
        check_compliance(fields, idx, "email", failures)
        if idx == 1:
            subj_wc = word_count(fields.get("subject", ""))
            body_wc = word_count(body)
            total = subj_wc + body_wc
            if total > 25:
                failures.append(f"email 1 is {total} words (subject+body); must be <=25 (nine-word-style)")

    return failures


# ---------------------------------------------------------------------------
# Rubric: deliverability-audit
# ---------------------------------------------------------------------------

def check_deliverability_audit(text):
    failures = []

    row_re = re.compile(r'^\|(.+)\|(.+)\|(.+)\|$')
    rows = []
    for line in text.splitlines():
        line = line.strip()
        m = row_re.match(line)
        if not m:
            continue
        cols = [c.strip() for c in m.groups()]
        # skip separator rows like | --- | --- | --- |
        if all(re.fullmatch(r':?-{2,}:?', c) for c in cols):
            continue
        # skip header row (labeled "Item"/"Status"/"Evidence")
        if cols[0].lower() in ("item", "check", "label"):
            continue
        rows.append(cols)

    if not rows:
        return ["no checklist table rows found (expected '| Item | [status] | Evidence |' rows)"]

    covered = set()
    for label, status, evidence in rows:
        status_m = re.search(r'\[(verified|failed|todo)\]', status.lower())
        if not status_m:
            failures.append(f"item '{label}': status column has no [verified|failed|todo] tag")
        if not evidence.strip() or evidence.strip() in ("", "-", "โ€”"):
            failures.append(f"item '{label}': no evidence line โ€” items with no evidence fail the linter")

        low_label = label.lower()
        for key, aliases in REQUIRED_AUDIT_ITEMS.items():
            if any(a in low_label for a in aliases):
                covered.add(key)

    missing = set(REQUIRED_AUDIT_ITEMS.keys()) - covered
    if missing:
        failures.append(f"missing required checklist item(s): {sorted(missing)}")

    spam_rows = [r for r in rows if "spam" in r[0].lower() or "postmaster" in r[0].lower()]
    if spam_rows and not any(re.search(r'0\.\d+\s*%|<\s*0\.3\s*%|<\s*0\.1\s*%', r[2]) for r in spam_rows):
        failures.append("spam-rate item does not state the numeric <0.3% threshold (or a reading) in its evidence")

    return failures


DISPATCH = {
    "welcome-sequence": check_welcome_sequence,
    "launch-sequence": check_launch_sequence,
    "ecom-flow-set": check_ecom_flow_set,
    "daily-email": check_daily_email,
    "reactivation-campaign": check_reactivation_campaign,
    "deliverability-audit": check_deliverability_audit,
}


def main(argv):
    if len(argv) != 2:
        print("usage: python3 verify_email_marketing.py <deliverable.md>", file=sys.stderr)
        return 2

    path = Path(argv[1])
    if not path.exists():
        print(f"FAIL: file not found: {path}", file=sys.stderr)
        return 1

    text = path.read_text(encoding="utf-8")
    dtype = read_frontmatter_type(text)
    if not dtype:
        print(f"FAIL: {path} โ€” no frontmatter 'type: <deliverable-type>' found", file=sys.stderr)
        return 1

    checker = DISPATCH.get(dtype)
    if not checker:
        print(f"FAIL: {path} โ€” unknown deliverable type '{dtype}' (known: {sorted(DISPATCH)})", file=sys.stderr)
        return 1

    body_text = strip_frontmatter(text)
    failures = checker(body_text)

    if failures:
        print(f"FAIL [{dtype}] {path} โ€” {len(failures)} check(s) failed:")
        for f in failures:
            print(f"  - {f}")
        return 1

    print(f"PASS [{dtype}] {path} โ€” meets the email-marketing rubric (MANUAL.md ยง8.1)")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))