Skip to content

fsbtactic-code/marketing-brain-skill / skills/marketing-brain

marketing-brain

Flagged

Create, 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.

FileKindSize
SKILL.mdskill md10.6 KB
agents/openai.yamlconfig325 B
assets/BUILD-MANIFEST.jsonconfig1.2 KB
assets/cards.jsonlother21.1 KB
assets/edges.jsonlother33.0 KB
assets/knowledge.sqlitebinary136.0 KB
assets/legacy-library.mbpack.parts/manifest.jsonconfig857 B
assets/legacy-library.mbpack.parts/part-0000.binbinary48.0 MB
assets/legacy-library.mbpack.parts/part-0001.binbinary48.0 MB
assets/legacy-library.mbpack.parts/part-0002.binbinary7.7 MB
assets/research-catalog.jsonlother280.4 KB
assets/source-channels.jsonlother52.1 KB
assets/sources.jsonlother10.2 KB
assets/templates/content-calendar.mdmarkdown1.3 KB
assets/templates/evidence-ledger.mdmarkdown1.3 KB
assets/templates/experiment-backlog.mdmarkdown1.2 KB
assets/templates/issue-registry.mdmarkdown1.2 KB
assets/templates/marketing-brief.mdmarkdown1.6 KB
assets/templates/marketing-system-manifest.jsonconfig1.1 KB
assets/wiki/cards/card_ad_effects_heterogeneous_by_firm.mdmarkdown1.3 KB
assets/wiki/cards/card_ad_roi_measurement_noise.mdmarkdown1.4 KB
assets/wiki/cards/card_choice_overload_context_dependent.mdmarkdown1.4 KB
assets/wiki/cards/card_cost_transparency_context.mdmarkdown1.2 KB
assets/wiki/cards/card_ftc_material_connection_disclosure.mdmarkdown1.4 KB
assets/wiki/cards/card_google_ads_experiment_hygiene.mdmarkdown1.3 KB
assets/wiki/cards/card_google_no_word_count_freshness_trick.mdmarkdown1.2 KB
assets/wiki/cards/card_google_people_first.mdmarkdown1.2 KB
assets/wiki/cards/card_google_who_how_why.mdmarkdown1.1 KB
assets/wiki/cards/card_incrementality_control_group.mdmarkdown1.2 KB
assets/wiki/cards/card_incrementality_precision_stratification.mdmarkdown1.3 KB
assets/wiki/cards/card_short_video_ad_spillover.mdmarkdown1.3 KB
assets/wiki/cards/card_telegram_ad_format.mdmarkdown1.0 KB
assets/wiki/cards/card_telegram_destination_quality.mdmarkdown1.1 KB
assets/wiki/cards/card_telegram_no_unsupported_absolutes.mdmarkdown1.0 KB
assets/wiki/cards/card_viral_content_arousal.mdmarkdown1.3 KB
assets/wiki/cards/card_youtube_audience_signals.mdmarkdown1.2 KB
assets/wiki/cards/card_youtube_publish_time.mdmarkdown1.4 KB
assets/wiki/cards/card_youtube_quality_over_frequency.mdmarkdown1.3 KB
assets/wiki/cards/card_youtube_search_ranking.mdmarkdown1.1 KB
assets/wiki/cards/card_youtube_tags_low_priority.mdmarkdown1019 B
assets/wiki/domains/consumer-behavior.mdmarkdown2.2 KB
assets/wiki/domains/content-editorial.mdmarkdown5.1 KB
assets/wiki/domains/creator-community.mdmarkdown1009 B
assets/wiki/domains/cro-funnels.mdmarkdown2.3 KB
assets/wiki/domains/law-policy-ethics.mdmarkdown2.8 KB
assets/wiki/domains/measurement-analytics.mdmarkdown4.5 KB
assets/wiki/domains/offer-messaging-copy.mdmarkdown2.7 KB
assets/wiki/domains/organic-smm.mdmarkdown4.9 KB
assets/wiki/domains/paid-acquisition.mdmarkdown6.2 KB
assets/wiki/domains/pricing-promotions.mdmarkdown850 B
assets/wiki/domains/seo-geo-ai-search.mdmarkdown2.8 KB
assets/wiki/domains/strategy-research.mdmarkdown932 B
assets/wiki/index.mdmarkdown935 B
assets/wiki/open-questions.mdmarkdown159 B
assets/wiki/pages.jsonlother18.3 KB
references/research-catalog-policy.mdmarkdown1.3 KB
references/retrieval-policy.mdmarkdown1.0 KB
references/task-playbooks.mdmarkdown5.1 KB
references/taxonomy.mdmarkdown1005 B
references/third-party-notices.mdmarkdown1.6 KB
references/workflow-audience.mdmarkdown8.4 KB
references/workflow-audit.mdmarkdown7.0 KB
references/workflow-brand-voice.mdmarkdown8.0 KB
references/workflow-competitors.mdmarkdown7.2 KB
references/workflow-email.mdmarkdown8.8 KB
references/workflow-full-system.mdmarkdown9.2 KB
references/workflow-headlines.mdmarkdown8.4 KB
references/workflow-landing-cro.mdmarkdown6.9 KB
references/workflow-paid-ads.mdmarkdown10.1 KB
references/workflow-social.mdmarkdown9.2 KB
scripts/marketing_context_output.pyscript7.3 KB
scripts/marketing_context_query.pyscript8.6 KB
scripts/materialize_legacy_pack.pyscript12.1 KB
scripts/mbpack_codec.pyscript4.1 KB
scripts/mbpack_output.pyscript5.2 KB
scripts/retrieve_marketing_context.pyscript13.1 KB
scripts/search_knowledge.pyscript7.2 KB
scripts/search_legacy_pack.pyscript131 B
scripts/search_private_pack.pyscript11.0 KB
scripts/search_research_catalog.pyscript6.2 KB
scripts/verify_public_install.pyscript7.1 KB

