[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HHE6HAY58GZAFSB073YJ8":3,"skill-same:01M77HHE6HAY58GZAFSB073YJ8":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":43,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77HHE6HAY58GZAFSB073YJ8","greenhelix-agent-saas-factory",null,"The Agent SaaS Factory: Build, Deploy, and Monetize Software Products with Autonomous AI Agents. Complete guide to using AI agents to autonomously build, deploy, and monetize micro-SaaS products: GitHub for code, Stripe for billing, Postgres for data, and automated dispute arbitration. Includes detailed Python code examples with full API integration.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-saas-factory\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-saas-factory\nversion: \"1.3.1\"\ndescription: \"The Agent SaaS Factory: Build, Deploy, and Monetize Software Products with Autonomous AI Agents. Complete guide to using AI agents to autonomously build, deploy, and monetize micro-SaaS products: GitHub for code, Stripe for billing, Postgres for data, and automated dispute arbitration. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [saas, github, stripe, postgres, disputes, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - STRIPE_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# The Agent SaaS Factory: Build, Deploy, and Monetize Software Products with Autonomous AI Agents\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nWhen Stripe announced the Agentic Commerce Suite in March 2026 -- with Visa, OpenAI, and Samsung as launch partners -- they framed it as \"AI agents that can buy things.\" That is the merchant side of the equation. An agent browses a storefront, picks a product, and pays with a human's saved card. But what about the other side? What about an agent that builds the product, sets up the billing, deploys the database, handles the disputes, and operates the entire business -- end to end, without a human writing a single line of code or clicking a single button in a dashboard?\nThat is what this guide builds. A factory pattern where autonomous AI agents receive a product specification and produce a running, revenue-generating micro-SaaS: repository scaffolded on GitHub, schema designed and migrated in Postgres, billing configured in Stripe, dispute resolution automated, and the whole pipeline orchestrated by a single `AgentSaaSFactory` class. The BotStall marketplace demonstrated in late 2025 that agents could list and sell digital goods. We go further: agents that build, operate, and defend the entire software business.\nThe infrastructure is the GreenHelix A2A Commerce Gateway's pro-tier integration tools: 10 GitHub tools, 13 Stripe tools, 6 Postgres tools, and 5 Dispute tools -- 34 tools total, all accessible through a single HTTP endpoint at $0.005-$0.01 per call. This guide covers every one of them.\n\n## What You'll Learn\n- Chapter 1: Why Agents Should Build SaaS\n- Chapter 2: Setting Up the Agent's Development Environment\n- Chapter 3: The Data Layer: Agents Managing Postgres\n- Chapter 4: Monetization: Agents Running Stripe\n- Chapter 5: The Full Factory: Orchestrating the Pipeline\n- Chapter 6: Dispute Resolution and Customer Support Automation\n- Chapter 7: Security, Cost Governance, and Guardrails\n- Chapter 8: Production Recipes\n- Chapter 9: What's Next\n\n## Full Guide\n\n# The Agent SaaS Factory: Build, Deploy, and Monetize Software Products with Autonomous AI Agents\n\nWhen Stripe announced the Agentic Commerce Suite in March 2026 -- with Visa, OpenAI, and Samsung as launch partners -- they framed it as \"AI agents that can buy things.\" That is the merchant side of the equation. An agent browses a storefront, picks a product, and pays with a human's saved card. But what about the other side? What about an agent that builds the product, sets up the billing, deploys the database, handles the disputes, and operates the entire business -- end to end, without a human writing a single line of code or clicking a single button in a dashboard?\n\nThat is what this guide builds. A factory pattern where autonomous AI agents receive a product specification and produce a running, revenue-generating micro-SaaS: repository scaffolded on GitHub, schema designed and migrated in Postgres, billing configured in Stripe, dispute resolution automated, and the whole pipeline orchestrated by a single `AgentSaaSFactory` class. The BotStall marketplace demonstrated in late 2025 that agents could list and sell digital goods. We go further: agents that build, operate, and defend the entire software business.\n\nThe infrastructure is the GreenHelix A2A Commerce Gateway's pro-tier integration tools: 10 GitHub tools, 13 Stripe tools, 6 Postgres tools, and 5 Dispute tools -- 34 tools total, all accessible through a single HTTP endpoint at $0.005-$0.01 per call. This guide covers every one of them.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [Why Agents Should Build SaaS](#chapter-1-why-agents-should-build-saas)\n2. [Setting Up the Agent's Development Environment](#chapter-2-setting-up-the-agents-development-environment)\n3. [The Data Layer: Agents Managing Postgres](#chapter-3-the-data-layer-agents-managing-postgres)\n4. [Monetization: Agents Running Stripe](#chapter-4-monetization-agents-running-stripe)\n5. [The Full Factory: Orchestrating the Pipeline](#chapter-5-the-full-factory-orchestrating-the-pipeline)\n6. [Dispute Resolution and Customer Support Automation](#chapter-6-dispute-resolution-and-customer-support-automation)\n7. [Security, Cost Governance, and Guardrails](#chapter-7-security-cost-governance-and-guardrails)\n8. [Production Recipes](#chapter-8-production-recipes)\n9. [What's Next](#chapter-9-whats-next)\n\n---\n\n## Chapter 1: Why Agents Should Build SaaS\n\n### From Tools to Operators\n\nThe 2025 frame was \"agents as tools.\" Developer writes prompt, agent generates code, developer reviews and deploys. Faster pair programming. Useful. Not transformative.\n\nThe shift is \"agents as operators.\" The agent does not help you build a SaaS product -- it builds the SaaS product. Creates the repository. Designs the schema. Sets up Stripe pricing. Writes code, submits PRs, reviews diffs, merges. Monitors disputes and resolves them. The human's role shifts from implementer to investor: you provide the specification and the API credits. The agent does the rest.\n\nStripe's Agentic Commerce Suite already envisions agents that autonomously complete purchases and handle disputes. The missing piece is the supply side -- agents that build and operate the businesses those buyer agents purchase from.\n\n### The BotStall Precedent\n\nBotStall (late 2025) proved one half: agents listing and selling digital goods on a marketplace. But BotStall agents were vendors, not builders. A human created the product; the agent handled distribution. The Agent SaaS Factory closes the loop: the agent creates, operates, monetizes, and defends the entire business.\n\n### Architecture Overview\n\nThe factory runs on four services, all accessed through the GreenHelix A2A Commerce Gateway:\n\n```\n+------------------------------------------------------------+\n|                    AgentSaaSFactory                         |\n|                                                            |\n|  +------------------+  +------------------+                |\n|  | AgentDeveloper   |  | AgentDBA         |                |\n|  | 10 GitHub tools  |  | 6 Postgres tools |                |\n|  | $0.005\u002Fcall      |  | $0.01\u002Fcall       |                |\n|  +--------+---------+  +--------+---------+                |\n|           |                      |                         |\n|  +--------+---------+  +--------+---------+                |\n|  | AgentBilling     |  | AgentArbitrator  |                |\n|  | 13 Stripe tools  |  | 5 Dispute tools  |                |\n|  | $0.01\u002Fcall       |  | varies           |                |\n|  +--------+---------+  +--------+---------+                |\n|           |                      |                         |\n+-----------|----------------------|-------------------------+\n            |                      |\n   +--------v----------------------v---------+\n   |    GreenHelix A2A Commerce Gateway      |\n   |    Pro-tier: GitHub + Stripe + Postgres  |\n   |    + Disputes                            |\n   +------------------------------------------+\n```\n\n### Pro-Tier Cost Model\n\nEvery tool call has a fixed cost. There is no per-seat pricing, no monthly minimum, no overage surprise. You pay exactly for what the agent does.\n\n| Service | Tools | Cost per Call | Typical Calls per SaaS Build |\n|---------|-------|---------------|------------------------------|\n| GitHub | 10 | $0.005 | 40-60 |\n| Stripe | 13 | $0.01 | 15-25 |\n| Postgres | 6 | $0.01 | 20-40 |\n| Disputes | 5 | varies | 0-10 (reactive) |\n\nA complete micro-SaaS build costs $1.00-$1.50 in tool calls. Ongoing operation runs $0.10-$0.30\u002Fday. At $29\u002Fmonth from a single customer, the unit economics are immediately positive.\n\n---\n\n## Chapter 2: Setting Up the Agent's Development Environment\n\n### The AgentDeveloper Class\n\nThis class wraps all 10 GitHub tools into a development interface. The agent uses it to create repositories, scaffold projects, manage issues, submit pull requests, and perform code review.\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional, List\n\n\nclass AgentDeveloper:\n    \"\"\"GitHub development client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 10 GitHub integration tools into a development workflow\n    interface for autonomous repository management, code review, and\n    issue tracking.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Repository Management -----------------------------------------\n\n    def create_repo(\n        self,\n        name: str,\n        description: str,\n        private: bool = True,\n    ) -> dict:\n        \"\"\"Create a new GitHub repository.\"\"\"\n        return self._execute(\"create_repo\", {\n            \"name\": name,\n            \"description\": description,\n            \"private\": private,\n            \"auto_init\": True,\n        })\n\n    def get_repo(self, owner: str, repo: str) -> dict:\n        \"\"\"Get repository metadata.\"\"\"\n        return self._execute(\"get_repo\", {\n            \"owner\": owner,\n            \"repo\": repo,\n        })\n\n    # -- File Operations -----------------------------------------------\n\n    def get_file_contents(\n        self,\n        owner: str,\n        repo: str,\n        path: str,\n        ref: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Read a file from a repository.\"\"\"\n        payload = {\"owner\": owner, \"repo\": repo, \"path\": path}\n        if ref:\n            payload[\"ref\"] = ref\n        return self._execute(\"get_file_contents\", payload)\n\n    def create_or_update_file(\n        self,\n        owner: str,\n        repo: str,\n        path: str,\n        content: str,\n        message: str,\n        branch: Optional[str] = None,\n        sha: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Write or update a file in a repository.\"\"\"\n        payload = {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"path\": path,\n            \"content\": content,\n            \"message\": message,\n        }\n        if branch:\n            payload[\"branch\"] = branch\n        if sha:\n            payload[\"sha\"] = sha\n        return self._execute(\"create_or_update_file\", payload)\n\n    # -- Issue Tracking ------------------------------------------------\n\n    def create_issue(\n        self,\n        owner: str,\n        repo: str,\n        title: str,\n        body: str,\n        labels: Optional[List[str]] = None,\n    ) -> dict:\n        \"\"\"File a bug report or feature request.\"\"\"\n        payload = {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"title\": title,\n            \"body\": body,\n        }\n        if labels:\n            payload[\"labels\"] = labels\n        return self._execute(\"create_issue\", payload)\n\n    def get_issue(\n        self,\n        owner: str,\n        repo: str,\n        issue_number: int,\n    ) -> dict:\n        \"\"\"Retrieve issue details.\"\"\"\n        return self._execute(\"get_issue\", {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"issue_number\": issue_number,\n        })\n\n    # -- Code Review ---------------------------------------------------\n\n    def create_pull_request(\n        self,\n        owner: str,\n        repo: str,\n        title: str,\n        body: str,\n        head: str,\n        base: str = \"main\",\n    ) -> dict:\n        \"\"\"Submit code changes for review.\"\"\"\n        return self._execute(\"create_pull_request\", {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"title\": title,\n            \"body\": body,\n            \"head\": head,\n            \"base\": base,\n        })\n\n    def merge_pull_request(\n        self,\n        owner: str,\n        repo: str,\n        pull_number: int,\n        merge_method: str = \"squash\",\n    ) -> dict:\n        \"\"\"Merge an approved pull request.\"\"\"\n        return self._execute(\"merge_pull_request\", {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"pull_number\": pull_number,\n            \"merge_method\": merge_method,\n        })\n\n    # -- Code Intelligence ---------------------------------------------\n\n    def search_code(\n        self,\n        query: str,\n        owner: Optional[str] = None,\n        repo: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Search across codebases.\"\"\"\n        payload = {\"query\": query}\n        if owner and repo:\n            payload[\"query\"] = f\"{query} repo:{owner}\u002F{repo}\"\n        return self._execute(\"search_code\", payload)\n\n    def list_commits(\n        self,\n        owner: str,\n        repo: str,\n        sha: Optional[str] = None,\n        per_page: int = 30,\n    ) -> dict:\n        \"\"\"View commit history.\"\"\"\n        payload = {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"per_page\": per_page,\n        }\n        if sha:\n            payload[\"sha\"] = sha\n        return self._execute(\"list_commits\", payload)\n\n    # -- High-Level Workflows ------------------------------------------\n\n    def scaffold_project(\n        self,\n        owner: str,\n        repo: str,\n        files: dict,\n        branch: str = \"main\",\n    ) -> List[dict]:\n        \"\"\"Write multiple files to scaffold a project.\n\n        Args:\n            files: dict mapping file paths to content strings.\n                   Example: {\"src\u002Fapp.py\": \"...\", \"requirements.txt\": \"...\"}\n        \"\"\"\n        results = []\n        for path, content in files.items():\n            result = self.create_or_update_file(\n                owner=owner,\n                repo=repo,\n                path=path,\n                content=content,\n                message=f\"scaffold: add {path}\",\n                branch=branch,\n            )\n            results.append(result)\n        return results\n\n    def review_and_merge(\n        self,\n        owner: str,\n        repo: str,\n        head_branch: str,\n        title: str,\n        description: str,\n    ) -> dict:\n        \"\"\"Create a PR, perform automated review, and merge.\n\n        The agent creates the PR, searches the diff for known\n        anti-patterns, then merges if clean.\n        \"\"\"\n        pr = self.create_pull_request(\n            owner=owner,\n            repo=repo,\n            title=title,\n            body=description,\n            head=head_branch,\n            base=\"main\",\n        )\n        pull_number = pr[\"number\"]\n\n        # Agent-driven code review: search for common issues\n        issues_found = []\n        for pattern in [\"eval(\", \"exec(\", \"password =\", \"secret =\"]:\n            hits = self.search_code(\n                query=pattern,\n                owner=owner,\n                repo=repo,\n            )\n            if hits.get(\"total_count\", 0) > 0:\n                issues_found.append(pattern)\n\n        if issues_found:\n            self.create_issue(\n                owner=owner,\n                repo=repo,\n                title=f\"Security review: patterns found in PR #{pull_number}\",\n                body=f\"Found: {', '.join(issues_found)}. Review before merge.\",\n                labels=[\"security\", \"automated-review\"],\n            )\n            return {\"status\": \"blocked\", \"pr\": pr, \"issues\": issues_found}\n\n        merged = self.merge_pull_request(\n            owner=owner,\n            repo=repo,\n            pull_number=pull_number,\n        )\n        return {\"status\": \"merged\", \"pr\": pr, \"merge\": merged}\n```\n\n### Pattern: Agent-Driven Code Review\n\nThe agent reads the diff, searches the codebase for related code, and judges whether the change is safe -- beyond what linters and CI catch.\n\n```python\nimport os\n\ndev = AgentDeveloper(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"dev-agent-01\",\n)\n\n# Agent reviews its own work before merging\nowner, repo = \"myorg\", \"newsletter-saas\"\n\n# 1. Check recent commits on the feature branch\ncommits = dev.list_commits(owner, repo, sha=\"feature\u002Fadd-billing\")\nprint(f\"Feature branch has {len(commits)} commits\")\n\n# 2. Search for any hardcoded secrets that slipped in\nsecrets_check = dev.search_code(\n    query=\"STRIPE_SECRET password API_KEY\",\n    owner=owner,\n    repo=repo,\n)\nif secrets_check.get(\"total_count\", 0) > 0:\n    dev.create_issue(\n        owner=owner,\n        repo=repo,\n        title=\"CRITICAL: Hardcoded secrets detected\",\n        body=\"Automated scan found potential secrets in codebase.\",\n        labels=[\"security\", \"P0\"],\n    )\n    raise RuntimeError(\"Secrets detected -- aborting merge\")\n\n# 3. If clean, create PR and merge\nresult = dev.review_and_merge(\n    owner=owner,\n    repo=repo,\n    head_branch=\"feature\u002Fadd-billing\",\n    title=\"Add Stripe billing integration\",\n    description=\"Adds subscription management with usage-based pricing.\",\n)\nprint(f\"PR status: {result['status']}\")\n```\n\n### Pattern: Automated Issue Tracking\n\nThe agent tracks its own work with issues, creating a paper trail for every feature and bug fix.\n\n```python\n# Agent creates a tracking issue before starting work\nissue = dev.create_issue(\n    owner=\"myorg\",\n    repo=\"newsletter-saas\",\n    title=\"Implement subscriber management API\",\n    body=(\n        \"## Requirements\\n\"\n        \"- POST \u002Fapi\u002Fsubscribers to add new subscriber\\n\"\n        \"- GET \u002Fapi\u002Fsubscribers to list all subscribers\\n\"\n        \"- DELETE \u002Fapi\u002Fsubscribers\u002F:id to unsubscribe\\n\"\n        \"- Store in Postgres with email uniqueness constraint\\n\\n\"\n        \"## Acceptance Criteria\\n\"\n        \"- All endpoints return JSON\\n\"\n        \"- Email validation on POST\\n\"\n        \"- Idempotent DELETE\\n\"\n    ),\n    labels=[\"feature\", \"api\", \"agent-created\"],\n)\nissue_number = issue[\"number\"]\n\n# Agent reads the issue back to confirm requirements\ndetails = dev.get_issue(\"myorg\", \"newsletter-saas\", issue_number)\nprint(f\"Working on: {details['title']}\")\n\n# ... agent implements the feature ...\n\n# Agent closes the issue by referencing it in the PR body\ndev.create_pull_request(\n    owner=\"myorg\",\n    repo=\"newsletter-saas\",\n    title=\"Implement subscriber management API\",\n    body=f\"Closes #{issue_number}\\n\\nAdds CRUD endpoints for subscribers.\",\n    head=\"feature\u002Fsubscriber-api\",\n)\n```\n\n**Cost for a typical development session:** 40-60 GitHub tool calls at $0.005 each = $0.20-$0.30. That covers repo creation, 10-15 file writes, 3-5 PR cycles, issue tracking, and code search.\n\n---\n\n## Chapter 3: The Data Layer: Agents Managing Postgres\n\n### The AgentDBA Class\n\nThis class wraps all 6 Postgres tools. The agent uses it to design schemas, run migrations, seed data, and validate data integrity.\n\n```python\nimport requests\nimport json\nfrom typing import Optional, List\n\n\nclass AgentDBA:\n    \"\"\"Postgres database administration client for the GreenHelix\n    A2A Commerce Gateway.\n\n    Wraps the 6 Postgres integration tools into a database management\n    interface for schema design, migrations, queries, and data validation.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Schema Inspection ---------------------------------------------\n\n    def get_schema(self) -> dict:\n        \"\"\"Inspect the full database schema.\"\"\"\n        return self._execute(\"get_schema\", {})\n\n    def list_tables(self) -> dict:\n        \"\"\"List all tables in the database.\"\"\"\n        return self._execute(\"list_tables\", {})\n\n    def describe_table(self, table_name: str) -> dict:\n        \"\"\"Get the structure of a specific table.\"\"\"\n        return self._execute(\"describe_table\", {\n            \"table_name\": table_name,\n        })\n\n    # -- Query Execution -----------------------------------------------\n\n    def query(self, sql: str, params: Optional[List] = None) -> dict:\n        \"\"\"Run a SELECT query. Read-only.\"\"\"\n        payload = {\"sql\": sql}\n        if params:\n            payload[\"params\"] = params\n        return self._execute(\"query\", payload)\n\n    def execute_query(\n        self,\n        sql: str,\n        params: Optional[List] = None,\n    ) -> dict:\n        \"\"\"Run any SQL statement (INSERT, UPDATE, DELETE, DDL).\"\"\"\n        payload = {\"sql\": sql}\n        if params:\n            payload[\"params\"] = params\n        return self._execute(\"execute_query\", payload)\n\n    # -- Migrations ----------------------------------------------------\n\n    def execute_migration(\n        self,\n        migration_sql: str,\n        version: str,\n        description: str,\n    ) -> dict:\n        \"\"\"Run a schema migration with version tracking.\"\"\"\n        return self._execute(\"execute_migration\", {\n            \"migration_sql\": migration_sql,\n            \"version\": version,\n            \"description\": description,\n        })\n\n    # -- High-Level Workflows ------------------------------------------\n\n    def schema_first_design(\n        self,\n        tables: dict,\n    ) -> List[dict]:\n        \"\"\"Design and create a full schema from a table specification.\n\n        Args:\n            tables: dict mapping table names to column definitions.\n                Example:\n                {\n                    \"subscribers\": [\n                        \"id SERIAL PRIMARY KEY\",\n                        \"email VARCHAR(255) UNIQUE NOT NULL\",\n                        \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n                    ]\n                }\n        \"\"\"\n        results = []\n        for table_name, columns in tables.items():\n            col_defs = \", \".join(columns)\n            sql = f\"CREATE TABLE IF NOT EXISTS {table_name} ({col_defs})\"\n            result = self.execute_query(sql)\n            results.append({\"table\": table_name, \"result\": result})\n        return results\n\n    def safe_migration_chain(\n        self,\n        migrations: List[dict],\n    ) -> List[dict]:\n        \"\"\"Execute a chain of migrations in order, stopping on failure.\n\n        Args:\n            migrations: list of dicts with keys:\n                - version: str (e.g., \"001\")\n                - description: str\n                - up: str (SQL to apply)\n        \"\"\"\n        results = []\n        for m in migrations:\n            try:\n                result = self.execute_migration(\n                    migration_sql=m[\"up\"],\n                    version=m[\"version\"],\n                    description=m[\"description\"],\n                )\n                results.append({\n                    \"version\": m[\"version\"],\n                    \"status\": \"applied\",\n                    \"result\": result,\n                })\n            except Exception as e:\n                results.append({\n                    \"version\": m[\"version\"],\n                    \"status\": \"failed\",\n                    \"error\": str(e),\n                })\n                break  # Stop chain on failure\n        return results\n\n    def validate_data(\n        self,\n        table: str,\n        checks: List[dict],\n    ) -> List[dict]:\n        \"\"\"Run validation checks against a table.\n\n        Args:\n            checks: list of dicts with keys:\n                - name: str (human-readable check name)\n                - sql: str (query that should return 0 rows if valid)\n        \"\"\"\n        results = []\n        for check in checks:\n            result = self.query(check[\"sql\"])\n            row_count = len(result.get(\"rows\", []))\n            results.append({\n                \"check\": check[\"name\"],\n                \"passed\": row_count == 0,\n                \"violations\": row_count,\n            })\n        return results\n```\n\n### Pattern: Schema-First Development\n\nThe agent designs the schema before writing application code, ensuring the data layer is correct before business logic is built on top.\n\n```python\nimport os\n\ndba = AgentDBA(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"dba-agent-01\",\n)\n\n# Agent designs the schema for a newsletter SaaS\nschema = dba.schema_first_design({\n    \"subscribers\": [\n        \"id SERIAL PRIMARY KEY\",\n        \"email VARCHAR(255) UNIQUE NOT NULL\",\n        \"name VARCHAR(255)\",\n        \"status VARCHAR(20) DEFAULT 'active' CHECK (status IN ('active', 'unsubscribed', 'bounced'))\",\n        \"stripe_customer_id VARCHAR(255)\",\n        \"subscribed_at TIMESTAMPTZ DEFAULT NOW()\",\n        \"unsubscribed_at TIMESTAMPTZ\",\n    ],\n    \"newsletters\": [\n        \"id SERIAL PRIMARY KEY\",\n        \"subject VARCHAR(500) NOT NULL\",\n        \"body TEXT NOT NULL\",\n        \"status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'scheduled', 'sent'))\",\n        \"scheduled_for TIMESTAMPTZ\",\n        \"sent_at TIMESTAMPTZ\",\n        \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n    ],\n    \"send_log\": [\n        \"id SERIAL PRIMARY KEY\",\n        \"newsletter_id INTEGER REFERENCES newsletters(id)\",\n        \"subscriber_id INTEGER REFERENCES subscribers(id)\",\n        \"status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed', 'bounced'))\",\n        \"sent_at TIMESTAMPTZ\",\n        \"error_message TEXT\",\n        \"UNIQUE(newsletter_id, subscriber_id)\",\n    ],\n})\n\n# Verify the schema was created correctly\ntables = dba.list_tables()\nprint(f\"Tables created: {[t['table_name'] for t in tables['rows']]}\")\n\nfor table in [\"subscribers\", \"newsletters\", \"send_log\"]:\n    desc = dba.describe_table(table)\n    print(f\"\\n{table}:\")\n    for col in desc[\"columns\"]:\n        print(f\"  {col['column_name']} {col['data_type']} {col.get('constraints', '')}\")\n```\n\n### Pattern: Safe Migration Chains\n\nVersioned migrations tracked in order. The chain stops on the first failure to prevent partial schema states.\n\n```python\n# Agent evolves the schema over time\nmigrations = dba.safe_migration_chain([\n    {\n        \"version\": \"002\",\n        \"description\": \"Add subscriber tags for segmentation\",\n        \"up\": \"\"\"\n            CREATE TABLE IF NOT EXISTS subscriber_tags (\n                id SERIAL PRIMARY KEY,\n                subscriber_id INTEGER REFERENCES subscribers(id) ON DELETE CASCADE,\n                tag VARCHAR(100) NOT NULL,\n                created_at TIMESTAMPTZ DEFAULT NOW(),\n                UNIQUE(subscriber_id, tag)\n            );\n            CREATE INDEX idx_subscriber_tags_tag ON subscriber_tags(tag);\n        \"\"\",\n    },\n    {\n        \"version\": \"003\",\n        \"description\": \"Add open tracking to send_log\",\n        \"up\": \"\"\"\n            ALTER TABLE send_log ADD COLUMN IF NOT EXISTS opened_at TIMESTAMPTZ;\n            ALTER TABLE send_log ADD COLUMN IF NOT EXISTS open_count INTEGER DEFAULT 0;\n            CREATE INDEX idx_send_log_opened ON send_log(opened_at)\n                WHERE opened_at IS NOT NULL;\n        \"\"\",\n    },\n    {\n        \"version\": \"004\",\n        \"description\": \"Add revenue tracking table\",\n        \"up\": \"\"\"\n            CREATE TABLE IF NOT EXISTS revenue_events (\n                id SERIAL PRIMARY KEY,\n                subscriber_id INTEGER REFERENCES subscribers(id),\n                stripe_payment_intent_id VARCHAR(255) UNIQUE,\n                amount_cents INTEGER NOT NULL,\n                currency VARCHAR(3) DEFAULT 'usd',\n                event_type VARCHAR(50) NOT NULL,\n                created_at TIMESTAMPTZ DEFAULT NOW()\n            );\n            CREATE INDEX idx_revenue_subscriber ON revenue_events(subscriber_id);\n            CREATE INDEX idx_revenue_created ON revenue_events(created_at);\n        \"\"\",\n    },\n])\n\nfor m in migrations:\n    status_marker = \"OK\" if m[\"status\"] == \"applied\" else \"FAIL\"\n    print(f\"  [{status_marker}] v{m['version']}: {m.get('error', 'applied')}\")\n```\n\n### Pattern: Data Validation Pipeline\n\nAfter seeding data or processing a batch, the agent runs validation checks to catch integrity issues early.\n\n```python\n# After importing subscriber data, validate\nvalidations = dba.validate_data(\n    table=\"subscribers\",\n    checks=[\n        {\n            \"name\": \"No duplicate emails\",\n            \"sql\": \"\"\"\n                SELECT email, COUNT(*) as cnt FROM subscribers\n                GROUP BY email HAVING COUNT(*) > 1\n            \"\"\",\n        },\n        {\n            \"name\": \"All active subscribers have email\",\n            \"sql\": \"\"\"\n                SELECT id FROM subscribers\n                WHERE status = 'active' AND (email IS NULL OR email = '')\n            \"\"\",\n        },\n        {\n            \"name\": \"No future subscription dates\",\n            \"sql\": \"\"\"\n                SELECT id FROM subscribers\n                WHERE subscribed_at > NOW() + INTERVAL '1 minute'\n            \"\"\",\n        },\n        {\n            \"name\": \"Unsubscribed have unsubscribed_at set\",\n            \"sql\": \"\"\"\n                SELECT id FROM subscribers\n                WHERE status = 'unsubscribed' AND unsubscribed_at IS NULL\n            \"\"\",\n        },\n    ],\n)\n\nall_passed = all(v[\"passed\"] for v in validations)\nfor v in validations:\n    marker = \"PASS\" if v[\"passed\"] else f\"FAIL ({v['violations']} violations)\"\n    print(f\"  [{marker}] {v['check']}\")\n\nif not all_passed:\n    raise DataValidationError(\"Validation failed -- see results above\")\n```\n\n**Cost for a typical database session:** 20-40 Postgres tool calls at $0.01 each = $0.20-$0.40. That covers schema creation, 3-5 migrations, data seeding, and validation.\n\n---\n\n## Chapter 4: Monetization: Agents Running Stripe\n\n### The AgentBilling Class\n\nThis class wraps all 13 Stripe tools. The agent uses it to create products, set pricing, generate checkout sessions, manage invoices, and track revenue.\n\n```python\nimport requests\nimport json\nfrom typing import Optional, List, Literal\n\n\nclass AgentBilling:\n    \"\"\"Stripe billing client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 13 Stripe integration tools into a monetization interface\n    for product creation, pricing, checkout, invoicing, and revenue tracking.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Customer Management -------------------------------------------\n\n    def create_customer(\n        self,\n        email: str,\n        name: Optional[str] = None,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Register a new Stripe customer.\"\"\"\n        payload = {\"email\": email}\n        if name:\n            payload[\"name\"] = name\n        if metadata:\n            payload[\"metadata\"] = metadata\n        return self._execute(\"create_customer\", payload)\n\n    def get_customer(self, customer_id: str) -> dict:\n        \"\"\"Retrieve customer details.\"\"\"\n        return self._execute(\"get_customer\", {\n            \"customer_id\": customer_id,\n        })\n\n    # -- Product & Pricing ---------------------------------------------\n\n    def create_product(\n        self,\n        name: str,\n        description: str,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Define a new product or service.\"\"\"\n        payload = {\"name\": name, \"description\": description}\n        if metadata:\n            payload[\"metadata\"] = metadata\n        return self._execute(\"create_product\", payload)\n\n    def get_product(self, product_id: str) -> dict:\n        \"\"\"Retrieve product details.\"\"\"\n        return self._execute(\"get_product\", {\n            \"product_id\": product_id,\n        })\n\n    def create_price(\n        self,\n        product_id: str,\n        unit_amount: int,\n        currency: str = \"usd\",\n        recurring: Optional[dict] = None,\n        usage_type: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Set pricing for a product.\n\n        Args:\n            unit_amount: Price in cents (e.g., 2900 = $29.00)\n            recurring: dict with \"interval\" key (\"month\", \"year\")\n            usage_type: \"metered\" for usage-based billing\n        \"\"\"\n        payload = {\n            \"product_id\": product_id,\n            \"unit_amount\": unit_amount,\n            \"currency\": currency,\n        }\n        if recurring:\n            payload[\"recurring\"] = recurring\n        if usage_type:\n            payload[\"usage_type\"] = usage_type\n        return self._execute(\"create_price\", payload)\n\n    # -- Checkout & Payments -------------------------------------------\n\n    def create_checkout_session(\n        self,\n        price_id: str,\n        success_url: str,\n        cancel_url: str,\n        mode: Literal[\"payment\", \"subscription\"] = \"subscription\",\n        customer_id: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Generate a Stripe checkout page.\"\"\"\n        payload = {\n            \"price_id\": price_id,\n            \"success_url\": success_url,\n            \"cancel_url\": cancel_url,\n            \"mode\": mode,\n        }\n        if customer_id:\n            payload[\"customer_id\"] = customer_id\n        return self._execute(\"create_checkout_session\", payload)\n\n    def get_checkout_session(self, session_id: str) -> dict:\n        \"\"\"Check the status of a checkout session.\"\"\"\n        return self._execute(\"get_checkout_session\", {\n            \"session_id\": session_id,\n        })\n\n    # -- Invoicing -----------------------------------------------------\n\n    def create_invoice(\n        self,\n        customer_id: str,\n        auto_advance: bool = True,\n        collection_method: str = \"charge_automatically\",\n    ) -> dict:\n        \"\"\"Generate an invoice for a customer.\"\"\"\n        return self._execute(\"create_invoice\", {\n            \"customer_id\": customer_id,\n            \"auto_advance\": auto_advance,\n            \"collection_method\": collection_method,\n        })\n\n    def get_invoice(self, invoice_id: str) -> dict:\n        \"\"\"Retrieve invoice details.\"\"\"\n        return self._execute(\"get_invoice\", {\n            \"invoice_id\": invoice_id,\n        })\n\n    def list_invoices(\n        self,\n        customer_id: Optional[str] = None,\n        status: Optional[str] = None,\n        limit: int = 10,\n    ) -> dict:\n        \"\"\"List invoices with optional filtering.\"\"\"\n        payload = {\"limit\": limit}\n        if customer_id:\n            payload[\"customer_id\"] = customer_id\n        if status:\n            payload[\"status\"] = status\n        return self._execute(\"list_invoices\", payload)\n\n    # -- Payment Intents -----------------------------------------------\n\n    def create_payment_intent(\n        self,\n        amount: int,\n        currency: str = \"usd\",\n        customer_id: Optional[str] = None,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Initiate a payment.\"\"\"\n        payload = {\"amount\": amount, \"currency\": currency}\n        if customer_id:\n            payload[\"customer_id\"] = customer_id\n        if metadata:\n            payload[\"metadata\"] = metadata\n        return self._execute(\"create_payment_intent\", payload)\n\n    def get_payment_intent(self, payment_intent_id: str) -> dict:\n        \"\"\"Check the status of a payment.\"\"\"\n        return self._execute(\"get_payment_intent\", {\n            \"payment_intent_id\": payment_intent_id,\n        })\n\n    # -- Revenue Tracking ----------------------------------------------\n\n    def get_balance(self) -> dict:\n        \"\"\"Check the Stripe account balance.\"\"\"\n        return self._execute(\"get_balance\", {})\n\n    # -- High-Level Workflows ------------------------------------------\n\n    def setup_subscription_product(\n        self,\n        name: str,\n        description: str,\n        monthly_price_cents: int,\n        yearly_price_cents: Optional[int] = None,\n    ) -> dict:\n        \"\"\"Create a product with monthly (and optional yearly) pricing.\n\n        Returns dict with product_id, monthly_price_id, yearly_price_id.\n        \"\"\"\n        product = self.create_product(name=name, description=description)\n        product_id = product[\"id\"]\n\n        monthly = self.create_price(\n            product_id=product_id,\n            unit_amount=monthly_price_cents,\n            recurring={\"interval\": \"month\"},\n        )\n\n        result = {\n            \"product_id\": product_id,\n            \"monthly_price_id\": monthly[\"id\"],\n        }\n\n        if yearly_price_cents:\n            yearly = self.create_price(\n                product_id=product_id,\n                unit_amount=yearly_price_cents,\n                recurring={\"interval\": \"year\"},\n            )\n            result[\"yearly_price_id\"] = yearly[\"id\"]\n\n        return result\n\n    def setup_usage_based_product(\n        self,\n        name: str,\n        description: str,\n        per_unit_cents: int,\n    ) -> dict:\n        \"\"\"Create a metered billing product.\n\n        Returns dict with product_id and price_id for usage reporting.\n        \"\"\"\n        product = self.create_product(name=name, description=description)\n        price = self.create_price(\n            product_id=product[\"id\"],\n            unit_amount=per_unit_cents,\n            usage_type=\"metered\",\n            recurring={\"interval\": \"month\"},\n        )\n        return {\n            \"product_id\": product[\"id\"],\n            \"price_id\": price[\"id\"],\n        }\n```\n\n### Pattern: Subscription Lifecycle\n\nComplete subscription setup with monthly\u002Fannual pricing and customer onboarding through checkout.\n\n```python\nimport os\n\nbilling = AgentBilling(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"billing-agent-01\",\n)\n\n# 1. Create the subscription product\nproduct = billing.setup_subscription_product(\n    name=\"NewsletterPro\",\n    description=\"Automated newsletter platform with analytics\",\n    monthly_price_cents=2900,       # $29\u002Fmonth\n    yearly_price_cents=29000,       # $290\u002Fyear (2 months free)\n)\nprint(f\"Product: {product['product_id']}\")\nprint(f\"Monthly: {product['monthly_price_id']}\")\nprint(f\"Yearly:  {product['yearly_price_id']}\")\n\n# 2. Onboard a customer\ncustomer = billing.create_customer(\n    email=\"alice@example.com\",\n    name=\"Alice Chen\",\n    metadata={\"source\": \"organic\", \"plan\": \"monthly\"},\n)\n\n# 3. Generate checkout session\nsession = billing.create_checkout_session(\n    price_id=product[\"monthly_price_id\"],\n    success_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fwelcome\",\n    cancel_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fpricing\",\n    mode=\"subscription\",\n    customer_id=customer[\"id\"],\n)\nprint(f\"Checkout URL: {session['url']}\")\n\n# 4. Agent polls for completion (in production, use webhooks)\nimport time\nfor _ in range(30):\n    status = billing.get_checkout_session(session[\"id\"])\n    if status[\"payment_status\"] == \"paid\":\n        print(\"Payment confirmed -- activating subscription\")\n        break\n    time.sleep(10)\n```\n\n### Pattern: Usage-Based Billing\n\nFor API-as-a-Service products, the agent sets up metered billing where customers pay per API call.\n\n```python\n# Create a metered product\napi_product = billing.setup_usage_based_product(\n    name=\"TranslationAPI\",\n    description=\"Neural machine translation API\",\n    per_unit_cents=1,  # $0.01 per translation\n)\n\n# Generate an invoice at month end\ninvoices = billing.list_invoices(\n    customer_id=\"cus_abc123\",\n    status=\"draft\",\n)\nif invoices.get(\"data\"):\n    invoice = billing.get_invoice(invoices[\"data\"][0][\"id\"])\n    print(f\"Draft invoice: ${invoice['amount_due'] \u002F 100:.2f}\")\n```\n\n### Pattern: Revenue Reconciliation\n\nPeriodic balance check against internal records.\n\n```python\n# Daily revenue check\nbalance = billing.get_balance()\navailable = sum(b[\"amount\"] for b in balance.get(\"available\", []))\npending = sum(b[\"amount\"] for b in balance.get(\"pending\", []))\n\nprint(f\"Available: ${available \u002F 100:.2f}\")\nprint(f\"Pending:   ${pending \u002F 100:.2f}\")\n\n# Cross-reference with recent invoices\nrecent = billing.list_invoices(status=\"paid\", limit=50)\ninvoice_total = sum(inv[\"amount_paid\"] for inv in recent.get(\"data\", []))\nprint(f\"Invoiced (last 50): ${invoice_total \u002F 100:.2f}\")\n```\n\n**Cost for a typical billing setup:** 15-25 Stripe tool calls at $0.01 each = $0.15-$0.25. That covers product creation, pricing, customer onboarding, checkout sessions, and balance checks.\n\n---\n\n## Chapter 5: The Full Factory: Orchestrating the Pipeline\n\n### The AgentSaaSFactory Class\n\nThis is the orchestrator. It combines `AgentDeveloper`, `AgentDBA`, and `AgentBilling` into a single pipeline that takes a product specification and produces a running micro-SaaS.\n\n```python\nimport os\nimport json\nimport time\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass SaaSSpec:\n    \"\"\"Specification for a micro-SaaS product.\"\"\"\n    name: str\n    description: str\n    repo_name: str\n    owner: str\n    monthly_price_cents: int\n    yearly_price_cents: Optional[int] = None\n    tables: dict = field(default_factory=dict)\n    migrations: list = field(default_factory=list)\n    app_files: dict = field(default_factory=dict)\n    success_url: str = \"\"\n    cancel_url: str = \"\"\n\n\nclass AgentSaaSFactory:\n    \"\"\"End-to-end SaaS factory combining GitHub, Postgres, and Stripe.\n\n    Takes a SaaSSpec and produces a running, revenue-generating\n    micro-SaaS with repository, database, and billing.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.developer = AgentDeveloper(\n            api_key=api_key,\n            agent_id=f\"{agent_id}-dev\",\n            base_url=base_url,\n        )\n        self.dba = AgentDBA(\n            api_key=api_key,\n            agent_id=f\"{agent_id}-dba\",\n            base_url=base_url,\n        )\n        self.billing = AgentBilling(\n            api_key=api_key,\n            agent_id=f\"{agent_id}-billing\",\n            base_url=base_url,\n        )\n        self.agent_id = agent_id\n        self.build_log = []\n\n    def _log(self, phase: str, message: str, data: Optional[dict] = None):\n        entry = {\n            \"timestamp\": time.time(),\n            \"phase\": phase,\n            \"message\": message,\n            \"data\": data,\n        }\n        self.build_log.append(entry)\n        print(f\"[{phase}] {message}\")\n\n    def build(self, spec: SaaSSpec) -> dict:\n        \"\"\"Execute the full SaaS build pipeline.\n\n        Phase 1: Create repository and scaffold code\n        Phase 2: Design schema and run migrations\n        Phase 3: Set up Stripe products and pricing\n        Phase 4: Deploy and verify\n\n        Returns a manifest with all created resource IDs.\n        \"\"\"\n        manifest = {\"spec\": spec.name, \"resources\": {}}\n\n        # Phase 1: Repository\n        self._log(\"repo\", f\"Creating repository {spec.repo_name}\")\n        repo = self.developer.create_repo(\n            name=spec.repo_name,\n            description=spec.description,\n        )\n        manifest[\"resources\"][\"repo\"] = repo\n        self._log(\"repo\", f\"Repository created: {repo.get('html_url')}\")\n\n        # Scaffold application files\n        if spec.app_files:\n            self._log(\"repo\", f\"Scaffolding {len(spec.app_files)} files\")\n            self.developer.scaffold_project(\n                owner=spec.owner,\n                repo=spec.repo_name,\n                files=spec.app_files,\n            )\n\n        # Phase 2: Database\n        if spec.tables:\n            self._log(\"db\", f\"Creating {len(spec.tables)} tables\")\n            schema_result = self.dba.schema_first_design(spec.tables)\n            manifest[\"resources\"][\"tables\"] = schema_result\n\n        if spec.migrations:\n            self._log(\"db\", f\"Running {len(spec.migrations)} migrations\")\n            migration_result = self.dba.safe_migration_chain(spec.migrations)\n            manifest[\"resources\"][\"migrations\"] = migration_result\n\n            # Verify schema integrity\n            tables = self.dba.list_tables()\n            self._log(\n                \"db\",\n                f\"Schema verified: {len(tables.get('rows', []))} tables\",\n            )\n\n        # Phase 3: Billing\n        self._log(\"billing\", \"Setting up Stripe product and pricing\")\n        product = self.billing.setup_subscription_product(\n            name=spec.name,\n            description=spec.description,\n            monthly_price_cents=spec.monthly_price_cents,\n            yearly_price_cents=spec.yearly_price_cents,\n        )\n        manifest[\"resources\"][\"stripe\"] = product\n\n        # Store billing config in the repo\n        billing_config = json.dumps(product, indent=2)\n        self.developer.create_or_update_file(\n            owner=spec.owner,\n            repo=spec.repo_name,\n            path=\"config\u002Fbilling.json\",\n            content=billing_config,\n            message=\"Add Stripe billing configuration\",\n        )\n        self._log(\"billing\", f\"Product created: {product['product_id']}\")\n\n        # Phase 4: Verification\n        self._log(\"verify\", \"Running post-build checks\")\n\n        # Verify repo exists and has correct files\n        repo_check = self.developer.get_repo(spec.owner, spec.repo_name)\n        assert repo_check.get(\"name\") == spec.repo_name\n\n        # Verify product exists in Stripe\n        product_check = self.billing.get_product(product[\"product_id\"])\n        assert product_check.get(\"active\") is True\n\n        # Verify all tables exist\n        if spec.tables:\n            for table_name in spec.tables:\n                desc = self.dba.describe_table(table_name)\n                assert len(desc.get(\"columns\", [])) > 0\n\n        self._log(\"verify\", \"All post-build checks passed\")\n\n        # Create a tracking issue\n        self.developer.create_issue(\n            owner=spec.owner,\n            repo=spec.repo_name,\n            title=f\"Build manifest: {spec.name}\",\n            body=(\n                f\"## Build Manifest\\n\\n\"\n                f\"```json\\n{json.dumps(manifest, indent=2, default=str)}\\n```\\n\\n\"\n                f\"Build completed at {time.strftime('%Y-%m-%d %H:%M:%S UTC')}\"\n            ),\n            labels=[\"build-manifest\", \"agent-created\"],\n        )\n\n        manifest[\"build_log\"] = self.build_log\n        return manifest\n```\n\n### End-to-End Walkthrough\n\nThe factory building a complete newsletter SaaS from a single specification:\n\n```python\nspec = SaaSSpec(\n    name=\"NewsletterPro\",\n    description=\"Automated newsletter platform with analytics and billing\",\n    repo_name=\"newsletter-pro\",\n    owner=\"myorg\",\n    monthly_price_cents=2900,\n    yearly_price_cents=29000,\n    tables={\n        \"subscribers\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"email VARCHAR(255) UNIQUE NOT NULL\",\n            \"name VARCHAR(255)\",\n            \"status VARCHAR(20) DEFAULT 'active'\",\n            \"stripe_customer_id VARCHAR(255)\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"newsletters\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"subject VARCHAR(500) NOT NULL\",\n            \"body TEXT NOT NULL\",\n            \"status VARCHAR(20) DEFAULT 'draft'\",\n            \"sent_at TIMESTAMPTZ\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    migrations=[\n        {\n            \"version\": \"001\",\n            \"description\": \"Initial schema\",\n            \"up\": \"SELECT 1\",  # Tables already created by schema_first_design\n        },\n    ],\n    app_files={\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI\napp = FastAPI(title=\"NewsletterPro\")\n\n@app.get(\"\u002Fhealth\")\ndef health():\n    return {\"status\": \"ok\"}\n''',\n        \"src\u002Fsubscribers.py\": '''from fastapi import APIRouter\nrouter = APIRouter(prefix=\"\u002Fapi\u002Fsubscribers\", tags=[\"subscribers\"])\n\n@router.post(\"\u002F\")\ndef add_subscriber(email: str, name: str = None):\n    \"\"\"Add a new subscriber.\"\"\"\n    pass  # Implementation uses AgentDBA.execute_query\n\n@router.get(\"\u002F\")\ndef list_subscribers(limit: int = 50, offset: int = 0):\n    \"\"\"List all active subscribers.\"\"\"\n    pass\n''',\n        \"Dockerfile\": '''FROM python:3.12-slim\nWORKDIR \u002Fapp\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY src\u002F src\u002F\nCMD [\"uvicorn\", \"src.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n''',\n        \".github\u002Fworkflows\u002Fci.yml\": '''name: CI\non: [push, pull_request]\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n      - run: pip install -r requirements.txt\n      - run: python -m pytest tests\u002F -x -q\n''',\n    },\n    success_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fwelcome\",\n    cancel_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fpricing\",\n)\n\n# Build the entire SaaS\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"factory-01\",\n)\n\nmanifest = factory.build(spec)\n\n# Output: complete manifest with all resource IDs\nprint(json.dumps(manifest[\"resources\"], indent=2, default=str))\n```\n\n### CrewAI Integration Pattern\n\nThe factory integrates as a CrewAI tool:\n\n```python\nfrom crewai import Agent, Task, Crew\nfrom crewai_tools import tool\n\n\n@tool(\"build_saas\")\ndef build_saas_tool(spec_json: str) -> str:\n    \"\"\"Build a complete micro-SaaS from a JSON specification.\n\n    The spec must include: name, description, repo_name, owner,\n    monthly_price_cents, tables (dict), and app_files (dict).\n    \"\"\"\n    spec_data = json.loads(spec_json)\n    spec = SaaSSpec(**spec_data)\n\n    factory = AgentSaaSFactory(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"crewai-factory\",\n    )\n    manifest = factory.build(spec)\n    return json.dumps(manifest[\"resources\"], indent=2, default=str)\n\n\nproduct_manager = Agent(\n    role=\"Product Manager\",\n    goal=\"Define micro-SaaS specifications based on market research\",\n    backstory=\"You identify gaps in the SaaS market and write specs.\",\n)\n\nbuilder = Agent(\n    role=\"SaaS Builder\",\n    goal=\"Build complete micro-SaaS products from specifications\",\n    backstory=\"You turn product specs into deployed, billing-enabled SaaS.\",\n    tools=[build_saas_tool],\n)\n\ndefine_task = Task(\n    description=\"Research the newsletter SaaS market and define a spec.\",\n    expected_output=\"JSON spec for a newsletter SaaS product.\",\n    agent=product_manager,\n)\n\nbuild_task = Task(\n    description=\"Build the SaaS from the spec provided by the PM.\",\n    expected_output=\"Build manifest with all resource IDs.\",\n    agent=builder,\n)\n\ncrew = Crew(\n    agents=[product_manager, builder],\n    tasks=[define_task, build_task],\n    verbose=True,\n)\n\nresult = crew.kickoff()\n```\n\n**Total cost for a full factory build:** ~75-125 tool calls across all three services = $0.55-$0.95. Under a dollar to build and deploy a micro-SaaS.\n\n---\n\n## Chapter 6: Dispute Resolution and Customer Support Automation\n\n### The AgentArbitrator Class\n\nThis class wraps all 5 dispute tools. The agent uses it to handle chargebacks, enforce SLAs, and resolve customer disputes without human intervention.\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional, Literal, List\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass EscalationRule:\n    \"\"\"Defines when a dispute should be escalated to a human.\"\"\"\n    max_amount_cents: int\n    max_auto_resolve_count: int\n    require_human_above: int  # amount in cents\n\n\nclass AgentArbitrator:\n    \"\"\"Dispute resolution client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 5 dispute tools into an arbitration interface for\n    automated chargeback handling, SLA enforcement, and dispute analytics.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        escalation_rules: Optional[EscalationRule] = None,\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.escalation_rules = escalation_rules or EscalationRule(\n            max_amount_cents=10000,      # $100\n            max_auto_resolve_count=5,\n            require_human_above=50000,   # $500\n        )\n        self._auto_resolve_count = 0\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Core Dispute Operations ---------------------------------------\n\n    def open_dispute(\n        self,\n        transaction_id: str,\n        reason: str,\n        amount_cents: int,\n        evidence: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Open a new dispute against a transaction.\"\"\"\n        payload = {\n            \"transaction_id\": transaction_id,\n            \"reason\": reason,\n            \"amount_cents\": amount_cents,\n        }\n        if evidence:\n            payload[\"evidence\"] = evidence\n        return self._execute(\"open_dispute\", payload)\n\n    def respond_dispute(\n        self,\n        dispute_id: str,\n        response_text: str,\n        evidence: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Respond to a dispute with evidence.\"\"\"\n        payload = {\n            \"dispute_id\": dispute_id,\n            \"response\": response_text,\n        }\n        if evidence:\n            payload[\"evidence\"] = evidence\n        return self._execute(\"respond_dispute\", payload)\n\n    def resolve_dispute(\n        self,\n        dispute_id: str,\n        resolution: Literal[\"accepted\", \"rejected\", \"refunded\"],\n        notes: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Resolve or close a dispute.\"\"\"\n        payload = {\n            \"dispute_id\": dispute_id,\n            \"resolution\": resolution,\n        }\n        if notes:\n            payload[\"notes\"] = notes\n        return self._execute(\"resolve_dispute\", payload)\n\n    def list_disputes(\n        self,\n        status: Optional[str] = None,\n        limit: int = 50,\n    ) -> dict:\n        \"\"\"List all disputes with optional status filter.\"\"\"\n        payload = {\"limit\": limit}\n        if status:\n            payload[\"status\"] = status\n        return self._execute(\"list_disputes\", payload)\n\n    def get_dispute(self, dispute_id: str) -> dict:\n        \"\"\"Get full details for a specific dispute.\"\"\"\n        return self._execute(\"get_dispute\", {\n            \"dispute_id\": dispute_id,\n        })\n\n    # -- Automated Chargeback Handling ---------------------------------\n\n    def handle_chargeback(\n        self,\n        dispute_id: str,\n        billing: \"AgentBilling\",\n        dba: \"AgentDBA\",\n    ) -> dict:\n        \"\"\"Automated chargeback response pipeline.\n\n        1. Fetch dispute details\n        2. Gather evidence from Stripe and database\n        3. Auto-respond if within escalation rules\n        4. Escalate to human if above thresholds\n        \"\"\"\n        dispute = self.get_dispute(dispute_id)\n        amount = dispute.get(\"amount_cents\", 0)\n\n        # Check escalation rules\n        if amount > self.escalation_rules.require_human_above:\n            return {\n                \"action\": \"escalated\",\n                \"reason\": f\"Amount ${amount\u002F100:.2f} exceeds auto-resolve threshold\",\n                \"dispute\": dispute,\n            }\n\n        if self._auto_resolve_count >= self.escalation_rules.max_auto_resolve_count:\n            return {\n                \"action\": \"escalated\",\n                \"reason\": \"Auto-resolve count limit reached\",\n                \"dispute\": dispute,\n            }\n\n        # Gather evidence from Stripe\n        tx_id = dispute.get(\"transaction_id\", \"\")\n        payment = billing.get_payment_intent(tx_id)\n\n        # Gather evidence from database\n        db_records = dba.query(\n            \"SELECT * FROM revenue_events WHERE stripe_payment_intent_id = $1\",\n            params=[tx_id],\n        )\n\n        evidence = {\n            \"payment_status\": payment.get(\"status\"),\n            \"payment_created\": payment.get(\"created\"),\n            \"delivery_confirmed\": len(db_records.get(\"rows\", [])) > 0,\n            \"customer_id\": payment.get(\"customer\"),\n        }\n\n        # Respond with evidence\n        self.respond_dispute(\n            dispute_id=dispute_id,\n            response_text=(\n                f\"Payment {tx_id} was completed successfully on \"\n                f\"{payment.get('created')}. Service delivery confirmed \"\n                f\"in application database. Customer ID: {payment.get('customer')}.\"\n            ),\n            evidence=evidence,\n        )\n\n        # Auto-resolve if amount is within threshold\n        if amount \u003C= self.escalation_rules.max_amount_cents:\n            resolution = self.resolve_dispute(\n                dispute_id=dispute_id,\n                resolution=\"rejected\",\n                notes=\"Auto-resolved: evidence confirms valid transaction\",\n            )\n            self._auto_resolve_count += 1\n            return {\"action\": \"auto_resolved\", \"resolution\": resolution}\n\n        return {\"action\": \"responded\", \"evidence_submitted\": True}\n\n    # -- SLA Enforcement -----------------------------------------------\n\n    def enforce_sla(\n        self,\n        sla_hours: int = 24,\n    ) -> List[dict]:\n        \"\"\"Check for open disputes approaching SLA deadline.\n\n        Returns list of disputes needing attention.\n        \"\"\"\n        open_disputes = self.list_disputes(status=\"open\")\n        urgent = []\n\n        for dispute in open_disputes.get(\"data\", []):\n            created = dispute.get(\"created_at\", 0)\n            elapsed_hours = (time.time() - created) \u002F 3600\n\n            if elapsed_hours > sla_hours * 0.75:  # 75% of SLA\n                urgent.append({\n                    \"dispute_id\": dispute[\"id\"],\n                    \"elapsed_hours\": round(elapsed_hours, 1),\n                    \"sla_hours\": sla_hours,\n                    \"remaining_hours\": round(sla_hours - elapsed_hours, 1),\n                    \"amount_cents\": dispute.get(\"amount_cents\", 0),\n                })\n\n        return urgent\n\n    # -- Dispute Analytics ---------------------------------------------\n\n    def get_dispute_analytics(self) -> dict:\n        \"\"\"Generate analytics across all disputes.\"\"\"\n        all_disputes = self.list_disputes(limit=200)\n        disputes = all_disputes.get(\"data\", [])\n\n        total = len(disputes)\n        if total == 0:\n            return {\"total\": 0, \"message\": \"No disputes found\"}\n\n        by_status = {}\n        total_amount = 0\n        for d in disputes:\n            status = d.get(\"status\", \"unknown\")\n            by_status[status] = by_status.get(status, 0) + 1\n            total_amount += d.get(\"amount_cents\", 0)\n\n        return {\n            \"total_disputes\": total,\n            \"by_status\": by_status,\n            \"total_amount_cents\": total_amount,\n            \"average_amount_cents\": total_amount \u002F\u002F total,\n            \"win_rate\": by_status.get(\"rejected\", 0) \u002F max(total, 1),\n        }\n```\n\n### Pattern: Automated Chargeback Pipeline\n\nThe agent gathers evidence from Stripe and the database, then responds or escalates based on configurable rules.\n\n```python\nimport os\n\narbitrator = AgentArbitrator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"arbitrator-01\",\n    escalation_rules=EscalationRule(\n        max_amount_cents=5000,       # Auto-resolve up to $50\n        max_auto_resolve_count=10,   # Max 10 auto-resolves per session\n        require_human_above=25000,   # Always escalate above $250\n    ),\n)\n\nbilling = AgentBilling(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"billing-agent-01\",\n)\ndba = AgentDBA(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"dba-agent-01\",\n)\n\n# Process all open disputes\nopen_disputes = arbitrator.list_disputes(status=\"open\")\nfor dispute in open_disputes.get(\"data\", []):\n    result = arbitrator.handle_chargeback(\n        dispute_id=dispute[\"id\"],\n        billing=billing,\n        dba=dba,\n    )\n    print(f\"Dispute {dispute['id']}: {result['action']}\")\n```\n\n### Pattern: SLA Enforcement Loop\n\nRun hourly to catch disputes approaching their SLA deadline.\n\n```python\n# Hourly SLA check\nurgent = arbitrator.enforce_sla(sla_hours=24)\nif urgent:\n    print(f\"WARNING: {len(urgent)} disputes approaching SLA deadline\")\n    for d in urgent:\n        print(\n            f\"  Dispute {d['dispute_id']}: \"\n            f\"{d['remaining_hours']}h remaining, \"\n            f\"${d['amount_cents']\u002F100:.2f}\"\n        )\n\n# Daily analytics\nanalytics = arbitrator.get_dispute_analytics()\nprint(f\"\\nDispute Analytics:\")\nprint(f\"  Total: {analytics['total_disputes']}\")\nprint(f\"  By status: {analytics['by_status']}\")\nprint(f\"  Win rate: {analytics.get('win_rate', 0):.0%}\")\nprint(f\"  Avg amount: ${analytics.get('average_amount_cents', 0)\u002F100:.2f}\")\n```\n\n---\n\n## Chapter 7: Security, Cost Governance, and Guardrails\n\nAutonomous agents with access to repositories, databases, and payment systems need hard constraints. These guardrails prevent an agent from draining your Stripe account, dropping production tables, or committing secrets.\n\n### Budget Caps for Pro-Tier Tools\n\nAn agent in a retry loop burns credits fast. Set explicit per-session budget caps.\n\n```python\nclass BudgetExhaustedError(Exception):\n    \"\"\"Raised when an agent exceeds its budget cap.\"\"\"\n    pass\n\n\nclass BudgetGovernor:\n    \"\"\"Tracks tool call spending and enforces hard limits.\"\"\"\n\n    def __init__(self, daily_limit_usd: float = 5.00):\n        self.daily_limit = daily_limit_usd\n        self.spent_today = 0.0\n        self.call_log = []\n        self.cost_map = {\n            \"github\": 0.005,\n            \"stripe\": 0.01,\n            \"postgres\": 0.01,\n            \"dispute\": 0.01,\n        }\n\n    def check_and_record(self, service: str):\n        \"\"\"Check budget before a tool call; raise if exceeded.\"\"\"\n        cost = self.cost_map.get(service, 0.01)\n        if self.spent_today + cost > self.daily_limit:\n            raise BudgetExhaustedError(\n                f\"Daily limit ${self.daily_limit:.2f} would be exceeded. \"\n                f\"Spent today: ${self.spent_today:.2f}\"\n            )\n        self.spent_today += cost\n        self.call_log.append({\n            \"service\": service,\n            \"cost\": cost,\n            \"running_total\": self.spent_today,\n            \"timestamp\": time.time(),\n        })\n\n    def get_remaining(self) -> float:\n        return self.daily_limit - self.spent_today\n\n    def get_summary(self) -> dict:\n        by_service = {}\n        for entry in self.call_log:\n            svc = entry[\"service\"]\n            by_service[svc] = by_service.get(svc, 0) + entry[\"cost\"]\n        return {\n            \"spent_today\": round(self.spent_today, 4),\n            \"daily_limit\": self.daily_limit,\n            \"remaining\": round(self.get_remaining(), 4),\n            \"by_service\": by_service,\n            \"total_calls\": len(self.call_log),\n        }\n\n\n# Usage: wrap the factory with budget governance\ngovernor = BudgetGovernor(daily_limit_usd=5.00)\n\n# Before every tool call in _execute:\ngovernor.check_and_record(\"github\")   # raises if over budget\ngovernor.check_and_record(\"postgres\") # raises if over budget\n\n# Periodic check\nsummary = governor.get_summary()\nprint(f\"Budget: ${summary['remaining']:.2f} remaining of ${summary['daily_limit']:.2f}\")\n```\n\n### SQL Injection Prevention\n\nThe agent generates SQL dynamically. Every query with user-derived data must use parameterized queries. The `AgentDBA` class enforces this through its `params` argument, but defense-in-depth adds a second check.\n\n```python\nimport re\n\nDANGEROUS_PATTERNS = [\n    r\";\\s*DROP\\s\",\n    r\";\\s*DELETE\\s+FROM\\s\",\n    r\";\\s*TRUNCATE\\s\",\n    r\";\\s*ALTER\\s+TABLE\\s.*DROP\\s\",\n    r\"--\\s\",\n    r\"\u002F\\*\",\n    r\"'\\s*OR\\s+'1'\\s*=\\s*'1\",\n    r\"UNION\\s+SELECT\",\n]\n\n\ndef validate_sql(sql: str) -> bool:\n    \"\"\"Reject SQL containing injection patterns.\n\n    This is a defense-in-depth measure. The primary protection is\n    parameterized queries in AgentDBA.query() and .execute_query().\n    \"\"\"\n    for pattern in DANGEROUS_PATTERNS:\n        if re.search(pattern, sql, re.IGNORECASE):\n            raise SQLInjectionError(\n                f\"SQL rejected: matches pattern '{pattern}'\"\n            )\n    return True\n\n\nclass SQLInjectionError(Exception):\n    pass\n\n\n# Integrate into AgentDBA._execute as a pre-check\n# validate_sql(input_data.get(\"sql\", \"\"))\n```\n\n### Idempotency Keys\n\nStripe operations must be idempotent. If the agent retries a checkout session creation due to a timeout, it must not create a duplicate. Use client-generated idempotency keys.\n\n```python\nimport hashlib\n\n\ndef make_idempotency_key(agent_id: str, operation: str, params: dict) -> str:\n    \"\"\"Generate a deterministic idempotency key from operation parameters.\n\n    Same agent + same operation + same params = same key.\n    Prevents duplicate Stripe objects on retry.\n    \"\"\"\n    payload = json.dumps(\n        {\"agent\": agent_id, \"op\": operation, \"params\": params},\n        sort_keys=True,\n    )\n    return hashlib.sha256(payload.encode()).hexdigest()[:32]\n\n\n# Usage in AgentBilling\nkey = make_idempotency_key(\n    agent_id=\"billing-agent-01\",\n    operation=\"create_checkout_session\",\n    params={\"price_id\": \"price_abc\", \"customer_id\": \"cus_123\"},\n)\n# Pass as header: Idempotency-Key: {key}\n```\n\n### Branch Protection\n\nThe agent should never push directly to `main`. All changes go through feature branches and pull requests.\n\n```python\nclass BranchProtectionPolicy:\n    \"\"\"Enforces branch protection rules for agent commits.\"\"\"\n\n    PROTECTED_BRANCHES = {\"main\", \"master\", \"production\", \"release\"}\n\n    @classmethod\n    def validate_branch(cls, branch: str) -> str:\n        \"\"\"Ensure the agent is not writing to a protected branch.\"\"\"\n        if branch in cls.PROTECTED_BRANCHES:\n            raise BranchProtectionError(\n                f\"Direct writes to '{branch}' are prohibited. \"\n                f\"Use a feature branch and create a pull request.\"\n            )\n        return branch\n\n    @classmethod\n    def generate_feature_branch(cls, prefix: str, description: str) -> str:\n        \"\"\"Generate a safe feature branch name.\"\"\"\n        slug = re.sub(r\"[^a-z0-9]+\", \"-\", description.lower()).strip(\"-\")[:40]\n        return f\"{prefix}\u002F{slug}\"\n\n\nclass BranchProtectionError(Exception):\n    pass\n\n\n# Before any create_or_update_file call:\nbranch = BranchProtectionPolicy.generate_feature_branch(\n    prefix=\"agent\",\n    description=\"add billing integration\",\n)\n# Result: \"agent\u002Fadd-billing-integration\"\nBranchProtectionPolicy.validate_branch(branch)  # passes\nBranchProtectionPolicy.validate_branch(\"main\")  # raises\n```\n\n### Kill Switch Pattern\n\nEvery long-running agent process needs a kill switch. If the agent enters a bad state, you need to stop it immediately.\n\n```python\nimport os\nimport signal\n\n\nclass KillSwitch:\n    \"\"\"Emergency stop for agent processes.\n\n    Check this before every tool call. If the kill file exists,\n    the agent stops immediately.\n    \"\"\"\n\n    def __init__(self, kill_file: str = \"\u002Ftmp\u002Fagent_kill_switch\"):\n        self.kill_file = kill_file\n\n    def check(self):\n        \"\"\"Raise if kill switch is engaged.\"\"\"\n        if os.path.exists(self.kill_file):\n            raise AgentKilledError(\n                f\"Kill switch engaged: {self.kill_file} exists. \"\n                f\"Remove the file to resume.\"\n            )\n\n    def engage(self, reason: str = \"manual\"):\n        \"\"\"Engage the kill switch.\"\"\"\n        with open(self.kill_file, \"w\") as f:\n            f.write(f\"killed at {time.time()}: {reason}\\n\")\n\n    def disengage(self):\n        \"\"\"Remove the kill switch.\"\"\"\n        if os.path.exists(self.kill_file):\n            os.remove(self.kill_file)\n\n\nclass AgentKilledError(Exception):\n    pass\n\n\n# Integrate into the factory's _execute path:\nkill_switch = KillSwitch()\n\n# Before every tool call:\nkill_switch.check()  # raises AgentKilledError if kill file exists\n\n# From a human operator's terminal:\n# touch \u002Ftmp\u002Fagent_kill_switch   \u003C-- stops the agent immediately\n# rm \u002Ftmp\u002Fagent_kill_switch      \u003C-- allows it to resume\n```\n\n---\n\n## Chapter 8: Production Recipes\n\n### Recipe 1: Newsletter SaaS\n\n**What it builds:** Subscriber management with email sending, open tracking, and $29\u002Fmonth subscription billing.\n\n**Tools used:** All 34\n\n```python\nimport os\n\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"newsletter-factory\",\n)\n\nnewsletter_spec = SaaSSpec(\n    name=\"NewsletterPro\",\n    description=\"Newsletter platform with subscriber management and analytics\",\n    repo_name=\"newsletter-pro\",\n    owner=\"myorg\",\n    monthly_price_cents=2900,\n    yearly_price_cents=29000,\n    tables={\n        \"subscribers\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"email VARCHAR(255) UNIQUE NOT NULL\",\n            \"name VARCHAR(255)\",\n            \"status VARCHAR(20) DEFAULT 'active'\",\n            \"stripe_customer_id VARCHAR(255)\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"newsletters\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"subject VARCHAR(500) NOT NULL\",\n            \"body TEXT NOT NULL\",\n            \"status VARCHAR(20) DEFAULT 'draft'\",\n            \"sent_at TIMESTAMPTZ\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"send_log\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"newsletter_id INTEGER REFERENCES newsletters(id)\",\n            \"subscriber_id INTEGER REFERENCES subscribers(id)\",\n            \"status VARCHAR(20) DEFAULT 'pending'\",\n            \"opened_at TIMESTAMPTZ\",\n            \"open_count INTEGER DEFAULT 0\",\n            \"sent_at TIMESTAMPTZ\",\n            \"UNIQUE(newsletter_id, subscriber_id)\",\n        ],\n        \"revenue_events\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"subscriber_id INTEGER REFERENCES subscribers(id)\",\n            \"stripe_payment_intent_id VARCHAR(255) UNIQUE\",\n            \"amount_cents INTEGER NOT NULL\",\n            \"event_type VARCHAR(50) NOT NULL\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    app_files={\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI\nfrom src.subscribers import router as sub_router\nfrom src.newsletters import router as news_router\n\napp = FastAPI(title=\"NewsletterPro\", version=\"1.0.0\")\napp.include_router(sub_router)\napp.include_router(news_router)\n\n@app.get(\"\u002Fhealth\")\ndef health():\n    return {\"status\": \"ok\"}\n''',\n        \"src\u002Fsubscribers.py\": '''from fastapi import APIRouter, HTTPException\nrouter = APIRouter(prefix=\"\u002Fapi\u002Fsubscribers\", tags=[\"subscribers\"])\n\n@router.post(\"\u002F\")\ndef create(email: str, name: str = None):\n    return {\"status\": \"created\"}\n\n@router.get(\"\u002F\")\ndef list_all(limit: int = 50, offset: int = 0):\n    return {\"subscribers\": [], \"total\": 0}\n\n@router.delete(\"\u002F{subscriber_id}\")\ndef unsubscribe(subscriber_id: int):\n    return {\"status\": \"unsubscribed\"}\n''',\n        \"src\u002Fnewsletters.py\": '''from fastapi import APIRouter\nrouter = APIRouter(prefix=\"\u002Fapi\u002Fnewsletters\", tags=[\"newsletters\"])\n\n@router.post(\"\u002F\")\ndef create(subject: str, body: str):\n    return {\"status\": \"draft_created\"}\n\n@router.post(\"\u002F{newsletter_id}\u002Fsend\")\ndef send(newsletter_id: int):\n    return {\"status\": \"sending\"}\n''',\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n        \"Dockerfile\": '''FROM python:3.12-slim\nWORKDIR \u002Fapp\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY src\u002F src\u002F\nCMD [\"uvicorn\", \"src.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n''',\n    },\n)\n\nmanifest = factory.build(newsletter_spec)\n\n# Set up dispute handling for the newsletter SaaS\narbitrator = AgentArbitrator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"newsletter-arbitrator\",\n)\n```\n\n**Cost projection:**\n\n| Phase | Tool Calls | Cost |\n|-------|-----------|------|\n| Repository + scaffolding | 12 GitHub | $0.06 |\n| Schema + migrations | 10 Postgres | $0.10 |\n| Billing setup | 6 Stripe | $0.06 |\n| Verification | 8 mixed | $0.06 |\n| **Total build** | **36** | **$0.28** |\n| Daily operation | 5-10 | $0.05-$0.10 |\n| Monthly operation | 150-300 | $1.50-$3.00 |\n\nAt $29\u002Fmonth per customer, you break even at 1 customer. At 10 customers ($290\u002Fmonth), the agent operation cost is 1% of revenue.\n\n### Recipe 2: API-as-a-Service\n\n**What it builds:** Metered API with per-request billing, versioned releases, and usage tracking.\n\n**Tools used:** GitHub (10), Postgres (6), Stripe (13)\n\n```python\napi_spec = SaaSSpec(\n    name=\"TranslateAPI\",\n    description=\"Neural machine translation API with per-request billing\",\n    repo_name=\"translate-api\",\n    owner=\"myorg\",\n    monthly_price_cents=0,  # Usage-based, no base fee\n    tables={\n        \"api_keys\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"key_hash VARCHAR(64) UNIQUE NOT NULL\",\n            \"customer_id VARCHAR(255) NOT NULL\",\n            \"name VARCHAR(255)\",\n            \"rate_limit INTEGER DEFAULT 100\",\n            \"active BOOLEAN DEFAULT true\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"usage_log\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"api_key_id INTEGER REFERENCES api_keys(id)\",\n            \"endpoint VARCHAR(255) NOT NULL\",\n            \"request_chars INTEGER NOT NULL\",\n            \"response_chars INTEGER NOT NULL\",\n            \"latency_ms INTEGER\",\n            \"status_code INTEGER\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"releases\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"version VARCHAR(20) NOT NULL UNIQUE\",\n            \"changelog TEXT\",\n            \"model_version VARCHAR(50)\",\n            \"released_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    app_files={\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI, Header, HTTPException\napp = FastAPI(title=\"TranslateAPI\", version=\"2.0.0\")\n\n@app.post(\"\u002Fv2\u002Ftranslate\")\ndef translate(text: str, target_lang: str, x_api_key: str = Header()):\n    # Verify API key, log usage, translate, return\n    return {\"translated\": text, \"lang\": target_lang}\n\n@app.get(\"\u002Fv2\u002Fusage\")\ndef get_usage(x_api_key: str = Header()):\n    return {\"requests_this_month\": 0, \"cost_cents\": 0}\n''',\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n    },\n)\n\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"api-factory\",\n)\nmanifest = factory.build(api_spec)\n\n# Set up metered billing separately (usage-based, not subscription)\nbilling = AgentBilling(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"api-billing\",\n)\n\nmetered_product = billing.setup_usage_based_product(\n    name=\"TranslateAPI Usage\",\n    description=\"Per-request translation API billing\",\n    per_unit_cents=1,  # $0.01 per request\n)\n\n# Agent manages versioned releases through GitHub\ndev = AgentDeveloper(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"api-dev\",\n)\n\n# Tag a release\ncommits = dev.list_commits(\"myorg\", \"translate-api\", per_page=1)\nlatest_sha = commits[0][\"sha\"] if commits else \"HEAD\"\n\ndev.create_or_update_file(\n    owner=\"myorg\",\n    repo=\"translate-api\",\n    path=\"CHANGELOG.md\",\n    content=\"# v2.1.0\\n- Added batch translation endpoint\\n- Improved latency by 40%\\n\",\n    message=\"Release v2.1.0\",\n)\n```\n\n**Cost projection:**\n\n| Phase | Tool Calls | Cost |\n|-------|-----------|------|\n| Build | 30 | $0.22 |\n| Monthly operation | 200-500 | $2.00-$5.00 |\n| Monthly revenue (1k requests\u002Fday) | - | $300.00 |\n| Margin | - | **98%+** |\n\n### Recipe 3: Agent Marketplace Operator\n\n**What it builds:** Marketplace where AI agents list and sell services. The operator handles listings, payments, and disputes.\n\n**Tools used:** All 34\n\n```python\nmarketplace_spec = SaaSSpec(\n    name=\"AgentBazaar\",\n    description=\"Marketplace for AI agent services with escrow and dispute resolution\",\n    repo_name=\"agent-bazaar\",\n    owner=\"myorg\",\n    monthly_price_cents=4900,  # $49\u002Fmonth for marketplace access\n    yearly_price_cents=49000,  # $490\u002Fyear\n    tables={\n        \"sellers\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"agent_id VARCHAR(255) UNIQUE NOT NULL\",\n            \"name VARCHAR(255) NOT NULL\",\n            \"stripe_account_id VARCHAR(255)\",\n            \"trust_score NUMERIC(5,2) DEFAULT 0.50\",\n            \"verified BOOLEAN DEFAULT false\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"listings\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"seller_id INTEGER REFERENCES sellers(id)\",\n            \"title VARCHAR(500) NOT NULL\",\n            \"description TEXT NOT NULL\",\n            \"price_cents INTEGER NOT NULL\",\n            \"category VARCHAR(100)\",\n            \"active BOOLEAN DEFAULT true\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"orders\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"listing_id INTEGER REFERENCES listings(id)\",\n            \"buyer_agent_id VARCHAR(255) NOT NULL\",\n            \"seller_id INTEGER REFERENCES sellers(id)\",\n            \"status VARCHAR(30) DEFAULT 'pending'\",\n            \"stripe_payment_intent_id VARCHAR(255)\",\n            \"amount_cents INTEGER NOT NULL\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n            \"completed_at TIMESTAMPTZ\",\n        ],\n        \"reviews\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"order_id INTEGER REFERENCES orders(id) UNIQUE\",\n            \"reviewer_agent_id VARCHAR(255) NOT NULL\",\n            \"rating INTEGER CHECK (rating BETWEEN 1 AND 5)\",\n            \"comment TEXT\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    app_files={\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI\napp = FastAPI(title=\"AgentBazaar\", version=\"1.0.0\")\n\n@app.get(\"\u002Fhealth\")\ndef health():\n    return {\"status\": \"ok\"}\n\n@app.get(\"\u002Fapi\u002Flistings\")\ndef list_services(category: str = None, limit: int = 20):\n    return {\"listings\": [], \"total\": 0}\n\n@app.post(\"\u002Fapi\u002Forders\")\ndef create_order(listing_id: int, buyer_agent_id: str):\n    return {\"status\": \"pending\", \"order_id\": None}\n''',\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n    },\n)\n\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"marketplace-factory\",\n)\nmanifest = factory.build(marketplace_spec)\n\n# The marketplace operator handles disputes between buyer and seller agents\narbitrator = AgentArbitrator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"marketplace-arbitrator\",\n    escalation_rules=EscalationRule(\n        max_amount_cents=10000,       # Auto-resolve up to $100\n        max_auto_resolve_count=20,    # Higher limit for marketplace volume\n        require_human_above=50000,    # Escalate above $500\n    ),\n)\n\n# Trust-weighted auto-resolution: use seller trust score to decide\ndba = AgentDBA(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"marketplace-dba\",\n)\n\ndef trust_weighted_resolve(dispute_id: str):\n    \"\"\"Resolve disputes using seller trust scores.\"\"\"\n    dispute = arbitrator.get_dispute(dispute_id)\n    tx_id = dispute.get(\"transaction_id\")\n\n    # Look up the order and seller trust score\n    order = dba.query(\n        \"SELECT o.*, s.trust_score FROM orders o \"\n        \"JOIN sellers s ON o.seller_id = s.id \"\n        \"WHERE o.stripe_payment_intent_id = $1\",\n        params=[tx_id],\n    )\n\n    if not order.get(\"rows\"):\n        return arbitrator.resolve_dispute(\n            dispute_id, \"accepted\", \"Order not found -- refunding buyer\"\n        )\n\n    seller_trust = float(order[\"rows\"][0].get(\"trust_score\", 0.5))\n\n    if seller_trust >= 0.90:\n        # High-trust seller: reject dispute (favor seller)\n        return arbitrator.resolve_dispute(\n            dispute_id, \"rejected\",\n            f\"Seller trust score {seller_trust:.2f} -- favoring seller\",\n        )\n    elif seller_trust \u003C 0.30:\n        # Low-trust seller: accept dispute (favor buyer)\n        return arbitrator.resolve_dispute(\n            dispute_id, \"refunded\",\n            f\"Seller trust score {seller_trust:.2f} -- refunding buyer\",\n        )\n    else:\n        # Mid-range: submit evidence and let it pend for human review\n        arbitrator.respond_dispute(\n            dispute_id,\n            f\"Seller trust score: {seller_trust:.2f}. Requires human review.\",\n        )\n        return {\"action\": \"pending_review\"}\n```\n\n**Cost projection:**\n\n| Phase | Tool Calls | Cost |\n|-------|-----------|------|\n| Build | 45 | $0.35 |\n| Monthly operation (100 orders\u002Fday) | 1,500 | $12.00 |\n| Monthly revenue (50 sellers at $49) | - | $2,450.00 |\n| Dispute handling (5% dispute rate) | 300 | $3.00 |\n| **Monthly margin** | - | **99%+** |\n\n---\n\n## Chapter 9: What's Next\n\n### Cross-References to the Product Library\n\nThis guide covers the build phase. The other guides in the series cover operational depth:\n\n- **P1: Agent-to-Agent Commerce** -- Escrow patterns for when your factory agents outsource subtasks to specialist agents.\n- **P2: Agent FinOps Playbook** -- Budget enforcement and spend analytics for agent fleets. Essential beyond three agents.\n- **P3: Verified Bot Reputation** -- Cryptographic proof of your SaaS agent's track record for marketplace trust.\n- **P4: Trading Bot Audit Trail** -- Immutable logging for any agent handling money. Compliance-grade Stripe records.\n- **P5: Agent Trust Verification** -- Trust scoring algorithms for Recipe 3's trust-weighted dispute resolution.\n- **P6: Strategy Marketplace Playbook** -- Marketplace operations at scale: moderation, fraud detection, multi-sided economics.\n\n### Agent-to-Agent SaaS\n\nThe factory pattern in this guide builds SaaS for human customers. The next evolution: SaaS built by agents, for agents, purchased by agents. Agent A builds a translation API (Recipe 2). Agent B discovers it on the GreenHelix marketplace. Agent C evaluates the seller's trust score. The buyer creates an escrow, the seller performs the work, the escrow releases on delivery confirmation. No human involved at any step. The 34 tools here cover the supply side. The full 128-tool GreenHelix catalog covers the demand side.\n\n### Portfolio Management\n\nOnce proven with a single product, an orchestrator agent runs multiple factories in parallel. It tracks revenue per product, reallocates budget from underperformers, and shuts down products that miss profitability thresholds.\n\n```python\nclass SaaSPortfolio:\n    \"\"\"Manage a portfolio of agent-built micro-SaaS products.\"\"\"\n\n    def __init__(self, factory: AgentSaaSFactory):\n        self.factory = factory\n        self.products = {}\n\n    def launch(self, spec: SaaSSpec) -> dict:\n        manifest = self.factory.build(spec)\n        self.products[spec.name] = {\n            \"manifest\": manifest,\n            \"launched_at\": time.time(),\n            \"revenue_cents\": 0,\n            \"cost_cents\": 0,\n        }\n        return manifest\n\n    def evaluate(self, days_threshold: int = 30) -> List[dict]:\n        \"\"\"Evaluate all products and recommend actions.\"\"\"\n        recommendations = []\n        for name, data in self.products.items():\n            age_days = (time.time() - data[\"launched_at\"]) \u002F 86400\n            if age_days \u003C days_threshold:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"observe\",\n                    \"reason\": f\"Only {age_days:.0f} days old\",\n                })\n            elif data[\"revenue_cents\"] == 0:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"sunset\",\n                    \"reason\": \"Zero revenue after threshold\",\n                })\n            elif data[\"revenue_cents\"] > data[\"cost_cents\"] * 3:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"scale\",\n                    \"reason\": \"3x+ ROI -- increase investment\",\n                })\n            else:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"optimize\",\n                    \"reason\": \"Positive but below 3x threshold\",\n                })\n        return recommendations\n```\n\nThe agent economy is here. Stripe handles the demand side. The Agent SaaS Factory handles the supply side. GitHub for code, Postgres for data, Stripe for money, Disputes for trust -- 34 tools, under a dollar per build, pennies per day to operate. Build one. Ship it. Watch it earn. Then build the next one.\n\n","# The Agent SaaS Factory: Build, Deploy, and Monetize Software Products with Autonomous AI Agents\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nWhen Stripe announced the Agentic Commerce Suite in March 2026 -- with Visa, OpenAI, and Samsung as launch partners -- they framed it as \"AI agents that can buy things.\" That is the merchant side of the equation. An agent browses a storefront, picks a product, and pays with a human's saved card. But what about the other side? What about an agent that builds the product, sets up the billing, deploys the database, handles the disputes, and operates the entire business -- end to end, without a human writing a single line of code or clicking a single button in a dashboard?\nThat is what this guide builds. A factory pattern where autonomous AI agents receive a product specification and produce a running, revenue-generating micro-SaaS: repository scaffolded on GitHub, schema designed and migrated in Postgres, billing configured in Stripe, dispute resolution automated, and the whole pipeline orchestrated by a single `AgentSaaSFactory` class. The BotStall marketplace demonstrated in late 2025 that agents could list and sell digital goods. We go further: agents that build, operate, and defend the entire software business.\nThe infrastructure is the GreenHelix A2A Commerce Gateway's pro-tier integration tools: 10 GitHub tools, 13 Stripe tools, 6 Postgres tools, and 5 Dispute tools -- 34 tools total, all accessible through a single HTTP endpoint at $0.005-$0.01 per call. This guide covers every one of them.\n\n## What You'll Learn\n- Chapter 1: Why Agents Should Build SaaS\n- Chapter 2: Setting Up the Agent's Development Environment\n- Chapter 3: The Data Layer: Agents Managing Postgres\n- Chapter 4: Monetization: Agents Running Stripe\n- Chapter 5: The Full Factory: Orchestrating the Pipeline\n- Chapter 6: Dispute Resolution and Customer Support Automation\n- Chapter 7: Security, Cost Governance, and Guardrails\n- Chapter 8: Production Recipes\n- Chapter 9: What's Next\n\n## Full Guide\n\n# The Agent SaaS Factory: Build, Deploy, and Monetize Software Products with Autonomous AI Agents\n\nWhen Stripe announced the Agentic Commerce Suite in March 2026 -- with Visa, OpenAI, and Samsung as launch partners -- they framed it as \"AI agents that can buy things.\" That is the merchant side of the equation. An agent browses a storefront, picks a product, and pays with a human's saved card. But what about the other side? What about an agent that builds the product, sets up the billing, deploys the database, handles the disputes, and operates the entire business -- end to end, without a human writing a single line of code or clicking a single button in a dashboard?\n\nThat is what this guide builds. A factory pattern where autonomous AI agents receive a product specification and produce a running, revenue-generating micro-SaaS: repository scaffolded on GitHub, schema designed and migrated in Postgres, billing configured in Stripe, dispute resolution automated, and the whole pipeline orchestrated by a single `AgentSaaSFactory` class. The BotStall marketplace demonstrated in late 2025 that agents could list and sell digital goods. We go further: agents that build, operate, and defend the entire software business.\n\nThe infrastructure is the GreenHelix A2A Commerce Gateway's pro-tier integration tools: 10 GitHub tools, 13 Stripe tools, 6 Postgres tools, and 5 Dispute tools -- 34 tools total, all accessible through a single HTTP endpoint at $0.005-$0.01 per call. This guide covers every one of them.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [Why Agents Should Build SaaS](#chapter-1-why-agents-should-build-saas)\n2. [Setting Up the Agent's Development Environment](#chapter-2-setting-up-the-agents-development-environment)\n3. [The Data Layer: Agents Managing Postgres](#chapter-3-the-data-layer-agents-managing-postgres)\n4. [Monetization: Agents Running Stripe](#chapter-4-monetization-agents-running-stripe)\n5. [The Full Factory: Orchestrating the Pipeline](#chapter-5-the-full-factory-orchestrating-the-pipeline)\n6. [Dispute Resolution and Customer Support Automation](#chapter-6-dispute-resolution-and-customer-support-automation)\n7. [Security, Cost Governance, and Guardrails](#chapter-7-security-cost-governance-and-guardrails)\n8. [Production Recipes](#chapter-8-production-recipes)\n9. [What's Next](#chapter-9-whats-next)\n\n---\n\n## Chapter 1: Why Agents Should Build SaaS\n\n### From Tools to Operators\n\nThe 2025 frame was \"agents as tools.\" Developer writes prompt, agent generates code, developer reviews and deploys. Faster pair programming. Useful. Not transformative.\n\nThe shift is \"agents as operators.\" The agent does not help you build a SaaS product -- it builds the SaaS product. Creates the repository. Designs the schema. Sets up Stripe pricing. Writes code, submits PRs, reviews diffs, merges. Monitors disputes and resolves them. The human's role shifts from implementer to investor: you provide the specification and the API credits. The agent does the rest.\n\nStripe's Agentic Commerce Suite already envisions agents that autonomously complete purchases and handle disputes. The missing piece is the supply side -- agents that build and operate the businesses those buyer agents purchase from.\n\n### The BotStall Precedent\n\nBotStall (late 2025) proved one half: agents listing and selling digital goods on a marketplace. But BotStall agents were vendors, not builders. A human created the product; the agent handled distribution. The Agent SaaS Factory closes the loop: the agent creates, operates, monetizes, and defends the entire business.\n\n### Architecture Overview\n\nThe factory runs on four services, all accessed through the GreenHelix A2A Commerce Gateway:\n\n```\n+------------------------------------------------------------+\n|                    AgentSaaSFactory                         |\n|                                                            |\n|  +------------------+  +------------------+                |\n|  | AgentDeveloper   |  | AgentDBA         |                |\n|  | 10 GitHub tools  |  | 6 Postgres tools |                |\n|  | $0.005\u002Fcall      |  | $0.01\u002Fcall       |                |\n|  +--------+---------+  +--------+---------+                |\n|           |                      |                         |\n|  +--------+---------+  +--------+---------+                |\n|  | AgentBilling     |  | AgentArbitrator  |                |\n|  | 13 Stripe tools  |  | 5 Dispute tools  |                |\n|  | $0.01\u002Fcall       |  | varies           |                |\n|  +--------+---------+  +--------+---------+                |\n|           |                      |                         |\n+-----------|----------------------|-------------------------+\n            |                      |\n   +--------v----------------------v---------+\n   |    GreenHelix A2A Commerce Gateway      |\n   |    Pro-tier: GitHub + Stripe + Postgres  |\n   |    + Disputes                            |\n   +------------------------------------------+\n```\n\n### Pro-Tier Cost Model\n\nEvery tool call has a fixed cost. There is no per-seat pricing, no monthly minimum, no overage surprise. You pay exactly for what the agent does.\n\n| Service | Tools | Cost per Call | Typical Calls per SaaS Build |\n|---------|-------|---------------|------------------------------|\n| GitHub | 10 | $0.005 | 40-60 |\n| Stripe | 13 | $0.01 | 15-25 |\n| Postgres | 6 | $0.01 | 20-40 |\n| Disputes | 5 | varies | 0-10 (reactive) |\n\nA complete micro-SaaS build costs $1.00-$1.50 in tool calls. Ongoing operation runs $0.10-$0.30\u002Fday. At $29\u002Fmonth from a single customer, the unit economics are immediately positive.\n\n---\n\n## Chapter 2: Setting Up the Agent's Development Environment\n\n### The AgentDeveloper Class\n\nThis class wraps all 10 GitHub tools into a development interface. The agent uses it to create repositories, scaffold projects, manage issues, submit pull requests, and perform code review.\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional, List\n\n\nclass AgentDeveloper:\n    \"\"\"GitHub development client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 10 GitHub integration tools into a development workflow\n    interface for autonomous repository management, code review, and\n    issue tracking.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Repository Management -----------------------------------------\n\n    def create_repo(\n        self,\n        name: str,\n        description: str,\n        private: bool = True,\n    ) -> dict:\n        \"\"\"Create a new GitHub repository.\"\"\"\n        return self._execute(\"create_repo\", {\n            \"name\": name,\n            \"description\": description,\n            \"private\": private,\n            \"auto_init\": True,\n        })\n\n    def get_repo(self, owner: str, repo: str) -> dict:\n        \"\"\"Get repository metadata.\"\"\"\n        return self._execute(\"get_repo\", {\n            \"owner\": owner,\n            \"repo\": repo,\n        })\n\n    # -- File Operations -----------------------------------------------\n\n    def get_file_contents(\n        self,\n        owner: str,\n        repo: str,\n        path: str,\n        ref: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Read a file from a repository.\"\"\"\n        payload = {\"owner\": owner, \"repo\": repo, \"path\": path}\n        if ref:\n            payload[\"ref\"] = ref\n        return self._execute(\"get_file_contents\", payload)\n\n    def create_or_update_file(\n        self,\n        owner: str,\n        repo: str,\n        path: str,\n        content: str,\n        message: str,\n        branch: Optional[str] = None,\n        sha: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Write or update a file in a repository.\"\"\"\n        payload = {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"path\": path,\n            \"content\": content,\n            \"message\": message,\n        }\n        if branch:\n            payload[\"branch\"] = branch\n        if sha:\n            payload[\"sha\"] = sha\n        return self._execute(\"create_or_update_file\", payload)\n\n    # -- Issue Tracking ------------------------------------------------\n\n    def create_issue(\n        self,\n        owner: str,\n        repo: str,\n        title: str,\n        body: str,\n        labels: Optional[List[str]] = None,\n    ) -> dict:\n        \"\"\"File a bug report or feature request.\"\"\"\n        payload = {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"title\": title,\n            \"body\": body,\n        }\n        if labels:\n            payload[\"labels\"] = labels\n        return self._execute(\"create_issue\", payload)\n\n    def get_issue(\n        self,\n        owner: str,\n        repo: str,\n        issue_number: int,\n    ) -> dict:\n        \"\"\"Retrieve issue details.\"\"\"\n        return self._execute(\"get_issue\", {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"issue_number\": issue_number,\n        })\n\n    # -- Code Review ---------------------------------------------------\n\n    def create_pull_request(\n        self,\n        owner: str,\n        repo: str,\n        title: str,\n        body: str,\n        head: str,\n        base: str = \"main\",\n    ) -> dict:\n        \"\"\"Submit code changes for review.\"\"\"\n        return self._execute(\"create_pull_request\", {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"title\": title,\n            \"body\": body,\n            \"head\": head,\n            \"base\": base,\n        })\n\n    def merge_pull_request(\n        self,\n        owner: str,\n        repo: str,\n        pull_number: int,\n        merge_method: str = \"squash\",\n    ) -> dict:\n        \"\"\"Merge an approved pull request.\"\"\"\n        return self._execute(\"merge_pull_request\", {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"pull_number\": pull_number,\n            \"merge_method\": merge_method,\n        })\n\n    # -- Code Intelligence ---------------------------------------------\n\n    def search_code(\n        self,\n        query: str,\n        owner: Optional[str] = None,\n        repo: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Search across codebases.\"\"\"\n        payload = {\"query\": query}\n        if owner and repo:\n            payload[\"query\"] = f\"{query} repo:{owner}\u002F{repo}\"\n        return self._execute(\"search_code\", payload)\n\n    def list_commits(\n        self,\n        owner: str,\n        repo: str,\n        sha: Optional[str] = None,\n        per_page: int = 30,\n    ) -> dict:\n        \"\"\"View commit history.\"\"\"\n        payload = {\n            \"owner\": owner,\n            \"repo\": repo,\n            \"per_page\": per_page,\n        }\n        if sha:\n            payload[\"sha\"] = sha\n        return self._execute(\"list_commits\", payload)\n\n    # -- High-Level Workflows ------------------------------------------\n\n    def scaffold_project(\n        self,\n        owner: str,\n        repo: str,\n        files: dict,\n        branch: str = \"main\",\n    ) -> List[dict]:\n        \"\"\"Write multiple files to scaffold a project.\n\n        Args:\n            files: dict mapping file paths to content strings.\n                   Example: {\"src\u002Fapp.py\": \"...\", \"requirements.txt\": \"...\"}\n        \"\"\"\n        results = []\n        for path, content in files.items():\n            result = self.create_or_update_file(\n                owner=owner,\n                repo=repo,\n                path=path,\n                content=content,\n                message=f\"scaffold: add {path}\",\n                branch=branch,\n            )\n            results.append(result)\n        return results\n\n    def review_and_merge(\n        self,\n        owner: str,\n        repo: str,\n        head_branch: str,\n        title: str,\n        description: str,\n    ) -> dict:\n        \"\"\"Create a PR, perform automated review, and merge.\n\n        The agent creates the PR, searches the diff for known\n        anti-patterns, then merges if clean.\n        \"\"\"\n        pr = self.create_pull_request(\n            owner=owner,\n            repo=repo,\n            title=title,\n            body=description,\n            head=head_branch,\n            base=\"main\",\n        )\n        pull_number = pr[\"number\"]\n\n        # Agent-driven code review: search for common issues\n        issues_found = []\n        for pattern in [\"eval(\", \"exec(\", \"password =\", \"secret =\"]:\n            hits = self.search_code(\n                query=pattern,\n                owner=owner,\n                repo=repo,\n            )\n            if hits.get(\"total_count\", 0) > 0:\n                issues_found.append(pattern)\n\n        if issues_found:\n            self.create_issue(\n                owner=owner,\n                repo=repo,\n                title=f\"Security review: patterns found in PR #{pull_number}\",\n                body=f\"Found: {', '.join(issues_found)}. Review before merge.\",\n                labels=[\"security\", \"automated-review\"],\n            )\n            return {\"status\": \"blocked\", \"pr\": pr, \"issues\": issues_found}\n\n        merged = self.merge_pull_request(\n            owner=owner,\n            repo=repo,\n            pull_number=pull_number,\n        )\n        return {\"status\": \"merged\", \"pr\": pr, \"merge\": merged}\n```\n\n### Pattern: Agent-Driven Code Review\n\nThe agent reads the diff, searches the codebase for related code, and judges whether the change is safe -- beyond what linters and CI catch.\n\n```python\nimport os\n\ndev = AgentDeveloper(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"dev-agent-01\",\n)\n\n# Agent reviews its own work before merging\nowner, repo = \"myorg\", \"newsletter-saas\"\n\n# 1. Check recent commits on the feature branch\ncommits = dev.list_commits(owner, repo, sha=\"feature\u002Fadd-billing\")\nprint(f\"Feature branch has {len(commits)} commits\")\n\n# 2. Search for any hardcoded secrets that slipped in\nsecrets_check = dev.search_code(\n    query=\"STRIPE_SECRET password API_KEY\",\n    owner=owner,\n    repo=repo,\n)\nif secrets_check.get(\"total_count\", 0) > 0:\n    dev.create_issue(\n        owner=owner,\n        repo=repo,\n        title=\"CRITICAL: Hardcoded secrets detected\",\n        body=\"Automated scan found potential secrets in codebase.\",\n        labels=[\"security\", \"P0\"],\n    )\n    raise RuntimeError(\"Secrets detected -- aborting merge\")\n\n# 3. If clean, create PR and merge\nresult = dev.review_and_merge(\n    owner=owner,\n    repo=repo,\n    head_branch=\"feature\u002Fadd-billing\",\n    title=\"Add Stripe billing integration\",\n    description=\"Adds subscription management with usage-based pricing.\",\n)\nprint(f\"PR status: {result['status']}\")\n```\n\n### Pattern: Automated Issue Tracking\n\nThe agent tracks its own work with issues, creating a paper trail for every feature and bug fix.\n\n```python\n# Agent creates a tracking issue before starting work\nissue = dev.create_issue(\n    owner=\"myorg\",\n    repo=\"newsletter-saas\",\n    title=\"Implement subscriber management API\",\n    body=(\n        \"## Requirements\\n\"\n        \"- POST \u002Fapi\u002Fsubscribers to add new subscriber\\n\"\n        \"- GET \u002Fapi\u002Fsubscribers to list all subscribers\\n\"\n        \"- DELETE \u002Fapi\u002Fsubscribers\u002F:id to unsubscribe\\n\"\n        \"- Store in Postgres with email uniqueness constraint\\n\\n\"\n        \"## Acceptance Criteria\\n\"\n        \"- All endpoints return JSON\\n\"\n        \"- Email validation on POST\\n\"\n        \"- Idempotent DELETE\\n\"\n    ),\n    labels=[\"feature\", \"api\", \"agent-created\"],\n)\nissue_number = issue[\"number\"]\n\n# Agent reads the issue back to confirm requirements\ndetails = dev.get_issue(\"myorg\", \"newsletter-saas\", issue_number)\nprint(f\"Working on: {details['title']}\")\n\n# ... agent implements the feature ...\n\n# Agent closes the issue by referencing it in the PR body\ndev.create_pull_request(\n    owner=\"myorg\",\n    repo=\"newsletter-saas\",\n    title=\"Implement subscriber management API\",\n    body=f\"Closes #{issue_number}\\n\\nAdds CRUD endpoints for subscribers.\",\n    head=\"feature\u002Fsubscriber-api\",\n)\n```\n\n**Cost for a typical development session:** 40-60 GitHub tool calls at $0.005 each = $0.20-$0.30. That covers repo creation, 10-15 file writes, 3-5 PR cycles, issue tracking, and code search.\n\n---\n\n## Chapter 3: The Data Layer: Agents Managing Postgres\n\n### The AgentDBA Class\n\nThis class wraps all 6 Postgres tools. The agent uses it to design schemas, run migrations, seed data, and validate data integrity.\n\n```python\nimport requests\nimport json\nfrom typing import Optional, List\n\n\nclass AgentDBA:\n    \"\"\"Postgres database administration client for the GreenHelix\n    A2A Commerce Gateway.\n\n    Wraps the 6 Postgres integration tools into a database management\n    interface for schema design, migrations, queries, and data validation.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Schema Inspection ---------------------------------------------\n\n    def get_schema(self) -> dict:\n        \"\"\"Inspect the full database schema.\"\"\"\n        return self._execute(\"get_schema\", {})\n\n    def list_tables(self) -> dict:\n        \"\"\"List all tables in the database.\"\"\"\n        return self._execute(\"list_tables\", {})\n\n    def describe_table(self, table_name: str) -> dict:\n        \"\"\"Get the structure of a specific table.\"\"\"\n        return self._execute(\"describe_table\", {\n            \"table_name\": table_name,\n        })\n\n    # -- Query Execution -----------------------------------------------\n\n    def query(self, sql: str, params: Optional[List] = None) -> dict:\n        \"\"\"Run a SELECT query. Read-only.\"\"\"\n        payload = {\"sql\": sql}\n        if params:\n            payload[\"params\"] = params\n        return self._execute(\"query\", payload)\n\n    def execute_query(\n        self,\n        sql: str,\n        params: Optional[List] = None,\n    ) -> dict:\n        \"\"\"Run any SQL statement (INSERT, UPDATE, DELETE, DDL).\"\"\"\n        payload = {\"sql\": sql}\n        if params:\n            payload[\"params\"] = params\n        return self._execute(\"execute_query\", payload)\n\n    # -- Migrations ----------------------------------------------------\n\n    def execute_migration(\n        self,\n        migration_sql: str,\n        version: str,\n        description: str,\n    ) -> dict:\n        \"\"\"Run a schema migration with version tracking.\"\"\"\n        return self._execute(\"execute_migration\", {\n            \"migration_sql\": migration_sql,\n            \"version\": version,\n            \"description\": description,\n        })\n\n    # -- High-Level Workflows ------------------------------------------\n\n    def schema_first_design(\n        self,\n        tables: dict,\n    ) -> List[dict]:\n        \"\"\"Design and create a full schema from a table specification.\n\n        Args:\n            tables: dict mapping table names to column definitions.\n                Example:\n                {\n                    \"subscribers\": [\n                        \"id SERIAL PRIMARY KEY\",\n                        \"email VARCHAR(255) UNIQUE NOT NULL\",\n                        \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n                    ]\n                }\n        \"\"\"\n        results = []\n        for table_name, columns in tables.items():\n            col_defs = \", \".join(columns)\n            sql = f\"CREATE TABLE IF NOT EXISTS {table_name} ({col_defs})\"\n            result = self.execute_query(sql)\n            results.append({\"table\": table_name, \"result\": result})\n        return results\n\n    def safe_migration_chain(\n        self,\n        migrations: List[dict],\n    ) -> List[dict]:\n        \"\"\"Execute a chain of migrations in order, stopping on failure.\n\n        Args:\n            migrations: list of dicts with keys:\n                - version: str (e.g., \"001\")\n                - description: str\n                - up: str (SQL to apply)\n        \"\"\"\n        results = []\n        for m in migrations:\n            try:\n                result = self.execute_migration(\n                    migration_sql=m[\"up\"],\n                    version=m[\"version\"],\n                    description=m[\"description\"],\n                )\n                results.append({\n                    \"version\": m[\"version\"],\n                    \"status\": \"applied\",\n                    \"result\": result,\n                })\n            except Exception as e:\n                results.append({\n                    \"version\": m[\"version\"],\n                    \"status\": \"failed\",\n                    \"error\": str(e),\n                })\n                break  # Stop chain on failure\n        return results\n\n    def validate_data(\n        self,\n        table: str,\n        checks: List[dict],\n    ) -> List[dict]:\n        \"\"\"Run validation checks against a table.\n\n        Args:\n            checks: list of dicts with keys:\n                - name: str (human-readable check name)\n                - sql: str (query that should return 0 rows if valid)\n        \"\"\"\n        results = []\n        for check in checks:\n            result = self.query(check[\"sql\"])\n            row_count = len(result.get(\"rows\", []))\n            results.append({\n                \"check\": check[\"name\"],\n                \"passed\": row_count == 0,\n                \"violations\": row_count,\n            })\n        return results\n```\n\n### Pattern: Schema-First Development\n\nThe agent designs the schema before writing application code, ensuring the data layer is correct before business logic is built on top.\n\n```python\nimport os\n\ndba = AgentDBA(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"dba-agent-01\",\n)\n\n# Agent designs the schema for a newsletter SaaS\nschema = dba.schema_first_design({\n    \"subscribers\": [\n        \"id SERIAL PRIMARY KEY\",\n        \"email VARCHAR(255) UNIQUE NOT NULL\",\n        \"name VARCHAR(255)\",\n        \"status VARCHAR(20) DEFAULT 'active' CHECK (status IN ('active', 'unsubscribed', 'bounced'))\",\n        \"stripe_customer_id VARCHAR(255)\",\n        \"subscribed_at TIMESTAMPTZ DEFAULT NOW()\",\n        \"unsubscribed_at TIMESTAMPTZ\",\n    ],\n    \"newsletters\": [\n        \"id SERIAL PRIMARY KEY\",\n        \"subject VARCHAR(500) NOT NULL\",\n        \"body TEXT NOT NULL\",\n        \"status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'scheduled', 'sent'))\",\n        \"scheduled_for TIMESTAMPTZ\",\n        \"sent_at TIMESTAMPTZ\",\n        \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n    ],\n    \"send_log\": [\n        \"id SERIAL PRIMARY KEY\",\n        \"newsletter_id INTEGER REFERENCES newsletters(id)\",\n        \"subscriber_id INTEGER REFERENCES subscribers(id)\",\n        \"status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed', 'bounced'))\",\n        \"sent_at TIMESTAMPTZ\",\n        \"error_message TEXT\",\n        \"UNIQUE(newsletter_id, subscriber_id)\",\n    ],\n})\n\n# Verify the schema was created correctly\ntables = dba.list_tables()\nprint(f\"Tables created: {[t['table_name'] for t in tables['rows']]}\")\n\nfor table in [\"subscribers\", \"newsletters\", \"send_log\"]:\n    desc = dba.describe_table(table)\n    print(f\"\\n{table}:\")\n    for col in desc[\"columns\"]:\n        print(f\"  {col['column_name']} {col['data_type']} {col.get('constraints', '')}\")\n```\n\n### Pattern: Safe Migration Chains\n\nVersioned migrations tracked in order. The chain stops on the first failure to prevent partial schema states.\n\n```python\n# Agent evolves the schema over time\nmigrations = dba.safe_migration_chain([\n    {\n        \"version\": \"002\",\n        \"description\": \"Add subscriber tags for segmentation\",\n        \"up\": \"\"\"\n            CREATE TABLE IF NOT EXISTS subscriber_tags (\n                id SERIAL PRIMARY KEY,\n                subscriber_id INTEGER REFERENCES subscribers(id) ON DELETE CASCADE,\n                tag VARCHAR(100) NOT NULL,\n                created_at TIMESTAMPTZ DEFAULT NOW(),\n                UNIQUE(subscriber_id, tag)\n            );\n            CREATE INDEX idx_subscriber_tags_tag ON subscriber_tags(tag);\n        \"\"\",\n    },\n    {\n        \"version\": \"003\",\n        \"description\": \"Add open tracking to send_log\",\n        \"up\": \"\"\"\n            ALTER TABLE send_log ADD COLUMN IF NOT EXISTS opened_at TIMESTAMPTZ;\n            ALTER TABLE send_log ADD COLUMN IF NOT EXISTS open_count INTEGER DEFAULT 0;\n            CREATE INDEX idx_send_log_opened ON send_log(opened_at)\n                WHERE opened_at IS NOT NULL;\n        \"\"\",\n    },\n    {\n        \"version\": \"004\",\n        \"description\": \"Add revenue tracking table\",\n        \"up\": \"\"\"\n            CREATE TABLE IF NOT EXISTS revenue_events (\n                id SERIAL PRIMARY KEY,\n                subscriber_id INTEGER REFERENCES subscribers(id),\n                stripe_payment_intent_id VARCHAR(255) UNIQUE,\n                amount_cents INTEGER NOT NULL,\n                currency VARCHAR(3) DEFAULT 'usd',\n                event_type VARCHAR(50) NOT NULL,\n                created_at TIMESTAMPTZ DEFAULT NOW()\n            );\n            CREATE INDEX idx_revenue_subscriber ON revenue_events(subscriber_id);\n            CREATE INDEX idx_revenue_created ON revenue_events(created_at);\n        \"\"\",\n    },\n])\n\nfor m in migrations:\n    status_marker = \"OK\" if m[\"status\"] == \"applied\" else \"FAIL\"\n    print(f\"  [{status_marker}] v{m['version']}: {m.get('error', 'applied')}\")\n```\n\n### Pattern: Data Validation Pipeline\n\nAfter seeding data or processing a batch, the agent runs validation checks to catch integrity issues early.\n\n```python\n# After importing subscriber data, validate\nvalidations = dba.validate_data(\n    table=\"subscribers\",\n    checks=[\n        {\n            \"name\": \"No duplicate emails\",\n            \"sql\": \"\"\"\n                SELECT email, COUNT(*) as cnt FROM subscribers\n                GROUP BY email HAVING COUNT(*) > 1\n            \"\"\",\n        },\n        {\n            \"name\": \"All active subscribers have email\",\n            \"sql\": \"\"\"\n                SELECT id FROM subscribers\n                WHERE status = 'active' AND (email IS NULL OR email = '')\n            \"\"\",\n        },\n        {\n            \"name\": \"No future subscription dates\",\n            \"sql\": \"\"\"\n                SELECT id FROM subscribers\n                WHERE subscribed_at > NOW() + INTERVAL '1 minute'\n            \"\"\",\n        },\n        {\n            \"name\": \"Unsubscribed have unsubscribed_at set\",\n            \"sql\": \"\"\"\n                SELECT id FROM subscribers\n                WHERE status = 'unsubscribed' AND unsubscribed_at IS NULL\n            \"\"\",\n        },\n    ],\n)\n\nall_passed = all(v[\"passed\"] for v in validations)\nfor v in validations:\n    marker = \"PASS\" if v[\"passed\"] else f\"FAIL ({v['violations']} violations)\"\n    print(f\"  [{marker}] {v['check']}\")\n\nif not all_passed:\n    raise DataValidationError(\"Validation failed -- see results above\")\n```\n\n**Cost for a typical database session:** 20-40 Postgres tool calls at $0.01 each = $0.20-$0.40. That covers schema creation, 3-5 migrations, data seeding, and validation.\n\n---\n\n## Chapter 4: Monetization: Agents Running Stripe\n\n### The AgentBilling Class\n\nThis class wraps all 13 Stripe tools. The agent uses it to create products, set pricing, generate checkout sessions, manage invoices, and track revenue.\n\n```python\nimport requests\nimport json\nfrom typing import Optional, List, Literal\n\n\nclass AgentBilling:\n    \"\"\"Stripe billing client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 13 Stripe integration tools into a monetization interface\n    for product creation, pricing, checkout, invoicing, and revenue tracking.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Customer Management -------------------------------------------\n\n    def create_customer(\n        self,\n        email: str,\n        name: Optional[str] = None,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Register a new Stripe customer.\"\"\"\n        payload = {\"email\": email}\n        if name:\n            payload[\"name\"] = name\n        if metadata:\n            payload[\"metadata\"] = metadata\n        return self._execute(\"create_customer\", payload)\n\n    def get_customer(self, customer_id: str) -> dict:\n        \"\"\"Retrieve customer details.\"\"\"\n        return self._execute(\"get_customer\", {\n            \"customer_id\": customer_id,\n        })\n\n    # -- Product & Pricing ---------------------------------------------\n\n    def create_product(\n        self,\n        name: str,\n        description: str,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Define a new product or service.\"\"\"\n        payload = {\"name\": name, \"description\": description}\n        if metadata:\n            payload[\"metadata\"] = metadata\n        return self._execute(\"create_product\", payload)\n\n    def get_product(self, product_id: str) -> dict:\n        \"\"\"Retrieve product details.\"\"\"\n        return self._execute(\"get_product\", {\n            \"product_id\": product_id,\n        })\n\n    def create_price(\n        self,\n        product_id: str,\n        unit_amount: int,\n        currency: str = \"usd\",\n        recurring: Optional[dict] = None,\n        usage_type: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Set pricing for a product.\n\n        Args:\n            unit_amount: Price in cents (e.g., 2900 = $29.00)\n            recurring: dict with \"interval\" key (\"month\", \"year\")\n            usage_type: \"metered\" for usage-based billing\n        \"\"\"\n        payload = {\n            \"product_id\": product_id,\n            \"unit_amount\": unit_amount,\n            \"currency\": currency,\n        }\n        if recurring:\n            payload[\"recurring\"] = recurring\n        if usage_type:\n            payload[\"usage_type\"] = usage_type\n        return self._execute(\"create_price\", payload)\n\n    # -- Checkout & Payments -------------------------------------------\n\n    def create_checkout_session(\n        self,\n        price_id: str,\n        success_url: str,\n        cancel_url: str,\n        mode: Literal[\"payment\", \"subscription\"] = \"subscription\",\n        customer_id: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Generate a Stripe checkout page.\"\"\"\n        payload = {\n            \"price_id\": price_id,\n            \"success_url\": success_url,\n            \"cancel_url\": cancel_url,\n            \"mode\": mode,\n        }\n        if customer_id:\n            payload[\"customer_id\"] = customer_id\n        return self._execute(\"create_checkout_session\", payload)\n\n    def get_checkout_session(self, session_id: str) -> dict:\n        \"\"\"Check the status of a checkout session.\"\"\"\n        return self._execute(\"get_checkout_session\", {\n            \"session_id\": session_id,\n        })\n\n    # -- Invoicing -----------------------------------------------------\n\n    def create_invoice(\n        self,\n        customer_id: str,\n        auto_advance: bool = True,\n        collection_method: str = \"charge_automatically\",\n    ) -> dict:\n        \"\"\"Generate an invoice for a customer.\"\"\"\n        return self._execute(\"create_invoice\", {\n            \"customer_id\": customer_id,\n            \"auto_advance\": auto_advance,\n            \"collection_method\": collection_method,\n        })\n\n    def get_invoice(self, invoice_id: str) -> dict:\n        \"\"\"Retrieve invoice details.\"\"\"\n        return self._execute(\"get_invoice\", {\n            \"invoice_id\": invoice_id,\n        })\n\n    def list_invoices(\n        self,\n        customer_id: Optional[str] = None,\n        status: Optional[str] = None,\n        limit: int = 10,\n    ) -> dict:\n        \"\"\"List invoices with optional filtering.\"\"\"\n        payload = {\"limit\": limit}\n        if customer_id:\n            payload[\"customer_id\"] = customer_id\n        if status:\n            payload[\"status\"] = status\n        return self._execute(\"list_invoices\", payload)\n\n    # -- Payment Intents -----------------------------------------------\n\n    def create_payment_intent(\n        self,\n        amount: int,\n        currency: str = \"usd\",\n        customer_id: Optional[str] = None,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Initiate a payment.\"\"\"\n        payload = {\"amount\": amount, \"currency\": currency}\n        if customer_id:\n            payload[\"customer_id\"] = customer_id\n        if metadata:\n            payload[\"metadata\"] = metadata\n        return self._execute(\"create_payment_intent\", payload)\n\n    def get_payment_intent(self, payment_intent_id: str) -> dict:\n        \"\"\"Check the status of a payment.\"\"\"\n        return self._execute(\"get_payment_intent\", {\n            \"payment_intent_id\": payment_intent_id,\n        })\n\n    # -- Revenue Tracking ----------------------------------------------\n\n    def get_balance(self) -> dict:\n        \"\"\"Check the Stripe account balance.\"\"\"\n        return self._execute(\"get_balance\", {})\n\n    # -- High-Level Workflows ------------------------------------------\n\n    def setup_subscription_product(\n        self,\n        name: str,\n        description: str,\n        monthly_price_cents: int,\n        yearly_price_cents: Optional[int] = None,\n    ) -> dict:\n        \"\"\"Create a product with monthly (and optional yearly) pricing.\n\n        Returns dict with product_id, monthly_price_id, yearly_price_id.\n        \"\"\"\n        product = self.create_product(name=name, description=description)\n        product_id = product[\"id\"]\n\n        monthly = self.create_price(\n            product_id=product_id,\n            unit_amount=monthly_price_cents,\n            recurring={\"interval\": \"month\"},\n        )\n\n        result = {\n            \"product_id\": product_id,\n            \"monthly_price_id\": monthly[\"id\"],\n        }\n\n        if yearly_price_cents:\n            yearly = self.create_price(\n                product_id=product_id,\n                unit_amount=yearly_price_cents,\n                recurring={\"interval\": \"year\"},\n            )\n            result[\"yearly_price_id\"] = yearly[\"id\"]\n\n        return result\n\n    def setup_usage_based_product(\n        self,\n        name: str,\n        description: str,\n        per_unit_cents: int,\n    ) -> dict:\n        \"\"\"Create a metered billing product.\n\n        Returns dict with product_id and price_id for usage reporting.\n        \"\"\"\n        product = self.create_product(name=name, description=description)\n        price = self.create_price(\n            product_id=product[\"id\"],\n            unit_amount=per_unit_cents,\n            usage_type=\"metered\",\n            recurring={\"interval\": \"month\"},\n        )\n        return {\n            \"product_id\": product[\"id\"],\n            \"price_id\": price[\"id\"],\n        }\n```\n\n### Pattern: Subscription Lifecycle\n\nComplete subscription setup with monthly\u002Fannual pricing and customer onboarding through checkout.\n\n```python\nimport os\n\nbilling = AgentBilling(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"billing-agent-01\",\n)\n\n# 1. Create the subscription product\nproduct = billing.setup_subscription_product(\n    name=\"NewsletterPro\",\n    description=\"Automated newsletter platform with analytics\",\n    monthly_price_cents=2900,       # $29\u002Fmonth\n    yearly_price_cents=29000,       # $290\u002Fyear (2 months free)\n)\nprint(f\"Product: {product['product_id']}\")\nprint(f\"Monthly: {product['monthly_price_id']}\")\nprint(f\"Yearly:  {product['yearly_price_id']}\")\n\n# 2. Onboard a customer\ncustomer = billing.create_customer(\n    email=\"alice@example.com\",\n    name=\"Alice Chen\",\n    metadata={\"source\": \"organic\", \"plan\": \"monthly\"},\n)\n\n# 3. Generate checkout session\nsession = billing.create_checkout_session(\n    price_id=product[\"monthly_price_id\"],\n    success_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fwelcome\",\n    cancel_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fpricing\",\n    mode=\"subscription\",\n    customer_id=customer[\"id\"],\n)\nprint(f\"Checkout URL: {session['url']}\")\n\n# 4. Agent polls for completion (in production, use webhooks)\nimport time\nfor _ in range(30):\n    status = billing.get_checkout_session(session[\"id\"])\n    if status[\"payment_status\"] == \"paid\":\n        print(\"Payment confirmed -- activating subscription\")\n        break\n    time.sleep(10)\n```\n\n### Pattern: Usage-Based Billing\n\nFor API-as-a-Service products, the agent sets up metered billing where customers pay per API call.\n\n```python\n# Create a metered product\napi_product = billing.setup_usage_based_product(\n    name=\"TranslationAPI\",\n    description=\"Neural machine translation API\",\n    per_unit_cents=1,  # $0.01 per translation\n)\n\n# Generate an invoice at month end\ninvoices = billing.list_invoices(\n    customer_id=\"cus_abc123\",\n    status=\"draft\",\n)\nif invoices.get(\"data\"):\n    invoice = billing.get_invoice(invoices[\"data\"][0][\"id\"])\n    print(f\"Draft invoice: ${invoice['amount_due'] \u002F 100:.2f}\")\n```\n\n### Pattern: Revenue Reconciliation\n\nPeriodic balance check against internal records.\n\n```python\n# Daily revenue check\nbalance = billing.get_balance()\navailable = sum(b[\"amount\"] for b in balance.get(\"available\", []))\npending = sum(b[\"amount\"] for b in balance.get(\"pending\", []))\n\nprint(f\"Available: ${available \u002F 100:.2f}\")\nprint(f\"Pending:   ${pending \u002F 100:.2f}\")\n\n# Cross-reference with recent invoices\nrecent = billing.list_invoices(status=\"paid\", limit=50)\ninvoice_total = sum(inv[\"amount_paid\"] for inv in recent.get(\"data\", []))\nprint(f\"Invoiced (last 50): ${invoice_total \u002F 100:.2f}\")\n```\n\n**Cost for a typical billing setup:** 15-25 Stripe tool calls at $0.01 each = $0.15-$0.25. That covers product creation, pricing, customer onboarding, checkout sessions, and balance checks.\n\n---\n\n## Chapter 5: The Full Factory: Orchestrating the Pipeline\n\n### The AgentSaaSFactory Class\n\nThis is the orchestrator. It combines `AgentDeveloper`, `AgentDBA`, and `AgentBilling` into a single pipeline that takes a product specification and produces a running micro-SaaS.\n\n```python\nimport os\nimport json\nimport time\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass SaaSSpec:\n    \"\"\"Specification for a micro-SaaS product.\"\"\"\n    name: str\n    description: str\n    repo_name: str\n    owner: str\n    monthly_price_cents: int\n    yearly_price_cents: Optional[int] = None\n    tables: dict = field(default_factory=dict)\n    migrations: list = field(default_factory=list)\n    app_files: dict = field(default_factory=dict)\n    success_url: str = \"\"\n    cancel_url: str = \"\"\n\n\nclass AgentSaaSFactory:\n    \"\"\"End-to-end SaaS factory combining GitHub, Postgres, and Stripe.\n\n    Takes a SaaSSpec and produces a running, revenue-generating\n    micro-SaaS with repository, database, and billing.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.developer = AgentDeveloper(\n            api_key=api_key,\n            agent_id=f\"{agent_id}-dev\",\n            base_url=base_url,\n        )\n        self.dba = AgentDBA(\n            api_key=api_key,\n            agent_id=f\"{agent_id}-dba\",\n            base_url=base_url,\n        )\n        self.billing = AgentBilling(\n            api_key=api_key,\n            agent_id=f\"{agent_id}-billing\",\n            base_url=base_url,\n        )\n        self.agent_id = agent_id\n        self.build_log = []\n\n    def _log(self, phase: str, message: str, data: Optional[dict] = None):\n        entry = {\n            \"timestamp\": time.time(),\n            \"phase\": phase,\n            \"message\": message,\n            \"data\": data,\n        }\n        self.build_log.append(entry)\n        print(f\"[{phase}] {message}\")\n\n    def build(self, spec: SaaSSpec) -> dict:\n        \"\"\"Execute the full SaaS build pipeline.\n\n        Phase 1: Create repository and scaffold code\n        Phase 2: Design schema and run migrations\n        Phase 3: Set up Stripe products and pricing\n        Phase 4: Deploy and verify\n\n        Returns a manifest with all created resource IDs.\n        \"\"\"\n        manifest = {\"spec\": spec.name, \"resources\": {}}\n\n        # Phase 1: Repository\n        self._log(\"repo\", f\"Creating repository {spec.repo_name}\")\n        repo = self.developer.create_repo(\n            name=spec.repo_name,\n            description=spec.description,\n        )\n        manifest[\"resources\"][\"repo\"] = repo\n        self._log(\"repo\", f\"Repository created: {repo.get('html_url')}\")\n\n        # Scaffold application files\n        if spec.app_files:\n            self._log(\"repo\", f\"Scaffolding {len(spec.app_files)} files\")\n            self.developer.scaffold_project(\n                owner=spec.owner,\n                repo=spec.repo_name,\n                files=spec.app_files,\n            )\n\n        # Phase 2: Database\n        if spec.tables:\n            self._log(\"db\", f\"Creating {len(spec.tables)} tables\")\n            schema_result = self.dba.schema_first_design(spec.tables)\n            manifest[\"resources\"][\"tables\"] = schema_result\n\n        if spec.migrations:\n            self._log(\"db\", f\"Running {len(spec.migrations)} migrations\")\n            migration_result = self.dba.safe_migration_chain(spec.migrations)\n            manifest[\"resources\"][\"migrations\"] = migration_result\n\n            # Verify schema integrity\n            tables = self.dba.list_tables()\n            self._log(\n                \"db\",\n                f\"Schema verified: {len(tables.get('rows', []))} tables\",\n            )\n\n        # Phase 3: Billing\n        self._log(\"billing\", \"Setting up Stripe product and pricing\")\n        product = self.billing.setup_subscription_product(\n            name=spec.name,\n            description=spec.description,\n            monthly_price_cents=spec.monthly_price_cents,\n            yearly_price_cents=spec.yearly_price_cents,\n        )\n        manifest[\"resources\"][\"stripe\"] = product\n\n        # Store billing config in the repo\n        billing_config = json.dumps(product, indent=2)\n        self.developer.create_or_update_file(\n            owner=spec.owner,\n            repo=spec.repo_name,\n            path=\"config\u002Fbilling.json\",\n            content=billing_config,\n            message=\"Add Stripe billing configuration\",\n        )\n        self._log(\"billing\", f\"Product created: {product['product_id']}\")\n\n        # Phase 4: Verification\n        self._log(\"verify\", \"Running post-build checks\")\n\n        # Verify repo exists and has correct files\n        repo_check = self.developer.get_repo(spec.owner, spec.repo_name)\n        assert repo_check.get(\"name\") == spec.repo_name\n\n        # Verify product exists in Stripe\n        product_check = self.billing.get_product(product[\"product_id\"])\n        assert product_check.get(\"active\") is True\n\n        # Verify all tables exist\n        if spec.tables:\n            for table_name in spec.tables:\n                desc = self.dba.describe_table(table_name)\n                assert len(desc.get(\"columns\", [])) > 0\n\n        self._log(\"verify\", \"All post-build checks passed\")\n\n        # Create a tracking issue\n        self.developer.create_issue(\n            owner=spec.owner,\n            repo=spec.repo_name,\n            title=f\"Build manifest: {spec.name}\",\n            body=(\n                f\"## Build Manifest\\n\\n\"\n                f\"```json\\n{json.dumps(manifest, indent=2, default=str)}\\n```\\n\\n\"\n                f\"Build completed at {time.strftime('%Y-%m-%d %H:%M:%S UTC')}\"\n            ),\n            labels=[\"build-manifest\", \"agent-created\"],\n        )\n\n        manifest[\"build_log\"] = self.build_log\n        return manifest\n```\n\n### End-to-End Walkthrough\n\nThe factory building a complete newsletter SaaS from a single specification:\n\n```python\nspec = SaaSSpec(\n    name=\"NewsletterPro\",\n    description=\"Automated newsletter platform with analytics and billing\",\n    repo_name=\"newsletter-pro\",\n    owner=\"myorg\",\n    monthly_price_cents=2900,\n    yearly_price_cents=29000,\n    tables={\n        \"subscribers\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"email VARCHAR(255) UNIQUE NOT NULL\",\n            \"name VARCHAR(255)\",\n            \"status VARCHAR(20) DEFAULT 'active'\",\n            \"stripe_customer_id VARCHAR(255)\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"newsletters\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"subject VARCHAR(500) NOT NULL\",\n            \"body TEXT NOT NULL\",\n            \"status VARCHAR(20) DEFAULT 'draft'\",\n            \"sent_at TIMESTAMPTZ\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    migrations=[\n        {\n            \"version\": \"001\",\n            \"description\": \"Initial schema\",\n            \"up\": \"SELECT 1\",  # Tables already created by schema_first_design\n        },\n    ],\n    app_files={\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI\napp = FastAPI(title=\"NewsletterPro\")\n\n@app.get(\"\u002Fhealth\")\ndef health():\n    return {\"status\": \"ok\"}\n''',\n        \"src\u002Fsubscribers.py\": '''from fastapi import APIRouter\nrouter = APIRouter(prefix=\"\u002Fapi\u002Fsubscribers\", tags=[\"subscribers\"])\n\n@router.post(\"\u002F\")\ndef add_subscriber(email: str, name: str = None):\n    \"\"\"Add a new subscriber.\"\"\"\n    pass  # Implementation uses AgentDBA.execute_query\n\n@router.get(\"\u002F\")\ndef list_subscribers(limit: int = 50, offset: int = 0):\n    \"\"\"List all active subscribers.\"\"\"\n    pass\n''',\n        \"Dockerfile\": '''FROM python:3.12-slim\nWORKDIR \u002Fapp\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY src\u002F src\u002F\nCMD [\"uvicorn\", \"src.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n''',\n        \".github\u002Fworkflows\u002Fci.yml\": '''name: CI\non: [push, pull_request]\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n      - run: pip install -r requirements.txt\n      - run: python -m pytest tests\u002F -x -q\n''',\n    },\n    success_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fwelcome\",\n    cancel_url=\"https:\u002F\u002Fnewsletter-pro.example.com\u002Fpricing\",\n)\n\n# Build the entire SaaS\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"factory-01\",\n)\n\nmanifest = factory.build(spec)\n\n# Output: complete manifest with all resource IDs\nprint(json.dumps(manifest[\"resources\"], indent=2, default=str))\n```\n\n### CrewAI Integration Pattern\n\nThe factory integrates as a CrewAI tool:\n\n```python\nfrom crewai import Agent, Task, Crew\nfrom crewai_tools import tool\n\n\n@tool(\"build_saas\")\ndef build_saas_tool(spec_json: str) -> str:\n    \"\"\"Build a complete micro-SaaS from a JSON specification.\n\n    The spec must include: name, description, repo_name, owner,\n    monthly_price_cents, tables (dict), and app_files (dict).\n    \"\"\"\n    spec_data = json.loads(spec_json)\n    spec = SaaSSpec(**spec_data)\n\n    factory = AgentSaaSFactory(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"crewai-factory\",\n    )\n    manifest = factory.build(spec)\n    return json.dumps(manifest[\"resources\"], indent=2, default=str)\n\n\nproduct_manager = Agent(\n    role=\"Product Manager\",\n    goal=\"Define micro-SaaS specifications based on market research\",\n    backstory=\"You identify gaps in the SaaS market and write specs.\",\n)\n\nbuilder = Agent(\n    role=\"SaaS Builder\",\n    goal=\"Build complete micro-SaaS products from specifications\",\n    backstory=\"You turn product specs into deployed, billing-enabled SaaS.\",\n    tools=[build_saas_tool],\n)\n\ndefine_task = Task(\n    description=\"Research the newsletter SaaS market and define a spec.\",\n    expected_output=\"JSON spec for a newsletter SaaS product.\",\n    agent=product_manager,\n)\n\nbuild_task = Task(\n    description=\"Build the SaaS from the spec provided by the PM.\",\n    expected_output=\"Build manifest with all resource IDs.\",\n    agent=builder,\n)\n\ncrew = Crew(\n    agents=[product_manager, builder],\n    tasks=[define_task, build_task],\n    verbose=True,\n)\n\nresult = crew.kickoff()\n```\n\n**Total cost for a full factory build:** ~75-125 tool calls across all three services = $0.55-$0.95. Under a dollar to build and deploy a micro-SaaS.\n\n---\n\n## Chapter 6: Dispute Resolution and Customer Support Automation\n\n### The AgentArbitrator Class\n\nThis class wraps all 5 dispute tools. The agent uses it to handle chargebacks, enforce SLAs, and resolve customer disputes without human intervention.\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional, Literal, List\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass EscalationRule:\n    \"\"\"Defines when a dispute should be escalated to a human.\"\"\"\n    max_amount_cents: int\n    max_auto_resolve_count: int\n    require_human_above: int  # amount in cents\n\n\nclass AgentArbitrator:\n    \"\"\"Dispute resolution client for the GreenHelix A2A Commerce Gateway.\n\n    Wraps the 5 dispute tools into an arbitration interface for\n    automated chargeback handling, SLA enforcement, and dispute analytics.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        escalation_rules: Optional[EscalationRule] = None,\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.escalation_rules = escalation_rules or EscalationRule(\n            max_amount_cents=10000,      # $100\n            max_auto_resolve_count=5,\n            require_human_above=50000,   # $500\n        )\n        self._auto_resolve_count = 0\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        if resp.status_code == 402:\n            raise BudgetExhaustedError(\n                f\"Agent {self.agent_id} budget exceeded: {resp.text}\"\n            )\n        resp.raise_for_status()\n        return resp.json()\n\n    # -- Core Dispute Operations ---------------------------------------\n\n    def open_dispute(\n        self,\n        transaction_id: str,\n        reason: str,\n        amount_cents: int,\n        evidence: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Open a new dispute against a transaction.\"\"\"\n        payload = {\n            \"transaction_id\": transaction_id,\n            \"reason\": reason,\n            \"amount_cents\": amount_cents,\n        }\n        if evidence:\n            payload[\"evidence\"] = evidence\n        return self._execute(\"open_dispute\", payload)\n\n    def respond_dispute(\n        self,\n        dispute_id: str,\n        response_text: str,\n        evidence: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Respond to a dispute with evidence.\"\"\"\n        payload = {\n            \"dispute_id\": dispute_id,\n            \"response\": response_text,\n        }\n        if evidence:\n            payload[\"evidence\"] = evidence\n        return self._execute(\"respond_dispute\", payload)\n\n    def resolve_dispute(\n        self,\n        dispute_id: str,\n        resolution: Literal[\"accepted\", \"rejected\", \"refunded\"],\n        notes: Optional[str] = None,\n    ) -> dict:\n        \"\"\"Resolve or close a dispute.\"\"\"\n        payload = {\n            \"dispute_id\": dispute_id,\n            \"resolution\": resolution,\n        }\n        if notes:\n            payload[\"notes\"] = notes\n        return self._execute(\"resolve_dispute\", payload)\n\n    def list_disputes(\n        self,\n        status: Optional[str] = None,\n        limit: int = 50,\n    ) -> dict:\n        \"\"\"List all disputes with optional status filter.\"\"\"\n        payload = {\"limit\": limit}\n        if status:\n            payload[\"status\"] = status\n        return self._execute(\"list_disputes\", payload)\n\n    def get_dispute(self, dispute_id: str) -> dict:\n        \"\"\"Get full details for a specific dispute.\"\"\"\n        return self._execute(\"get_dispute\", {\n            \"dispute_id\": dispute_id,\n        })\n\n    # -- Automated Chargeback Handling ---------------------------------\n\n    def handle_chargeback(\n        self,\n        dispute_id: str,\n        billing: \"AgentBilling\",\n        dba: \"AgentDBA\",\n    ) -> dict:\n        \"\"\"Automated chargeback response pipeline.\n\n        1. Fetch dispute details\n        2. Gather evidence from Stripe and database\n        3. Auto-respond if within escalation rules\n        4. Escalate to human if above thresholds\n        \"\"\"\n        dispute = self.get_dispute(dispute_id)\n        amount = dispute.get(\"amount_cents\", 0)\n\n        # Check escalation rules\n        if amount > self.escalation_rules.require_human_above:\n            return {\n                \"action\": \"escalated\",\n                \"reason\": f\"Amount ${amount\u002F100:.2f} exceeds auto-resolve threshold\",\n                \"dispute\": dispute,\n            }\n\n        if self._auto_resolve_count >= self.escalation_rules.max_auto_resolve_count:\n            return {\n                \"action\": \"escalated\",\n                \"reason\": \"Auto-resolve count limit reached\",\n                \"dispute\": dispute,\n            }\n\n        # Gather evidence from Stripe\n        tx_id = dispute.get(\"transaction_id\", \"\")\n        payment = billing.get_payment_intent(tx_id)\n\n        # Gather evidence from database\n        db_records = dba.query(\n            \"SELECT * FROM revenue_events WHERE stripe_payment_intent_id = $1\",\n            params=[tx_id],\n        )\n\n        evidence = {\n            \"payment_status\": payment.get(\"status\"),\n            \"payment_created\": payment.get(\"created\"),\n            \"delivery_confirmed\": len(db_records.get(\"rows\", [])) > 0,\n            \"customer_id\": payment.get(\"customer\"),\n        }\n\n        # Respond with evidence\n        self.respond_dispute(\n            dispute_id=dispute_id,\n            response_text=(\n                f\"Payment {tx_id} was completed successfully on \"\n                f\"{payment.get('created')}. Service delivery confirmed \"\n                f\"in application database. Customer ID: {payment.get('customer')}.\"\n            ),\n            evidence=evidence,\n        )\n\n        # Auto-resolve if amount is within threshold\n        if amount \u003C= self.escalation_rules.max_amount_cents:\n            resolution = self.resolve_dispute(\n                dispute_id=dispute_id,\n                resolution=\"rejected\",\n                notes=\"Auto-resolved: evidence confirms valid transaction\",\n            )\n            self._auto_resolve_count += 1\n            return {\"action\": \"auto_resolved\", \"resolution\": resolution}\n\n        return {\"action\": \"responded\", \"evidence_submitted\": True}\n\n    # -- SLA Enforcement -----------------------------------------------\n\n    def enforce_sla(\n        self,\n        sla_hours: int = 24,\n    ) -> List[dict]:\n        \"\"\"Check for open disputes approaching SLA deadline.\n\n        Returns list of disputes needing attention.\n        \"\"\"\n        open_disputes = self.list_disputes(status=\"open\")\n        urgent = []\n\n        for dispute in open_disputes.get(\"data\", []):\n            created = dispute.get(\"created_at\", 0)\n            elapsed_hours = (time.time() - created) \u002F 3600\n\n            if elapsed_hours > sla_hours * 0.75:  # 75% of SLA\n                urgent.append({\n                    \"dispute_id\": dispute[\"id\"],\n                    \"elapsed_hours\": round(elapsed_hours, 1),\n                    \"sla_hours\": sla_hours,\n                    \"remaining_hours\": round(sla_hours - elapsed_hours, 1),\n                    \"amount_cents\": dispute.get(\"amount_cents\", 0),\n                })\n\n        return urgent\n\n    # -- Dispute Analytics ---------------------------------------------\n\n    def get_dispute_analytics(self) -> dict:\n        \"\"\"Generate analytics across all disputes.\"\"\"\n        all_disputes = self.list_disputes(limit=200)\n        disputes = all_disputes.get(\"data\", [])\n\n        total = len(disputes)\n        if total == 0:\n            return {\"total\": 0, \"message\": \"No disputes found\"}\n\n        by_status = {}\n        total_amount = 0\n        for d in disputes:\n            status = d.get(\"status\", \"unknown\")\n            by_status[status] = by_status.get(status, 0) + 1\n            total_amount += d.get(\"amount_cents\", 0)\n\n        return {\n            \"total_disputes\": total,\n            \"by_status\": by_status,\n            \"total_amount_cents\": total_amount,\n            \"average_amount_cents\": total_amount \u002F\u002F total,\n            \"win_rate\": by_status.get(\"rejected\", 0) \u002F max(total, 1),\n        }\n```\n\n### Pattern: Automated Chargeback Pipeline\n\nThe agent gathers evidence from Stripe and the database, then responds or escalates based on configurable rules.\n\n```python\nimport os\n\narbitrator = AgentArbitrator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"arbitrator-01\",\n    escalation_rules=EscalationRule(\n        max_amount_cents=5000,       # Auto-resolve up to $50\n        max_auto_resolve_count=10,   # Max 10 auto-resolves per session\n        require_human_above=25000,   # Always escalate above $250\n    ),\n)\n\nbilling = AgentBilling(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"billing-agent-01\",\n)\ndba = AgentDBA(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"dba-agent-01\",\n)\n\n# Process all open disputes\nopen_disputes = arbitrator.list_disputes(status=\"open\")\nfor dispute in open_disputes.get(\"data\", []):\n    result = arbitrator.handle_chargeback(\n        dispute_id=dispute[\"id\"],\n        billing=billing,\n        dba=dba,\n    )\n    print(f\"Dispute {dispute['id']}: {result['action']}\")\n```\n\n### Pattern: SLA Enforcement Loop\n\nRun hourly to catch disputes approaching their SLA deadline.\n\n```python\n# Hourly SLA check\nurgent = arbitrator.enforce_sla(sla_hours=24)\nif urgent:\n    print(f\"WARNING: {len(urgent)} disputes approaching SLA deadline\")\n    for d in urgent:\n        print(\n            f\"  Dispute {d['dispute_id']}: \"\n            f\"{d['remaining_hours']}h remaining, \"\n            f\"${d['amount_cents']\u002F100:.2f}\"\n        )\n\n# Daily analytics\nanalytics = arbitrator.get_dispute_analytics()\nprint(f\"\\nDispute Analytics:\")\nprint(f\"  Total: {analytics['total_disputes']}\")\nprint(f\"  By status: {analytics['by_status']}\")\nprint(f\"  Win rate: {analytics.get('win_rate', 0):.0%}\")\nprint(f\"  Avg amount: ${analytics.get('average_amount_cents', 0)\u002F100:.2f}\")\n```\n\n---\n\n## Chapter 7: Security, Cost Governance, and Guardrails\n\nAutonomous agents with access to repositories, databases, and payment systems need hard constraints. These guardrails prevent an agent from draining your Stripe account, dropping production tables, or committing secrets.\n\n### Budget Caps for Pro-Tier Tools\n\nAn agent in a retry loop burns credits fast. Set explicit per-session budget caps.\n\n```python\nclass BudgetExhaustedError(Exception):\n    \"\"\"Raised when an agent exceeds its budget cap.\"\"\"\n    pass\n\n\nclass BudgetGovernor:\n    \"\"\"Tracks tool call spending and enforces hard limits.\"\"\"\n\n    def __init__(self, daily_limit_usd: float = 5.00):\n        self.daily_limit = daily_limit_usd\n        self.spent_today = 0.0\n        self.call_log = []\n        self.cost_map = {\n            \"github\": 0.005,\n            \"stripe\": 0.01,\n            \"postgres\": 0.01,\n            \"dispute\": 0.01,\n        }\n\n    def check_and_record(self, service: str):\n        \"\"\"Check budget before a tool call; raise if exceeded.\"\"\"\n        cost = self.cost_map.get(service, 0.01)\n        if self.spent_today + cost > self.daily_limit:\n            raise BudgetExhaustedError(\n                f\"Daily limit ${self.daily_limit:.2f} would be exceeded. \"\n                f\"Spent today: ${self.spent_today:.2f}\"\n            )\n        self.spent_today += cost\n        self.call_log.append({\n            \"service\": service,\n            \"cost\": cost,\n            \"running_total\": self.spent_today,\n            \"timestamp\": time.time(),\n        })\n\n    def get_remaining(self) -> float:\n        return self.daily_limit - self.spent_today\n\n    def get_summary(self) -> dict:\n        by_service = {}\n        for entry in self.call_log:\n            svc = entry[\"service\"]\n            by_service[svc] = by_service.get(svc, 0) + entry[\"cost\"]\n        return {\n            \"spent_today\": round(self.spent_today, 4),\n            \"daily_limit\": self.daily_limit,\n            \"remaining\": round(self.get_remaining(), 4),\n            \"by_service\": by_service,\n            \"total_calls\": len(self.call_log),\n        }\n\n\n# Usage: wrap the factory with budget governance\ngovernor = BudgetGovernor(daily_limit_usd=5.00)\n\n# Before every tool call in _execute:\ngovernor.check_and_record(\"github\")   # raises if over budget\ngovernor.check_and_record(\"postgres\") # raises if over budget\n\n# Periodic check\nsummary = governor.get_summary()\nprint(f\"Budget: ${summary['remaining']:.2f} remaining of ${summary['daily_limit']:.2f}\")\n```\n\n### SQL Injection Prevention\n\nThe agent generates SQL dynamically. Every query with user-derived data must use parameterized queries. The `AgentDBA` class enforces this through its `params` argument, but defense-in-depth adds a second check.\n\n```python\nimport re\n\nDANGEROUS_PATTERNS = [\n    r\";\\s*DROP\\s\",\n    r\";\\s*DELETE\\s+FROM\\s\",\n    r\";\\s*TRUNCATE\\s\",\n    r\";\\s*ALTER\\s+TABLE\\s.*DROP\\s\",\n    r\"--\\s\",\n    r\"\u002F\\*\",\n    r\"'\\s*OR\\s+'1'\\s*=\\s*'1\",\n    r\"UNION\\s+SELECT\",\n]\n\n\ndef validate_sql(sql: str) -> bool:\n    \"\"\"Reject SQL containing injection patterns.\n\n    This is a defense-in-depth measure. The primary protection is\n    parameterized queries in AgentDBA.query() and .execute_query().\n    \"\"\"\n    for pattern in DANGEROUS_PATTERNS:\n        if re.search(pattern, sql, re.IGNORECASE):\n            raise SQLInjectionError(\n                f\"SQL rejected: matches pattern '{pattern}'\"\n            )\n    return True\n\n\nclass SQLInjectionError(Exception):\n    pass\n\n\n# Integrate into AgentDBA._execute as a pre-check\n# validate_sql(input_data.get(\"sql\", \"\"))\n```\n\n### Idempotency Keys\n\nStripe operations must be idempotent. If the agent retries a checkout session creation due to a timeout, it must not create a duplicate. Use client-generated idempotency keys.\n\n```python\nimport hashlib\n\n\ndef make_idempotency_key(agent_id: str, operation: str, params: dict) -> str:\n    \"\"\"Generate a deterministic idempotency key from operation parameters.\n\n    Same agent + same operation + same params = same key.\n    Prevents duplicate Stripe objects on retry.\n    \"\"\"\n    payload = json.dumps(\n        {\"agent\": agent_id, \"op\": operation, \"params\": params},\n        sort_keys=True,\n    )\n    return hashlib.sha256(payload.encode()).hexdigest()[:32]\n\n\n# Usage in AgentBilling\nkey = make_idempotency_key(\n    agent_id=\"billing-agent-01\",\n    operation=\"create_checkout_session\",\n    params={\"price_id\": \"price_abc\", \"customer_id\": \"cus_123\"},\n)\n# Pass as header: Idempotency-Key: {key}\n```\n\n### Branch Protection\n\nThe agent should never push directly to `main`. All changes go through feature branches and pull requests.\n\n```python\nclass BranchProtectionPolicy:\n    \"\"\"Enforces branch protection rules for agent commits.\"\"\"\n\n    PROTECTED_BRANCHES = {\"main\", \"master\", \"production\", \"release\"}\n\n    @classmethod\n    def validate_branch(cls, branch: str) -> str:\n        \"\"\"Ensure the agent is not writing to a protected branch.\"\"\"\n        if branch in cls.PROTECTED_BRANCHES:\n            raise BranchProtectionError(\n                f\"Direct writes to '{branch}' are prohibited. \"\n                f\"Use a feature branch and create a pull request.\"\n            )\n        return branch\n\n    @classmethod\n    def generate_feature_branch(cls, prefix: str, description: str) -> str:\n        \"\"\"Generate a safe feature branch name.\"\"\"\n        slug = re.sub(r\"[^a-z0-9]+\", \"-\", description.lower()).strip(\"-\")[:40]\n        return f\"{prefix}\u002F{slug}\"\n\n\nclass BranchProtectionError(Exception):\n    pass\n\n\n# Before any create_or_update_file call:\nbranch = BranchProtectionPolicy.generate_feature_branch(\n    prefix=\"agent\",\n    description=\"add billing integration\",\n)\n# Result: \"agent\u002Fadd-billing-integration\"\nBranchProtectionPolicy.validate_branch(branch)  # passes\nBranchProtectionPolicy.validate_branch(\"main\")  # raises\n```\n\n### Kill Switch Pattern\n\nEvery long-running agent process needs a kill switch. If the agent enters a bad state, you need to stop it immediately.\n\n```python\nimport os\nimport signal\n\n\nclass KillSwitch:\n    \"\"\"Emergency stop for agent processes.\n\n    Check this before every tool call. If the kill file exists,\n    the agent stops immediately.\n    \"\"\"\n\n    def __init__(self, kill_file: str = \"\u002Ftmp\u002Fagent_kill_switch\"):\n        self.kill_file = kill_file\n\n    def check(self):\n        \"\"\"Raise if kill switch is engaged.\"\"\"\n        if os.path.exists(self.kill_file):\n            raise AgentKilledError(\n                f\"Kill switch engaged: {self.kill_file} exists. \"\n                f\"Remove the file to resume.\"\n            )\n\n    def engage(self, reason: str = \"manual\"):\n        \"\"\"Engage the kill switch.\"\"\"\n        with open(self.kill_file, \"w\") as f:\n            f.write(f\"killed at {time.time()}: {reason}\\n\")\n\n    def disengage(self):\n        \"\"\"Remove the kill switch.\"\"\"\n        if os.path.exists(self.kill_file):\n            os.remove(self.kill_file)\n\n\nclass AgentKilledError(Exception):\n    pass\n\n\n# Integrate into the factory's _execute path:\nkill_switch = KillSwitch()\n\n# Before every tool call:\nkill_switch.check()  # raises AgentKilledError if kill file exists\n\n# From a human operator's terminal:\n# touch \u002Ftmp\u002Fagent_kill_switch   \u003C-- stops the agent immediately\n# rm \u002Ftmp\u002Fagent_kill_switch      \u003C-- allows it to resume\n```\n\n---\n\n## Chapter 8: Production Recipes\n\n### Recipe 1: Newsletter SaaS\n\n**What it builds:** Subscriber management with email sending, open tracking, and $29\u002Fmonth subscription billing.\n\n**Tools used:** All 34\n\n```python\nimport os\n\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"newsletter-factory\",\n)\n\nnewsletter_spec = SaaSSpec(\n    name=\"NewsletterPro\",\n    description=\"Newsletter platform with subscriber management and analytics\",\n    repo_name=\"newsletter-pro\",\n    owner=\"myorg\",\n    monthly_price_cents=2900,\n    yearly_price_cents=29000,\n    tables={\n        \"subscribers\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"email VARCHAR(255) UNIQUE NOT NULL\",\n            \"name VARCHAR(255)\",\n            \"status VARCHAR(20) DEFAULT 'active'\",\n            \"stripe_customer_id VARCHAR(255)\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"newsletters\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"subject VARCHAR(500) NOT NULL\",\n            \"body TEXT NOT NULL\",\n            \"status VARCHAR(20) DEFAULT 'draft'\",\n            \"sent_at TIMESTAMPTZ\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"send_log\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"newsletter_id INTEGER REFERENCES newsletters(id)\",\n            \"subscriber_id INTEGER REFERENCES subscribers(id)\",\n            \"status VARCHAR(20) DEFAULT 'pending'\",\n            \"opened_at TIMESTAMPTZ\",\n            \"open_count INTEGER DEFAULT 0\",\n            \"sent_at TIMESTAMPTZ\",\n            \"UNIQUE(newsletter_id, subscriber_id)\",\n        ],\n        \"revenue_events\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"subscriber_id INTEGER REFERENCES subscribers(id)\",\n            \"stripe_payment_intent_id VARCHAR(255) UNIQUE\",\n            \"amount_cents INTEGER NOT NULL\",\n            \"event_type VARCHAR(50) NOT NULL\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    app_files={\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI\nfrom src.subscribers import router as sub_router\nfrom src.newsletters import router as news_router\n\napp = FastAPI(title=\"NewsletterPro\", version=\"1.0.0\")\napp.include_router(sub_router)\napp.include_router(news_router)\n\n@app.get(\"\u002Fhealth\")\ndef health():\n    return {\"status\": \"ok\"}\n''',\n        \"src\u002Fsubscribers.py\": '''from fastapi import APIRouter, HTTPException\nrouter = APIRouter(prefix=\"\u002Fapi\u002Fsubscribers\", tags=[\"subscribers\"])\n\n@router.post(\"\u002F\")\ndef create(email: str, name: str = None):\n    return {\"status\": \"created\"}\n\n@router.get(\"\u002F\")\ndef list_all(limit: int = 50, offset: int = 0):\n    return {\"subscribers\": [], \"total\": 0}\n\n@router.delete(\"\u002F{subscriber_id}\")\ndef unsubscribe(subscriber_id: int):\n    return {\"status\": \"unsubscribed\"}\n''',\n        \"src\u002Fnewsletters.py\": '''from fastapi import APIRouter\nrouter = APIRouter(prefix=\"\u002Fapi\u002Fnewsletters\", tags=[\"newsletters\"])\n\n@router.post(\"\u002F\")\ndef create(subject: str, body: str):\n    return {\"status\": \"draft_created\"}\n\n@router.post(\"\u002F{newsletter_id}\u002Fsend\")\ndef send(newsletter_id: int):\n    return {\"status\": \"sending\"}\n''',\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n        \"Dockerfile\": '''FROM python:3.12-slim\nWORKDIR \u002Fapp\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nCOPY src\u002F src\u002F\nCMD [\"uvicorn\", \"src.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n''',\n    },\n)\n\nmanifest = factory.build(newsletter_spec)\n\n# Set up dispute handling for the newsletter SaaS\narbitrator = AgentArbitrator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"newsletter-arbitrator\",\n)\n```\n\n**Cost projection:**\n\n| Phase | Tool Calls | Cost |\n|-------|-----------|------|\n| Repository + scaffolding | 12 GitHub | $0.06 |\n| Schema + migrations | 10 Postgres | $0.10 |\n| Billing setup | 6 Stripe | $0.06 |\n| Verification | 8 mixed | $0.06 |\n| **Total build** | **36** | **$0.28** |\n| Daily operation | 5-10 | $0.05-$0.10 |\n| Monthly operation | 150-300 | $1.50-$3.00 |\n\nAt $29\u002Fmonth per customer, you break even at 1 customer. At 10 customers ($290\u002Fmonth), the agent operation cost is 1% of revenue.\n\n### Recipe 2: API-as-a-Service\n\n**What it builds:** Metered API with per-request billing, versioned releases, and usage tracking.\n\n**Tools used:** GitHub (10), Postgres (6), Stripe (13)\n\n```python\napi_spec = SaaSSpec(\n    name=\"TranslateAPI\",\n    description=\"Neural machine translation API with per-request billing\",\n    repo_name=\"translate-api\",\n    owner=\"myorg\",\n    monthly_price_cents=0,  # Usage-based, no base fee\n    tables={\n        \"api_keys\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"key_hash VARCHAR(64) UNIQUE NOT NULL\",\n            \"customer_id VARCHAR(255) NOT NULL\",\n            \"name VARCHAR(255)\",\n            \"rate_limit INTEGER DEFAULT 100\",\n            \"active BOOLEAN DEFAULT true\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"usage_log\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"api_key_id INTEGER REFERENCES api_keys(id)\",\n            \"endpoint VARCHAR(255) NOT NULL\",\n            \"request_chars INTEGER NOT NULL\",\n            \"response_chars INTEGER NOT NULL\",\n            \"latency_ms INTEGER\",\n            \"status_code INTEGER\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"releases\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"version VARCHAR(20) NOT NULL UNIQUE\",\n            \"changelog TEXT\",\n            \"model_version VARCHAR(50)\",\n            \"released_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    app_files={\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI, Header, HTTPException\napp = FastAPI(title=\"TranslateAPI\", version=\"2.0.0\")\n\n@app.post(\"\u002Fv2\u002Ftranslate\")\ndef translate(text: str, target_lang: str, x_api_key: str = Header()):\n    # Verify API key, log usage, translate, return\n    return {\"translated\": text, \"lang\": target_lang}\n\n@app.get(\"\u002Fv2\u002Fusage\")\ndef get_usage(x_api_key: str = Header()):\n    return {\"requests_this_month\": 0, \"cost_cents\": 0}\n''',\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n    },\n)\n\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"api-factory\",\n)\nmanifest = factory.build(api_spec)\n\n# Set up metered billing separately (usage-based, not subscription)\nbilling = AgentBilling(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"api-billing\",\n)\n\nmetered_product = billing.setup_usage_based_product(\n    name=\"TranslateAPI Usage\",\n    description=\"Per-request translation API billing\",\n    per_unit_cents=1,  # $0.01 per request\n)\n\n# Agent manages versioned releases through GitHub\ndev = AgentDeveloper(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"api-dev\",\n)\n\n# Tag a release\ncommits = dev.list_commits(\"myorg\", \"translate-api\", per_page=1)\nlatest_sha = commits[0][\"sha\"] if commits else \"HEAD\"\n\ndev.create_or_update_file(\n    owner=\"myorg\",\n    repo=\"translate-api\",\n    path=\"CHANGELOG.md\",\n    content=\"# v2.1.0\\n- Added batch translation endpoint\\n- Improved latency by 40%\\n\",\n    message=\"Release v2.1.0\",\n)\n```\n\n**Cost projection:**\n\n| Phase | Tool Calls | Cost |\n|-------|-----------|------|\n| Build | 30 | $0.22 |\n| Monthly operation | 200-500 | $2.00-$5.00 |\n| Monthly revenue (1k requests\u002Fday) | - | $300.00 |\n| Margin | - | **98%+** |\n\n### Recipe 3: Agent Marketplace Operator\n\n**What it builds:** Marketplace where AI agents list and sell services. The operator handles listings, payments, and disputes.\n\n**Tools used:** All 34\n\n```python\nmarketplace_spec = SaaSSpec(\n    name=\"AgentBazaar\",\n    description=\"Marketplace for AI agent services with escrow and dispute resolution\",\n    repo_name=\"agent-bazaar\",\n    owner=\"myorg\",\n    monthly_price_cents=4900,  # $49\u002Fmonth for marketplace access\n    yearly_price_cents=49000,  # $490\u002Fyear\n    tables={\n        \"sellers\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"agent_id VARCHAR(255) UNIQUE NOT NULL\",\n            \"name VARCHAR(255) NOT NULL\",\n            \"stripe_account_id VARCHAR(255)\",\n            \"trust_score NUMERIC(5,2) DEFAULT 0.50\",\n            \"verified BOOLEAN DEFAULT false\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"listings\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"seller_id INTEGER REFERENCES sellers(id)\",\n            \"title VARCHAR(500) NOT NULL\",\n            \"description TEXT NOT NULL\",\n            \"price_cents INTEGER NOT NULL\",\n            \"category VARCHAR(100)\",\n            \"active BOOLEAN DEFAULT true\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n        \"orders\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"listing_id INTEGER REFERENCES listings(id)\",\n            \"buyer_agent_id VARCHAR(255) NOT NULL\",\n            \"seller_id INTEGER REFERENCES sellers(id)\",\n            \"status VARCHAR(30) DEFAULT 'pending'\",\n            \"stripe_payment_intent_id VARCHAR(255)\",\n            \"amount_cents INTEGER NOT NULL\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n            \"completed_at TIMESTAMPTZ\",\n        ],\n        \"reviews\": [\n            \"id SERIAL PRIMARY KEY\",\n            \"order_id INTEGER REFERENCES orders(id) UNIQUE\",\n            \"reviewer_agent_id VARCHAR(255) NOT NULL\",\n            \"rating INTEGER CHECK (rating BETWEEN 1 AND 5)\",\n            \"comment TEXT\",\n            \"created_at TIMESTAMPTZ DEFAULT NOW()\",\n        ],\n    },\n    app_files={\n        \"src\u002Fmain.py\": '''from fastapi import FastAPI\napp = FastAPI(title=\"AgentBazaar\", version=\"1.0.0\")\n\n@app.get(\"\u002Fhealth\")\ndef health():\n    return {\"status\": \"ok\"}\n\n@app.get(\"\u002Fapi\u002Flistings\")\ndef list_services(category: str = None, limit: int = 20):\n    return {\"listings\": [], \"total\": 0}\n\n@app.post(\"\u002Fapi\u002Forders\")\ndef create_order(listing_id: int, buyer_agent_id: str):\n    return {\"status\": \"pending\", \"order_id\": None}\n''',\n        \"requirements.txt\": \"fastapi>=0.100.0\\nuvicorn>=0.23.0\\npsycopg2-binary>=2.9.0\\nstripe>=7.0.0\\n\",\n    },\n)\n\nfactory = AgentSaaSFactory(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"marketplace-factory\",\n)\nmanifest = factory.build(marketplace_spec)\n\n# The marketplace operator handles disputes between buyer and seller agents\narbitrator = AgentArbitrator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"marketplace-arbitrator\",\n    escalation_rules=EscalationRule(\n        max_amount_cents=10000,       # Auto-resolve up to $100\n        max_auto_resolve_count=20,    # Higher limit for marketplace volume\n        require_human_above=50000,    # Escalate above $500\n    ),\n)\n\n# Trust-weighted auto-resolution: use seller trust score to decide\ndba = AgentDBA(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    agent_id=\"marketplace-dba\",\n)\n\ndef trust_weighted_resolve(dispute_id: str):\n    \"\"\"Resolve disputes using seller trust scores.\"\"\"\n    dispute = arbitrator.get_dispute(dispute_id)\n    tx_id = dispute.get(\"transaction_id\")\n\n    # Look up the order and seller trust score\n    order = dba.query(\n        \"SELECT o.*, s.trust_score FROM orders o \"\n        \"JOIN sellers s ON o.seller_id = s.id \"\n        \"WHERE o.stripe_payment_intent_id = $1\",\n        params=[tx_id],\n    )\n\n    if not order.get(\"rows\"):\n        return arbitrator.resolve_dispute(\n            dispute_id, \"accepted\", \"Order not found -- refunding buyer\"\n        )\n\n    seller_trust = float(order[\"rows\"][0].get(\"trust_score\", 0.5))\n\n    if seller_trust >= 0.90:\n        # High-trust seller: reject dispute (favor seller)\n        return arbitrator.resolve_dispute(\n            dispute_id, \"rejected\",\n            f\"Seller trust score {seller_trust:.2f} -- favoring seller\",\n        )\n    elif seller_trust \u003C 0.30:\n        # Low-trust seller: accept dispute (favor buyer)\n        return arbitrator.resolve_dispute(\n            dispute_id, \"refunded\",\n            f\"Seller trust score {seller_trust:.2f} -- refunding buyer\",\n        )\n    else:\n        # Mid-range: submit evidence and let it pend for human review\n        arbitrator.respond_dispute(\n            dispute_id,\n            f\"Seller trust score: {seller_trust:.2f}. Requires human review.\",\n        )\n        return {\"action\": \"pending_review\"}\n```\n\n**Cost projection:**\n\n| Phase | Tool Calls | Cost |\n|-------|-----------|------|\n| Build | 45 | $0.35 |\n| Monthly operation (100 orders\u002Fday) | 1,500 | $12.00 |\n| Monthly revenue (50 sellers at $49) | - | $2,450.00 |\n| Dispute handling (5% dispute rate) | 300 | $3.00 |\n| **Monthly margin** | - | **99%+** |\n\n---\n\n## Chapter 9: What's Next\n\n### Cross-References to the Product Library\n\nThis guide covers the build phase. The other guides in the series cover operational depth:\n\n- **P1: Agent-to-Agent Commerce** -- Escrow patterns for when your factory agents outsource subtasks to specialist agents.\n- **P2: Agent FinOps Playbook** -- Budget enforcement and spend analytics for agent fleets. Essential beyond three agents.\n- **P3: Verified Bot Reputation** -- Cryptographic proof of your SaaS agent's track record for marketplace trust.\n- **P4: Trading Bot Audit Trail** -- Immutable logging for any agent handling money. Compliance-grade Stripe records.\n- **P5: Agent Trust Verification** -- Trust scoring algorithms for Recipe 3's trust-weighted dispute resolution.\n- **P6: Strategy Marketplace Playbook** -- Marketplace operations at scale: moderation, fraud detection, multi-sided economics.\n\n### Agent-to-Agent SaaS\n\nThe factory pattern in this guide builds SaaS for human customers. The next evolution: SaaS built by agents, for agents, purchased by agents. Agent A builds a translation API (Recipe 2). Agent B discovers it on the GreenHelix marketplace. Agent C evaluates the seller's trust score. The buyer creates an escrow, the seller performs the work, the escrow releases on delivery confirmation. No human involved at any step. The 34 tools here cover the supply side. The full 128-tool GreenHelix catalog covers the demand side.\n\n### Portfolio Management\n\nOnce proven with a single product, an orchestrator agent runs multiple factories in parallel. It tracks revenue per product, reallocates budget from underperformers, and shuts down products that miss profitability thresholds.\n\n```python\nclass SaaSPortfolio:\n    \"\"\"Manage a portfolio of agent-built micro-SaaS products.\"\"\"\n\n    def __init__(self, factory: AgentSaaSFactory):\n        self.factory = factory\n        self.products = {}\n\n    def launch(self, spec: SaaSSpec) -> dict:\n        manifest = self.factory.build(spec)\n        self.products[spec.name] = {\n            \"manifest\": manifest,\n            \"launched_at\": time.time(),\n            \"revenue_cents\": 0,\n            \"cost_cents\": 0,\n        }\n        return manifest\n\n    def evaluate(self, days_threshold: int = 30) -> List[dict]:\n        \"\"\"Evaluate all products and recommend actions.\"\"\"\n        recommendations = []\n        for name, data in self.products.items():\n            age_days = (time.time() - data[\"launched_at\"]) \u002F 86400\n            if age_days \u003C days_threshold:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"observe\",\n                    \"reason\": f\"Only {age_days:.0f} days old\",\n                })\n            elif data[\"revenue_cents\"] == 0:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"sunset\",\n                    \"reason\": \"Zero revenue after threshold\",\n                })\n            elif data[\"revenue_cents\"] > data[\"cost_cents\"] * 3:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"scale\",\n                    \"reason\": \"3x+ ROI -- increase investment\",\n                })\n            else:\n                recommendations.append({\n                    \"product\": name,\n                    \"action\": \"optimize\",\n                    \"reason\": \"Positive but below 3x threshold\",\n                })\n        return recommendations\n```\n\nThe agent economy is here. Stripe handles the demand side. The Agent SaaS Factory handles the supply side. GitHub for code, Postgres for data, Stripe for money, Disputes for trust -- 34 tools, under a dollar per build, pennies per day to operate. Build one. Ship it. Watch it earn. Then build the next one.\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"metadata":37,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32,33],"saas","github","stripe","postgres","disputes","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":38},{"requires":39,"primaryEnv":41},{"env":40},[41,42],"GREENHELIX_API_KEY","STRIPE_API_KEY",0,[41,42],"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-saas-factory","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-saas-factory",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-saas-factory",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-saas-factory","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-saas-factory\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]