Skip to content

Commit 2b96528

Browse files
committed
chore: merge jules-bug-smash into main - rescue all staged work
2 parents 3c2d2a6 + 3baf08a commit 2b96528

1,373 files changed

Lines changed: 486683 additions & 11182 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.agent/rules/000-bootstrap.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
trigger: always_on
3+
---
4+
5+
# 000: BOOTSTRAP & PROTOCOL CHECK
6+
**CRITICAL: Mandatory Pre-flight Check.**
7+
8+
Before starting any task, you must verify the following from `AGENTS.md`:
9+
10+
1. **Workspace Context**: Identify if you are working in `frontend` or `container`.
11+
2. **Installation Protocol**: You MUST use `pnpm add <pkg> --filter <package>` from the root. Never install at root without `-w`.
12+
3. **SDK Enforcement**: Verify you are using `@google/genai` (New SDK) and NOT `@google/generative-ai` (Legacy).
13+
4. **Backend/Frontend Sync**: If modifying Drizzle schemas, ensure `frontend/src/db` is the target as per the "Schema Sync" section.
14+
15+
**STOP**: If you have not explicitly read `AGENTS.md` in this session, do so now.

.agent/rules/000-core-directive.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
trigger: always_on
3+
---
4+
5+
# CORE DIRECTIVE: PROTOCOL ENFORCEMENT
6+
7+
**CRITICAL:** Before performing ANY task, you MUST synchronize your internal state with the project's specific constraints.
8+
9+
1. **Mandatory Documentation Review:**
10+
- You MUST read the `AGENTS.md` file in the root directory. It contains the workspace architecture and pnpm protocols.
11+
- You MUST read ALL files in the `.agent/rules/` directory to understand the coding standards (Drizzle, Shadcn, Astro).
12+
13+
2. **Workspace Verification:**
14+
- Confirm if the task involves the `frontend` or `root/backend`.
15+
- Apply the `pnpm --filter` protocol defined in `AGENTS.md`.
16+
17+
3. **Validation Step:**
18+
- If you have not read `AGENTS.md` in the current session, STOP and read it now.
19+
- Failure to follow the `pnpm` installation rules defined in `AGENTS.md` will result in environment corruption.
20+
21+
**DO NOT proceed with code generation until you have confirmed the pnpm workspace structure.**

.agent/rules/AGENT_GOVERNANCE.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
trigger: always_on
3+
---
4+
5+
# AGENT & WORKFLOW GOVERNANCE
6+
7+
## 1. The Manager-Worker Pattern
8+
* **Rule**: Agents (`extends Agent`) **MUST NOT** perform long-running blocking tasks (>10s).
9+
* **Rule**: Long-running tasks (Cloning, Vectorizing, Scraping) **MUST** be offloaded to Cloudflare Workflows (`extends WorkflowEntrypoint`).
10+
* **Rule**: Agents act as "Managers" (State/Decision); Workflows act as "Workers" (Execution).
11+
12+
## 2. Tool Integration (MCP)
13+
* **Constraint**: Do NOT import Node.js-exclusive packages (e.g., `fs`, `child_process`) directly into the Worker.
14+
* **Strategy**: Adapt the *logic* of official tools into the Agents SDK `sql`-backed state or stateless `Octokit` calls.
15+
* **Schema**: All tools must strictly define Zod schemas for the Agents SDK to generate valid MCP interfaces.
16+
17+
## 3. Sandbox Usage
18+
* **Lifecycle**: Sandboxes are ephemeral. Data must be extracted (to R2, D1, or Vectorize) before the `step` completes.
19+
* **Security**: Never pass raw user input directly to `sandbox.exec()`. Sanitize command arguments.
20+
21+
## 4. Vectorization & RAG
22+
* **Chunking**: Code must be chunked (e.g., by function/class) before embedding.
23+
* **Model**: Use `@cf/baai/bge-large-en-v1.5` for embeddings (1024 dimensions).
24+
* **Metadata**: Upserts MUST include `{ repo, filepath, commit_sha }`.