scripts/materialize_legacy_pack.py

View on GitHub
from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import tempfile
import zlib
from dataclasses import dataclass
from pathlib import Path
from typing import Any, BinaryIO, Sequence


SKILL_ROOT = Path(__file__).resolve().parents[1]
ASSET_ROOT = SKILL_ROOT / "assets"
DEFAULT_PACK = ASSET_ROOT / "legacy-library.mbpack"
BUFFER_SIZE = 1024 * 1024
SHARD_FORMAT = "marketing-brain-pack-shards"
SHARD_SCHEMA_VERSION = 1


@dataclass
class DecompressionState:
    decompressor: Any
    compressed_digest: Any
    pack_digest: Any
    maximum_pack_bytes: int


def sha256_path(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(BUFFER_SIZE), b""):
            digest.update(block)
    return digest.hexdigest()


def shard_root(pack_path: Path) -> Path:
    return pack_path.parent / f"{pack_path.name}.parts"


def shard_manifest_path(pack_path: Path) -> Path:
    return shard_root(pack_path) / "manifest.json"


def read_json(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(f"JSON object required: {path}")
    return value


def expected_pack_from_build_manifest(pack_path: Path) -> dict[str, Any]:
    path = pack_path.parent / "BUILD-MANIFEST.json"
    manifest = read_json(path)
    files = manifest.get("files")
    if not isinstance(files, dict):
        raise ValueError("BUILD-MANIFEST.json has no files object")
    digest = files.get(pack_path.name)
    if not isinstance(digest, str) or len(digest) != 64:
        raise ValueError(f"BUILD-MANIFEST.json has no hash for {pack_path.name}")
    return {"pack_sha256": digest, "pack_bytes": None}


def safe_part_name(value: object) -> str:
    if not isinstance(value, str) or not value:
        raise ValueError("Shard part name must be nonempty")
    if re.fullmatch(r"part-[0-9]{4}\.bin", value) is None:
        raise ValueError(f"Unsafe shard part name: {value}")
    return value


def validate_shard_manifest(manifest: dict[str, Any]) -> list[dict[str, Any]]:
    if manifest.get("format") != SHARD_FORMAT:
        raise ValueError(f"Shard format must be {SHARD_FORMAT}")
    if manifest.get("schema_version") != SHARD_SCHEMA_VERSION:
        raise ValueError(f"Shard schema_version must be {SHARD_SCHEMA_VERSION}")
    if manifest.get("compression") != "zlib":
        raise ValueError("Shard compression must be zlib")
    for field in ("pack_sha256", "compressed_sha256"):
        value = manifest.get(field)
        if not isinstance(value, str) or len(value) != 64:
            raise ValueError(f"Invalid shard manifest field: {field}")
    for field in ("pack_bytes", "compressed_bytes"):
        value = manifest.get(field)
        if not isinstance(value, int) or isinstance(value, bool) or value < 1:
            raise ValueError(f"Invalid shard manifest field: {field}")
    parts = manifest.get("parts")
    if not isinstance(parts, list) or not parts:
        raise ValueError("Shard manifest must contain parts")
    normalized: list[dict[str, Any]] = []
    seen: set[str] = set()
    for part in parts:
        if not isinstance(part, dict):
            raise ValueError("Every shard part must be an object")
        name = safe_part_name(part.get("name"))
        if name in seen:
            raise ValueError(f"Duplicate shard part: {name}")
        seen.add(name)
        size = part.get("bytes")
        digest = part.get("sha256")
        if not isinstance(size, int) or isinstance(size, bool) or size < 1:
            raise ValueError(f"Invalid byte count for shard part: {name}")
        if not isinstance(digest, str) or len(digest) != 64:
            raise ValueError(f"Invalid SHA-256 for shard part: {name}")
        normalized.append({"name": name, "bytes": size, "sha256": digest})
    return normalized


def validate_manifest_against_build(
    pack_path: Path,
    manifest: dict[str, Any],
) -> dict[str, Any]:
    expected = expected_pack_from_build_manifest(pack_path)
    if manifest.get("pack_sha256") != expected["pack_sha256"]:
        raise ValueError("Shard pack SHA-256 does not match BUILD-MANIFEST.json")
    return {
        "pack_sha256": expected["pack_sha256"],
        "pack_bytes": manifest.get("pack_bytes"),
    }


def verify_pack(pack_path: Path, expected: dict[str, Any] | None = None) -> dict[str, Any]:
    resolved = pack_path.expanduser().resolve()
    if not resolved.is_file():
        raise FileNotFoundError(f"Marketing Brain pack not found: {resolved}")
    requirements = expected or expected_pack_from_build_manifest(resolved)
    size = resolved.stat().st_size
    expected_size = requirements.get("pack_bytes")
    if expected_size is not None and size != expected_size:
        raise ValueError(f"Pack size mismatch: expected {expected_size}, got {size}")
    digest = sha256_path(resolved)
    if digest != requirements.get("pack_sha256"):
        raise ValueError("Pack SHA-256 mismatch")
    return {"path": str(resolved), "bytes": size, "sha256": digest}


def decompress_block(
    block: bytes,
    target: BinaryIO,
    state: DecompressionState,
    remaining: int,
) -> int:
    pending = block
    produced = 0
    while pending:
        output = state.decompressor.decompress(
            pending,
            max(1, remaining - produced + 1),
        )
        pending = state.decompressor.unconsumed_tail
        if len(output) > remaining - produced:
            raise ValueError("Materialized pack exceeds manifest pack_bytes")
        if output:
            target.write(output)
            state.pack_digest.update(output)
            produced += len(output)
        if state.decompressor.unused_data:
            raise ValueError("Compressed shard stream contains trailing data")
    return produced


def decompress_part(
    part_path: Path,
    target: BinaryIO,
    state: DecompressionState,
    prior_pack_bytes: int,
) -> tuple[int, int]:
    compressed_bytes = 0
    pack_bytes = 0
    with part_path.open("rb") as source:
        for block in iter(lambda: source.read(BUFFER_SIZE), b""):
            state.compressed_digest.update(block)
            compressed_bytes += len(block)
            remaining = state.maximum_pack_bytes - prior_pack_bytes - pack_bytes
            pack_bytes += decompress_block(
                block,
                target,
                state,
                remaining,
            )
    return compressed_bytes, pack_bytes


def verify_existing_pack(resolved: Path) -> dict[str, Any]:
    manifest_path = shard_manifest_path(resolved)
    if manifest_path.is_file():
        manifest = read_json(manifest_path)
        validate_shard_manifest(manifest)
        expected = validate_manifest_against_build(resolved, manifest)
    else:
        expected = expected_pack_from_build_manifest(resolved)
    return {**verify_pack(resolved, expected), "materialized": False}


def verified_part_path(root: Path, part: dict[str, Any]) -> Path:
    path = root / str(part["name"])
    if not path.is_file():
        raise FileNotFoundError(f"Missing shard part: {path}")
    if path.stat().st_size != part["bytes"]:
        raise ValueError(f"Shard size mismatch: {part['name']}")
    if sha256_path(path) != part["sha256"]:
        raise ValueError(f"Shard SHA-256 mismatch: {part['name']}")
    return path


def validate_stream(
    manifest: dict[str, Any],
    state: DecompressionState,
    compressed_bytes: int,
    pack_bytes: int,
) -> None:
    if not state.decompressor.eof:
        raise ValueError("Compressed shard stream ended before zlib EOF")
    if compressed_bytes != manifest["compressed_bytes"]:
        raise ValueError("Compressed shard byte count mismatch")
    if state.compressed_digest.hexdigest() != manifest["compressed_sha256"]:
        raise ValueError("Compressed shard SHA-256 mismatch")
    if pack_bytes != manifest["pack_bytes"]:
        raise ValueError("Materialized pack byte count mismatch")
    if state.pack_digest.hexdigest() != manifest["pack_sha256"]:
        raise ValueError("Materialized pack SHA-256 mismatch")
    if state.decompressor.unused_data:
        raise ValueError("Compressed shard stream contains trailing data")


def reconstruct_pack(
    resolved: Path,
    manifest: dict[str, Any],
    parts: list[dict[str, Any]],
) -> dict[str, Any]:
    root = shard_manifest_path(resolved).parent
    resolved.parent.mkdir(parents=True, exist_ok=True)
    temporary_handle = tempfile.NamedTemporaryFile(
        mode="wb",
        prefix=f".{resolved.name}.",
        suffix=".tmp",
        dir=resolved.parent,
        delete=False,
    )
    temporary = Path(temporary_handle.name)
    compressed_digest = hashlib.sha256()
    pack_digest = hashlib.sha256()
    compressed_bytes = 0
    pack_bytes = 0
    decompressor = zlib.decompressobj()
    state = DecompressionState(
        decompressor=decompressor,
        compressed_digest=compressed_digest,
        pack_digest=pack_digest,
        maximum_pack_bytes=int(manifest["pack_bytes"]),
    )
    try:
        with temporary_handle as target:
            for part in parts:
                part_path = verified_part_path(root, part)
                part_compressed, part_pack = decompress_part(
                    part_path,
                    target,
                    state,
                    pack_bytes,
                )
                compressed_bytes += part_compressed
                pack_bytes += part_pack
            tail = decompressor.flush()
            if tail:
                if len(tail) > int(manifest["pack_bytes"]) - pack_bytes:
                    raise ValueError("Materialized pack exceeds manifest pack_bytes")
                target.write(tail)
                pack_digest.update(tail)
                pack_bytes += len(tail)
            target.flush()
            os.fsync(target.fileno())
        validate_stream(manifest, state, compressed_bytes, pack_bytes)
        try:
            os.replace(temporary, resolved)
        except OSError:
            if not resolved.is_file():
                raise
            verify_pack(resolved, manifest)
    finally:
        temporary.unlink(missing_ok=True)
    return {
        "path": str(resolved),
        "bytes": pack_bytes,
        "sha256": pack_digest.hexdigest(),
        "materialized": True,
        "parts": len(parts),
    }


def materialize_pack(pack_path: Path = DEFAULT_PACK) -> dict[str, Any]:
    resolved = pack_path.expanduser().resolve()
    if resolved.is_file():
        return verify_existing_pack(resolved)
    manifest_path = shard_manifest_path(resolved)
    if not manifest_path.is_file():
        raise FileNotFoundError(
            f"Marketing Brain pack and shard manifest are missing: {resolved}"
        )
    manifest = read_json(manifest_path)
    parts = validate_shard_manifest(manifest)
    validate_manifest_against_build(resolved, manifest)
    return reconstruct_pack(resolved, manifest, parts)


def ensure_pack(pack_path: Path = DEFAULT_PACK) -> Path:
    resolved = pack_path.expanduser().resolve()
    result = materialize_pack(resolved)
    return Path(str(result["path"]))


def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Verify or materialize the complete Marketing Brain legacy pack.",
    )
    parser.add_argument("--pack", type=Path, default=DEFAULT_PACK)
    parser.add_argument("--verify-only", action="store_true")
    parser.add_argument("--json", action="store_true", dest="as_json")
    return parser.parse_args(argv)


def main(argv: Sequence[str] | None = None) -> int:
    arguments = parse_args(argv)
    try:
        result = (
            verify_pack(arguments.pack)
            if arguments.verify_only
            else materialize_pack(arguments.pack)
        )
    except (FileNotFoundError, OSError, ValueError, zlib.error) as error:
        print(f"materialize-legacy-pack: {error}")
        return 2
    if arguments.as_json:
        print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
    else:
        print(f"Marketing Brain corpus ready: {result['path']}")
        print(f"SHA-256: {result['sha256']}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
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: 471kUpdated Claude CodeCodexVerifiedInstall
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: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall