Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
23 changes: 0 additions & 23 deletions .agent/rules/02-do-abstraction.md

This file was deleted.

29 changes: 29 additions & 0 deletions .agent/rules/agent-skills.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Agent Skills Service Standards

## 1. Skill Storage Model
- Skills MUST NOT be fetched directly from GitHub during active AI inference.
- They must be ingested "out-of-band" into the D1 `agent_skills` table using the `/api/skills/ingest` or `/api/skills/ingest-structured` routes.
- The `SkillManager` service (`@/ai/providers/agent-support/skills.ts`) is the sole interface for skill resolution at inference time.

## 2. Provider-Level Injection
- Backend Agents must define skills using the `options: { skills: ['skill-name'] }` array passed to `AIProvider` generation methods.
- The `AIProvider` is solely responsible for querying `SkillManager`, which reads from D1 and caches in-memory with TTL.
- Chat agents receive dynamic skills via the `X-Agent-Skills` HTTP header, merged with static agent-defined skills in `resolveSystemPrompt()`.

## 3. Drizzle ORM Syntax
- Always use the `drizzle-zod` package for schema validation. Do NOT use `drizzle-orm/zod` (v1.0.0+ only).
- Schema definitions for agents live under `@db/schemas/agents/`.
- New relational tables (`agent_skill_allowed_tools`, `agent_skill_references`) use cascading FKs to `agentSkills.id`.

## 4. Additive API Changes
- When modifying Hono routes in production, favor ADDING new endpoints over destructively modifying existing ones.
- Example: `/ingest-structured` was added alongside the existing `/ingest` to prevent breaking active frontend clients.

## 5. Graceful Degradation
- Always parse external markdown and YAML frontmatter defensively.
- Do NOT fail a D1 insert if optional fields like `allowed-tools` are missing from SKILL.md.
- Default to an empty array and proceed with the core skill insertion.

## 6. Environment Variables
- AI generation tasks must exclusively use `GEMINI_API_KEY`.
- Skill ingestion routes use `GITHUB_TOKEN` via the existing `getOctokit()` service.
122 changes: 122 additions & 0 deletions .agent/rules/agent-specialist-delegation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Agent Specialist Delegation Rule

> **Enforcement level:** Mandatory — all code under `src/backend/src/ai/agents/`
> **Introduced by:** v7 PRD — `docs/20260417/standardize_agents/v7/PRD.md`
> **Verification:** grep-based CI guard — `scripts/check-agent-delegation.sh`

---

## Rule

**Specialist agents are the single source of truth for their domain.** No agent outside the specialist's directory may import or directly call the specialist's underlying SDK/service. Instead, agents consume specialist functionality via `@callable` RPC methods accessed through `getPeerAgent(env.FOO_AGENT)`.

---

## Domain Ownership Table

| Domain | Specialist Agent | Sanctioned Directory | Owned Imports |
|--------|-----------------|---------------------|---------------|
| **Cloudflare Docs / MCP** | `CloudflareAgent` | `chat/CloudflareAgent/` | `@/ai/mcp/*`, `queryMCP`, `rewriteQuestionForMCP` |
| **GitHub / Octokit** | `GithubAgent` | `backend/GithubAgent/` | `@octokit/*`, `@services/octokit/*`, `@/services/octokit/*`, `@/services/github/client` |

### CoordinatorAgent — Pure Router Contract

`chat/CoordinatorAgent/` is a **pure router**. It must never import any service SDK or domain client. Allowed imports are limited to:
- `agents` (for `callable`, `getAgentByName`, `StreamingResponse`, `getPeerAgent`)
- `@/ai/providers/agent-support/base-chat-agent`
- Local `./types`

**Forbidden in CoordinatorAgent:**
- `@octokit/*`
- `@/ai/mcp/*`
- `@/cloudflare/*`
- `@services/*`, `@/services/*`
- Any third-party SDK

---

## How to Consume Specialist APIs

### Cloudflare Docs (CloudflareAgent)

```typescript
// ✅ CORRECT — delegate via getPeerAgent
const cloudflareAgent = (agent as any).getPeerAgent((env as any).CLOUDFLARE_AGENT);
const result = await cloudflareAgent.agenticSearch(rawQuestion);
const docs = result?.docsContext ?? null;
```

```typescript
// ❌ WRONG — bypasses CloudflareAgent
import { queryMCP } from '@/ai/mcp/mcp-client';
const result = await queryMCP(env, question, 'MyAgent');
```