.agent/rules/HEALTH_GOVERNANCE.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Health Check Governance
2+
3+
## Rule: Every New Module Must Register a Health Check
4+
5+
When adding a new domain module under `backend/src/`, you **MUST**:
6+
7+
1. Create a `health.ts` file co-located with the module
8+
2. Export `checkHealth(env: Env): Promise<HealthStepResult>`
9+
3. Register the check in `backend/src/health/coordinator.ts``CODE_CHECKS` array
10+
4. Assign a `HealthCategory` from the union in `backend/src/health/types.ts`
11+
12+
## Rule: Dynamic Tests via D1
13+
14+
Runtime endpoint monitoring uses the `health_test_definitions` table. CRUD is available at:
15+
16+
- `GET /api/health/tests` — list all
17+
- `POST /api/health/tests` — create (Zod-validated)
18+
- `DELETE /api/health/tests/:id` — remove
19+
20+
## Rule: AI Remediation
21+
22+
Failed health checks automatically receive AI-powered remediation hints via `analyzeFailure()`. These are stored in the `ai_suggestion` column of `health_results`.
23+
24+
## Rule: Cron Schedule
25+
26+
Health suite runs weekly via cron `0 3 * * 0` (Sundays 3AM UTC).
27+
On-demand runs are available via `POST /api/health/run`.
28+
29+
## Rule: Frontend Sync
30+
31+
The frontend at `/health` **must** display all categories defined in `CATEGORY_META` in `Health.tsx`.
32+
When adding a new `HealthCategory` to `types.ts`, also add an entry to the frontend registry.

.agent/rules/actions-llm.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# GitHub Actions LLM Rules
2+
3+
## 1. Resilience
4+
5+
- Always use `response_format={"type": "json_object"}` when interacting with `gpt-oss-120b` for data extraction.
6+
- Implement `try/except` blocks around the LLM call to prevent a single bad generation from crashing the CI pipeline.
7+
8+
## 2. Dependency Management
9+
10+
- Keep scripts self-contained within the YAML (using `cat <<EOF`) for simple tasks, or use a dedicated `scripts/` folder for complex ones.
11+
- Prioritize standard libraries (`openai`, `pydantic`) over experimental ones to ensure stability in the CI runner.

.agent/rules/agent-registry.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Rule: Agent Registry and Dynamic UI
2+
3+
## 1. Dynamic UI Consumption
4+
5+
- Frontend agent selectors, wizards, and sidebars (e.g., `AgentSidebar.tsx`) **MUST NEVER** hardcode the list of available specialist agents.
6+
- All dynamic agent discovery must occur via the `GET /api/agents/specialists` REST endpoint. This ensures the backend remains the single source of truth for agent capabilities, routing, and availability.
7+
8+
## 2. The Specialist Pattern
9+
10+
- Avoid creating numerous bespoke subclasses of `HonoBaseAgent` (e.g., `DataAgent`, `UXAgent`, `SREAgent`) unless they require fundamentally distinct toolsets or event lifecycles.
11+
- Default to using **ONE** flexible `SpecialistAgent` class.
12+
- Dictate the specific persona dynamically at runtime by overriding the `systemPrompt` or passing a `specialty` configuration parameter when the frontend initiates the session.
13+
- **Why?** This prevents sprawling class files, keeps the agent execution logic DRY, and enables the system to spin up arbitrary expert subsets without code deployments.
14+
15+
## 3. Plan Generation Output
16+
17+
- The ultimate goal of a Workshop or Consultation flow is actionable output.
18+
- Specialist Agents should be equipped with a `save_plan(plan: JSON)` tool.
19+
- When the agent and user align on a roadmap, the agent must invoke `save_plan` to persist the structured JSON to the `projects`, `plans`, or `todos` table via Drizzle.
20+
- The UI should then react to this database mutation (e.g., by advancing the Wizard, redirecting to the Kanban board, or pushing a toast).

.agent/rules/ai-providers.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Protocol: AI Provider Routing & Resolution
2+
3+
**MANDATORY IMPORT PATH**: Agents must _always and exclusively_ import AI functions from `@/ai/providers`.
4+
**FORBIDDEN IMPORTS**: It is _never_ acceptable to import directly from specific provider files (e.g., `ai/providers/openai`, `ai/providers/gemini`) or the index file explicitly (e.g., `ai/providers/index`).
5+
6+
**FUNCTION USAGE**: When using functions like `generateText`, `generateStructuredResponse`, etc., the agent should specify the `provider` and `model` arguments when known.
7+
8+
**FALLBACK BEHAVIOR**:
9+
10+
- If no provider or model is provided by the caller, the system relies on the `index.ts` routing to default to `worker-ai`, which then utilizes its internal business logic to select the correct fallback model.
11+
- Similarly, if a provider is specified but no model is provided, the specific provider module's logic determines the default model.
12+
- Agents should not hardcode default models unless explicitly required by the business logic.

