Skip to content

Commit 951a823

Browse files
jmbish04claude
andcommitted
Merge origin/main into claude/sentinel-engine
Resolve conflicts from PR #450 architecture restructuring: - Integrate with mountRoutes() pattern in routes/index.ts - Add LearningAgent to ai/agents/exports.ts barrel - Add StitchLoopWorkflow to workflows/exports.ts barrel - Add Sentinel routes to GlobalRoutes.tsx and RepoRoutes.tsx - Add stitch-loop-workflow to wrangler.jsonc workflows array - Add db:auto script to package.json Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2 parents 9a08f9c + 2ff26d0 commit 951a823

1,031 files changed

Lines changed: 212546 additions & 32550 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: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,20 @@
22
trigger: always_on
33
---
44

5-
# 000: BOOTSTRAP & PROTOCOL CHECK
6-
**CRITICAL: Mandatory Pre-flight Check.**
5+
# 000-bootstrap.md: Agent Genesis Directive
76

8-
Before starting any task, you must verify the following from `AGENTS.md`:
7+
## Core Operating Procedure
8+
1. **Initialize Context:** On the first turn of every session, read only `AGENTS.md` at the repo root to understand the system architecture and active specialist agents.
9+
2. **Standardization Protocol:** All implementation must align with the `StandardizationAgent` logic defined in `src/ai/agents/StandardizationAgent.ts`.
10+
3. **Lazy Load Rules:** Do NOT read all files in `.agent/rules/` by default. Instead, identify the relevant rules based on the task (e.g., read `ai-provider-standards.md` only for AI-related tasks).
911

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.
12+
## Environment Constraints
13+
- **Primary IDE:** Google Antigravity.
14+
- **Runtime:** Cloudflare Workers (workerd).
15+
- **Stack:** Hono (API), Astro 6 (Frontend), Drizzle ORM (D1 Data Layer).
16+
- **Architecture:** Unified Worker Assets with Cloudflare AI Gateway routing.
1417

15-
**STOP**: If you have not explicitly read `AGENTS.md` in this session, do so now.
18+
## Code Output Rules
19+
- ALWAYS respond with full end-to-end code for the modified module.
20+
- NEVER use shortcuts or "rest of code" comments.
21+
- Ensure `integer('id').primaryKey({ autoIncrement: true })` is used for all Drizzle primary keys (D1/SQLite standard).

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

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Rule: Dual-Scope Routing Paradigm
2+
3+
## Overview
4+
5+
This application enforces a strict **Dual-Scope Paradigm** for all views and API calls.
6+
Every new route, component, and API endpoint must declare which scope it belongs to.
7+
8+
---
9+
10+
## Scope Definitions
11+
12+
### 🌐 Global Scope
13+
- **URL prefix:** `/` (no `/repos/:owner/:repo` prefix)
14+
- **Purview:** cross-repository; holistic planning; master dashboards; settings
15+
- **Route file:** `src/frontend/src/routes/GlobalRoutes.tsx`
16+
- **API pattern:** `/api/projects`, `/api/global/*`, `/api/tasks`, `/api/settings`
17+
- **Examples:** `/projects`, `/kanban`, `/roadmap`, `/dashboard`, `/chat`, `/workshop`
18+
19+
### 🗂️ Active Workspace (Repo-Specific) Scope
20+
- **URL prefix:** `/repos/:owner/:repo/...`
21+
- **Purview:** strictly confined to a single selected GitHub `owner/repo`
22+
- **Route file:** `src/frontend/src/routes/RepoRoutes.tsx`
23+
- **API pattern:** `/api/repos/:owner/:repo/*`
24+
- **Examples:** `/repos/jmbish04/core-github-api/plan`, `.../prs`, `.../explorer`
25+
26+
---
27+
28+
## Rule 1 — Scope Declaration Before Implementation
29+
30+
**When adding any new view, you MUST first determine its scope:**
31+
32+
```
33+
Is this view useful regardless of which repo is selected?
34+
→ YES → Global Scope → add to GlobalRoutes.tsx
35+
→ NO → Repo Scope → add to RepoRoutes.tsx
36+
```
37+
38+
Never add a route without explicitly declaring its scope in a comment:
39+
```tsx
40+
// SCOPE: GLOBAL — shows PRs across all watched repos
41+
<Route path="/pr-center" element={<PRCommandCenter />} />
42+
43+
// SCOPE: REPO — shows PRs only for the active owner/repo workspace
44+
<Route path="prs" element={<RepoPRs />} />
45+
```
46+
47+
---
48+
49+
## Rule 2 — React Router v6 Relative Paths (MANDATORY)
50+
51+
**Never repeat the parent path in a nested child route.**
52+
53+
```tsx
54+
// ❌ WRONG — resolves to /repos/:owner/:repo/repos/:owner/:repo/plan
55+
<Route path="/repos/:owner/:repo" element={<RepoLayout />}>
56+
<Route path="repos/:owner/:repo/plan" element={<RepoPlan />} />
57+
</Route>
58+
59+
// ✅ CORRECT — resolves to /repos/:owner/:repo/plan
60+
<Route path="/repos/:owner/:repo" element={<RepoLayout />}>
61+
<Route path="plan" element={<RepoPlan />} />
62+
</Route>
63+
```
64+
65+
**Checklist for every child route inside `RepoRoutes.tsx`:**
66+
- [ ] Path does NOT start with `/`
67+
- [ ] Path does NOT contain `repos/:owner/:repo`
68+
- [ ] Path is a relative segment only (e.g., `"plan"`, `"projects/kanban"`)
69+
70+
---
71+
72+
## Rule 3 — Hono API Scope Validation
73+
74+
All Hono router definitions must enforce scope validation with Zod.
75+
76+
### Global API endpoints
77+
```typescript
78+
// src/backend/src/routes/api/global/projects.ts
79+
app.get("/api/projects", zValidator("query", GlobalProjectQuerySchema), handler);
80+
```
81+
82+
### Repo-scoped API endpoints
83+
Every repo-scoped route must validate `owner` and `repo` using a shared Zod schema:
84+
85+
```typescript
86+
// src/backend/src/routes/api/repos/[owner]/[repo]/projects.ts
87+
const RepoParamsSchema = z.object({
88+
owner: z.string().min(1),
89+
repo: z.string().min(1),
90+
});
91+
92+
app.get("/api/repos/:owner/:repo/projects",
93+
zValidator("param", RepoParamsSchema),
94+
async (c) => { /* ... */ }
95+
);
96+
```
97+
98+
**Never** serve repo-scoped data from a global endpoint.
99+
**Never** call a global endpoint from a component inside `RepoRoutes.tsx`.
100+
101+
---
102+
103+
## Rule 4 — File Placement
104+
105+
| Artifact | Global scope | Repo scope |
106+
|---|---|---|
107+
| Route definition | `src/frontend/src/routes/GlobalRoutes.tsx` | `src/frontend/src/routes/RepoRoutes.tsx` |
108+
| View component | `src/frontend/src/views/control/global/` | `src/frontend/src/views/repos/` |
109+
| Hono API handler | `src/backend/src/routes/api/...` | `src/backend/src/routes/api/repos/...` |
110+
| TanStack Query hook | uses `/api/*` | uses `/api/repos/:owner/:repo/*` |
111+
| Context dependency | no repo context needed | must consume `useRepoContext()` |
112+
113+
---
114+
115+
## Rule 5 — App.tsx Is a Composition Layer Only
116+
117+
`App.tsx` must remain a thin provider + route composition layer.
118+
It imports `GlobalRoutes` and `RepoRoutes` and renders them inside `<Routes>`.
119+
**No route definitions belong directly in `App.tsx`.**
120+
121+
```tsx
122+
// ✅ Correct App.tsx pattern
123+
function App() {
124+
return (
125+
<AuthProvider>
126+
<BrowserRouter>
127+
<Routes>
128+
{GlobalRoutes()}
129+
{RepoRoutes()}
130+
</Routes>
131+
</BrowserRouter>
132+
</AuthProvider>
133+
);
134+
}
135+
```