```typescript
// ❌ WRONG — double-rewrite (CloudflareAgent.agenticSearch rewrites internally)
const rewritten = await ai.rewriteQuestionForMCP(question);
const result = await cloudflareAgent.agenticSearch(rewritten);
```

### GitHub Search (GithubAgent)

```typescript
// ✅ CORRECT — delegate via getPeerAgent
const githubAgent = (agent as any).getPeerAgent((env as any).GITHUB_AGENT);
const items = await githubAgent.searchRepositories({ query, perPage: 20 });
const codeResults = await githubAgent.searchCode(query, repoContext);
```

```typescript
// ❌ WRONG — bypasses GithubAgent
import { getOctokit } from "@services/octokit/core";
const octokit = await getOctokit(env);
```

---

## Sanctioned Exception

**`src/backend/src/services/planning/babysitter/utils.ts`** calls `queryMCP` directly. This is the **one** sanctioned non-agent call site because the babysitter runs in scheduled-worker context with no Durable Object instance available. The exception is documented inline at the call site. Do NOT copy this pattern into any code path that has access to an agent instance.

---

## Enforcement

Since no ESLint config exists in this project, enforcement is via:

1. **This rule document** — LLM-driven PR reviews must check compliance
2. **Verification greps** — run before merging any PR that touches `src/backend/src/ai/agents/`:

```bash
# Only CloudflareAgent may import MCP client
rg -n "from ['\"]@/ai/mcp/mcp-client" src/backend/src/ai/agents \
| grep -v "chat/CloudflareAgent" | wc -l # must be 0

# Only GithubAgent may import Octokit
rg -n "@octokit|getOctokit|new Octokit" src/backend/src/ai/agents \
| grep -v "backend/GithubAgent" | wc -l # must be 0

# No agent outside CloudflareAgent calls rewriteQuestionForMCP
rg -n "rewriteQuestionForMCP" src/backend/src/ai/agents \
| grep -v "chat/CloudflareAgent" | wc -l # must be 0

# CoordinatorAgent imports no service SDKs
rg -n "from ['\"]@/cloudflare|@/ai/mcp|@octokit|@services" \
src/backend/src/ai/agents/chat/CoordinatorAgent | wc -l # must be 0
```

3. **CI guard script** — `scripts/check-agent-delegation.sh` (fails the build on violations)

---

## Adding New Specialist Surface Area

If your agent needs functionality that a specialist owns:

1. Check if the specialist already exposes a `@callable` method for it
2. If not, **add a new `@callable` method on the specialist first**
3. Consume via `getPeerAgent(env.FOO_AGENT).newMethod(args)` from your agent
4. Wrap in try/catch with graceful degradation (see `GuardrailAgent/methods/cloudflare-docs.ts` for reference)

**Never import the specialist's internal SDK into your agent.** The specialist boundary exists to ensure single-owner maintenance, consistent caching, and centralized error handling.
5 changes: 0 additions & 5 deletions .agent/rules/ai-routing.md

This file was deleted.

14 changes: 0 additions & 14 deletions .agent/rules/ai-rules.md

This file was deleted.

31 changes: 31 additions & 0 deletions .agent/rules/backend-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Backend API & Hono Architecture

## 1. Primary Protocol & Communication
- **Hono RPC (`hc`)**: Use Hono RPC for all API interactions to maintain full-stack type safety.
- **Real-Time Context**: Use WebSockets (via Durable Objects/Agents SDK) and Server-Sent Events (SSE) for long-running workflows or streaming. Return status updates seamlessly to the frontend without persistent DB polling.
- **Type Definitions**: Never redefine backend types on the frontend. Use the exported `AppType`.

## 2. Global Env & Bindings Enforcement
- **Requirement**: `Env` is generated by `wrangler types` and globally exposed. Use `Env` freely in function signatures without relative imports (e.g., `import type { Env } ...` is FORBIDDEN).
- **Forbidden Pattern**: `import { Bindings } from '@utils/hono'` is strictly prohibited. `const app = new Hono<{ Bindings: Env }>()`.

## 3. Pathing & Import Aliases
- **Requirement**: All internal imports MUST use defined path aliases.
- `@/*` -> local `src`
- `@db/*` -> Dizzle data layer
- `@api/*` -> Hono RPC AppType definitions
- `@ui/*` -> Shadcn
- `@shared/*` -> Shared Zod schemas
- **Forbidden Pattern**: Relative paths for cross-library access (`../../../db`).

