@antoneeo/mkt-agentic-sdlc-skill 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,567 +1,703 @@
1
- #!/usr/bin/env python3
2
- """mkt_check.py -- mechanical validator for mkt_docs/ (Marketing Agentic SDLC).
3
-
4
- Commands:
5
- check [--root R] [--strict] run validate + ledger + budget + funnel + trace
6
- validate [--root R] [--strict] frontmatter + index freshness on canonical docs
7
- ledger [--root R] evidence ledger integrity + [EV-nn] reference resolution
8
- budget [--root R] [FILE] budget allocation sums to Total budget (±1%)
9
- funnel [--root R] [FILE] funnel model rows recompute (±5%)
10
- trace [--root R] objective -> tactic -> KPI chain
11
- index [--root R] (re)generate mkt_docs/INDEX.md
12
-
13
- Exit codes: 0 clean (warnings allowed unless --strict), 1 errors (or warnings
14
- under --strict), 2 usage / structural problem (no mkt_docs).
15
-
16
- Pure stdlib. ASCII output only (Windows-console safe).
17
- """
18
-
19
- import argparse
20
- import re
21
- import sys
22
- from pathlib import Path
23
-
24
- CANONICAL_DIRS = ("vision", "strategy", "tactics", "deliverables")
25
- VALID_STATUS = ("CURRENT", "SUPERSEDED", "DRAFT", "DEPRECATED")
26
- LEDGER_CLASSES = ("FACT", "BENCHMARK", "ASSUMPTION")
27
- CONFIDENCE_VALUES = ("HIGH", "MED", "MEDIUM", "LOW")
28
- EV_REF = re.compile(r"\[(EV-\d+)\]")
29
- OBJECTIVE_HEADING = re.compile(r"^###\s+(O\d+)\b", re.MULTILINE)
30
- OBJECTIVE_TOKEN = re.compile(r"\bO\d+\b")
31
- EXAMPLE_MARKER = "(example)"
32
-
33
- BUDGET_TOLERANCE = 0.01 # ±1% on allocation sum
34
- FUNNEL_TOLERANCE = 0.05 # ±5% on recomputed funnel cells
35
-
36
-
37
- class Report:
38
- def __init__(self):
39
- self.errors = []
40
- self.warnings = []
41
-
42
- def error(self, msg):
43
- self.errors.append(msg)
44
-
45
- def warn(self, msg):
46
- self.warnings.append(msg)
47
-
48
- def merge(self, other):
49
- self.errors.extend(other.errors)
50
- self.warnings.extend(other.warnings)
51
-
52
- def print(self, title):
53
- for w in self.warnings:
54
- print(f"[WARN] {title}: {w}")
55
- for e in self.errors:
56
- print(f"[ERROR] {title}: {e}")
57
-
58
- def exit_code(self, strict=False):
59
- if self.errors:
60
- return 1
61
- if strict and self.warnings:
62
- return 1
63
- return 0
64
-
65
-
66
- # ---------------------------------------------------------------- helpers
67
-
68
- def find_root(root_arg):
69
- """Resolve the project root: --root wins, else walk up from cwd."""
70
- if root_arg:
71
- root = Path(root_arg).resolve()
72
- return root if (root / "mkt_docs").is_dir() else None
73
- cur = Path.cwd().resolve()
74
- for candidate in (cur, *cur.parents):
75
- if (candidate / "mkt_docs").is_dir():
76
- return candidate
77
- return None
78
-
79
-
80
- def read_text(path):
81
- return path.read_text(encoding="utf-8", errors="replace")
82
-
83
-
84
- def load_frontmatter(text):
85
- """Return (dict, body). Tolerant: missing frontmatter -> ({}, text)."""
86
- if not text.startswith("---"):
87
- return {}, text
88
- lines = text.split("\n")
89
- fm = {}
90
- for i, line in enumerate(lines[1:], start=1):
91
- if line.strip() == "---":
92
- return fm, "\n".join(lines[i + 1:])
93
- m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", line)
94
- if m:
95
- fm[m.group(1).strip()] = m.group(2).strip()
96
- return {}, text # unterminated frontmatter: treat as body
97
-
98
-
99
- def parse_num(cell):
100
- """Parse a table-cell number: strips currency symbols, spaces, commas,
101
- percent signs and [EV-nn] refs; supports k/M suffix. Returns float or None."""
102
- if cell is None:
103
- return None
104
- s = EV_REF.sub("", cell)
105
- s = re.sub(r"[^\dkKmM.,%-]", "", s.strip())
106
- s = s.replace(",", "").replace("%", "")
107
- if not s:
108
- return None
109
- mult = 1.0
110
- if s and s[-1] in "kK":
111
- mult, s = 1_000.0, s[:-1]
112
- elif s and s[-1] in "mM":
113
- mult, s = 1_000_000.0, s[:-1]
114
- try:
115
- return float(s) * mult
116
- except ValueError:
117
- return None
118
-
119
-
120
- def parse_tables(text):
121
- """Return every markdown table as (header_cells_lower, rows) where each
122
- row is a dict {header_lower: cell}."""
123
- tables = []
124
- lines = text.split("\n")
125
- i = 0
126
- while i < len(lines):
127
- line = lines[i].strip()
128
- if line.startswith("|") and i + 1 < len(lines) \
129
- and re.match(r"^\|[\s\-:|]+\|$", lines[i + 1].strip()):
130
- headers = [h.strip().lower() for h in line.strip("|").split("|")]
131
- rows = []
132
- j = i + 2
133
- while j < len(lines) and lines[j].strip().startswith("|"):
134
- cells = [c.strip() for c in lines[j].strip().strip("|").split("|")]
135
- if len(cells) >= len(headers) - 1: # tolerate ragged tail
136
- row = {}
137
- for k, h in enumerate(headers):
138
- row[h] = cells[k] if k < len(cells) else ""
139
- rows.append(row)
140
- j += 1
141
- tables.append((headers, rows))
142
- i = j
143
- else:
144
- i += 1
145
- return tables
146
-
147
-
148
- def find_table(text, required_cols):
149
- """First table whose header contains every required column (contains-match)."""
150
- req = [c.lower() for c in required_cols]
151
- for headers, rows in parse_tables(text):
152
- if all(any(r in h for h in headers) for r in req):
153
- return headers, rows
154
- # exact-name pass for short names like 'kpi'
155
- if all(r in headers for r in req):
156
- return headers, rows
157
- return None, None
158
-
159
-
160
- def col(row, name):
161
- """Fetch a cell by contains-match on the header name."""
162
- name = name.lower()
163
- if name in row:
164
- return row[name]
165
- for h, v in row.items():
166
- if name in h:
167
- return v
168
- return None
169
-
170
-
171
- def is_example_row(row):
172
- return any(EXAMPLE_MARKER in (v or "") for v in row.values())
173
-
174
-
175
- def close_enough(stated, computed, tol):
176
- if stated is None or computed is None:
177
- return True # missing cells reported separately
178
- if computed == 0:
179
- return abs(stated) < 1e-9
180
- return abs(stated - computed) / abs(computed) <= tol
181
-
182
-
183
- def canonical_files(root):
184
- docs = root / "mkt_docs"
185
- for d in CANONICAL_DIRS:
186
- base = docs / d
187
- if base.is_dir():
188
- for p in sorted(base.rglob("*.md")):
189
- yield p
190
-
191
-
192
- def all_md_files(root):
193
- docs = root / "mkt_docs"
194
- for p in sorted(docs.rglob("*.md")):
195
- yield p
196
-
197
-
198
- # ---------------------------------------------------------------- index
199
-
200
- def build_index(root):
201
- docs = root / "mkt_docs"
202
- lines = [
203
- "# mkt_docs INDEX (generated by mkt_check.py index -- do not edit by hand)",
204
- "",
205
- "| Path | Description | Status |",
206
- "|---|---|---|",
207
- ]
208
- for p in canonical_files(root):
209
- if p.name == "INDEX.md":
210
- continue
211
- fm, body = load_frontmatter(read_text(p))
212
- desc = fm.get("description", "")
213
- status = fm.get("status", "")
214
- if not desc:
215
- h1 = re.search(r"^#\s+(.+)$", body, re.MULTILINE)
216
- desc = h1.group(1).strip() if h1 else ""
217
- rel = p.relative_to(docs).as_posix()
218
- lines.append(f"| {rel} | {desc} | {status} |")
219
- return "\n".join(lines) + "\n"
220
-
221
-
222
- def cmd_index(root):
223
- content = build_index(root)
224
- out = root / "mkt_docs" / "INDEX.md"
225
- out.write_text(content, encoding="utf-8")
226
- print(f"[OK] wrote {out.relative_to(root).as_posix()}")
227
- return 0
228
-
229
-
230
- # ---------------------------------------------------------------- validate
231
-
232
- def run_validate(root):
233
- rep = Report()
234
- docs = root / "mkt_docs"
235
- known = {p.name for p in docs.rglob("*.md")}
236
- for p in canonical_files(root):
237
- if p.name == "INDEX.md":
238
- continue
239
- rel = p.relative_to(docs).as_posix()
240
- fm, _ = load_frontmatter(read_text(p))
241
- status = fm.get("status", "")
242
- if not status:
243
- rep.warn(f"{rel}: missing frontmatter 'status'")
244
- elif status.upper() not in VALID_STATUS:
245
- rep.warn(f"{rel}: invalid status '{status}' (expected {'|'.join(VALID_STATUS)})")
246
- sup = fm.get("supersedes", "")
247
- if sup and Path(sup).name not in known:
248
- rep.warn(f"{rel}: supersedes '{sup}' which does not exist under mkt_docs/")
249
- index_path = docs / "INDEX.md"
250
- if not index_path.exists():
251
- rep.warn("mkt_docs/INDEX.md missing -- generate with 'mkt_check.py index'")
252
- elif read_text(index_path) != build_index(root):
253
- rep.warn("mkt_docs/INDEX.md stale -- regenerate with 'mkt_check.py index'")
254
- return rep
255
-
256
-
257
- # ---------------------------------------------------------------- ledger
258
-
259
- def load_ledger(root):
260
- """Return (rows, report). Rows: list of dicts with id/claim/class/... keys."""
261
- rep = Report()
262
- path = root / "mkt_docs" / "research" / "evidence_ledger.md"
263
- if not path.exists():
264
- rep.error("research/evidence_ledger.md missing")
265
- return [], rep
266
- headers, rows = find_table(read_text(path), ["id", "claim", "class", "source"])
267
- if rows is None:
268
- rep.error("evidence_ledger.md: ledger table not found "
269
- "(need columns ID | Claim | Class | ... | Source | ...)")
270
- return [], rep
271
- entries = []
272
- seen = set()
273
- for row in rows:
274
- rid = (col(row, "id") or "").strip()
275
- if not rid:
276
- continue
277
- if is_example_row(row):
278
- continue
279
- if not re.fullmatch(r"EV-\d+", rid):
280
- rep.error(f"ledger: bad ID '{rid}' (expected EV-<n>)")
281
- continue
282
- if rid in seen:
283
- rep.error(f"ledger: duplicate ID {rid}")
284
- seen.add(rid)
285
- entries.append(row)
286
- return entries, rep
287
-
288
-
289
- def run_ledger(root):
290
- entries, rep = load_ledger(root)
291
- ids = set()
292
- for row in entries:
293
- rid = col(row, "id").strip()
294
- ids.add(rid)
295
- cls = (col(row, "class") or "").strip().upper()
296
- source = (col(row, "source") or "").strip()
297
- date = (col(row, "date") or "").strip()
298
- confidence = (col(row, "confidence") or "").strip().upper()
299
- if cls not in LEDGER_CLASSES:
300
- rep.error(f"ledger {rid}: class '{cls}' invalid (FACT|BENCHMARK|ASSUMPTION)")
301
- continue
302
- if cls == "BENCHMARK":
303
- if "http" not in source.lower():
304
- rep.error(f"ledger {rid}: BENCHMARK without a source URL")
305
- if not date:
306
- rep.error(f"ledger {rid}: BENCHMARK without a date")
307
- if cls == "ASSUMPTION":
308
- if confidence not in CONFIDENCE_VALUES:
309
- rep.error(f"ledger {rid}: ASSUMPTION without confidence (HIGH|MED|LOW)")
310
- value = (col(row, "value") or "").strip()
311
- if value and not re.search(r"\d\s*[-–—]\s*\d|\bto\b", value):
312
- rep.warn(f"ledger {rid}: ASSUMPTION value looks like a point estimate, expected a range")
313
- # reference resolution across every md file (ledger file itself excluded)
314
- referenced = set()
315
- ledger_path = root / "mkt_docs" / "research" / "evidence_ledger.md"
316
- for p in all_md_files(root):
317
- if p == ledger_path:
318
- continue
319
- text = read_text(p)
320
- for line in text.split("\n"):
321
- if EXAMPLE_MARKER in line:
322
- continue
323
- for m in EV_REF.finditer(line):
324
- referenced.add(m.group(1))
325
- if m.group(1) not in ids:
326
- rel = p.relative_to(root / "mkt_docs").as_posix()
327
- rep.error(f"{rel}: reference [{m.group(1)}] not found in the ledger")
328
- for rid in sorted(ids - referenced, key=lambda x: int(x.split("-")[1])):
329
- rep.warn(f"ledger {rid}: never referenced by any document")
330
- return rep
331
-
332
-
333
- # ---------------------------------------------------------------- budget
334
-
335
- def default_tactical_files(root, file_arg):
336
- if file_arg:
337
- p = Path(file_arg)
338
- if not p.is_absolute():
339
- p = root / file_arg
340
- return [p] if p.exists() else []
341
- tactics = root / "mkt_docs" / "tactics"
342
- files = []
343
- if (tactics / "TACTICAL_PLAN.md").exists():
344
- files.append(tactics / "TACTICAL_PLAN.md")
345
- if tactics.is_dir():
346
- files.extend(sorted(tactics.glob("CAMPAIGN_*.md")))
347
- return files
348
-
349
-
350
- def run_budget(root, file_arg=None):
351
- rep = Report()
352
- files = default_tactical_files(root, file_arg)
353
- if not files:
354
- rep.warn("no tactical plan found (tactics/TACTICAL_PLAN.md) -- budget check skipped")
355
- return rep
356
- for path in files:
357
- rel = path.name
358
- text = read_text(path)
359
- m = re.search(r"^Total budget:\s*(.+)$", text, re.MULTILINE | re.IGNORECASE)
360
- if not m:
361
- rep.error(f"{rel}: 'Total budget:' line missing")
362
- continue
363
- total = parse_num(m.group(1))
364
- if total is None or total <= 0:
365
- rep.error(f"{rel}: cannot parse Total budget '{m.group(1).strip()}'")
366
- continue
367
- headers, rows = find_table(text, ["channel", "budget", "share"])
368
- if rows is None:
369
- rep.error(f"{rel}: Budget Allocation table not found (Channel | Budget | Share)")
370
- continue
371
- rows = [r for r in rows if not is_example_row(r)]
372
- if not rows:
373
- rep.error(f"{rel}: Budget Allocation table has no rows")
374
- continue
375
- alloc = 0.0
376
- for r in rows:
377
- v = parse_num(col(r, "budget"))
378
- if v is None:
379
- rep.error(f"{rel}: unparseable budget cell '{col(r, 'budget')}' "
380
- f"for channel '{col(r, 'channel')}'")
381
- else:
382
- alloc += v
383
- if not close_enough(alloc, total, BUDGET_TOLERANCE):
384
- rep.error(f"{rel}: allocations sum to {alloc:g}, Total budget is {total:g} "
385
- f"(tolerance 1%)")
386
- return rep
387
-
388
-
389
- # ---------------------------------------------------------------- funnel
390
-
391
- FUNNEL_CHAIN = (
392
- # (stated_col, compute, label)
393
- ("clicks", lambda b, cpc, cvr, close, r: b / cpc if cpc else None, "Budget/CPC"),
394
- ("leads", lambda b, cpc, cvr, close, r: (r["clicks"] * cvr / 100.0)
395
- if (r["clicks"] is not None and cvr is not None) else None, "Clicks*CVR%"),
396
- ("customers", lambda b, cpc, cvr, close, r: (r["leads"] * close / 100.0)
397
- if (r["leads"] is not None and close is not None) else None, "Leads*Close%"),
398
- ("cac", lambda b, cpc, cvr, close, r: (b / r["customers"])
399
- if (r["customers"] not in (None, 0) and b is not None) else None, "Budget/Customers"),
400
- )
401
-
402
-
403
- def run_funnel(root, file_arg=None):
404
- rep = Report()
405
- files = default_tactical_files(root, file_arg)
406
- if not files:
407
- rep.warn("no tactical plan found -- funnel check skipped")
408
- return rep
409
- for path in files:
410
- rel = path.name
411
- text = read_text(path)
412
- headers, rows = find_table(text, ["channel", "budget", "cpc", "cvr", "customers", "cac"])
413
- if rows is None:
414
- rep.error(f"{rel}: Funnel Model table not found "
415
- "(Channel | Budget | CPC | Clicks | CVR % | Leads | Close % | Customers | CAC)")
416
- continue
417
- rows = [r for r in rows if not is_example_row(r)]
418
- if not rows:
419
- rep.error(f"{rel}: Funnel Model table has no rows")
420
- continue
421
- for r in rows:
422
- channel = col(r, "channel") or "?"
423
- budget = parse_num(col(r, "budget"))
424
- cpc = parse_num(col(r, "cpc"))
425
- cvr = parse_num(col(r, "cvr"))
426
- close = parse_num(col(r, "close"))
427
- stated = {
428
- "clicks": parse_num(col(r, "clicks")),
429
- "leads": parse_num(col(r, "leads")),
430
- "customers": parse_num(col(r, "customers")),
431
- "cac": parse_num(col(r, "cac")),
432
- }
433
- if budget is None or cpc is None:
434
- rep.error(f"{rel} [{channel}]: Budget/CPC missing or unparseable")
435
- continue
436
- # verify each stated cell against computation from STATED upstream
437
- # cells (so a single wrong cell does not cascade into four errors)
438
- chain_inputs = dict(stated)
439
- for name, compute, label in FUNNEL_CHAIN:
440
- computed = compute(budget, cpc, cvr, close, chain_inputs)
441
- if stated[name] is None:
442
- rep.error(f"{rel} [{channel}]: '{name}' cell missing")
443
- continue
444
- if computed is None:
445
- continue # upstream missing, already reported
446
- if not close_enough(stated[name], computed, FUNNEL_TOLERANCE):
447
- rep.error(f"{rel} [{channel}]: {name}={stated[name]:g} but {label} "
448
- f"= {computed:g} (tolerance 5%)")
449
- return rep
450
-
451
-
452
- # ---------------------------------------------------------------- trace
453
-
454
- def run_trace(root):
455
- rep = Report()
456
- docs = root / "mkt_docs"
457
- obj_path = docs / "strategy" / "OBJECTIVES.md"
458
- if not obj_path.exists():
459
- rep.warn("strategy/OBJECTIVES.md missing -- trace check skipped")
460
- return rep
461
- objectives = set(OBJECTIVE_HEADING.findall(read_text(obj_path)))
462
- if not objectives:
463
- rep.error("OBJECTIVES.md: no '### O<n> --...' headings found")
464
- return rep
465
-
466
- tactical = docs / "tactics" / "TACTICAL_PLAN.md"
467
- served = set()
468
- if tactical.exists():
469
- headers, rows = find_table(read_text(tactical), ["channel", "objective", "kpi"])
470
- if rows is None:
471
- rep.error("TACTICAL_PLAN.md: Channel Plan table not found "
472
- "(Channel | Objective | KPI | Budget | Owner)")
473
- else:
474
- for r in rows:
475
- if is_example_row(r):
476
- continue
477
- tokens = set(OBJECTIVE_TOKEN.findall(col(r, "objective") or ""))
478
- if not tokens:
479
- rep.error(f"TACTICAL_PLAN.md [{col(r, 'channel')}]: no objective (O<n>) named")
480
- for t in tokens:
481
- if t not in objectives:
482
- rep.error(f"TACTICAL_PLAN.md [{col(r, 'channel')}]: objective {t} "
483
- "not defined in OBJECTIVES.md")
484
- served |= tokens & objectives
485
- if not (col(r, "kpi") or "").strip():
486
- rep.error(f"TACTICAL_PLAN.md [{col(r, 'channel')}]: KPI cell empty")
487
- for o in sorted(objectives - served):
488
- rep.warn(f"objective {o}: no tactic serves it in TACTICAL_PLAN.md")
489
- else:
490
- rep.warn("tactics/TACTICAL_PLAN.md missing -- tactic trace skipped")
491
-
492
- measure = docs / "tactics" / "MEASUREMENT_PLAN.md"
493
- if measure.exists():
494
- headers, rows = find_table(read_text(measure), ["objective", "kpi", "target"])
495
- if rows is None:
496
- rep.error("MEASUREMENT_PLAN.md: KPI table not found (Objective | KPI | Target | ...)")
497
- else:
498
- measured = set()
499
- for r in rows:
500
- if is_example_row(r):
501
- continue
502
- measured |= set(OBJECTIVE_TOKEN.findall(col(r, "objective") or ""))
503
- for o in sorted(objectives - measured):
504
- rep.error(f"objective {o}: no KPI row in MEASUREMENT_PLAN.md")
505
- else:
506
- rep.warn("tactics/MEASUREMENT_PLAN.md missing -- KPI trace skipped")
507
- return rep
508
-
509
-
510
- # ---------------------------------------------------------------- check
511
-
512
- def run_check(root):
513
- rep = Report()
514
- for title, fn in (("validate", run_validate), ("ledger", run_ledger),
515
- ("budget", run_budget), ("funnel", run_funnel),
516
- ("trace", run_trace)):
517
- sub = fn(root)
518
- sub.print(title)
519
- rep.merge(sub)
520
- return rep
521
-
522
-
523
- # ---------------------------------------------------------------- main
524
-
525
- def main(argv=None):
526
- parser = argparse.ArgumentParser(prog="mkt_check.py", description=__doc__)
527
- parser.add_argument("command", choices=["check", "validate", "ledger",
528
- "budget", "funnel", "trace", "index"])
529
- parser.add_argument("file", nargs="?", default=None,
530
- help="optional target file for budget/funnel")
531
- parser.add_argument("--root", default=None, help="project root (contains mkt_docs/)")
532
- parser.add_argument("--strict", action="store_true",
533
- help="warnings also fail the exit code")
534
- args = parser.parse_args(argv)
535
-
536
- root = find_root(args.root)
537
- if root is None:
538
- print("[ERROR] no mkt_docs/ directory found (use --root or run mkt-sdlc-init)")
539
- return 2
540
-
541
- if args.command == "index":
542
- return cmd_index(root)
543
-
544
- runners = {
545
- "validate": lambda: run_validate(root),
546
- "ledger": lambda: run_ledger(root),
547
- "budget": lambda: run_budget(root, args.file),
548
- "funnel": lambda: run_funnel(root, args.file),
549
- "trace": lambda: run_trace(root),
550
- }
551
- if args.command == "check":
552
- rep = run_check(root)
553
- else:
554
- rep = runners[args.command]()
555
- rep.print(args.command)
556
-
557
- code = rep.exit_code(strict=args.strict)
558
- if code == 0:
559
- print(f"[OK] {args.command} clean "
560
- f"({len(rep.warnings)} warning(s))" if rep.warnings else f"[OK] {args.command} clean")
561
- else:
562
- print(f"[FAIL] {args.command}: {len(rep.errors)} error(s), {len(rep.warnings)} warning(s)")
563
- return code
564
-
565
-
566
- if __name__ == "__main__":
567
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """mkt_check.py -- the MARKETING domain entry point.
3
+
4
+ The family's shared spine lives in `sdlc_core.py`, byte-identical in every
5
+ distribution; this file is the marketing OVERLAY on top of it. It is deliberately
6
+ not thin: a marketing plan is not a set of ANALYSIS documents, so the document
7
+ model (`vision/ strategy/ tactics/ deliverables/`, the evidence ledger, the budget
8
+ and funnel arithmetic) is genuinely this domain's own and stays here. What
9
+ converges is the spine, not the paperwork.
10
+
11
+ From the overlay (unchanged behaviour, unchanged exit codes):
12
+ check [--root R] [--strict] run validate + ledger + budget + funnel + trace
13
+ validate [--root R] [--strict] frontmatter + index freshness on canonical docs
14
+ ledger [--root R] evidence ledger integrity + [EV-nn] reference resolution
15
+ budget [--root R] [FILE] budget allocation sums to Total budget (+/-1%)
16
+ funnel [--root R] [FILE] funnel model rows recompute (+/-5%)
17
+ trace [--root R] objective -> tactic -> KPI chain
18
+ index [--root R] (re)generate INDEX.md
19
+
20
+ From the shared core (new to this distribution):
21
+ stale / mark / gate / orient / plan / migrate -- the spine commands, identical everywhere
22
+
23
+ Both files must sit in the same directory. Copying only this one fails at import,
24
+ loudly, which is the intended failure.
25
+
26
+ Docs root: `mkt_docs/` by default. `--docs-dir ai_docs` reaches a migrated project,
27
+ which is what makes the move to the family's single tree possible at all.
28
+
29
+ Exit codes: 0 clean (warnings allowed unless --strict), 1 errors (or warnings
30
+ under --strict), 2 usage / structural problem (no docs root).
31
+
32
+ Pure stdlib. ASCII output only (Windows-console safe).
33
+ """
34
+
35
+ import argparse
36
+ import re
37
+ import sys
38
+ from pathlib import Path
39
+
40
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
41
+
42
+ try:
43
+ import sdlc_core
44
+ except ImportError as exc: # pragma: no cover - exercised by the copied-file test
45
+ sys.stderr.write(
46
+ "[ERROR] mkt_check.py cannot find sdlc_core.py next to it: " + str(exc) + "\n"
47
+ " The validator ships as TWO files since the multi-domain core.\n"
48
+ " Copy both, or run sdlc_core.py directly.\n")
49
+ sys.exit(1)
50
+
51
+ # This distribution IS the marketing lens. The default docs root is its own; the
52
+ # core still resolves `--docs-dir` and the env seam on top of it, so a project that
53
+ # has migrated to the family's single `ai_docs/` tree is reachable from here too.
54
+ DOMAIN = "marketing"
55
+ MKT_DOCS_DIR = "mkt_docs"
56
+ sdlc_core.set_entry_point(DOMAIN, provides=("marketing",))
57
+ sdlc_core.set_docs_dir(MKT_DOCS_DIR)
58
+
59
+ sdlc_core.set_profile(
60
+ skill_name="mkt-agentic-sdlc",
61
+ unit_noun="engagement",
62
+ support_files=("templates.md", "frameworks.md", "research.md", "elicitation.md",
63
+ "review.md", "routing.md", "guides.md", "vision.md", "dispatch.md",
64
+ "ENFORCEMENT.md"),
65
+ capabilities=(
66
+ # spine
67
+ "triage", "write_triggers", "workstream_registry", "vision_gate",
68
+ "design_review_gate", "guide_router", "worktree_hygiene",
69
+ # marketing overlay
70
+ "subagent_dispatch", "question_discipline",
71
+ ),
72
+ # The strategy is reviewed before any tactic is executed: nine phases, but the
73
+ # ordering the gate cares about is the same one every domain owes.
74
+ design_gate_between=("### 6. Strategy", "### 8. Action"),
75
+ )
76
+
77
+ # The subcommands this overlay implements itself. Anything else on the command
78
+ # line is handed straight to the shared core, so a spine command this file never
79
+ # heard of (as `migrate` once was) cannot be silently dropped by a stale list here.
80
+ OVERLAY_COMMANDS = ("check", "validate", "ledger", "budget", "funnel", "trace", "index")
81
+
82
+ CANONICAL_DIRS = ("vision", "strategy", "tactics", "deliverables")
83
+ VALID_STATUS = ("CURRENT", "SUPERSEDED", "DRAFT", "DEPRECATED")
84
+ LEDGER_CLASSES = ("FACT", "BENCHMARK", "ASSUMPTION")
85
+ CONFIDENCE_VALUES = ("HIGH", "MED", "MEDIUM", "LOW")
86
+ EV_REF = re.compile(r"\[(EV-\d+)\]")
87
+ # A source that points INSIDE this engagement instead of at the world: a document of
88
+ # OUR OWN under a canonical dir, or the "see X" form. Only FACT can carry it today,
89
+ # because FACT is the one class the URL rule does not reach.
90
+ INTERNAL_SOURCE_RE = re.compile(
91
+ r"(?:\b(?:mkt_docs|ai_docs|research|strategy|tactics|deliverables|vision)/\S*\.md\b"
92
+ r"|\b(?:see|vedi|cfr\.?)\s)", re.IGNORECASE)
93
+ # The two origins research.md sanctions for a FACT. A cell that opens by naming the
94
+ # client is exempt: their own primary data may well be a Markdown file they handed
95
+ # over, and telling its author to "reclassify as BENCHMARK and add a URL" would be
96
+ # advice to misclassify.
97
+ CLIENT_ORIGIN_RE = re.compile(
98
+ r"^\s*(?:user|client|owner|utente|cliente|titolare|proprietario)\b", re.IGNORECASE)
99
+ OBJECTIVE_HEADING = re.compile(r"^###\s+(O\d+)\b", re.MULTILINE)
100
+ OBJECTIVE_TOKEN = re.compile(r"\bO\d+\b")
101
+ EXAMPLE_MARKER = "(example)"
102
+
103
+ BUDGET_TOLERANCE = 0.01 # ±1% on allocation sum
104
+ FUNNEL_TOLERANCE = 0.05 # ±5% on recomputed funnel cells
105
+
106
+
107
+ class Report:
108
+ def __init__(self):
109
+ self.errors = []
110
+ self.warnings = []
111
+
112
+ def error(self, msg):
113
+ self.errors.append(msg)
114
+
115
+ def warn(self, msg):
116
+ self.warnings.append(msg)
117
+
118
+ def merge(self, other):
119
+ self.errors.extend(other.errors)
120
+ self.warnings.extend(other.warnings)
121
+
122
+ def print(self, title):
123
+ for w in self.warnings:
124
+ print(f"[WARN] {title}: {w}")
125
+ for e in self.errors:
126
+ print(f"[ERROR] {title}: {e}")
127
+
128
+ def exit_code(self, strict=False):
129
+ if self.errors:
130
+ return 1
131
+ if strict and self.warnings:
132
+ return 1
133
+ return 0
134
+
135
+
136
+ # ---------------------------------------------------------------- helpers
137
+
138
+ def find_root(root_arg, docs_dir=None):
139
+ """Resolve the project root: --root wins, else walk up from cwd.
140
+
141
+ The docs-root NAME comes from the core (`--docs-dir`, then the env seam, then
142
+ discovery, then this distribution's `mkt_docs`), so one project mid-migration
143
+ cannot be validated half under one root and half under the other.
144
+ """
145
+ if docs_dir:
146
+ sdlc_core.set_docs_dir(docs_dir)
147
+ name = sdlc_core.docs_dir()
148
+ if root_arg:
149
+ root = Path(root_arg).resolve()
150
+ return root if (root / name).is_dir() else None
151
+ cur = Path.cwd().resolve()
152
+ for candidate in (cur, *cur.parents):
153
+ if (candidate / name).is_dir():
154
+ return candidate
155
+ return None
156
+
157
+
158
+ def read_text(path):
159
+ return path.read_text(encoding="utf-8", errors="replace")
160
+
161
+
162
+ def load_frontmatter(text):
163
+ """Return (dict, body). Tolerant: missing frontmatter -> ({}, text)."""
164
+ if not text.startswith("---"):
165
+ return {}, text
166
+ lines = text.split("\n")
167
+ fm = {}
168
+ for i, line in enumerate(lines[1:], start=1):
169
+ if line.strip() == "---":
170
+ return fm, "\n".join(lines[i + 1:])
171
+ m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", line)
172
+ if m:
173
+ fm[m.group(1).strip()] = m.group(2).strip()
174
+ return {}, text # unterminated frontmatter: treat as body
175
+
176
+
177
+ def parse_num(cell):
178
+ """Parse a table-cell number: strips currency symbols, spaces, commas,
179
+ percent signs and [EV-nn] refs; supports k/M suffix. Returns float or None."""
180
+ if cell is None:
181
+ return None
182
+ s = EV_REF.sub("", cell)
183
+ s = re.sub(r"[^\dkKmM.,%-]", "", s.strip())
184
+ s = s.replace(",", "").replace("%", "")
185
+ if not s:
186
+ return None
187
+ mult = 1.0
188
+ if s and s[-1] in "kK":
189
+ mult, s = 1_000.0, s[:-1]
190
+ elif s and s[-1] in "mM":
191
+ mult, s = 1_000_000.0, s[:-1]
192
+ try:
193
+ return float(s) * mult
194
+ except ValueError:
195
+ return None
196
+
197
+
198
+ def parse_tables(text):
199
+ """Return every markdown table as (header_cells_lower, rows) where each
200
+ row is a dict {header_lower: cell}."""
201
+ tables = []
202
+ lines = text.split("\n")
203
+ i = 0
204
+ while i < len(lines):
205
+ line = lines[i].strip()
206
+ if line.startswith("|") and i + 1 < len(lines) \
207
+ and re.match(r"^\|[\s\-:|]+\|$", lines[i + 1].strip()):
208
+ headers = [h.strip().lower() for h in line.strip("|").split("|")]
209
+ rows = []
210
+ j = i + 2
211
+ while j < len(lines) and lines[j].strip().startswith("|"):
212
+ cells = [c.strip() for c in lines[j].strip().strip("|").split("|")]
213
+ if len(cells) >= len(headers) - 1: # tolerate ragged tail
214
+ row = {}
215
+ for k, h in enumerate(headers):
216
+ row[h] = cells[k] if k < len(cells) else ""
217
+ rows.append(row)
218
+ j += 1
219
+ tables.append((headers, rows))
220
+ i = j
221
+ else:
222
+ i += 1
223
+ return tables
224
+
225
+
226
+ def find_table(text, required_cols):
227
+ """First table whose header contains every required column (contains-match)."""
228
+ req = [c.lower() for c in required_cols]
229
+ for headers, rows in parse_tables(text):
230
+ if all(any(r in h for h in headers) for r in req):
231
+ return headers, rows
232
+ # exact-name pass for short names like 'kpi'
233
+ if all(r in headers for r in req):
234
+ return headers, rows
235
+ return None, None
236
+
237
+
238
+ def col(row, name):
239
+ """Fetch a cell by contains-match on the header name."""
240
+ name = name.lower()
241
+ if name in row:
242
+ return row[name]
243
+ for h, v in row.items():
244
+ if name in h:
245
+ return v
246
+ return None
247
+
248
+
249
+ def is_example_row(row):
250
+ return any(EXAMPLE_MARKER in (v or "") for v in row.values())
251
+
252
+
253
+ def close_enough(stated, computed, tol):
254
+ if stated is None or computed is None:
255
+ return True # missing cells reported separately
256
+ if computed == 0:
257
+ return abs(stated) < 1e-9
258
+ return abs(stated - computed) / abs(computed) <= tol
259
+
260
+
261
+ def canonical_files(root):
262
+ docs = sdlc_core.ai_path(root)
263
+ for d in CANONICAL_DIRS:
264
+ base = docs / d
265
+ if base.is_dir():
266
+ for p in sorted(base.rglob("*.md")):
267
+ yield p
268
+
269
+
270
+ def all_md_files(root):
271
+ docs = sdlc_core.ai_path(root)
272
+ for p in sorted(docs.rglob("*.md")):
273
+ yield p
274
+
275
+
276
+ # ---------------------------------------------------------------- index
277
+
278
+ def build_index(root):
279
+ docs = sdlc_core.ai_path(root)
280
+ lines = [
281
+ "# mkt_docs INDEX (generated by mkt_check.py index -- do not edit by hand)",
282
+ "",
283
+ "| Path | Description | Status |",
284
+ "|---|---|---|",
285
+ ]
286
+ for p in canonical_files(root):
287
+ if p.name == "INDEX.md":
288
+ continue
289
+ fm, body = load_frontmatter(read_text(p))
290
+ desc = fm.get("description", "")
291
+ status = fm.get("status", "")
292
+ if not desc:
293
+ h1 = re.search(r"^#\s+(.+)$", body, re.MULTILINE)
294
+ desc = h1.group(1).strip() if h1 else ""
295
+ rel = p.relative_to(docs).as_posix()
296
+ lines.append(f"| {rel} | {desc} | {status} |")
297
+ return "\n".join(lines) + "\n"
298
+
299
+
300
+ def cmd_index(root):
301
+ content = build_index(root)
302
+ out = sdlc_core.ai_path(root) / "INDEX.md"
303
+ out.write_text(content, encoding="utf-8")
304
+ print(f"[OK] wrote {out.relative_to(root).as_posix()}")
305
+ return 0
306
+
307
+
308
+ # ---------------------------------------------------------------- validate
309
+
310
+ def run_validate(root):
311
+ rep = Report()
312
+ docs = sdlc_core.ai_path(root)
313
+ known = {p.name for p in docs.rglob("*.md")}
314
+ for p in canonical_files(root):
315
+ if p.name == "INDEX.md":
316
+ continue
317
+ rel = p.relative_to(docs).as_posix()
318
+ fm, _ = load_frontmatter(read_text(p))
319
+ status = fm.get("status", "")
320
+ if not status:
321
+ rep.warn(f"{rel}: missing frontmatter 'status'")
322
+ elif status.upper() not in VALID_STATUS:
323
+ rep.warn(f"{rel}: invalid status '{status}' (expected {'|'.join(VALID_STATUS)})")
324
+ sup = fm.get("supersedes", "")
325
+ if sup and Path(sup).name not in known:
326
+ rep.warn(f"{rel}: supersedes '{sup}' which does not exist under mkt_docs/")
327
+ index_path = docs / "INDEX.md"
328
+ if not index_path.exists():
329
+ rep.warn("mkt_docs/INDEX.md missing -- generate with 'mkt_check.py index'")
330
+ elif read_text(index_path) != build_index(root):
331
+ rep.warn("mkt_docs/INDEX.md stale -- regenerate with 'mkt_check.py index'")
332
+ return rep
333
+
334
+
335
+ # ---------------------------------------------------------------- ledger
336
+
337
+ def load_ledger(root):
338
+ """Return (rows, report). Rows: list of dicts with id/claim/class/... keys."""
339
+ rep = Report()
340
+ path = sdlc_core.ai_path(root) / "research" / "evidence_ledger.md"
341
+ if not path.exists():
342
+ rep.error("research/evidence_ledger.md missing")
343
+ return [], rep
344
+ headers, rows = find_table(read_text(path), ["id", "claim", "class", "source"])
345
+ if rows is None:
346
+ rep.error("evidence_ledger.md: ledger table not found "
347
+ "(need columns ID | Claim | Class | ... | Source | ...)")
348
+ return [], rep
349
+ entries = []
350
+ seen = set()
351
+ for row in rows:
352
+ rid = (col(row, "id") or "").strip()
353
+ if not rid:
354
+ continue
355
+ if is_example_row(row):
356
+ continue
357
+ if not re.fullmatch(r"EV-\d+", rid):
358
+ rep.error(f"ledger: bad ID '{rid}' (expected EV-<n>)")
359
+ continue
360
+ if rid in seen:
361
+ rep.error(f"ledger: duplicate ID {rid}")
362
+ seen.add(rid)
363
+ entries.append(row)
364
+ return entries, rep
365
+
366
+
367
+ def run_ledger(root):
368
+ entries, rep = load_ledger(root)
369
+ ids = set()
370
+ for row in entries:
371
+ rid = col(row, "id").strip()
372
+ ids.add(rid)
373
+ cls = (col(row, "class") or "").strip().upper()
374
+ source = (col(row, "source") or "").strip()
375
+ date = (col(row, "date") or "").strip()
376
+ confidence = (col(row, "confidence") or "").strip().upper()
377
+ if cls not in LEDGER_CLASSES:
378
+ rep.error(f"ledger {rid}: class '{cls}' invalid (FACT|BENCHMARK|ASSUMPTION)")
379
+ continue
380
+ if cls == "BENCHMARK":
381
+ if "http" not in source.lower():
382
+ rep.error(f"ledger {rid}: BENCHMARK without a source URL")
383
+ if not date:
384
+ rep.error(f"ledger {rid}: BENCHMARK without a date")
385
+ if cls == "FACT" and not source:
386
+ rep.error(f"ledger {rid}: FACT without a source -- name the origin "
387
+ "('user, Wave 1' or the client's data file)")
388
+ if (cls == "FACT" and source and not CLIENT_ORIGIN_RE.match(source)
389
+ and INTERNAL_SOURCE_RE.search(source)):
390
+ # FACT means "the client told me" or "the client's own primary data" — the
391
+ # one class that legitimately has no URL. Pointing it at another document
392
+ # of this engagement is how a researched observation gets in without the
393
+ # URL its class would owe: the row cites a file that cites the source, the
394
+ # validator resolves nothing, and "see VOC.md" is exactly the form the
395
+ # BENCHMARK rule rejects. Observed in a cold-agent field test, 2026-08-02.
396
+ rep.error(f"ledger {rid}: FACT sourced to an internal document ('{source}') -- "
397
+ "a FACT is what the client stated or their own primary data; an "
398
+ "observation gathered by research is a BENCHMARK and owes its URL")
399
+ if cls == "ASSUMPTION":
400
+ if confidence not in CONFIDENCE_VALUES:
401
+ rep.error(f"ledger {rid}: ASSUMPTION without confidence (HIGH|MED|LOW)")
402
+ value = (col(row, "value") or "").strip()
403
+ if value and not re.search(r"\d\s*[-–—]\s*\d|\bto\b", value):
404
+ rep.warn(f"ledger {rid}: ASSUMPTION value looks like a point estimate, expected a range")
405
+ # reference resolution across every md file (ledger file itself excluded)
406
+ referenced = set()
407
+ ledger_path = sdlc_core.ai_path(root) / "research" / "evidence_ledger.md"
408
+ for p in all_md_files(root):
409
+ if p == ledger_path:
410
+ continue
411
+ text = read_text(p)
412
+ for line in text.split("\n"):
413
+ if EXAMPLE_MARKER in line:
414
+ continue
415
+ for m in EV_REF.finditer(line):
416
+ referenced.add(m.group(1))
417
+ if m.group(1) not in ids:
418
+ rel = p.relative_to(sdlc_core.ai_path(root)).as_posix()
419
+ rep.error(f"{rel}: reference [{m.group(1)}] not found in the ledger")
420
+ for rid in sorted(ids - referenced, key=lambda x: int(x.split("-")[1])):
421
+ rep.warn(f"ledger {rid}: never referenced by any document")
422
+ return rep
423
+
424
+
425
+ # ---------------------------------------------------------------- budget
426
+
427
+ def default_tactical_files(root, file_arg):
428
+ if file_arg:
429
+ p = Path(file_arg)
430
+ if not p.is_absolute():
431
+ p = root / file_arg
432
+ return [p] if p.exists() else []
433
+ tactics = sdlc_core.ai_path(root) / "tactics"
434
+ files = []
435
+ if (tactics / "TACTICAL_PLAN.md").exists():
436
+ files.append(tactics / "TACTICAL_PLAN.md")
437
+ if tactics.is_dir():
438
+ files.extend(sorted(tactics.glob("CAMPAIGN_*.md")))
439
+ return files
440
+
441
+
442
+ def run_budget(root, file_arg=None):
443
+ rep = Report()
444
+ files = default_tactical_files(root, file_arg)
445
+ if not files:
446
+ rep.warn("no tactical plan found (tactics/TACTICAL_PLAN.md) -- budget check skipped")
447
+ return rep
448
+ for path in files:
449
+ rel = path.name
450
+ text = read_text(path)
451
+ m = re.search(r"^Total budget:\s*(.+)$", text, re.MULTILINE | re.IGNORECASE)
452
+ if not m:
453
+ rep.error(f"{rel}: 'Total budget:' line missing")
454
+ continue
455
+ total = parse_num(m.group(1))
456
+ if total is None or total <= 0:
457
+ rep.error(f"{rel}: cannot parse Total budget '{m.group(1).strip()}'")
458
+ continue
459
+ headers, rows = find_table(text, ["channel", "budget", "share"])
460
+ if rows is None:
461
+ rep.error(f"{rel}: Budget Allocation table not found (Channel | Budget | Share)")
462
+ continue
463
+ rows = [r for r in rows if not is_example_row(r)]
464
+ if not rows:
465
+ rep.error(f"{rel}: Budget Allocation table has no rows")
466
+ continue
467
+ alloc = 0.0
468
+ for r in rows:
469
+ v = parse_num(col(r, "budget"))
470
+ if v is None:
471
+ rep.error(f"{rel}: unparseable budget cell '{col(r, 'budget')}' "
472
+ f"for channel '{col(r, 'channel')}'")
473
+ else:
474
+ alloc += v
475
+ if not close_enough(alloc, total, BUDGET_TOLERANCE):
476
+ rep.error(f"{rel}: allocations sum to {alloc:g}, Total budget is {total:g} "
477
+ f"(tolerance 1%)")
478
+ return rep
479
+
480
+
481
+ # ---------------------------------------------------------------- funnel
482
+
483
+ FUNNEL_CHAIN = (
484
+ # (stated_col, compute, label)
485
+ ("clicks", lambda b, cpc, cvr, close, r: b / cpc if cpc else None, "Budget/CPC"),
486
+ ("leads", lambda b, cpc, cvr, close, r: (r["clicks"] * cvr / 100.0)
487
+ if (r["clicks"] is not None and cvr is not None) else None, "Clicks*CVR%"),
488
+ ("customers", lambda b, cpc, cvr, close, r: (r["leads"] * close / 100.0)
489
+ if (r["leads"] is not None and close is not None) else None, "Leads*Close%"),
490
+ ("cac", lambda b, cpc, cvr, close, r: (b / r["customers"])
491
+ if (r["customers"] not in (None, 0) and b is not None) else None, "Budget/Customers"),
492
+ )
493
+
494
+
495
+ def run_funnel(root, file_arg=None):
496
+ rep = Report()
497
+ files = default_tactical_files(root, file_arg)
498
+ if not files:
499
+ rep.warn("no tactical plan found -- funnel check skipped")
500
+ return rep
501
+ for path in files:
502
+ rel = path.name
503
+ text = read_text(path)
504
+ headers, rows = find_table(text, ["channel", "budget", "cpc", "cvr", "customers", "cac"])
505
+ if rows is None:
506
+ rep.error(f"{rel}: Funnel Model table not found "
507
+ "(Channel | Budget | CPC | Clicks | CVR % | Leads | Close % | Customers | CAC)")
508
+ continue
509
+ rows = [r for r in rows if not is_example_row(r)]
510
+ if not rows:
511
+ rep.error(f"{rel}: Funnel Model table has no rows")
512
+ continue
513
+ for r in rows:
514
+ channel = col(r, "channel") or "?"
515
+ budget = parse_num(col(r, "budget"))
516
+ cpc = parse_num(col(r, "cpc"))
517
+ cvr = parse_num(col(r, "cvr"))
518
+ close = parse_num(col(r, "close"))
519
+ stated = {
520
+ "clicks": parse_num(col(r, "clicks")),
521
+ "leads": parse_num(col(r, "leads")),
522
+ "customers": parse_num(col(r, "customers")),
523
+ "cac": parse_num(col(r, "cac")),
524
+ }
525
+ if budget is None or cpc is None:
526
+ rep.error(f"{rel} [{channel}]: Budget/CPC missing or unparseable")
527
+ continue
528
+ # verify each stated cell against computation from STATED upstream
529
+ # cells (so a single wrong cell does not cascade into four errors)
530
+ chain_inputs = dict(stated)
531
+ for name, compute, label in FUNNEL_CHAIN:
532
+ computed = compute(budget, cpc, cvr, close, chain_inputs)
533
+ if stated[name] is None:
534
+ rep.error(f"{rel} [{channel}]: '{name}' cell missing")
535
+ continue
536
+ if computed is None:
537
+ continue # upstream missing, already reported
538
+ if not close_enough(stated[name], computed, FUNNEL_TOLERANCE):
539
+ rep.error(f"{rel} [{channel}]: {name}={stated[name]:g} but {label} "
540
+ f"= {computed:g} (tolerance 5%)")
541
+ return rep
542
+
543
+
544
+ # ---------------------------------------------------------------- trace
545
+
546
+ def run_trace(root):
547
+ rep = Report()
548
+ docs = sdlc_core.ai_path(root)
549
+ obj_path = docs / "strategy" / "OBJECTIVES.md"
550
+ if not obj_path.exists():
551
+ rep.warn("strategy/OBJECTIVES.md missing -- trace check skipped")
552
+ return rep
553
+ objectives = set(OBJECTIVE_HEADING.findall(read_text(obj_path)))
554
+ if not objectives:
555
+ rep.error("OBJECTIVES.md: no '### O<n> --...' headings found")
556
+ return rep
557
+
558
+ tactical = docs / "tactics" / "TACTICAL_PLAN.md"
559
+ served = set()
560
+ if tactical.exists():
561
+ headers, rows = find_table(read_text(tactical), ["channel", "objective", "kpi"])
562
+ if rows is None:
563
+ rep.error("TACTICAL_PLAN.md: Channel Plan table not found "
564
+ "(Channel | Objective | KPI | Budget | Owner)")
565
+ else:
566
+ for r in rows:
567
+ if is_example_row(r):
568
+ continue
569
+ tokens = set(OBJECTIVE_TOKEN.findall(col(r, "objective") or ""))
570
+ if not tokens:
571
+ rep.error(f"TACTICAL_PLAN.md [{col(r, 'channel')}]: no objective (O<n>) named")
572
+ for t in tokens:
573
+ if t not in objectives:
574
+ rep.error(f"TACTICAL_PLAN.md [{col(r, 'channel')}]: objective {t} "
575
+ "not defined in OBJECTIVES.md")
576
+ served |= tokens & objectives
577
+ if not (col(r, "kpi") or "").strip():
578
+ rep.error(f"TACTICAL_PLAN.md [{col(r, 'channel')}]: KPI cell empty")
579
+ for o in sorted(objectives - served):
580
+ rep.warn(f"objective {o}: no tactic serves it in TACTICAL_PLAN.md")
581
+ else:
582
+ rep.warn("tactics/TACTICAL_PLAN.md missing -- tactic trace skipped")
583
+
584
+ measure = docs / "tactics" / "MEASUREMENT_PLAN.md"
585
+ if measure.exists():
586
+ headers, rows = find_table(read_text(measure), ["objective", "kpi", "target"])
587
+ if rows is None:
588
+ rep.error("MEASUREMENT_PLAN.md: KPI table not found (Objective | KPI | Target | ...)")
589
+ else:
590
+ measured = set()
591
+ for r in rows:
592
+ if is_example_row(r):
593
+ continue
594
+ measured |= set(OBJECTIVE_TOKEN.findall(col(r, "objective") or ""))
595
+ for o in sorted(objectives - measured):
596
+ rep.error(f"objective {o}: no KPI row in MEASUREMENT_PLAN.md")
597
+ else:
598
+ rep.warn("tactics/MEASUREMENT_PLAN.md missing -- KPI trace skipped")
599
+ return rep
600
+
601
+
602
+ # ---------------------------------------------------------------- check
603
+
604
+ def run_check(root):
605
+ rep = Report()
606
+ for title, fn in (("validate", run_validate), ("ledger", run_ledger),
607
+ ("budget", run_budget), ("funnel", run_funnel),
608
+ ("trace", run_trace)):
609
+ sub = fn(root)
610
+ sub.print(title)
611
+ rep.merge(sub)
612
+ return rep
613
+
614
+
615
+ # ---------------------------------------------------------------- main
616
+
617
+ # --- portable checks this distribution exposes -------------------------------
618
+ # The marketing arithmetic, offered to documents owned by ANOTHER domain: a
619
+ # distilled spec that carries a budget table can import `marketing.budget` and have
620
+ # it actually checked, instead of the table sitting in a document whose own
621
+ # validator has no opinion about it (UC8). Imported checks may only ADD findings.
622
+
623
+ def _report_findings(rep):
624
+ return ([("error", m) for m in rep.errors]
625
+ + [("warning", m) for m in rep.warnings])
626
+
627
+
628
+ @sdlc_core.portable_check("marketing.ledger")
629
+ def _check_ledger(rel, meta, text):
630
+ root = sdlc_core.find_project_root()
631
+ return _report_findings(run_ledger(root)) if root else []
632
+
633
+
634
+ @sdlc_core.portable_check("marketing.budget")
635
+ def _check_budget(rel, meta, text):
636
+ root = sdlc_core.find_project_root()
637
+ return _report_findings(run_budget(root)) if root else []
638
+
639
+
640
+ @sdlc_core.portable_check("marketing.funnel")
641
+ def _check_funnel(rel, meta, text):
642
+ root = sdlc_core.find_project_root()
643
+ return _report_findings(run_funnel(root)) if root else []
644
+
645
+
646
+ def main(argv=None):
647
+ argv = list(sys.argv[1:] if argv is None else argv)
648
+ # Spine commands are the core's, identical in every distribution: hand over
649
+ # every subcommand this overlay does not explicitly intercept, untouched,
650
+ # rather than keeping a hand-copied list of spine names here -- which is how
651
+ # `migrate` got dropped while SKILL.md kept promising it.
652
+ if argv and not argv[0].startswith("-") and argv[0] not in OVERLAY_COMMANDS:
653
+ return sdlc_core.main(argv)
654
+
655
+ parser = argparse.ArgumentParser(prog="mkt_check.py", description=__doc__)
656
+ parser.add_argument("command", choices=list(OVERLAY_COMMANDS))
657
+ parser.add_argument("file", nargs="?", default=None,
658
+ help="optional target file for budget/funnel")
659
+ parser.add_argument("--root", default=None, help="project root (contains the docs root)")
660
+ parser.add_argument("--docs-dir", dest="docs_dir", default=None,
661
+ help="name of the documentation root (default: mkt_docs; "
662
+ "use --docs-dir ai_docs on a project that has migrated "
663
+ "to the family's single tree)")
664
+ parser.add_argument("--strict", action="store_true",
665
+ help="warnings also fail the exit code")
666
+ args = parser.parse_args(argv)
667
+
668
+ # Resolve the docs root fresh on EVERY invocation, from this distribution's own
669
+ # default: the core keeps it in module state, and an entry point that inherited
670
+ # whatever a previous call left behind would be answering the wrong question.
671
+ root = find_root(args.root, args.docs_dir or MKT_DOCS_DIR)
672
+ if root is None:
673
+ print(f"[ERROR] no {sdlc_core.docs_dir()}/ directory found "
674
+ "(use --root or run mkt-sdlc-init)")
675
+ return 2
676
+
677
+ if args.command == "index":
678
+ return cmd_index(root)
679
+
680
+ runners = {
681
+ "validate": lambda: run_validate(root),
682
+ "ledger": lambda: run_ledger(root),
683
+ "budget": lambda: run_budget(root, args.file),
684
+ "funnel": lambda: run_funnel(root, args.file),
685
+ "trace": lambda: run_trace(root),
686
+ }
687
+ if args.command == "check":
688
+ rep = run_check(root)
689
+ else:
690
+ rep = runners[args.command]()
691
+ rep.print(args.command)
692
+
693
+ code = rep.exit_code(strict=args.strict)
694
+ if code == 0:
695
+ print(f"[OK] {args.command} clean "
696
+ f"({len(rep.warnings)} warning(s))" if rep.warnings else f"[OK] {args.command} clean")
697
+ else:
698
+ print(f"[FAIL] {args.command}: {len(rep.errors)} error(s), {len(rep.warnings)} warning(s)")
699
+ return code
700
+
701
+
702
+ if __name__ == "__main__":
703
+ sys.exit(main())