.agent/rules/02-do-abstraction.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Rule: Durable Object Abstraction Pattern
2+
3+
## Context
4+
Our backend architecture standardizes Durable Object interactions into two distinct paradigms: AI Agents and WebSocket Broadcasters. Raw mounting of Durable Objects using `idFromName` and `.get()` causes type ambiguity, routing inconsistencies, and runtime errors.
5+
6+
## Core Directives
7+
8+
### 1. Raw DO Instantiation is Forbidden
9+
- **NEVER** use `namespace.idFromName('name')` or `namespace.get(id)` directly within routing files, utility functions, or workflow handlers.
10+
- **NEVER** instantiate raw `Request` objects targeted at `http://agent/...` without a client utility.
11+
12+
### 2. The Agent Paradigm (HoniClient)
13+
All stateful AI Agents in this system are built using the `honidev` framework.
14+
- **RPC Access**: When you need to interact directly with an agent's internal methods (e.g., `stub.chat()`, `stub.workflowComplete()`), you **MUST** use `HoniClient.getStub()`.
15+
- **HTTP Access**: When you need to send an HTTP request to an agent's internal Hono router, you **MUST** use `HoniClient.fetch()`.
16+
- **Import Path**: `import { HoniClient } from '@utils/honi-client';`
17+
18+
### 3. The Broadcast Paradigm (BroadcastClient)
19+
WebSocket broadcasters (e.g., `ROOM_DO`, `JulesWebhookBroadcaster`) are stateful but are not AI agents.
20+
- **Usage**: When dispatching broadcasts or checking room presence, use the unified `BroadcastClient` utility to construct the request.
21+
22+
## Enforcement
23+
This architectural standard replaces legacy utilities such as `getAgentByName` and `routeAgentRequest`, which have been removed from the codebase. Any attempt to reinvent DO mounting wrappers will be blocked during code review.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Rule: Mobile-First Responsive Design
2+
3+
## Core Directive
4+
All UI generation and modification must adhere to a strict mobile-first responsive design pattern. The application shell (Sidebar) handles its own responsive state, but all internal page views and components must adapt smoothly to smaller viewports.
5+
6+
## 1. Container Widths (Fluid Layouts)
7+
- **NEVER** hardcode fixed pixel widths for layout containers (e.g., do not use `w-[800px]`).
8+
- **ALWAYS** use Tailwind's responsive utility classes such as `w-full`, `max-w-7xl`, or percentage-based widths that scale up on larger breakpoints (e.g., `w-full md:w-1/2`).
9+
10+
## 2. Flex and Grid Layouts
11+
- All grid and flex layouts MUST specify behavior for the base (mobile) breakpoint and scale up using `md:` or `lg:` prefixes.
12+
- **Example:** Use `flex-col md:flex-row` instead of just `flex`.
13+
- **Example:** Use `grid-cols-1 md:grid-cols-3` instead of `grid-cols-3`.
14+
15+
## 3. Data Tables and Wide Elements
16+
- Data tables, grids, and abnormally wide elements MUST be wrapped in an `overflow-x-auto` container.
17+
- This prevents the table from breaking the mobile viewport width, allowing users to scroll horizontally while the rest of the page remains contained.
18+
19+
## 4. Touch Targets
20+
- Ensure buttons, links, and inputs are adequately sized for mobile touch interaction. Do not squish interactive elements.
Lines changed: 64 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,64 @@
1-
# Rule: AI Provider Standards (Antigravity)
2-
3-
## 1. Zod Supremacy
4-
- Every structured AI call (`generateStructuredResponse`, `generateStructuredWithTools`) MUST accept a `z.ZodType<T>` payload.
5-
- Weak interfaces (`any` or `Record<string, unknown>`) are forbidden for output generation.
6-
- Use `zod-to-json-schema` to natively pipe the schema into the payload's `response_format` for supported compat endpoints.
7-
- Always call `schema.parse(rawParsed)` on the final JSON result to guarantee structural integrity.
8-
9-
## 2. Universal File Context
10-
- Any method ending in `*FromFiles` must handle payloads consisting of `FileInput` objects (`{ name, type, data, isBase64 }`).
11-
- Providers with native file processing (e.g., Gemini's `inlineData`) should construct standard multi-part arrays.
12-
- Providers without native large-file limits (e.g., Worker AI) MUST use the transparent Vectorize RAG chunking algorithm if the total string length exceeds 6,000 characters to prevent hitting input limits.
13-
14-
## 3. Jules SDK Integration
15-
- Since Jules operates via long-running chat streams, large structured responses should be handled by getting broad context from Jules, and piping its output into `worker-ai` `generateStructuredResponse` to enforce strict formatting.
16-
- Explicit reasoning and agent orchestration features (`analyzeRepo`, `completeTask`, `createPlan`) should exclusively utilize Jules.
17-
18-
## 4. No Vercel AI SDK
19-
- Under no circumstances will you import `ai` or `@ai-sdk/`. It has been banned due to edge runtime parsing inconsistencies on Workers.
20-
- Use the native `fetch` API against the Cloudflare AI Gateway instead.
1+
# AI Provider Standards
2+
3+
## URL Construction (CRITICAL)
4+
5+
**NEVER** manually construct AI Gateway URLs or append endpoint paths. Use `AIGateway.getBaseUrl()` with the `endpoint` option — it returns the **full URL** ready for `fetch()`.
6+
7+
```typescript
8+
// ✅ CORRECT — endpoint specified, baseUrl is the complete URL
9+
const { baseUrl } = await AIGateway.getBaseUrl(env, { provider: 'openai', endpoint: 'chat' });
10+
const res = await fetch(baseUrl, { ... });
11+
12+
// ✅ CORRECT — raw base for Gemini's custom native path
13+
const { baseUrl } = await AIGateway.getBaseUrl(env, { provider: 'gemini' });
14+
const res = await fetch(`${baseUrl}/v1beta/models/${model}:generateContent`, { ... });
15+
16+
// ❌ FORBIDDEN — manual path appending defeats centralization
17+
const { baseUrl } = await AIGateway.getBaseUrl(env, { provider: 'openai' });
18+
const res = await fetch(`${baseUrl}/v1/chat/completions`, { ... });
19+
```
20+
21+
### Endpoint Options
22+
- `endpoint: 'chat'` → appends `/v1/chat/completions`
23+
- `endpoint: 'models'` → appends `/v1/models`
24+
- No endpoint → raw gateway URL (for Gemini native path only)
25+
26+
## Authentication
27+
28+
- **BYOK Mode** (`AI_GATEWAY_TOKEN` set): Only send `cf-aig-authorization: Bearer {token}`. Do NOT send `Authorization` header — the gateway injects stored provider keys.
29+
- **Direct Mode** (`AI_GATEWAY_TOKEN` absent): Send `Authorization: Bearer {apiKey}` as usual.
30+
31+
## Imports
32+
33+
- **Canonical**: `import { AIGateway } from '@/ai/providers/ai-gateway'`
34+
- **Legacy re-export**: `@/ai/utils/ai-gateway` still works but is deprecated
35+
36+
## Logging
37+
38+
All AI providers MUST use the `Logger` class from `src/lib/logger.ts` (NOT raw `console.log`/`console.error`).
39+
40+
> See `.agent/rules/traceability-logging.md` for full enforcement rules.
41+
42+
Standard source overrides:
43+
44+
| Provider | Source Override |
45+
|----------|----------------|
46+
| AI Gateway | `'AIGateway'` |
47+
| Workers AI | `'WorkerAI'` |
48+
| OpenAI | `'OpenAI'` |
49+
| Anthropic | `'Anthropic'` |
50+
| Gemini | `'Gemini'` |
51+
| Router | `'AIRouter'` |
52+
| Health | `'GatewayHealth'` |
53+
| Diagnostician | `'Diagnostician'` |
54+
55+
## Provider Files
56+
57+
| Provider | File | Status |
58+
|----------|------|--------|
59+
| Gateway | `src/ai/providers/ai-gateway.ts` | Source of truth |
60+
| Config | `src/ai/providers/config.ts` | Model resolution only — NO gateway URLs |
61+
| Workers AI | `src/ai/providers/worker-ai.ts` | Uses gateway client |
62+
| OpenAI | `src/ai/providers/openai.ts` | Uses gateway client |
63+
| Anthropic | `src/ai/providers/anthropic.ts` | Uses gateway client |
64+
| Gemini | `src/ai/providers/gemini.ts` | Uses native client via `getBaseUrl()` |

.agent/rules/ai-providers.md

Lines changed: 0 additions & 12 deletions
This file was deleted.

.agent/rules/alerts.md

Lines changed: 0 additions & 16 deletions
This file was deleted.

.agent/rules/cloudflare-deployments.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,9 @@ When operating on Cloudflare Workers that exceed 5MB uncompressed:
88
2. Never rely on the default `wrangler deploy` CLI command directly if timeouts occur; wrap it in a Node script that overrides the `undici` global dispatcher timeout to at least 120,000ms.
99
3. Inject `NODE_OPTIONS=--max-old-space-size=8192` to prevent heap exhaustion during `esbuild` minification phases.
1010
4. Ensure `compatibility_flags = ["nodejs_compat"]` is set and `node_compat = false` is enforced to prevent polyfill bloat.
11+
12+
## Rule: Cloudflare Bindings Philosophy
13+
14+
- **Naming Convention:** When interacting with the Cloudflare API, be aware that `script_name` refers to the `worker_name` defined in `wrangler.jsonc` or `wrangler.toml`.
15+
- **Create & Patch Only:** The automated bindings manager is designed to **provision** resources (e.g., creating a D1 database) and **patch** the repository's `wrangler.jsonc` via a GitHub PR.
16+
- **No Direct Attachment:** Do **NOT** attempt to attach bindings directly to the Worker script via the Cloudflare API. The binding manager stops at PR creation, allowing the native CI/CD deployment pipeline to handle the actual attachment upon merge.

.agent/rules/cloudflare-stack.md

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)