## 4. Dual-Scope Routing Paradigm
- **Global Routes (`/api/global/*`)**: System-wide components independent of an installation (health, generic user management, webhooks).
- **Repo-Specific Routes (`/api/repos/:owner/:repo/*`)**: Require repository context. Scopes should be strictly enforced at the middleware layer using `githubApp.octokit.rest.apps.getRepoInstallation`.

## 5. Agent Real-Time & Networking
- Agents SDK uses WebSocket upgrades mapping to the orchestrator bindings. Do not rely on legacy non-SDK Durable Object instantiations.
- `platformProxy.configPath` within `astro.config.mjs` must explicitly point to the single unified root `wrangler.jsonc` file.

## 6. Secrets Management
- **Mandate**: ALL backend code MUST retrieve secrets using `getSecret(env, 'SECRET_NAME')` from `@/utils/secrets` instead of directly accessing `env.SECRET_NAME` or `env.SECRET_NAME.get()`.
- **Reasoning**: This provides a unified interface whether the secret is locally bound or coming from the Cloudflare Secrets Store.
6 changes: 0 additions & 6 deletions .agent/rules/cloudflare-standards.md

This file was deleted.

23 changes: 23 additions & 0 deletions .agent/rules/database.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Database & D1 Governance

## 1. Drizzle ORM Mandate & Separation of Concerns
- **Drizzle ORM** is the strict standard for D1 interactions. Raw SQL bindings (`env.DB.prepare().run()`) are FORBIDDEN for application logic.
- **Strict D1 Instance Separation**:
- `DB` (Core App logic, e.g., Agent persistence, sessions). Must be initialized via `getDb(env.DB)`.
- `DB_WEBHOOKS` (Stateless GitHub events, sync history). Must be initialized via `getWebhooksDb(env.DB_WEBHOOKS)`.
- Never cross-contaminate logic or run migrations on the wrong bindings.

## 2. Schema and Migrations
- Schema definitions must reside in `@db/schema.ts` and `@db/schema-webhooks.ts`.
- Migrations MUST be generated via `drizzle-kit` and run via the deployment scripts (`pnpm run migrate:remote`). DO NOT write manual `.sql` migration files.
- `drizzle.config.ts` manages two separate connections depending on the `env` argument.

## 3. Batch API Mandate
- When performing loop-based insertions (e.g., skill tool mappings), use `db.insert().values([...])` with arrays, NOT individual inserts inside a loop.
- For cross-table batch operations, use `env.DB.batch()` to group related inserts into a single round-trip.
- Cascading deletes (`onDelete: 'cascade'`) must be used on FK references to prevent orphaned rows.

## 4. Modular Schema Organization
- Schemas are namespaced by domain under `@db/schemas/{domain}/` (e.g., `agents/`, `logs/`, `github/`).
- Each domain folder has its own `index.ts` barrel export.
- `schema.core.ts` explicitly controls which schemas participate in `drizzle.config.core.ts` migrations (excludes DB_WEBHOOKS-owned tables).
7 changes: 0 additions & 7 deletions .agent/rules/durable-object-agents.md

This file was deleted.

68 changes: 0 additions & 68 deletions .agent/rules/durable_objects.md

This file was deleted.

17 changes: 17 additions & 0 deletions .agent/rules/frontend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Frontend & UI Architecture Status

## 1. Moody Modern Architecture & Shadcn
- **Framework**: Astro (latest) + `@astrojs/react`.
- **Styling**: Tailwind CSS v4 (OKLCH). Default Dark Theme is mandatory (`<html class="dark">`). No light mode toggles unless requested.
- **UI Components**: Shadcn UI (Official) and Shadcn-compatible registries. Replace all raw HTML component mockups with Shadcn equivalents.

## 2. Astro Islands & Hydration
- **Hydration Rules**: All interactive React components must be wrapped as Astro islands (`client:load` or `client:visible`).
- **Routing**: Every page must have a dedicated `.astro` file in `src/pages/` for SSR. Unified monolithic Worker `wrangler.jsonc` platform proxy configuration is mandatory.

## 3. Responsive Design & Layouts
- **Mobile First**: Wrap content in `<div class="container overflow-x-hidden md:px-0 scroll-smooth">` inside the `Layout` template. Use generic Tailwind responsive breakpoints.
- **Header & Navigation**: Keep headers sticky and responsive with full-screen collapsible navigation overlays for mobile.

## 4. Stitch Design System Compliance
- **Directives**: Follow the `DESIGN.md` guidelines created by Stitch. Use the "Strict No-Line Rule" constraints (no 1px borders for containment if forbidden), remove redundant search boxes if unnecessary, and ensure the UI operates under a system-first context (minimal UI clutter).
Loading