fsbtactic-code/marketing-brain-skill / skills/marketing-brain
marketing-brain
FlaggedCreate, improve, research, or audit marketing strategy and execution using a bundled marketing library, verified live primary sources for volatile facts, and clearly labeled agent judgment. Use for full marketing systems, audits, landing pages and CRO, competitor intelligence, brand voice, audience and JTBD research, email sequences, SMM and social content systems, paid ads, headlines, copywriting, positioning, offers, launches, GTM, growth, funnels, retention, pricing, SEO, analytics, attribution, experiments, and consumer or buyer psychology. Trigger for English and Russian requests, including requests for ready-to-use assets.
scripts/search_knowledge.py
View on GitHubfrom __future__ import annotations
import argparse
import json
import sqlite3
import sys
from pathlib import Path
from typing import Any
SKILL_ROOT = Path(__file__).resolve().parents[1]
ASSET_ROOT = SKILL_ROOT / "assets"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Search verified Marketing Brain cards.")
parser.add_argument("--query", required=True)
parser.add_argument("--domain")
parser.add_argument("--limit", type=int, default=5)
parser.add_argument("--json", action="store_true", dest="as_json")
return parser.parse_args()
def normalize_limit(value: int) -> int:
return max(1, min(value, 20))
def fts_query(value: str) -> str:
terms = [term.strip('"\'()[]{}:*') for term in value.split()]
clean = [term for term in terms if term]
return " OR ".join(f'"{term}"' for term in clean)
def decode_json(value: Any, default: Any) -> Any:
if isinstance(value, str):
try:
return json.loads(value)
except json.JSONDecodeError:
return default
return value if value is not None else default
def attach_sqlite_context(
connection: sqlite3.Connection, cards: list[dict[str, Any]]
) -> list[dict[str, Any]]:
if not cards:
return cards
card_ids = [card["card_id"] for card in cards]
source_ids = sorted(
{
ref.get("source_id")
for card in cards
for ref in decode_json(card.get("source_refs_json"), [])
if ref.get("source_id")
}
)
sources: dict[str, dict[str, Any]] = {}
if source_ids:
placeholders = ",".join("?" for _ in source_ids)
rows = connection.execute(
f"SELECT * FROM sources WHERE source_id IN ({placeholders})", source_ids
)
sources = {row["source_id"]: dict(row) for row in rows}
placeholders = ",".join("?" for _ in card_ids)
edge_rows = connection.execute(
f"SELECT * FROM edges WHERE subject_id IN ({placeholders}) "
f"OR object_id IN ({placeholders}) ORDER BY edge_id",
card_ids + card_ids,
)
edges = [dict(row) for row in edge_rows]
for card in cards:
refs = decode_json(card.get("source_refs_json"), [])
card["source_refs"] = refs
card["source_details"] = [
sources[ref["source_id"]]
for ref in refs
if ref.get("source_id") in sources
]
card["graph_relations"] = [
edge
for edge in edges
if edge["subject_id"] == card["card_id"] or edge["object_id"] == card["card_id"]
]
return cards
def search_sqlite(query: str, domain: str | None, limit: int) -> list[dict[str, Any]]:
path = ASSET_ROOT / "knowledge.sqlite"
if not path.exists():
return []
connection = sqlite3.connect(path)
connection.row_factory = sqlite3.Row
try:
sql = """
SELECT c.*, bm25(card_fts) AS rank
FROM card_fts
JOIN cards c ON c.rowid = card_fts.rowid
WHERE card_fts MATCH ?
"""
params: list[Any] = [fts_query(query)]
if domain:
sql += " AND c.domains_json LIKE ?"
params.append(f'%"{domain}"%')
sql += " ORDER BY rank LIMIT ?"
params.append(limit)
cards = [dict(row) for row in connection.execute(sql, params)]
return attach_sqlite_context(connection, cards)
except sqlite3.OperationalError:
return []
finally:
connection.close()
def score_card(card: dict[str, Any], terms: set[str]) -> int:
searchable = " ".join(
str(card.get(field, ""))
for field in ("claim", "application", "conditions", "limitations", "domains")
).casefold()
return sum(1 for term in terms if term in searchable)
def read_jsonl(path: Path) -> list[dict[str, Any]]:
if not path.exists():
return []
with path.open("r", encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def attach_jsonl_context(cards: list[dict[str, Any]]) -> list[dict[str, Any]]:
sources = {
source["source_id"]: source for source in read_jsonl(ASSET_ROOT / "sources.jsonl")
}
edges = read_jsonl(ASSET_ROOT / "edges.jsonl")
for card in cards:
refs = card.get("source_refs", [])
card["source_details"] = [
sources[ref["source_id"]]
for ref in refs
if ref.get("source_id") in sources
]
card["graph_relations"] = [
edge
for edge in edges
if edge.get("subject_id") == card.get("card_id")
or edge.get("object_id") == card.get("card_id")
]
return cards
def search_jsonl(query: str, domain: str | None, limit: int) -> list[dict[str, Any]]:
path = ASSET_ROOT / "cards.jsonl"
terms = {term.casefold() for term in query.split() if len(term) > 1}
matches: list[tuple[int, dict[str, Any]]] = []
for card in read_jsonl(path):
if domain and domain not in card.get("domains", []):
continue
score = score_card(card, terms)
if score:
matches.append((score, card))
matches.sort(key=lambda item: (-item[0], item[1].get("card_id", "")))
return attach_jsonl_context([card for _, card in matches[:limit]])
def render_markdown(cards: list[dict[str, Any]]) -> str:
if not cards:
return "No verified knowledge card matched the query."
blocks = []
for card in cards:
refs = card.get("source_refs") or json.loads(card.get("source_refs_json", "[]"))
sources = {source["source_id"]: source for source in card.get("source_details", [])}
ref_parts = []
for ref in refs:
source = sources.get(ref.get("source_id"), {})
title = source.get("title", ref.get("source_id"))
url = source.get("canonical_url")
label = f"[{title}]({url})" if url else str(title)
ref_parts.append(f"{label} [{ref.get('locator')}]")
relation_text = ", ".join(
f"{edge['subject_id']} {edge['relation']} {edge['object_id']}"
for edge in card.get("graph_relations", [])
if edge.get("relation") not in {"derived_from", "classified_as"}
)
blocks.append(
"\n".join(
[
f"## {card.get('card_id')}",
str(card.get("claim", "")),
f"Application: {card.get('application', '')}",
f"Evidence: {card.get('evidence_class', '')}",
f"Review due: {card.get('review_due', '')}",
f"Sources: {', '.join(ref_parts)}",
f"Relations: {relation_text or 'none'}",
]
)
)
return "\n\n".join(blocks)
def main() -> int:
args = parse_args()
limit = normalize_limit(args.limit)
cards = search_sqlite(args.query, args.domain, limit)
if not cards:
cards = search_jsonl(args.query, args.domain, limit)
if args.as_json:
json.dump(cards, sys.stdout, ensure_ascii=False, indent=2)
sys.stdout.write("\n")
else:
print(render_markdown(cards))
return 0
if __name__ == "__main__":
raise SystemExit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |