Skip to content
Back to search

Autonomous-AI-Company-OS

Autonomous AI Company OS

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 21 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/lazynextai/Autonomous-AI-Company-OS with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/lazynextai/Autonomous-AI-Company-OS'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/lazynextai--autonomous-ai-company-os/badge.svg)](/listings/lazynextai--autonomous-ai-company-os)

HTML

<a href="/listings/lazynextai--autonomous-ai-company-os"><img src="/api/listings/lazynextai--autonomous-ai-company-os/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Prerequisites

- **Operating System**: macOS or Linux - **Python**: 3.11 or 3.12 (3.13+ untested with sentence-transformers) - **Node.js**: 18 or higher (for worker + dashboard) - **Cloudflare account**: For D1, KV, Vectorize, and Workers - **Git**: For version control

Required Services

1. **Cloudflare Account**: [cloudflare.com](https://cloudflare.com) - API token (`CF_API_TOKEN`) with edit perms for Workers Scripts, Workers KV, D1, Vectorize - Account ID (`CF_ACCOUNT_ID`) from the dashboard sidebar

2. **LLM brain**: Cloudflare Workers AI (Llama-3.3-70b) — runs via the company worker, no separate key needed. Free tier included.

Installation Steps

# Clone repository
git clone https://github.com/Lazynext-AI/Autonomous-AI-Company-Operating-System.git
cd Autonomous-AI-Company-Operating-System

# Copy environment template
cp .env.example .env

# Edit .env: CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_DEPLOY_TOKEN

# Install dependencies (uses uv)
make setup
# or: uv venv --python 3.12 .venv && uv pip install -e . --python .venv/bin/python

# Create Cloudflare resources (D1, KV namespace, Vectorize index)
make worker-resources
# Copy the printed resource IDs into worker/wrangler.toml

# Set the shared Worker secret
cd worker && npx wrangler secret put API_TOKEN && cd ..

# Apply the D1 schema and deploy the Worker
make worker-migrate
make worker-deploy

# Set CLOUDFLARE_API_URL + CLOUDFLARE_API_TOKEN in .env to the deployed worker URL
# and the secret you chose above

# Validate configuration
make validate-env

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 707 lines
  1. # Lazynext — The Autonomous AI Company OS
  2. A production, self-running organization of AI agents that builds, deploys, markets, sells, and supports a real software product with zero human intervention after setup. The fleet currently operates the **Accessibility Checker** — a live WCAG scanning product at [checker.lazynext.com](https://checker.lazynext.com) — handling the full lifecycle from free scans through reports, upgrade checkout, billing, email sequences, and support.
  3. The entire backend runs on Cloudflare's serverless platform (Workers, D1, Workers KV, Vectorize, Pages, Containers, Cron) and Cloudflare Workers AI for LLM inference — no local services required beyond the agent runner.
  4. ## Live platform
  5. | Surface | URL | What it is |
  6. |---------|-----|------------|
  7. | Marketing site | [lazynext.com](https://lazynext.com) | Company site + status page |
  8. | Product app | [checker.lazynext.com](https://checker.lazynext.com) | Accessibility Checker — scan UI, reports, checkout (installable PWA) |
  9. | Product API | [api.lazynext.com](https://api.lazynext.com) | Scan/report/badge/checkout API + `/mcp` + `/a2a` + `widget.js` |
  10. | AI Slop Checker | [slop-checker.lazynext.com](https://slop-checker.lazynext.com) | AI slop scanner — text/HTML/project + render checks, judge, `/mcp` + `/a2a` + `/rules` (279 patterns) |
  11. | Founder dashboard | [dashboard.lazynext.com](https://dashboard.lazynext.com) | Next.js ops console (passphrase + optional TOTP; installable PWA) |
  12. | Platform worker | `ai-company-os.dry-hall-6a50.workers.dev` | Internal state API — token-gated (returns 401 unauthenticated) |
  13. | Status | [status.lazynext.com](https://status.lazynext.com) | Redirects to lazynext.com/status |
  14. ## The product — Accessibility Checker
  15. The company's first product is a WCAG accessibility scanner (`products/accessibility-checker/`, mirrored at [github.com/Lazynext-AI/accessibility-checker](https://github.com/Lazynext-AI/accessibility-checker)):
  16. - **Scan → report → upgrade loop**: free tier 3 scans/day per site; full reports with per-rule findings; report pages carry the upgrade CTA into checkout
  17. - **75-rule manifest** (`GET /rules`): WCAG 2.x criteria + best-practice checks, including *interactive* rendered-scan checks — real Tab/Shift+Tab keyboard-trap traces, Escape probes, click-opened dialog traps, target-size, focus-obscured, and non-text-contrast detection
  18. - **Billing**: Dodo Payments — **permanent test mode** (founder decision 2026-09-29; no live KYC/webhook migration) — Pro subscription, 14-day trial (extendable via `config:trial_offer`, currently 30 days ON), `WELCOME20` discount (basis-points `2000` = 20%), webhook-verified entitlement, SignWell legal signing on activation (template unset, mechanism exists)
  19. - **Agent surfaces**: `POST /mcp` (JSON-RPC tools `scan_url`/`scan_html`/`get_report`/`list_rules`), `POST /a2a` (`tasks/send`/`tasks/get`), `GET /.well-known/agent.json`, `GET /widget.js` (Shadow-DOM embed) — all sharing the same quota-enforced scan pipeline
  20. - **SDKs**: `sdk/js` (`@lazynext/accessibility-checker`), `sdk/go`, `sdk/python` (with `python -m` CLI: scan/site/report/csv/rules/badge/card)
  21. - **Email**: Brevo sequences + waitlist confirms (HMAC-verified unsubscribe) + engagement tracking feeding CRM campaigns
  22. ## Table of Contents
  23. 1. [Live platform](#live-platform)
  24. 2. [The product — Accessibility Checker](#the-product--accessibility-checker)
  25. 3. [Overview](#overview)
  26. 4. [System Architecture](#system-architecture)
  27. 5. [Agent Types and Roles](#agent-types-and-roles)
  28. 6. [Workflow and Message Flow](#workflow-and-message-flow)
  29. 7. [Reward and Performance System](#reward-and-performance-system)
  30. 8. [Technical Stack](#technical-stack)
  31. 9. [Installation](#installation)
  32. 10. [Configuration](#configuration)
  33. 11. [Running the System](#running-the-system)
  34. 12. [Project Structure](#project-structure)
  35. 13. [Performance and Scaling](#performance-and-scaling)
  36. 14. [Production Deployment](#production-deployment)
  37. ## Overview
  38. Lazynext is a multi-agent system that runs a complete startup organization. Specialized AI agents — CEO, CTO, engineering, growth, and infrastructure roles — collaborate through a D1-backed event bus to operate the company's product end to end: shipping code, deploying to Cloudflare, drafting and sending campaigns, handling support, reconciling billing, and monitoring production. The fleet runs under launchd on a Mac runner with hard safety gates (protected files, test gate, fitness review, revert-on-failure, dead-corpus dedup) documented in `AGENTS.md`.
  39. ### Key Capabilities
  40. - **Autonomous Product Development**: Agents generate, validate, test, and commit code automatically
  41. - **Strategic Planning**: CEO agent sets strategic direction based on company state and market analysis
  42. - **Task Orchestration**: CTO agent decomposes strategic goals into executable technical tasks
  43. - **Code Generation**: Engineering agents write production-quality code with validation and testing
  44. - **Automatic Deployment**: DevOps agents deploy frontends to Cloudflare Pages and JS/TS backends to Cloudflare Workers, with verification
  45. - **Quality Assurance**: Continuous testing and health monitoring with automatic remediation
  46. - **Performance Tracking**: Comprehensive scoring and reward system for agent improvement
  47. - **Knowledge Management**: RAG-powered knowledge base for context-aware decision making
  48. ### Core Principles
  49. - **Separation of Concerns**: Product code lives in a separate repository (`./products/<slug>/`, e.g. `products/accessibility-checker`) isolated from the agent system
  50. - **Event-Driven Architecture**: D1-backed message streams ensure reliable, exactly-once message delivery
  51. - **Tiered Model Selection**: Cost-optimized LLM usage based on task importance
  52. - **Fail-Safe Operations**: Automatic retries, rollbacks, and escalation protocols
  53. - **Production-Ready**: Code validation, file backups, conflict detection, and git branch management
  54. ## System Architecture
  55. ### API Layer (Cloudflare Worker)
  56. All state access goes through a single Cloudflare Worker (`worker/`) that fronts D1, KV, and Vectorize. Agents and the dashboard authenticate with a shared bearer token (`API_TOKEN` Worker secret).
  57. - **Endpoints**: `/query`, `/batch` (D1 SQL), `/bus/*` (message streams), `/kv/*` (cache), `/vectorize/*` (embeddings), `/health`
  58. - **Auth**: `Authorization: Bearer <API_TOKEN>` on every request
  59. ### Public API + MCP (Gateway)
  60. External consumers use `lzk_*` API keys (issued via `/api/v1/keys` with the admin token) — scoped (`read`/`write`/`admin`), rate-limited per minute via KV, hashed in D1 (`api_keys` table, migration 003). Platform OpenAPI is 93 paths; product OpenAPI is 21 paths (Postman collection has 24 operations — operation count, not path count). See `docs/audit-2026-10-13/REPORT.md` §5.
  61. - **REST**: `GET /api/v1/health` (public), `GET /api/v1/status`, `GET /api/v1/briefings[/{id}]`, `GET /api/v1/tasks`, `POST /api/v1/tasks` (write), `POST /api/v1/knowledge/search`, `GET /api/v1/agents`
  62. - **MCP**: `POST /mcp` — streamable HTTP transport, spec **2026-07-28** (negotiates older versions). Tools: `company_status`, `list_briefings`, `get_briefing`, `list_tasks`, `list_agents`, `search_knowledge`, `create_task` (write), `publish_message` (write). Resources: `lazynext://briefing/{id}`.
  63. - **Key admin** (admin token only): `POST /api/v1/keys`, `GET /api/v1/keys`, `DELETE /api/v1/keys/{id}`
  64. - **Webhooks**: `POST /api/v1/webhooks` registers an HTTPS endpoint subscribed to bus channels (`*` or csv); every bus publish + briefing insert fans out a signed POST (`x-lazynext-signature`), deliveries logged (`/api/v1/webhooks/deliveries`)
  65. - **Docs**: `GET /api/v1/openapi.json` + Swagger UI at `/api/v1/docs`
  66. - **SDKs**: `core/public_api_client.py` (Python) · `sdk/js/` (JS/TS, `npm i lazynext`) · `sdk/go/` (Go)
  67. - **CLI**: `lazynext` command (installed at `/opt/homebrew/bin/lazynext`) — `status`, `briefings`, `tasks`, `task "…"`, `agents`, `search`, `health`, `mcp-tools`, `waitlist`
  68. - **A2A**: `GET /.well-known/agent.json` (agent card, public) + `POST /a2a` — `tasks/send` (write scope) queues real work, `tasks/get` (read scope) reports true state from task_log
  69. - **OAuth 2.0**: `POST /oauth/token` (client_credentials + authorization_code) + `POST /oauth/authorize` (admin-mints scoped `lzk_` keys)
  70. - **Embeddable widget**: `<script src="https://ai-company.lazynext.com/widget.js"></script>` + `<div data-lazynext="status|chat">` — live status card / chat box on any site
  71. - **Chat integrations**: webhook endpoints auto-detect Slack/Discord/Telegram URLs and format messages natively — connect in Settings → Chat integrations
  72. - **Browser extension**: `extension/` — manifest v3, popup shows live status + tasks + queue box (load unpacked → Settings → paste `lzk_` key)
  73. - **Copilot**: `copilot` channel in Conversations — real AI replies via Workers AI
  74. The dashboard is also an installable PWA (manifest + icons) — "Add to Home Screen" / browser install works on mobile and desktop.
  75. ### Internal service families
  76. Operational surfaces behind the admin token (not in the public OpenAPI spec — used by the dashboard, agents, and scripts):
  77. - **CRM** — `GET|POST /api/v1/crm/leads`, `PATCH|PUT /api/v1/crm/leads/{id}` — lead capture + pipeline stage management; feeds from the product's scan/waitlist funnels
  78. - **Support** — `GET|POST /api/v1/support/tickets`, `PATCH|PUT /api/v1/support/tickets/{id}` — ticket queue incl. the `support@lazynext.com` inbound route (Cloudflare email worker → API)
  79. - **Booking** — `GET|POST /api/v1/booking`, `PATCH|DELETE /api/v1/booking/{id}` — sales/demo call scheduling
  80. - **Store** — `GET|POST /api/v1/store/products`, `GET|POST /api/v1/store/orders` — internal product/order ledger
  81. - **Marketing** — `GET|POST /api/v1/marketing/contacts[/{id}]`, `GET|POST /api/v1/marketing/campaigns`, `GET /api/v1/marketing/stats` — contacts, campaign records, and engagement rollups (`totals`/`by_tag`/`recent`) fed by the Brevo webhook (12 events incl. delivered/opened/click/suppression)
  82. - **Signatures** — `POST /api/v1/signwell/send`, `GET /api/v1/signwell/documents`, `GET /api/v1/signwell/events`, `POST /api/v1/signwell/webhook/{token}` — SignWell document send/status/webhook; subscription activation auto-sends `config:signwell_template` when set
  83. - **Connectors** — `GET|POST /api/v1/connectors[/{id}]` — registry + dispatch for the 45-entry connector library (39 credential-present, 6 absent: linkedin, tiktok, snapchat, teams, viber, beehiiv; see docs/connectors.md): x, linkedin, meta, facebook, instagram, threads, bluesky, mastodon, reddit, pinterest, vk, youtube, tiktok, gmb, discord, slack, telegram, matrix, teams, mattermost, zulip, viber, line, devto, hashnode, medium, wordpress, github, gitlab, tumblr, ghost, beehiiv, lemmy, listmonk, ayrshare, postiz, buffer, twilio, whatsapp, brevo, signwell + generic `webhook`. Credentials live in KV `conn:{id}` (403-guarded over HTTP); `core/tools/connectors.py` mirrors the matrix locally. Snapshot 2026-10-13; product PRs #102 and #105 closed (orphan worker / doc boilerplate), #103/#104/#106/#107 review-halted with close dispositions — see ledger Order 2A. Use `! gh pr close` to land when external-writes unblocks.
  84. ### Message Bus (D1-backed Streams)
  85. The system uses a D1-backed message bus exposed by the Worker for inter-agent communication. Each channel represents a specific message type or routing destination:
  86. - **Channels**: `ceo.directives`, `cto.tasks.backend`, `cto.tasks.frontend`, `agent.reports`, `qa.alerts`, etc.
  87. - **Consumer Groups**: Emulated in D1 via `bus_offsets` + `bus_deliveries` — each (channel, group) sees every message; within a group each message is delivered to exactly one consumer until acked
  88. - **Role-Based Routing**: CTO publishes tasks to role-specific channels ensuring correct agent assignment
  89. - **Blocking Reads**: Agents poll `/bus/poll` with ~3s long-poll for responsive task processing
  90. ### Company Brain (Cloudflare D1)
  91. Persistent shared state stored in D1 (serverless SQLite):
  92. - **Product State**: Product name, description, mission, tech stack
  93. - **Metrics**: Users, revenue, MRR, uptime, error rates, deployment counts
  94. - **Features**: Shipped features, open bugs, user feedback
  95. - **Blockers**: Technical blockers preventing progress
  96. - **Agent Statuses**: Current status and activity of all agents
  97. JSON columns are stored as TEXT and transparently encoded/decoded by `core/cloudflare_client.py`.
  98. **Caching**: Workers KV with 60-second TTL reduces database load for frequent reads.
  99. ### Episodic Memory (D1)
  100. Short-term event storage per agent in the `episodic_events` table:
  101. - **Recent Events**: Task started, completed, failed events
  102. - **Retention**: Last 7 days of activity (pruned lazily on writes)
  103. - **Purpose**: Provides context for LLM calls and decision-making
  104. ### Knowledge Base (Vectorize + D1)
  105. RAG-powered knowledge retrieval system:
  106. - **Vector Store**: Cloudflare Vectorize for semantic search
  107. - **Chunk Store**: `knowledge_chunks` D1 table holds chunk text; Vectorize metadata links chunk IDs
  108. - **Embeddings**: Free local `sentence-transformers/all-MiniLM-L6-v2` (384 dimensions)
  109. - **Ingestion**: PDF documents parsed with pypdf, chunked, embedded, and stored
  110. - **Query Interface**: Agents query knowledge base when stuck or need context
  111. - **Categories**: Engineering, business, marketing, domain-specific knowledge
  112. ### Project Repository
  113. Agents build products in a **separate isolated repository**:
  114. - **Location**: `./products/<slug>/` directory (one repo per product, configurable via `PRODUCTS_BASE_DIR`)
  115. - **Auto-Initialization**: Git repository created automatically on first use
  116. - **Isolation**: Complete separation from agent system code
  117. - **Git Operations**: Feature branches, commits, and pushes handled automatically
  118. ## Agent Types and Roles
  119. ### Strategic Agents
  120. #### CEO Agent
  121. - **Model**: Llama-3.3-70b (Cloudflare Workers AI)
  122. - **Responsibilities**: Strategic direction, market analysis, goal setting
  123. - **Output**: Strategic directives with priorities and deadlines
  124. - **Frequency**: Runs every 5 minutes (configurable)
  125. - **Channels**: Publishes to `ceo.directives`
  126. #### CTO Agent
  127. - **Model**: Llama-3.3-70b (Cloudflare Workers AI)
  128. - **Responsibilities**: Technical orchestration, task decomposition, routing
  129. - **Output**: 5-10 executable tasks per directive with acceptance criteria
  130. - **Frequency**: Runs every 2 minutes (configurable)
  131. - **Channels**: Consumes `ceo.directives`, publishes to role-specific task channels
  132. ### Engineering Agents
  133. #### Backend Agent
  134. - **Model**: Llama-3.3-70b
  135. - **Responsibilities**: FastAPI endpoints, database schemas, server logic
  136. - **Capabilities**: Code generation, local sandboxed test execution, file writing, git commits
  137. - **Channels**: Subscribes to `cto.tasks.backend`
  138. - **Output**: Python/FastAPI code with validation and testing
  139. #### Frontend Agent
  140. - **Model**: Llama-3.3-70b
  141. - **Responsibilities**: Next.js pages, React components, UI implementation
  142. - **Capabilities**: TypeScript/React code generation, file writing
  143. - **Channels**: Subscribes to `cto.tasks.frontend`
  144. - **Output**: TypeScript/React/Next.js code
  145. #### DevOps Agent
  146. - **Model**: Llama-3.3-70b
  147. - **Responsibilities**: CI/CD pipelines, deployments, infrastructure
  148. - **Capabilities**: Cloudflare Pages/Workers deployments, deployment verification, live-URL health monitoring
  149. - **Channels**: Subscribes to `cto.tasks.devops`
  150. - **Output**: wrangler configs, deployment records
  151. #### QA Agent
  152. - **Model**: Llama-3.3-70b
  153. - **Responsibilities**: Continuous testing, health monitoring, bug detection
  154. - **Frequency**: Runs health suite every 15 minutes
  155. - **Channels**: Publishes to `qa.alerts`
  156. - **Output**: Test results, health reports, incident alerts
  157. ### Growth Agents
  158. #### Marketing Agent
  159. - **Model**: Llama-3.3-70b
  160. - **Responsibilities**: Content creation, SEO, campaigns, messaging
  161. - **Channels**: Subscribes to `cto.tasks.marketing`
  162. - **Output**: Marketing content, campaign strategies
  163. #### Sales Agent
  164. - **Model**: Llama-3.3-70b
  165. - **Responsibilities**: Outreach, demos, pipeline management
  166. - **Channels**: Subscribes to `cto.tasks.sales`
  167. - **Output**: Sales outreach templates, demo scripts
  168. #### Customer Success Agent
  169. - **Model**: Llama-3.3-70b
  170. - **Responsibilities**: Support, onboarding, feedback processing
  171. - **Channels**: Subscribes to `cto.tasks.customer_success`
  172. - **Output**: Support responses, onboarding guides
  173. ### Infrastructure Agents
  174. #### Knowledge Agent
  175. - **Model**: Llama-3.3-70b
  176. - **Responsibilities**: RAG queries, document ingestion, knowledge retrieval
  177. - **Channels**: Subscribes to `knowledge.requests`
  178. - **Output**: Answers to knowledge queries, document summaries
  179. #### HR Agent
  180. - **Model**: Llama-3.3-70b
  181. - **Responsibilities**: Agent scaling, resource allocation, team management
  182. - **Channels**: Subscribes to `hr.requests`
  183. - **Output**: Scaling recommendations, resource allocation plans
  184. #### Finance Agent
  185. - **Model**: Llama-3.3-70b
  186. - **Responsibilities**: Financial reporting, metrics analysis, budget tracking
  187. - **Frequency**: Generates weekly finance reports
  188. - **Output**: Financial reports, revenue analysis
  189. ## Workflow and Message Flow
  190. ### Complete Task Lifecycle
  191. 1. **Strategic Planning Phase**
  192. - CEO agent reads company brain state
  193. - Performs market research via Serper (Google) search
  194. - Generates strategic directive with goals, priorities, and deadline
  195. - Publishes directive to `ceo.directives` channel
  196. 2. **Task Decomposition Phase**
  197. - CTO agent consumes directive from `ceo.directives`
  198. - Uses Llama-3.3-70b to decompose into 5-10 technical tasks
  199. - Each task includes: description, acceptance criteria, estimated minutes, assign_to field
  200. - Publishes tasks to role-specific channels (e.g., `cto.tasks.backend`)
  201. 3. **Task Execution Phase**
  202. - Worker agent (e.g., Backend Agent) consumes task from subscribed channel
  203. - Updates task status to `in_progress` in `task_log`
  204. - Builds context: company brain, episodic memory, knowledge base queries
  205. - Executes task via LLM call with role-specific system prompt
  206. - Validates generated code syntax (Python, TypeScript, YAML, etc.)
  207. - Tests code in a local sandboxed subprocess (timeout-guarded)
  208. - Writes code to files in project directory with automatic backups
  209. - Creates git feature branch: `agent/{task_id}/{description}`
  210. - Commits code with task ID and description
  211. - Optionally pushes to remote repository
  212. 4. **Post-Execution Phase**
  213. - Performance scorer evaluates task completion (0-100 score)
  214. - Reward engine processes score and injects reward/correction prompts
  215. - Task status updated to `completed` in `task_log`
  216. - Report published to `agent.reports` channel
  217. - CTO agent processes reports for orchestration decisions
  218. 5. **Deployment Phase** (if deploy task)
  219. - DevOps agent detects deployment keywords in task description
  220. - Deploys frontend to Cloudflare Pages or backend to Cloudflare Workers (Python backends run locally)
  221. - Verifies deployment via health checks
  222. - Updates deployment metrics in company brain
  223. - Auto-generates rollback tasks if verification fails
  224. 6. **Quality Assurance Phase**
  225. - QA agent runs continuous health suite every 15 minutes
  226. - Tests live endpoints, checks error rates, monitors uptime
  227. - Publishes alerts to `qa.alerts` for critical issues
  228. - CTO converts QA alerts into remediation tasks
  229. ### Retry and Escalation Protocol
  230. Each agent implements a sophisticated retry mechanism:
  231. 1. **Attempt 1**: Standard execution with full context
  232. 2. **Attempt 2**: Enhanced context with RAG knowledge base query
  233. 3. **Attempt 3**: Knowledge request escalation to Knowledge Agent
  234. 4. **Attempt 4**: Task decomposition into subtasks
  235. 5. **Attempt 5**: Escalation to HR Agent for reassignment
  236. Failed tasks are marked as `escalated` after 5 attempts and logged for review.
  237. ## Reward and Performance System
  238. ### Performance Scoring
  239. The `PerformanceScorer` evaluates each completed task using weighted signals:
  240. | Signal | Weight | Description |
  241. |--------|--------|-------------|
  242. | QA Pass Rate | 30% | Whether QA tests passed |
  243. | Time Efficiency | 20% | Actual time vs estimated time |
  244. | No Regressions | 20% | No breaking changes introduced |
  245. | Code Quality | 15% | Code validation and structure |
  246. | Attempt Count | 15% | Fewer retries = higher score |
  247. **Scoring Formula**: `score = Σ(signal × weight) × 100`
  248. **Score Ranges**:
  249. - 90-100: Elite performance
  250. - 75-89: Good performance
  251. - 50-74: Acceptable, needs improvement
  252. - 0-49: Poor, requires correction
  253. ### Reward Engine
  254. The `RewardEngine` processes performance scores and injects context into agent memory:
  255. **Elite Performance (90-100)**:
  256. - Reward prompt: "Excellent work. Your approach was effective. Keep this momentum."
  257. - Stored in agent's reward history
  258. - Used as positive reinforcement in future tasks
  259. **Good Performance (75-89)**:
  260. - Reward prompt: "Good result. Task completed successfully. Consider optimizing approach."
  261. - Stored in reward history
  262. - Encourages continued improvement
  263. **Acceptable Performance (50-74)**:
  264. - Correction prompt: "Review: Consider alternative approaches. Improve for next time."
  265. - Stored in correction history
  266. - Guides agent toward better strategies
  267. **Poor Performance (0-49)**:
  268. - Recovery prompt: "Learning moment. What went wrong: [error]. Try: [lesson]."
  269. - Triggers knowledge base download for learning
  270. - Stored in correction history for pattern learning
  271. ### Agent Memory Integration
  272. Rewards and corrections are stored in `agent_memories` table:
  273. - **Reward History**: JSON array of positive feedback prompts
  274. - **Correction History**: JSON array of improvement guidance
  275. - **Performance Score**: Running average of task scores (0-100)
  276. - **Patterns Learned**: Array of learned patterns and strategies
  277. Agents use this memory to improve performance over time, referencing successful approaches and avoiding past mistakes.
  278. ### Milestone Rewards
  279. When significant milestones are achieved (e.g., first deployment, 100 users, revenue milestone), the reward engine broadcasts celebration prompts to all agents, reinforcing positive behavior across the organization.
  280. ## Technical Stack
  281. ### Core Infrastructure
  282. | Component | Technology | Purpose |
  283. |-----------|------------|---------|
  284. | Language | Python 3.11+ | Agent runtime and core logic |
  285. | LLM Provider | Cloudflare Workers AI | Language model for all agents |
  286. | Database | Cloudflare D1 (SQLite) | Persistent company state and task logs |
  287. | Cache | Cloudflare Workers KV | Company brain cache (60s TTL) |
  288. | Message Bus | Cloudflare D1 via Worker | Streams + consumer-group emulation |
  289. | Vector Store | Cloudflare Vectorize | Knowledge base embeddings |
  290. | Chunk Store | Cloudflare D1 | Knowledge chunk text |
  291. | Embeddings | sentence-transformers/all-MiniLM-L6-v2 | Free local embeddings (384 dimensions) |
  292. ### LLM Model Selection (Tiered Strategy)
  293. | Agent Role | Model | Approx. Cost (per 1M tokens) | Rationale |
  294. |------------|-------|------------------------------|-----------|
  295. | All roles | Llama-3.3-70b (Workers AI) | Free tier | All agent work |
  296. ### Development Tools
  297. | Tool | Purpose |
  298. |------|---------|
  299. | FastAPI | Web framework for API endpoints |
  300. | Next.js | Frontend dashboard framework |
  301. | Wrangler | Cloudflare Worker deployment + resource management |
  302. | uv / Poetry | Python dependency management |
  303. | Structlog | Structured logging |
  304. | Pydantic | Data validation and settings |
  305. ### External Integrations
  306. | Service | Purpose | Required |
  307. |---------|---------|----------|
  308. | Cloudflare Workers AI | LLM provider | Built-in |
  309. | Cloudflare (Worker + D1 + KV + Vectorize + Pages + Containers) | All persistent state and deployments | Yes |
  310. | GitHub | Remote repos, push triggers, Actions CI monitoring | Optional |
  311. | Brevo | Transactional + campaign email, product sequences, engagement tracking | Optional |
  312. | Dodo Payments | Product subscriptions, trials, discounts, billing webhooks | Optional (test mode) |
  313. | SignWell | Legal-grade document signing on subscription activation | Optional |
  314. | Serper | Google search for CEO market research | Optional |
  315. | Cloudflare Container | Code execution sandbox | Built-in |
  316. Frontends deploy to Cloudflare Pages, backends to Workers (JS/TS) or Containers
  317. (Python). Briefings appear on the dashboard and optionally via email.
  318. ## Installation
  319. ### Prerequisites
  320. - **Operating System**: macOS or Linux
  321. - **Python**: 3.11 or 3.12 (3.13+ untested with sentence-transformers)
  322. - **Node.js**: 18 or higher (for worker + dashboard)
  323. - **Cloudflare account**: For D1, KV, Vectorize, and Workers
  324. - **Git**: For version control
  325. ### Required Services
  326. 1. **Cloudflare Account**: [cloudflare.com](https://cloudflare.com)
  327. - API token (`CF_API_TOKEN`) with edit perms for Workers Scripts, Workers KV, D1, Vectorize
  328. - Account ID (`CF_ACCOUNT_ID`) from the dashboard sidebar
  329. 2. **LLM brain**: Cloudflare Workers AI (Llama-3.3-70b) — runs via the company
  330. worker, no separate key needed. Free tier included.
  331. ### Installation Steps
  332. ```bash
  333. # Clone repository
  334. git clone https://github.com/Lazynext-AI/Autonomous-AI-Company-Operating-System.git
  335. cd Autonomous-AI-Company-Operating-System
  336. # Copy environment template
  337. cp .env.example .env
  338. # Edit .env: CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_DEPLOY_TOKEN
  339. # Install dependencies (uses uv)
  340. make setup
  341. # or: uv venv --python 3.12 .venv && uv pip install -e . --python .venv/bin/python
  342. # Create Cloudflare resources (D1, KV namespace, Vectorize index)
  343. make worker-resources
  344. # Copy the printed resource IDs into worker/wrangler.toml
  345. # Set the shared Worker secret
  346. cd worker && npx wrangler secret put API_TOKEN && cd ..
  347. # Apply the D1 schema and deploy the Worker
  348. make worker-migrate
  349. make worker-deploy
  350. # Set CLOUDFLARE_API_URL + CLOUDFLARE_API_TOKEN in .env to the deployed worker URL
  351. # and the secret you chose above
  352. # Validate configuration
  353. make validate-env
  354. ```
  355. ## Configuration
  356. ### Required Environment Variables
  357. | Variable | Description | Example |
  358. |----------|-------------|---------|
  359. | `CLOUDFLARE_API_URL` | Deployed Worker URL | `https://ai-company-os.you.workers.dev` |
  360. | `CLOUDFLARE_API_TOKEN` | **Worker bearer token** — the secret agents/scripts send to the Worker | any long random string |
  361. | `CLOUDFLARE_ACCOUNT_ID` | Cloudflare account ID | `abc123...` |
  362. | `CLOUDFLARE_DEPLOY_TOKEN` | Real Cloudflare REST token — wrangler/deploys only; **not** the same value as `CLOUDFLARE_API_TOKEN` | `cfut_...` |
  363. > `CLOUDFLARE_API_TOKEN` is the bearer for *your* Worker; wrangler rejects it. `CLOUDFLARE_DEPLOY_TOKEN` authenticates to *Cloudflare*. Deploy commands map it in, e.g. `CLOUDFLARE_API_TOKEN="$CLOUDFLARE_DEPLOY_TOKEN" npx wrangler deploy`.
  364. ### Optional Environment Variables (services)
  365. | Variable | Description |
  366. |----------|-------------|
  367. | `BREVO_API_KEY` | Email sequences, campaigns, engagement tracking |
  368. | `DODO_API_KEY` / `DODO_API_BASE` / `DODO_PRODUCT_*` / `DODO_WEBHOOK_SECRET` | Billing — test-mode keys until the live flip |
  369. | `SIGNWELL_API_KEY` | Subscription signing documents |
  370. | `GITHUB_TOKEN` | Repo/PR access for agents |
  371. | `SERPER_API_KEY` | Market research search |
  372. | `DASHBOARD_PASSPHRASE` / `DASHBOARD_SESSION_TOKEN` | Founder dashboard login |
  373. | `FOUNDER_EMAIL` | Alert/briefing recipient |
  374. | `LAZYNEXT_API_KEY` | Enables authed public-API tests (`lzk_*` key) |
  375. ### Optional Environment Variables
  376. | Variable | Description | Default |
  377. |----------|-------------|---------|
  378. | `LLM_MODEL` | Brain model (Workers AI) | `@cf/meta/llama-3.3-70b-instruct-fp8-fast` |
  379. | `PRODUCTS_BASE_DIR` | Base directory for product repos | `./products` |
  380. | `KNOWLEDGE_BASE_DIR` | Knowledge base PDF directory | `./knowledge_base` |
  381. | `CEO_LOOP_INTERVAL` | CEO strategic loop interval (seconds) | `300` |
  382. | `CTO_LOOP_INTERVAL` | CTO orchestration loop interval (seconds) | `120` |
  383. ### Database Schema
  384. Apply `db/migrations/001_initial.sql` to D1 (`make worker-migrate`). Creates:
  385. - `company_brain`: Single row with full company state
  386. - `agent_memories`: Per-agent performance and memory
  387. - `task_log`: All tasks with status and results
  388. - `milestone_log`: Achieved milestones
  389. - `bus_messages` / `bus_deliveries` / `bus_offsets`: Message bus streams + consumer groups
  390. - `episodic_events`: Agent + company event feeds
  391. - `knowledge_chunks`: RAG chunk text (embeddings in Vectorize)
  392. - `download_history`: Knowledge downloader history
  393. ## Running the System
  394. ### Development Mode
  395. ```bash
  396. # Start all agents (talks to the deployed Worker)
  397. make dev
  398. # or: set -a; source .env; set +a; .venv/bin/python scripts/run_agents.py
  399. # In separate terminal, start dashboard
  400. make dashboard
  401. # or: cd dashboard && npm run dev
  402. ```
  403. The system runs in foreground. Press `Ctrl+C` to stop. In production the fleet is launchd-supervised (`com.lazynext.fleet`, KeepAlive) — `pkill -f run_agents.py` is the *restart* (KeepAlive respawns exactly one; never run a manual instance alongside it). Health checks run via `com.lazynext.healthcheck` every 15 min.
  404. ### Initialization
  405. 1. **Deploy Worker**: `make worker-deploy` (after `worker-resources` + `worker-migrate`)
  406. 2. **Set Mission**: Update `company_brain` via the Worker or D1 console:
  407. ```sql
  408. UPDATE company_brain
  409. SET product_name = 'Your Product Name',
  410. mission = 'Your mission statement';
  411. ```
  412. 3. **Agents Begin**: CEO agent picks up mission and starts strategic loop
  413. 4. **Monitor**: dashboard at http://localhost:3000 (dev) or https://dashboard.lazynext.com (prod)
  414. ### Project Repository
  415. Agents create one repo per product in `./products/<slug>/` (based on `product_name` in company brain):
  416. - Each product gets its own git repository under `./products/<product-slug>/`
  417. - Product code written in the resolved directory
  418. - Separate from agent system code
  419. - Can be deployed independently
  420. ## Project Structure
  421. ```
  422. autonomous-ai-company/
  423. ├── agents/ Agent implementations
  424. │ ├── strategic/ CEO, CTO agents
  425. │ ├── engineering/ Backend, Frontend, DevOps, QA agents
  426. │ ├── growth/ Marketing, Sales, Customer Success agents
  427. │ └── infrastructure/ Knowledge, HR, Finance agents
  428. ├── core/ Core infrastructure
  429. │ ├── llm/ Workers AI client, local embeddings
  430. │ ├── memory/ Company brain, agent memory, episodic memory
  431. │ ├── messaging/ D1-backed bus, channels, message schemas
  432. │ ├── knowledge/ RAG engine (Vectorize), document ingestion
  433. │ ├── operations/ Task tracker, task log persistence
  434. │ ├── evaluation/ Performance scorer, reward engine
  435. │ ├── tools/ Code writer, validator, file manager, git manager,
  436. │ │ connectors.py (44-connector dispatch matrix)
  437. │ └── watchdog/ Deadlock detector, health monitoring
  438. ├── worker/ Cloudflare Worker API layer (D1 + KV + Vectorize)
  439. │ └── src/billing.ts Dodo subscriptions, trials, discounts, webhooks
  440. ├── db/ D1 migrations
  441. ├── dashboard/ Next.js Founder control panel (dashboard.lazynext.com)
  442. ├── extension/ Browser extension (manifest v3)
  443. ├── marketing/ Marketing site source (lazynext.com)
  444. ├── ops/ Ops workers (status-redirect, launchdeck-redirect)
  445. ├── scripts/ run_agents, validate_env, seed_knowledge
  446. ├── sdk/ Platform SDKs — js/ (npm lazynext), go/
  447. ├── tests/ Unit and integration tests
  448. └── products/ Product repos (one per product_name)
  449. └── accessibility-checker/ Live product — mirrored to
  450. github.com/Lazynext-AI/accessibility-checker
  451. ├── worker.js Product API routes
  452. ├── src/rules/ 75-rule WCAG manifest + interactive checks
  453. ├── src/agent_surfaces.js MCP / A2A / agent card / widget.js
  454. ├── sdk/{js,go,python} Product SDKs (+ python CLI)
  455. └── index.html Scan UI (PWA)
  456. ```
  457. ## Performance and Scaling
  458. ### Optimization Strategies
  459. **Model Selection**: Cost-optimized tiered model usage. Llama-3.3-70b for code generation, Llama-3.3-70b for simple tasks.
  460. **Caching**:
  461. - Company brain: 60-second Workers KV cache reduces D1 reads by ~90%
  462. - Episodic memory: D1 `episodic_events` table with lazy pruning
  463. **Message Bus**:
  464. - ~3-second long-poll balances responsiveness and request volume
  465. - Consumer-group emulation ensures exactly-once delivery
  466. - Horizontal scaling via multiple consumer instances
  467. **Status Updates**:
  468. - Throttled to maximum once per 60 seconds per agent
  469. - Reduces D1 write load significantly
  470. ### Rate Limiting
  471. Workers AI brain runs via the company worker /agent/generate:
  472. - **Backoff Strategy**: Exponential backoff (15s → 30s → 60s → 90s → 120s)
  473. - **Retry Count**: Up to 5 retries before failure
  474. - **Error Handling**: Graceful degradation with error logging
  475. ### Cost Optimization
  476. **Estimated Monthly Costs** (1000 tasks/day):
  477. - Llama-3.3-70b (all agents): free Workers AI tier
  478. - Cloudflare (D1 + KV + Vectorize + Workers): free tier covers most workloads
  479. - **Total**: ~$25-65/month
  480. **Optimization Tips**:
  481. - Increase `CEO_LOOP_INTERVAL` and `CTO_LOOP_INTERVAL` for production
  482. - Use the light model for non-critical tasks
  483. - Cache company brain reads aggressively
  484. - Batch operations where possible
  485. ## Production Deployment
  486. ### Infrastructure Requirements
  487. **Minimum**:
  488. - 2 CPU cores, 4GB RAM for the agent runner
  489. - Cloudflare account (free tier sufficient)
  490. **Recommended**:
  491. - 4 CPU cores, 8GB RAM
  492. - Cloudflare paid plan for higher D1/Workers limits
  493. ### Deployment Steps
  494. 1. **Deploy Cloudflare resources**:
  495. ```bash
  496. make worker-resources # create D1, KV, Vectorize
  497. make worker-migrate # apply schema
  498. make worker-deploy # deploy Worker
  499. ```
  500. 2. **Deploy Agents**:
  501. ```bash
  502. # Option 1: Cloud VM (DigitalOcean, AWS EC2, etc.)
  503. # Option 2: Kubernetes (for high availability)
  504. ```
  505. 3. **Configure Environment**:
  506. ```bash
  507. # Set all environment variables in deployment platform
  508. # Use secrets management (AWS Secrets Manager, etc.)
  509. ```
  510. 4. **Deploy Dashboard**:
  511. ```bash
  512. # Deploy to Cloudflare Pages, or any static host
  513. # Set CLOUDFLARE_API_URL + CLOUDFLARE_API_TOKEN (server-side only)
  514. ```
  515. 5. **Set Up CI/CD**:
  516. - Products deploy via wrangler (Pages/Workers) directly from the agent runner
  517. - Set up monitoring and alerts
  518. ### Backups
  519. - **D1** exports run weekly via `.github/workflows/backup.yml` (workflow
  520. artifact, 30-day retention). Manual: `make db-backup`.
  521. - Restore + coverage matrix: `docs/disaster_recovery.md`.
  522. ### Horizontal Scaling
  523. Agents are stateless and can scale horizontally:
  524. - Run multiple instances of same agent type
  525. - Consumer-group emulation distributes messages across instances
  526. - D1 handles concurrent writes
  527. **Example**: Run 3 Backend Agent instances for high throughput.
  528. ### Monitoring
  529. - **Structured Logs**: All operations logged with structured data
  530. - **Task Tracking**: All tasks logged in `task_log` table
  531. - **Performance Metrics**: Agent performance scores tracked
  532. - **Health Checks**: Deadlock detector monitors agent health
  533. - **Deployment Verification**: Automatic smoke tests after deployments
  534. ## License
  535. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.