.agent/rules/ai-routing.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# AI Routing & Fallback Rules
2+
3+
- **Silent Failures:** Never allow a third-party AI provider failure to crash the request if a `worker-ai` equivalent model can handle the prompt.
4+
- **Type Safety:** Do not alter the return types (`string`, `T`) of the core generation functions to include metadata. Always use the `onFallback` callback mechanism in `AIOptions` to bubble up execution state.
5+
- **Observability:** Every fallback event must be aggressively logged to D1 to track provider reliability and API Gateway latency over time.

.agent/rules/ai-rules.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Rule: AI Provider & Structured Responses
2+
3+
## 1. Structured Output Mandate
4+
5+
- **CRYSTAL CLEAR RULE**: ANYTIME the AI model is being instructed to respond with a structured response (JSON), you **MUST** use `generateStructuredResponse` or `generateStructuredWithTools` exported from `@/ai/providers`.
6+
- **FORBIDDEN**: Do not rely on native Agent SDK schemas (e.g. `outputType: MySchema as any` in `@openai/agents`). These frequently fail to map correctly through the Cloudflare AI Gateway or result in brittle string parsing.
7+
8+
## 2. The Extraction Pattern (Agents with Tools)
9+
10+
If you are running an autonomous Agent that requires tool usage (e.g., `HealthDiagnostician` or `ResearchAgent`):
11+
12+
1. Configure the Agent to output standard text/markdown (`outputType` must NOT be explicitly defined).
13+
2. Await the Agent's `finalOutput` inside the execution loop.
14+
3. Pass that string into `generateStructuredResponse` along with your Zod schema (converted via `zodToJsonSchema`) to strictly extract and type the final JSON object. This ensures Gateway compatibility while guaranteeing Zod-verified JSON.

.agent/rules/alerts-standards.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Alerts Standards
2+
3+
## 1. The `createAlert()` Contract
4+
5+
Every new feature that may fail, produce notable events, or require user attention **MUST** emit alerts using the canonical `createAlert()` function:
6+
7+
```typescript
8+
import { createAlert } from "@alerts";
9+
10+
await createAlert(env, {
11+
type: "deployment", // AlertType: health | webhook | security | deployment | agent | info
12+
severity: "error", // AlertSeverity: info | warning | error | critical
13+
title: "Deploy failed",
14+
description: "Wrangler exited with code 1. Check logs.",
15+
link_url: "/webhooks", // Optional deep-link (relative path)
16+
process_origin: "DeployWorkflow", // Human-readable origin
17+
});
18+
```
19+
20+
`createAlert()` is fire-and-forget: it never throws, never blocks the main thread, and auto-gates based on `ALERTS_CONFIG` in KV.
21+
22+
## 2. When to Emit Alerts
23+
24+
| Scenario | Type | Severity |
25+
| ----------------------------------- | ------------ | --------------------- |
26+
| Health check failure | `health` | `error` or `critical` |
27+
| Webhook delivery failure (repeated) | `webhook` | `warning` |
28+
| Detected secret leak | `security` | `critical` |
29+
| Worker deploy failure | `deployment` | `error` |
30+
| Agent task failure after retries | `agent` | `error` |
31+
| Informational system event | `info` | `info` |
32+
33+
Do **NOT** alert on:
34+
35+
- Expected/transient 4xx responses
36+
- Individual tool-call retries (only alert on final failure)
37+
- Debug or verbose logs (use `console.log` / `@logging` for those)
38+
39+
## 3. Config-Gated Alerts
40+
41+
`createAlert()` reads `ALERTS_CONFIG` from `KV_CONFIGS` at emit time. If a type is disabled or the master switch is off, the alert is dropped silently. You do not need to check the config yourself — the service handles it.
42+
43+
## 4. Path Alias
44+
45+
Always use `@alerts` — never use a relative import:
46+
47+
```typescript
48+
// ✅ Correct
49+
import { createAlert } from "@alerts";
50+
51+
// ❌ Wrong
52+
import { createAlert } from "../../alerts";
53+
```
54+
55+
## 5. New Alert Types
56+
57+
If you need a new alert type (beyond the 6 built-in), you must:
58+
59+
1. Add it to `ALERT_TYPES` in `backend/src/db/schemas/app/alerts.ts`
60+
2. Add it to `AlertTypeFlags` in `backend/src/alerts/config.ts`
61+
3. Add its `TYPE_META` entry in `AlertTray.tsx` and `Alerts.tsx`
62+
4. Run `pnpm drizzle-kit generate` if schema changed

0 commit comments

Comments
 (0)