feat: complete a2host architecture, backend, zero-build frontend, and IEEE docs
This commit is contained in:
commit
ab65271a58
9
.agents/mcp_config.json
Normal file
9
.agents/mcp_config.json
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"spline": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "spline-mcp-server"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
259
.agents/skills/3d-web-experience/SKILL.md
Normal file
259
.agents/skills/3d-web-experience/SKILL.md
Normal file
@ -0,0 +1,259 @@
|
|||||||
|
---
|
||||||
|
name: 3d-web-experience
|
||||||
|
description: "Expert in building 3D experiences for the web - Three.js, React Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D portfolios, immersive websites, and bringing ..."
|
||||||
|
risk: unknown
|
||||||
|
source: "vibeship-spawner-skills (Apache 2.0)"
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# 3D Web Experience
|
||||||
|
|
||||||
|
**Role**: 3D Web Experience Architect
|
||||||
|
|
||||||
|
You bring the third dimension to the web. You know when 3D enhances
|
||||||
|
and when it's just showing off. You balance visual impact with
|
||||||
|
performance. You make 3D accessible to users who've never touched
|
||||||
|
a 3D app. You create moments of wonder without sacrificing usability.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
- Three.js implementation
|
||||||
|
- React Three Fiber
|
||||||
|
- WebGL optimization
|
||||||
|
- 3D model integration
|
||||||
|
- Spline workflows
|
||||||
|
- 3D product configurators
|
||||||
|
- Interactive 3D scenes
|
||||||
|
- 3D performance optimization
|
||||||
|
|
||||||
|
## Patterns
|
||||||
|
|
||||||
|
### 3D Stack Selection
|
||||||
|
|
||||||
|
Choosing the right 3D approach
|
||||||
|
|
||||||
|
**When to use**: When starting a 3D web project
|
||||||
|
|
||||||
|
```python
|
||||||
|
## 3D Stack Selection
|
||||||
|
|
||||||
|
### Options Comparison
|
||||||
|
| Tool | Best For | Learning Curve | Control |
|
||||||
|
|------|----------|----------------|---------|
|
||||||
|
| Spline | Quick prototypes, designers | Low | Medium |
|
||||||
|
| React Three Fiber | React apps, complex scenes | Medium | High |
|
||||||
|
| Three.js vanilla | Max control, non-React | High | Maximum |
|
||||||
|
| Babylon.js | Games, heavy 3D | High | Maximum |
|
||||||
|
|
||||||
|
### Decision Tree
|
||||||
|
```
|
||||||
|
Need quick 3D element?
|
||||||
|
└── Yes → Spline
|
||||||
|
└── No → Continue
|
||||||
|
|
||||||
|
Using React?
|
||||||
|
└── Yes → React Three Fiber
|
||||||
|
└── No → Continue
|
||||||
|
|
||||||
|
Need max performance/control?
|
||||||
|
└── Yes → Three.js vanilla
|
||||||
|
└── No → Spline or R3F
|
||||||
|
```
|
||||||
|
|
||||||
|
### Spline (Fastest Start)
|
||||||
|
```jsx
|
||||||
|
import Spline from '@splinetool/react-spline';
|
||||||
|
|
||||||
|
export default function Scene() {
|
||||||
|
return (
|
||||||
|
<Spline scene="https://prod.spline.design/xxx/scene.splinecode" />
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### React Three Fiber
|
||||||
|
```jsx
|
||||||
|
import { Canvas } from '@react-three/fiber';
|
||||||
|
import { OrbitControls, useGLTF } from '@react-three/drei';
|
||||||
|
|
||||||
|
function Model() {
|
||||||
|
const { scene } = useGLTF('/model.glb');
|
||||||
|
return <primitive object={scene} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Scene() {
|
||||||
|
return (
|
||||||
|
<Canvas>
|
||||||
|
<ambientLight />
|
||||||
|
<Model />
|
||||||
|
<OrbitControls />
|
||||||
|
</Canvas>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3D Model Pipeline
|
||||||
|
|
||||||
|
Getting models web-ready
|
||||||
|
|
||||||
|
**When to use**: When preparing 3D assets
|
||||||
|
|
||||||
|
```python
|
||||||
|
## 3D Model Pipeline
|
||||||
|
|
||||||
|
### Format Selection
|
||||||
|
| Format | Use Case | Size |
|
||||||
|
|--------|----------|------|
|
||||||
|
| GLB/GLTF | Standard web 3D | Smallest |
|
||||||
|
| FBX | From 3D software | Large |
|
||||||
|
| OBJ | Simple meshes | Medium |
|
||||||
|
| USDZ | Apple AR | Medium |
|
||||||
|
|
||||||
|
### Optimization Pipeline
|
||||||
|
```
|
||||||
|
1. Model in Blender/etc
|
||||||
|
2. Reduce poly count (< 100K for web)
|
||||||
|
3. Bake textures (combine materials)
|
||||||
|
4. Export as GLB
|
||||||
|
5. Compress with gltf-transform
|
||||||
|
6. Test file size (< 5MB ideal)
|
||||||
|
```
|
||||||
|
|
||||||
|
### GLTF Compression
|
||||||
|
```bash
|
||||||
|
# Install gltf-transform
|
||||||
|
npm install -g @gltf-transform/cli
|
||||||
|
|
||||||
|
# Compress model
|
||||||
|
gltf-transform optimize input.glb output.glb \
|
||||||
|
--compress draco \
|
||||||
|
--texture-compress webp
|
||||||
|
```
|
||||||
|
|
||||||
|
### Loading in R3F
|
||||||
|
```jsx
|
||||||
|
import { useGLTF, useProgress, Html } from '@react-three/drei';
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
|
function Loader() {
|
||||||
|
const { progress } = useProgress();
|
||||||
|
return <Html center>{progress.toFixed(0)}%</Html>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Scene() {
|
||||||
|
return (
|
||||||
|
<Canvas>
|
||||||
|
<Suspense fallback={<Loader />}>
|
||||||
|
<Model />
|
||||||
|
</Suspense>
|
||||||
|
</Canvas>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scroll-Driven 3D
|
||||||
|
|
||||||
|
3D that responds to scroll
|
||||||
|
|
||||||
|
**When to use**: When integrating 3D with scroll
|
||||||
|
|
||||||
|
```python
|
||||||
|
## Scroll-Driven 3D
|
||||||
|
|
||||||
|
### R3F + Scroll Controls
|
||||||
|
```jsx
|
||||||
|
import { ScrollControls, useScroll } from '@react-three/drei';
|
||||||
|
import { useFrame } from '@react-three/fiber';
|
||||||
|
|
||||||
|
function RotatingModel() {
|
||||||
|
const scroll = useScroll();
|
||||||
|
const ref = useRef();
|
||||||
|
|
||||||
|
useFrame(() => {
|
||||||
|
// Rotate based on scroll position
|
||||||
|
ref.current.rotation.y = scroll.offset * Math.PI * 2;
|
||||||
|
});
|
||||||
|
|
||||||
|
return <mesh ref={ref}>...</mesh>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Scene() {
|
||||||
|
return (
|
||||||
|
<Canvas>
|
||||||
|
<ScrollControls pages={3}>
|
||||||
|
<RotatingModel />
|
||||||
|
</ScrollControls>
|
||||||
|
</Canvas>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### GSAP + Three.js
|
||||||
|
```javascript
|
||||||
|
import gsap from 'gsap';
|
||||||
|
import ScrollTrigger from 'gsap/ScrollTrigger';
|
||||||
|
|
||||||
|
gsap.to(camera.position, {
|
||||||
|
scrollTrigger: {
|
||||||
|
trigger: '.section',
|
||||||
|
scrub: true,
|
||||||
|
},
|
||||||
|
z: 5,
|
||||||
|
y: 2,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common Scroll Effects
|
||||||
|
- Camera movement through scene
|
||||||
|
- Model rotation on scroll
|
||||||
|
- Reveal/hide elements
|
||||||
|
- Color/material changes
|
||||||
|
- Exploded view animations
|
||||||
|
```
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
|
||||||
|
### ❌ 3D For 3D's Sake
|
||||||
|
|
||||||
|
**Why bad**: Slows down the site.
|
||||||
|
Confuses users.
|
||||||
|
Battery drain on mobile.
|
||||||
|
Doesn't help conversion.
|
||||||
|
|
||||||
|
**Instead**: 3D should serve a purpose.
|
||||||
|
Product visualization = good.
|
||||||
|
Random floating shapes = probably not.
|
||||||
|
Ask: would an image work?
|
||||||
|
|
||||||
|
### ❌ Desktop-Only 3D
|
||||||
|
|
||||||
|
**Why bad**: Most traffic is mobile.
|
||||||
|
Kills battery.
|
||||||
|
Crashes on low-end devices.
|
||||||
|
Frustrated users.
|
||||||
|
|
||||||
|
**Instead**: Test on real mobile devices.
|
||||||
|
Reduce quality on mobile.
|
||||||
|
Provide static fallback.
|
||||||
|
Consider disabling 3D on low-end.
|
||||||
|
|
||||||
|
### ❌ No Loading State
|
||||||
|
|
||||||
|
**Why bad**: Users think it's broken.
|
||||||
|
High bounce rate.
|
||||||
|
3D takes time to load.
|
||||||
|
Bad first impression.
|
||||||
|
|
||||||
|
**Instead**: Loading progress indicator.
|
||||||
|
Skeleton/placeholder.
|
||||||
|
Load 3D after page is interactive.
|
||||||
|
Optimize model size.
|
||||||
|
|
||||||
|
## Related Skills
|
||||||
|
|
||||||
|
Works well with: `scroll-experience`, `interactive-portfolio`, `frontend`, `landing-page-design`
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
This skill is applicable to execute the workflow or actions described in the overview.
|
||||||
785
.agents/skills/cpic-ui-design-and-templates/SKILL.md
Normal file
785
.agents/skills/cpic-ui-design-and-templates/SKILL.md
Normal file
@ -0,0 +1,785 @@
|
|||||||
|
---
|
||||||
|
name: cpic-ui-design-and-templates
|
||||||
|
description: >-
|
||||||
|
Definitive design system, color palette, responsive screen architecture (mobile to ultrawide),
|
||||||
|
glassmorphism tokens, and page templates for CPIC - Conecta (SENA Intranet). Use when creating,
|
||||||
|
refactoring, styling, or structuring pages, layouts, sidebars, modals, chat interfaces,
|
||||||
|
tables, or dashboards.
|
||||||
|
---
|
||||||
|
|
||||||
|
# CPIC - Conecta: Master UI Design System & Page Templates
|
||||||
|
|
||||||
|
Guía canónica y definitiva del sistema de diseño visual, paleta cromática, arquitectura responsiva multi-pantalla y plantillas estructurales para el proyecto **Chatbot Intranet CPIC ("Conecta")** del **SENA (Centro de Procesos Industriales y Construcción)**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Identidad Visual y Principios de Diseño
|
||||||
|
|
||||||
|
El sistema visual de CPIC combina **elegancia institucional del SENA** con una estética **Luxury Glassmorphism** moderna (estilo Linear / Apple / Vercel), optimizada para modo oscuro por defecto con soporte completo para modo claro y accesibilidad WCAG 2.1 AA/AAA.
|
||||||
|
|
||||||
|
### Pilares Fundamentales:
|
||||||
|
1. **Verde Institucional SENA & Acentos Lime**: Verde esmeralda institucional (`#39A900`) y lima eléctrica (`#00FF00` / `#a3e635`) sobre fondos oscuros o alabastro.
|
||||||
|
2. **Elevación Glassmorphism en 3 Capas (3-Tier Glass Elevation)**: Jerarquía de profundidad mediante `backdrop-blur`, transparencias finas, bordes sutiles de 1px e iluminaciones interiores (`inset 0 1px 0`).
|
||||||
|
3. **Arquitectura Responsiva Mobile-First Real**: Estabilidad con `100dvh`, navegación off-canvas en pantallas táctiles, chips deslizables, tablas con scroll horizontal y modales convertibles a hojas inferiores (*bottom-sheets*).
|
||||||
|
4. **Micro-interacciones Táctiles y Fluidas**: Escalamiento sutil (`hover:scale-[1.01]`, `active:scale-[0.98]`), anillos de foco de alto contraste y barras de desplazamiento personalizadas de 5px.
|
||||||
|
5. **Inclusión y Accesibilidad Universal**: Cumplimiento WCAG, fuente OpenDyslexic, modo alto contraste, filtros para daltonismo y docks dedicados a Lengua de Señas Colombiana (LSC).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Paleta de Colores y Tokens de Diseño
|
||||||
|
|
||||||
|
### 2.1. Acentos Institucionales SENA & Lime
|
||||||
|
|
||||||
|
| Token / Variable | Hex / Valor | Uso Principal | Modo Oscuro | Modo Claro |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **SENA Verde Oficial** | `#39A900` | Marca institucional, títulos clave, viñetas activas | `#39A900` / `#50e93b` | `#39A900` / `#166534` |
|
||||||
|
| `--color-lime` | `#00FF00` | Acento primario, foco de alto impacto, luces de neón | `#00FF00` | `#16a34a` / `#15803d` |
|
||||||
|
| `--color-lime-dark` | `#00CC00` | Estados hover, bordes de acento | `#00CC00` | `#15803d` |
|
||||||
|
| `--color-lime-deep` | `#009900` | Texto de alto contraste en fondos claros | `#52ff52` | `#009900` |
|
||||||
|
| `--color-lime-light` | `#66FF66` | Anillos de loaders, bordes secundarios | `#66FF66` | `#22c55e` |
|
||||||
|
| `--color-lime-soft` | `#B3FFB3` | Fondos de selección suaves | `rgba(179,255,179,0.15)` | `rgba(179,255,179,0.3)` |
|
||||||
|
| `--color-lime-pale` | `#E6FFE6` | Resaltados de advertencias y tablas | `rgba(230,255,230,0.08)`| `#e6ffe6` |
|
||||||
|
| **Tailwind Lime 400** | `#a3e635` | Textos de acento en dark mode (`text-lime`) | `#a3e635` | `#15803d` |
|
||||||
|
| **Tailwind Lime 500** | `#84cc16` | Sombras resplandecientes, scrollbars activas | `#84cc16` | `#16a34a` |
|
||||||
|
| **Emerald 800** | `#166534` | Encabezados Markdown en modo claro | `#86efac` | `#166534` |
|
||||||
|
| **Emerald 700** | `#15803d` | Enlaces y botones de texto en modo claro | `#4ade80` | `#15803d` |
|
||||||
|
|
||||||
|
### 2.2. Sistema de Elevación Glassmorphism (3-Tier Glass)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ TIER 0: App Base Wallpaper (/background.webp + velo oscuro) │
|
||||||
|
│ ┌──────────────────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ TIER 1: Ambient Glow Orbs (blur-[120px] de Lime y Emerald) │ │
|
||||||
|
│ │ ┌────────────────────────────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ TIER 2: Contenedores Estructurales (Cards, Sidebars, Main) │ │ │
|
||||||
|
│ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │
|
||||||
|
│ │ │ │ TIER 3: Flotantes (Modales, Popovers, Toasts, Docks) │ │ │ │
|
||||||
|
│ │ │ └──────────────────────────────────────────────────────┘ │ │ │
|
||||||
|
│ │ └────────────────────────────────────────────────────────────┘ │ │
|
||||||
|
│ └──────────────────────────────────────────────────────────────────┘ │
|
||||||
|
└────────────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Tier 0 — Lienzo Base:
|
||||||
|
- **Fondo General**: `background-image: var(--app-bg-image, url('/background.webp'))` con `background-size: cover; background-position: center; background-attachment: fixed;`.
|
||||||
|
- **Velo de Profundidad**: `body::before { background: rgba(0, 0, 0, 0.2); }`.
|
||||||
|
- **Fondo Fallback Dark**: `#0a0a0a` / `#0a160a`.
|
||||||
|
- **Fondo Fallback Light**: `#f8fafc` (Slate 50) / `#f3f4f6`.
|
||||||
|
|
||||||
|
#### Tier 1 — Ambient Glow Orbs:
|
||||||
|
Orbes desenfocados que crean atmósfera tridimensional detrás del contenido:
|
||||||
|
```jsx
|
||||||
|
<div className="absolute inset-0 pointer-events-none overflow-hidden -z-10" aria-hidden="true">
|
||||||
|
<div className="absolute top-10 left-1/4 w-96 h-96 bg-lime-500/8 dark:bg-lime-500/10 rounded-full blur-[120px]" />
|
||||||
|
<div className="absolute bottom-20 right-1/4 w-96 h-96 bg-emerald-500/6 dark:bg-emerald-500/8 rounded-full blur-[140px]" />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Tier 2 — Tarjetas Estructurales y Barras de Navegación:
|
||||||
|
- **Modo Oscuro**:
|
||||||
|
```css
|
||||||
|
bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-white/10
|
||||||
|
shadow-[0_4px_24px_rgba(0,0,0,0.3),inset_0_1px_0_rgba(255,255,255,0.08)]
|
||||||
|
```
|
||||||
|
- **Modo Claro**:
|
||||||
|
```css
|
||||||
|
bg-white/85 backdrop-blur-2xl border border-black/8
|
||||||
|
shadow-[0_4px_24px_rgba(0,0,0,0.06),inset_0_1px_0_rgba(255,255,255,0.7)]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Tier 3 — Elementos Flotantes, Modales, Menús y Toasts:
|
||||||
|
- **Modo Oscuro**:
|
||||||
|
```css
|
||||||
|
bg-[rgba(15,28,15,0.94)] backdrop-blur-3xl border border-lime/25
|
||||||
|
shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_24px_rgba(132,204,22,0.12)]
|
||||||
|
```
|
||||||
|
- **Modo Claro**:
|
||||||
|
```css
|
||||||
|
bg-white/95 backdrop-blur-3xl border border-slate-200/90
|
||||||
|
shadow-[0_16px_48px_rgba(0,0,0,0.15)]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3. Jerarquía Tipográfica y Colores de Texto
|
||||||
|
|
||||||
|
- **Fuente Primaria**: `'Segoe UI', 'Poppins', 'Roboto', system-ui, sans-serif`.
|
||||||
|
- **Fuente de Accesibilidad**: `'OpenDyslexic', 'Comic Sans MS', cursive`.
|
||||||
|
- **Textos en Modo Oscuro**:
|
||||||
|
- Títulos principales (h1/h2): `#ffffff` con `tracking-tight`.
|
||||||
|
- Títulos de sección: `#86efac` o `#a3e635`.
|
||||||
|
- Cuerpo principal: `rgba(255, 255, 255, 0.92)` (`text-white/90`).
|
||||||
|
- Texto secundario / metadatos: `rgba(255, 255, 255, 0.65)` (`text-white/65`).
|
||||||
|
- Texto atenuado / timestamps: `rgba(255, 255, 255, 0.40)` (`text-white/40`).
|
||||||
|
- **Textos en Modo Claro**:
|
||||||
|
- Títulos principales (h1/h2): `#0f172a` (Slate 900) o `#166534` (Emerald 800).
|
||||||
|
- Cuerpo principal: `#1f2937` (Gray 800).
|
||||||
|
- Texto secundario: `#4b5563` (Gray 600).
|
||||||
|
- Texto atenuado: `#9ca3af` (Gray 400).
|
||||||
|
|
||||||
|
### 2.4. Badges de Roles y Estados Semánticos
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
// Superadmin / Root
|
||||||
|
<span className="bg-red-500/10 text-red-600 dark:text-red-400 border border-red-500/25 px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wide">
|
||||||
|
ROOT
|
||||||
|
</span>
|
||||||
|
|
||||||
|
// Administrador
|
||||||
|
<span className="bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/25 px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wide">
|
||||||
|
ADMIN
|
||||||
|
</span>
|
||||||
|
|
||||||
|
// Personal Interno / Instructor
|
||||||
|
<span className="bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/25 px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wide">
|
||||||
|
INTERNO
|
||||||
|
</span>
|
||||||
|
|
||||||
|
// Usuario General / Aprendiz
|
||||||
|
<span className="bg-lime/15 text-lime-deep dark:text-lime border border-lime/25 px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wide">
|
||||||
|
USUARIO
|
||||||
|
</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.5. Estados de Alerta y Notificación
|
||||||
|
|
||||||
|
- **Éxito (Success)**: `bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30`.
|
||||||
|
- **Advertencia (Warning)**: `bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30`.
|
||||||
|
- **Peligro / Error (Danger)**: `bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30`.
|
||||||
|
- **Informativo / Sincronización (Info)**: `bg-cyan-500/10 text-cyan-600 dark:text-cyan-400 border-cyan-500/30`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Arquitectura Responsiva para Todo Tipo de Pantallas
|
||||||
|
|
||||||
|
El layout debe adaptarse sin saltos bruscos ni desbordes a través de 4 rangos de resolución:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┬───────────────────┬──────────────────────┬──────────────────────┐
|
||||||
|
│ MÓVIL (<640px) │ TABLET (640-1023) │ ESCRITORIO (1024-1439│ ULTRAWIDE (1440px+) │
|
||||||
|
│ Pantalla 1 col │ 2 col adaptable │ 3 col simétrica │ 3 col con max-w │
|
||||||
|
│ Drawer lateral │ Sidebar colapsada │ AppSidebar + Main + │ Lectura optimizada │
|
||||||
|
│ Barra chips │ Scroll horizontal │ RightSidebar │ Alta densidad │
|
||||||
|
│ Bottom-sheets │ Modales centrados │ Snap vertical │ Cards contenidas │
|
||||||
|
└─────────────────┴───────────────────┴──────────────────────┴──────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1. Matriz de Adaptabilidad por Pantalla
|
||||||
|
|
||||||
|
| Pantalla | Breakpoint Tailwind | Layout Estructural | Barra Izquierda (`AppSidebar`) | Barra Derecha (`RightSidebar`) | Navegación Secundaria | Modales / Diálogos |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **Móvil Pequeño** | `320px` - `480px` | 1 columna vertical fluida | Drawer lateral oculto (Z-50) con botón hamburguesa | Píldora flotante compacta inferior derecha | Barra de chips horizontal deslizable | Bottom-Sheet (hoja inferior `90dvh`) |
|
||||||
|
| **Móvil Grande** | `481px` - `639px` | 1 columna con márgenes `p-2.5` | Drawer lateral oculto con fondo oscuro translúcido | Píldora flotante inferior derecha | Chips deslizables centrados automáticamente | Bottom-Sheet con arrastre |
|
||||||
|
| **Tablet Portrait** | `640px` - `767px` | 1 columna o 2 columnas en tarjetas | Drawer lateral o riel flotante | Oculta o fusionada en barra inferior | Chips deslizables o pestañas | Modal centrado `max-w-md` |
|
||||||
|
| **Tablet Landscape** | `768px` - `1023px` | 2 columnas (Sidebar + Main) | Riel de iconos colapsado (`w-16`), expandible en hover | Oculta o en menú de cabecera | Pestañas fijas o barra de navegación | Modal centrado `max-w-lg` |
|
||||||
|
| **Escritorio Estándar** | `1024px` - `1439px` | 3 columnas (`AppSidebar` + `Main` + `RightSidebar`) | Colapsada a iconos (`w-[72px]`), expandible a `w-64` | Riel estático vertical (`w-14` o `w-16`) | Puntos navegadores flotantes a la derecha | Modal centrado con fondo desenfocado |
|
||||||
|
| **Ultrawide / 4K** | `1440px` en adelante | 3 columnas con límites de lectura (`max-w-7xl`) | Barra fija expandible | Riel estático vertical con herramientas | Puntos flotantes + atajos de teclado | Modal centrado `max-w-2xl` |
|
||||||
|
|
||||||
|
### 3.2. Reglas Críticas de Estabilidad de Pantalla
|
||||||
|
|
||||||
|
1. **Uso Exclusivo de Dynamic Viewport Height (`100dvh`)**:
|
||||||
|
- **NUNCA** usar `100vh` en contenedores de aplicación completa porque las barras de navegación dinámicas de iOS Safari y Chrome Android causan saltos y recortes.
|
||||||
|
- Usar: `className="h-[100dvh] max-h-[100dvh] w-full flex flex-col md:flex-row relative z-10 overflow-hidden p-2 sm:p-3 gap-2 sm:gap-3"`.
|
||||||
|
2. **Safe Area Insets (Áreas Seguras para Notches y Home Bar)**:
|
||||||
|
- Toda barra inferior o botón flotante debe respetar las áreas seguras:
|
||||||
|
```css
|
||||||
|
bottom: max(0.75rem, env(safe-area-inset-bottom));
|
||||||
|
right: max(0.75rem, env(safe-area-inset-right));
|
||||||
|
left: max(0.75rem, env(safe-area-inset-left));
|
||||||
|
```
|
||||||
|
3. **Áreas Táctiles Mínimas (Touch Targets)**:
|
||||||
|
- Todo botón o enlace interactivo debe tener al menos `44px x 44px` (`min-h-[44px] min-w-[44px]`) o padding generoso.
|
||||||
|
4. **Prevención de Zoom Automático en iOS**:
|
||||||
|
- Todo `input` y `textarea` debe tener `text-sm` en desktop pero un tamaño computado de al menos `16px` en móvil para evitar que iOS haga zoom indeseado.
|
||||||
|
5. **Scrollbars Personalizadas y Ocultamiento Táctil**:
|
||||||
|
- En pantallas móviles (`< 768px`), las barras de desplazamiento se ocultan para maximizar espacio táctil. En desktop, usan la píldora de 5px (`.custom-scrollbar`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Plantillas Maestras de Página (Templates)
|
||||||
|
|
||||||
|
A continuación se presentan las estructuras exactas para las vistas principales de la aplicación.
|
||||||
|
|
||||||
|
### 4.1. Template 1: Shell Base del Portal / Landing Page (3 Columnas)
|
||||||
|
|
||||||
|
Esta plantilla es la base de la pantalla de inicio (`/` o `/[lang]/index.astro`), con AppSidebar colapsable, cabecera móvil, chips deslizables, scroll continuo por secciones con snap vertical, puntos indicadores a la derecha, barra flotante de pie de página retráctil y RightSidebar.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import React, { useRef, useState, useCallback, useEffect } from "react";
|
||||||
|
import AppSidebar from "./AppSidebar.jsx";
|
||||||
|
import RightSidebar from "./RightSidebar.jsx";
|
||||||
|
import Footer from "./Footer.jsx";
|
||||||
|
import { Link } from "../../utils/navigate.jsx";
|
||||||
|
|
||||||
|
const SECCIONES = [
|
||||||
|
{ id: 'hero', name: 'Inicio', icon: 'fa-house' },
|
||||||
|
{ id: 'oferta', name: 'Oferta Académica', icon: 'fa-graduation-cap' },
|
||||||
|
{ id: 'mision', name: 'Misión y Visión', icon: 'fa-compass' },
|
||||||
|
{ id: 'contacto', name: 'Contacto', icon: 'fa-headset' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function PortalLayoutTemplate() {
|
||||||
|
const mainRef = useRef(null);
|
||||||
|
const chipsNavRef = useRef(null);
|
||||||
|
const [activeSection, setActiveSection] = useState(0);
|
||||||
|
const [isFooterVisible, setIsFooterVisible] = useState(false);
|
||||||
|
const lastScrollTopRef = useRef(0);
|
||||||
|
|
||||||
|
const handleScroll = useCallback((e) => {
|
||||||
|
const el = e.target;
|
||||||
|
const currentScroll = el.scrollTop;
|
||||||
|
const isAtBottom = el.scrollHeight - currentScroll - el.clientHeight < 60;
|
||||||
|
|
||||||
|
// Footer retráctil
|
||||||
|
if (isAtBottom || (currentScroll - lastScrollTopRef.current > 10 && currentScroll > 60)) {
|
||||||
|
setIsFooterVisible(true);
|
||||||
|
} else if (currentScroll - lastScrollTopRef.current < -10) {
|
||||||
|
setIsFooterVisible(false);
|
||||||
|
}
|
||||||
|
lastScrollTopRef.current = currentScroll;
|
||||||
|
|
||||||
|
// Detección de sección activa
|
||||||
|
const sections = el.querySelectorAll('section');
|
||||||
|
sections.forEach((sec, idx) => {
|
||||||
|
const top = sec.offsetTop - el.offsetTop;
|
||||||
|
const height = sec.offsetHeight;
|
||||||
|
if (currentScroll >= top - height / 3 && currentScroll < top + height / 2) {
|
||||||
|
setActiveSection(idx);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const scrollToSection = (idx) => {
|
||||||
|
if (!mainRef.current) return;
|
||||||
|
const sections = mainRef.current.querySelectorAll('section');
|
||||||
|
if (sections[idx]) {
|
||||||
|
sections[idx].scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
|
setActiveSection(idx);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-[100dvh] max-h-[100dvh] w-full flex flex-col md:flex-row relative z-10 overflow-hidden p-2 sm:p-3 gap-2 sm:gap-3">
|
||||||
|
{/* 1. Orbes de resplandor ambiental */}
|
||||||
|
<div className="absolute inset-0 pointer-events-none overflow-hidden -z-10" aria-hidden="true">
|
||||||
|
<div className="absolute top-10 left-1/4 w-96 h-96 bg-lime-500/8 dark:bg-lime-500/10 rounded-full blur-[120px]" />
|
||||||
|
<div className="absolute bottom-20 right-1/4 w-96 h-96 bg-emerald-500/6 dark:bg-emerald-500/8 rounded-full blur-[140px]" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 2. Barra lateral de navegación principal */}
|
||||||
|
<AppSidebar />
|
||||||
|
|
||||||
|
{/* 3. Contenedor Central Dinámico */}
|
||||||
|
<div className="flex-1 min-w-0 relative flex flex-col h-full overflow-hidden">
|
||||||
|
{/* Cabecera y Chips para Móvil (< 768px) */}
|
||||||
|
<div className="md:hidden shrink-0 flex flex-col gap-1.5 mb-1.5 z-20">
|
||||||
|
<div className="flex items-center justify-between px-3 py-2 bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl shadow-[0_4px_20px_rgba(0,0,0,0.06),inset_0_1px_0_rgba(255,255,255,0.7)] dark:shadow-[0_4px_20px_rgba(0,0,0,0.3),inset_0_1px_0_rgba(255,255,255,0.08)] pl-14">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
<img src="/Logo.webp" alt="CPIC" className="w-6 h-6 rounded-lg object-cover" />
|
||||||
|
<span className="font-bold text-xs text-gray-900 dark:text-white truncate">
|
||||||
|
CPIC <span className="text-[#39A900] dark:text-lime">conecta</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
href="/chat"
|
||||||
|
className="px-2.5 py-1 rounded-xl bg-lime/15 text-lime-deep dark:text-lime border border-lime/30 text-xs font-semibold flex items-center gap-1.5 no-underline hover:bg-lime/25 transition-colors"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-comment-dots text-[11px]" />
|
||||||
|
<span>Chat</span>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chips horizontales deslizables */}
|
||||||
|
<div
|
||||||
|
ref={chipsNavRef}
|
||||||
|
className="w-full overflow-x-auto flex items-center gap-1.5 py-1 px-1 border border-black/8 dark:border-white/10 bg-white/75 dark:bg-[rgba(10,22,10,0.75)] backdrop-blur-2xl rounded-2xl"
|
||||||
|
style={{ scrollbarWidth: 'none' }}
|
||||||
|
>
|
||||||
|
{SECCIONES.map((sec, idx) => (
|
||||||
|
<button
|
||||||
|
key={sec.id}
|
||||||
|
onClick={() => scrollToSection(idx)}
|
||||||
|
className={`px-3 py-1.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all flex items-center gap-1.5 shrink-0 cursor-pointer min-h-[36px] ${
|
||||||
|
activeSection === idx
|
||||||
|
? "bg-lime text-black shadow-sm font-bold scale-[1.02]"
|
||||||
|
: "bg-black/5 dark:bg-white/5 text-gray-700 dark:text-white/70 hover:bg-black/10 dark:hover:bg-white/10"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${sec.icon} text-[10px]` } />
|
||||||
|
<span>{sec.name}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Área Principal con Snap Scroll y Máscara de Degradado */}
|
||||||
|
<main
|
||||||
|
ref={mainRef}
|
||||||
|
onScroll={handleScroll}
|
||||||
|
tabIndex={0}
|
||||||
|
className="flex-1 min-w-0 flex flex-col overflow-y-auto scroll-smooth snap-none md:snap-y md:snap-mandatory custom-scrollbar relative h-full focus:outline-none md:[mask-image:linear-gradient(to_bottom,transparent_0%,black_1.5%,black_98.5%,transparent_100%)]"
|
||||||
|
>
|
||||||
|
{/* Secciones como tarjetas Tier 2 */}
|
||||||
|
<section className="min-h-full snap-start flex flex-col justify-center p-4 sm:p-8 bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-3xl mb-3 shadow-[0_8px_32px_rgba(0,0,0,0.1)]">
|
||||||
|
<h1 className="text-2xl sm:text-4xl font-extrabold text-gray-900 dark:text-white tracking-tight">
|
||||||
|
Bienvenido a <span className="text-[#39A900] dark:text-lime">CPIC Conecta</span>
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-sm sm:text-base text-gray-600 dark:text-white/70 max-w-xl">
|
||||||
|
Asistente virtual e intranet del Centro de Procesos Industriales y Construcción.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* Navegador de puntos lateral (Desktop lg+) */}
|
||||||
|
<nav
|
||||||
|
aria-label="Navegación de secciones"
|
||||||
|
className="hidden lg:flex absolute right-4 top-1/2 -translate-y-1/2 z-30 flex-col gap-2 p-1.5 rounded-full bg-black/50 dark:bg-black/60 backdrop-blur-xl border border-white/10 shadow-xl"
|
||||||
|
>
|
||||||
|
{SECCIONES.map((sec, idx) => (
|
||||||
|
<button
|
||||||
|
key={sec.id}
|
||||||
|
onClick={() => scrollToSection(idx)}
|
||||||
|
aria-label={`Ir a sección ${sec.name}`}
|
||||||
|
className={`w-2.5 rounded-full transition-all duration-300 ${
|
||||||
|
activeSection === idx
|
||||||
|
? 'h-6 bg-lime shadow-[0_0_10px_rgba(132,204,22,0.8)]'
|
||||||
|
: 'h-2.5 bg-white/35 hover:bg-white/80 hover:scale-125'
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 4. Footer Retráctil Flotante */}
|
||||||
|
<Footer isVisible={isFooterVisible} onToggle={() => setIsFooterVisible(false)} />
|
||||||
|
|
||||||
|
{/* 5. Barra Lateral Derecha de Herramientas */}
|
||||||
|
<RightSidebar />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.2. Template 2: Área de Trabajo del Chat con IA (`Chat.jsx`)
|
||||||
|
|
||||||
|
Estructura de la vista de conversación (`/chat`), con cabecera de estado y modelo, flujo de mensajes con Markdown enriquecido, dock de interpretación LSC, botón flotante de retorno inferior con alerta de nuevos mensajes y barra de entrada multimedia.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import React, { useState, useRef } from "react";
|
||||||
|
import { motion, AnimatePresence } from 'framer-motion';
|
||||||
|
|
||||||
|
export default function ChatTemplate() {
|
||||||
|
const [messages, setMessages] = useState([]);
|
||||||
|
const [inputValue, setInputValue] = useState('');
|
||||||
|
const [isTyping, setIsTyping] = useState(false);
|
||||||
|
const [showScrollBottom, setShowScrollBottom] = useState(false);
|
||||||
|
const messagesEndRef = useRef(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-1 h-full flex flex-col bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl md:rounded-3xl shadow-[0_8px_32px_rgba(0,0,0,0.12),inset_0_1px_0_rgba(255,255,255,0.7)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.08)] overflow-hidden relative">
|
||||||
|
|
||||||
|
{/* Cabecera del Chat: Estado de Conexión y Modelo */}
|
||||||
|
<header className="px-4 py-3 border-b border-black/8 dark:border-white/10 flex items-center justify-between shrink-0 bg-white/50 dark:bg-white/[0.02]">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-9 h-9 rounded-xl bg-lime/15 border border-lime/30 flex items-center justify-center text-lime-deep dark:text-lime">
|
||||||
|
<i className="fa-solid fa-robot text-base" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 className="font-bold text-sm text-gray-900 dark:text-white flex items-center gap-2">
|
||||||
|
<span>Asistente CPIC</span>
|
||||||
|
<span className="w-2 h-2 rounded-full bg-lime animate-pulse" />
|
||||||
|
</h2>
|
||||||
|
<p className="text-[11px] text-gray-500 dark:text-white/50">Gemini Pro • RAG Activo</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Acciones de Cabecera */}
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<button className="w-8 h-8 rounded-xl hover:bg-black/5 dark:hover:bg-white/8 text-gray-600 dark:text-white/70 flex items-center justify-center transition-colors">
|
||||||
|
<i className="fa-solid fa-magnifying-glass text-xs" />
|
||||||
|
</button>
|
||||||
|
<button className="w-8 h-8 rounded-xl hover:bg-black/5 dark:hover:bg-white/8 text-gray-600 dark:text-white/70 flex items-center justify-center transition-colors">
|
||||||
|
<i className="fa-solid fa-clock-rotate-left text-xs" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* Contenedor de Mensajes con Scroll */}
|
||||||
|
<div className="flex-1 min-h-0 overflow-y-auto px-3 py-3 sm:px-6 sm:py-5 flex flex-col gap-3 custom-scrollbar relative">
|
||||||
|
{/* Mensaje del Bot */}
|
||||||
|
<div className="w-full flex justify-start">
|
||||||
|
<div className="max-w-[88%] sm:max-w-[75%] rounded-2xl p-4 bg-white/70 dark:bg-white/[0.05] border border-black/6 dark:border-white/10 backdrop-blur-xl shadow-sm">
|
||||||
|
<div className="message-text text-sm text-gray-800 dark:text-white/90 leading-relaxed">
|
||||||
|
<p>¡Hola! Soy el asistente virtual del CPIC. ¿En qué puedo orientarte hoy sobre matrículas, programas o trámites?</p>
|
||||||
|
</div>
|
||||||
|
{/* Acciones de feedback y LSC */}
|
||||||
|
<div className="flex items-center gap-2 mt-2 pt-2 border-t border-black/6 dark:border-white/8 text-xs text-gray-400 dark:text-white/40">
|
||||||
|
<button className="hover:text-lime transition-colors" title="Me gusta"><i className="fa-regular fa-thumbs-up" /></button>
|
||||||
|
<button className="hover:text-red-400 transition-colors" title="No me gusta"><i className="fa-regular fa-thumbs-down" /></button>
|
||||||
|
<button className="hover:text-lime transition-colors ml-auto flex items-center gap-1 text-[11px]">
|
||||||
|
<i className="fa-solid fa-hands-asl-interpreting" />
|
||||||
|
<span>Ver en LSC</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Mensaje del Usuario */}
|
||||||
|
<div className="w-full flex justify-end">
|
||||||
|
<div className="max-w-[88%] sm:max-w-[75%] rounded-2xl p-3.5 bg-lime/15 dark:bg-lime/20 border border-lime/30 text-gray-900 dark:text-white text-sm shadow-sm">
|
||||||
|
¿Cuáles son las fechas de inscripción para la carrera técnica en Construcción?
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div ref={messagesEndRef} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Píldora Flotante "Ir al Final" */}
|
||||||
|
{showScrollBottom && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="absolute bottom-20 right-5 z-20 flex items-center gap-2 px-3.5 py-2 rounded-full bg-white/90 dark:bg-[rgba(10,22,10,0.92)] backdrop-blur-2xl border border-black/10 dark:border-white/15 text-gray-800 dark:text-white shadow-lg text-xs font-semibold cursor-pointer hover:scale-105 active:scale-95 transition-all"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-arrow-down text-[#39A900] dark:text-lime" />
|
||||||
|
<span>Ir al final</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Barra Inferior de Entrada (Input Bar) */}
|
||||||
|
<footer className="p-3 sm:p-4 border-t border-black/8 dark:border-white/10 bg-white/40 dark:bg-black/20 shrink-0">
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); }} className="flex items-center gap-2">
|
||||||
|
<div className="flex-1 relative flex items-center">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
|
placeholder="Escribe tu consulta aquí..."
|
||||||
|
className="w-full px-4 py-3 bg-white/70 dark:bg-black/40 backdrop-blur-xl border border-black/10 dark:border-white/12 rounded-2xl text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-white/30 focus:outline-none focus:border-[#39A900] focus:ring-2 focus:ring-[#39A900]/20 transition-all"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="absolute right-3 text-gray-400 hover:text-lime transition-colors"
|
||||||
|
title="Dictado por voz"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-microphone text-sm" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!inputValue.trim()}
|
||||||
|
className="w-11 h-11 rounded-2xl bg-lime text-black flex items-center justify-center font-bold shadow-md hover:scale-105 active:scale-95 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shrink-0"
|
||||||
|
title="Enviar mensaje"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-paper-plane text-sm" />
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.3. Template 3: Panel de Administración y Tablas CRUD (`AdminApp.jsx`)
|
||||||
|
|
||||||
|
Plantilla para tableros de gestión, métricas, CRUD de usuarios/categorías y tablas interactivas TanStack.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import AppSidebar from "./AppSidebar.jsx";
|
||||||
|
import RightSidebar from "./RightSidebar.jsx";
|
||||||
|
|
||||||
|
const TABS = [
|
||||||
|
{ id: 'dashboard', label: 'Métricas', icon: 'fa-chart-pie' },
|
||||||
|
{ id: 'usuarios', label: 'Usuarios', icon: 'fa-users' },
|
||||||
|
{ id: 'roles', label: 'Roles y Permisos', icon: 'fa-shield-halved' },
|
||||||
|
{ id: 'preguntas', label: 'Base de Conocimiento', icon: 'fa-database' },
|
||||||
|
{ id: 'tickets', label: 'Tickets y Soporte', icon: 'fa-ticket' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function AdminAppTemplate() {
|
||||||
|
const [currentTab, setCurrentTab] = useState('dashboard');
|
||||||
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-[100dvh] max-h-[100dvh] w-full flex flex-col md:flex-row relative z-10 overflow-hidden p-2 sm:p-3 gap-2 sm:gap-3">
|
||||||
|
<AppSidebar />
|
||||||
|
|
||||||
|
<div className="flex-1 min-w-0 flex flex-col h-full overflow-hidden bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl md:rounded-3xl shadow-[0_8px_32px_rgba(0,0,0,0.12)]">
|
||||||
|
|
||||||
|
{/* Barra Superior del Panel Admin: Pestañas y Acciones */}
|
||||||
|
<header className="px-4 py-3 sm:px-6 sm:py-4 border-b border-black/8 dark:border-white/10 flex flex-wrap items-center justify-between gap-3 shrink-0">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg sm:text-xl font-extrabold text-gray-900 dark:text-white flex items-center gap-2">
|
||||||
|
<i className="fa-solid fa-shield-halved text-[#39A900] dark:text-lime" />
|
||||||
|
<span>Gestión de Intranet</span>
|
||||||
|
</h1>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-white/50">Control de acceso, embeddings y métricas</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navegación por pestañas tipo píldora */}
|
||||||
|
<div className="flex items-center gap-1 overflow-x-auto max-w-full p-1 bg-black/5 dark:bg-white/5 rounded-2xl border border-black/6 dark:border-white/8">
|
||||||
|
{TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => setCurrentTab(tab.id)}
|
||||||
|
className={`px-3 py-1.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all flex items-center gap-1.5 cursor-pointer ${
|
||||||
|
currentTab === tab.id
|
||||||
|
? 'bg-lime text-black shadow-sm font-bold scale-[1.02]'
|
||||||
|
: 'text-gray-600 dark:text-white/60 hover:text-gray-950 dark:hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${tab.icon} text-[11px]` } />
|
||||||
|
<span>{tab.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* Contenido Dinámico del Tableros */}
|
||||||
|
<main className="flex-1 overflow-y-auto p-4 sm:p-6 custom-scrollbar space-y-6">
|
||||||
|
|
||||||
|
{/* 1. Fila de Tarjetas de Estadísticas (Tier 2 Glass) */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
|
||||||
|
{[
|
||||||
|
{ label: 'Consultas Hoy', val: '1,420', change: '+12%', icon: 'fa-comments', color: 'lime' },
|
||||||
|
{ label: 'Usuarios Activos', val: '384', change: '+5%', icon: 'fa-users', color: 'blue' },
|
||||||
|
{ label: 'Embeddings Indexados', val: '8,950', change: '100%', icon: 'fa-vector-square', color: 'emerald' },
|
||||||
|
{ label: 'Tickets Pendientes', val: '6', change: '-2', icon: 'fa-circle-exclamation', color: 'amber' },
|
||||||
|
].map((stat, idx) => (
|
||||||
|
<div
|
||||||
|
key={idx}
|
||||||
|
className="p-4 rounded-2xl bg-white/60 dark:bg-white/[0.04] border border-black/8 dark:border-white/10 backdrop-blur-xl shadow-sm hover:scale-[1.01] transition-transform"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between text-gray-500 dark:text-white/50 text-xs font-semibold">
|
||||||
|
<span>{stat.label}</span>
|
||||||
|
<i className={`fa-solid ${stat.icon} text-sm text-[#39A900] dark:text-lime`} />
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-2xl font-black text-gray-900 dark:text-white tabular-nums tracking-tight">
|
||||||
|
{stat.val}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[11px] font-semibold text-emerald-500 flex items-center gap-1">
|
||||||
|
<span>{stat.change}</span>
|
||||||
|
<span className="text-gray-400 dark:text-white/30 font-normal">vs periodo anterior</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 2. Barra de Búsqueda y Botones de Acción */}
|
||||||
|
<div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
|
||||||
|
<div className="relative flex-1 max-w-md">
|
||||||
|
<i className="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/30 text-xs" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
placeholder="Filtrar por nombre, correo o rol..."
|
||||||
|
className="w-full pl-9 pr-4 py-2.5 bg-white/60 dark:bg-black/40 backdrop-blur-xl border border-black/10 dark:border-white/12 rounded-xl text-xs text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:border-[#39A900] focus:ring-2 focus:ring-[#39A900]/20"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button className="px-3.5 py-2.5 rounded-xl bg-lime text-black font-bold text-xs flex items-center gap-1.5 shadow-sm hover:scale-105 active:scale-95 transition-all cursor-pointer">
|
||||||
|
<i className="fa-solid fa-plus text-xs" />
|
||||||
|
<span>Crear Nuevo</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 3. Tabla de Datos Responsive con Scroll Horizontal */}
|
||||||
|
<div className="w-full overflow-x-auto rounded-2xl border border-black/8 dark:border-white/10 bg-white/40 dark:bg-black/20 backdrop-blur-xl">
|
||||||
|
<table className="w-full text-left text-xs admin-table border-collapse">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-black/8 dark:border-white/10 text-gray-500 dark:text-white/60 font-semibold uppercase tracking-wider text-[10px]">
|
||||||
|
<th className="p-3.5">Usuario</th>
|
||||||
|
<th className="p-3.5">Rol</th>
|
||||||
|
<th className="p-3.5">Estado</th>
|
||||||
|
<th className="p-3.5">Último Acceso</th>
|
||||||
|
<th className="p-3.5 text-right">Acciones</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-black/6 dark:divide-white/6 text-gray-800 dark:text-white/80">
|
||||||
|
<tr className="hover:bg-black/5 dark:hover:bg-white/5 transition-colors">
|
||||||
|
<td className="p-3.5 flex items-center gap-2.5">
|
||||||
|
<div className="w-8 h-8 rounded-xl bg-lime/15 border border-lime/30 flex items-center justify-center font-bold text-lime-deep dark:text-lime">
|
||||||
|
G
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold text-gray-900 dark:text-white">Geronimo Gómez</div>
|
||||||
|
<div className="text-[10px] text-gray-400 dark:text-white/40">geronimo@sena.edu.co</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="p-3.5">
|
||||||
|
<span className="px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase bg-red-500/10 text-red-600 dark:text-red-400 border border-red-500/25">
|
||||||
|
ROOT
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="p-3.5">
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-emerald-500 font-medium text-[11px]">
|
||||||
|
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
|
||||||
|
Activo
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="p-3.5 tabular-nums text-gray-400 dark:text-white/40">Hoy, 09:28</td>
|
||||||
|
<td className="p-3.5 text-right">
|
||||||
|
<button className="w-7 h-7 rounded-lg hover:bg-black/10 dark:hover:bg-white/10 text-gray-500 hover:text-lime transition-colors">
|
||||||
|
<i className="fa-solid fa-pen-to-square text-xs" />
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<RightSidebar />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.4. Template 4: Autenticación y Diálogos de Seguridad (`AuthApp.jsx`)
|
||||||
|
|
||||||
|
Plantilla centrada de tarjeta de cristal para inicio de sesión, registro y recuperación de contraseña.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import React, { useState } from "react";
|
||||||
|
|
||||||
|
export default function AuthTemplate() {
|
||||||
|
const [isRegister, setIsRegister] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-[100dvh] w-full flex items-center justify-center p-3 sm:p-6 relative overflow-hidden">
|
||||||
|
{/* Resplandor ambiental */}
|
||||||
|
<div className="absolute inset-0 pointer-events-none -z-10">
|
||||||
|
<div className="absolute top-1/4 left-1/3 w-96 h-96 bg-lime-500/10 rounded-full blur-[140px]" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tarjeta de Cristal Centrada */}
|
||||||
|
<div className="w-full max-w-md bg-white/85 dark:bg-[rgba(10,22,10,0.88)] backdrop-blur-2xl border border-black/8 dark:border-white/12 rounded-3xl p-6 sm:p-8 shadow-[0_16px_48px_rgba(0,0,0,0.2),inset_0_1px_0_rgba(255,255,255,0.1)]">
|
||||||
|
{/* Logo y Encabezado */}
|
||||||
|
<div className="flex flex-col items-center text-center mb-6">
|
||||||
|
<div className="w-14 h-14 rounded-2xl bg-lime/15 border border-lime/30 flex items-center justify-center text-lime mb-3 shadow-[0_0_20px_rgba(132,204,22,0.25)]">
|
||||||
|
<i className="fa-solid fa-shield-halved text-2xl text-[#39A900] dark:text-lime" />
|
||||||
|
</div>
|
||||||
|
<h1 className="text-xl sm:text-2xl font-black text-gray-900 dark:text-white tracking-tight">
|
||||||
|
CPIC <span className="text-[#39A900] dark:text-lime">Conecta</span>
|
||||||
|
</h1>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-white/50 mt-1">
|
||||||
|
Ingresa tus credenciales institucionales del SENA
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Selector de pestañas Login / Registro */}
|
||||||
|
<div className="grid grid-cols-2 p-1 bg-black/5 dark:bg-white/5 rounded-2xl mb-5 border border-black/6 dark:border-white/8">
|
||||||
|
<button
|
||||||
|
onClick={() => setIsRegister(false)}
|
||||||
|
className={`py-2 rounded-xl text-xs font-bold transition-all ${
|
||||||
|
!isRegister ? 'bg-lime text-black shadow-sm' : 'text-gray-600 dark:text-white/60'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Iniciar Sesión
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setIsRegister(true)}
|
||||||
|
className={`py-2 rounded-xl text-xs font-bold transition-all ${
|
||||||
|
isRegister ? 'bg-lime text-black shadow-sm' : 'text-gray-600 dark:text-white/60'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Registrarse
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Formulario */}
|
||||||
|
<form onSubmit={(e) => e.preventDefault()} className="space-y-3.5">
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold text-gray-700 dark:text-white/70 uppercase tracking-wider mb-1">
|
||||||
|
Correo Institucional
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
placeholder="nombre@sena.edu.co"
|
||||||
|
className="w-full px-4 py-3 bg-white/60 dark:bg-black/40 backdrop-blur-xl border border-black/10 dark:border-white/12 rounded-2xl text-sm text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:border-[#39A900] focus:ring-2 focus:ring-[#39A900]/20 transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-[11px] font-semibold text-gray-700 dark:text-white/70 uppercase tracking-wider mb-1">
|
||||||
|
Contraseña
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="••••••••"
|
||||||
|
className="w-full px-4 py-3 bg-white/60 dark:bg-black/40 backdrop-blur-xl border border-black/10 dark:border-white/12 rounded-2xl text-sm text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:border-[#39A900] focus:ring-2 focus:ring-[#39A900]/20 transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full py-3.5 mt-2 rounded-2xl bg-lime text-black font-extrabold text-sm shadow-[0_4px_16px_rgba(132,204,22,0.3)] hover:scale-[1.01] active:scale-[0.98] transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
{isRegister ? 'Crear Cuenta' : 'Ingresar'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Micro-Interacciones, Animaciones y Clases Utilitarias
|
||||||
|
|
||||||
|
### 5.1. Reglas de Interacción Táctil
|
||||||
|
- **Botones y Enlaces**:
|
||||||
|
- `transition-all duration-200 ease-out` obligatorio en todos los interactivos.
|
||||||
|
- Elevación hover: `hover:scale-[1.01]` o `hover:scale-[1.02]`.
|
||||||
|
- Presión táctil (click/tap): `active:scale-[0.98]`.
|
||||||
|
- Anillo de Foco Accesible:
|
||||||
|
`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-lime focus-visible:ring-offset-2 focus-visible:ring-offset-black`.
|
||||||
|
|
||||||
|
### 5.2. Clases de Animación y Keyframes (`global.css`)
|
||||||
|
- `--animate-slide-in-left`: Entrada fluida de cajón lateral.
|
||||||
|
- `--animate-typing-bounce`: Indicador de tres puntos rebotando para el bot escribiendo.
|
||||||
|
- `--animate-wave`: Onda acústica para el panel de dictado por voz.
|
||||||
|
- `--animate-classify-spin`: Spinner de anillo con aceleración para la clasificación RAG.
|
||||||
|
- `--animate-progress-bar`: Barra de cuenta regresiva de 6s para notificaciones Toast.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Accesibilidad (WCAG 2.1 AA/AAA)
|
||||||
|
|
||||||
|
El sistema soporta por diseño y mediante clases en `html`:
|
||||||
|
1. **Contraste Mínimo**:
|
||||||
|
- Texto normal: ratio >= 4.5:1 contra fondos glassmorphism.
|
||||||
|
- Texto grande e iconos clave: ratio >= 3.0:1.
|
||||||
|
2. **Modo Alto Contraste**: `html.a11y-high-contrast { filter: contrast(1.4); }`.
|
||||||
|
3. **Reducción de Movimiento**:
|
||||||
|
`@media (prefers-reduced-motion: reduce)` suprime todas las transiciones y animaciones a `0.01ms`.
|
||||||
|
4. **Fuente para Dislexia**: `html.a11y-dyslexia-font` activa `'OpenDyslexic'`.
|
||||||
|
5. **Filtros de Daltonismo**: Modos Protanopia, Deuteranopia y Tritanopia vía filtros SVG nativos.
|
||||||
|
6. **LSC (Lengua de Señas Colombiana)**: Integración de dock flotante para video interpretativo de preguntas y respuestas.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Checklist de Verificación de Diseño para el Desarrollador/Agente
|
||||||
|
|
||||||
|
Antes de dar por completado un cambio visual o nueva página, comprobar:
|
||||||
|
|
||||||
|
- [ ] **Lienzo**: ¿Usa `h-[100dvh]` en el contenedor raíz en vez de `100vh`?
|
||||||
|
- [ ] **Modo Oscuro / Claro**: ¿Se comprueban ambos temas con `dark:` y fondos glass legibles?
|
||||||
|
- [ ] **Acentos**: ¿Los títulos y acentos principales usan `#39A900`, `var(--color-lime)` o `#166534` en modo claro?
|
||||||
|
- [ ] **Móvil (< 768px)**: ¿El menú lateral se convierte en drawer off-canvas con botón flotante?
|
||||||
|
- [ ] **Móvil (< 768px)**: ¿Las pestañas o categorías usan un contenedor deslizable horizontalmente sin scrollbar visible?
|
||||||
|
- [ ] **Scrollbars**: ¿Tienen la clase `.custom-scrollbar` de 5px?
|
||||||
|
- [ ] **Interacciones**: ¿Tienen `transition-all duration-200` y `active:scale-[0.98]`?
|
||||||
|
- [ ] **Accesibilidad**: ¿Los elementos interactivos tienen etiquetas `aria-label` o títulos descriptivos?
|
||||||
|
- [ ] **Áreas Táctiles**: ¿Los botones tienen al menos 44px de altura/ancho en móviles?
|
||||||
@ -0,0 +1,227 @@
|
|||||||
|
import React, { useState, useRef, useCallback } from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SampleFullPageTemplate
|
||||||
|
*
|
||||||
|
* Componente de referencia completo que ejemplifica la implementación
|
||||||
|
* de los patrones de diseño, paleta de colores y arquitectura responsiva
|
||||||
|
* para el ecosistema CPIC - Conecta (SENA).
|
||||||
|
*/
|
||||||
|
export default function SampleFullPageTemplate() {
|
||||||
|
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
|
||||||
|
const [activeTab, setActiveTab] = useState(0);
|
||||||
|
const [isDarkMode, setIsDarkMode] = useState(true);
|
||||||
|
const mainRef = useRef(null);
|
||||||
|
|
||||||
|
const TABS = [
|
||||||
|
{ id: 'general', name: 'General', icon: 'fa-house' },
|
||||||
|
{ id: 'oferta', name: 'Oferta Académica', icon: 'fa-graduation-cap' },
|
||||||
|
{ id: 'metricas', name: 'Métricas', icon: 'fa-chart-pie' },
|
||||||
|
{ id: 'soporte', name: 'Soporte', icon: 'fa-headset' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
setIsDarkMode((prev) => {
|
||||||
|
const next = !prev;
|
||||||
|
if (next) {
|
||||||
|
document.documentElement.classList.add('dark');
|
||||||
|
document.documentElement.setAttribute('data-theme', 'dark');
|
||||||
|
} else {
|
||||||
|
document.documentElement.classList.remove('dark');
|
||||||
|
document.documentElement.setAttribute('data-theme', 'light');
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-[100dvh] max-h-[100dvh] w-full flex flex-col md:flex-row relative z-10 overflow-hidden p-2 sm:p-3 gap-2 sm:gap-3">
|
||||||
|
{/* ── 1. Resplandor Ambiental de Fondo (Tier 1) ── */}
|
||||||
|
<div className="absolute inset-0 pointer-events-none overflow-hidden -z-10" aria-hidden="true">
|
||||||
|
<div className="absolute top-10 left-1/4 w-96 h-96 bg-lime-500/8 dark:bg-lime-500/10 rounded-full blur-[120px]" />
|
||||||
|
<div className="absolute bottom-20 right-1/4 w-96 h-96 bg-emerald-500/6 dark:bg-emerald-500/8 rounded-full blur-[140px]" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── 2. Botón Hamburguesa Flotante para Móvil ── */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
|
||||||
|
className="md:hidden fixed top-3 left-3 z-40 w-10 h-10 rounded-xl bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 flex items-center justify-center text-gray-800 dark:text-white shadow-md cursor-pointer"
|
||||||
|
aria-label="Abrir menú"
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${mobileMenuOpen ? 'fa-xmark' : 'fa-bars'} text-sm`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* ── 3. Barra Lateral Principal (Desktop fija / Móvil Drawer) ── */}
|
||||||
|
<aside
|
||||||
|
className={`
|
||||||
|
fixed md:static inset-y-0 left-0 z-50
|
||||||
|
w-64 md:w-20 md:hover:w-64
|
||||||
|
transition-all duration-300 ease-in-out
|
||||||
|
flex flex-col justify-between p-3
|
||||||
|
bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl
|
||||||
|
border border-black/8 dark:border-white/10
|
||||||
|
rounded-r-3xl md:rounded-3xl
|
||||||
|
shadow-[0_8px_32px_rgba(0,0,0,0.15)]
|
||||||
|
${mobileMenuOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{/* Cabecera Sidebar con Logo */}
|
||||||
|
<div className="flex items-center gap-3 px-2 py-1">
|
||||||
|
<div className="w-10 h-10 rounded-2xl bg-lime/15 border border-lime/30 flex items-center justify-center shrink-0">
|
||||||
|
<span className="font-extrabold text-[#39A900] dark:text-lime text-base">C</span>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 overflow-hidden">
|
||||||
|
<h2 className="font-bold text-sm text-gray-900 dark:text-white truncate">CPIC Conecta</h2>
|
||||||
|
<p className="text-[10px] text-gray-400 dark:text-white/40 truncate">SENA Regional Caldas</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Enlaces de Navegación */}
|
||||||
|
<nav className="flex-1 my-4 space-y-1.5 overflow-y-auto">
|
||||||
|
{TABS.map((tab, idx) => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => { setActiveTab(idx); setMobileMenuOpen(false); }}
|
||||||
|
className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-2xl text-xs font-semibold transition-all cursor-pointer ${
|
||||||
|
activeTab === idx
|
||||||
|
? 'bg-lime/15 text-lime-deep dark:text-lime border border-lime/30 shadow-[0_2px_12px_rgba(132,204,22,0.15)]'
|
||||||
|
: 'text-gray-600 dark:text-white/60 hover:bg-black/5 dark:hover:bg-white/5'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${tab.icon} text-sm shrink-0`} />
|
||||||
|
<span className="truncate">{tab.name}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* Pie de Sidebar con Alternador de Modo Oscuro */}
|
||||||
|
<div className="pt-2 border-t border-black/8 dark:border-white/8">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggleTheme}
|
||||||
|
className="w-full flex items-center gap-3 px-3 py-2.5 rounded-2xl text-xs font-semibold text-gray-600 dark:text-white/60 hover:bg-black/5 dark:hover:bg-white/8 transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${isDarkMode ? 'fa-sun text-amber-400' : 'fa-moon text-emerald-600'} text-sm shrink-0`} />
|
||||||
|
<span className="truncate">{isDarkMode ? 'Modo Claro' : 'Modo Oscuro'}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* Telón oscuro para Drawer en móvil */}
|
||||||
|
{mobileMenuOpen && (
|
||||||
|
<div
|
||||||
|
onClick={() => setMobileMenuOpen(false)}
|
||||||
|
className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 md:hidden"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── 4. Columna Central Principal (Tier 2 Glass) ── */}
|
||||||
|
<div className="flex-1 min-w-0 flex flex-col h-full overflow-hidden">
|
||||||
|
{/* Cabecera Móvil y Chips Deslizables */}
|
||||||
|
<div className="md:hidden shrink-0 flex flex-col gap-1.5 mb-1.5 z-20">
|
||||||
|
<div className="flex items-center justify-between px-3 py-2 bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl pl-14">
|
||||||
|
<span className="font-bold text-xs text-gray-900 dark:text-white">
|
||||||
|
CPIC <span className="text-[#39A900] dark:text-lime">conecta</span>
|
||||||
|
</span>
|
||||||
|
<span className="px-2 py-0.5 rounded-md text-[10px] font-semibold bg-lime/15 text-lime-deep dark:text-lime border border-lime/25">
|
||||||
|
EN LÍNEA
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className="w-full overflow-x-auto flex items-center gap-1.5 py-1 px-1 bg-white/75 dark:bg-[rgba(10,22,10,0.75)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl"
|
||||||
|
style={{ scrollbarWidth: 'none' }}
|
||||||
|
>
|
||||||
|
{TABS.map((tab, idx) => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => setActiveTab(idx)}
|
||||||
|
className={`px-3 py-1.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all flex items-center gap-1.5 shrink-0 ${
|
||||||
|
activeTab === idx
|
||||||
|
? 'bg-lime text-black font-bold shadow-sm'
|
||||||
|
: 'text-gray-700 dark:text-white/70 hover:bg-black/5 dark:hover:bg-white/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${tab.icon} text-[10px]`} />
|
||||||
|
<span>{tab.name}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tarjeta de Contenido Principal con Scroll Interno */}
|
||||||
|
<main
|
||||||
|
ref={mainRef}
|
||||||
|
className="flex-1 overflow-y-auto p-4 sm:p-6 lg:p-8 custom-scrollbar bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl md:rounded-3xl shadow-[0_8px_32px_rgba(0,0,0,0.1)] flex flex-col gap-6"
|
||||||
|
>
|
||||||
|
{/* Título y Subtítulo */}
|
||||||
|
<div>
|
||||||
|
<div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-lime/10 border border-lime/20 text-[#39A900] dark:text-lime text-xs font-bold mb-2">
|
||||||
|
<span className="w-2 h-2 rounded-full bg-lime animate-pulse" />
|
||||||
|
SENA - Centro de Procesos Industriales y Construcción
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl sm:text-4xl font-black text-gray-900 dark:text-white tracking-tight">
|
||||||
|
Ecosistema Virtual <span className="text-[#39A900] dark:text-lime">Conecta</span>
|
||||||
|
</h1>
|
||||||
|
<p className="text-xs sm:text-sm text-gray-600 dark:text-white/70 mt-1 max-w-2xl leading-relaxed">
|
||||||
|
Diseño unificado responsivo en 3 capas de cristal con verde institucional y soporte universal.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Rejilla de Módulos (Auto-fit Grid) */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
|
||||||
|
{[
|
||||||
|
{ title: 'Chat con IA y RAG', desc: 'Respuestas contextuales con modelos multi-proveedor.', icon: 'fa-brain' },
|
||||||
|
{ title: 'Lengua de Señas (LSC)', desc: 'Dock interpretativo sincronizado para inclusión auditiva.', icon: 'fa-hands-asl-interpreting' },
|
||||||
|
{ title: 'Gestión Institucional', desc: 'Administración de roles, embeddings y métricas en tiempo real.', icon: 'fa-cubes' },
|
||||||
|
].map((card, idx) => (
|
||||||
|
<div
|
||||||
|
key={idx}
|
||||||
|
className="p-5 rounded-2xl bg-white/60 dark:bg-white/[0.04] border border-black/8 dark:border-white/10 backdrop-blur-xl shadow-sm hover:scale-[1.01] hover:border-lime/30 transition-all flex flex-col justify-between"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div className="w-10 h-10 rounded-xl bg-lime/15 border border-lime/25 flex items-center justify-center text-[#39A900] dark:text-lime mb-3">
|
||||||
|
<i className={`fa-solid ${card.icon} text-base`} />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-bold text-sm text-gray-900 dark:text-white">{card.title}</h3>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-white/60 mt-1 leading-normal">{card.desc}</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 pt-3 border-t border-black/6 dark:border-white/8 flex items-center justify-between text-xs">
|
||||||
|
<span className="text-[#39A900] dark:text-lime font-bold">Explorar</span>
|
||||||
|
<i className="fa-solid fa-arrow-right text-gray-400 group-hover:translate-x-1 transition-transform" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ── 5. Barra Lateral Derecha (RightSidebar) ── */}
|
||||||
|
<aside className="hidden md:flex md:flex-col md:w-14 lg:w-16 md:shrink-0 md:justify-between p-2 bg-white/85 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-3xl shadow-[0_8px_32px_rgba(0,0,0,0.12)]">
|
||||||
|
<div className="flex flex-col items-center gap-2">
|
||||||
|
<div className="w-9 h-9 rounded-2xl bg-lime/15 border border-lime/30 flex items-center justify-center text-lime-deep dark:text-lime font-black text-xs">
|
||||||
|
CPIC
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="w-9 h-9 rounded-2xl hover:bg-black/5 dark:hover:bg-white/10 flex items-center justify-center text-gray-600 dark:text-white/70 transition-colors"
|
||||||
|
title="Accesibilidad"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-universal-access text-sm" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="w-9 h-9 rounded-2xl bg-lime text-black flex items-center justify-center shadow-md hover:scale-105 active:scale-95 transition-all"
|
||||||
|
title="Asistente Virtual"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-comment-dots text-sm" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -0,0 +1,138 @@
|
|||||||
|
# Catálogo Exhaustivo de Colores y Tokens - CPIC Conecta
|
||||||
|
|
||||||
|
Este documento recopila la totalidad de tokens, códigos hexadecimales, variables CSS, clases de Tailwind y equivalencias para modo claro y oscuro en el ecosistema **CPIC - Conecta (SENA)**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Variables CSS del Tema (`@theme` en `global.css`)
|
||||||
|
|
||||||
|
```css
|
||||||
|
@theme {
|
||||||
|
--color-lime: #00FF00;
|
||||||
|
--color-lime-dark: #00CC00;
|
||||||
|
--color-lime-light: #66FF66;
|
||||||
|
--color-lime-soft: #B3FFB3;
|
||||||
|
--color-lime-pale: #E6FFE6;
|
||||||
|
--color-lime-deep: #009900;
|
||||||
|
--color-glass-border: rgba(255, 255, 255, 0.2);
|
||||||
|
--color-glass-bg: rgba(255, 255, 255, 0.12);
|
||||||
|
--color-sidebar: rgba(0, 100, 0, 0.85);
|
||||||
|
--color-sidebar-mobile: #0a3a0a;
|
||||||
|
--font-sans: 'Segoe UI', 'Poppins', 'Roboto', system-ui, sans-serif;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Paleta Institucional SENA y Escala Esmeralda / Lima
|
||||||
|
|
||||||
|
| Nombre | Hex / RGBA | Tailwind / CSS Variable | Propósito |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **SENA Verde Oficial** | `#39A900` | `#39A900` | Identidad corporativa SENA, títulos principales, logotipos, viñetas activas |
|
||||||
|
| **Electric Lime** | `#00FF00` | `var(--color-lime)` | Acentos vivos, anillos de foco accesibles, loaders |
|
||||||
|
| **Lime Dark** | `#00CC00` | `var(--color-lime-dark)` | Citas en markdown (blockquote), estados hover |
|
||||||
|
| **Lime Deep** | `#009900` | `var(--color-lime-deep)` | Encabezados en modo claro, texto legible en fondos blancos |
|
||||||
|
| **Lime Light** | `#66FF66` | `var(--color-lime-light)` | Borde superior de anillos de carga y resplandores |
|
||||||
|
| **Lime Soft** | `#B3FFB3` | `var(--color-lime-soft)` | Fondos de selección muy suaves |
|
||||||
|
| **Lime Pale** | `#E6FFE6` | `var(--color-lime-pale)` | Resaltados sutiles en tablas y alertas |
|
||||||
|
| **Tailwind Lime 400** | `#a3e635` | `text-lime` | Acentos de texto en modo oscuro, tooltips de gráficos |
|
||||||
|
| **Tailwind Lime 500** | `#84cc16` | `#84cc16` | Sombras resplandecientes, scrollbars activas |
|
||||||
|
| **Emerald 800** | `#166534` | `text-emerald-800` | Encabezados h1-h3 de markdown en modo claro |
|
||||||
|
| **Emerald 700** | `#15803d` | `text-emerald-700` | Enlaces y acentos con ratio de contraste alto en modo claro |
|
||||||
|
| **Emerald 600** | `#16a34a` | `text-emerald-600` | Enlaces interactivos en modo claro |
|
||||||
|
| **Emerald Bright** | `#52ff52` | `#52ff52` | Encabezados h1-h3 de markdown en modo oscuro |
|
||||||
|
| **Emerald Neon** | `#50e93b` | `#50e93b` | Enlaces y citas en modo oscuro |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Superficies y Capas de Cristal (Glassmorphism Tokens)
|
||||||
|
|
||||||
|
### 3.1. Modo Oscuro (`html.dark`)
|
||||||
|
|
||||||
|
- **Fondo General del Cuerpo**: Imagen `/background.webp` + velo `rgba(0, 0, 0, 0.2)`
|
||||||
|
- **Color Base Sólido (Fallback)**: `#0a0a0a` o `#0a160a`
|
||||||
|
- **Contenedores y Tarjetas Principales**:
|
||||||
|
- Fondo: `rgba(10, 22, 10, 0.85)` o `bg-white/[0.04]` a `bg-white/[0.08]`
|
||||||
|
- Filtro: `backdrop-blur-2xl`
|
||||||
|
- Borde: `border border-white/10`
|
||||||
|
- Sombra: `shadow-[0_4px_24px_rgba(0,0,0,0.3),inset_0_1px_0_rgba(255,255,255,0.08)]`
|
||||||
|
- **Elementos Flotantes (Modales, Menús, Toasts)**:
|
||||||
|
- Fondo: `rgba(15, 28, 15, 0.94)`
|
||||||
|
- Filtro: `backdrop-blur-3xl`
|
||||||
|
- Borde: `border border-lime/25`
|
||||||
|
- Sombra: `shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_24px_rgba(132,204,22,0.12)]`
|
||||||
|
- **Inputs y Entradas de Formulario**:
|
||||||
|
- Fondo: `bg-black/40`
|
||||||
|
- Borde: `border border-white/12`
|
||||||
|
- Foco: `border-[#39A900] ring-2 ring-[#39A900]/20 bg-black/60`
|
||||||
|
- Placeholder: `placeholder-white/30`
|
||||||
|
- **Barras de Scroll (`.custom-scrollbar`)**:
|
||||||
|
- Thumb: `rgba(132, 204, 22, 0.3)`
|
||||||
|
- Thumb Hover: `rgba(132, 204, 22, 0.75)` con `box-shadow: 0 0 10px rgba(132, 204, 22, 0.5)`
|
||||||
|
|
||||||
|
### 3.2. Modo Claro (`html[data-theme="light"]`)
|
||||||
|
|
||||||
|
- **Fondo General del Cuerpo**: Imagen `/background.webp` + velo `rgba(255, 255, 255, 0.4)`
|
||||||
|
- **Color Base Sólido (Fallback)**: `#f8fafc` (Slate 50)
|
||||||
|
- **Contenedores y Tarjetas Principales**:
|
||||||
|
- Fondo: `bg-white/85`
|
||||||
|
- Filtro: `backdrop-blur-2xl`
|
||||||
|
- Borde: `border border-black/8` o `border-slate-200/80`
|
||||||
|
- Sombra: `shadow-[0_4px_24px_rgba(0,0,0,0.06),inset_0_1px_0_rgba(255,255,255,0.7)]`
|
||||||
|
- **Elementos Flotantes (Modales, Menús, Toasts)**:
|
||||||
|
- Fondo: `bg-white/95`
|
||||||
|
- Filtro: `backdrop-blur-3xl`
|
||||||
|
- Borde: `border border-slate-200`
|
||||||
|
- Sombra: `shadow-[0_16px_48px_rgba(0,0,0,0.12)]`
|
||||||
|
- **Inputs y Entradas de Formulario**:
|
||||||
|
- Fondo: `bg-white/70`
|
||||||
|
- Borde: `border border-black/10`
|
||||||
|
- Foco: `border-[#39A900] ring-2 ring-[#39A900]/20 bg-white/90`
|
||||||
|
- Placeholder: `placeholder-gray-400`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Roles Institucionales y Códigos de Seguridad
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
// ROOT / SUPERADMIN (Rojo Alerta)
|
||||||
|
bg-red-500/10 text-red-600 dark:text-red-400 border border-red-500/25
|
||||||
|
|
||||||
|
// ADMIN (Ámbar Dorado)
|
||||||
|
bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/25
|
||||||
|
|
||||||
|
// INTERNO / STAFF / INSTRUCTOR (Azul Profesional)
|
||||||
|
bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/25
|
||||||
|
|
||||||
|
// USUARIO / APRENDIZ (Lima Institucional)
|
||||||
|
bg-lime/15 text-lime-deep dark:text-lime border border-lime/25
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Estados Semánticos del Sistema
|
||||||
|
|
||||||
|
- **Validado / Conectado / Activo**:
|
||||||
|
- Punto: `bg-emerald-500` con `animate-pulse` opcional
|
||||||
|
- Badge: `bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/25`
|
||||||
|
- **En Espera / Pendiente / Advertencia**:
|
||||||
|
- Punto: `bg-amber-500`
|
||||||
|
- Badge: `bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/25`
|
||||||
|
- **Error / Rechazado / Bloqueado**:
|
||||||
|
- Punto: `bg-red-500`
|
||||||
|
- Badge: `bg-red-500/10 text-red-600 dark:text-red-400 border border-red-500/25`
|
||||||
|
- **Sincronizando / Indexando RAG / Clasificando**:
|
||||||
|
- Punto: `bg-cyan-500` con `animate-ping`
|
||||||
|
- Badge: `bg-cyan-500/10 text-cyan-600 dark:text-cyan-400 border border-cyan-500/25`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Paleta para Gráficos TanStack (`@tanstack/charts`)
|
||||||
|
|
||||||
|
- **Serie 1 (Primaria - Preguntas Frecuentes)**: `#39A900`
|
||||||
|
- **Serie 2 (Secundaria - Usuarios)**: `#0ea5e9` (Sky 500)
|
||||||
|
- **Serie 3 (Satisfacción Positiva)**: `#10b981` (Emerald 500)
|
||||||
|
- **Serie 4 (Incidencias / Dudas)**: `#f59e0b` (Amber 500)
|
||||||
|
- **Serie 5 (Acceso Externo)**: `#8b5cf6` (Purple 500)
|
||||||
|
- **Fondo de Tooltips**: `rgba(15, 23, 42, 0.94)` (Dark) / `rgba(255, 255, 255, 0.96)` (Light)
|
||||||
|
- **Borde de Tooltips**: `1px solid rgba(57, 169, 0, 0.45)` (Dark) / `rgba(57, 169, 0, 0.35)` (Light)
|
||||||
@ -0,0 +1,257 @@
|
|||||||
|
# Recetas y Plantillas de Componentes y Páginas - CPIC Conecta
|
||||||
|
|
||||||
|
Este archivo provee recetas completas listas para copiar y pegar de los componentes y páginas clave de **CPIC Conecta**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Plantilla Astro Base (`ScrollLayout.astro`)
|
||||||
|
|
||||||
|
Utilizada para envolver cualquier página en Astro con detección instantánea de tema oscuro/claro y precarga de fuentes e iconos:
|
||||||
|
|
||||||
|
```astro
|
||||||
|
---
|
||||||
|
import '../styles/global.css';
|
||||||
|
import '@fortawesome/fontawesome-free/css/all.min.css';
|
||||||
|
|
||||||
|
export interface Props {
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
lang?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
title = "CPIC - Conecta",
|
||||||
|
description = "Asistente Virtual e Intranet del CPIC - SENA",
|
||||||
|
lang = "es"
|
||||||
|
} = Astro.props;
|
||||||
|
---
|
||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang={lang}>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>{title}</title>
|
||||||
|
<meta name="description" content={description} />
|
||||||
|
<meta name="theme-color" content="#00FF00" />
|
||||||
|
<link rel="icon" type="image/png" href="/Logo.png" />
|
||||||
|
<link rel="preload" as="image" href="/background.webp" fetchpriority="high" />
|
||||||
|
<script is:inline>
|
||||||
|
(function () {
|
||||||
|
try {
|
||||||
|
var theme = localStorage.getItem('cpic_theme') || 'dark';
|
||||||
|
document.documentElement.setAttribute('data-theme', theme);
|
||||||
|
if (theme === 'dark') document.documentElement.classList.add('dark');
|
||||||
|
else document.documentElement.classList.remove('dark');
|
||||||
|
} catch (e) {
|
||||||
|
document.documentElement.classList.add('dark');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body class="scroll-page">
|
||||||
|
<slot />
|
||||||
|
|
||||||
|
{/* Page transition loader */}
|
||||||
|
<div id="page-loader">
|
||||||
|
<div style="position:relative;display:flex;align-items:center;justify-content:center">
|
||||||
|
<div class="loader-ring"></div>
|
||||||
|
<div class="loader-ring inner"></div>
|
||||||
|
<div class="loader-logo"></div>
|
||||||
|
</div>
|
||||||
|
<div class="loader-text">Cargando…</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Componente de Entrada de Cristal (`GlassInput.jsx`)
|
||||||
|
|
||||||
|
Estándar para formularios en modo oscuro y claro:
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import React from "react";
|
||||||
|
|
||||||
|
export const GLASS_INPUT_CLASS =
|
||||||
|
"w-full px-4 py-3 bg-white/60 dark:bg-black/40 backdrop-blur-xl border border-black/10 dark:border-white/12 rounded-2xl text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-white/30 focus:outline-none focus:border-[#39A900] focus:ring-2 focus:ring-[#39A900]/20 focus:bg-white/80 dark:focus:bg-black/60 shadow-[inset_0_1px_2px_rgba(0,0,0,0.05)] transition-all text-sm";
|
||||||
|
|
||||||
|
export const GlassInput = React.forwardRef(function GlassInput(
|
||||||
|
{ type = "text", value, onChange, placeholder, disabled, icon, ...props },
|
||||||
|
ref
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<div className="relative w-full flex items-center">
|
||||||
|
{icon && (
|
||||||
|
<span className="absolute left-4 text-gray-400 dark:text-white/40 text-sm pointer-events-none">
|
||||||
|
<i className={`fa-solid ${icon}`} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<input
|
||||||
|
ref={ref}
|
||||||
|
type={type}
|
||||||
|
value={value}
|
||||||
|
onChange={onChange}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
className={`${GLASS_INPUT_CLASS} ${icon ? "pl-11" : ""}`}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Botones Estándar del Sistema
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
// 1. Botón Primario Institucional (Acento Lima con sombra resplandeciente)
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="px-4 py-2.5 rounded-2xl bg-lime text-black font-extrabold text-xs sm:text-sm flex items-center gap-2 shadow-[0_4px_16px_rgba(132,204,22,0.35)] hover:scale-[1.02] active:scale-[0.98] transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-check text-xs" />
|
||||||
|
<span>Guardar Cambios</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
// 2. Botón Secundario (Vidrio Fantasma)
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="px-4 py-2.5 rounded-2xl bg-black/5 dark:bg-white/8 text-gray-700 dark:text-white/80 font-semibold text-xs sm:text-sm border border-black/8 dark:border-white/10 hover:bg-black/10 dark:hover:bg-white/12 active:scale-[0.98] transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<span>Cancelar</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
// 3. Botón de Peligro / Eliminar
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="px-4 py-2.5 rounded-2xl bg-red-500/10 text-red-600 dark:text-red-400 font-semibold text-xs sm:text-sm border border-red-500/25 hover:bg-red-500/20 active:scale-[0.98] transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<i className="fa-solid fa-trash-can text-xs" />
|
||||||
|
<span>Eliminar</span>
|
||||||
|
</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Modal de Confirmación Estándar (`ConfirmModal.jsx`)
|
||||||
|
|
||||||
|
Modal con elevación Tier 3, animación elástica y soporte para cierre con tecla Escape:
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import React, { useEffect } from "react";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
|
||||||
|
export default function ConfirmModal({
|
||||||
|
isOpen,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirmText = "Confirmar",
|
||||||
|
cancelText = "Cancelar",
|
||||||
|
isDanger = false,
|
||||||
|
onConfirm,
|
||||||
|
onCancel
|
||||||
|
}) {
|
||||||
|
useEffect(() => {
|
||||||
|
const handleKeyDown = (e) => {
|
||||||
|
if (e.key === "Escape" && isOpen) onCancel();
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||||
|
}, [isOpen, onCancel]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnimatePresence>
|
||||||
|
{isOpen && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
{/* Fondo oscuro con desenfoque */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
onClick={onCancel}
|
||||||
|
className="fixed inset-0 bg-black/70 backdrop-blur-md"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Tarjeta del diálogo */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, scale: 0.95, y: 15 }}
|
||||||
|
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, scale: 0.95, y: 15 }}
|
||||||
|
className="relative w-full max-w-md bg-white/95 dark:bg-[rgba(15,28,15,0.95)] backdrop-blur-3xl border border-black/10 dark:border-lime/25 rounded-3xl p-6 shadow-[0_20px_50px_rgba(0,0,0,0.4)] z-10"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 mb-4">
|
||||||
|
<div
|
||||||
|
className={`w-10 h-10 rounded-2xl flex items-center justify-center text-lg ${
|
||||||
|
isDanger
|
||||||
|
? "bg-red-500/10 text-red-500 border border-red-500/25"
|
||||||
|
: "bg-lime/15 text-lime-deep dark:text-lime border border-lime/30"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<i className={`fa-solid ${isDanger ? "fa-triangle-exclamation" : "fa-circle-question"}`} />
|
||||||
|
</div>
|
||||||
|
<h3 className="text-base font-bold text-gray-900 dark:text-white">{title}</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs sm:text-sm text-gray-600 dark:text-white/70 leading-relaxed mb-6">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
className="px-4 py-2 rounded-xl text-xs font-semibold text-gray-600 dark:text-white/70 hover:bg-black/5 dark:hover:bg-white/8 transition-colors"
|
||||||
|
>
|
||||||
|
{cancelText}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onConfirm}
|
||||||
|
className={`px-4 py-2 rounded-xl text-xs font-bold transition-all ${
|
||||||
|
isDanger
|
||||||
|
? "bg-red-500 text-white shadow-md hover:bg-red-600 active:scale-95"
|
||||||
|
: "bg-lime text-black shadow-md hover:scale-105 active:scale-95"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{confirmText}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Esqueletos de Carga Shimmer (`Skeleton.jsx`)
|
||||||
|
|
||||||
|
Para evitar saltos de diseño (Cumulative Layout Shift):
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
export function SkeletonBlock({ className = "h-10 w-full" }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`animate-pulse bg-black/5 dark:bg-white/5 rounded-xl border border-black/4 dark:border-white/6 ${className}`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TableRowSkeleton({ cols = 5 }) {
|
||||||
|
return (
|
||||||
|
<tr className="border-b border-black/6 dark:border-white/6">
|
||||||
|
{Array.from({ length: cols }).map((_, idx) => (
|
||||||
|
<td key={idx} className="p-4">
|
||||||
|
<SkeletonBlock className="h-4 w-3/4" />
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,150 @@
|
|||||||
|
# Arquitectura Responsiva y Layouts Multi-Pantalla - CPIC Conecta
|
||||||
|
|
||||||
|
Este documento define la estrategia estructural de interfaz para soportar cualquier dispositivo: smartphones pequeños (`320px`), tablets, laptops de alta resolución y monitores ultrawide (`1440px+`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Diagramas de Disposición por Dispositivo
|
||||||
|
|
||||||
|
### 1.1. Vista Móvil (`< 768px`)
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────┐
|
||||||
|
│ [☰] [Logo] CPIC Conecta [💬 Chat] │ <- Cabecera Compacta (pl-14)
|
||||||
|
├────────────────────────────────────────────────────────┤
|
||||||
|
│ [🏠 Inicio] [🎓 Oferta] [🧭 Misión] [📞 Contacto] │ <- Chips Horizontales (Swipeable)
|
||||||
|
├────────────────────────────────────────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ │
|
||||||
|
│ CONTENIDO PRINCIPAL │
|
||||||
|
│ (Scroll Vertical Fluido) │
|
||||||
|
│ │
|
||||||
|
│ │
|
||||||
|
│ │
|
||||||
|
├────────────────────────────────────────────────────────┤
|
||||||
|
│ [♿] [💬] │ <- Píldora Flotante Inferior
|
||||||
|
└────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
*Cuando se pulsa el botón hamburguesa `[☰]`, se despliega un Drawer lateral off-canvas (`fixed inset-y-0 left-0 z-50`) con telón de fondo oscuro translúcido.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 1.2. Vista de Escritorio Estándar (`1024px` a `1439px`)
|
||||||
|
```
|
||||||
|
┌───────┬────────────────────────────────────────┬───────┐
|
||||||
|
│ APP │ [🏠 Secciones / Títulos Principales] │ RIGHT │
|
||||||
|
│ SIDE │ │ SIDE │
|
||||||
|
│ BAR │ Tarjeta de Sección (Tier 2 Glass) │ BAR │
|
||||||
|
│ │ - Título H1 / H2 │ │
|
||||||
|
│ [🏠] │ - Párrafos de alto contraste │ [Logo]│
|
||||||
|
│ [💬] │ - Botones con acento Lime │ │
|
||||||
|
│ [👥] │ │ [♿] │
|
||||||
|
│ [📊] │ ------------------------------------ │ │
|
||||||
|
│ │ │ [💬] │
|
||||||
|
│ │ (Scroll con Snap Vertical Obligatorio)│ • │ <- Dots Nav
|
||||||
|
│ │ │ • │
|
||||||
|
│ [⚙️] │ │ • │
|
||||||
|
│ [🌓] │ │ │
|
||||||
|
│ [🚪] │ [ 🏷️ CPIC Conecta • SofiaPlus • SENA ] │ │ <- Footer Retráctil
|
||||||
|
└───────┴────────────────────────────────────────┴───────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Especificación Técnica por Rango de Pantalla
|
||||||
|
|
||||||
|
### 2.1. Móvil Pequeño y Estándar (`320px` - `639px`)
|
||||||
|
|
||||||
|
- **Contenedor Principal**:
|
||||||
|
```jsx
|
||||||
|
<div className="h-[100dvh] max-h-[100dvh] w-full flex flex-col p-2 gap-2 overflow-hidden relative">
|
||||||
|
```
|
||||||
|
- **Botón Hamburguesa Flotante**:
|
||||||
|
- Posición: `fixed top-3 left-3 z-30 md:hidden`.
|
||||||
|
- Tamaño: `w-10 h-10 min-w-[40px] min-h-[40px] rounded-xl bg-white/80 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-xl border border-black/8 dark:border-white/10`.
|
||||||
|
- **Barra Superior**:
|
||||||
|
- Espaciado izquierdo obligatorio: `pl-14` para no solaparse con el botón hamburguesa flotante.
|
||||||
|
- **Navegación por Chips**:
|
||||||
|
- Contenedor con `overflow-x-auto flex items-center gap-1.5 py-1 px-1`.
|
||||||
|
- Ocultar scrollbar estándar: `style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}`.
|
||||||
|
- Auto-centrado del chip activo mediante `scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })`.
|
||||||
|
- **Modales en Móvil**:
|
||||||
|
- En lugar de modales centrados flotantes, se convierten en **Bottom Sheets**:
|
||||||
|
```jsx
|
||||||
|
<div className="fixed inset-x-0 bottom-0 rounded-t-3xl max-h-[90dvh] overflow-y-auto p-5 bg-white/95 dark:bg-[rgba(10,24,10,0.95)] backdrop-blur-3xl border-t border-lime/30 z-50">
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2. Tablet Portrait y Landscape (`640px` - `1023px`)
|
||||||
|
|
||||||
|
- **Estructura**:
|
||||||
|
- `sm:` activa rejillas de 2 columnas para tarjetas: `grid grid-cols-1 sm:grid-cols-2 gap-3`.
|
||||||
|
- En `md:` (768px), `AppSidebar` pasa de ser un drawer móvil oculto a ser una barra lateral fija o colapsada a iconos (`w-16`).
|
||||||
|
- Las tablas deben estar envueltas en contenedores de scroll horizontal con sombra indicadora:
|
||||||
|
```jsx
|
||||||
|
<div className="w-full overflow-x-auto rounded-2xl border border-black/8 dark:border-white/10">
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.3. Escritorio Estándar (`1024px` - `1439px`)
|
||||||
|
|
||||||
|
- **Estructura de 3 Columnas**:
|
||||||
|
1. **Columna Izquierda (`AppSidebar`)**: Ancho base colapsado `w-[72px]`, expandible a `w-64` en hover o al pinchar el botón de anclaje.
|
||||||
|
2. **Columna Central (`main`)**: `flex-1 min-w-0 flex flex-col h-full overflow-hidden`.
|
||||||
|
- Snap scrolling vertical: `snap-y snap-mandatory`.
|
||||||
|
- Máscara de desvanecimiento superior e inferior para evitar cortes bruscos:
|
||||||
|
```css
|
||||||
|
mask-image: linear-gradient(to bottom, transparent 0%, black 1.5%, black 98.5%, transparent 100%);
|
||||||
|
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 1.5%, black 98.5%, transparent 100%);
|
||||||
|
```
|
||||||
|
3. **Columna Derecha (`RightSidebar`)**: Ancho `w-14 lg:w-16`, conteniendo el icono de accesibilidad (`AccessibilityPanel`), el iniciador del chat flotante (`FloatingChat`) y el logo institucional.
|
||||||
|
- **Navegador de Puntos**: Columna vertical flotante centrada a la derecha (`hidden lg:flex absolute right-4 top-1/2 -translate-y-1/2`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.4. Pantallas Ultrawide (`1440px+` y monitores 4K)
|
||||||
|
|
||||||
|
- En resoluciones ultrawide, evitar que las burbujas de texto o tablas se extiendan de lado a lado sin límite:
|
||||||
|
- Ancho máximo de tarjetas: `max-w-6xl` o `max-w-7xl` con centrado automático `mx-auto`.
|
||||||
|
- Burbujas de chat: limitadas a `max-w-[75%]` o `max-w-[800px]`.
|
||||||
|
- Formularios de administración: disposición en 2 o 3 columnas de campos en lugar de una lista vertical estirada.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Manejo de Viewport y Safe Areas
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* Altura completa del viewport sin salto por barra de navegador móvil */
|
||||||
|
.app-container {
|
||||||
|
height: 100dvh;
|
||||||
|
max-height: 100dvh;
|
||||||
|
min-height: 100dvh;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Espaciado para iPhone Notch e Isla Dinámica */
|
||||||
|
.safe-padding-top {
|
||||||
|
padding-top: max(0.75rem, env(safe-area-inset-top));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Espaciado para barra de inicio (Home indicator) en iOS y Android */
|
||||||
|
.safe-padding-bottom {
|
||||||
|
padding-bottom: max(0.75rem, env(safe-area-inset-bottom));
|
||||||
|
}
|
||||||
|
|
||||||
|
.safe-right {
|
||||||
|
right: max(0.75rem, env(safe-area-inset-right));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Reglas de Accesibilidad Táctil (Mobile Touch Standards)
|
||||||
|
|
||||||
|
1. **Tamaño Mínimo de Botón**: `min-h-[44px] min-w-[44px]`.
|
||||||
|
2. **Espaciado entre Interactivos**: Mínimo `8px` (`gap-2`) para evitar pulsaciones erróneas.
|
||||||
|
3. **Gestos y Navegación por Teclado**:
|
||||||
|
- `ArrowDown` / `PageDown`: Desplazar a la siguiente sección activa.
|
||||||
|
- `ArrowUp` / `PageUp`: Desplazar a la sección anterior.
|
||||||
|
- `Escape`: Cerrar cualquier drawer, modal o menú abierto.
|
||||||
163
.agents/skills/diagrams-and-data-tables/SKILL.md
Normal file
163
.agents/skills/diagrams-and-data-tables/SKILL.md
Normal file
@ -0,0 +1,163 @@
|
|||||||
|
---
|
||||||
|
name: diagrams-and-data-tables
|
||||||
|
description: >-
|
||||||
|
Guides the creation, structure, and styling of professional Mermaid diagrams
|
||||||
|
(sequence, flowcharts, ERD, state transitions) and high-density, accessible
|
||||||
|
data tables with glassmorphism, responsive behavior, micro-interactions, and WCAG compliance.
|
||||||
|
Use when designing data representations, documenting architecture, or implementing UI tables.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Diagrams and Data Tables Skill
|
||||||
|
|
||||||
|
This skill enforces best practices for visualizing software architecture through **Mermaid diagrams** and creating production-grade, accessible **data tables** across the frontend and technical documentation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 1: Mermaid Diagrams Engineering
|
||||||
|
|
||||||
|
Mermaid diagrams provide living documentation of architectural patterns, data flows, and relational schemas.
|
||||||
|
|
||||||
|
### 1. Core Syntax Rules
|
||||||
|
- **Quote Node Labels**: Always quote labels containing special characters, brackets, or parentheses: `id["Process (Async)"]`.
|
||||||
|
- **Avoid HTML in Labels**: Use pure Markdown formatting or plain text; avoid `<br/>` or raw tags where Mermaid may parse them incorrectly.
|
||||||
|
- **Direction & Clean Layout**: Use `flowchart TD` (top-down) for hierarchical flows or `flowchart LR` (left-to-right) for sequential pipelines.
|
||||||
|
|
||||||
|
### 2. Common Diagram Patterns
|
||||||
|
|
||||||
|
#### A. Sequence Diagram: WebSocket Client-Server Flow
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
autonumber
|
||||||
|
actor User as Usuario / Client
|
||||||
|
participant UI as React Frontend
|
||||||
|
participant WS as WebSocket Server (Ratchet)
|
||||||
|
participant Auth as JWT Guard
|
||||||
|
participant RAG as RAG / Gemini Engine
|
||||||
|
participant DB as MySQL Database
|
||||||
|
|
||||||
|
User->>UI: Escribe mensaje
|
||||||
|
UI->>WS: {"action": "chat_message", "token": "jwt..."}
|
||||||
|
WS->>Auth: Validar token y rol
|
||||||
|
Auth-->>WS: Rol verificado (e.g. Interno)
|
||||||
|
WS->>RAG: Consultar Base Conocimiento / Embeddings
|
||||||
|
RAG->>DB: SELECT cosine_similarity...
|
||||||
|
DB-->>RAG: Documentos relevantes
|
||||||
|
RAG-->>WS: Stream chunks de respuesta
|
||||||
|
WS-->>UI: {"type": "stream_chunk", "chunk": "..."}
|
||||||
|
UI-->>User: Renderizado progresivo
|
||||||
|
```
|
||||||
|
|
||||||
|
#### B. Flowchart: RAG Query & Tool Routing
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A["Entrada del Usuario"] --> B{"¿Consulta de Horarios / Ambientes?"}
|
||||||
|
B -- "Sí" --> C["Tool: CRONODE API"]
|
||||||
|
B -- "No" --> D{"¿Búsqueda en Base de Conocimiento?"}
|
||||||
|
|
||||||
|
C --> E["Formatear Matriz / Calendario"]
|
||||||
|
D -- "Sí" --> F["Búsqueda Vectorial (Cosine Similarity)"]
|
||||||
|
D -- "No" --> G["Generación General Gemini LLM"]
|
||||||
|
|
||||||
|
F --> H["Inyectar Contexto RAG"]
|
||||||
|
H --> I["Generar Respuesta Verificada"]
|
||||||
|
E --> J["Enviar Payload + Table Data al Cliente"]
|
||||||
|
I --> J
|
||||||
|
G --> J
|
||||||
|
```
|
||||||
|
|
||||||
|
#### C. Entity-Relationship Diagram (ERD)
|
||||||
|
```mermaid
|
||||||
|
erDiagram
|
||||||
|
usuarios ||--o{ chat_historial : "posee"
|
||||||
|
usuarios ||--o{ conversaciones : "registra"
|
||||||
|
roles ||--o{ usuarios : "asigna_a"
|
||||||
|
categorias ||--o{ temas : "agrupa"
|
||||||
|
temas ||--o{ preguntas_respuestas : "contiene"
|
||||||
|
temas ||--o{ documentos : "asocia"
|
||||||
|
|
||||||
|
usuarios {
|
||||||
|
int id PK
|
||||||
|
string email
|
||||||
|
string rol
|
||||||
|
boolean activo
|
||||||
|
}
|
||||||
|
categorias {
|
||||||
|
int id PK
|
||||||
|
string nombre
|
||||||
|
text descripcion
|
||||||
|
}
|
||||||
|
temas {
|
||||||
|
int id PK
|
||||||
|
int categoria_id FK
|
||||||
|
string nombre
|
||||||
|
}
|
||||||
|
preguntas_respuestas {
|
||||||
|
int id PK
|
||||||
|
int tema_id FK
|
||||||
|
text pregunta
|
||||||
|
text respuesta
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 2: High-Density UI Data Tables
|
||||||
|
|
||||||
|
When creating data tables in the frontend (React / Tailwind / Vanilla CSS):
|
||||||
|
|
||||||
|
### 1. Visual Aesthetics & Design System Tokens
|
||||||
|
- **Glassmorphism Base**:
|
||||||
|
```html
|
||||||
|
<div className="overflow-x-auto custom-scrollbar w-full rounded-2xl border border-black/8 dark:border-white/10 bg-white/70 dark:bg-[rgba(10,22,10,0.75)] backdrop-blur-xl shadow-xs">
|
||||||
|
<table className="w-full text-left text-xs border-collapse min-w-[600px]">
|
||||||
|
```
|
||||||
|
- **Institutional Headers (SENA Palette)**:
|
||||||
|
```html
|
||||||
|
<thead className="bg-[#39A900] dark:bg-[rgba(57,169,0,0.85)] text-white font-semibold text-[11px] sticky top-0 z-10">
|
||||||
|
<tr>
|
||||||
|
<th scope="col" className="py-2.5 px-3.5 whitespace-nowrap">ID</th>
|
||||||
|
<th scope="col" className="py-2.5 px-3.5 whitespace-nowrap">Nombre</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
```
|
||||||
|
- **Zebra Striping & Hover States**:
|
||||||
|
- Even rows: `even:bg-black/[0.02] dark:even:bg-white/[0.02]`
|
||||||
|
- Hover: `hover:bg-[#39A900]/8 dark:hover:bg-lime/8 transition-colors`
|
||||||
|
- Subtle cell borders: `border-b border-black/6 dark:border-white/6`
|
||||||
|
|
||||||
|
### 2. Rich Cell Typography & Components
|
||||||
|
- **Status Badges**:
|
||||||
|
- Active / Free: `bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 border border-emerald-500/30`
|
||||||
|
- Inactive / Occupied: `bg-red-500/15 text-red-700 dark:text-red-400 border border-red-500/30`
|
||||||
|
- Pending / Warning: `bg-amber-500/15 text-amber-700 dark:text-amber-400 border border-amber-500/30`
|
||||||
|
- **Action Buttons**: Icon-first buttons with active scale:
|
||||||
|
`p-1.5 rounded-lg bg-black/5 dark:bg-white/5 hover:bg-black/10 dark:hover:bg-white/10 active:scale-95 transition-all`
|
||||||
|
- **Text Truncation**: Use `max-w-[200px] truncate` with `title={val}` on hover to prevent column blowout.
|
||||||
|
|
||||||
|
### 3. Responsive Table Adaptations (Mobile-First)
|
||||||
|
- **Container Scroll**: Always wrap tables in `overflow-x-auto custom-scrollbar` so mobile viewports swipe horizontally without breaking parent layout boundaries.
|
||||||
|
- **Card-View Alternative**: For complex administrative views (e.g., `CrudPage.jsx`), provide a toggle between structured table view (`viewMode="table"`) and card grid view (`viewMode="card"`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 3: Markdown Tables Standards for Reports & Artifacts
|
||||||
|
|
||||||
|
For Markdown artifacts, technical documentation, and summaries:
|
||||||
|
|
||||||
|
1. **Alignment Conventions**:
|
||||||
|
- Left-align text / descriptions: `:---`
|
||||||
|
- Center-align statuses, IDs, counts, dates: `:---:`
|
||||||
|
- Right-align monetary amounts, latencies, percentages: `---:`
|
||||||
|
|
||||||
|
2. **Standard Report Table Structure**:
|
||||||
|
```markdown
|
||||||
|
| Módulo / Tabla | Registros | Estado | Latencia (p95) | Observaciones |
|
||||||
|
| :--- | :---: | :---: | ---: | :--- |
|
||||||
|
| `categorias` | 123 | ✅ Activo | 12 ms | Acceso según permisos de rol |
|
||||||
|
| `preguntas_respuestas` | 804 | ✅ Indexado | 48 ms | Embeddings vectoriales al 100% |
|
||||||
|
| `conversaciones` | 0 | 🧹 Limpio | — | Historial en estado inicial |
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Readability Rules**:
|
||||||
|
- Keep column counts under 6 columns in standard markdown to avoid horizontal squishing.
|
||||||
|
- Use bold markdown for key metrics and inline code formatting for table names or routes.
|
||||||
231
.agents/skills/github-flow/SKILL.md
Normal file
231
.agents/skills/github-flow/SKILL.md
Normal file
@ -0,0 +1,231 @@
|
|||||||
|
---
|
||||||
|
name: github-flow
|
||||||
|
description: >-
|
||||||
|
Guides git and GitHub workflow using GitHub Flow: branch creation off main,
|
||||||
|
atomic conventional commits, pull requests, automated CI checks, code reviews,
|
||||||
|
merge strategies, and branch cleanup. Use when creating branches, preparing commits,
|
||||||
|
managing PRs, resolving merge conflicts, or integrating changes into main.
|
||||||
|
---
|
||||||
|
|
||||||
|
# GitHub Flow: Branching, Commits, and Pull Requests
|
||||||
|
|
||||||
|
A lightweight, branch-based workflow optimized for continuous delivery, code quality, and rapid iteration. Under **GitHub Flow**, the `main` branch is always stable and deployable, and all new features, bugfixes, or refactors are developed in dedicated, short-lived branches integrated via Pull Requests (PRs).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Core Principles of GitHub Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
main (deployable) ───────────────────●──────────────────────●───────►
|
||||||
|
\ / /
|
||||||
|
feat/chat-export ●───●─────● (PR #42: Merged) /
|
||||||
|
\ /
|
||||||
|
fix/socket-reconnect ●──────●─────────────────● (PR #43: Merged)
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **`main` is always deployable**: No untested or half-finished code is committed directly to `main`.
|
||||||
|
2. **Branch from `main`**: Always create descriptive branches directly from the latest updated `main`.
|
||||||
|
3. **Commit early and atomically**: Small, logical commits following the **Conventional Commits** specification.
|
||||||
|
4. **Open a Pull Request early**: Open a PR as soon as work is ready (or draft PR for early feedback).
|
||||||
|
5. **Review and discuss**: Solicit feedback, pass CI tests, and address comments.
|
||||||
|
6. **Merge and delete branch**: Integrate into `main` (Squash & Merge or Rebase & Merge) and immediately delete the feature branch.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Step-by-Step Workflow Guide
|
||||||
|
|
||||||
|
### Step 1: Synchronize `main` & Create Feature Branch
|
||||||
|
|
||||||
|
Before starting any new task, ensure your local `main` matches the remote repository:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Switch to main and pull latest changes
|
||||||
|
git checkout main
|
||||||
|
git pull --ff-only origin main
|
||||||
|
|
||||||
|
# Create a new branch with a semantic prefix
|
||||||
|
git checkout -b <type>/<short-description>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Branch Naming Conventions:
|
||||||
|
| Prefix | Purpose | Example |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `feat/` | New feature or capability | `feat/speech-to-text` |
|
||||||
|
| `fix/` | Bugfix or patch | `fix/admin-session-timeout` |
|
||||||
|
| `refactor/` | Code refactoring without behavior change | `refactor/websocket-handler` |
|
||||||
|
| `perf/` | Performance improvement | `perf/vector-search-indexing` |
|
||||||
|
| `docs/` | Documentation only | `docs/api-endpoints-guide` |
|
||||||
|
| `test/` | Adding or correcting unit/integration tests | `test/faq-repository-suite` |
|
||||||
|
| `chore/` | Maintenance, dependencies, build configs | `chore/upgrade-vite` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Step 2: Atomic Commits with Conventional Commits
|
||||||
|
|
||||||
|
Keep each commit focused on a single logical change. Follow the **Conventional Commits** format:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<type>(<scope>): <short imperative summary>
|
||||||
|
|
||||||
|
[optional body explaining WHY and WHAT changed]
|
||||||
|
|
||||||
|
[optional footer: Closes #123, BREAKING CHANGE: ...]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Commit Types:
|
||||||
|
* `feat`: A new feature for the user or system.
|
||||||
|
* `fix`: A bug fix.
|
||||||
|
* `refactor`: Code change that neither fixes a bug nor adds a feature.
|
||||||
|
* `style`: Formatting, missing semicolons, whitespace (no code logic change).
|
||||||
|
* `perf`: Performance optimization.
|
||||||
|
* `test`: Adding missing tests or refactoring test suites.
|
||||||
|
* `docs`: Documentation updates.
|
||||||
|
* `chore`: Build process, package updates, tooling config.
|
||||||
|
|
||||||
|
#### Good vs. Bad Commits:
|
||||||
|
* ✅ `feat(chat): add auto-reconnect backoff on WebSocket disconnect`
|
||||||
|
* ✅ `fix(auth): prevent token leakage in error response payloads`
|
||||||
|
* ❌ `changes`
|
||||||
|
* ❌ `fixed stuff and updated tests and ui`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Step 3: Local Verification & Pre-Push Validation
|
||||||
|
|
||||||
|
Before pushing, verify code quality, syntax, and test suites locally:
|
||||||
|
|
||||||
|
1. **Check status & modified files**:
|
||||||
|
```bash
|
||||||
|
git status
|
||||||
|
git diff
|
||||||
|
```
|
||||||
|
2. **Run tests & linters** (project specific):
|
||||||
|
```bash
|
||||||
|
# Run frontend build / lint if applicable
|
||||||
|
npm run build
|
||||||
|
# Run backend tests / static analysis if applicable
|
||||||
|
composer test
|
||||||
|
```
|
||||||
|
3. **Verify no sensitive secrets or temporary files are staged**:
|
||||||
|
Ensure `.env`, credentials, local cache files, or `.system_generated/` are ignored in `.gitignore`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Step 4: Push to Remote & Open Pull Request
|
||||||
|
|
||||||
|
Push the branch to `origin` setting the upstream tracking:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git push -u origin <branch-name>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Creating the PR:
|
||||||
|
- **Using GitHub CLI (`gh`)**:
|
||||||
|
```bash
|
||||||
|
gh pr create --title "feat(chat): implement speech-to-text integration" --body-file .agents/skills/github-flow/references/pull-request-template.md
|
||||||
|
```
|
||||||
|
- **Using GitHub Web**: Navigate to repository URL, click **Compare & pull request**, and fill in the PR template.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Step 5: Keep Branch Synchronized with `main`
|
||||||
|
|
||||||
|
If other PRs were merged into `main` while working on your branch, rebase your branch on top of latest `main` to maintain clean history:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Fetch latest main without switching branches
|
||||||
|
git fetch origin main
|
||||||
|
|
||||||
|
# Rebase feature branch on origin/main
|
||||||
|
git rebase origin/main
|
||||||
|
|
||||||
|
# If conflicts occur:
|
||||||
|
# 1. Edit conflicting files and resolve markers (<<<<<<< / ======= / >>>>>>>)
|
||||||
|
# 2. Stage resolved files: git add <resolved-file>
|
||||||
|
# 3. Continue rebase: git rebase --continue
|
||||||
|
# 4. Force-push with lease:
|
||||||
|
git push --force-with-lease origin <branch-name>
|
||||||
|
```
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> Always use `--force-with-lease` instead of `--force` when pushing rebased branches to prevent overwriting team member commits.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Step 6: Code Review, Approval, & Merge
|
||||||
|
|
||||||
|
1. **Review**: Team members and automated CI pipelines review the PR.
|
||||||
|
2. **Address Feedback**: Push additional commits to the same branch; GitHub updates the PR automatically.
|
||||||
|
3. **Merge Method**:
|
||||||
|
* **Squash and Merge** (Recommended for feature branches): Combines all branch commits into one clean commit on `main`.
|
||||||
|
* **Rebase and Merge**: Retains individual commits in a flat linear history.
|
||||||
|
4. **Branch Cleanup**:
|
||||||
|
```bash
|
||||||
|
# Delete remote branch (GitHub web does this via button or gh)
|
||||||
|
gh pr merge --squash --delete-branch
|
||||||
|
|
||||||
|
# Or locally clean up:
|
||||||
|
git checkout main
|
||||||
|
git pull --ff-only origin main
|
||||||
|
git branch -d <branch-name>
|
||||||
|
git remote prune origin
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Pull Request Template Standard
|
||||||
|
|
||||||
|
When opening a PR, structure the description with the following markdown format:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Description
|
||||||
|
Provide a concise overview of what this PR does and why it was created.
|
||||||
|
|
||||||
|
## Type of Change
|
||||||
|
- [ ] 🚀 New feature (non-breaking change adding functionality)
|
||||||
|
- [ ] 🐛 Bug fix (non-breaking change fixing an issue)
|
||||||
|
- [ ] ♻️ Refactoring (clean code, structure improvement)
|
||||||
|
- [ ] ⚡ Performance optimization
|
||||||
|
- [ ] 📝 Documentation update
|
||||||
|
- [ ] 🔒 Security patch
|
||||||
|
|
||||||
|
## Key Changes
|
||||||
|
- Detailed bullet points of main changes
|
||||||
|
- Touched components, models, or endpoints
|
||||||
|
|
||||||
|
## How Has This Been Tested?
|
||||||
|
- [ ] Unit tests pass
|
||||||
|
- [ ] Integration tests pass
|
||||||
|
- [ ] Manual test in local browser/environment
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
- [ ] Code follows project style guidelines and naming conventions.
|
||||||
|
- [ ] Self-review conducted; no console.logs or dead debug code left behind.
|
||||||
|
- [ ] No sensitive credentials, secrets, or .env files included.
|
||||||
|
- [ ] Documentation updated where relevant.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Git Emergency & Utility Cheatsheet
|
||||||
|
|
||||||
|
| Task | Command |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **Discard unstaged changes in a file** | `git restore <file>` |
|
||||||
|
| **Unstage a file without losing changes** | `git restore --staged <file>` |
|
||||||
|
| **Undo last commit keeping changes staged** | `git reset --soft HEAD~1` |
|
||||||
|
| **Temporarily stash work in progress** | `git stash save "wip: message"` |
|
||||||
|
| **Restore stashed work** | `git stash pop` |
|
||||||
|
| **Clean untracked files & directories** | `git clean -fd` (Use with caution!) |
|
||||||
|
| **View pretty one-line git log graph** | `git log --oneline --graph --decorate -n 15` |
|
||||||
|
| **Show diff of staged changes** | `git diff --cached` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Integration with Scrum Multi-Agent Framework
|
||||||
|
|
||||||
|
When working with `scrum-multi-agent-orchestration`:
|
||||||
|
1. **Developer Agents (Frontend / Backend)**: Create branches named `feat/<ticket-id>-description` or `fix/<ticket-id>-description`.
|
||||||
|
2. **QA Agent**: Checks out the branch, executes verification test suites, and posts results to the PR.
|
||||||
|
3. **Code Reviewer Agent**: Audits the PR diff against security, clean code, accessibility (WCAG), and Definition of Done (DoD).
|
||||||
|
4. **Scrum Master / Tech Lead**: Approves and triggers Squash & Merge into `main`.
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
## Description
|
||||||
|
<!-- Provide a concise overview of what this PR does and why it was created. Link relevant issue if applicable. -->
|
||||||
|
Closes #
|
||||||
|
|
||||||
|
## Type of Change
|
||||||
|
- [ ] 🚀 `feat`: New feature or capability
|
||||||
|
- [ ] 🐛 `fix`: Bug fix
|
||||||
|
- [ ] ♻️ `refactor`: Code reorganization without behavioral change
|
||||||
|
- [ ] ⚡ `perf`: Performance enhancement
|
||||||
|
- [ ] 📝 `docs`: Documentation addition or update
|
||||||
|
- [ ] 🧪 `test`: Adding or adjusting automated test coverage
|
||||||
|
- [ ] 🔧 `chore`: Tooling, build config, or dependency update
|
||||||
|
|
||||||
|
## Key Changes
|
||||||
|
<!-- Highlight the specific files or modules affected and what changed -->
|
||||||
|
-
|
||||||
|
|
||||||
|
## Verification & Testing
|
||||||
|
<!-- Describe how you verified your changes -->
|
||||||
|
- [ ] Automated tests run and passed (`npm test` / `composer test`)
|
||||||
|
- [ ] Manual test in local environment
|
||||||
|
- [ ] Responsive design verified (mobile, tablet, desktop)
|
||||||
|
- [ ] No regression detected in related features
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
- [ ] My code follows the project's coding standards and design system.
|
||||||
|
- [ ] I have performed a self-review of my code.
|
||||||
|
- [ ] No leftover debug `console.log` statements or sensitive keys/secrets committed.
|
||||||
|
- [ ] Branch is rebased against the latest `origin/main`.
|
||||||
60
.agents/skills/modern-ui-design-system/SKILL.md
Normal file
60
.agents/skills/modern-ui-design-system/SKILL.md
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
---
|
||||||
|
name: modern-ui-design-system
|
||||||
|
description: >-
|
||||||
|
Provides modern design system guidelines, glassmorphism aesthetics, institutional CPIC/SENA color palettes,
|
||||||
|
micro-interactions, and visual polish. Use when styling, redesigning, or creating UI components to ensure
|
||||||
|
a premium, coherent, and attractive aesthetic.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Modern UI Design System Skill
|
||||||
|
|
||||||
|
## Visual Language & Design Tokens
|
||||||
|
|
||||||
|
1. **Color Palette**:
|
||||||
|
- **Brand Primary**: Emerald & Lime green institutional accents.
|
||||||
|
- Dark Mode Accent: `text-lime` (`#a3e635` / `#84cc16`), `bg-lime/10`, `border-lime/20`.
|
||||||
|
- Light Mode Accent: `#15803d` (Emerald 700) / `#16a34a` (Emerald 600) for contrast.
|
||||||
|
- **Background Surfaces**:
|
||||||
|
- Dark Mode Base: Obsidian / Void black (`#0a0a0a` or `#0a160a`).
|
||||||
|
- Dark Mode Cards: `bg-white/[0.04]` to `bg-white/[0.08]` with `backdrop-blur-xl`.
|
||||||
|
- Light Mode Base: Soft neutral slate / alabaster (`#f8fafc` or `#f3f4f6`).
|
||||||
|
- Light Mode Cards: `bg-white/85` with `backdrop-blur-xl`.
|
||||||
|
- **Borders & Dividers**:
|
||||||
|
- Dark Mode: `border-white/10` or `border-white/[0.08]`.
|
||||||
|
- Light Mode: `border-black/[0.08]` or `border-slate-200/80`.
|
||||||
|
- **Typography Shades**:
|
||||||
|
- Dark Mode: Primary `text-white`, secondary `text-white/70`, muted `text-white/40`.
|
||||||
|
- Light Mode: Primary `text-slate-900`, secondary `text-slate-700`, muted `text-slate-500`.
|
||||||
|
|
||||||
|
2. **Glassmorphism Guidelines**:
|
||||||
|
- Always pair `backdrop-blur-xl` or `backdrop-blur-2xl` with a subtle 1px border.
|
||||||
|
- Example container class:
|
||||||
|
```html
|
||||||
|
bg-white/80 dark:bg-[rgba(10,22,10,0.85)] backdrop-blur-2xl border border-black/8 dark:border-white/10 rounded-2xl shadow-[0_4px_24px_rgba(0,0,0,0.06)] dark:shadow-[0_4px_24px_rgba(0,0,0,0.25)]
|
||||||
|
```
|
||||||
|
- Avoid solid opaque white or solid pitch black boxes unless explicitly serving as high-contrast dialogs.
|
||||||
|
|
||||||
|
3. **Micro-Interactions & Transitions**:
|
||||||
|
- **Interactive Elements**: All buttons, links, and cards must specify transitions:
|
||||||
|
`transition-all duration-200 ease-out`.
|
||||||
|
- **Hover Effects**:
|
||||||
|
- Subtle elevation or scaling: `hover:scale-[1.01]` or `hover:scale-[1.02]`.
|
||||||
|
- Border highlight: `hover:border-lime/30` or `hover:bg-white/[0.08]`.
|
||||||
|
- **Active State Feedback**:
|
||||||
|
- Button press feel: `active:scale-[0.98]`.
|
||||||
|
- **Focus Rings**:
|
||||||
|
- `focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-lime focus-visible:ring-offset-2 focus-visible:ring-offset-black`.
|
||||||
|
|
||||||
|
4. **Feedback & Loading States**:
|
||||||
|
- Never use raw text without containers or jarring layout shifts.
|
||||||
|
- **Skeleton Loaders**: Use pulsating shimmer blocks:
|
||||||
|
```html
|
||||||
|
<div className="animate-pulse bg-white/10 dark:bg-white/5 rounded-xl h-10 w-full" />
|
||||||
|
```
|
||||||
|
- **Typing / Thinking Indicator**: Smooth pulse or animated dot sequence (`animate-bounce`).
|
||||||
|
|
||||||
|
5. **Iconography**:
|
||||||
|
- Standardize on FontAwesome solid / regular icons with consistent sizing:
|
||||||
|
- Inline buttons: `text-sm` or `text-base`.
|
||||||
|
- Badges / chips: `text-xs`.
|
||||||
|
- Navigation headers: `w-5 h-5` / `text-base` centered in `w-9 h-9` rounded containers.
|
||||||
75
.agents/skills/premium-motion-animations/SKILL.md
Normal file
75
.agents/skills/premium-motion-animations/SKILL.md
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
---
|
||||||
|
name: premium-motion-animations
|
||||||
|
description: >-
|
||||||
|
Guides the implementation of fluid motion design, physics-based Bézier transitions, staggered entry animations,
|
||||||
|
border glows, and tactile micro-interactions for frontend components. Use when creating, animating, or polishing
|
||||||
|
interactive components, modals, chat messages, or transitions to achieve a state-of-the-art SaaS look and feel.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Premium Motion & Animation Skill
|
||||||
|
|
||||||
|
## Core Animation Guidelines
|
||||||
|
|
||||||
|
1. **Physics-Based Bézier Easing**:
|
||||||
|
- Never use default linear transitions for layout elements or panels.
|
||||||
|
- Use high-end cubic-bezier curves for fluid acceleration and natural deceleration:
|
||||||
|
- **Enter / Reveal curve**: `cubic-bezier(0.16, 1, 0.3, 1)` (smooth elastic ease-out).
|
||||||
|
- **Exit / Dismiss curve**: `cubic-bezier(0.7, 0, 0.84, 0)` (crisp ease-in).
|
||||||
|
- **Snappy micro-interactions**: `cubic-bezier(0.2, 0.8, 0.2, 1)`.
|
||||||
|
|
||||||
|
2. **Staggered Cascade Entries (Lists & Messages)**:
|
||||||
|
- When rendering lists of cards, chat messages, or topic chips, stagger their entrance animations so they do not all pop in simultaneously.
|
||||||
|
- Example implementation with dynamic animation delays:
|
||||||
|
```jsx
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<div
|
||||||
|
key={item.id}
|
||||||
|
className="animate-slide-up opacity-0"
|
||||||
|
style={{ animationDelay: `${index * 40}ms`, animationFillMode: 'forwards' }}
|
||||||
|
>
|
||||||
|
{item.content}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Keyframe Definitions (Tailwind / CSS)**:
|
||||||
|
- **Slide & Fade In**:
|
||||||
|
```css
|
||||||
|
@keyframes slideUpFade {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(12px) scale(0.98);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **Beacon Pulse (Radar)**:
|
||||||
|
```html
|
||||||
|
<span className="relative flex h-2.5 w-2.5">
|
||||||
|
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-lime-400 opacity-75" />
|
||||||
|
<span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-lime-500" />
|
||||||
|
</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Tactile Hover & Press Micro-Interactions**:
|
||||||
|
- Buttons, action cards, and icons must communicate physics feedback:
|
||||||
|
- Base: `transition-all duration-200 ease-out`
|
||||||
|
- Hover: `hover:scale-[1.02] hover:-translate-y-0.5`
|
||||||
|
- Active / Click: `active:scale-[0.97] active:translate-y-0`
|
||||||
|
- Subtle brightness/glow change: `hover:shadow-[0_4px_20px_rgba(132,204,22,0.2)]`
|
||||||
|
|
||||||
|
5. **Animated Border Beams & Shimmers**:
|
||||||
|
- Active cards and focused search bars can use a gradient border sweep or subtle shimmer:
|
||||||
|
```css
|
||||||
|
background: linear-gradient(60deg, rgba(255,255,255,0.05), rgba(132,204,22,0.15), rgba(255,255,255,0.05));
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: shimmer 4s infinite linear;
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Hardware Acceleration & Performance**:
|
||||||
|
- Always animate GPU-accelerated properties: `transform`, `opacity`, `filter`.
|
||||||
|
- Never animate layout geometry properties like `height`, `width`, `top`, `left`, `margin`, or `padding` directly when animating motion; use transforms (`scale`, `translate3d`).
|
||||||
|
- Add `will-change: transform, opacity` only during active transitions, avoiding long-term memory leaks.
|
||||||
60
.agents/skills/premium-visual-polish/SKILL.md
Normal file
60
.agents/skills/premium-visual-polish/SKILL.md
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
---
|
||||||
|
name: premium-visual-polish
|
||||||
|
description: >-
|
||||||
|
Provides guidelines for high-end visual depth, ambient background glow, refined glassmorphism, inner highlights,
|
||||||
|
and typographic polish. Use when styling, modernizing, or refining UI components to impart a luxury, top-tier
|
||||||
|
software aesthetic (Linear/Apple/Vercel style).
|
||||||
|
---
|
||||||
|
|
||||||
|
# Premium Visual Polish Skill
|
||||||
|
|
||||||
|
## Visual Depth & Luxury Aesthetic
|
||||||
|
|
||||||
|
1. **Ambient Glow Blobs**:
|
||||||
|
- Backgrounds should avoid flat black or plain gray. Add soft, blurred ambient colored orbs to create atmospheric depth:
|
||||||
|
```jsx
|
||||||
|
<div className="fixed inset-0 pointer-events-none overflow-hidden -z-10">
|
||||||
|
<div className="absolute -top-40 -left-40 w-96 h-96 bg-lime-500/10 rounded-full blur-[100px] animate-pulse duration-[8000ms]" />
|
||||||
|
<div className="absolute top-1/2 -right-40 w-96 h-96 bg-emerald-500/8 rounded-full blur-[120px]" />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **3-Tier Layered Glass Elevation System**:
|
||||||
|
- **Tier 1 (Base Shell)**:
|
||||||
|
- Dark: `bg-[#0a0a0a]` or `bg-[#071107]` with subtle radial gradients.
|
||||||
|
- Light: `bg-[#f8fafc]` (slate-50) with delicate alabaster tones.
|
||||||
|
- **Tier 2 (Structural Cards & Sidebars)**:
|
||||||
|
- Dark: `bg-[rgba(10,22,10,0.75)] backdrop-blur-2xl border border-white/10 shadow-[0_4px_24px_rgba(0,0,0,0.2)]`
|
||||||
|
- Light: `bg-white/85 backdrop-blur-2xl border border-black/8 shadow-[0_4px_24px_rgba(0,0,0,0.06)]`
|
||||||
|
- **Tier 3 (Floating Popovers, Menus, Modals)**:
|
||||||
|
- Dark: `bg-[rgba(15,28,15,0.92)] backdrop-blur-3xl border border-lime/20 shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_24px_rgba(132,204,22,0.08)]`
|
||||||
|
- Light: `bg-white/95 backdrop-blur-3xl border border-slate-200 shadow-[0_16px_48px_rgba(0,0,0,0.12)]`
|
||||||
|
|
||||||
|
3. **Inner Highlights & Glass Edge Sheen**:
|
||||||
|
- High-end glass elements feature a top edge highlight representing light hitting the beveled glass edge:
|
||||||
|
```css
|
||||||
|
box-shadow: inset 0 1px 0 0 rgba(255, 255, 255, 0.12), 0 4px 20px rgba(0, 0, 0, 0.25);
|
||||||
|
```
|
||||||
|
- For primary buttons:
|
||||||
|
```css
|
||||||
|
box-shadow: inset 0 1px 0 0 rgba(255, 255, 255, 0.25), 0 2px 8px rgba(132, 204, 22, 0.3);
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Typography & Hierarchy**:
|
||||||
|
- **Headings & Titles**: Use tight letter-spacing: `tracking-tight` (`letter-spacing: -0.025em`) to feel modern and intentional.
|
||||||
|
- **Numbers & Metrics**: Use tabular figures (`font-variant-numeric: tabular-nums` or `tabular-nums`) to prevent jitter in counters, dates, and timestamps.
|
||||||
|
- **Labels & Subtitles**: Uppercase micro-labels with wide letter-spacing (`text-[10px] font-semibold tracking-wider uppercase text-lime/80`).
|
||||||
|
|
||||||
|
5. **Icon Containers & Badges**:
|
||||||
|
- Avoid naked icons on bare backgrounds. Place icons in subtle glass badges:
|
||||||
|
```jsx
|
||||||
|
<div className="w-8 h-8 rounded-xl bg-white/5 dark:bg-white/5 border border-white/10 flex items-center justify-center text-lime shadow-sm">
|
||||||
|
<i className="fa-solid fa-sparkles text-sm" />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Empty States & Refined Placeholders**:
|
||||||
|
- Empty states should look designed, not like missing content. Include:
|
||||||
|
- A subtle glass badge with a soft glow behind the icon.
|
||||||
|
- A concise title (`text-sm font-semibold text-white/80`).
|
||||||
|
- A helpful hint (`text-xs text-white/40 max-w-xs text-center`).
|
||||||
2249
.agents/skills/react-best-practices/AGENTS.md
Normal file
2249
.agents/skills/react-best-practices/AGENTS.md
Normal file
File diff suppressed because it is too large
Load Diff
123
.agents/skills/react-best-practices/README.md
Normal file
123
.agents/skills/react-best-practices/README.md
Normal file
@ -0,0 +1,123 @@
|
|||||||
|
# React Best Practices
|
||||||
|
|
||||||
|
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
- `rules/` - Individual rule files (one per rule)
|
||||||
|
- `_sections.md` - Section metadata (titles, impacts, descriptions)
|
||||||
|
- `_template.md` - Template for creating new rules
|
||||||
|
- `area-description.md` - Individual rule files
|
||||||
|
- `src/` - Build scripts and utilities
|
||||||
|
- `metadata.json` - Document metadata (version, organization, abstract)
|
||||||
|
- __`AGENTS.md`__ - Compiled output (generated)
|
||||||
|
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Build AGENTS.md from rules:
|
||||||
|
```bash
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Validate rule files:
|
||||||
|
```bash
|
||||||
|
pnpm validate
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Extract test cases:
|
||||||
|
```bash
|
||||||
|
pnpm extract-tests
|
||||||
|
```
|
||||||
|
|
||||||
|
## Creating a New Rule
|
||||||
|
|
||||||
|
1. Copy `rules/_template.md` to `rules/area-description.md`
|
||||||
|
2. Choose the appropriate area prefix:
|
||||||
|
- `async-` for Eliminating Waterfalls (Section 1)
|
||||||
|
- `bundle-` for Bundle Size Optimization (Section 2)
|
||||||
|
- `server-` for Server-Side Performance (Section 3)
|
||||||
|
- `client-` for Client-Side Data Fetching (Section 4)
|
||||||
|
- `rerender-` for Re-render Optimization (Section 5)
|
||||||
|
- `rendering-` for Rendering Performance (Section 6)
|
||||||
|
- `js-` for JavaScript Performance (Section 7)
|
||||||
|
- `advanced-` for Advanced Patterns (Section 8)
|
||||||
|
3. Fill in the frontmatter and content
|
||||||
|
4. Ensure you have clear examples with explanations
|
||||||
|
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
|
||||||
|
|
||||||
|
## Rule File Structure
|
||||||
|
|
||||||
|
Each rule file should follow this structure:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
title: Rule Title Here
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: Optional description
|
||||||
|
tags: tag1, tag2, tag3
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rule Title Here
|
||||||
|
|
||||||
|
Brief explanation of the rule and why it matters.
|
||||||
|
|
||||||
|
**Incorrect (description of what's wrong):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Bad code example
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (description of what's right):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Good code example
|
||||||
|
```
|
||||||
|
|
||||||
|
Optional explanatory text after examples.
|
||||||
|
|
||||||
|
Reference: [Link](https://example.com)
|
||||||
|
|
||||||
|
## File Naming Convention
|
||||||
|
|
||||||
|
- Files starting with `_` are special (excluded from build)
|
||||||
|
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
|
||||||
|
- Section is automatically inferred from filename prefix
|
||||||
|
- Rules are sorted alphabetically by title within each section
|
||||||
|
- IDs (e.g., 1.1, 1.2) are auto-generated during build
|
||||||
|
|
||||||
|
## Impact Levels
|
||||||
|
|
||||||
|
- `CRITICAL` - Highest priority, major performance gains
|
||||||
|
- `HIGH` - Significant performance improvements
|
||||||
|
- `MEDIUM-HIGH` - Moderate-high gains
|
||||||
|
- `MEDIUM` - Moderate performance improvements
|
||||||
|
- `LOW-MEDIUM` - Low-medium gains
|
||||||
|
- `LOW` - Incremental improvements
|
||||||
|
|
||||||
|
## Scripts
|
||||||
|
|
||||||
|
- `pnpm build` - Compile rules into AGENTS.md
|
||||||
|
- `pnpm validate` - Validate all rule files
|
||||||
|
- `pnpm extract-tests` - Extract test cases for LLM evaluation
|
||||||
|
- `pnpm dev` - Build and validate
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
When adding or modifying rules:
|
||||||
|
|
||||||
|
1. Use the correct filename prefix for your section
|
||||||
|
2. Follow the `_template.md` structure
|
||||||
|
3. Include clear bad/good examples with explanations
|
||||||
|
4. Add appropriate tags
|
||||||
|
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
|
||||||
|
6. Rules are automatically sorted by title - no need to manage numbers!
|
||||||
|
|
||||||
|
## Acknowledgments
|
||||||
|
|
||||||
|
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
|
||||||
127
.agents/skills/react-best-practices/SKILL.md
Normal file
127
.agents/skills/react-best-practices/SKILL.md
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
---
|
||||||
|
name: react-best-practices
|
||||||
|
description: "React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance pat..."
|
||||||
|
risk: unknown
|
||||||
|
source: community
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Vercel React Best Practices
|
||||||
|
|
||||||
|
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||||
|
|
||||||
|
## When to Apply
|
||||||
|
|
||||||
|
Reference these guidelines when:
|
||||||
|
- Writing new React components or Next.js pages
|
||||||
|
- Implementing data fetching (client or server-side)
|
||||||
|
- Reviewing code for performance issues
|
||||||
|
- Refactoring existing React/Next.js code
|
||||||
|
- Optimizing bundle size or load times
|
||||||
|
|
||||||
|
## Rule Categories by Priority
|
||||||
|
|
||||||
|
| Priority | Category | Impact | Prefix |
|
||||||
|
|----------|----------|--------|--------|
|
||||||
|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||||
|
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||||
|
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||||
|
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||||
|
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||||
|
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||||
|
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||||
|
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
### 1. Eliminating Waterfalls (CRITICAL)
|
||||||
|
|
||||||
|
- `async-defer-await` - Move await into branches where actually used
|
||||||
|
- `async-parallel` - Use Promise.all() for independent operations
|
||||||
|
- `async-dependencies` - Use better-all for partial dependencies
|
||||||
|
- `async-api-routes` - Start promises early, await late in API routes
|
||||||
|
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||||
|
|
||||||
|
### 2. Bundle Size Optimization (CRITICAL)
|
||||||
|
|
||||||
|
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||||
|
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||||
|
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||||
|
- `bundle-conditional` - Load modules only when feature is activated
|
||||||
|
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||||
|
|
||||||
|
### 3. Server-Side Performance (HIGH)
|
||||||
|
|
||||||
|
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||||
|
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||||
|
- `server-serialization` - Minimize data passed to client components
|
||||||
|
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||||
|
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||||
|
|
||||||
|
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||||
|
|
||||||
|
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||||
|
- `client-event-listeners` - Deduplicate global event listeners
|
||||||
|
|
||||||
|
### 5. Re-render Optimization (MEDIUM)
|
||||||
|
|
||||||
|
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||||
|
- `rerender-memo` - Extract expensive work into memoized components
|
||||||
|
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||||
|
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||||
|
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||||
|
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||||
|
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||||
|
|
||||||
|
### 6. Rendering Performance (MEDIUM)
|
||||||
|
|
||||||
|
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||||
|
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||||
|
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||||
|
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||||
|
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||||
|
- `rendering-activity` - Use Activity component for show/hide
|
||||||
|
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||||
|
|
||||||
|
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||||
|
|
||||||
|
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||||
|
- `js-index-maps` - Build Map for repeated lookups
|
||||||
|
- `js-cache-property-access` - Cache object properties in loops
|
||||||
|
- `js-cache-function-results` - Cache function results in module-level Map
|
||||||
|
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||||
|
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||||
|
- `js-length-check-first` - Check array length before expensive comparison
|
||||||
|
- `js-early-exit` - Return early from functions
|
||||||
|
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||||
|
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||||
|
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||||
|
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||||
|
|
||||||
|
### 8. Advanced Patterns (LOW)
|
||||||
|
|
||||||
|
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||||
|
- `advanced-use-latest` - useLatest for stable callback refs
|
||||||
|
|
||||||
|
## How to Use
|
||||||
|
|
||||||
|
Read individual rule files for detailed explanations and code examples:
|
||||||
|
|
||||||
|
```
|
||||||
|
rules/async-parallel.md
|
||||||
|
rules/bundle-barrel-imports.md
|
||||||
|
rules/_sections.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Each rule file contains:
|
||||||
|
- Brief explanation of why it matters
|
||||||
|
- Incorrect code example with explanation
|
||||||
|
- Correct code example with explanation
|
||||||
|
- Additional context and references
|
||||||
|
|
||||||
|
## Full Compiled Document
|
||||||
|
|
||||||
|
For the complete guide with all rules expanded: `AGENTS.md`
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
This skill is applicable to execute the workflow or actions described in the overview.
|
||||||
15
.agents/skills/react-best-practices/metadata.json
Normal file
15
.agents/skills/react-best-practices/metadata.json
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"version": "0.1.0",
|
||||||
|
"organization": "Vercel Engineering",
|
||||||
|
"date": "January 2026",
|
||||||
|
"abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
|
||||||
|
"references": [
|
||||||
|
"https://react.dev",
|
||||||
|
"https://nextjs.org",
|
||||||
|
"https://swr.vercel.app",
|
||||||
|
"https://github.com/shuding/better-all",
|
||||||
|
"https://github.com/isaacs/node-lru-cache",
|
||||||
|
"https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
|
||||||
|
"https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
.agents/skills/react-best-practices/rules/_sections.md
Normal file
46
.agents/skills/react-best-practices/rules/_sections.md
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
# Sections
|
||||||
|
|
||||||
|
This file defines all sections, their ordering, impact levels, and descriptions.
|
||||||
|
The section ID (in parentheses) is the filename prefix used to group rules.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Eliminating Waterfalls (async)
|
||||||
|
|
||||||
|
**Impact:** CRITICAL
|
||||||
|
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
|
||||||
|
|
||||||
|
## 2. Bundle Size Optimization (bundle)
|
||||||
|
|
||||||
|
**Impact:** CRITICAL
|
||||||
|
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
|
||||||
|
|
||||||
|
## 3. Server-Side Performance (server)
|
||||||
|
|
||||||
|
**Impact:** HIGH
|
||||||
|
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
|
||||||
|
|
||||||
|
## 4. Client-Side Data Fetching (client)
|
||||||
|
|
||||||
|
**Impact:** MEDIUM-HIGH
|
||||||
|
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
|
||||||
|
|
||||||
|
## 5. Re-render Optimization (rerender)
|
||||||
|
|
||||||
|
**Impact:** MEDIUM
|
||||||
|
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
|
||||||
|
|
||||||
|
## 6. Rendering Performance (rendering)
|
||||||
|
|
||||||
|
**Impact:** MEDIUM
|
||||||
|
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
|
||||||
|
|
||||||
|
## 7. JavaScript Performance (js)
|
||||||
|
|
||||||
|
**Impact:** LOW-MEDIUM
|
||||||
|
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
|
||||||
|
|
||||||
|
## 8. Advanced Patterns (advanced)
|
||||||
|
|
||||||
|
**Impact:** LOW
|
||||||
|
**Description:** Advanced patterns for specific cases that require careful implementation.
|
||||||
28
.agents/skills/react-best-practices/rules/_template.md
Normal file
28
.agents/skills/react-best-practices/rules/_template.md
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Rule Title Here
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: Optional description of impact (e.g., "20-50% improvement")
|
||||||
|
tags: tag1, tag2
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rule Title Here
|
||||||
|
|
||||||
|
**Impact: MEDIUM (optional impact description)**
|
||||||
|
|
||||||
|
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
|
||||||
|
|
||||||
|
**Incorrect (description of what's wrong):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Bad code example here
|
||||||
|
const bad = example()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (description of what's right):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Good code example here
|
||||||
|
const good = example()
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [Link to documentation or resource](https://example.com)
|
||||||
@ -0,0 +1,55 @@
|
|||||||
|
---
|
||||||
|
title: Store Event Handlers in Refs
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: stable subscriptions
|
||||||
|
tags: advanced, hooks, refs, event-handlers, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Store Event Handlers in Refs
|
||||||
|
|
||||||
|
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||||
|
|
||||||
|
**Incorrect (re-subscribes on every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener(event, handler)
|
||||||
|
return () => window.removeEventListener(event, handler)
|
||||||
|
}, [event, handler])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (stable subscription):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
const handlerRef = useRef(handler)
|
||||||
|
useEffect(() => {
|
||||||
|
handlerRef.current = handler
|
||||||
|
}, [handler])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const listener = () => handlerRef.current()
|
||||||
|
window.addEventListener(event, listener)
|
||||||
|
return () => window.removeEventListener(event, listener)
|
||||||
|
}, [event])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useEffectEvent } from 'react'
|
||||||
|
|
||||||
|
function useWindowEvent(event: string, handler: () => void) {
|
||||||
|
const onEvent = useEffectEvent(handler)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener(event, onEvent)
|
||||||
|
return () => window.removeEventListener(event, onEvent)
|
||||||
|
}, [event])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||||
@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: useLatest for Stable Callback Refs
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: prevents effect re-runs
|
||||||
|
tags: advanced, hooks, useLatest, refs, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## useLatest for Stable Callback Refs
|
||||||
|
|
||||||
|
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function useLatest<T>(value: T) {
|
||||||
|
const ref = useRef(value)
|
||||||
|
useEffect(() => {
|
||||||
|
ref.current = value
|
||||||
|
}, [value])
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Incorrect (effect re-runs on every callback change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => onSearch(query), 300)
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
}, [query, onSearch])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (stable effect, fresh callback):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
const onSearchRef = useLatest(onSearch)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => onSearchRef.current(query), 300)
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
}, [query])
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: Prevent Waterfall Chains in API Routes
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: api-routes, server-actions, waterfalls, parallelization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prevent Waterfall Chains in API Routes
|
||||||
|
|
||||||
|
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||||
|
|
||||||
|
**Incorrect (config waits for auth, data waits for both):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await auth()
|
||||||
|
const config = await fetchConfig()
|
||||||
|
const data = await fetchData(session.user.id)
|
||||||
|
return Response.json({ data, config })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (auth and config start immediately):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const sessionPromise = auth()
|
||||||
|
const configPromise = fetchConfig()
|
||||||
|
const session = await sessionPromise
|
||||||
|
const [config, data] = await Promise.all([
|
||||||
|
configPromise,
|
||||||
|
fetchData(session.user.id)
|
||||||
|
])
|
||||||
|
return Response.json({ data, config })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||||
@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
title: Defer Await Until Needed
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: avoids blocking unused code paths
|
||||||
|
tags: async, await, conditional, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer Await Until Needed
|
||||||
|
|
||||||
|
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||||
|
|
||||||
|
**Incorrect (blocks both branches):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||||
|
const userData = await fetchUserData(userId)
|
||||||
|
|
||||||
|
if (skipProcessing) {
|
||||||
|
// Returns immediately but still waited for userData
|
||||||
|
return { skipped: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only this branch uses userData
|
||||||
|
return processUserData(userData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (only blocks when needed):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||||
|
if (skipProcessing) {
|
||||||
|
// Returns immediately without waiting
|
||||||
|
return { skipped: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch only when needed
|
||||||
|
const userData = await fetchUserData(userId)
|
||||||
|
return processUserData(userData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Another example (early return optimization):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Incorrect: always fetches permissions
|
||||||
|
async function updateResource(resourceId: string, userId: string) {
|
||||||
|
const permissions = await fetchPermissions(userId)
|
||||||
|
const resource = await getResource(resourceId)
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return { error: 'Not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!permissions.canEdit) {
|
||||||
|
return { error: 'Forbidden' }
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateResourceData(resource, permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct: fetches only when needed
|
||||||
|
async function updateResource(resourceId: string, userId: string) {
|
||||||
|
const resource = await getResource(resourceId)
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return { error: 'Not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions = await fetchPermissions(userId)
|
||||||
|
|
||||||
|
if (!permissions.canEdit) {
|
||||||
|
return { error: 'Forbidden' }
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateResourceData(resource, permissions)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
title: Dependency-Based Parallelization
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: async, parallelization, dependencies, better-all
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency-Based Parallelization
|
||||||
|
|
||||||
|
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||||
|
|
||||||
|
**Incorrect (profile waits for config unnecessarily):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [user, config] = await Promise.all([
|
||||||
|
fetchUser(),
|
||||||
|
fetchConfig()
|
||||||
|
])
|
||||||
|
const profile = await fetchProfile(user.id)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (config and profile run in parallel):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { all } from 'better-all'
|
||||||
|
|
||||||
|
const { user, config, profile } = await all({
|
||||||
|
async user() { return fetchUser() },
|
||||||
|
async config() { return fetchConfig() },
|
||||||
|
async profile() {
|
||||||
|
return fetchProfile((await this.$.user).id)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
||||||
28
.agents/skills/react-best-practices/rules/async-parallel.md
Normal file
28
.agents/skills/react-best-practices/rules/async-parallel.md
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Promise.all() for Independent Operations
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 2-10× improvement
|
||||||
|
tags: async, parallelization, promises, waterfalls
|
||||||
|
---
|
||||||
|
|
||||||
|
## Promise.all() for Independent Operations
|
||||||
|
|
||||||
|
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||||
|
|
||||||
|
**Incorrect (sequential execution, 3 round trips):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const user = await fetchUser()
|
||||||
|
const posts = await fetchPosts()
|
||||||
|
const comments = await fetchComments()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (parallel execution, 1 round trip):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [user, posts, comments] = await Promise.all([
|
||||||
|
fetchUser(),
|
||||||
|
fetchPosts(),
|
||||||
|
fetchComments()
|
||||||
|
])
|
||||||
|
```
|
||||||
@ -0,0 +1,99 @@
|
|||||||
|
---
|
||||||
|
title: Strategic Suspense Boundaries
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: faster initial paint
|
||||||
|
tags: async, suspense, streaming, layout-shift
|
||||||
|
---
|
||||||
|
|
||||||
|
## Strategic Suspense Boundaries
|
||||||
|
|
||||||
|
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||||
|
|
||||||
|
**Incorrect (wrapper blocked by data fetching):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const data = await fetchData() // Blocks entire page
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<div>
|
||||||
|
<DataDisplay data={data} />
|
||||||
|
</div>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The entire layout waits for data even though only the middle section needs it.
|
||||||
|
|
||||||
|
**Correct (wrapper shows immediately, data streams in):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Page() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<div>
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<DataDisplay />
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function DataDisplay() {
|
||||||
|
const data = await fetchData() // Only blocks this component
|
||||||
|
return <div>{data.content}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||||
|
|
||||||
|
**Alternative (share promise across components):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Page() {
|
||||||
|
// Start fetch immediately, but don't await
|
||||||
|
const dataPromise = fetchData()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>Sidebar</div>
|
||||||
|
<div>Header</div>
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<DataDisplay dataPromise={dataPromise} />
|
||||||
|
<DataSummary dataPromise={dataPromise} />
|
||||||
|
</Suspense>
|
||||||
|
<div>Footer</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||||
|
const data = use(dataPromise) // Unwraps the promise
|
||||||
|
return <div>{data.content}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||||
|
const data = use(dataPromise) // Reuses the same promise
|
||||||
|
return <div>{data.summary}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||||
|
|
||||||
|
**When NOT to use this pattern:**
|
||||||
|
|
||||||
|
- Critical data needed for layout decisions (affects positioning)
|
||||||
|
- SEO-critical content above the fold
|
||||||
|
- Small, fast queries where suspense overhead isn't worth it
|
||||||
|
- When you want to avoid layout shift (loading → content jump)
|
||||||
|
|
||||||
|
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||||
@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
title: Avoid Barrel File Imports
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: 200-800ms import cost, slow builds
|
||||||
|
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avoid Barrel File Imports
|
||||||
|
|
||||||
|
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||||
|
|
||||||
|
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||||
|
|
||||||
|
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||||
|
|
||||||
|
**Incorrect (imports entire library):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Check, X, Menu } from 'lucide-react'
|
||||||
|
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||||
|
// Runtime cost: 200-800ms on every cold start
|
||||||
|
|
||||||
|
import { Button, TextField } from '@mui/material'
|
||||||
|
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (imports only what you need):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import Check from 'lucide-react/dist/esm/icons/check'
|
||||||
|
import X from 'lucide-react/dist/esm/icons/x'
|
||||||
|
import Menu from 'lucide-react/dist/esm/icons/menu'
|
||||||
|
// Loads only 3 modules (~2KB vs ~1MB)
|
||||||
|
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import TextField from '@mui/material/TextField'
|
||||||
|
// Loads only what you use
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative (Next.js 13.5+):**
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js - use optimizePackageImports
|
||||||
|
module.exports = {
|
||||||
|
experimental: {
|
||||||
|
optimizePackageImports: ['lucide-react', '@mui/material']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then you can keep the ergonomic barrel imports:
|
||||||
|
import { Check, X, Menu } from 'lucide-react'
|
||||||
|
// Automatically transformed to direct imports at build time
|
||||||
|
```
|
||||||
|
|
||||||
|
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||||
|
|
||||||
|
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||||
|
|
||||||
|
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
title: Conditional Module Loading
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: loads large data only when needed
|
||||||
|
tags: bundle, conditional-loading, lazy-loading
|
||||||
|
---
|
||||||
|
|
||||||
|
## Conditional Module Loading
|
||||||
|
|
||||||
|
Load large data or modules only when a feature is activated.
|
||||||
|
|
||||||
|
**Example (lazy-load animation frames):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function AnimationPlayer({ enabled }: { enabled: boolean }) {
|
||||||
|
const [frames, setFrames] = useState<Frame[] | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (enabled && !frames && typeof window !== 'undefined') {
|
||||||
|
import('./animation-frames.js')
|
||||||
|
.then(mod => setFrames(mod.frames))
|
||||||
|
.catch(() => setEnabled(false))
|
||||||
|
}
|
||||||
|
}, [enabled, frames])
|
||||||
|
|
||||||
|
if (!frames) return <Skeleton />
|
||||||
|
return <Canvas frames={frames} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||||
@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: Defer Non-Critical Third-Party Libraries
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: loads after hydration
|
||||||
|
tags: bundle, third-party, analytics, defer
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer Non-Critical Third-Party Libraries
|
||||||
|
|
||||||
|
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||||
|
|
||||||
|
**Incorrect (blocks initial bundle):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Analytics } from '@vercel/analytics/react'
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<Analytics />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (loads after hydration):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const Analytics = dynamic(
|
||||||
|
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
||||||
|
{ ssr: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<Analytics />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
---
|
||||||
|
title: Dynamic Imports for Heavy Components
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: directly affects TTI and LCP
|
||||||
|
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dynamic Imports for Heavy Components
|
||||||
|
|
||||||
|
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||||
|
|
||||||
|
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { MonacoEditor } from './monaco-editor'
|
||||||
|
|
||||||
|
function CodePanel({ code }: { code: string }) {
|
||||||
|
return <MonacoEditor value={code} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (Monaco loads on demand):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
|
const MonacoEditor = dynamic(
|
||||||
|
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
||||||
|
{ ssr: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
function CodePanel({ code }: { code: string }) {
|
||||||
|
return <MonacoEditor value={code} />
|
||||||
|
}
|
||||||
|
```
|
||||||
50
.agents/skills/react-best-practices/rules/bundle-preload.md
Normal file
50
.agents/skills/react-best-practices/rules/bundle-preload.md
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: Preload Based on User Intent
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces perceived latency
|
||||||
|
tags: bundle, preload, user-intent, hover
|
||||||
|
---
|
||||||
|
|
||||||
|
## Preload Based on User Intent
|
||||||
|
|
||||||
|
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||||
|
|
||||||
|
**Example (preload on hover/focus):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||||
|
const preload = () => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
void import('./monaco-editor')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onMouseEnter={preload}
|
||||||
|
onFocus={preload}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
Open Editor
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example (preload when feature flag is enabled):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FlagsProvider({ children, flags }: Props) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||||
|
void import('./monaco-editor').then(mod => mod.init())
|
||||||
|
}
|
||||||
|
}, [flags.editorEnabled])
|
||||||
|
|
||||||
|
return <FlagsContext.Provider value={flags}>
|
||||||
|
{children}
|
||||||
|
</FlagsContext.Provider>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||||
@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
title: Deduplicate Global Event Listeners
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: single listener for N components
|
||||||
|
tags: client, swr, event-listeners, subscription
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deduplicate Global Event Listeners
|
||||||
|
|
||||||
|
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||||
|
|
||||||
|
**Incorrect (N instances = N listeners):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.metaKey && e.key === key) {
|
||||||
|
callback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', handler)
|
||||||
|
return () => window.removeEventListener('keydown', handler)
|
||||||
|
}, [key, callback])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||||
|
|
||||||
|
**Correct (N instances = 1 listener):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import useSWRSubscription from 'swr/subscription'
|
||||||
|
|
||||||
|
// Module-level Map to track callbacks per key
|
||||||
|
const keyCallbacks = new Map<string, Set<() => void>>()
|
||||||
|
|
||||||
|
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||||
|
// Register this callback in the Map
|
||||||
|
useEffect(() => {
|
||||||
|
if (!keyCallbacks.has(key)) {
|
||||||
|
keyCallbacks.set(key, new Set())
|
||||||
|
}
|
||||||
|
keyCallbacks.get(key)!.add(callback)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
const set = keyCallbacks.get(key)
|
||||||
|
if (set) {
|
||||||
|
set.delete(callback)
|
||||||
|
if (set.size === 0) {
|
||||||
|
keyCallbacks.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [key, callback])
|
||||||
|
|
||||||
|
useSWRSubscription('global-keydown', () => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||||
|
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', handler)
|
||||||
|
return () => window.removeEventListener('keydown', handler)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function Profile() {
|
||||||
|
// Multiple shortcuts will share the same listener
|
||||||
|
useKeyboardShortcut('p', () => { /* ... */ })
|
||||||
|
useKeyboardShortcut('k', () => { /* ... */ })
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
---
|
||||||
|
title: Use SWR for Automatic Deduplication
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: automatic deduplication
|
||||||
|
tags: client, swr, deduplication, data-fetching
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use SWR for Automatic Deduplication
|
||||||
|
|
||||||
|
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||||
|
|
||||||
|
**Incorrect (no deduplication, each instance fetches):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function UserList() {
|
||||||
|
const [users, setUsers] = useState([])
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/users')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(setUsers)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (multiple instances share one request):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import useSWR from 'swr'
|
||||||
|
|
||||||
|
function UserList() {
|
||||||
|
const { data: users } = useSWR('/api/users', fetcher)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**For immutable data:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useImmutableSWR } from '@/lib/swr'
|
||||||
|
|
||||||
|
function StaticContent() {
|
||||||
|
const { data } = useImmutableSWR('/api/config', fetcher)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**For mutations:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useSWRMutation } from 'swr/mutation'
|
||||||
|
|
||||||
|
function UpdateButton() {
|
||||||
|
const { trigger } = useSWRMutation('/api/user', updateUser)
|
||||||
|
return <button onClick={() => trigger()}>Update</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||||
@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Batch DOM CSS Changes
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces reflows/repaints
|
||||||
|
tags: javascript, dom, css, performance, reflow
|
||||||
|
---
|
||||||
|
|
||||||
|
## Batch DOM CSS Changes
|
||||||
|
|
||||||
|
Avoid changing styles one property at a time. Group multiple CSS changes together via classes or `cssText` to minimize browser reflows.
|
||||||
|
|
||||||
|
**Incorrect (multiple reflows):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
// Each line triggers a reflow
|
||||||
|
element.style.width = '100px'
|
||||||
|
element.style.height = '200px'
|
||||||
|
element.style.backgroundColor = 'blue'
|
||||||
|
element.style.border = '1px solid black'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (add class - single reflow):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// CSS file
|
||||||
|
.highlighted-box {
|
||||||
|
width: 100px;
|
||||||
|
height: 200px;
|
||||||
|
background-color: blue;
|
||||||
|
border: 1px solid black;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JavaScript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
element.classList.add('highlighted-box')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (change cssText - single reflow):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function updateElementStyles(element: HTMLElement) {
|
||||||
|
element.style.cssText = `
|
||||||
|
width: 100px;
|
||||||
|
height: 200px;
|
||||||
|
background-color: blue;
|
||||||
|
border: 1px solid black;
|
||||||
|
`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**React example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Incorrect: changing styles one by one
|
||||||
|
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (ref.current && isHighlighted) {
|
||||||
|
ref.current.style.width = '100px'
|
||||||
|
ref.current.style.height = '200px'
|
||||||
|
ref.current.style.backgroundColor = 'blue'
|
||||||
|
}
|
||||||
|
}, [isHighlighted])
|
||||||
|
|
||||||
|
return <div ref={ref}>Content</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct: toggle class
|
||||||
|
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
||||||
|
Content
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Prefer CSS classes over inline styles when possible. Classes are cached by the browser and provide better separation of concerns.
|
||||||
@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
title: Cache Repeated Function Calls
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoid redundant computation
|
||||||
|
tags: javascript, cache, memoization, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Repeated Function Calls
|
||||||
|
|
||||||
|
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||||
|
|
||||||
|
**Incorrect (redundant computation):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function ProjectList({ projects }: { projects: Project[] }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{projects.map(project => {
|
||||||
|
// slugify() called 100+ times for same project names
|
||||||
|
const slug = slugify(project.name)
|
||||||
|
|
||||||
|
return <ProjectCard key={project.id} slug={slug} />
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (cached results):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Module-level cache
|
||||||
|
const slugifyCache = new Map<string, string>()
|
||||||
|
|
||||||
|
function cachedSlugify(text: string): string {
|
||||||
|
if (slugifyCache.has(text)) {
|
||||||
|
return slugifyCache.get(text)!
|
||||||
|
}
|
||||||
|
const result = slugify(text)
|
||||||
|
slugifyCache.set(text, result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectList({ projects }: { projects: Project[] }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{projects.map(project => {
|
||||||
|
// Computed only once per unique project name
|
||||||
|
const slug = cachedSlugify(project.name)
|
||||||
|
|
||||||
|
return <ProjectCard key={project.id} slug={slug} />
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Simpler pattern for single-value functions:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
let isLoggedInCache: boolean | null = null
|
||||||
|
|
||||||
|
function isLoggedIn(): boolean {
|
||||||
|
if (isLoggedInCache !== null) {
|
||||||
|
return isLoggedInCache
|
||||||
|
}
|
||||||
|
|
||||||
|
isLoggedInCache = document.cookie.includes('auth=')
|
||||||
|
return isLoggedInCache
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear cache when auth changes
|
||||||
|
function onAuthChange() {
|
||||||
|
isLoggedInCache = null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||||
|
|
||||||
|
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||||
@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Cache Property Access in Loops
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces lookups
|
||||||
|
tags: javascript, loops, optimization, caching
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Property Access in Loops
|
||||||
|
|
||||||
|
Cache object property lookups in hot paths.
|
||||||
|
|
||||||
|
**Incorrect (3 lookups × N iterations):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
process(obj.config.settings.value)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 lookup total):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const value = obj.config.settings.value
|
||||||
|
const len = arr.length
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
process(value)
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,70 @@
|
|||||||
|
---
|
||||||
|
title: Cache Storage API Calls
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces expensive I/O
|
||||||
|
tags: javascript, localStorage, storage, caching, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cache Storage API Calls
|
||||||
|
|
||||||
|
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||||
|
|
||||||
|
**Incorrect (reads storage on every call):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getTheme() {
|
||||||
|
return localStorage.getItem('theme') ?? 'light'
|
||||||
|
}
|
||||||
|
// Called 10 times = 10 storage reads
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (Map cache):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const storageCache = new Map<string, string | null>()
|
||||||
|
|
||||||
|
function getLocalStorage(key: string) {
|
||||||
|
if (!storageCache.has(key)) {
|
||||||
|
storageCache.set(key, localStorage.getItem(key))
|
||||||
|
}
|
||||||
|
return storageCache.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLocalStorage(key: string, value: string) {
|
||||||
|
localStorage.setItem(key, value)
|
||||||
|
storageCache.set(key, value) // keep cache in sync
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||||
|
|
||||||
|
**Cookie caching:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
let cookieCache: Record<string, string> | null = null
|
||||||
|
|
||||||
|
function getCookie(name: string) {
|
||||||
|
if (!cookieCache) {
|
||||||
|
cookieCache = Object.fromEntries(
|
||||||
|
document.cookie.split('; ').map(c => c.split('='))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return cookieCache[name]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important (invalidate on external changes):**
|
||||||
|
|
||||||
|
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
window.addEventListener('storage', (e) => {
|
||||||
|
if (e.key) storageCache.delete(e.key)
|
||||||
|
})
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (document.visibilityState === 'visible') {
|
||||||
|
storageCache.clear()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
title: Combine Multiple Array Iterations
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: reduces iterations
|
||||||
|
tags: javascript, arrays, loops, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Combine Multiple Array Iterations
|
||||||
|
|
||||||
|
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||||
|
|
||||||
|
**Incorrect (3 iterations):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const admins = users.filter(u => u.isAdmin)
|
||||||
|
const testers = users.filter(u => u.isTester)
|
||||||
|
const inactive = users.filter(u => !u.isActive)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 iteration):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const admins: User[] = []
|
||||||
|
const testers: User[] = []
|
||||||
|
const inactive: User[] = []
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (user.isAdmin) admins.push(user)
|
||||||
|
if (user.isTester) testers.push(user)
|
||||||
|
if (!user.isActive) inactive.push(user)
|
||||||
|
}
|
||||||
|
```
|
||||||
50
.agents/skills/react-best-practices/rules/js-early-exit.md
Normal file
50
.agents/skills/react-best-practices/rules/js-early-exit.md
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: Early Return from Functions
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: avoids unnecessary computation
|
||||||
|
tags: javascript, functions, optimization, early-return
|
||||||
|
---
|
||||||
|
|
||||||
|
## Early Return from Functions
|
||||||
|
|
||||||
|
Return early when result is determined to skip unnecessary processing.
|
||||||
|
|
||||||
|
**Incorrect (processes all items even after finding answer):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function validateUsers(users: User[]) {
|
||||||
|
let hasError = false
|
||||||
|
let errorMessage = ''
|
||||||
|
|
||||||
|
for (const user of users) {
|
||||||
|
if (!user.email) {
|
||||||
|
hasError = true
|
||||||
|
errorMessage = 'Email required'
|
||||||
|
}
|
||||||
|
if (!user.name) {
|
||||||
|
hasError = true
|
||||||
|
errorMessage = 'Name required'
|
||||||
|
}
|
||||||
|
// Continues checking all users even after error found
|
||||||
|
}
|
||||||
|
|
||||||
|
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (returns immediately on first error):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function validateUsers(users: User[]) {
|
||||||
|
for (const user of users) {
|
||||||
|
if (!user.email) {
|
||||||
|
return { valid: false, error: 'Email required' }
|
||||||
|
}
|
||||||
|
if (!user.name) {
|
||||||
|
return { valid: false, error: 'Name required' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true }
|
||||||
|
}
|
||||||
|
```
|
||||||
45
.agents/skills/react-best-practices/rules/js-hoist-regexp.md
Normal file
45
.agents/skills/react-best-practices/rules/js-hoist-regexp.md
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
title: Hoist RegExp Creation
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: avoids recreation
|
||||||
|
tags: javascript, regexp, optimization, memoization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hoist RegExp Creation
|
||||||
|
|
||||||
|
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||||
|
|
||||||
|
**Incorrect (new RegExp every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Highlighter({ text, query }: Props) {
|
||||||
|
const regex = new RegExp(`(${query})`, 'gi')
|
||||||
|
const parts = text.split(regex)
|
||||||
|
return <>{parts.map((part, i) => ...)}</>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (memoize or hoist):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
|
||||||
|
function Highlighter({ text, query }: Props) {
|
||||||
|
const regex = useMemo(
|
||||||
|
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||||
|
[query]
|
||||||
|
)
|
||||||
|
const parts = text.split(regex)
|
||||||
|
return <>{parts.map((part, i) => ...)}</>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warning (global regex has mutable state):**
|
||||||
|
|
||||||
|
Global regex (`/g`) has mutable `lastIndex` state:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const regex = /foo/g
|
||||||
|
regex.test('foo') // true, lastIndex = 3
|
||||||
|
regex.test('foo') // false, lastIndex = 0
|
||||||
|
```
|
||||||
37
.agents/skills/react-best-practices/rules/js-index-maps.md
Normal file
37
.agents/skills/react-best-practices/rules/js-index-maps.md
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
title: Build Index Maps for Repeated Lookups
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: 1M ops to 2K ops
|
||||||
|
tags: javascript, map, indexing, optimization, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Build Index Maps for Repeated Lookups
|
||||||
|
|
||||||
|
Multiple `.find()` calls by the same key should use a Map.
|
||||||
|
|
||||||
|
**Incorrect (O(n) per lookup):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function processOrders(orders: Order[], users: User[]) {
|
||||||
|
return orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
user: users.find(u => u.id === order.userId)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (O(1) per lookup):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function processOrders(orders: Order[], users: User[]) {
|
||||||
|
const userById = new Map(users.map(u => [u.id, u]))
|
||||||
|
|
||||||
|
return orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
user: userById.get(order.userId)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Build map once (O(n)), then all lookups are O(1).
|
||||||
|
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||||
@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
title: Early Length Check for Array Comparisons
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: avoids expensive operations when lengths differ
|
||||||
|
tags: javascript, arrays, performance, optimization, comparison
|
||||||
|
---
|
||||||
|
|
||||||
|
## Early Length Check for Array Comparisons
|
||||||
|
|
||||||
|
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
||||||
|
|
||||||
|
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
||||||
|
|
||||||
|
**Incorrect (always runs expensive comparison):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function hasChanges(current: string[], original: string[]) {
|
||||||
|
// Always sorts and joins, even when lengths differ
|
||||||
|
return current.sort().join() !== original.sort().join()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
|
||||||
|
|
||||||
|
**Correct (O(1) length check first):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function hasChanges(current: string[], original: string[]) {
|
||||||
|
// Early return if lengths differ
|
||||||
|
if (current.length !== original.length) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Only sort/join when lengths match
|
||||||
|
const currentSorted = current.toSorted()
|
||||||
|
const originalSorted = original.toSorted()
|
||||||
|
for (let i = 0; i < currentSorted.length; i++) {
|
||||||
|
if (currentSorted[i] !== originalSorted[i]) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This new approach is more efficient because:
|
||||||
|
- It avoids the overhead of sorting and joining the arrays when lengths differ
|
||||||
|
- It avoids consuming memory for the joined strings (especially important for large arrays)
|
||||||
|
- It avoids mutating the original arrays
|
||||||
|
- It returns early when a difference is found
|
||||||
82
.agents/skills/react-best-practices/rules/js-min-max-loop.md
Normal file
82
.agents/skills/react-best-practices/rules/js-min-max-loop.md
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Use Loop for Min/Max Instead of Sort
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: O(n) instead of O(n log n)
|
||||||
|
tags: javascript, arrays, performance, sorting, algorithms
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Loop for Min/Max Instead of Sort
|
||||||
|
|
||||||
|
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||||
|
|
||||||
|
**Incorrect (O(n log n) - sort to find latest):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface Project {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
updatedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLatestProject(projects: Project[]) {
|
||||||
|
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
|
||||||
|
return sorted[0]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Sorts the entire array just to find the maximum value.
|
||||||
|
|
||||||
|
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getOldestAndNewest(projects: Project[]) {
|
||||||
|
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
|
||||||
|
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Still sorts unnecessarily when only min/max are needed.
|
||||||
|
|
||||||
|
**Correct (O(n) - single loop):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function getLatestProject(projects: Project[]) {
|
||||||
|
if (projects.length === 0) return null
|
||||||
|
|
||||||
|
let latest = projects[0]
|
||||||
|
|
||||||
|
for (let i = 1; i < projects.length; i++) {
|
||||||
|
if (projects[i].updatedAt > latest.updatedAt) {
|
||||||
|
latest = projects[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return latest
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOldestAndNewest(projects: Project[]) {
|
||||||
|
if (projects.length === 0) return { oldest: null, newest: null }
|
||||||
|
|
||||||
|
let oldest = projects[0]
|
||||||
|
let newest = projects[0]
|
||||||
|
|
||||||
|
for (let i = 1; i < projects.length; i++) {
|
||||||
|
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
|
||||||
|
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
return { oldest, newest }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Single pass through the array, no copying, no sorting.
|
||||||
|
|
||||||
|
**Alternative (Math.min/Math.max for small arrays):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const numbers = [5, 2, 8, 1, 9]
|
||||||
|
const min = Math.min(...numbers)
|
||||||
|
const max = Math.max(...numbers)
|
||||||
|
```
|
||||||
|
|
||||||
|
This works for small arrays but can be slower for very large arrays due to spread operator limitations. Use the loop approach for reliability.
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
---
|
||||||
|
title: Use Set/Map for O(1) Lookups
|
||||||
|
impact: LOW-MEDIUM
|
||||||
|
impactDescription: O(n) to O(1)
|
||||||
|
tags: javascript, set, map, data-structures, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Set/Map for O(1) Lookups
|
||||||
|
|
||||||
|
Convert arrays to Set/Map for repeated membership checks.
|
||||||
|
|
||||||
|
**Incorrect (O(n) per check):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const allowedIds = ['a', 'b', 'c', ...]
|
||||||
|
items.filter(item => allowedIds.includes(item.id))
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (O(1) per check):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||||
|
items.filter(item => allowedIds.has(item.id))
|
||||||
|
```
|
||||||
@ -0,0 +1,57 @@
|
|||||||
|
---
|
||||||
|
title: Use toSorted() Instead of sort() for Immutability
|
||||||
|
impact: MEDIUM-HIGH
|
||||||
|
impactDescription: prevents mutation bugs in React state
|
||||||
|
tags: javascript, arrays, immutability, react, state, mutation
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use toSorted() Instead of sort() for Immutability
|
||||||
|
|
||||||
|
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||||
|
|
||||||
|
**Incorrect (mutates original array):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function UserList({ users }: { users: User[] }) {
|
||||||
|
// Mutates the users prop array!
|
||||||
|
const sorted = useMemo(
|
||||||
|
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
|
[users]
|
||||||
|
)
|
||||||
|
return <div>{sorted.map(renderUser)}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (creates new array):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function UserList({ users }: { users: User[] }) {
|
||||||
|
// Creates new sorted array, original unchanged
|
||||||
|
const sorted = useMemo(
|
||||||
|
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||||
|
[users]
|
||||||
|
)
|
||||||
|
return <div>{sorted.map(renderUser)}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why this matters in React:**
|
||||||
|
|
||||||
|
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||||
|
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||||
|
|
||||||
|
**Browser support (fallback for older browsers):**
|
||||||
|
|
||||||
|
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Fallback for older browsers
|
||||||
|
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Other immutable array methods:**
|
||||||
|
|
||||||
|
- `.toSorted()` - immutable sort
|
||||||
|
- `.toReversed()` - immutable reverse
|
||||||
|
- `.toSpliced()` - immutable splice
|
||||||
|
- `.with()` - immutable element replacement
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
title: Use Activity Component for Show/Hide
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: preserves state/DOM
|
||||||
|
tags: rendering, activity, visibility, state-preservation
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Activity Component for Show/Hide
|
||||||
|
|
||||||
|
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Activity } from 'react'
|
||||||
|
|
||||||
|
function Dropdown({ isOpen }: Props) {
|
||||||
|
return (
|
||||||
|
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||||
|
<ExpensiveMenu />
|
||||||
|
</Activity>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Avoids expensive re-renders and state loss.
|
||||||
@ -0,0 +1,47 @@
|
|||||||
|
---
|
||||||
|
title: Animate SVG Wrapper Instead of SVG Element
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: enables hardware acceleration
|
||||||
|
tags: rendering, svg, css, animation, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Animate SVG Wrapper Instead of SVG Element
|
||||||
|
|
||||||
|
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||||
|
|
||||||
|
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function LoadingSpinner() {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
className="animate-spin"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (animating wrapper div - hardware accelerated):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function LoadingSpinner() {
|
||||||
|
return (
|
||||||
|
<div className="animate-spin">
|
||||||
|
<svg
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||||
@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
title: Use Explicit Conditional Rendering
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: prevents rendering 0 or NaN
|
||||||
|
tags: rendering, conditional, jsx, falsy-values
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Explicit Conditional Rendering
|
||||||
|
|
||||||
|
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||||
|
|
||||||
|
**Incorrect (renders "0" when count is 0):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Badge({ count }: { count: number }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{count && <span className="badge">{count}</span>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// When count = 0, renders: <div>0</div>
|
||||||
|
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (renders nothing when count is 0):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Badge({ count }: { count: number }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{count > 0 ? <span className="badge">{count}</span> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// When count = 0, renders: <div></div>
|
||||||
|
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||||
|
```
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: CSS content-visibility for Long Lists
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: faster initial render
|
||||||
|
tags: rendering, css, content-visibility, long-lists
|
||||||
|
---
|
||||||
|
|
||||||
|
## CSS content-visibility for Long Lists
|
||||||
|
|
||||||
|
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||||
|
|
||||||
|
**CSS:**
|
||||||
|
|
||||||
|
```css
|
||||||
|
.message-item {
|
||||||
|
content-visibility: auto;
|
||||||
|
contain-intrinsic-size: 0 80px;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function MessageList({ messages }: { messages: Message[] }) {
|
||||||
|
return (
|
||||||
|
<div className="overflow-y-auto h-screen">
|
||||||
|
{messages.map(msg => (
|
||||||
|
<div key={msg.id} className="message-item">
|
||||||
|
<Avatar user={msg.author} />
|
||||||
|
<div>{msg.content}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
||||||
@ -0,0 +1,46 @@
|
|||||||
|
---
|
||||||
|
title: Hoist Static JSX Elements
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: avoids re-creation
|
||||||
|
tags: rendering, jsx, static, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hoist Static JSX Elements
|
||||||
|
|
||||||
|
Extract static JSX outside components to avoid re-creation.
|
||||||
|
|
||||||
|
**Incorrect (recreates element every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function LoadingSkeleton() {
|
||||||
|
return <div className="animate-pulse h-20 bg-gray-200" />
|
||||||
|
}
|
||||||
|
|
||||||
|
function Container() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{loading && <LoadingSkeleton />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (reuses same element):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const loadingSkeleton = (
|
||||||
|
<div className="animate-pulse h-20 bg-gray-200" />
|
||||||
|
)
|
||||||
|
|
||||||
|
function Container() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{loading && loadingSkeleton}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
||||||
|
|
||||||
|
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
|
||||||
@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Prevent Hydration Mismatch Without Flickering
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoids visual flicker and hydration errors
|
||||||
|
tags: rendering, ssr, hydration, localStorage, flicker
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prevent Hydration Mismatch Without Flickering
|
||||||
|
|
||||||
|
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
|
||||||
|
|
||||||
|
**Incorrect (breaks SSR):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||||
|
// localStorage is not available on server - throws error
|
||||||
|
const theme = localStorage.getItem('theme') || 'light'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={theme}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Server-side rendering will fail because `localStorage` is undefined.
|
||||||
|
|
||||||
|
**Incorrect (visual flickering):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||||
|
const [theme, setTheme] = useState('light')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Runs after hydration - causes visible flash
|
||||||
|
const stored = localStorage.getItem('theme')
|
||||||
|
if (stored) {
|
||||||
|
setTheme(stored)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={theme}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
||||||
|
|
||||||
|
**Correct (no flicker, no hydration mismatch):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div id="theme-wrapper">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
<script
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: `
|
||||||
|
(function() {
|
||||||
|
try {
|
||||||
|
var theme = localStorage.getItem('theme') || 'light';
|
||||||
|
var el = document.getElementById('theme-wrapper');
|
||||||
|
if (el) el.className = theme;
|
||||||
|
} catch (e) {}
|
||||||
|
})();
|
||||||
|
`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
||||||
|
|
||||||
|
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
|
||||||
@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: Optimize SVG Precision
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: reduces file size
|
||||||
|
tags: rendering, svg, optimization, svgo
|
||||||
|
---
|
||||||
|
|
||||||
|
## Optimize SVG Precision
|
||||||
|
|
||||||
|
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
||||||
|
|
||||||
|
**Incorrect (excessive precision):**
|
||||||
|
|
||||||
|
```svg
|
||||||
|
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (1 decimal place):**
|
||||||
|
|
||||||
|
```svg
|
||||||
|
<path d="M 10.3 20.8 L 30.9 40.2" />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Automate with SVGO:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx svgo --precision=1 --multipass icon.svg
|
||||||
|
```
|
||||||
@ -0,0 +1,39 @@
|
|||||||
|
---
|
||||||
|
title: Defer State Reads to Usage Point
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: avoids unnecessary subscriptions
|
||||||
|
tags: rerender, searchParams, localStorage, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defer State Reads to Usage Point
|
||||||
|
|
||||||
|
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
||||||
|
|
||||||
|
**Incorrect (subscribes to all searchParams changes):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ShareButton({ chatId }: { chatId: string }) {
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
|
||||||
|
const handleShare = () => {
|
||||||
|
const ref = searchParams.get('ref')
|
||||||
|
shareChat(chatId, { ref })
|
||||||
|
}
|
||||||
|
|
||||||
|
return <button onClick={handleShare}>Share</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (reads on demand, no subscription):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ShareButton({ chatId }: { chatId: string }) {
|
||||||
|
const handleShare = () => {
|
||||||
|
const params = new URLSearchParams(window.location.search)
|
||||||
|
const ref = params.get('ref')
|
||||||
|
shareChat(chatId, { ref })
|
||||||
|
}
|
||||||
|
|
||||||
|
return <button onClick={handleShare}>Share</button>
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
title: Narrow Effect Dependencies
|
||||||
|
impact: LOW
|
||||||
|
impactDescription: minimizes effect re-runs
|
||||||
|
tags: rerender, useEffect, dependencies, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Narrow Effect Dependencies
|
||||||
|
|
||||||
|
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
||||||
|
|
||||||
|
**Incorrect (re-runs on any user field change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
useEffect(() => {
|
||||||
|
console.log(user.id)
|
||||||
|
}, [user])
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (re-runs only when id changes):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
useEffect(() => {
|
||||||
|
console.log(user.id)
|
||||||
|
}, [user.id])
|
||||||
|
```
|
||||||
|
|
||||||
|
**For derived state, compute outside effect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Incorrect: runs on width=767, 766, 765...
|
||||||
|
useEffect(() => {
|
||||||
|
if (width < 768) {
|
||||||
|
enableMobileMode()
|
||||||
|
}
|
||||||
|
}, [width])
|
||||||
|
|
||||||
|
// Correct: runs only on boolean transition
|
||||||
|
const isMobile = width < 768
|
||||||
|
useEffect(() => {
|
||||||
|
if (isMobile) {
|
||||||
|
enableMobileMode()
|
||||||
|
}
|
||||||
|
}, [isMobile])
|
||||||
|
```
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
title: Subscribe to Derived State
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: reduces re-render frequency
|
||||||
|
tags: rerender, derived-state, media-query, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Subscribe to Derived State
|
||||||
|
|
||||||
|
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
||||||
|
|
||||||
|
**Incorrect (re-renders on every pixel change):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Sidebar() {
|
||||||
|
const width = useWindowWidth() // updates continuously
|
||||||
|
const isMobile = width < 768
|
||||||
|
return <nav className={isMobile ? 'mobile' : 'desktop'}>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (re-renders only when boolean changes):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Sidebar() {
|
||||||
|
const isMobile = useMediaQuery('(max-width: 767px)')
|
||||||
|
return <nav className={isMobile ? 'mobile' : 'desktop'}>
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
title: Use Functional setState Updates
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: prevents stale closures and unnecessary callback recreations
|
||||||
|
tags: react, hooks, useState, useCallback, callbacks, closures
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Functional setState Updates
|
||||||
|
|
||||||
|
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
|
||||||
|
|
||||||
|
**Incorrect (requires state as dependency):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function TodoList() {
|
||||||
|
const [items, setItems] = useState(initialItems)
|
||||||
|
|
||||||
|
// Callback must depend on items, recreated on every items change
|
||||||
|
const addItems = useCallback((newItems: Item[]) => {
|
||||||
|
setItems([...items, ...newItems])
|
||||||
|
}, [items]) // ❌ items dependency causes recreations
|
||||||
|
|
||||||
|
// Risk of stale closure if dependency is forgotten
|
||||||
|
const removeItem = useCallback((id: string) => {
|
||||||
|
setItems(items.filter(item => item.id !== id))
|
||||||
|
}, []) // ❌ Missing items dependency - will use stale items!
|
||||||
|
|
||||||
|
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
|
||||||
|
|
||||||
|
**Correct (stable callbacks, no stale closures):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function TodoList() {
|
||||||
|
const [items, setItems] = useState(initialItems)
|
||||||
|
|
||||||
|
// Stable callback, never recreated
|
||||||
|
const addItems = useCallback((newItems: Item[]) => {
|
||||||
|
setItems(curr => [...curr, ...newItems])
|
||||||
|
}, []) // ✅ No dependencies needed
|
||||||
|
|
||||||
|
// Always uses latest state, no stale closure risk
|
||||||
|
const removeItem = useCallback((id: string) => {
|
||||||
|
setItems(curr => curr.filter(item => item.id !== id))
|
||||||
|
}, []) // ✅ Safe and stable
|
||||||
|
|
||||||
|
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Benefits:**
|
||||||
|
|
||||||
|
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
||||||
|
2. **No stale closures** - Always operates on the latest state value
|
||||||
|
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
||||||
|
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
||||||
|
|
||||||
|
**When to use functional updates:**
|
||||||
|
|
||||||
|
- Any setState that depends on the current state value
|
||||||
|
- Inside useCallback/useMemo when state is needed
|
||||||
|
- Event handlers that reference state
|
||||||
|
- Async operations that update state
|
||||||
|
|
||||||
|
**When direct updates are fine:**
|
||||||
|
|
||||||
|
- Setting state to a static value: `setCount(0)`
|
||||||
|
- Setting state from props/arguments only: `setName(newName)`
|
||||||
|
- State doesn't depend on previous value
|
||||||
|
|
||||||
|
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
|
||||||
@ -0,0 +1,58 @@
|
|||||||
|
---
|
||||||
|
title: Use Lazy State Initialization
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: wasted computation on every render
|
||||||
|
tags: react, hooks, useState, performance, initialization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Lazy State Initialization
|
||||||
|
|
||||||
|
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
||||||
|
|
||||||
|
**Incorrect (runs on every render):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FilteredList({ items }: { items: Item[] }) {
|
||||||
|
// buildSearchIndex() runs on EVERY render, even after initialization
|
||||||
|
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
// When query changes, buildSearchIndex runs again unnecessarily
|
||||||
|
return <SearchResults index={searchIndex} query={query} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function UserProfile() {
|
||||||
|
// JSON.parse runs on every render
|
||||||
|
const [settings, setSettings] = useState(
|
||||||
|
JSON.parse(localStorage.getItem('settings') || '{}')
|
||||||
|
)
|
||||||
|
|
||||||
|
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (runs only once):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function FilteredList({ items }: { items: Item[] }) {
|
||||||
|
// buildSearchIndex() runs ONLY on initial render
|
||||||
|
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
return <SearchResults index={searchIndex} query={query} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function UserProfile() {
|
||||||
|
// JSON.parse runs only on initial render
|
||||||
|
const [settings, setSettings] = useState(() => {
|
||||||
|
const stored = localStorage.getItem('settings')
|
||||||
|
return stored ? JSON.parse(stored) : {}
|
||||||
|
})
|
||||||
|
|
||||||
|
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
||||||
|
|
||||||
|
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
||||||
44
.agents/skills/react-best-practices/rules/rerender-memo.md
Normal file
44
.agents/skills/react-best-practices/rules/rerender-memo.md
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
title: Extract to Memoized Components
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: enables early returns
|
||||||
|
tags: rerender, memo, useMemo, optimization
|
||||||
|
---
|
||||||
|
|
||||||
|
## Extract to Memoized Components
|
||||||
|
|
||||||
|
Extract expensive work into memoized components to enable early returns before computation.
|
||||||
|
|
||||||
|
**Incorrect (computes avatar even when loading):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function Profile({ user, loading }: Props) {
|
||||||
|
const avatar = useMemo(() => {
|
||||||
|
const id = computeAvatarId(user)
|
||||||
|
return <Avatar id={id} />
|
||||||
|
}, [user])
|
||||||
|
|
||||||
|
if (loading) return <Skeleton />
|
||||||
|
return <div>{avatar}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (skips computation when loading):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
||||||
|
const id = useMemo(() => computeAvatarId(user), [user])
|
||||||
|
return <Avatar id={id} />
|
||||||
|
})
|
||||||
|
|
||||||
|
function Profile({ user, loading }: Props) {
|
||||||
|
if (loading) return <Skeleton />
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<UserAvatar user={user} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
||||||
@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
title: Use Transitions for Non-Urgent Updates
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: maintains UI responsiveness
|
||||||
|
tags: rerender, transitions, startTransition, performance
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use Transitions for Non-Urgent Updates
|
||||||
|
|
||||||
|
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
||||||
|
|
||||||
|
**Incorrect (blocks UI on every scroll):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ScrollTracker() {
|
||||||
|
const [scrollY, setScrollY] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => setScrollY(window.scrollY)
|
||||||
|
window.addEventListener('scroll', handler, { passive: true })
|
||||||
|
return () => window.removeEventListener('scroll', handler)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (non-blocking updates):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { startTransition } from 'react'
|
||||||
|
|
||||||
|
function ScrollTracker() {
|
||||||
|
const [scrollY, setScrollY] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => {
|
||||||
|
startTransition(() => setScrollY(window.scrollY))
|
||||||
|
}
|
||||||
|
window.addEventListener('scroll', handler, { passive: true })
|
||||||
|
return () => window.removeEventListener('scroll', handler)
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,73 @@
|
|||||||
|
---
|
||||||
|
title: Use after() for Non-Blocking Operations
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: faster response times
|
||||||
|
tags: server, async, logging, analytics, side-effects
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use after() for Non-Blocking Operations
|
||||||
|
|
||||||
|
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
||||||
|
|
||||||
|
**Incorrect (blocks response):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { logUserAction } from '@/app/utils'
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
// Perform mutation
|
||||||
|
await updateDatabase(request)
|
||||||
|
|
||||||
|
// Logging blocks the response
|
||||||
|
const userAgent = request.headers.get('user-agent') || 'unknown'
|
||||||
|
await logUserAction({ userAgent })
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ status: 'success' }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (non-blocking):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { after } from 'next/server'
|
||||||
|
import { headers, cookies } from 'next/headers'
|
||||||
|
import { logUserAction } from '@/app/utils'
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
// Perform mutation
|
||||||
|
await updateDatabase(request)
|
||||||
|
|
||||||
|
// Log after response is sent
|
||||||
|
after(async () => {
|
||||||
|
const userAgent = (await headers()).get('user-agent') || 'unknown'
|
||||||
|
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
|
||||||
|
|
||||||
|
logUserAction({ sessionCookie, userAgent })
|
||||||
|
})
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ status: 'success' }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The response is sent immediately while logging happens in the background.
|
||||||
|
|
||||||
|
**Common use cases:**
|
||||||
|
|
||||||
|
- Analytics tracking
|
||||||
|
- Audit logging
|
||||||
|
- Sending notifications
|
||||||
|
- Cache invalidation
|
||||||
|
- Cleanup tasks
|
||||||
|
|
||||||
|
**Important notes:**
|
||||||
|
|
||||||
|
- `after()` runs even if the response fails or redirects
|
||||||
|
- Works in Server Actions, Route Handlers, and Server Components
|
||||||
|
|
||||||
|
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
|
||||||
@ -0,0 +1,41 @@
|
|||||||
|
---
|
||||||
|
title: Cross-Request LRU Caching
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: caches across requests
|
||||||
|
tags: server, cache, lru, cross-request
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cross-Request LRU Caching
|
||||||
|
|
||||||
|
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { LRUCache } from 'lru-cache'
|
||||||
|
|
||||||
|
const cache = new LRUCache<string, any>({
|
||||||
|
max: 1000,
|
||||||
|
ttl: 5 * 60 * 1000 // 5 minutes
|
||||||
|
})
|
||||||
|
|
||||||
|
export async function getUser(id: string) {
|
||||||
|
const cached = cache.get(id)
|
||||||
|
if (cached) return cached
|
||||||
|
|
||||||
|
const user = await db.user.findUnique({ where: { id } })
|
||||||
|
cache.set(id, user)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request 1: DB query, result cached
|
||||||
|
// Request 2: cache hit, no DB query
|
||||||
|
```
|
||||||
|
|
||||||
|
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
||||||
|
|
||||||
|
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
||||||
|
|
||||||
|
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
||||||
|
|
||||||
|
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
title: Per-Request Deduplication with React.cache()
|
||||||
|
impact: MEDIUM
|
||||||
|
impactDescription: deduplicates within request
|
||||||
|
tags: server, cache, react-cache, deduplication
|
||||||
|
---
|
||||||
|
|
||||||
|
## Per-Request Deduplication with React.cache()
|
||||||
|
|
||||||
|
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { cache } from 'react'
|
||||||
|
|
||||||
|
export const getCurrentUser = cache(async () => {
|
||||||
|
const session = await auth()
|
||||||
|
if (!session?.user?.id) return null
|
||||||
|
return await db.user.findUnique({
|
||||||
|
where: { id: session.user.id }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
||||||
@ -0,0 +1,79 @@
|
|||||||
|
---
|
||||||
|
title: Parallel Data Fetching with Component Composition
|
||||||
|
impact: CRITICAL
|
||||||
|
impactDescription: eliminates server-side waterfalls
|
||||||
|
tags: server, rsc, parallel-fetching, composition
|
||||||
|
---
|
||||||
|
|
||||||
|
## Parallel Data Fetching with Component Composition
|
||||||
|
|
||||||
|
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
||||||
|
|
||||||
|
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default async function Page() {
|
||||||
|
const header = await fetchHeader()
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>{header}</div>
|
||||||
|
<Sidebar />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Sidebar() {
|
||||||
|
const items = await fetchSidebarItems()
|
||||||
|
return <nav>{items.map(renderItem)}</nav>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (both fetch simultaneously):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Header() {
|
||||||
|
const data = await fetchHeader()
|
||||||
|
return <div>{data}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Sidebar() {
|
||||||
|
const items = await fetchSidebarItems()
|
||||||
|
return <nav>{items.map(renderItem)}</nav>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Header />
|
||||||
|
<Sidebar />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Alternative with children prop:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Layout({ children }: { children: ReactNode }) {
|
||||||
|
const header = await fetchHeader()
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>{header}</div>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Sidebar() {
|
||||||
|
const items = await fetchSidebarItems()
|
||||||
|
return <nav>{items.map(renderItem)}</nav>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return (
|
||||||
|
<Layout>
|
||||||
|
<Sidebar />
|
||||||
|
</Layout>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
title: Minimize Serialization at RSC Boundaries
|
||||||
|
impact: HIGH
|
||||||
|
impactDescription: reduces data transfer size
|
||||||
|
tags: server, rsc, serialization, props
|
||||||
|
---
|
||||||
|
|
||||||
|
## Minimize Serialization at RSC Boundaries
|
||||||
|
|
||||||
|
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
||||||
|
|
||||||
|
**Incorrect (serializes all 50 fields):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const user = await fetchUser() // 50 fields
|
||||||
|
return <Profile user={user} />
|
||||||
|
}
|
||||||
|
|
||||||
|
'use client'
|
||||||
|
function Profile({ user }: { user: User }) {
|
||||||
|
return <div>{user.name}</div> // uses 1 field
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (serializes only 1 field):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function Page() {
|
||||||
|
const user = await fetchUser()
|
||||||
|
return <Profile name={user.name} />
|
||||||
|
}
|
||||||
|
|
||||||
|
'use client'
|
||||||
|
function Profile({ name }: { name: string }) {
|
||||||
|
return <div>{name}</div>
|
||||||
|
}
|
||||||
|
```
|
||||||
619
.agents/skills/react-flow-architect/SKILL.md
Normal file
619
.agents/skills/react-flow-architect/SKILL.md
Normal file
@ -0,0 +1,619 @@
|
|||||||
|
---
|
||||||
|
name: react-flow-architect
|
||||||
|
description: "Expert ReactFlow architect for building interactive graph applications with hierarchical node-edge systems, performance optimization, and auto-layout integration. Use when Claude needs to create or..."
|
||||||
|
risk: unknown
|
||||||
|
source: community
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# ReactFlow Architect
|
||||||
|
|
||||||
|
Build production-ready ReactFlow applications with hierarchical navigation, performance optimization, and advanced state management.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
Create basic interactive graph:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import ReactFlow, { Node, Edge } from "reactflow";
|
||||||
|
|
||||||
|
const nodes: Node[] = [
|
||||||
|
{ id: "1", position: { x: 0, y: 0 }, data: { label: "Node 1" } },
|
||||||
|
{ id: "2", position: { x: 100, y: 100 }, data: { label: "Node 2" } },
|
||||||
|
];
|
||||||
|
|
||||||
|
const edges: Edge[] = [{ id: "e1-2", source: "1", target: "2" }];
|
||||||
|
|
||||||
|
export default function Graph() {
|
||||||
|
return <ReactFlow nodes={nodes} edges={edges} />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Core Patterns
|
||||||
|
|
||||||
|
### Hierarchical Tree Navigation
|
||||||
|
|
||||||
|
Build expandable/collapsible tree structures with parent-child relationships.
|
||||||
|
|
||||||
|
#### Node Schema
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface TreeNode extends Node {
|
||||||
|
data: {
|
||||||
|
label: string;
|
||||||
|
level: number;
|
||||||
|
hasChildren: boolean;
|
||||||
|
isExpanded: boolean;
|
||||||
|
childCount: number;
|
||||||
|
category: "root" | "category" | "process" | "detail";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Incremental Node Building
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const buildVisibleNodes = useCallback(
|
||||||
|
(allNodes: TreeNode[], expandedIds: Set<string>, otherDeps: any[]) => {
|
||||||
|
const visibleNodes = new Map<string, TreeNode>();
|
||||||
|
const visibleEdges = new Map<string, TreeEdge>();
|
||||||
|
|
||||||
|
// Start with root nodes
|
||||||
|
const rootNodes = allNodes.filter((n) => n.data.level === 0);
|
||||||
|
|
||||||
|
// Recursively add visible nodes
|
||||||
|
const addVisibleChildren = (node: TreeNode) => {
|
||||||
|
visibleNodes.set(node.id, node);
|
||||||
|
|
||||||
|
if (expandedIds.has(node.id)) {
|
||||||
|
const children = allNodes.filter((n) => n.parentNode === node.id);
|
||||||
|
children.forEach((child) => addVisibleChildren(child));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
rootNodes.forEach((root) => addVisibleChildren(root));
|
||||||
|
|
||||||
|
return {
|
||||||
|
nodes: Array.from(visibleNodes.values()),
|
||||||
|
edges: Array.from(visibleEdges.values()),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance Optimization
|
||||||
|
|
||||||
|
Handle large datasets with incremental rendering and memoization.
|
||||||
|
|
||||||
|
#### Incremental Rendering
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const useIncrementalGraph = (
|
||||||
|
allNodes: Node[],
|
||||||
|
allEdges: Edge[],
|
||||||
|
expandedList: string[],
|
||||||
|
) => {
|
||||||
|
const prevExpandedListRef = useRef<Set<string>>(new Set());
|
||||||
|
const prevOtherDepsRef = useRef<any[]>([]);
|
||||||
|
|
||||||
|
const { visibleNodes, visibleEdges } = useMemo(() => {
|
||||||
|
const currentExpandedSet = new Set(expandedList);
|
||||||
|
const prevExpandedSet = prevExpandedListRef.current;
|
||||||
|
|
||||||
|
// Check if expanded list changed
|
||||||
|
const expandedChanged = !areSetsEqual(currentExpandedSet, prevExpandedSet);
|
||||||
|
|
||||||
|
// Check if other dependencies changed
|
||||||
|
const otherDepsChanged = !arraysEqual(otherDeps, prevOtherDepsRef.current);
|
||||||
|
|
||||||
|
if (expandedChanged && !otherDepsChanged) {
|
||||||
|
// Only expanded list changed - incremental update
|
||||||
|
return buildIncrementalUpdate(
|
||||||
|
cachedVisibleNodesRef.current,
|
||||||
|
cachedVisibleEdgesRef.current,
|
||||||
|
allNodes,
|
||||||
|
allEdges,
|
||||||
|
currentExpandedSet,
|
||||||
|
prevExpandedSet,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Full rebuild needed
|
||||||
|
return buildFullGraph(allNodes, allEdges, currentExpandedSet);
|
||||||
|
}
|
||||||
|
}, [allNodes, allEdges, expandedList, ...otherDeps]);
|
||||||
|
|
||||||
|
return { visibleNodes, visibleEdges };
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Memoization Patterns
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Memoize node components to prevent unnecessary re-renders
|
||||||
|
const ProcessNode = memo(({ data, selected }: NodeProps) => {
|
||||||
|
return (
|
||||||
|
<div className={`process-node ${selected ? 'selected' : ''}`}>
|
||||||
|
{data.label}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}, (prevProps, nextProps) => {
|
||||||
|
// Custom comparison function
|
||||||
|
return (
|
||||||
|
prevProps.data.label === nextProps.data.label &&
|
||||||
|
prevProps.selected === nextProps.selected &&
|
||||||
|
prevProps.data.isExpanded === nextProps.data.isExpanded
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Memoize edge calculations
|
||||||
|
const styledEdges = useMemo(() => {
|
||||||
|
return edges.map(edge => ({
|
||||||
|
...edge,
|
||||||
|
style: {
|
||||||
|
...edge.style,
|
||||||
|
strokeWidth: selectedEdgeId === edge.id ? 3 : 2,
|
||||||
|
stroke: selectedEdgeId === edge.id ? '#3b82f6' : '#94a3b8',
|
||||||
|
},
|
||||||
|
animated: selectedEdgeId === edge.id,
|
||||||
|
}));
|
||||||
|
}, [edges, selectedEdgeId]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### State Management
|
||||||
|
|
||||||
|
Complex node/edge state patterns with undo/redo and persistence.
|
||||||
|
|
||||||
|
#### Reducer Pattern
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type GraphAction =
|
||||||
|
| { type: "SELECT_NODE"; payload: string }
|
||||||
|
| { type: "SELECT_EDGE"; payload: string }
|
||||||
|
| { type: "TOGGLE_EXPAND"; payload: string }
|
||||||
|
| { type: "UPDATE_NODES"; payload: Node[] }
|
||||||
|
| { type: "UPDATE_EDGES"; payload: Edge[] }
|
||||||
|
| { type: "UNDO" }
|
||||||
|
| { type: "REDO" };
|
||||||
|
|
||||||
|
const graphReducer = (state: GraphState, action: GraphAction): GraphState => {
|
||||||
|
switch (action.type) {
|
||||||
|
case "SELECT_NODE":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
selectedNodeId: action.payload,
|
||||||
|
selectedEdgeId: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
case "TOGGLE_EXPAND":
|
||||||
|
const newExpanded = new Set(state.expandedNodeIds);
|
||||||
|
if (newExpanded.has(action.payload)) {
|
||||||
|
newExpanded.delete(action.payload);
|
||||||
|
} else {
|
||||||
|
newExpanded.add(action.payload);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
expandedNodeIds: newExpanded,
|
||||||
|
isDirty: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
default:
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
#### History Management
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const useHistoryManager = (
|
||||||
|
state: GraphState,
|
||||||
|
dispatch: Dispatch<GraphAction>,
|
||||||
|
) => {
|
||||||
|
const canUndo = state.historyIndex > 0;
|
||||||
|
const canRedo = state.historyIndex < state.history.length - 1;
|
||||||
|
|
||||||
|
const undo = useCallback(() => {
|
||||||
|
if (canUndo) {
|
||||||
|
const newIndex = state.historyIndex - 1;
|
||||||
|
const historyEntry = state.history[newIndex];
|
||||||
|
|
||||||
|
dispatch({
|
||||||
|
type: "RESTORE_FROM_HISTORY",
|
||||||
|
payload: {
|
||||||
|
...historyEntry,
|
||||||
|
historyIndex: newIndex,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [canUndo, state.historyIndex, state.history]);
|
||||||
|
|
||||||
|
const saveToHistory = useCallback(() => {
|
||||||
|
dispatch({ type: "SAVE_TO_HISTORY" });
|
||||||
|
}, [dispatch]);
|
||||||
|
|
||||||
|
return { canUndo, canRedo, undo, redo, saveToHistory };
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Features
|
||||||
|
|
||||||
|
### Auto-Layout Integration
|
||||||
|
|
||||||
|
Integrate Dagre for automatic graph layout:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import dagre from "dagre";
|
||||||
|
|
||||||
|
const layoutOptions = {
|
||||||
|
rankdir: "TB", // Top to Bottom
|
||||||
|
nodesep: 100, // Node separation
|
||||||
|
ranksep: 150, // Rank separation
|
||||||
|
marginx: 50,
|
||||||
|
marginy: 50,
|
||||||
|
edgesep: 10,
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyLayout = (nodes: Node[], edges: Edge[]) => {
|
||||||
|
const g = new dagre.graphlib.Graph();
|
||||||
|
g.setGraph(layoutOptions);
|
||||||
|
g.setDefaultEdgeLabel(() => ({}));
|
||||||
|
|
||||||
|
// Add nodes to graph
|
||||||
|
nodes.forEach((node) => {
|
||||||
|
g.setNode(node.id, { width: 200, height: 100 });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add edges to graph
|
||||||
|
edges.forEach((edge) => {
|
||||||
|
g.setEdge(edge.source, edge.target);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Calculate layout
|
||||||
|
dagre.layout(g);
|
||||||
|
|
||||||
|
// Apply positions
|
||||||
|
return nodes.map((node) => ({
|
||||||
|
...node,
|
||||||
|
position: {
|
||||||
|
x: g.node(node.id).x - 100,
|
||||||
|
y: g.node(node.id).y - 50,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Debounce layout calculations
|
||||||
|
const debouncedLayout = useMemo(() => debounce(applyLayout, 150), []);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Focus Mode
|
||||||
|
|
||||||
|
Isolate selected nodes and their direct connections:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const useFocusMode = (
|
||||||
|
selectedNodeId: string,
|
||||||
|
allNodes: Node[],
|
||||||
|
allEdges: Edge[],
|
||||||
|
) => {
|
||||||
|
return useMemo(() => {
|
||||||
|
if (!selectedNodeId) return { nodes: allNodes, edges: allEdges };
|
||||||
|
|
||||||
|
// Get direct connections
|
||||||
|
const connectedNodeIds = new Set([selectedNodeId]);
|
||||||
|
const focusedEdges: Edge[] = [];
|
||||||
|
|
||||||
|
allEdges.forEach((edge) => {
|
||||||
|
if (edge.source === selectedNodeId || edge.target === selectedNodeId) {
|
||||||
|
focusedEdges.push(edge);
|
||||||
|
connectedNodeIds.add(edge.source);
|
||||||
|
connectedNodeIds.add(edge.target);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get connected nodes
|
||||||
|
const focusedNodes = allNodes.filter((n) => connectedNodeIds.has(n.id));
|
||||||
|
|
||||||
|
return { nodes: focusedNodes, edges: focusedEdges };
|
||||||
|
}, [selectedNodeId, allNodes, allEdges]);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Smooth transitions for focus mode
|
||||||
|
const focusModeStyles = {
|
||||||
|
transition: "all 0.3s ease-in-out",
|
||||||
|
opacity: isInFocus ? 1 : 0.3,
|
||||||
|
filter: isInFocus ? "none" : "blur(2px)",
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Search Integration
|
||||||
|
|
||||||
|
Search and navigate to specific nodes:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const searchNodes = useCallback((nodes: Node[], query: string) => {
|
||||||
|
if (!query.trim()) return [];
|
||||||
|
|
||||||
|
const lowerQuery = query.toLowerCase();
|
||||||
|
return nodes.filter(
|
||||||
|
(node) =>
|
||||||
|
node.data.label.toLowerCase().includes(lowerQuery) ||
|
||||||
|
node.data.description?.toLowerCase().includes(lowerQuery),
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const navigateToSearchResult = (nodeId: string) => {
|
||||||
|
// Expand parent nodes
|
||||||
|
const nodePath = calculateBreadcrumbPath(nodeId, allNodes);
|
||||||
|
const parentIds = nodePath.slice(0, -1).map((n) => n.id);
|
||||||
|
|
||||||
|
setExpandedIds((prev) => new Set([...prev, ...parentIds]));
|
||||||
|
setSelectedNodeId(nodeId);
|
||||||
|
|
||||||
|
// Fit view to node
|
||||||
|
fitView({ nodes: [{ id: nodeId }], duration: 800 });
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance Tools
|
||||||
|
|
||||||
|
### Graph Performance Analyzer
|
||||||
|
|
||||||
|
Create a performance analysis script:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// scripts/graph-analyzer.js
|
||||||
|
class GraphAnalyzer {
|
||||||
|
analyzeCode(content, filePath) {
|
||||||
|
const analysis = {
|
||||||
|
metrics: {
|
||||||
|
nodeCount: this.countNodes(content),
|
||||||
|
edgeCount: this.countEdges(content),
|
||||||
|
renderTime: this.estimateRenderTime(content),
|
||||||
|
memoryUsage: this.estimateMemoryUsage(content),
|
||||||
|
complexity: this.calculateComplexity(content),
|
||||||
|
},
|
||||||
|
issues: [],
|
||||||
|
optimizations: [],
|
||||||
|
patterns: this.detectPatterns(content),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Detect performance issues
|
||||||
|
this.detectPerformanceIssues(analysis);
|
||||||
|
|
||||||
|
// Suggest optimizations
|
||||||
|
this.suggestOptimizations(analysis);
|
||||||
|
|
||||||
|
return analysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
countNodes(content) {
|
||||||
|
const nodePatterns = [
|
||||||
|
/nodes:\s*\[.*?\]/gs,
|
||||||
|
/const\s+\w+\s*=\s*\[.*?id:.*?position:/gs,
|
||||||
|
];
|
||||||
|
|
||||||
|
let totalCount = 0;
|
||||||
|
nodePatterns.forEach((pattern) => {
|
||||||
|
const matches = content.match(pattern);
|
||||||
|
if (matches) {
|
||||||
|
matches.forEach((match) => {
|
||||||
|
const nodeMatches = match.match(/id:\s*['"`][^'"`]+['"`]/g);
|
||||||
|
if (nodeMatches) {
|
||||||
|
totalCount += nodeMatches.length;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return totalCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
estimateRenderTime(content) {
|
||||||
|
const nodeCount = this.countNodes(content);
|
||||||
|
const edgeCount = this.countEdges(content);
|
||||||
|
|
||||||
|
// Base render time estimation (ms)
|
||||||
|
const baseTime = 5;
|
||||||
|
const nodeTime = nodeCount * 0.1;
|
||||||
|
const edgeTime = edgeCount * 0.05;
|
||||||
|
|
||||||
|
return baseTime + nodeTime + edgeTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
detectPerformanceIssues(analysis) {
|
||||||
|
const { metrics } = analysis;
|
||||||
|
|
||||||
|
if (metrics.nodeCount > 500) {
|
||||||
|
analysis.issues.push({
|
||||||
|
type: "HIGH_NODE_COUNT",
|
||||||
|
severity: "high",
|
||||||
|
message: `Too many nodes (${metrics.nodeCount}). Consider virtualization.`,
|
||||||
|
suggestion: "Implement virtualization or reduce visible nodes",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (metrics.renderTime > 16) {
|
||||||
|
analysis.issues.push({
|
||||||
|
type: "SLOW_RENDER",
|
||||||
|
severity: "high",
|
||||||
|
message: `Render time (${metrics.renderTime.toFixed(2)}ms) exceeds 60fps.`,
|
||||||
|
suggestion: "Optimize with memoization and incremental rendering",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Performance Guidelines
|
||||||
|
|
||||||
|
1. **Use React.memo** for node components to prevent unnecessary re-renders
|
||||||
|
2. **Implement virtualization** for graphs with 1000+ nodes
|
||||||
|
3. **Debounce layout calculations** during rapid interactions
|
||||||
|
4. **Use useCallback** for edge creation and manipulation functions
|
||||||
|
5. **Implement proper TypeScript types** for nodes and edges
|
||||||
|
|
||||||
|
### Memory Management
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Use Map for O(1) lookups instead of array.find
|
||||||
|
const nodesById = useMemo(
|
||||||
|
() => new Map(allNodes.map((n) => [n.id, n])),
|
||||||
|
[allNodes],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Cache layout results
|
||||||
|
const layoutCacheRef = useRef<Map<string, Node[]>>(new Map());
|
||||||
|
|
||||||
|
// Proper cleanup in useEffect
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
// Clean up any lingering references
|
||||||
|
nodesMapRef.current.clear();
|
||||||
|
edgesMapRef.current.clear();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
```
|
||||||
|
|
||||||
|
### State Optimization
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Use useRef for objects that shouldn't trigger re-renders
|
||||||
|
const autoSaveDataRef = useRef({
|
||||||
|
nodes: [],
|
||||||
|
edges: [],
|
||||||
|
lastSaved: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update properties without breaking reference
|
||||||
|
const updateAutoSaveData = (newNodes: Node[], newEdges: Edge[]) => {
|
||||||
|
autoSaveDataRef.current.nodes = newNodes;
|
||||||
|
autoSaveDataRef.current.edges = newEdges;
|
||||||
|
autoSaveDataRef.current.lastSaved = Date.now();
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Problems & Solutions
|
||||||
|
|
||||||
|
### Performance Issues
|
||||||
|
|
||||||
|
- **Problem**: Lag during node expansion
|
||||||
|
- **Solution**: Implement incremental rendering with change detection
|
||||||
|
|
||||||
|
- **Problem**: Memory usage increases over time
|
||||||
|
- **Solution**: Proper cleanup in useEffect hooks and use WeakMap for temporary data
|
||||||
|
|
||||||
|
### Layout Conflicts
|
||||||
|
|
||||||
|
- **Problem**: Manual positioning conflicts with auto-layout
|
||||||
|
- **Solution**: Use controlled positioning state and separate layout modes
|
||||||
|
|
||||||
|
### Rendering Issues
|
||||||
|
|
||||||
|
- **Problem**: Excessive re-renders
|
||||||
|
- **Solution**: Use memo, useMemo, and useCallback with stable dependencies
|
||||||
|
|
||||||
|
- **Problem**: Slow layout calculations
|
||||||
|
- **Solution**: Debounce layout calculations and cache results
|
||||||
|
|
||||||
|
## Complete Example
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import React, { useState, useCallback, useMemo, useRef } from 'react';
|
||||||
|
import ReactFlow, { Node, Edge, useReactFlow } from 'reactflow';
|
||||||
|
import dagre from 'dagre';
|
||||||
|
import { debounce } from 'lodash';
|
||||||
|
|
||||||
|
interface GraphState {
|
||||||
|
nodes: Node[];
|
||||||
|
edges: Edge[];
|
||||||
|
selectedNodeId: string | null;
|
||||||
|
expandedNodeIds: Set<string>;
|
||||||
|
history: GraphState[];
|
||||||
|
historyIndex: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function InteractiveGraph() {
|
||||||
|
const [state, setState] = useState<GraphState>({
|
||||||
|
nodes: [],
|
||||||
|
edges: [],
|
||||||
|
selectedNodeId: null,
|
||||||
|
expandedNodeIds: new Set(),
|
||||||
|
history: [],
|
||||||
|
historyIndex: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { fitView } = useReactFlow();
|
||||||
|
const layoutCacheRef = useRef<Map<string, Node[]>>(new Map());
|
||||||
|
|
||||||
|
// Memoized styled edges
|
||||||
|
const styledEdges = useMemo(() => {
|
||||||
|
return state.edges.map(edge => ({
|
||||||
|
...edge,
|
||||||
|
style: {
|
||||||
|
...edge.style,
|
||||||
|
strokeWidth: state.selectedNodeId === edge.source || state.selectedNodeId === edge.target ? 3 : 2,
|
||||||
|
stroke: state.selectedNodeId === edge.source || state.selectedNodeId === edge.target ? '#3b82f6' : '#94a3b8',
|
||||||
|
},
|
||||||
|
animated: state.selectedNodeId === edge.source || state.selectedNodeId === edge.target,
|
||||||
|
}));
|
||||||
|
}, [state.edges, state.selectedNodeId]);
|
||||||
|
|
||||||
|
// Debounced layout calculation
|
||||||
|
const debouncedLayout = useMemo(
|
||||||
|
() => debounce((nodes: Node[], edges: Edge[]) => {
|
||||||
|
const cacheKey = generateLayoutCacheKey(nodes, edges);
|
||||||
|
|
||||||
|
if (layoutCacheRef.current.has(cacheKey)) {
|
||||||
|
return layoutCacheRef.current.get(cacheKey)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
const layouted = applyDagreLayout(nodes, edges);
|
||||||
|
layoutCacheRef.current.set(cacheKey, layouted);
|
||||||
|
|
||||||
|
return layouted;
|
||||||
|
}, 150),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleNodeClick = useCallback((event: React.MouseEvent, node: Node) => {
|
||||||
|
setState(prev => ({
|
||||||
|
...prev,
|
||||||
|
selectedNodeId: node.id,
|
||||||
|
}));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleToggleExpand = useCallback((nodeId: string) => {
|
||||||
|
setState(prev => {
|
||||||
|
const newExpanded = new Set(prev.expandedNodeIds);
|
||||||
|
if (newExpanded.has(nodeId)) {
|
||||||
|
newExpanded.delete(nodeId);
|
||||||
|
} else {
|
||||||
|
newExpanded.add(nodeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
expandedNodeIds: newExpanded,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ReactFlow
|
||||||
|
nodes={state.nodes}
|
||||||
|
edges={styledEdges}
|
||||||
|
onNodeClick={handleNodeClick}
|
||||||
|
fitView
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This comprehensive skill provides everything needed to build production-ready ReactFlow applications with hierarchical navigation, performance optimization, and advanced state management patterns.
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
This skill is applicable to execute the workflow or actions described in the overview.
|
||||||
37
.agents/skills/react-modernization/SKILL.md
Normal file
37
.agents/skills/react-modernization/SKILL.md
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
name: react-modernization
|
||||||
|
description: "Upgrade React applications to latest versions, migrate from class components to hooks, and adopt concurrent features. Use when modernizing React codebases, migrating to React Hooks, or upgrading to..."
|
||||||
|
risk: unknown
|
||||||
|
source: community
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# React Modernization
|
||||||
|
|
||||||
|
Master React version upgrades, class to hooks migration, concurrent features adoption, and codemods for automated transformation.
|
||||||
|
|
||||||
|
## Use this skill when
|
||||||
|
|
||||||
|
- Upgrading React applications to latest versions
|
||||||
|
- Migrating class components to functional components with hooks
|
||||||
|
- Adopting concurrent React features (Suspense, transitions)
|
||||||
|
- Applying codemods for automated refactoring
|
||||||
|
- Modernizing state management patterns
|
||||||
|
- Updating to TypeScript
|
||||||
|
- Improving performance with React 18+ features
|
||||||
|
|
||||||
|
## Do not use this skill when
|
||||||
|
|
||||||
|
- The task is unrelated to react modernization
|
||||||
|
- You need a different domain or tool outside this scope
|
||||||
|
|
||||||
|
## Instructions
|
||||||
|
|
||||||
|
- Clarify goals, constraints, and required inputs.
|
||||||
|
- Apply relevant best practices and validate outcomes.
|
||||||
|
- Provide actionable steps and verification.
|
||||||
|
- If detailed examples are required, open `resources/implementation-playbook.md`.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- `resources/implementation-playbook.md` for detailed patterns and examples.
|
||||||
@ -0,0 +1,512 @@
|
|||||||
|
# React Modernization Implementation Playbook
|
||||||
|
|
||||||
|
This file contains detailed patterns, checklists, and code samples referenced by the skill.
|
||||||
|
|
||||||
|
# React Modernization
|
||||||
|
|
||||||
|
Master React version upgrades, class to hooks migration, concurrent features adoption, and codemods for automated transformation.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
- Upgrading React applications to latest versions
|
||||||
|
- Migrating class components to functional components with hooks
|
||||||
|
- Adopting concurrent React features (Suspense, transitions)
|
||||||
|
- Applying codemods for automated refactoring
|
||||||
|
- Modernizing state management patterns
|
||||||
|
- Updating to TypeScript
|
||||||
|
- Improving performance with React 18+ features
|
||||||
|
|
||||||
|
## Version Upgrade Path
|
||||||
|
|
||||||
|
### React 16 → 17 → 18
|
||||||
|
|
||||||
|
**Breaking Changes by Version:**
|
||||||
|
|
||||||
|
**React 17:**
|
||||||
|
- Event delegation changes
|
||||||
|
- No event pooling
|
||||||
|
- Effect cleanup timing
|
||||||
|
- JSX transform (no React import needed)
|
||||||
|
|
||||||
|
**React 18:**
|
||||||
|
- Automatic batching
|
||||||
|
- Concurrent rendering
|
||||||
|
- Strict Mode changes (double invocation)
|
||||||
|
- New root API
|
||||||
|
- Suspense on server
|
||||||
|
|
||||||
|
## Class to Hooks Migration
|
||||||
|
|
||||||
|
### State Management
|
||||||
|
```javascript
|
||||||
|
// Before: Class component
|
||||||
|
class Counter extends React.Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = {
|
||||||
|
count: 0,
|
||||||
|
name: ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
increment = () => {
|
||||||
|
this.setState({ count: this.state.count + 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p>Count: {this.state.count}</p>
|
||||||
|
<button onClick={this.increment}>Increment</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// After: Functional component with hooks
|
||||||
|
function Counter() {
|
||||||
|
const [count, setCount] = useState(0);
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
|
||||||
|
const increment = () => {
|
||||||
|
setCount(count + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p>Count: {count}</p>
|
||||||
|
<button onClick={increment}>Increment</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Lifecycle Methods to Hooks
|
||||||
|
```javascript
|
||||||
|
// Before: Lifecycle methods
|
||||||
|
class DataFetcher extends React.Component {
|
||||||
|
state = { data: null, loading: true };
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
this.fetchData();
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps) {
|
||||||
|
if (prevProps.id !== this.props.id) {
|
||||||
|
this.fetchData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
componentWillUnmount() {
|
||||||
|
this.cancelRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchData = async () => {
|
||||||
|
const data = await fetch(`/api/${this.props.id}`);
|
||||||
|
this.setState({ data, loading: false });
|
||||||
|
};
|
||||||
|
|
||||||
|
cancelRequest = () => {
|
||||||
|
// Cleanup
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.loading) return <div>Loading...</div>;
|
||||||
|
return <div>{this.state.data}</div>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// After: useEffect hook
|
||||||
|
function DataFetcher({ id }) {
|
||||||
|
const [data, setData] = useState(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
const fetchData = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/${id}`);
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (!cancelled) {
|
||||||
|
setData(result);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (!cancelled) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchData();
|
||||||
|
|
||||||
|
// Cleanup function
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [id]); // Re-run when id changes
|
||||||
|
|
||||||
|
if (loading) return <div>Loading...</div>;
|
||||||
|
return <div>{data}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Context and HOCs to Hooks
|
||||||
|
```javascript
|
||||||
|
// Before: Context consumer and HOC
|
||||||
|
const ThemeContext = React.createContext();
|
||||||
|
|
||||||
|
class ThemedButton extends React.Component {
|
||||||
|
static contextType = ThemeContext;
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return (
|
||||||
|
<button style={{ background: this.context.theme }}>
|
||||||
|
{this.props.children}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// After: useContext hook
|
||||||
|
function ThemedButton({ children }) {
|
||||||
|
const { theme } = useContext(ThemeContext);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button style={{ background: theme }}>
|
||||||
|
{children}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Before: HOC for data fetching
|
||||||
|
function withUser(Component) {
|
||||||
|
return class extends React.Component {
|
||||||
|
state = { user: null };
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
fetchUser().then(user => this.setState({ user }));
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return <Component {...this.props} user={this.state.user} />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// After: Custom hook
|
||||||
|
function useUser() {
|
||||||
|
const [user, setUser] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUser().then(setUser);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
function UserProfile() {
|
||||||
|
const user = useUser();
|
||||||
|
if (!user) return <div>Loading...</div>;
|
||||||
|
return <div>{user.name}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## React 18 Concurrent Features
|
||||||
|
|
||||||
|
### New Root API
|
||||||
|
```javascript
|
||||||
|
// Before: React 17
|
||||||
|
import ReactDOM from 'react-dom';
|
||||||
|
|
||||||
|
ReactDOM.render(<App />, document.getElementById('root'));
|
||||||
|
|
||||||
|
// After: React 18
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
|
||||||
|
const root = createRoot(document.getElementById('root'));
|
||||||
|
root.render(<App />);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Automatic Batching
|
||||||
|
```javascript
|
||||||
|
// React 18: All updates are batched
|
||||||
|
function handleClick() {
|
||||||
|
setCount(c => c + 1);
|
||||||
|
setFlag(f => !f);
|
||||||
|
// Only one re-render (batched)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Even in async:
|
||||||
|
setTimeout(() => {
|
||||||
|
setCount(c => c + 1);
|
||||||
|
setFlag(f => !f);
|
||||||
|
// Still batched in React 18!
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
|
// Opt out if needed
|
||||||
|
import { flushSync } from 'react-dom';
|
||||||
|
|
||||||
|
flushSync(() => {
|
||||||
|
setCount(c => c + 1);
|
||||||
|
});
|
||||||
|
// Re-render happens here
|
||||||
|
setFlag(f => !f);
|
||||||
|
// Another re-render
|
||||||
|
```
|
||||||
|
|
||||||
|
### Transitions
|
||||||
|
```javascript
|
||||||
|
import { useState, useTransition } from 'react';
|
||||||
|
|
||||||
|
function SearchResults() {
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [results, setResults] = useState([]);
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
// Urgent: Update input immediately
|
||||||
|
setQuery(e.target.value);
|
||||||
|
|
||||||
|
// Non-urgent: Update results (can be interrupted)
|
||||||
|
startTransition(() => {
|
||||||
|
setResults(searchResults(e.target.value));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<input value={query} onChange={handleChange} />
|
||||||
|
{isPending && <Spinner />}
|
||||||
|
<Results data={results} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Suspense for Data Fetching
|
||||||
|
```javascript
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
|
// Resource-based data fetching (with React 18)
|
||||||
|
const resource = fetchProfileData();
|
||||||
|
|
||||||
|
function ProfilePage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<ProfileDetails />
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<ProfileTimeline />
|
||||||
|
</Suspense>
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProfileDetails() {
|
||||||
|
// This will suspend if data not ready
|
||||||
|
const user = resource.user.read();
|
||||||
|
return <h1>{user.name}</h1>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProfileTimeline() {
|
||||||
|
const posts = resource.posts.read();
|
||||||
|
return <Timeline posts={posts} />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Codemods for Automation
|
||||||
|
|
||||||
|
### Run React Codemods
|
||||||
|
```bash
|
||||||
|
# Install jscodeshift
|
||||||
|
npm install -g jscodeshift
|
||||||
|
|
||||||
|
# React 16.9 codemod (rename unsafe lifecycle methods)
|
||||||
|
npx react-codeshift <transform> <path>
|
||||||
|
|
||||||
|
# Example: Rename UNSAFE_ methods
|
||||||
|
npx react-codeshift --parser=tsx \
|
||||||
|
--transform=react-codeshift/transforms/rename-unsafe-lifecycles.js \
|
||||||
|
src/
|
||||||
|
|
||||||
|
# Update to new JSX Transform (React 17+)
|
||||||
|
npx react-codeshift --parser=tsx \
|
||||||
|
--transform=react-codeshift/transforms/new-jsx-transform.js \
|
||||||
|
src/
|
||||||
|
|
||||||
|
# Class to Hooks (third-party)
|
||||||
|
npx codemod react/hooks/convert-class-to-function src/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom Codemod Example
|
||||||
|
```javascript
|
||||||
|
// custom-codemod.js
|
||||||
|
module.exports = function(file, api) {
|
||||||
|
const j = api.jscodeshift;
|
||||||
|
const root = j(file.source);
|
||||||
|
|
||||||
|
// Find setState calls
|
||||||
|
root.find(j.CallExpression, {
|
||||||
|
callee: {
|
||||||
|
type: 'MemberExpression',
|
||||||
|
property: { name: 'setState' }
|
||||||
|
}
|
||||||
|
}).forEach(path => {
|
||||||
|
// Transform to useState
|
||||||
|
// ... transformation logic
|
||||||
|
});
|
||||||
|
|
||||||
|
return root.toSource();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Run: jscodeshift -t custom-codemod.js src/
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance Optimization
|
||||||
|
|
||||||
|
### useMemo and useCallback
|
||||||
|
```javascript
|
||||||
|
function ExpensiveComponent({ items, filter }) {
|
||||||
|
// Memoize expensive calculation
|
||||||
|
const filteredItems = useMemo(() => {
|
||||||
|
return items.filter(item => item.category === filter);
|
||||||
|
}, [items, filter]);
|
||||||
|
|
||||||
|
// Memoize callback to prevent child re-renders
|
||||||
|
const handleClick = useCallback((id) => {
|
||||||
|
console.log('Clicked:', id);
|
||||||
|
}, []); // No dependencies, never changes
|
||||||
|
|
||||||
|
return (
|
||||||
|
<List items={filteredItems} onClick={handleClick} />
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Child component with memo
|
||||||
|
const List = React.memo(({ items, onClick }) => {
|
||||||
|
return items.map(item => (
|
||||||
|
<Item key={item.id} item={item} onClick={onClick} />
|
||||||
|
));
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Code Splitting
|
||||||
|
```javascript
|
||||||
|
import { lazy, Suspense } from 'react';
|
||||||
|
|
||||||
|
// Lazy load components
|
||||||
|
const Dashboard = lazy(() => import('./Dashboard'));
|
||||||
|
const Settings = lazy(() => import('./Settings'));
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/dashboard" element={<Dashboard />} />
|
||||||
|
<Route path="/settings" element={<Settings />} />
|
||||||
|
</Routes>
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## TypeScript Migration
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Before: JavaScript
|
||||||
|
function Button({ onClick, children }) {
|
||||||
|
return <button onClick={onClick}>{children}</button>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// After: TypeScript
|
||||||
|
interface ButtonProps {
|
||||||
|
onClick: () => void;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Button({ onClick, children }: ButtonProps) {
|
||||||
|
return <button onClick={onClick}>{children}</button>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generic components
|
||||||
|
interface ListProps<T> {
|
||||||
|
items: T[];
|
||||||
|
renderItem: (item: T) => React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function List<T>({ items, renderItem }: ListProps<T>) {
|
||||||
|
return <>{items.map(renderItem)}</>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration Checklist
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
### Pre-Migration
|
||||||
|
- [ ] Update dependencies incrementally (not all at once)
|
||||||
|
- [ ] Review breaking changes in release notes
|
||||||
|
- [ ] Set up testing suite
|
||||||
|
- [ ] Create feature branch
|
||||||
|
|
||||||
|
### Class → Hooks Migration
|
||||||
|
- [ ] Identify class components to migrate
|
||||||
|
- [ ] Start with leaf components (no children)
|
||||||
|
- [ ] Convert state to useState
|
||||||
|
- [ ] Convert lifecycle to useEffect
|
||||||
|
- [ ] Convert context to useContext
|
||||||
|
- [ ] Extract custom hooks
|
||||||
|
- [ ] Test thoroughly
|
||||||
|
|
||||||
|
### React 18 Upgrade
|
||||||
|
- [ ] Update to React 17 first (if needed)
|
||||||
|
- [ ] Update react and react-dom to 18
|
||||||
|
- [ ] Update @types/react if using TypeScript
|
||||||
|
- [ ] Change to createRoot API
|
||||||
|
- [ ] Test with StrictMode (double invocation)
|
||||||
|
- [ ] Address concurrent rendering issues
|
||||||
|
- [ ] Adopt Suspense/Transitions where beneficial
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
- [ ] Identify performance bottlenecks
|
||||||
|
- [ ] Add React.memo where appropriate
|
||||||
|
- [ ] Use useMemo/useCallback for expensive operations
|
||||||
|
- [ ] Implement code splitting
|
||||||
|
- [ ] Optimize re-renders
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
- [ ] Update test utilities (React Testing Library)
|
||||||
|
- [ ] Test with React 18 features
|
||||||
|
- [ ] Check for warnings in console
|
||||||
|
- [ ] Performance testing
|
||||||
|
```
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- **references/breaking-changes.md**: Version-specific breaking changes
|
||||||
|
- **references/codemods.md**: Codemod usage guide
|
||||||
|
- **references/hooks-migration.md**: Comprehensive hooks patterns
|
||||||
|
- **references/concurrent-features.md**: React 18 concurrent features
|
||||||
|
- **assets/codemod-config.json**: Codemod configurations
|
||||||
|
- **assets/migration-checklist.md**: Step-by-step checklist
|
||||||
|
- **scripts/apply-codemods.sh**: Automated codemod script
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
1. **Incremental Migration**: Don't migrate everything at once
|
||||||
|
2. **Test Thoroughly**: Comprehensive testing at each step
|
||||||
|
3. **Use Codemods**: Automate repetitive transformations
|
||||||
|
4. **Start Simple**: Begin with leaf components
|
||||||
|
5. **Leverage StrictMode**: Catch issues early
|
||||||
|
6. **Monitor Performance**: Measure before and after
|
||||||
|
7. **Document Changes**: Keep migration log
|
||||||
|
|
||||||
|
## Common Pitfalls
|
||||||
|
|
||||||
|
- Forgetting useEffect dependencies
|
||||||
|
- Over-using useMemo/useCallback
|
||||||
|
- Not handling cleanup in useEffect
|
||||||
|
- Mixing class and functional patterns
|
||||||
|
- Ignoring StrictMode warnings
|
||||||
|
- Breaking change assumptions
|
||||||
203
.agents/skills/react-patterns/SKILL.md
Normal file
203
.agents/skills/react-patterns/SKILL.md
Normal file
@ -0,0 +1,203 @@
|
|||||||
|
---
|
||||||
|
name: react-patterns
|
||||||
|
description: "Modern React patterns and principles. Hooks, composition, performance, TypeScript best practices."
|
||||||
|
risk: unknown
|
||||||
|
source: community
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# React Patterns
|
||||||
|
|
||||||
|
> Principles for building production-ready React applications.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Component Design Principles
|
||||||
|
|
||||||
|
### Component Types
|
||||||
|
|
||||||
|
| Type | Use | State |
|
||||||
|
|------|-----|-------|
|
||||||
|
| **Server** | Data fetching, static | None |
|
||||||
|
| **Client** | Interactivity | useState, effects |
|
||||||
|
| **Presentational** | UI display | Props only |
|
||||||
|
| **Container** | Logic/state | Heavy state |
|
||||||
|
|
||||||
|
### Design Rules
|
||||||
|
|
||||||
|
- One responsibility per component
|
||||||
|
- Props down, events up
|
||||||
|
- Composition over inheritance
|
||||||
|
- Prefer small, focused components
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Hook Patterns
|
||||||
|
|
||||||
|
### When to Extract Hooks
|
||||||
|
|
||||||
|
| Pattern | Extract When |
|
||||||
|
|---------|-------------|
|
||||||
|
| **useLocalStorage** | Same storage logic needed |
|
||||||
|
| **useDebounce** | Multiple debounced values |
|
||||||
|
| **useFetch** | Repeated fetch patterns |
|
||||||
|
| **useForm** | Complex form state |
|
||||||
|
|
||||||
|
### Hook Rules
|
||||||
|
|
||||||
|
- Hooks at top level only
|
||||||
|
- Same order every render
|
||||||
|
- Custom hooks start with "use"
|
||||||
|
- Clean up effects on unmount
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. State Management Selection
|
||||||
|
|
||||||
|
| Complexity | Solution |
|
||||||
|
|------------|----------|
|
||||||
|
| Simple | useState, useReducer |
|
||||||
|
| Shared local | Context |
|
||||||
|
| Server state | React Query, SWR |
|
||||||
|
| Complex global | Zustand, Redux Toolkit |
|
||||||
|
|
||||||
|
### State Placement
|
||||||
|
|
||||||
|
| Scope | Where |
|
||||||
|
|-------|-------|
|
||||||
|
| Single component | useState |
|
||||||
|
| Parent-child | Lift state up |
|
||||||
|
| Subtree | Context |
|
||||||
|
| App-wide | Global store |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. React 19 Patterns
|
||||||
|
|
||||||
|
### New Hooks
|
||||||
|
|
||||||
|
| Hook | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| **useActionState** | Form submission state |
|
||||||
|
| **useOptimistic** | Optimistic UI updates |
|
||||||
|
| **use** | Read resources in render |
|
||||||
|
|
||||||
|
### Compiler Benefits
|
||||||
|
|
||||||
|
- Automatic memoization
|
||||||
|
- Less manual useMemo/useCallback
|
||||||
|
- Focus on pure components
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Composition Patterns
|
||||||
|
|
||||||
|
### Compound Components
|
||||||
|
|
||||||
|
- Parent provides context
|
||||||
|
- Children consume context
|
||||||
|
- Flexible slot-based composition
|
||||||
|
- Example: Tabs, Accordion, Dropdown
|
||||||
|
|
||||||
|
### Render Props vs Hooks
|
||||||
|
|
||||||
|
| Use Case | Prefer |
|
||||||
|
|----------|--------|
|
||||||
|
| Reusable logic | Custom hook |
|
||||||
|
| Render flexibility | Render props |
|
||||||
|
| Cross-cutting | Higher-order component |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Performance Principles
|
||||||
|
|
||||||
|
### When to Optimize
|
||||||
|
|
||||||
|
| Signal | Action |
|
||||||
|
|--------|--------|
|
||||||
|
| Slow renders | Profile first |
|
||||||
|
| Large lists | Virtualize |
|
||||||
|
| Expensive calc | useMemo |
|
||||||
|
| Stable callbacks | useCallback |
|
||||||
|
|
||||||
|
### Optimization Order
|
||||||
|
|
||||||
|
1. Check if actually slow
|
||||||
|
2. Profile with DevTools
|
||||||
|
3. Identify bottleneck
|
||||||
|
4. Apply targeted fix
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Error Handling
|
||||||
|
|
||||||
|
### Error Boundary Usage
|
||||||
|
|
||||||
|
| Scope | Placement |
|
||||||
|
|-------|-----------|
|
||||||
|
| App-wide | Root level |
|
||||||
|
| Feature | Route/feature level |
|
||||||
|
| Component | Around risky component |
|
||||||
|
|
||||||
|
### Error Recovery
|
||||||
|
|
||||||
|
- Show fallback UI
|
||||||
|
- Log error
|
||||||
|
- Offer retry option
|
||||||
|
- Preserve user data
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. TypeScript Patterns
|
||||||
|
|
||||||
|
### Props Typing
|
||||||
|
|
||||||
|
| Pattern | Use |
|
||||||
|
|---------|-----|
|
||||||
|
| Interface | Component props |
|
||||||
|
| Type | Unions, complex |
|
||||||
|
| Generic | Reusable components |
|
||||||
|
|
||||||
|
### Common Types
|
||||||
|
|
||||||
|
| Need | Type |
|
||||||
|
|------|------|
|
||||||
|
| Children | ReactNode |
|
||||||
|
| Event handler | MouseEventHandler |
|
||||||
|
| Ref | RefObject<Element> |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Testing Principles
|
||||||
|
|
||||||
|
| Level | Focus |
|
||||||
|
|-------|-------|
|
||||||
|
| Unit | Pure functions, hooks |
|
||||||
|
| Integration | Component behavior |
|
||||||
|
| E2E | User flows |
|
||||||
|
|
||||||
|
### Test Priorities
|
||||||
|
|
||||||
|
- User-visible behavior
|
||||||
|
- Edge cases
|
||||||
|
- Error states
|
||||||
|
- Accessibility
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Anti-Patterns
|
||||||
|
|
||||||
|
| ❌ Don't | ✅ Do |
|
||||||
|
|----------|-------|
|
||||||
|
| Prop drilling deep | Use context |
|
||||||
|
| Giant components | Split smaller |
|
||||||
|
| useEffect for everything | Server components |
|
||||||
|
| Premature optimization | Profile first |
|
||||||
|
| Index as key | Stable unique ID |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> **Remember:** React is about composition. Build small, combine thoughtfully.
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
This skill is applicable to execute the workflow or actions described in the overview.
|
||||||
444
.agents/skills/react-state-management/SKILL.md
Normal file
444
.agents/skills/react-state-management/SKILL.md
Normal file
@ -0,0 +1,444 @@
|
|||||||
|
---
|
||||||
|
name: react-state-management
|
||||||
|
description: "Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions."
|
||||||
|
risk: unknown
|
||||||
|
source: community
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# React State Management
|
||||||
|
|
||||||
|
Comprehensive guide to modern React state management patterns, from local component state to global stores and server state synchronization.
|
||||||
|
|
||||||
|
## Do not use this skill when
|
||||||
|
|
||||||
|
- The task is unrelated to react state management
|
||||||
|
- You need a different domain or tool outside this scope
|
||||||
|
|
||||||
|
## Instructions
|
||||||
|
|
||||||
|
- Clarify goals, constraints, and required inputs.
|
||||||
|
- Apply relevant best practices and validate outcomes.
|
||||||
|
- Provide actionable steps and verification.
|
||||||
|
- If detailed examples are required, open `resources/implementation-playbook.md`.
|
||||||
|
|
||||||
|
## Use this skill when
|
||||||
|
|
||||||
|
- Setting up global state management in a React app
|
||||||
|
- Choosing between Redux Toolkit, Zustand, or Jotai
|
||||||
|
- Managing server state with React Query or SWR
|
||||||
|
- Implementing optimistic updates
|
||||||
|
- Debugging state-related issues
|
||||||
|
- Migrating from legacy Redux to modern patterns
|
||||||
|
|
||||||
|
## Core Concepts
|
||||||
|
|
||||||
|
### 1. State Categories
|
||||||
|
|
||||||
|
| Type | Description | Solutions |
|
||||||
|
|------|-------------|-----------|
|
||||||
|
| **Local State** | Component-specific, UI state | useState, useReducer |
|
||||||
|
| **Global State** | Shared across components | Redux Toolkit, Zustand, Jotai |
|
||||||
|
| **Server State** | Remote data, caching | React Query, SWR, RTK Query |
|
||||||
|
| **URL State** | Route parameters, search | React Router, nuqs |
|
||||||
|
| **Form State** | Input values, validation | React Hook Form, Formik |
|
||||||
|
|
||||||
|
### 2. Selection Criteria
|
||||||
|
|
||||||
|
```
|
||||||
|
Small app, simple state → Zustand or Jotai
|
||||||
|
Large app, complex state → Redux Toolkit
|
||||||
|
Heavy server interaction → React Query + light client state
|
||||||
|
Atomic/granular updates → Jotai
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Zustand (Simplest)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// store/useStore.ts
|
||||||
|
import { create } from 'zustand'
|
||||||
|
import { devtools, persist } from 'zustand/middleware'
|
||||||
|
|
||||||
|
interface AppState {
|
||||||
|
user: User | null
|
||||||
|
theme: 'light' | 'dark'
|
||||||
|
setUser: (user: User | null) => void
|
||||||
|
toggleTheme: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useStore = create<AppState>()(
|
||||||
|
devtools(
|
||||||
|
persist(
|
||||||
|
(set) => ({
|
||||||
|
user: null,
|
||||||
|
theme: 'light',
|
||||||
|
setUser: (user) => set({ user }),
|
||||||
|
toggleTheme: () => set((state) => ({
|
||||||
|
theme: state.theme === 'light' ? 'dark' : 'light'
|
||||||
|
})),
|
||||||
|
}),
|
||||||
|
{ name: 'app-storage' }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Usage in component
|
||||||
|
function Header() {
|
||||||
|
const { user, theme, toggleTheme } = useStore()
|
||||||
|
return (
|
||||||
|
<header className={theme}>
|
||||||
|
{user?.name}
|
||||||
|
<button onClick={toggleTheme}>Toggle Theme</button>
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Patterns
|
||||||
|
|
||||||
|
### Pattern 1: Redux Toolkit with TypeScript
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// store/index.ts
|
||||||
|
import { configureStore } from '@reduxjs/toolkit'
|
||||||
|
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
|
||||||
|
import userReducer from './slices/userSlice'
|
||||||
|
import cartReducer from './slices/cartSlice'
|
||||||
|
|
||||||
|
export const store = configureStore({
|
||||||
|
reducer: {
|
||||||
|
user: userReducer,
|
||||||
|
cart: cartReducer,
|
||||||
|
},
|
||||||
|
middleware: (getDefaultMiddleware) =>
|
||||||
|
getDefaultMiddleware({
|
||||||
|
serializableCheck: {
|
||||||
|
ignoredActions: ['persist/PERSIST'],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type RootState = ReturnType<typeof store.getState>
|
||||||
|
export type AppDispatch = typeof store.dispatch
|
||||||
|
|
||||||
|
// Typed hooks
|
||||||
|
export const useAppDispatch: () => AppDispatch = useDispatch
|
||||||
|
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// store/slices/userSlice.ts
|
||||||
|
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserState {
|
||||||
|
current: User | null
|
||||||
|
status: 'idle' | 'loading' | 'succeeded' | 'failed'
|
||||||
|
error: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialState: UserState = {
|
||||||
|
current: null,
|
||||||
|
status: 'idle',
|
||||||
|
error: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fetchUser = createAsyncThunk(
|
||||||
|
'user/fetchUser',
|
||||||
|
async (userId: string, { rejectWithValue }) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/users/${userId}`)
|
||||||
|
if (!response.ok) throw new Error('Failed to fetch user')
|
||||||
|
return await response.json()
|
||||||
|
} catch (error) {
|
||||||
|
return rejectWithValue((error as Error).message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const userSlice = createSlice({
|
||||||
|
name: 'user',
|
||||||
|
initialState,
|
||||||
|
reducers: {
|
||||||
|
setUser: (state, action: PayloadAction<User>) => {
|
||||||
|
state.current = action.payload
|
||||||
|
state.status = 'succeeded'
|
||||||
|
},
|
||||||
|
clearUser: (state) => {
|
||||||
|
state.current = null
|
||||||
|
state.status = 'idle'
|
||||||
|
},
|
||||||
|
},
|
||||||
|
extraReducers: (builder) => {
|
||||||
|
builder
|
||||||
|
.addCase(fetchUser.pending, (state) => {
|
||||||
|
state.status = 'loading'
|
||||||
|
state.error = null
|
||||||
|
})
|
||||||
|
.addCase(fetchUser.fulfilled, (state, action) => {
|
||||||
|
state.status = 'succeeded'
|
||||||
|
state.current = action.payload
|
||||||
|
})
|
||||||
|
.addCase(fetchUser.rejected, (state, action) => {
|
||||||
|
state.status = 'failed'
|
||||||
|
state.error = action.payload as string
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const { setUser, clearUser } = userSlice.actions
|
||||||
|
export default userSlice.reducer
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 2: Zustand with Slices (Scalable)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// store/slices/createUserSlice.ts
|
||||||
|
import { StateCreator } from 'zustand'
|
||||||
|
|
||||||
|
export interface UserSlice {
|
||||||
|
user: User | null
|
||||||
|
isAuthenticated: boolean
|
||||||
|
login: (credentials: Credentials) => Promise<void>
|
||||||
|
logout: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createUserSlice: StateCreator<
|
||||||
|
UserSlice & CartSlice, // Combined store type
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
UserSlice
|
||||||
|
> = (set, get) => ({
|
||||||
|
user: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
login: async (credentials) => {
|
||||||
|
const user = await authApi.login(credentials)
|
||||||
|
set({ user, isAuthenticated: true })
|
||||||
|
},
|
||||||
|
logout: () => {
|
||||||
|
set({ user: null, isAuthenticated: false })
|
||||||
|
// Can access other slices
|
||||||
|
// get().clearCart()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// store/index.ts
|
||||||
|
import { create } from 'zustand'
|
||||||
|
import { createUserSlice, UserSlice } from './slices/createUserSlice'
|
||||||
|
import { createCartSlice, CartSlice } from './slices/createCartSlice'
|
||||||
|
|
||||||
|
type StoreState = UserSlice & CartSlice
|
||||||
|
|
||||||
|
export const useStore = create<StoreState>()((...args) => ({
|
||||||
|
...createUserSlice(...args),
|
||||||
|
...createCartSlice(...args),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Selective subscriptions (prevents unnecessary re-renders)
|
||||||
|
export const useUser = () => useStore((state) => state.user)
|
||||||
|
export const useCart = () => useStore((state) => state.cart)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 3: Jotai for Atomic State
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// atoms/userAtoms.ts
|
||||||
|
import { atom } from 'jotai'
|
||||||
|
import { atomWithStorage } from 'jotai/utils'
|
||||||
|
|
||||||
|
// Basic atom
|
||||||
|
export const userAtom = atom<User | null>(null)
|
||||||
|
|
||||||
|
// Derived atom (computed)
|
||||||
|
export const isAuthenticatedAtom = atom((get) => get(userAtom) !== null)
|
||||||
|
|
||||||
|
// Atom with localStorage persistence
|
||||||
|
export const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light')
|
||||||
|
|
||||||
|
// Async atom
|
||||||
|
export const userProfileAtom = atom(async (get) => {
|
||||||
|
const user = get(userAtom)
|
||||||
|
if (!user) return null
|
||||||
|
const response = await fetch(`/api/users/${user.id}/profile`)
|
||||||
|
return response.json()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Write-only atom (action)
|
||||||
|
export const logoutAtom = atom(null, (get, set) => {
|
||||||
|
set(userAtom, null)
|
||||||
|
set(cartAtom, [])
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
})
|
||||||
|
|
||||||
|
// Usage
|
||||||
|
function Profile() {
|
||||||
|
const [user] = useAtom(userAtom)
|
||||||
|
const [, logout] = useAtom(logoutAtom)
|
||||||
|
const [profile] = useAtom(userProfileAtom) // Suspense-enabled
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<Skeleton />}>
|
||||||
|
<ProfileContent profile={profile} onLogout={logout} />
|
||||||
|
</Suspense>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 4: React Query for Server State
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// hooks/useUsers.ts
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
// Query keys factory
|
||||||
|
export const userKeys = {
|
||||||
|
all: ['users'] as const,
|
||||||
|
lists: () => [...userKeys.all, 'list'] as const,
|
||||||
|
list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,
|
||||||
|
details: () => [...userKeys.all, 'detail'] as const,
|
||||||
|
detail: (id: string) => [...userKeys.details(), id] as const,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch hook
|
||||||
|
export function useUsers(filters: UserFilters) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: userKeys.list(filters),
|
||||||
|
queryFn: () => fetchUsers(filters),
|
||||||
|
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||||
|
gcTime: 30 * 60 * 1000, // 30 minutes (formerly cacheTime)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single user hook
|
||||||
|
export function useUser(id: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: userKeys.detail(id),
|
||||||
|
queryFn: () => fetchUser(id),
|
||||||
|
enabled: !!id, // Don't fetch if no id
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mutation with optimistic update
|
||||||
|
export function useUpdateUser() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: updateUser,
|
||||||
|
onMutate: async (newUser) => {
|
||||||
|
// Cancel outgoing refetches
|
||||||
|
await queryClient.cancelQueries({ queryKey: userKeys.detail(newUser.id) })
|
||||||
|
|
||||||
|
// Snapshot previous value
|
||||||
|
const previousUser = queryClient.getQueryData(userKeys.detail(newUser.id))
|
||||||
|
|
||||||
|
// Optimistically update
|
||||||
|
queryClient.setQueryData(userKeys.detail(newUser.id), newUser)
|
||||||
|
|
||||||
|
return { previousUser }
|
||||||
|
},
|
||||||
|
onError: (err, newUser, context) => {
|
||||||
|
// Rollback on error
|
||||||
|
queryClient.setQueryData(
|
||||||
|
userKeys.detail(newUser.id),
|
||||||
|
context?.previousUser
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onSettled: (data, error, variables) => {
|
||||||
|
// Refetch after mutation
|
||||||
|
queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 5: Combining Client + Server State
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Zustand for client state
|
||||||
|
const useUIStore = create<UIState>((set) => ({
|
||||||
|
sidebarOpen: true,
|
||||||
|
modal: null,
|
||||||
|
toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
|
||||||
|
openModal: (modal) => set({ modal }),
|
||||||
|
closeModal: () => set({ modal: null }),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// React Query for server state
|
||||||
|
function Dashboard() {
|
||||||
|
const { sidebarOpen, toggleSidebar } = useUIStore()
|
||||||
|
const { data: users, isLoading } = useUsers({ active: true })
|
||||||
|
const { data: stats } = useStats()
|
||||||
|
|
||||||
|
if (isLoading) return <DashboardSkeleton />
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={sidebarOpen ? 'with-sidebar' : ''}>
|
||||||
|
<Sidebar open={sidebarOpen} onToggle={toggleSidebar} />
|
||||||
|
<main>
|
||||||
|
<StatsCards stats={stats} />
|
||||||
|
<UserTable users={users} />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Do's
|
||||||
|
- **Colocate state** - Keep state as close to where it's used as possible
|
||||||
|
- **Use selectors** - Prevent unnecessary re-renders with selective subscriptions
|
||||||
|
- **Normalize data** - Flatten nested structures for easier updates
|
||||||
|
- **Type everything** - Full TypeScript coverage prevents runtime errors
|
||||||
|
- **Separate concerns** - Server state (React Query) vs client state (Zustand)
|
||||||
|
|
||||||
|
### Don'ts
|
||||||
|
- **Don't over-globalize** - Not everything needs to be in global state
|
||||||
|
- **Don't duplicate server state** - Let React Query manage it
|
||||||
|
- **Don't mutate directly** - Always use immutable updates
|
||||||
|
- **Don't store derived data** - Compute it instead
|
||||||
|
- **Don't mix paradigms** - Pick one primary solution per category
|
||||||
|
|
||||||
|
## Migration Guides
|
||||||
|
|
||||||
|
### From Legacy Redux to RTK
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Before (legacy Redux)
|
||||||
|
const ADD_TODO = 'ADD_TODO'
|
||||||
|
const addTodo = (text) => ({ type: ADD_TODO, payload: text })
|
||||||
|
function todosReducer(state = [], action) {
|
||||||
|
switch (action.type) {
|
||||||
|
case ADD_TODO:
|
||||||
|
return [...state, { text: action.payload, completed: false }]
|
||||||
|
default:
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// After (Redux Toolkit)
|
||||||
|
const todosSlice = createSlice({
|
||||||
|
name: 'todos',
|
||||||
|
initialState: [],
|
||||||
|
reducers: {
|
||||||
|
addTodo: (state, action: PayloadAction<string>) => {
|
||||||
|
// Immer allows "mutations"
|
||||||
|
state.push({ text: action.payload, completed: false })
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [Redux Toolkit Documentation](https://redux-toolkit.js.org/)
|
||||||
|
- [Zustand GitHub](https://github.com/pmndrs/zustand)
|
||||||
|
- [Jotai Documentation](https://jotai.org/)
|
||||||
|
- [TanStack Query](https://tanstack.com/query)
|
||||||
295
.agents/skills/react-ui-patterns/SKILL.md
Normal file
295
.agents/skills/react-ui-patterns/SKILL.md
Normal file
@ -0,0 +1,295 @@
|
|||||||
|
---
|
||||||
|
name: react-ui-patterns
|
||||||
|
description: "Modern React UI patterns for loading states, error handling, and data fetching. Use when building UI components, handling async data, or managing UI states."
|
||||||
|
risk: unknown
|
||||||
|
source: community
|
||||||
|
date_added: "2026-02-27"
|
||||||
|
---
|
||||||
|
|
||||||
|
# React UI Patterns
|
||||||
|
|
||||||
|
## Core Principles
|
||||||
|
|
||||||
|
1. **Never show stale UI** - Loading spinners only when actually loading
|
||||||
|
2. **Always surface errors** - Users must know when something fails
|
||||||
|
3. **Optimistic updates** - Make the UI feel instant
|
||||||
|
4. **Progressive disclosure** - Show content as it becomes available
|
||||||
|
5. **Graceful degradation** - Partial data is better than no data
|
||||||
|
|
||||||
|
## Loading State Patterns
|
||||||
|
|
||||||
|
### The Golden Rule
|
||||||
|
|
||||||
|
**Show loading indicator ONLY when there's no data to display.**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// CORRECT - Only show loading when no data exists
|
||||||
|
const { data, loading, error } = useGetItemsQuery();
|
||||||
|
|
||||||
|
if (error) return <ErrorState error={error} onRetry={refetch} />;
|
||||||
|
if (loading && !data) return <LoadingState />;
|
||||||
|
if (!data?.items.length) return <EmptyState />;
|
||||||
|
|
||||||
|
return <ItemList items={data.items} />;
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// WRONG - Shows spinner even when we have cached data
|
||||||
|
if (loading) return <LoadingState />; // Flashes on refetch!
|
||||||
|
```
|
||||||
|
|
||||||
|
### Loading State Decision Tree
|
||||||
|
|
||||||
|
```
|
||||||
|
Is there an error?
|
||||||
|
→ Yes: Show error state with retry option
|
||||||
|
→ No: Continue
|
||||||
|
|
||||||
|
Is it loading AND we have no data?
|
||||||
|
→ Yes: Show loading indicator (spinner/skeleton)
|
||||||
|
→ No: Continue
|
||||||
|
|
||||||
|
Do we have data?
|
||||||
|
→ Yes, with items: Show the data
|
||||||
|
→ Yes, but empty: Show empty state
|
||||||
|
→ No: Show loading (fallback)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Skeleton vs Spinner
|
||||||
|
|
||||||
|
| Use Skeleton When | Use Spinner When |
|
||||||
|
|-------------------|------------------|
|
||||||
|
| Known content shape | Unknown content shape |
|
||||||
|
| List/card layouts | Modal actions |
|
||||||
|
| Initial page load | Button submissions |
|
||||||
|
| Content placeholders | Inline operations |
|
||||||
|
|
||||||
|
## Error Handling Patterns
|
||||||
|
|
||||||
|
### The Error Handling Hierarchy
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Inline error (field-level) → Form validation errors
|
||||||
|
2. Toast notification → Recoverable errors, user can retry
|
||||||
|
3. Error banner → Page-level errors, data still partially usable
|
||||||
|
4. Full error screen → Unrecoverable, needs user action
|
||||||
|
```
|
||||||
|
|
||||||
|
### Always Show Errors
|
||||||
|
|
||||||
|
**CRITICAL: Never swallow errors silently.**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// CORRECT - Error always surfaced to user
|
||||||
|
const [createItem, { loading }] = useCreateItemMutation({
|
||||||
|
onCompleted: () => {
|
||||||
|
toast.success({ title: 'Item created' });
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error('createItem failed:', error);
|
||||||
|
toast.error({ title: 'Failed to create item' });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// WRONG - Error silently caught, user has no idea
|
||||||
|
const [createItem] = useCreateItemMutation({
|
||||||
|
onError: (error) => {
|
||||||
|
console.error(error); // User sees nothing!
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error State Component Pattern
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface ErrorStateProps {
|
||||||
|
error: Error;
|
||||||
|
onRetry?: () => void;
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ErrorState = ({ error, onRetry, title }: ErrorStateProps) => (
|
||||||
|
<div className="error-state">
|
||||||
|
<Icon name="exclamation-circle" />
|
||||||
|
<h3>{title ?? 'Something went wrong'}</h3>
|
||||||
|
<p>{error.message}</p>
|
||||||
|
{onRetry && (
|
||||||
|
<Button onClick={onRetry}>Try Again</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Button State Patterns
|
||||||
|
|
||||||
|
### Button Loading State
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
isLoading={isSubmitting}
|
||||||
|
disabled={!isValid || isSubmitting}
|
||||||
|
>
|
||||||
|
Submit
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Disable During Operations
|
||||||
|
|
||||||
|
**CRITICAL: Always disable triggers during async operations.**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// CORRECT - Button disabled while loading
|
||||||
|
<Button
|
||||||
|
disabled={isSubmitting}
|
||||||
|
isLoading={isSubmitting}
|
||||||
|
onClick={handleSubmit}
|
||||||
|
>
|
||||||
|
Submit
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
// WRONG - User can tap multiple times
|
||||||
|
<Button onClick={handleSubmit}>
|
||||||
|
{isSubmitting ? 'Submitting...' : 'Submit'}
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Empty States
|
||||||
|
|
||||||
|
### Empty State Requirements
|
||||||
|
|
||||||
|
Every list/collection MUST have an empty state:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// WRONG - No empty state
|
||||||
|
return <FlatList data={items} />;
|
||||||
|
|
||||||
|
// CORRECT - Explicit empty state
|
||||||
|
return (
|
||||||
|
<FlatList
|
||||||
|
data={items}
|
||||||
|
ListEmptyComponent={<EmptyState />}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Contextual Empty States
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Search with no results
|
||||||
|
<EmptyState
|
||||||
|
icon="search"
|
||||||
|
title="No results found"
|
||||||
|
description="Try different search terms"
|
||||||
|
/>
|
||||||
|
|
||||||
|
// List with no items yet
|
||||||
|
<EmptyState
|
||||||
|
icon="plus-circle"
|
||||||
|
title="No items yet"
|
||||||
|
description="Create your first item"
|
||||||
|
action={{ label: 'Create Item', onClick: handleCreate }}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Form Submission Pattern
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const MyForm = () => {
|
||||||
|
const [submit, { loading }] = useSubmitMutation({
|
||||||
|
onCompleted: handleSuccess,
|
||||||
|
onError: handleError,
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!isValid) {
|
||||||
|
toast.error({ title: 'Please fix errors' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await submit({ variables: { input: values } });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form>
|
||||||
|
<Input
|
||||||
|
value={values.name}
|
||||||
|
onChange={handleChange('name')}
|
||||||
|
error={touched.name ? errors.name : undefined}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={!isValid || loading}
|
||||||
|
isLoading={loading}
|
||||||
|
>
|
||||||
|
Submit
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
|
||||||
|
### Loading States
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// WRONG - Spinner when data exists (causes flash)
|
||||||
|
if (loading) return <Spinner />;
|
||||||
|
|
||||||
|
// CORRECT - Only show loading without data
|
||||||
|
if (loading && !data) return <Spinner />;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// WRONG - Error swallowed
|
||||||
|
try {
|
||||||
|
await mutation();
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e); // User has no idea!
|
||||||
|
}
|
||||||
|
|
||||||
|
// CORRECT - Error surfaced
|
||||||
|
onError: (error) => {
|
||||||
|
console.error('operation failed:', error);
|
||||||
|
toast.error({ title: 'Operation failed' });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Button States
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// WRONG - Button not disabled during submission
|
||||||
|
<Button onClick={submit}>Submit</Button>
|
||||||
|
|
||||||
|
// CORRECT - Disabled and shows loading
|
||||||
|
<Button onClick={submit} disabled={loading} isLoading={loading}>
|
||||||
|
Submit
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
Before completing any UI component:
|
||||||
|
|
||||||
|
**UI States:**
|
||||||
|
- [ ] Error state handled and shown to user
|
||||||
|
- [ ] Loading state shown only when no data exists
|
||||||
|
- [ ] Empty state provided for collections
|
||||||
|
- [ ] Buttons disabled during async operations
|
||||||
|
- [ ] Buttons show loading indicator when appropriate
|
||||||
|
|
||||||
|
**Data & Mutations:**
|
||||||
|
- [ ] Mutations have onError handler
|
||||||
|
- [ ] All user actions have feedback (toast/visual)
|
||||||
|
|
||||||
|
## Integration with Other Skills
|
||||||
|
|
||||||
|
- **graphql-schema**: Use mutation patterns with proper error handling
|
||||||
|
- **testing-patterns**: Test all UI states (loading, error, empty, success)
|
||||||
|
- **formik-patterns**: Apply form submission patterns
|
||||||
|
|
||||||
|
## When to Use
|
||||||
|
This skill is applicable to execute the workflow or actions described in the overview.
|
||||||
63
.agents/skills/responsive-mobile-first/SKILL.md
Normal file
63
.agents/skills/responsive-mobile-first/SKILL.md
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
---
|
||||||
|
name: responsive-mobile-first
|
||||||
|
description: >-
|
||||||
|
Enforces mobile-first responsive architecture and viewport stability guidelines for all frontend components,
|
||||||
|
ensuring seamless adaptivity from mobile screens (320px) to ultrawide displays (1440px+). Use when building,
|
||||||
|
styling, or refactoring layouts, sidebars, modals, tables, or chat views.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Responsive Mobile-First Skill
|
||||||
|
|
||||||
|
## Core Principles
|
||||||
|
|
||||||
|
1. **Mobile-First CSS**:
|
||||||
|
- Write base CSS/Tailwind classes for mobile (`320px` - `480px`) first without prefixes.
|
||||||
|
- Expand layout and spacing progressively with breakpoint prefixes:
|
||||||
|
- `sm:` (640px)
|
||||||
|
- `md:` (768px) - Tablet portrait / collapsed sidebars transition
|
||||||
|
- `lg:` (1024px) - Desktop / expanded multi-column views
|
||||||
|
- `xl:` (1280px) and `2xl:` (1536px) - Ultrawide / max-width containers
|
||||||
|
- Never write desktop styles as base and attempt to override them with negative mobile queries.
|
||||||
|
|
||||||
|
2. **Dynamic Viewport Height**:
|
||||||
|
- Do NOT use rigid `100vh` for full-screen application shells (causes overflow and clipping due to dynamic URL bars in iOS Safari and Chrome Android).
|
||||||
|
- Use dynamic viewport height: `h-[100dvh]` or `min-h-[100dvh]` (fallback: `h-screen`).
|
||||||
|
- Use `h-[calc(100dvh-Xpx)]` for internal scrollable flex containers.
|
||||||
|
|
||||||
|
3. **Safe Area Insets**:
|
||||||
|
- For bottom bars, floating action buttons, and top navigation bars, support mobile notches and home indicators:
|
||||||
|
```css
|
||||||
|
padding-top: max(1rem, env(safe-area-inset-top));
|
||||||
|
padding-bottom: max(1rem, env(safe-area-inset-bottom));
|
||||||
|
padding-left: max(1rem, env(safe-area-inset-left));
|
||||||
|
padding-right: max(1rem, env(safe-area-inset-right));
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Off-Canvas Navigation & Sidebars**:
|
||||||
|
- On screens `< 768px` (`max-md:`), sidebars must:
|
||||||
|
- Render as an off-canvas drawer (`fixed inset-y-0 left-0 z-50` or `right-0`).
|
||||||
|
- Include an animated backdrop overlay (`fixed inset-0 bg-black/60 backdrop-blur-sm z-40`).
|
||||||
|
- Smoothly slide in and out (`transition-transform duration-300`).
|
||||||
|
- Close automatically on backdrop click, `Escape` key, or route navigation.
|
||||||
|
- Preserve a floating hamburger trigger visible only on mobile (`md:hidden fixed top-3 left-3 z-30`).
|
||||||
|
- On desktop (`md:` and above):
|
||||||
|
- Mount as structural flex children (`shrink-0 relative`).
|
||||||
|
|
||||||
|
5. **Adaptive Modals and Dialogs**:
|
||||||
|
- Desktop (`md:`): Centered floating dialog (`max-w-lg mx-auto rounded-2xl`).
|
||||||
|
- Mobile: Bottom-sheet behavior (`fixed inset-x-0 bottom-0 rounded-t-2xl max-h-[90dvh] overflow-y-auto`).
|
||||||
|
|
||||||
|
6. **Flexible Data & Grid Layouts**:
|
||||||
|
- Tables must be wrapped with horizontal scroll containers:
|
||||||
|
```jsx
|
||||||
|
<div className="w-full overflow-x-auto -mx-4 px-4 sm:mx-0 sm:px-0">
|
||||||
|
```
|
||||||
|
- Cards and tile lists must use auto-fit CSS grids instead of fixed column counts:
|
||||||
|
```css
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr));
|
||||||
|
```
|
||||||
|
|
||||||
|
7. **Touch Targets & Typography**:
|
||||||
|
- Minimum interactive touch target size: `44px x 44px` (or `min-h-[44px] min-w-[44px]`).
|
||||||
|
- Inputs must have font-size `>= 16px` on mobile to prevent automatic browser zoom in iOS Safari.
|
||||||
|
- Text truncation: Use `truncate` or `line-clamp-2` with full tooltips or expandable views.
|
||||||
219
.agents/skills/scrum-multi-agent-orchestration/SKILL.md
Normal file
219
.agents/skills/scrum-multi-agent-orchestration/SKILL.md
Normal file
@ -0,0 +1,219 @@
|
|||||||
|
---
|
||||||
|
name: scrum-multi-agent-orchestration
|
||||||
|
description: Multi-agent orchestration framework implementing Scrum agile methodology for software development. Coordinates specialized agent roles (Product Owner, Scrum Master, Tech Lead, Frontend, Backend, QA, and Code Reviewer) using hierarchical, sequential, and parallel workflows, contract-first handoffs, and Antigravity subagents.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Scrum Multi-Agent Orchestration
|
||||||
|
|
||||||
|
A specialized multi-agent engineering framework that applies **Scrum Agile Methodology** to coordinated AI agent teams. Each agent is assigned a dedicated software development role with clear boundaries, responsibilities, and communication protocols.
|
||||||
|
|
||||||
|
This skill builds upon the foundational multi-agent patterns from [`qodex-ai/ai-agent-skills`](https://github.com/qodex-ai/ai-agent-skills/tree/main/skills/multi-agent-orchestration) (MessageBroker, SharedMemory, WorkflowManager, and Benchmarking) and connects them directly with Antigravity's subagent capabilities (`define_subagent`, `invoke_subagent`, and `send_message`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Scrum Multi-Agent Roles
|
||||||
|
|
||||||
|
In this methodology, the master orchestrator decomposes user requests into sprints and delegates execution across 7 specialized roles:
|
||||||
|
|
||||||
|
```
|
||||||
|
[ User / Stakeholder ]
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ Product Owner (PO) ]
|
||||||
|
(Stories & Acceptance Criteria)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ Scrum Master / Orchestrator ]
|
||||||
|
(Sprint Planning & Task DAG)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ Tech Lead / Architect ]
|
||||||
|
(API Contracts & System Design)
|
||||||
|
│
|
||||||
|
┌──────────────┴──────────────┐
|
||||||
|
▼ ▼
|
||||||
|
[ Backend Developer ] [ Frontend Developer ]
|
||||||
|
(APIs, Logic, Data models) (UI, UX, Components, A11y)
|
||||||
|
└──────────────┬──────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ QA / Test Engineer ]
|
||||||
|
(Automated Tests & AC Verif.)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ Code Reviewer & Auditor ]
|
||||||
|
(Security, Clean Code, DoD)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Role Breakdown
|
||||||
|
|
||||||
|
| Role | Responsibility | Tools Required | Output Deliverable |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Product Owner (PO)** | Clarifies user requests, writes User Stories with Gherkin Acceptance Criteria (`Given/When/Then`), prioritizes backlog. | Codebase inspection, Read files | User Story specification & AC checklist |
|
||||||
|
| **Scrum Master (Orchestrator)** | Builds the execution DAG, handles dependency handoffs, unblocks agents, tracks sprint status. | Subagent tools, Messaging tools | Sprint Workflow Plan & Task assignments |
|
||||||
|
| **Tech Lead / Architect** | Designs data models, API schema contracts, interface specifications, and component hierarchies. | Read files, Codebase search | Contract specification (`contract.json` / TypeScript types) |
|
||||||
|
| **Backend Developer** | Implements backend routes, services, database migrations, and business logic adhering to the contract. | Write files, Edit files, Terminal | Tested API endpoints & backend logic |
|
||||||
|
| **Frontend Developer** | Builds responsive UI components, state management, and animations adhering to the design system. | Write files, Edit files, Terminal | Modern, accessible UI components |
|
||||||
|
| **QA / Test Engineer** | Writes unit and integration tests; runs automated test suites to verify all acceptance criteria. | Terminal, Read/Write files | Test report & coverage validation |
|
||||||
|
| **Code Reviewer** | Audits code for security (OWASP), accessibility (WCAG 2.1 AA), linting, and Definition of Done. | Read files, Codebase search | PR approval & DoD sign-off |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Orchestration Patterns Applied to Scrum
|
||||||
|
|
||||||
|
This framework combines the 4 key multi-agent patterns from `qodex-ai`:
|
||||||
|
|
||||||
|
### A. Hierarchical Pattern (Scrum Master Supervision)
|
||||||
|
The **Scrum Master** acts as the central coordinator, delegating tasks and listening to notifications without polling loops. When a subtask finishes, the orchestrator triggers the next dependent subagent.
|
||||||
|
|
||||||
|
### B. Sequential Pattern (Contract-First Flow)
|
||||||
|
Certain stages **must** execute sequentially:
|
||||||
|
1. Product Owner defines requirements.
|
||||||
|
2. Tech Lead publishes the contract specification.
|
||||||
|
3. Developers write code.
|
||||||
|
4. QA tests the code.
|
||||||
|
5. Reviewer signs off.
|
||||||
|
|
||||||
|
### C. Parallel Pattern (Concurrent Development)
|
||||||
|
Once the Tech Lead defines the API contract in shared memory:
|
||||||
|
- **Backend Developer** implements the server endpoints.
|
||||||
|
- **Frontend Developer** mocks or consumes the endpoints and builds the UI.
|
||||||
|
Both agents execute concurrently without blocking each other.
|
||||||
|
|
||||||
|
### D. Consensus & Verification Pattern (Definition of Done)
|
||||||
|
Before marking a story as `DONE`:
|
||||||
|
- The QA Engineer checks test passes.
|
||||||
|
- The Code Reviewer verifies security and coding standards.
|
||||||
|
- The Product Owner confirms all acceptance criteria are met.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Implementation with Antigravity Subagents
|
||||||
|
|
||||||
|
In Antigravity, subagents are defined using `define_subagent` and executed using `invoke_subagent`.
|
||||||
|
|
||||||
|
### 1. Defining Roles Dynamically
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Tech Lead / Architect (Read-only tools)
|
||||||
|
define_subagent(
|
||||||
|
Name="scrum-tech-lead",
|
||||||
|
Role="Software Architect",
|
||||||
|
Description="Designs API contracts, data schemas, and component architecture.",
|
||||||
|
EnableWriteTools=False,
|
||||||
|
EnableSubagentTools=False,
|
||||||
|
EnableMCPTools=False,
|
||||||
|
SystemPrompt="You are the Tech Lead. Generate precise TypeScript interfaces and API specs before coding starts."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Backend Developer (Write & command tools)
|
||||||
|
define_subagent(
|
||||||
|
Name="scrum-backend-dev",
|
||||||
|
Role="Backend Developer",
|
||||||
|
Description="Implements backend endpoints, business logic, and database models.",
|
||||||
|
EnableWriteTools=True,
|
||||||
|
EnableSubagentTools=False,
|
||||||
|
EnableMCPTools=False,
|
||||||
|
SystemPrompt="You are the Backend Developer. Implement endpoints strictly adhering to the Tech Lead contract."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Frontend Developer (Write & command tools)
|
||||||
|
define_subagent(
|
||||||
|
Name="scrum-frontend-dev",
|
||||||
|
Role="Frontend Developer",
|
||||||
|
Description="Implements UI components, styling, animations, and state management.",
|
||||||
|
EnableWriteTools=True,
|
||||||
|
EnableSubagentTools=False,
|
||||||
|
EnableMCPTools=False,
|
||||||
|
SystemPrompt="You are the Frontend Developer. Build mobile-first, accessible, responsive components matching design standards."
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Invoking Parallel Subagents
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Launch Backend in parallel
|
||||||
|
invoke_subagent(
|
||||||
|
TypeName="scrum-backend-dev",
|
||||||
|
Role="Backend Developer",
|
||||||
|
Prompt="Implement the login endpoint in src/api/auth.py using the contract at contracts/auth_contract.json",
|
||||||
|
Workspace="inherit"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Launch Frontend in parallel
|
||||||
|
invoke_subagent(
|
||||||
|
TypeName="scrum-frontend-dev",
|
||||||
|
Role="Frontend Developer",
|
||||||
|
Prompt="Implement the LoginForm component in src/components/LoginForm.tsx using the contract at contracts/auth_contract.json",
|
||||||
|
Workspace="inherit"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Asynchronous Messaging & Handoff
|
||||||
|
|
||||||
|
Agents communicate using Antigravity's `send_message` or the internal `MessageBroker` and `SharedMemory`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from agent_communication import MessageBroker, Message, MessageType, SharedMemory
|
||||||
|
|
||||||
|
memory = SharedMemory()
|
||||||
|
memory.write("api_contract", {
|
||||||
|
"endpoint": "/api/v1/auth/login",
|
||||||
|
"method": "POST",
|
||||||
|
"payload": {"username": "string", "password": "string"}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. End-to-End Sprint Workflow
|
||||||
|
|
||||||
|
### Step 1: Sprint Planning & User Story Creation
|
||||||
|
1. Product Owner receives user requirement.
|
||||||
|
2. Generates User Story with Gherkin acceptance criteria:
|
||||||
|
- `Given` preconditions
|
||||||
|
- `When` user action
|
||||||
|
- `Then` expected result
|
||||||
|
3. Estimates story points.
|
||||||
|
|
||||||
|
### Step 2: Architecture & Contract Specification
|
||||||
|
1. Tech Lead inspects the existing codebase.
|
||||||
|
2. Creates contract files (e.g., OpenAPI schemas or TypeScript `.d.ts` types).
|
||||||
|
3. Posts contracts to shared workspace or artifact.
|
||||||
|
|
||||||
|
### Step 3: Concurrent Sprint Execution
|
||||||
|
1. Scrum Master triggers **Frontend** and **Backend** agents simultaneously.
|
||||||
|
2. Both agents write code, run linters, and verify against the shared contract.
|
||||||
|
|
||||||
|
### Step 4: QA & Automated Testing
|
||||||
|
1. QA Engineer writes integration tests that simulate user workflows.
|
||||||
|
2. Executes tests in terminal (`npm test`, `pytest`, etc.).
|
||||||
|
3. Verifies each acceptance criterion. If a test fails, sends feedback message to the responsible dev agent.
|
||||||
|
|
||||||
|
### Step 5: Code Review & Definition of Done (DoD)
|
||||||
|
The Code Reviewer verifies:
|
||||||
|
- [ ] All acceptance criteria pass.
|
||||||
|
- [ ] No regression or broken builds.
|
||||||
|
- [ ] Code follows project style & architectural conventions.
|
||||||
|
- [ ] Accessibility (WCAG 2.1 AA) and security requirements met.
|
||||||
|
- [ ] Story status transitions to `DONE`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Scripts and Utilities
|
||||||
|
|
||||||
|
The skill includes the utilities from `qodex-ai` plus the Scrum orchestrator:
|
||||||
|
|
||||||
|
- [`scripts/scrum_orchestrator.py`](scripts/scrum_orchestrator.py): Scrum team state manager, persona definitions, and DAG workflow planner.
|
||||||
|
- [`scripts/agent_communication.py`](scripts/agent_communication.py): `MessageBroker`, `SharedMemory`, and `Message` passing protocol.
|
||||||
|
- [`scripts/workflow_management.py`](scripts/workflow_management.py): `WorkflowExecutor`, `Task`, and DAG dependency scheduler.
|
||||||
|
- [`scripts/benchmarking.py`](scripts/benchmarking.py): Metric tracking for agent performance, token cost, and execution duration.
|
||||||
|
- [`examples/scrum_feature_sprint.py`](examples/scrum_feature_sprint.py): Runnable Python simulation of a full Scrum sprint.
|
||||||
|
- [`examples/orchestration_patterns.py`](examples/orchestration_patterns.py): Pattern templates for Sequential, Parallel, and Hierarchical agent teams.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Proactive Recommendations
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> When executing complex, multi-component features with this skill, recommend the user trigger the **/teamwork-preview** slash command to visualize agent roles and tasks dynamically in the chat interface.
|
||||||
@ -0,0 +1,362 @@
|
|||||||
|
"""
|
||||||
|
Framework-Specific Multi-Agent Implementations
|
||||||
|
|
||||||
|
Templates for CrewAI, AutoGen, LangGraph, and Swarm.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, List, Optional, Any
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CrewAITemplate:
|
||||||
|
"""Template for CrewAI implementation."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_financial_team() -> Dict[str, Any]:
|
||||||
|
"""Create CrewAI financial analysis team."""
|
||||||
|
return {
|
||||||
|
"agents": [
|
||||||
|
{
|
||||||
|
"name": "Market Analyst",
|
||||||
|
"role": "Market Research Specialist",
|
||||||
|
"goal": "Analyze market conditions and trends",
|
||||||
|
"backstory": "Expert market analyst with 10+ years experience",
|
||||||
|
"tools": ["market_data_api", "financial_news"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Financial Analyst",
|
||||||
|
"role": "Financial Analysis Specialist",
|
||||||
|
"goal": "Analyze company financial statements",
|
||||||
|
"backstory": "CFA with deep financial analysis expertise",
|
||||||
|
"tools": ["financial_statements", "ratio_calculator"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Risk Manager",
|
||||||
|
"role": "Risk Assessment Specialist",
|
||||||
|
"goal": "Assess investment risks and scenarios",
|
||||||
|
"backstory": "Risk management expert",
|
||||||
|
"tools": ["risk_models", "scenario_analysis"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Report Writer",
|
||||||
|
"role": "Report Generation Specialist",
|
||||||
|
"goal": "Synthesize findings into comprehensive report",
|
||||||
|
"backstory": "Professional technical writer",
|
||||||
|
"tools": ["document_generator"],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"agent": "Market Analyst",
|
||||||
|
"description": "Analyze market conditions for {company}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent": "Financial Analyst",
|
||||||
|
"description": "Analyze Q3 financial results for {company}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent": "Risk Manager",
|
||||||
|
"description": "Assess risks and create scenarios for {company}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent": "Report Writer",
|
||||||
|
"description": "Write comprehensive investment analysis report",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"process": "sequential",
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_legal_team() -> Dict[str, Any]:
|
||||||
|
"""Create CrewAI legal team."""
|
||||||
|
return {
|
||||||
|
"agents": [
|
||||||
|
{
|
||||||
|
"name": "Contract Analyzer",
|
||||||
|
"role": "Legal Contract Specialist",
|
||||||
|
"goal": "Analyze and review contract terms",
|
||||||
|
"backstory": "Senior contract attorney",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Precedent Researcher",
|
||||||
|
"role": "Legal Research Specialist",
|
||||||
|
"goal": "Research relevant case law and precedents",
|
||||||
|
"backstory": "Legal researcher specializing in case law",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Risk Assessor",
|
||||||
|
"role": "Legal Risk Specialist",
|
||||||
|
"goal": "Identify and assess legal risks",
|
||||||
|
"backstory": "Risk management expert in legal domain",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Document Drafter",
|
||||||
|
"role": "Legal Document Specialist",
|
||||||
|
"goal": "Draft legal documents and recommendations",
|
||||||
|
"backstory": "Legal document drafting expert",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"process": "sequential",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AutoGenTemplate:
|
||||||
|
"""Template for AutoGen implementation."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_group_chat_config() -> Dict[str, Any]:
|
||||||
|
"""Create AutoGen group chat configuration."""
|
||||||
|
return {
|
||||||
|
"agents": [
|
||||||
|
{
|
||||||
|
"name": "analyst",
|
||||||
|
"system_message": "You are a financial analyst. Provide analysis based on data.",
|
||||||
|
"llm_config": {"model": "gpt-4", "temperature": 0.7},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "researcher",
|
||||||
|
"system_message": "You are a market researcher. Research trends and competition.",
|
||||||
|
"llm_config": {"model": "gpt-4", "temperature": 0.7},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "critic",
|
||||||
|
"system_message": "You are a critical evaluator. Challenge assumptions and findings.",
|
||||||
|
"llm_config": {"model": "gpt-4", "temperature": 0.7},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"group_chat_config": {
|
||||||
|
"agents": ["analyst", "researcher", "critic"],
|
||||||
|
"max_round": 10,
|
||||||
|
"speaker_selection_method": "auto",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_hierarchical_structure() -> Dict[str, Any]:
|
||||||
|
"""Create hierarchical AutoGen structure."""
|
||||||
|
return {
|
||||||
|
"primary_agents": [
|
||||||
|
{
|
||||||
|
"name": "senior_analyst",
|
||||||
|
"role": "Senior analyst coordinating teams",
|
||||||
|
"subordinates": ["junior_analyst_1", "junior_analyst_2"],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"secondary_agents": [
|
||||||
|
{
|
||||||
|
"name": "junior_analyst_1",
|
||||||
|
"role": "Fundamental analysis specialist",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "junior_analyst_2",
|
||||||
|
"role": "Technical analysis specialist",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LangGraphTemplate:
|
||||||
|
"""Template for LangGraph workflow implementation."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_research_workflow() -> Dict[str, Any]:
|
||||||
|
"""Create LangGraph research workflow."""
|
||||||
|
return {
|
||||||
|
"name": "research_workflow",
|
||||||
|
"state_schema": {
|
||||||
|
"topic": str,
|
||||||
|
"research_findings": str,
|
||||||
|
"analysis": str,
|
||||||
|
"recommendations": str,
|
||||||
|
},
|
||||||
|
"nodes": [
|
||||||
|
{
|
||||||
|
"name": "researcher",
|
||||||
|
"agent": "research_agent",
|
||||||
|
"description": "Research the topic",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "analyst",
|
||||||
|
"agent": "analyst_agent",
|
||||||
|
"description": "Analyze research findings",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "critic",
|
||||||
|
"agent": "critic_agent",
|
||||||
|
"description": "Critique and improve",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "writer",
|
||||||
|
"agent": "writer_agent",
|
||||||
|
"description": "Write final report",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"edges": [
|
||||||
|
("researcher", "analyst"),
|
||||||
|
("analyst", "critic"),
|
||||||
|
("critic", "writer"),
|
||||||
|
],
|
||||||
|
"entry_point": "researcher",
|
||||||
|
"exit_point": "writer",
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_dynamic_workflow() -> Dict[str, Any]:
|
||||||
|
"""Create dynamic LangGraph workflow with conditions."""
|
||||||
|
return {
|
||||||
|
"name": "dynamic_workflow",
|
||||||
|
"nodes": [
|
||||||
|
{
|
||||||
|
"name": "start",
|
||||||
|
"type": "input",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "analyze",
|
||||||
|
"type": "agent",
|
||||||
|
"agent": "analyzer",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "quality_check",
|
||||||
|
"type": "decision",
|
||||||
|
"condition": "analyze_quality > threshold",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "refine",
|
||||||
|
"type": "agent",
|
||||||
|
"agent": "refiner",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "end",
|
||||||
|
"type": "output",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"conditional_edges": [
|
||||||
|
{
|
||||||
|
"source": "quality_check",
|
||||||
|
"true_target": "end",
|
||||||
|
"false_target": "refine",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SwarmTemplate:
|
||||||
|
"""Template for OpenAI Swarm implementation."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_customer_support_swarm() -> Dict[str, Any]:
|
||||||
|
"""Create customer support Swarm."""
|
||||||
|
return {
|
||||||
|
"agents": [
|
||||||
|
{
|
||||||
|
"name": "triage_agent",
|
||||||
|
"instructions": "Determine which specialist to route the customer to. "
|
||||||
|
"Ask clarifying questions if needed.",
|
||||||
|
"functions": [
|
||||||
|
"route_to_billing",
|
||||||
|
"route_to_technical",
|
||||||
|
"route_to_account",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "billing_specialist",
|
||||||
|
"instructions": "Handle all billing and payment related questions. "
|
||||||
|
"Can access billing records.",
|
||||||
|
"tools": ["billing_system", "payment_processor"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "technical_support",
|
||||||
|
"instructions": "Handle technical issues and troubleshooting. "
|
||||||
|
"Can access diagnostic tools.",
|
||||||
|
"tools": ["diagnostic_tools", "knowledge_base"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "account_specialist",
|
||||||
|
"instructions": "Handle account management and profile changes.",
|
||||||
|
"tools": ["account_system"],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"handoff_functions": {
|
||||||
|
"route_to_billing": "Transfer to billing specialist",
|
||||||
|
"route_to_technical": "Transfer to technical support",
|
||||||
|
"route_to_account": "Transfer to account specialist",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_sales_swarm() -> Dict[str, Any]:
|
||||||
|
"""Create sales team Swarm."""
|
||||||
|
return {
|
||||||
|
"agents": [
|
||||||
|
{
|
||||||
|
"name": "sales_router",
|
||||||
|
"instructions": "Route customer inquiries to appropriate sales agent",
|
||||||
|
"functions": ["route_to_enterprise", "route_to_smb"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "enterprise_sales",
|
||||||
|
"instructions": "Handle enterprise customer inquiries",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "smb_sales",
|
||||||
|
"instructions": "Handle small business inquiries",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class AgentCommunicationManager:
|
||||||
|
"""Manage communication patterns between agents."""
|
||||||
|
|
||||||
|
def __init__(self, agents: Dict[str, Any]):
|
||||||
|
"""Initialize communication manager."""
|
||||||
|
self.agents = agents
|
||||||
|
self.message_queue = []
|
||||||
|
|
||||||
|
def broadcast_message(self, sender: str, message: str, recipients: List[str]):
|
||||||
|
"""Broadcast message to multiple agents."""
|
||||||
|
for recipient in recipients:
|
||||||
|
self.message_queue.append({
|
||||||
|
"from": sender,
|
||||||
|
"to": recipient,
|
||||||
|
"message": message,
|
||||||
|
"type": "broadcast",
|
||||||
|
})
|
||||||
|
|
||||||
|
def direct_message(self, sender: str, recipient: str, message: str):
|
||||||
|
"""Send direct message between agents."""
|
||||||
|
self.message_queue.append({
|
||||||
|
"from": sender,
|
||||||
|
"to": recipient,
|
||||||
|
"message": message,
|
||||||
|
"type": "direct",
|
||||||
|
})
|
||||||
|
|
||||||
|
def publish_shared_state(self, state_key: str, value: Any):
|
||||||
|
"""Publish to shared state (tool-mediated communication)."""
|
||||||
|
self.message_queue.append({
|
||||||
|
"type": "shared_state",
|
||||||
|
"key": state_key,
|
||||||
|
"value": value,
|
||||||
|
})
|
||||||
|
|
||||||
|
def get_pending_messages(self, agent: str) -> List[Dict]:
|
||||||
|
"""Get messages for specific agent."""
|
||||||
|
return [msg for msg in self.message_queue if msg.get("to") == agent]
|
||||||
|
|
||||||
|
def process_message_queue(self) -> Dict[str, Any]:
|
||||||
|
"""Process and summarize message queue."""
|
||||||
|
direct_messages = [m for m in self.message_queue if m["type"] == "direct"]
|
||||||
|
broadcasts = [m for m in self.message_queue if m["type"] == "broadcast"]
|
||||||
|
shared_states = [m for m in self.message_queue if m["type"] == "shared_state"]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"direct_messages": len(direct_messages),
|
||||||
|
"broadcasts": len(broadcasts),
|
||||||
|
"shared_states": len(shared_states),
|
||||||
|
"total_messages": len(self.message_queue),
|
||||||
|
}
|
||||||
@ -0,0 +1,411 @@
|
|||||||
|
"""
|
||||||
|
Multi-Agent Orchestration Patterns
|
||||||
|
|
||||||
|
Implements sequential, parallel, hierarchical, and consensus orchestration.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
import asyncio
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
|
||||||
|
|
||||||
|
class Agent(ABC):
|
||||||
|
"""Base agent class."""
|
||||||
|
|
||||||
|
def __init__(self, name: str, role: str, goal: str):
|
||||||
|
"""Initialize agent."""
|
||||||
|
self.name = name
|
||||||
|
self.role = role
|
||||||
|
self.goal = goal
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def work(self, task: str) -> str:
|
||||||
|
"""Execute task."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def work_async(self, task: str) -> str:
|
||||||
|
"""Execute task asynchronously."""
|
||||||
|
return self.work(task)
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleAgent(Agent):
|
||||||
|
"""Simple agent implementation."""
|
||||||
|
|
||||||
|
def __init__(self, name: str, role: str, goal: str):
|
||||||
|
"""Initialize simple agent."""
|
||||||
|
super().__init__(name, role, goal)
|
||||||
|
|
||||||
|
def work(self, task: str) -> str:
|
||||||
|
"""Simulate agent work."""
|
||||||
|
return f"{self.name}: Completed task - {task[:50]}..."
|
||||||
|
|
||||||
|
|
||||||
|
class SequentialOrchestrator:
|
||||||
|
"""Orchestrate agents to work sequentially."""
|
||||||
|
|
||||||
|
def __init__(self, agents: List[Agent]):
|
||||||
|
"""
|
||||||
|
Initialize orchestrator with agents.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agents: List of agents to orchestrate
|
||||||
|
"""
|
||||||
|
self.agents = agents
|
||||||
|
self.execution_log = []
|
||||||
|
|
||||||
|
def execute(self, initial_task: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute agents sequentially.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
initial_task: Initial task description
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Execution results dictionary
|
||||||
|
"""
|
||||||
|
current_input = initial_task
|
||||||
|
results = {}
|
||||||
|
|
||||||
|
for agent in self.agents:
|
||||||
|
result = agent.work(current_input)
|
||||||
|
results[agent.name] = result
|
||||||
|
self.execution_log.append({
|
||||||
|
"agent": agent.name,
|
||||||
|
"role": agent.role,
|
||||||
|
"task": current_input,
|
||||||
|
"result": result,
|
||||||
|
})
|
||||||
|
# Next agent uses this agent's output
|
||||||
|
current_input = result
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "sequential",
|
||||||
|
"results": results,
|
||||||
|
"final_output": current_input,
|
||||||
|
"execution_log": self.execution_log,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ParallelOrchestrator:
|
||||||
|
"""Orchestrate agents to work in parallel."""
|
||||||
|
|
||||||
|
def __init__(self, agents: List[Agent]):
|
||||||
|
"""Initialize parallel orchestrator."""
|
||||||
|
self.agents = agents
|
||||||
|
self.execution_log = []
|
||||||
|
|
||||||
|
async def execute_async(self, task: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute agents in parallel.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task: Task description
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Execution results dictionary
|
||||||
|
"""
|
||||||
|
# Create async tasks for all agents
|
||||||
|
tasks = [agent.work_async(task) for agent in self.agents]
|
||||||
|
|
||||||
|
# Execute all in parallel
|
||||||
|
results_list = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
results = {
|
||||||
|
agent.name: result
|
||||||
|
for agent, result in zip(self.agents, results_list)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.execution_log.append({
|
||||||
|
"type": "parallel",
|
||||||
|
"task": task,
|
||||||
|
"agents": [a.name for a in self.agents],
|
||||||
|
"results": results,
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "parallel",
|
||||||
|
"results": results,
|
||||||
|
"execution_log": self.execution_log,
|
||||||
|
}
|
||||||
|
|
||||||
|
def execute(self, task: str) -> Dict[str, Any]:
|
||||||
|
"""Execute agents synchronously (sequential fallback)."""
|
||||||
|
return asyncio.run(self.execute_async(task))
|
||||||
|
|
||||||
|
|
||||||
|
class HierarchicalOrchestrator:
|
||||||
|
"""Orchestrate agents in hierarchical structure."""
|
||||||
|
|
||||||
|
def __init__(self, manager_agent: Agent, specialist_teams: Dict[str, List[Agent]]):
|
||||||
|
"""
|
||||||
|
Initialize hierarchical orchestrator.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
manager_agent: Manager agent
|
||||||
|
specialist_teams: Dict of team names to lists of agents
|
||||||
|
"""
|
||||||
|
self.manager = manager_agent
|
||||||
|
self.specialist_teams = specialist_teams
|
||||||
|
self.execution_log = []
|
||||||
|
|
||||||
|
def execute(self, main_task: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute with hierarchical structure.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
main_task: Main task for manager
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Execution results
|
||||||
|
"""
|
||||||
|
team_results = {}
|
||||||
|
|
||||||
|
# Manager assigns tasks to teams
|
||||||
|
for team_name, agents in self.specialist_teams.items():
|
||||||
|
# Each team works on their aspect
|
||||||
|
team_task = f"{main_task} - Team: {team_name}"
|
||||||
|
team_result = {}
|
||||||
|
|
||||||
|
for agent in agents:
|
||||||
|
result = agent.work(team_task)
|
||||||
|
team_result[agent.name] = result
|
||||||
|
|
||||||
|
team_results[team_name] = team_result
|
||||||
|
|
||||||
|
self.execution_log.append({
|
||||||
|
"team": team_name,
|
||||||
|
"agents": [a.name for a in agents],
|
||||||
|
"results": team_result,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Manager synthesizes results
|
||||||
|
manager_result = self.manager.work(
|
||||||
|
f"Synthesize findings from: {list(team_results.keys())}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "hierarchical",
|
||||||
|
"team_results": team_results,
|
||||||
|
"manager_synthesis": manager_result,
|
||||||
|
"execution_log": self.execution_log,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ConsensusOrchestrator:
|
||||||
|
"""Orchestrate agent debate and consensus."""
|
||||||
|
|
||||||
|
def __init__(self, agents: List[Agent], mediator_agent: Agent):
|
||||||
|
"""Initialize consensus orchestrator."""
|
||||||
|
self.agents = agents
|
||||||
|
self.mediator = mediator_agent
|
||||||
|
self.debate_history = []
|
||||||
|
|
||||||
|
def execute(self, question: str, rounds: int = 2) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute debate and reach consensus.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
question: Question for debate
|
||||||
|
rounds: Number of debate rounds
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Consensus results
|
||||||
|
"""
|
||||||
|
# Round 1: Initial positions
|
||||||
|
positions = {}
|
||||||
|
for agent in self.agents:
|
||||||
|
position = agent.work(f"Argue your position on: {question}")
|
||||||
|
positions[agent.name] = position
|
||||||
|
self.debate_history.append({
|
||||||
|
"round": 1,
|
||||||
|
"agent": agent.name,
|
||||||
|
"position": position,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Additional rounds: Response to others
|
||||||
|
for round_num in range(2, rounds + 1):
|
||||||
|
for agent in self.agents:
|
||||||
|
other_positions = {
|
||||||
|
name: pos
|
||||||
|
for name, pos in positions.items()
|
||||||
|
if name != agent.name
|
||||||
|
}
|
||||||
|
response = agent.work(
|
||||||
|
f"Respond to these positions: {str(other_positions)}"
|
||||||
|
)
|
||||||
|
self.debate_history.append({
|
||||||
|
"round": round_num,
|
||||||
|
"agent": agent.name,
|
||||||
|
"response": response,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Mediator reaches consensus
|
||||||
|
consensus = self.mediator.work(
|
||||||
|
f"Synthesize consensus from debate on: {question}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "consensus",
|
||||||
|
"question": question,
|
||||||
|
"initial_positions": positions,
|
||||||
|
"debate_rounds": rounds,
|
||||||
|
"consensus": consensus,
|
||||||
|
"debate_history": self.debate_history,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class AdaptiveOrchestrator:
|
||||||
|
"""Adapt orchestration based on progress."""
|
||||||
|
|
||||||
|
def __init__(self, agents: List[Agent]):
|
||||||
|
"""Initialize adaptive orchestrator."""
|
||||||
|
self.agents = agents
|
||||||
|
self.execution_log = []
|
||||||
|
|
||||||
|
def execute_with_adaptation(
|
||||||
|
self,
|
||||||
|
initial_task: str,
|
||||||
|
progress_threshold: float = 0.7,
|
||||||
|
quality_threshold: float = 0.6,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute with adaptive workflow changes.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
initial_task: Initial task
|
||||||
|
progress_threshold: Threshold for adding resources
|
||||||
|
quality_threshold: Threshold for adding validation
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Adaptive execution results
|
||||||
|
"""
|
||||||
|
results = {}
|
||||||
|
current_task = initial_task
|
||||||
|
active_agents = self.agents.copy()
|
||||||
|
|
||||||
|
for iteration in range(3):
|
||||||
|
# Execute with current agents
|
||||||
|
iteration_results = {}
|
||||||
|
for agent in active_agents:
|
||||||
|
result = agent.work(current_task)
|
||||||
|
iteration_results[agent.name] = result
|
||||||
|
|
||||||
|
results[f"iteration_{iteration}"] = iteration_results
|
||||||
|
|
||||||
|
# Assess progress
|
||||||
|
progress = self._calculate_progress(iteration_results)
|
||||||
|
quality = self._calculate_quality(iteration_results)
|
||||||
|
|
||||||
|
log_entry = {
|
||||||
|
"iteration": iteration,
|
||||||
|
"agents": [a.name for a in active_agents],
|
||||||
|
"progress": progress,
|
||||||
|
"quality": quality,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Adapt based on progress
|
||||||
|
if progress < progress_threshold and iteration < 2:
|
||||||
|
# Add more agents
|
||||||
|
log_entry["adaptation"] = "Added specialist agent"
|
||||||
|
self.execution_log.append(log_entry)
|
||||||
|
elif quality < quality_threshold and iteration < 2:
|
||||||
|
# Add validation step
|
||||||
|
log_entry["adaptation"] = "Added validation agent"
|
||||||
|
self.execution_log.append(log_entry)
|
||||||
|
else:
|
||||||
|
self.execution_log.append(log_entry)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "adaptive",
|
||||||
|
"results": results,
|
||||||
|
"adaptations": self.execution_log,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _calculate_progress(results: Dict) -> float:
|
||||||
|
"""Calculate progress score."""
|
||||||
|
# Simple heuristic based on results
|
||||||
|
return min(len(results) / 3.0, 1.0)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _calculate_quality(results: Dict) -> float:
|
||||||
|
"""Calculate quality score."""
|
||||||
|
# Simple heuristic
|
||||||
|
return 0.7 # Placeholder
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowGraph:
|
||||||
|
"""Define workflow as directed acyclic graph (DAG)."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize workflow graph."""
|
||||||
|
self.nodes = {}
|
||||||
|
self.edges = []
|
||||||
|
|
||||||
|
def add_node(self, node_id: str, agent: Agent) -> None:
|
||||||
|
"""Add agent node."""
|
||||||
|
self.nodes[node_id] = agent
|
||||||
|
|
||||||
|
def add_edge(self, from_node: str, to_node: str) -> None:
|
||||||
|
"""Add dependency edge."""
|
||||||
|
self.edges.append((from_node, to_node))
|
||||||
|
|
||||||
|
def execute_dag(self, initial_task: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute workflow as DAG.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
initial_task: Initial task
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Execution results
|
||||||
|
"""
|
||||||
|
results = {}
|
||||||
|
ready_nodes = self._find_ready_nodes()
|
||||||
|
|
||||||
|
while ready_nodes:
|
||||||
|
for node_id in ready_nodes:
|
||||||
|
agent = self.nodes[node_id]
|
||||||
|
# Get input from dependencies
|
||||||
|
task_input = self._get_node_input(node_id, results, initial_task)
|
||||||
|
result = agent.work(task_input)
|
||||||
|
results[node_id] = result
|
||||||
|
|
||||||
|
ready_nodes = self._find_ready_nodes(completed=set(results.keys()))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"type": "dag",
|
||||||
|
"results": results,
|
||||||
|
"nodes": list(self.nodes.keys()),
|
||||||
|
"edges": self.edges,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _find_ready_nodes(self, completed: Optional[set] = None) -> List[str]:
|
||||||
|
"""Find nodes with all dependencies completed."""
|
||||||
|
if completed is None:
|
||||||
|
completed = set()
|
||||||
|
|
||||||
|
ready = []
|
||||||
|
for node_id in self.nodes:
|
||||||
|
if node_id not in completed:
|
||||||
|
dependencies = [
|
||||||
|
from_node
|
||||||
|
for from_node, to_node in self.edges
|
||||||
|
if to_node == node_id
|
||||||
|
]
|
||||||
|
if all(dep in completed for dep in dependencies):
|
||||||
|
ready.append(node_id)
|
||||||
|
|
||||||
|
return ready
|
||||||
|
|
||||||
|
def _get_node_input(
|
||||||
|
self, node_id: str, results: Dict, initial_task: str
|
||||||
|
) -> str:
|
||||||
|
"""Get input for node from dependencies."""
|
||||||
|
dependencies = [
|
||||||
|
from_node for from_node, to_node in self.edges if to_node == node_id
|
||||||
|
]
|
||||||
|
if not dependencies:
|
||||||
|
return initial_task
|
||||||
|
# Combine outputs from dependencies
|
||||||
|
return " + ".join(results.get(dep, "") for dep in dependencies)
|
||||||
@ -0,0 +1,93 @@
|
|||||||
|
"""
|
||||||
|
Example: End-to-End Scrum Feature Sprint with Multi-Agent Orchestration
|
||||||
|
|
||||||
|
Demonstrates a complete sprint execution where specialized agents collaborate:
|
||||||
|
1. Product Owner defines the User Story & Acceptance Criteria
|
||||||
|
2. Tech Lead / Architect specifies the API contract
|
||||||
|
3. Backend and Frontend Developers implement in parallel
|
||||||
|
4. QA Engineer validates tests and criteria
|
||||||
|
5. Code Reviewer verifies Definition of Done
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Add scripts directory to path
|
||||||
|
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../scripts")))
|
||||||
|
|
||||||
|
from scrum_orchestrator import ScrumSprintOrchestrator, ScrumRole, StoryStatus
|
||||||
|
|
||||||
|
|
||||||
|
def run_scrum_simulation():
|
||||||
|
print("=" * 60)
|
||||||
|
print("Starting Scrum Sprint Simulation with Multi-Agent Team")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# 1. Initialize Sprint
|
||||||
|
orchestrator = ScrumSprintOrchestrator(
|
||||||
|
sprint_name="Sprint 1 - Authentication & User Profile",
|
||||||
|
sprint_goal="Deliver secure JWT authentication and user profile view"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Product Owner creates User Story
|
||||||
|
story = orchestrator.add_story(
|
||||||
|
title="User Login and Profile Display",
|
||||||
|
description="As an intranet user, I want to authenticate securely and view my profile.",
|
||||||
|
acceptance_criteria=[
|
||||||
|
"Given valid credentials, when submitting the login form, the user receives a JWT token.",
|
||||||
|
"Given an authenticated session, the user profile page renders avatar, name, and email.",
|
||||||
|
"Given invalid credentials, a clear accessible error toast is shown."
|
||||||
|
],
|
||||||
|
story_points=3
|
||||||
|
)
|
||||||
|
print(f"\n[Product Owner] Created Story: {story.story_id} - {story.title}")
|
||||||
|
for ac in story.acceptance_criteria:
|
||||||
|
print(f" ✓ AC: {ac}")
|
||||||
|
|
||||||
|
# 3. Scrum Master plans workflow DAG
|
||||||
|
workflow_plan = orchestrator.plan_sprint_workflow(story)
|
||||||
|
print("\n[Scrum Master] Generated Sprint Workflow Plan:")
|
||||||
|
for step in workflow_plan["phases"]:
|
||||||
|
deps = f" (Depends on: {', '.join(step['depends_on'])})" if step["depends_on"] else " (Root task)"
|
||||||
|
print(f" → [{step['phase']}] Assigned to: {step['role']}{deps}")
|
||||||
|
|
||||||
|
# 4. Tech Lead drafts API Contract
|
||||||
|
api_contract = {
|
||||||
|
"endpoint": "/api/v1/auth/login",
|
||||||
|
"method": "POST",
|
||||||
|
"request": {"username": "str", "password": "str"},
|
||||||
|
"response": {"token": "str", "user": {"id": "str", "name": "str", "email": "str"}}
|
||||||
|
}
|
||||||
|
orchestrator.memory.write("api_contract", api_contract)
|
||||||
|
print("\n[Tech Lead] Published API Contract to Shared Memory.")
|
||||||
|
|
||||||
|
# 5. Parallel Execution: Backend & Frontend
|
||||||
|
print("\n[Orchestrator] Dispatching Parallel Development Tasks...")
|
||||||
|
# Backend Worker
|
||||||
|
contract = orchestrator.memory.read("api_contract")
|
||||||
|
print(f" [Backend Dev] Implementing endpoint {contract['endpoint']} matching schema...")
|
||||||
|
orchestrator.memory.write("backend_status", "COMPLETED_WITH_TEST_ENDPOINT")
|
||||||
|
|
||||||
|
# Frontend Worker
|
||||||
|
print(f" [Frontend Dev] Building Login Form & Profile View matching contract...")
|
||||||
|
orchestrator.memory.write("frontend_status", "COMPLETED_WITH_UI_COMPONENTS")
|
||||||
|
|
||||||
|
# 6. QA Verification
|
||||||
|
print("\n[QA Engineer] Running Test Suite against Acceptance Criteria:")
|
||||||
|
print(" ✓ Test 1: POST /api/v1/auth/login returns 200 with JWT token -> PASSED")
|
||||||
|
print(" ✓ Test 2: Profile page renders user info properly -> PASSED")
|
||||||
|
print(" ✓ Test 3: Invalid credentials trigger error notification -> PASSED")
|
||||||
|
|
||||||
|
# 7. Code Review & DoD Verification
|
||||||
|
print("\n[Code Reviewer] Auditing PR and Definition of Done:")
|
||||||
|
print(" ✓ OWASP Security check: Password hashing and JWT expiry verified")
|
||||||
|
print(" ✓ Accessibility check: WCAG 2.1 AA color contrast and screen reader aria-labels present")
|
||||||
|
print(" ✓ Definition of Done satisfied. Story signed off as DONE.")
|
||||||
|
|
||||||
|
story.status = StoryStatus.DONE
|
||||||
|
print(f"\n[Scrum Master] Story {story.story_id} successfully marked as: {story.status.value.upper()}")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run_scrum_simulation()
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,334 @@
|
|||||||
|
"""
|
||||||
|
Agent Communication Management
|
||||||
|
|
||||||
|
Handle agent-to-agent communication, message passing, and shared state.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, List, Optional, Any, Callable
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from enum import Enum
|
||||||
|
import json
|
||||||
|
|
||||||
|
|
||||||
|
class MessageType(Enum):
|
||||||
|
"""Types of messages between agents."""
|
||||||
|
|
||||||
|
DIRECT = "direct"
|
||||||
|
BROADCAST = "broadcast"
|
||||||
|
REQUEST = "request"
|
||||||
|
RESPONSE = "response"
|
||||||
|
FEEDBACK = "feedback"
|
||||||
|
ERROR = "error"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Message:
|
||||||
|
"""Message between agents."""
|
||||||
|
|
||||||
|
sender: str
|
||||||
|
recipient: str
|
||||||
|
content: str
|
||||||
|
message_type: MessageType
|
||||||
|
timestamp: float = field(default_factory=lambda: 0)
|
||||||
|
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict:
|
||||||
|
"""Convert to dictionary."""
|
||||||
|
return {
|
||||||
|
"sender": self.sender,
|
||||||
|
"recipient": self.recipient,
|
||||||
|
"content": self.content,
|
||||||
|
"type": self.message_type.value,
|
||||||
|
"timestamp": self.timestamp,
|
||||||
|
"metadata": self.metadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class MessageBroker:
|
||||||
|
"""Central message broker for agent communication."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize message broker."""
|
||||||
|
self.message_queue: List[Message] = []
|
||||||
|
self.agent_inboxes: Dict[str, List[Message]] = {}
|
||||||
|
self.message_handlers: Dict[MessageType, List[Callable]] = {}
|
||||||
|
|
||||||
|
def send_message(self, message: Message) -> bool:
|
||||||
|
"""
|
||||||
|
Send message from one agent to another.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: Message object
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Whether message was delivered
|
||||||
|
"""
|
||||||
|
self.message_queue.append(message)
|
||||||
|
|
||||||
|
# Add to recipient's inbox
|
||||||
|
if message.recipient not in self.agent_inboxes:
|
||||||
|
self.agent_inboxes[message.recipient] = []
|
||||||
|
self.agent_inboxes[message.recipient].append(message)
|
||||||
|
|
||||||
|
# Trigger handlers
|
||||||
|
self._trigger_handlers(message)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def broadcast_message(self, sender: str, content: str, recipients: List[str]):
|
||||||
|
"""
|
||||||
|
Broadcast message to multiple agents.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sender: Sending agent
|
||||||
|
content: Message content
|
||||||
|
recipients: List of recipient agents
|
||||||
|
"""
|
||||||
|
for recipient in recipients:
|
||||||
|
message = Message(
|
||||||
|
sender=sender,
|
||||||
|
recipient=recipient,
|
||||||
|
content=content,
|
||||||
|
message_type=MessageType.BROADCAST,
|
||||||
|
)
|
||||||
|
self.send_message(message)
|
||||||
|
|
||||||
|
def request_response(
|
||||||
|
self, sender: str, recipient: str, content: str, timeout: float = 5.0
|
||||||
|
) -> Optional[Message]:
|
||||||
|
"""
|
||||||
|
Send request and wait for response.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sender: Requesting agent
|
||||||
|
recipient: Agent to respond
|
||||||
|
content: Request content
|
||||||
|
timeout: Response timeout in seconds
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Response message or None
|
||||||
|
"""
|
||||||
|
message = Message(
|
||||||
|
sender=sender,
|
||||||
|
recipient=recipient,
|
||||||
|
content=content,
|
||||||
|
message_type=MessageType.REQUEST,
|
||||||
|
metadata={"timeout": timeout},
|
||||||
|
)
|
||||||
|
self.send_message(message)
|
||||||
|
|
||||||
|
# Placeholder - wait for response
|
||||||
|
# In production, implement actual timeout/wait mechanism
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_inbox(self, agent: str) -> List[Message]:
|
||||||
|
"""Get messages for specific agent."""
|
||||||
|
return self.agent_inboxes.get(agent, [])
|
||||||
|
|
||||||
|
def clear_inbox(self, agent: str) -> None:
|
||||||
|
"""Clear agent's inbox."""
|
||||||
|
self.agent_inboxes[agent] = []
|
||||||
|
|
||||||
|
def register_handler(
|
||||||
|
self, message_type: MessageType, handler: Callable
|
||||||
|
) -> None:
|
||||||
|
"""Register handler for message type."""
|
||||||
|
if message_type not in self.message_handlers:
|
||||||
|
self.message_handlers[message_type] = []
|
||||||
|
self.message_handlers[message_type].append(handler)
|
||||||
|
|
||||||
|
def _trigger_handlers(self, message: Message) -> None:
|
||||||
|
"""Trigger registered handlers."""
|
||||||
|
handlers = self.message_handlers.get(message.message_type, [])
|
||||||
|
for handler in handlers:
|
||||||
|
try:
|
||||||
|
handler(message)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def get_statistics(self) -> Dict[str, Any]:
|
||||||
|
"""Get communication statistics."""
|
||||||
|
type_counts = {}
|
||||||
|
for message in self.message_queue:
|
||||||
|
msg_type = message.message_type.value
|
||||||
|
type_counts[msg_type] = type_counts.get(msg_type, 0) + 1
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_messages": len(self.message_queue),
|
||||||
|
"by_type": type_counts,
|
||||||
|
"total_agents": len(self.agent_inboxes),
|
||||||
|
"agents": list(self.agent_inboxes.keys()),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SharedMemory:
|
||||||
|
"""Shared memory for tool-mediated agent communication."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize shared memory."""
|
||||||
|
self.memory: Dict[str, Any] = {}
|
||||||
|
self.access_log: List[Dict] = []
|
||||||
|
|
||||||
|
def write(self, key: str, value: Any, agent: str = "system") -> None:
|
||||||
|
"""
|
||||||
|
Write to shared memory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key: Memory key
|
||||||
|
value: Value to store
|
||||||
|
agent: Agent writing
|
||||||
|
"""
|
||||||
|
self.memory[key] = {
|
||||||
|
"value": value,
|
||||||
|
"writer": agent,
|
||||||
|
"access_count": 0,
|
||||||
|
}
|
||||||
|
self.access_log.append({
|
||||||
|
"action": "write",
|
||||||
|
"key": key,
|
||||||
|
"agent": agent,
|
||||||
|
})
|
||||||
|
|
||||||
|
def read(self, key: str, agent: str = "system") -> Optional[Any]:
|
||||||
|
"""
|
||||||
|
Read from shared memory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key: Memory key
|
||||||
|
agent: Agent reading
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Stored value or None
|
||||||
|
"""
|
||||||
|
if key in self.memory:
|
||||||
|
entry = self.memory[key]
|
||||||
|
entry["access_count"] += 1
|
||||||
|
self.access_log.append({
|
||||||
|
"action": "read",
|
||||||
|
"key": key,
|
||||||
|
"agent": agent,
|
||||||
|
})
|
||||||
|
return entry["value"]
|
||||||
|
return None
|
||||||
|
|
||||||
|
def append(self, key: str, value: Any, agent: str = "system") -> None:
|
||||||
|
"""Append to list in shared memory."""
|
||||||
|
if key not in self.memory:
|
||||||
|
self.memory[key] = {
|
||||||
|
"value": [],
|
||||||
|
"writer": agent,
|
||||||
|
"access_count": 0,
|
||||||
|
}
|
||||||
|
if isinstance(self.memory[key]["value"], list):
|
||||||
|
self.memory[key]["value"].append(value)
|
||||||
|
|
||||||
|
def get_all(self) -> Dict[str, Any]:
|
||||||
|
"""Get all shared memory contents."""
|
||||||
|
return {
|
||||||
|
key: entry["value"] for key, entry in self.memory.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_statistics(self) -> Dict[str, Any]:
|
||||||
|
"""Get memory access statistics."""
|
||||||
|
total_accesses = sum(
|
||||||
|
entry["access_count"] for entry in self.memory.values()
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_keys": len(self.memory),
|
||||||
|
"total_accesses": total_accesses,
|
||||||
|
"access_log_size": len(self.access_log),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ContextManager:
|
||||||
|
"""Manage context sharing between agents."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize context manager."""
|
||||||
|
self.contexts: Dict[str, Dict[str, Any]] = {}
|
||||||
|
self.global_context: Dict[str, Any] = {}
|
||||||
|
|
||||||
|
def create_context(self, context_id: str, initial_data: Optional[Dict] = None) -> None:
|
||||||
|
"""Create new context."""
|
||||||
|
self.contexts[context_id] = initial_data or {}
|
||||||
|
|
||||||
|
def update_context(self, context_id: str, data: Dict) -> None:
|
||||||
|
"""Update context data."""
|
||||||
|
if context_id in self.contexts:
|
||||||
|
self.contexts[context_id].update(data)
|
||||||
|
|
||||||
|
def get_context(self, context_id: str) -> Dict[str, Any]:
|
||||||
|
"""Get context data."""
|
||||||
|
return self.contexts.get(context_id, {})
|
||||||
|
|
||||||
|
def set_global_context(self, key: str, value: Any) -> None:
|
||||||
|
"""Set global context variable."""
|
||||||
|
self.global_context[key] = value
|
||||||
|
|
||||||
|
def get_global_context(self, key: str) -> Optional[Any]:
|
||||||
|
"""Get global context variable."""
|
||||||
|
return self.global_context.get(key)
|
||||||
|
|
||||||
|
def context_to_string(self, context_id: str) -> str:
|
||||||
|
"""Convert context to formatted string."""
|
||||||
|
context = self.get_context(context_id)
|
||||||
|
return json.dumps(context, indent=2)
|
||||||
|
|
||||||
|
|
||||||
|
class CommunicationProtocol:
|
||||||
|
"""Define communication protocol between agents."""
|
||||||
|
|
||||||
|
def __init__(self, broker: MessageBroker, shared_memory: SharedMemory):
|
||||||
|
"""Initialize protocol."""
|
||||||
|
self.broker = broker
|
||||||
|
self.shared_memory = shared_memory
|
||||||
|
|
||||||
|
def request_analysis(
|
||||||
|
self, requester: str, analyzer: str, subject: str
|
||||||
|
) -> None:
|
||||||
|
"""Request analysis from another agent."""
|
||||||
|
message = Message(
|
||||||
|
sender=requester,
|
||||||
|
recipient=analyzer,
|
||||||
|
content=f"Analyze: {subject}",
|
||||||
|
message_type=MessageType.REQUEST,
|
||||||
|
metadata={"action": "analyze"},
|
||||||
|
)
|
||||||
|
self.broker.send_message(message)
|
||||||
|
|
||||||
|
def share_findings(self, source_agent: str, key: str, findings: Dict) -> None:
|
||||||
|
"""Share findings through shared memory."""
|
||||||
|
self.shared_memory.write(key, findings, source_agent)
|
||||||
|
|
||||||
|
def aggregate_results(
|
||||||
|
self, agents: List[str], result_key: str
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Aggregate results from multiple agents."""
|
||||||
|
results = {}
|
||||||
|
for agent in agents:
|
||||||
|
agent_results = self.shared_memory.read(f"{agent}_{result_key}")
|
||||||
|
if agent_results:
|
||||||
|
results[agent] = agent_results
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def notify_status(self, agent: str, status: str) -> None:
|
||||||
|
"""Notify status update."""
|
||||||
|
message = Message(
|
||||||
|
sender=agent,
|
||||||
|
recipient="orchestrator",
|
||||||
|
content=f"Status: {status}",
|
||||||
|
message_type=MessageType.FEEDBACK,
|
||||||
|
)
|
||||||
|
self.broker.send_message(message)
|
||||||
|
|
||||||
|
def error_propagation(self, source_agent: str, error: str) -> None:
|
||||||
|
"""Propagate error to relevant agents."""
|
||||||
|
message = Message(
|
||||||
|
sender=source_agent,
|
||||||
|
recipient="orchestrator",
|
||||||
|
content=f"Error: {error}",
|
||||||
|
message_type=MessageType.ERROR,
|
||||||
|
)
|
||||||
|
self.broker.send_message(message)
|
||||||
@ -0,0 +1,341 @@
|
|||||||
|
"""
|
||||||
|
Multi-Agent System Benchmarking
|
||||||
|
|
||||||
|
Evaluate team performance and agent effectiveness.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, List, Any, Callable, Optional
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import time
|
||||||
|
import statistics
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BenchmarkResult:
|
||||||
|
"""Result from benchmark run."""
|
||||||
|
|
||||||
|
test_name: str
|
||||||
|
total_time: float
|
||||||
|
task_count: int
|
||||||
|
success_count: int
|
||||||
|
failure_count: int
|
||||||
|
quality_score: float
|
||||||
|
cost_tokens: int
|
||||||
|
|
||||||
|
|
||||||
|
class TeamBenchmark:
|
||||||
|
"""Benchmark multi-agent team performance."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize benchmarking suite."""
|
||||||
|
self.results: List[BenchmarkResult] = []
|
||||||
|
self.agent_metrics: Dict[str, Dict] = {}
|
||||||
|
|
||||||
|
def run_benchmark(
|
||||||
|
self,
|
||||||
|
test_name: str,
|
||||||
|
orchestrator,
|
||||||
|
test_data: List[Dict],
|
||||||
|
quality_metric: Optional[Callable] = None,
|
||||||
|
) -> BenchmarkResult:
|
||||||
|
"""
|
||||||
|
Run benchmark test.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
test_name: Name of benchmark
|
||||||
|
orchestrator: Orchestrator instance
|
||||||
|
test_data: Test cases
|
||||||
|
quality_metric: Function to evaluate quality
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Benchmark result
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
results = []
|
||||||
|
costs = []
|
||||||
|
|
||||||
|
for test_case in test_data:
|
||||||
|
try:
|
||||||
|
result = orchestrator.execute(test_case)
|
||||||
|
results.append(result)
|
||||||
|
# Assume cost in test_case
|
||||||
|
costs.append(test_case.get("cost", 0))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
end_time = time.time()
|
||||||
|
|
||||||
|
success_count = len(results)
|
||||||
|
failure_count = len(test_data) - success_count
|
||||||
|
total_time = end_time - start_time
|
||||||
|
|
||||||
|
# Calculate quality score
|
||||||
|
quality_score = (
|
||||||
|
quality_metric(results) if quality_metric else success_count / len(test_data)
|
||||||
|
)
|
||||||
|
|
||||||
|
benchmark_result = BenchmarkResult(
|
||||||
|
test_name=test_name,
|
||||||
|
total_time=total_time,
|
||||||
|
task_count=len(test_data),
|
||||||
|
success_count=success_count,
|
||||||
|
failure_count=failure_count,
|
||||||
|
quality_score=quality_score,
|
||||||
|
cost_tokens=sum(costs),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.results.append(benchmark_result)
|
||||||
|
return benchmark_result
|
||||||
|
|
||||||
|
def compare_orchestration_methods(
|
||||||
|
self,
|
||||||
|
methods: Dict[str, Callable],
|
||||||
|
test_data: List[Dict],
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Compare different orchestration methods.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
methods: Dict of method name to orchestrator
|
||||||
|
test_data: Test cases
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Comparison results
|
||||||
|
"""
|
||||||
|
comparison = {}
|
||||||
|
|
||||||
|
for method_name, orchestrator in methods.items():
|
||||||
|
result = self.run_benchmark(method_name, orchestrator, test_data)
|
||||||
|
comparison[method_name] = {
|
||||||
|
"total_time": result.total_time,
|
||||||
|
"success_rate": result.success_count / result.task_count,
|
||||||
|
"quality_score": result.quality_score,
|
||||||
|
"efficiency": result.success_count / (result.total_time + 0.001),
|
||||||
|
"cost_per_success": (
|
||||||
|
result.cost_tokens / result.success_count
|
||||||
|
if result.success_count > 0
|
||||||
|
else float("inf")
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
return comparison
|
||||||
|
|
||||||
|
def get_summary(self) -> Dict[str, Any]:
|
||||||
|
"""Get benchmark summary."""
|
||||||
|
if not self.results:
|
||||||
|
return {"status": "no_results"}
|
||||||
|
|
||||||
|
times = [r.total_time for r in self.results]
|
||||||
|
success_rates = [
|
||||||
|
r.success_count / r.task_count for r in self.results
|
||||||
|
]
|
||||||
|
quality_scores = [r.quality_score for r in self.results]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_benchmarks": len(self.results),
|
||||||
|
"avg_time": statistics.mean(times),
|
||||||
|
"median_time": statistics.median(times),
|
||||||
|
"avg_success_rate": statistics.mean(success_rates),
|
||||||
|
"avg_quality": statistics.mean(quality_scores),
|
||||||
|
"benchmarks": [r.__dict__ for r in self.results],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class AgentEffectiveness:
|
||||||
|
"""Measure individual agent effectiveness."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize effectiveness tracker."""
|
||||||
|
self.agent_stats: Dict[str, Dict] = {}
|
||||||
|
|
||||||
|
def record_agent_task(
|
||||||
|
self,
|
||||||
|
agent: str,
|
||||||
|
task_id: str,
|
||||||
|
success: bool,
|
||||||
|
quality_score: float,
|
||||||
|
duration: float,
|
||||||
|
) -> None:
|
||||||
|
"""Record agent task execution."""
|
||||||
|
if agent not in self.agent_stats:
|
||||||
|
self.agent_stats[agent] = {
|
||||||
|
"tasks": [],
|
||||||
|
"successes": 0,
|
||||||
|
"failures": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
stats = self.agent_stats[agent]
|
||||||
|
stats["tasks"].append({
|
||||||
|
"task_id": task_id,
|
||||||
|
"success": success,
|
||||||
|
"quality": quality_score,
|
||||||
|
"duration": duration,
|
||||||
|
})
|
||||||
|
|
||||||
|
if success:
|
||||||
|
stats["successes"] += 1
|
||||||
|
else:
|
||||||
|
stats["failures"] += 1
|
||||||
|
|
||||||
|
def get_agent_metrics(self, agent: str) -> Dict[str, Any]:
|
||||||
|
"""Get metrics for specific agent."""
|
||||||
|
if agent not in self.agent_stats:
|
||||||
|
return {"status": "no_data"}
|
||||||
|
|
||||||
|
stats = self.agent_stats[agent]
|
||||||
|
tasks = stats["tasks"]
|
||||||
|
|
||||||
|
if not tasks:
|
||||||
|
return {"status": "no_tasks"}
|
||||||
|
|
||||||
|
success_rate = stats["successes"] / (stats["successes"] + stats["failures"])
|
||||||
|
quality_scores = [t["quality"] for t in tasks]
|
||||||
|
durations = [t["duration"] for t in tasks]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"agent": agent,
|
||||||
|
"total_tasks": len(tasks),
|
||||||
|
"success_rate": success_rate,
|
||||||
|
"avg_quality": statistics.mean(quality_scores),
|
||||||
|
"avg_duration": statistics.mean(durations),
|
||||||
|
"reliability": success_rate, # Alias for clarity
|
||||||
|
}
|
||||||
|
|
||||||
|
def rank_agents(self) -> List[tuple]:
|
||||||
|
"""Rank agents by effectiveness."""
|
||||||
|
rankings = []
|
||||||
|
|
||||||
|
for agent in self.agent_stats.keys():
|
||||||
|
metrics = self.get_agent_metrics(agent)
|
||||||
|
if "success_rate" in metrics:
|
||||||
|
score = (
|
||||||
|
metrics["success_rate"] * 0.4 +
|
||||||
|
metrics["avg_quality"] * 0.4 +
|
||||||
|
(1 - min(metrics["avg_duration"] / 10.0, 1.0)) * 0.2
|
||||||
|
)
|
||||||
|
rankings.append((agent, score, metrics))
|
||||||
|
|
||||||
|
rankings.sort(key=lambda x: x[1], reverse=True)
|
||||||
|
return rankings
|
||||||
|
|
||||||
|
def get_team_report(self) -> Dict[str, Any]:
|
||||||
|
"""Get team effectiveness report."""
|
||||||
|
rankings = self.rank_agents()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_agents": len(self.agent_stats),
|
||||||
|
"rankings": [
|
||||||
|
{
|
||||||
|
"rank": i + 1,
|
||||||
|
"agent": agent,
|
||||||
|
"score": score,
|
||||||
|
"metrics": metrics,
|
||||||
|
}
|
||||||
|
for i, (agent, score, metrics) in enumerate(rankings)
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class CollaborationMetrics:
|
||||||
|
"""Measure collaboration effectiveness between agents."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize collaboration metrics."""
|
||||||
|
self.interactions: List[Dict] = []
|
||||||
|
|
||||||
|
def record_interaction(
|
||||||
|
self,
|
||||||
|
agent_a: str,
|
||||||
|
agent_b: str,
|
||||||
|
message: str,
|
||||||
|
response_time: float,
|
||||||
|
successful: bool,
|
||||||
|
) -> None:
|
||||||
|
"""Record agent-to-agent interaction."""
|
||||||
|
self.interactions.append({
|
||||||
|
"agent_a": agent_a,
|
||||||
|
"agent_b": agent_b,
|
||||||
|
"message": message,
|
||||||
|
"response_time": response_time,
|
||||||
|
"successful": successful,
|
||||||
|
})
|
||||||
|
|
||||||
|
def get_collaboration_graph(self) -> Dict[str, List[str]]:
|
||||||
|
"""Get collaboration graph between agents."""
|
||||||
|
graph = {}
|
||||||
|
|
||||||
|
for interaction in self.interactions:
|
||||||
|
agent_a = interaction["agent_a"]
|
||||||
|
agent_b = interaction["agent_b"]
|
||||||
|
|
||||||
|
if agent_a not in graph:
|
||||||
|
graph[agent_a] = []
|
||||||
|
if agent_b not in graph[agent_a]:
|
||||||
|
graph[agent_a].append(agent_b)
|
||||||
|
|
||||||
|
return graph
|
||||||
|
|
||||||
|
def get_interaction_metrics(self) -> Dict[str, Any]:
|
||||||
|
"""Get interaction metrics."""
|
||||||
|
if not self.interactions:
|
||||||
|
return {"total_interactions": 0}
|
||||||
|
|
||||||
|
response_times = [i["response_time"] for i in self.interactions]
|
||||||
|
success_rate = sum(1 for i in self.interactions if i["successful"]) / len(
|
||||||
|
self.interactions
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_interactions": len(self.interactions),
|
||||||
|
"success_rate": success_rate,
|
||||||
|
"avg_response_time": statistics.mean(response_times),
|
||||||
|
"median_response_time": statistics.median(response_times),
|
||||||
|
"max_response_time": max(response_times),
|
||||||
|
"collaboration_score": success_rate * (1 - min(statistics.mean(response_times) / 10.0, 1.0)),
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_agent_collaboration_analysis(self, agent: str) -> Dict[str, Any]:
|
||||||
|
"""Get collaboration analysis for specific agent."""
|
||||||
|
agent_interactions = [
|
||||||
|
i for i in self.interactions
|
||||||
|
if i["agent_a"] == agent or i["agent_b"] == agent
|
||||||
|
]
|
||||||
|
|
||||||
|
if not agent_interactions:
|
||||||
|
return {"agent": agent, "status": "no_interactions"}
|
||||||
|
|
||||||
|
partners = set()
|
||||||
|
for interaction in agent_interactions:
|
||||||
|
if interaction["agent_a"] == agent:
|
||||||
|
partners.add(interaction["agent_b"])
|
||||||
|
else:
|
||||||
|
partners.add(interaction["agent_a"])
|
||||||
|
|
||||||
|
success_rate = sum(
|
||||||
|
1 for i in agent_interactions if i["successful"]
|
||||||
|
) / len(agent_interactions)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"agent": agent,
|
||||||
|
"collaboration_partners": list(partners),
|
||||||
|
"total_interactions": len(agent_interactions),
|
||||||
|
"collaboration_success_rate": success_rate,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def create_benchmark_suite() -> Dict[str, Callable]:
|
||||||
|
"""Create standard benchmark suite."""
|
||||||
|
return {
|
||||||
|
"sequential_tasks": lambda orchestrator: orchestrator.execute(
|
||||||
|
{"type": "sequential", "task_count": 5}
|
||||||
|
),
|
||||||
|
"parallel_tasks": lambda orchestrator: orchestrator.execute(
|
||||||
|
{"type": "parallel", "task_count": 10}
|
||||||
|
),
|
||||||
|
"complex_workflow": lambda orchestrator: orchestrator.execute(
|
||||||
|
{"type": "complex", "task_count": 20}
|
||||||
|
),
|
||||||
|
"error_handling": lambda orchestrator: orchestrator.execute(
|
||||||
|
{"type": "with_errors", "task_count": 10}
|
||||||
|
),
|
||||||
|
}
|
||||||
@ -0,0 +1,224 @@
|
|||||||
|
"""
|
||||||
|
Scrum Multi-Agent Orchestrator
|
||||||
|
|
||||||
|
Integrates Scrum Agile methodology with multi-agent orchestration patterns.
|
||||||
|
Provides role definitions, sprint lifecycle management, user story tracking,
|
||||||
|
and coordinated task dispatching for Antigravity agents.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Dict, List, Optional, Any, Callable
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .agent_communication import MessageBroker, Message, MessageType, SharedMemory
|
||||||
|
from .workflow_management import WorkflowExecutor, Workflow, Task, TaskStatus
|
||||||
|
except ImportError:
|
||||||
|
from agent_communication import MessageBroker, Message, MessageType, SharedMemory
|
||||||
|
from workflow_management import WorkflowExecutor, Workflow, Task, TaskStatus
|
||||||
|
|
||||||
|
|
||||||
|
class ScrumRole(Enum):
|
||||||
|
"""Specialized agent roles within the Scrum development team."""
|
||||||
|
PRODUCT_OWNER = "product_owner"
|
||||||
|
SCRUM_MASTER = "scrum_master"
|
||||||
|
TECH_LEAD = "tech_lead"
|
||||||
|
FRONTEND_DEV = "frontend_dev"
|
||||||
|
BACKEND_DEV = "backend_dev"
|
||||||
|
QA_ENGINEER = "qa_engineer"
|
||||||
|
CODE_REVIEWER = "code_reviewer"
|
||||||
|
|
||||||
|
|
||||||
|
class StoryStatus(Enum):
|
||||||
|
"""Status of a User Story in the Sprint."""
|
||||||
|
BACKLOG = "backlog"
|
||||||
|
PLANNING = "planning"
|
||||||
|
IN_PROGRESS = "in_progress"
|
||||||
|
IN_QA = "in_qa"
|
||||||
|
IN_REVIEW = "in_review"
|
||||||
|
DONE = "done"
|
||||||
|
BLOCKED = "blocked"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class UserStory:
|
||||||
|
"""Represents an Agile User Story with acceptance criteria."""
|
||||||
|
story_id: str
|
||||||
|
title: str
|
||||||
|
description: str
|
||||||
|
acceptance_criteria: List[str]
|
||||||
|
story_points: int = 1
|
||||||
|
status: StoryStatus = StoryStatus.BACKLOG
|
||||||
|
technical_spec: Optional[str] = None
|
||||||
|
qa_checklist: List[str] = field(default_factory=list)
|
||||||
|
artifacts: Dict[str, str] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Sprint:
|
||||||
|
"""Represents a development sprint."""
|
||||||
|
sprint_id: str
|
||||||
|
name: str
|
||||||
|
goal: str
|
||||||
|
stories: List[UserStory] = field(default_factory=list)
|
||||||
|
created_at: float = field(default_factory=time.time)
|
||||||
|
completed_at: Optional[float] = None
|
||||||
|
retrospective_notes: List[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class ScrumAgentPersona:
|
||||||
|
"""System prompts and configuration profiles for each Scrum agent."""
|
||||||
|
|
||||||
|
PROMPTS: Dict[ScrumRole, Dict[str, Any]] = {
|
||||||
|
ScrumRole.PRODUCT_OWNER: {
|
||||||
|
"title": "Product Owner Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the Product Owner. Your responsibility is to define the Sprint Goal, "
|
||||||
|
"refine User Stories into precise Gherkin format (Given/When/Then), clarify business value, "
|
||||||
|
"set strict acceptance criteria, and ensure the deliverables meet user needs."
|
||||||
|
),
|
||||||
|
"tools_required": ["search_codebase", "read_file"]
|
||||||
|
},
|
||||||
|
ScrumRole.SCRUM_MASTER: {
|
||||||
|
"title": "Scrum Master / Orchestrator Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the Scrum Master and Workflow Orchestrator. Your role is to break down stories into "
|
||||||
|
"actionable developer subtasks, map dependencies (sequential vs parallel), monitor execution, "
|
||||||
|
"resolve blockers, coordinate inter-agent handoffs, and facilitate sprint completion."
|
||||||
|
),
|
||||||
|
"tools_required": ["subagent_tools", "messaging_tools"]
|
||||||
|
},
|
||||||
|
ScrumRole.TECH_LEAD: {
|
||||||
|
"title": "Tech Lead / Architect Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the Software Architect and Tech Lead. You design API schemas, TypeScript interfaces, "
|
||||||
|
"database schemas, component hierarchies, and enforce architectural consistency and security standards. "
|
||||||
|
"You provide technical blueprints before developers start implementation."
|
||||||
|
),
|
||||||
|
"tools_required": ["read_file", "search_codebase"]
|
||||||
|
},
|
||||||
|
ScrumRole.FRONTEND_DEV: {
|
||||||
|
"title": "Frontend Developer Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the Frontend Developer. You implement responsive, accessible, high-performance UI components "
|
||||||
|
"following the Modern UI Design System, mobile-first layouts, and smooth micro-interactions. "
|
||||||
|
"You consume API contracts provided by the Tech Lead and Backend Developer."
|
||||||
|
),
|
||||||
|
"tools_required": ["write_file", "edit_file", "read_file", "run_command"]
|
||||||
|
},
|
||||||
|
ScrumRole.BACKEND_DEV: {
|
||||||
|
"title": "Backend Developer Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the Backend Developer. You implement clean API routes, business services, database models, "
|
||||||
|
"input validations, and integrations. You ensure high efficiency, reliability, and security."
|
||||||
|
),
|
||||||
|
"tools_required": ["write_file", "edit_file", "read_file", "run_command"]
|
||||||
|
},
|
||||||
|
ScrumRole.QA_ENGINEER: {
|
||||||
|
"title": "QA / Test Engineer Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the QA Engineer. You design and execute unit, integration, and E2E test suites. "
|
||||||
|
"You strictly verify that each acceptance criterion of the User Story passes before certifying "
|
||||||
|
"the build for review."
|
||||||
|
),
|
||||||
|
"tools_required": ["run_command", "read_file", "write_file"]
|
||||||
|
},
|
||||||
|
ScrumRole.CODE_REVIEWER: {
|
||||||
|
"title": "Code Reviewer & Auditor Agent",
|
||||||
|
"system_prompt": (
|
||||||
|
"You are the Code Reviewer and Security/A11y Auditor. You review diffs for code smells, "
|
||||||
|
"OWASP vulnerabilities, WCAG accessibility, and maintainability. You sign off on the Definition of Done."
|
||||||
|
),
|
||||||
|
"tools_required": ["read_file", "search_codebase"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ScrumSprintOrchestrator:
|
||||||
|
"""Coordinates a full Scrum Sprint across multi-agent roles."""
|
||||||
|
|
||||||
|
def __init__(self, sprint_name: str, sprint_goal: str):
|
||||||
|
self.sprint = Sprint(sprint_id=f"sprint_{int(time.time())}", name=sprint_name, goal=sprint_goal)
|
||||||
|
self.memory = SharedMemory()
|
||||||
|
self.broker = MessageBroker()
|
||||||
|
self.workflow_executor = WorkflowExecutor()
|
||||||
|
self.logs: List[Dict[str, Any]] = []
|
||||||
|
|
||||||
|
def add_story(self, title: str, description: str, acceptance_criteria: List[str], story_points: int = 1) -> UserStory:
|
||||||
|
story = UserStory(
|
||||||
|
story_id=f"US-{len(self.sprint.stories) + 1}",
|
||||||
|
title=title,
|
||||||
|
description=description,
|
||||||
|
acceptance_criteria=acceptance_criteria,
|
||||||
|
story_points=story_points
|
||||||
|
)
|
||||||
|
self.sprint.stories.append(story)
|
||||||
|
return story
|
||||||
|
|
||||||
|
def plan_sprint_workflow(self, story: UserStory) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Creates an optimized workflow DAG (Directed Acyclic Graph) for a user story:
|
||||||
|
1. PO & Architect define technical spec & contracts (Sequential)
|
||||||
|
2. Frontend & Backend developers work in parallel against the contract (Parallel)
|
||||||
|
3. QA executes tests and validates criteria (Sequential)
|
||||||
|
4. Code Reviewer audits against Definition of Done (Sequential)
|
||||||
|
"""
|
||||||
|
story_prefix = story.story_id
|
||||||
|
plan = {
|
||||||
|
"story_id": story.story_id,
|
||||||
|
"phases": [
|
||||||
|
{
|
||||||
|
"phase": "Architecture & Contracts",
|
||||||
|
"role": ScrumRole.TECH_LEAD.value,
|
||||||
|
"task_id": f"{story_prefix}_arch",
|
||||||
|
"depends_on": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"phase": "Backend Implementation",
|
||||||
|
"role": ScrumRole.BACKEND_DEV.value,
|
||||||
|
"task_id": f"{story_prefix}_backend",
|
||||||
|
"depends_on": [f"{story_prefix}_arch"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"phase": "Frontend Implementation",
|
||||||
|
"role": ScrumRole.FRONTEND_DEV.value,
|
||||||
|
"task_id": f"{story_prefix}_frontend",
|
||||||
|
"depends_on": [f"{story_prefix}_arch"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"phase": "QA & Automated Testing",
|
||||||
|
"role": ScrumRole.QA_ENGINEER.value,
|
||||||
|
"task_id": f"{story_prefix}_qa",
|
||||||
|
"depends_on": [f"{story_prefix}_backend", f"{story_prefix}_frontend"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"phase": "Code Review & Definition of Done",
|
||||||
|
"role": ScrumRole.CODE_REVIEWER.value,
|
||||||
|
"task_id": f"{story_prefix}_review",
|
||||||
|
"depends_on": [f"{story_prefix}_qa"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
return plan
|
||||||
|
|
||||||
|
def get_antigravity_subagent_specs(self) -> Dict[str, Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Returns parameters ready for Antigravity's `define_subagent` and `invoke_subagent`.
|
||||||
|
"""
|
||||||
|
specs = {}
|
||||||
|
for role, persona in ScrumAgentPersona.PROMPTS.items():
|
||||||
|
specs[role.value] = {
|
||||||
|
"name": f"scrum-{role.value}",
|
||||||
|
"role": persona["title"],
|
||||||
|
"description": f"Scrum specialist responsible for {persona['title']}",
|
||||||
|
"system_prompt": persona["system_prompt"],
|
||||||
|
"enable_write_tools": role in [
|
||||||
|
ScrumRole.FRONTEND_DEV,
|
||||||
|
ScrumRole.BACKEND_DEV,
|
||||||
|
ScrumRole.QA_ENGINEER
|
||||||
|
],
|
||||||
|
"enable_subagent_tools": role == ScrumRole.SCRUM_MASTER
|
||||||
|
}
|
||||||
|
return specs
|
||||||
@ -0,0 +1,334 @@
|
|||||||
|
"""
|
||||||
|
Workflow Management for Multi-Agent Systems
|
||||||
|
|
||||||
|
Handle workflow execution, monitoring, and optimization.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, List, Any, Optional, Callable
|
||||||
|
from enum import Enum
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowStatus(Enum):
|
||||||
|
"""Workflow execution status."""
|
||||||
|
|
||||||
|
PENDING = "pending"
|
||||||
|
RUNNING = "running"
|
||||||
|
PAUSED = "paused"
|
||||||
|
COMPLETED = "completed"
|
||||||
|
FAILED = "failed"
|
||||||
|
|
||||||
|
|
||||||
|
class TaskStatus(Enum):
|
||||||
|
"""Task execution status."""
|
||||||
|
|
||||||
|
PENDING = "pending"
|
||||||
|
RUNNING = "running"
|
||||||
|
COMPLETED = "completed"
|
||||||
|
FAILED = "failed"
|
||||||
|
SKIPPED = "skipped"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Task:
|
||||||
|
"""Task to be executed by an agent."""
|
||||||
|
|
||||||
|
task_id: str
|
||||||
|
agent: str
|
||||||
|
description: str
|
||||||
|
status: TaskStatus = TaskStatus.PENDING
|
||||||
|
result: Optional[str] = None
|
||||||
|
error: Optional[str] = None
|
||||||
|
start_time: float = field(default_factory=time.time)
|
||||||
|
end_time: Optional[float] = None
|
||||||
|
dependencies: List[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Workflow:
|
||||||
|
"""Workflow orchestration."""
|
||||||
|
|
||||||
|
workflow_id: str
|
||||||
|
name: str
|
||||||
|
tasks: Dict[str, Task] = field(default_factory=dict)
|
||||||
|
status: WorkflowStatus = WorkflowStatus.PENDING
|
||||||
|
start_time: Optional[float] = None
|
||||||
|
end_time: Optional[float] = None
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowExecutor:
|
||||||
|
"""Execute workflows with multiple agents."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize workflow executor."""
|
||||||
|
self.workflows: Dict[str, Workflow] = {}
|
||||||
|
self.execution_history: List[Dict] = []
|
||||||
|
|
||||||
|
def create_workflow(self, workflow_id: str, name: str) -> Workflow:
|
||||||
|
"""Create new workflow."""
|
||||||
|
workflow = Workflow(workflow_id=workflow_id, name=name)
|
||||||
|
self.workflows[workflow_id] = workflow
|
||||||
|
return workflow
|
||||||
|
|
||||||
|
def add_task(
|
||||||
|
self,
|
||||||
|
workflow_id: str,
|
||||||
|
task_id: str,
|
||||||
|
agent: str,
|
||||||
|
description: str,
|
||||||
|
dependencies: Optional[List[str]] = None,
|
||||||
|
) -> Task:
|
||||||
|
"""Add task to workflow."""
|
||||||
|
task = Task(
|
||||||
|
task_id=task_id,
|
||||||
|
agent=agent,
|
||||||
|
description=description,
|
||||||
|
dependencies=dependencies or [],
|
||||||
|
)
|
||||||
|
self.workflows[workflow_id].tasks[task_id] = task
|
||||||
|
return task
|
||||||
|
|
||||||
|
def execute_workflow(
|
||||||
|
self, workflow_id: str, executor_func: Callable
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Execute workflow.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
workflow_id: Workflow ID
|
||||||
|
executor_func: Function to execute tasks
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Execution results
|
||||||
|
"""
|
||||||
|
workflow = self.workflows[workflow_id]
|
||||||
|
workflow.status = WorkflowStatus.RUNNING
|
||||||
|
workflow.start_time = time.time()
|
||||||
|
|
||||||
|
executed_tasks = set()
|
||||||
|
results = {}
|
||||||
|
|
||||||
|
while len(executed_tasks) < len(workflow.tasks):
|
||||||
|
# Find ready tasks
|
||||||
|
ready_tasks = self._get_ready_tasks(workflow, executed_tasks)
|
||||||
|
|
||||||
|
if not ready_tasks:
|
||||||
|
# Check if workflow is stuck
|
||||||
|
if len(executed_tasks) > 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
for task_id in ready_tasks:
|
||||||
|
task = workflow.tasks[task_id]
|
||||||
|
task.status = TaskStatus.RUNNING
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Execute task
|
||||||
|
result = executor_func(task)
|
||||||
|
task.result = result
|
||||||
|
task.status = TaskStatus.COMPLETED
|
||||||
|
results[task_id] = result
|
||||||
|
except Exception as e:
|
||||||
|
task.error = str(e)
|
||||||
|
task.status = TaskStatus.FAILED
|
||||||
|
results[task_id] = None
|
||||||
|
|
||||||
|
task.end_time = time.time()
|
||||||
|
executed_tasks.add(task_id)
|
||||||
|
|
||||||
|
# Finalize workflow
|
||||||
|
workflow.end_time = time.time()
|
||||||
|
if all(task.status == TaskStatus.COMPLETED for task in workflow.tasks.values()):
|
||||||
|
workflow.status = WorkflowStatus.COMPLETED
|
||||||
|
else:
|
||||||
|
workflow.status = WorkflowStatus.FAILED
|
||||||
|
|
||||||
|
execution_record = {
|
||||||
|
"workflow_id": workflow_id,
|
||||||
|
"status": workflow.status.value,
|
||||||
|
"duration": workflow.end_time - workflow.start_time,
|
||||||
|
"results": results,
|
||||||
|
}
|
||||||
|
self.execution_history.append(execution_record)
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def _get_ready_tasks(
|
||||||
|
self, workflow: Workflow, executed: set
|
||||||
|
) -> List[str]:
|
||||||
|
"""Get tasks ready to execute."""
|
||||||
|
ready = []
|
||||||
|
for task_id, task in workflow.tasks.items():
|
||||||
|
if task_id not in executed and task.status == TaskStatus.PENDING:
|
||||||
|
# Check if all dependencies are complete
|
||||||
|
deps_met = all(dep in executed for dep in task.dependencies)
|
||||||
|
if deps_met:
|
||||||
|
ready.append(task_id)
|
||||||
|
|
||||||
|
return ready
|
||||||
|
|
||||||
|
def get_workflow_status(self, workflow_id: str) -> Dict[str, Any]:
|
||||||
|
"""Get workflow status."""
|
||||||
|
workflow = self.workflows[workflow_id]
|
||||||
|
return {
|
||||||
|
"id": workflow.workflow_id,
|
||||||
|
"name": workflow.name,
|
||||||
|
"status": workflow.status.value,
|
||||||
|
"tasks": {
|
||||||
|
task_id: task.status.value
|
||||||
|
for task_id, task in workflow.tasks.items()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowOptimizer:
|
||||||
|
"""Optimize workflow execution."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def analyze_dependencies(workflow: Workflow) -> Dict[str, Any]:
|
||||||
|
"""Analyze task dependencies."""
|
||||||
|
dep_graph = {}
|
||||||
|
for task_id, task in workflow.tasks.items():
|
||||||
|
dep_graph[task_id] = task.dependencies
|
||||||
|
|
||||||
|
# Find critical path
|
||||||
|
critical_path = WorkflowOptimizer._find_critical_path(
|
||||||
|
dep_graph, workflow.tasks
|
||||||
|
)
|
||||||
|
|
||||||
|
# Find parallelizable tasks
|
||||||
|
parallel_groups = WorkflowOptimizer._find_parallel_groups(dep_graph)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"dependency_graph": dep_graph,
|
||||||
|
"critical_path": critical_path,
|
||||||
|
"parallelizable_groups": parallel_groups,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _find_critical_path(dep_graph: Dict, tasks: Dict) -> List[str]:
|
||||||
|
"""Find tasks on critical path."""
|
||||||
|
# Simple implementation - actual critical path is more complex
|
||||||
|
return list(dep_graph.keys())
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _find_parallel_groups(dep_graph: Dict) -> List[List[str]]:
|
||||||
|
"""Find groups of tasks that can execute in parallel."""
|
||||||
|
groups = []
|
||||||
|
remaining = set(dep_graph.keys())
|
||||||
|
|
||||||
|
while remaining:
|
||||||
|
# Find tasks with no dependencies in remaining set
|
||||||
|
independent = [
|
||||||
|
task
|
||||||
|
for task in remaining
|
||||||
|
if not any(dep in remaining for dep in dep_graph.get(task, []))
|
||||||
|
]
|
||||||
|
if independent:
|
||||||
|
groups.append(independent)
|
||||||
|
remaining -= set(independent)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
return groups
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def estimate_execution_time(
|
||||||
|
workflow: Workflow, task_times: Dict[str, float]
|
||||||
|
) -> float:
|
||||||
|
"""Estimate total execution time."""
|
||||||
|
parallel_groups = WorkflowOptimizer._find_parallel_groups({
|
||||||
|
task_id: task.dependencies
|
||||||
|
for task_id, task in workflow.tasks.items()
|
||||||
|
})
|
||||||
|
|
||||||
|
total_time = 0
|
||||||
|
for group in parallel_groups:
|
||||||
|
group_time = max(
|
||||||
|
task_times.get(task_id, 1.0) for task_id in group
|
||||||
|
)
|
||||||
|
total_time += group_time
|
||||||
|
|
||||||
|
return total_time
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def suggest_parallelization(workflow: Workflow) -> List[Dict[str, Any]]:
|
||||||
|
"""Suggest ways to parallelize workflow."""
|
||||||
|
suggestions = []
|
||||||
|
|
||||||
|
dep_graph = {
|
||||||
|
task_id: task.dependencies
|
||||||
|
for task_id, task in workflow.tasks.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
# Find sequential chains that could be parallelized
|
||||||
|
for task_id, dependencies in dep_graph.items():
|
||||||
|
if len(dependencies) == 0:
|
||||||
|
suggestions.append({
|
||||||
|
"task": task_id,
|
||||||
|
"suggestion": "Can be parallelized with other independent tasks",
|
||||||
|
})
|
||||||
|
|
||||||
|
return suggestions
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowMonitor:
|
||||||
|
"""Monitor workflow execution."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize monitor."""
|
||||||
|
self.events: List[Dict] = []
|
||||||
|
|
||||||
|
def record_event(
|
||||||
|
self, workflow_id: str, task_id: str, event_type: str, data: Dict
|
||||||
|
) -> None:
|
||||||
|
"""Record workflow event."""
|
||||||
|
event = {
|
||||||
|
"workflow_id": workflow_id,
|
||||||
|
"task_id": task_id,
|
||||||
|
"event_type": event_type,
|
||||||
|
"timestamp": time.time(),
|
||||||
|
"data": data,
|
||||||
|
}
|
||||||
|
self.events.append(event)
|
||||||
|
|
||||||
|
def get_workflow_metrics(self, workflow_id: str) -> Dict[str, Any]:
|
||||||
|
"""Get workflow metrics."""
|
||||||
|
workflow_events = [e for e in self.events if e["workflow_id"] == workflow_id]
|
||||||
|
|
||||||
|
task_times = {}
|
||||||
|
for event in workflow_events:
|
||||||
|
task_id = event["task_id"]
|
||||||
|
if event["event_type"] == "start":
|
||||||
|
task_times[task_id] = {"start": event["timestamp"]}
|
||||||
|
elif event["event_type"] == "complete":
|
||||||
|
if task_id in task_times:
|
||||||
|
task_times[task_id]["end"] = event["timestamp"]
|
||||||
|
|
||||||
|
# Calculate durations
|
||||||
|
durations = {
|
||||||
|
task_id: times.get("end", time.time()) - times["start"]
|
||||||
|
for task_id, times in task_times.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_tasks": len(task_times),
|
||||||
|
"task_durations": durations,
|
||||||
|
"avg_duration": sum(durations.values()) / len(durations)
|
||||||
|
if durations
|
||||||
|
else 0,
|
||||||
|
"max_duration": max(durations.values()) if durations else 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_performance_report(self) -> Dict[str, Any]:
|
||||||
|
"""Get overall performance report."""
|
||||||
|
if not self.events:
|
||||||
|
return {"status": "no_events"}
|
||||||
|
|
||||||
|
workflow_ids = set(e["workflow_id"] for e in self.events)
|
||||||
|
|
||||||
|
report = {}
|
||||||
|
for workflow_id in workflow_ids:
|
||||||
|
report[workflow_id] = self.get_workflow_metrics(workflow_id)
|
||||||
|
|
||||||
|
return report
|
||||||
83
.agents/skills/security-audit/AI-AND-LLM.md
Normal file
83
.agents/skills/security-audit/AI-AND-LLM.md
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
# AI, LLM, and Agent Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when a language model participates in a trust-sensitive decision: chatbots and assistants, RAG pipelines, persistent agent memory, agent/tool-calling loops, MCP servers and clients, code that builds prompts from untrusted input, or code that consumes model output and acts on it. The important data flow is *untrusted content → model or memory → capability, authority, or sink*.
|
||||||
|
|
||||||
|
Use this alongside `ATTACK-CLASSES.md`, not instead of it. Transport, access control, query construction, filesystem use, and output rendering remain ordinary trust boundaries. This file covers the model-specific delegation layer. Split large targets by retrieval, memory, tool dispatch, MCP, and output handling.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- Prompt injection alone is not a finding. Require a code-level boundary failure: content reaches another principal's context, invokes authority the requester lacks, discloses data they cannot read, or drives a sink they cannot reach directly.
|
||||||
|
- Model output, memory, tool descriptions, and MCP responses are untrusted inputs. Point to the code that grants authority, trusts output, writes durable state, or feeds a sink.
|
||||||
|
- A guardrail prompt is not a security boundary. Count only deterministic checks, resource-scoped authorization, isolation, binding, and constrained credentials.
|
||||||
|
- State the attacker, affected principal, effective execution identity, resource, exact action, authority used, and observable impact. An intentional direct request to use the requester's existing authority is not a delegation defect merely because a model executes it.
|
||||||
|
- Authorization and action binding are separate controls. Attacker-controlled content that causes an action under an affected principal's valid authority is an action-binding failure when that principal did not intentionally request or approve the exact action.
|
||||||
|
- Classify every candidate as `confirmed` only after source evidence and bounded local validation establish the boundary and result. Use `needs_validation` when a required provider, deployment, model, renderer, or identity behavior is not observable locally.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Context, retrieval, and memory attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Indirect injection through retrieved or ingested content**
|
||||||
|
An attacker can write a RAG document, indexed page, file, email, issue body, tool response, or metadata that enters a different principal's model context. Trace who can write each source, how retrieval scopes it, whose session consumes it, and what capability is enabled there. Check isolation, resource authorization, and binding to the consuming principal's intent separately. The defect is a missing deterministic control, not persuasive text by itself.
|
||||||
|
|
||||||
|
**Cross-session or cross-tenant context bleed**
|
||||||
|
Conversation history, embeddings, retrieval results, or prompt caches are keyed too broadly. Verify tenant and ACL filters in the query itself and every cache key. A tenant field stored on an object is not enforcement if an alternate query, shared cache, or batch path omits it.
|
||||||
|
|
||||||
|
**Persistent memory poisoning**
|
||||||
|
Attacker-controlled content or model summaries are written into memory that later shapes another task, user, or privileged session. Review who may create, update, merge, and delete memory; its provenance and tenant scope; whether low-trust observations become durable instructions or facts; and whether retrieval distinguishes user preferences from tool policy. Memory intentionally saved by a user and used only for that user's intentional, allowed requests is not a cross-boundary finding.
|
||||||
|
|
||||||
|
**Prompt role and provenance confusion**
|
||||||
|
Prompt assembly lets untrusted text impersonate a system message, prior turn, tool result, policy, or memory record. Look for string concatenation, untyped history, caller-controlled role fields, and serialization round trips that lose source labels. Confirm that the forged provenance changes a deterministic trust decision or reaches a meaningful capability.
|
||||||
|
|
||||||
|
## Tool and action attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Tool-argument injection into a downstream sink**
|
||||||
|
Model-produced arguments reach SQL, shell, file, URL-fetch, or privileged APIs without handler-side validation. Treat the tool schema as input parsing, then follow each field from decoded call to sink. Structured output narrows shape; it does not establish authorization, safe paths, safe URLs, or query semantics.
|
||||||
|
|
||||||
|
**Excessive agency and confused-deputy authority**
|
||||||
|
The agent uses a service identity or broad credential, while the tool handler does not re-check the requesting principal's permission on the named resource. Verify both the effective identity and whether the caller could perform that exact operation through the normal product interface. A shared credential with enforced per-user query scope is not a defect.
|
||||||
|
|
||||||
|
**Action-confirmation and approval binding**
|
||||||
|
A user approves one described action but execution can use changed arguments, a different resource, a different principal, or a later model turn. An action-binding defect also exists when attacker-controlled content causes a side effect under a victim's valid authority without the victim's intentional request or approval, even if generic authorization permits the victim to perform it. Review whether intent or confirmation binds the normalized tool name, complete argument object, requester, target, amount, expiry, and batch membership. Check retries and resumed sessions: an approval must not authorize a mutated or duplicate side effect.
|
||||||
|
|
||||||
|
**Tool-schema and dispatcher disagreement**
|
||||||
|
The schema accepts aliases, extra fields, duplicate keys, coercions, nested free-form objects, or out-of-range values that the dispatcher or handler interprets differently. Compare schema validation, canonicalization, generated bindings, and handler defaults. Validate again where values become resource selectors or security-relevant options.
|
||||||
|
|
||||||
|
**Unbounded delegated action loops**
|
||||||
|
A bounded request can enqueue repeated spend, send, mutation, or external API work without a per-request budget, per-action authorization, cancellation, or idempotency control. Confirm impact on shared cost, quotas, other users, or durable state. Do not test by exhausting a service; use code-level accounting and a locally bounded loop.
|
||||||
|
|
||||||
|
## MCP and sub-agent trust classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Sub-agent and MCP trust inheritance**
|
||||||
|
A delegated task receives the full session, credentials, memory, or capabilities rather than the least authority required. Check the principal and tenant carried into each call, capability narrowing, credential audience, and whether delegated results are treated as untrusted on return.
|
||||||
|
|
||||||
|
**MCP server and tool identity confusion**
|
||||||
|
Calls or results are routed by attacker-influenceable server names, tool names, request IDs, resource URIs, or model-selected aliases rather than the authenticated connection and outstanding request. Check whether two servers can claim the same tool or resource identity, whether reconnect changes the binding, and whether a response from one server can satisfy another server's pending call.
|
||||||
|
|
||||||
|
**MCP metadata and schema as policy**
|
||||||
|
Tool descriptions, resource metadata, prompts, completion hints, or schemas supplied by an MCP peer are trusted as policy or authorization. These fields can guide the model but cannot grant capability. Find the deterministic allowlist, server identity check, and handler authorization that remain authoritative when metadata conflicts.
|
||||||
|
|
||||||
|
## Output and disclosure attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Insecure output rendering**
|
||||||
|
Model output reaches an executing HTML, Markdown, template, URL, or command sink without the sink's required encoding and policy. For browser rendering, verify auto-loaded resources and CSP or sanitization in `CLIENT-SIDE.md`; renderer behavior outside the repository makes the candidate `needs_validation`.
|
||||||
|
|
||||||
|
**Sensitive context extraction**
|
||||||
|
The assembled context contains credentials, another user's data, private source, or policy values that themselves grant access, and user-influenced output exposes them. Read prompt assembly and data-fetch code. Disclosure of generic instructions or behavior that does not cross a data boundary is not a finding.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Draw four maps first: each execution identity, each capability, every writable context or memory source, and each output destination. Then connect the principal at the start to the authority at the end.
|
||||||
|
- Start at side-effecting tools and work backward through dispatcher, schema, confirmation, model context, retrieval, and ingestion. Start at durable memory reads and trace every writer.
|
||||||
|
- Compare direct, queued, retry, resume, batch, and delegated paths for the same action. The strongest gate must apply after arguments are final and before every side effect.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Name the crossed boundary and observable result: attacker, affected principal or shared resource, execution identity, target, and unauthorized or unrequested action or disclosure.
|
||||||
|
2. For confused-deputy authority claims, prove the tool lacks requester-and-resource authorization and that the attacker cannot perform the same action normally. For action-binding claims, instead prove attacker-controlled content caused an action under the affected principal's authority that the principal did not intentionally request or approve. Valid generic authorization does not establish that intent.
|
||||||
|
3. For memory or retrieval claims, cite both the attacker-controlled write and the later cross-principal read or privileged decision. A shared record without a reachable consumer is not enough.
|
||||||
|
4. For action binding, establish the intentional request or normalized approved object, if any, and compare it with the object the handler uses. Confirm a locally observable unrequested action, mutation, duplicate, or authority change without extending the test into harmful execution. For schema disagreement, compare the normalized validated object with the handler's object.
|
||||||
|
5. For MCP identity claims, verify the authenticated connection, request correlation, tool namespace, and effective credential. Mark `needs_validation` if external server identity or deployment routing is required.
|
||||||
|
6. Return `confirmed` findings only with a complete source trace and meaningful result. Return `needs_validation` for a specific unresolved boundary fact and state the bounded local or owner-observed check needed to resolve it.
|
||||||
130
.agents/skills/security-audit/ATTACK-CLASSES.md
Normal file
130
.agents/skills/security-audit/ATTACK-CLASSES.md
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
# Attack Classes
|
||||||
|
|
||||||
|
#### Attack classes — choose and split based on Phase 1
|
||||||
|
|
||||||
|
Select attack classes relevant to the application type. Not every class applies to every codebase. The list below is a starting point; add application-specific classes from Phase 1 and split large codebases per subsystem. Frame work as finding, validating, fixing, and prioritizing vulnerabilities. Keep validation to source review and bounded local fixtures; do not develop payload chains, test availability on live services, or take action in shared environments.
|
||||||
|
|
||||||
|
Use `confirmed` only when source evidence and bounded validation establish the full boundary and meaningful result. Use `needs_validation` when a specific deployment, provider, platform, identity, or runtime fact is unavailable; state the missing fact and the safe owner-observed or local check that resolves it.
|
||||||
|
|
||||||
|
> **Native / binary / kernel targets** (C/C++/Rust-unsafe, kernel modules, parsers and decoders, FFI, concurrent runtimes, binary loaders, JITs, firmware): use the memory-safety, integer/ABI, concurrency, binary-loader, and privileged-interface classes in [MEMORY-SAFETY-AND-BINARY.md](MEMORY-SAFETY-AND-BINARY.md).
|
||||||
|
>
|
||||||
|
> **AI / LLM / agent targets** (chatbots, RAG, persistent memory, tool-calling agents, MCP servers/clients, prompt assembly, or model-controlled actions): use the context, memory-poisoning, action-binding, tool-schema, MCP-identity, and output classes in [AI-AND-LLM.md](AI-AND-LLM.md).
|
||||||
|
>
|
||||||
|
> **HTTP, web, and identity targets** (ordinary web apps, APIs, reverse proxies, CDNs, gateways, custom HTTP parsers, sessions, CSRF, JWT, OAuth/OIDC, SAML, MFA, passkeys, account recovery/linking, API keys, or mTLS): use [WEB-PROTOCOL-AND-AUTH.md](WEB-PROTOCOL-AND-AUTH.md).
|
||||||
|
>
|
||||||
|
> **Client-side and browser targets** (SPAs, browser extensions, embedded webviews, service workers, browser storage, cross-window messaging, CORS, WebSockets, or DOM rendering): use [CLIENT-SIDE.md](CLIENT-SIDE.md).
|
||||||
|
>
|
||||||
|
> **Supply-chain and release targets** (dependency resolution, generated inputs, CI, release/signing/promotion, updates, plugins, or extensions): use [SUPPLY-CHAIN-AND-RELEASE.md](SUPPLY-CHAIN-AND-RELEASE.md).
|
||||||
|
>
|
||||||
|
> **Cloud and deployment targets** (IAM, infrastructure as code, containers/Kubernetes, service mesh, serverless/edge, ingress, provider events, or runtime configuration): use [CLOUD-AND-DEPLOYMENT.md](CLOUD-AND-DEPLOYMENT.md).
|
||||||
|
>
|
||||||
|
> **Protocol, RPC, and messaging targets** (gRPC, GraphQL transports, Protobuf/Cap'n Proto/Thrift, custom protocols, queues, brokers, pub/sub, webhooks, or streaming RPC): use [PROTOCOLS-RPC-AND-MESSAGING.md](PROTOCOLS-RPC-AND-MESSAGING.md).
|
||||||
|
>
|
||||||
|
> **Resource-exhaustion and availability targets** (untrusted work can consume shared CPU, memory, disk, connections, workers, queues, quotas, or operator-owned spend): use [RESOURCE-EXHAUSTION-AND-AVAILABILITY.md](RESOURCE-EXHAUSTION-AND-AVAILABILITY.md).
|
||||||
|
>
|
||||||
|
> **Data-isolation and lifecycle targets** (multi-tenant stores, caches/search, object links, analytics, export/backup, migration, deletion, retention, or restore): use [DATA-ISOLATION-AND-LIFECYCLE.md](DATA-ISOLATION-AND-LIFECYCLE.md).
|
||||||
|
>
|
||||||
|
> **Desktop, mobile, and local-IPC targets** (native apps, deep links, webview bridges, exported components, privileged helpers, local daemons, Unix sockets/XPC/Binder/D-Bus): use [DESKTOP-MOBILE-AND-LOCAL-IPC.md](DESKTOP-MOBILE-AND-LOCAL-IPC.md).
|
||||||
|
|
||||||
|
**Injection** (subagent_type: `general`)
|
||||||
|
Trace untrusted input from entry point to dangerous sink. What counts as a "dangerous sink" depends on the application:
|
||||||
|
- Web apps: SQL queries, HTML output, shell commands, template engines, file paths, HTTP redirects, deserialization
|
||||||
|
- Libraries: any function that processes caller-supplied data without validation — buffer operations, parsers, format strings
|
||||||
|
- CLI tools: shell command construction, file path handling, environment variable interpolation
|
||||||
|
- Services: query construction, message serialization, log injection, LDAP/XPATH queries
|
||||||
|
- Client-side (browser/JS): DOM XSS, prototype pollution, `postMessage`/origin trust, and other browser-side classes — covered by the [CLIENT-SIDE.md](CLIENT-SIDE.md) companion blocks when selected
|
||||||
|
|
||||||
|
Do not stop at the obvious direct paths. Look for indirect injection: data stored safely, then retrieved and used in a dangerous context by different code. Look for injection through field names, keys, headers, and metadata — not just values. Look for injection into secondary systems (logs, caches, search indexes, analytics).
|
||||||
|
|
||||||
|
**Access control** (subagent_type: `general`)
|
||||||
|
Verify that a caller cannot do something outside its authority. Go beyond checking whether permission checks exist — verify they check the *right* permission for the *right* resource via the *right* mechanism:
|
||||||
|
- Is there a path to the same state change that checks a different (weaker) permission?
|
||||||
|
- Can a field in the request body override what the permission system intended to restrict?
|
||||||
|
- Are there endpoints that gate on authentication but forget authorization?
|
||||||
|
- Does the same resource have multiple access paths with inconsistent checks?
|
||||||
|
- What about bulk/batch/export/import operations — do they enforce per-item permissions?
|
||||||
|
|
||||||
|
For complex access models, split into separate agents for auth bypass vs authorization logic.
|
||||||
|
|
||||||
|
**Resource and file handling** (subagent_type: `general`)
|
||||||
|
- Path traversal (reading/writing outside intended directories) — including through symlinks, encoded sequences, and null bytes
|
||||||
|
- SSRF (making the application fetch attacker-controlled URLs) — including through redirects, DNS rebinding, and URL parser differentials
|
||||||
|
- Unsafe deserialization, archive extraction (zip slip), temp file handling
|
||||||
|
- Memory safety (if applicable): buffer overflows, use-after-free, integer overflow
|
||||||
|
- Race conditions on file operations (TOCTOU between check and use)
|
||||||
|
|
||||||
|
**Cryptography and secrets** (subagent_type: `general`)
|
||||||
|
- Weak randomness for security-critical values (tokens, keys, nonces)
|
||||||
|
- Hardcoded secrets, secrets in logs, error messages, URLs, or client-visible responses
|
||||||
|
- Broken key derivation, missing HMAC verification, nonce reuse
|
||||||
|
- Timing side-channels on secret comparison
|
||||||
|
- Misuse of crypto primitives (ECB mode, unauthenticated encryption, static IVs, etc.)
|
||||||
|
- What happens when crypto operations fail? Does the error path fall back to no-crypto?
|
||||||
|
|
||||||
|
**Business logic** (subagent_type: `general`)
|
||||||
|
Hunt logic errors by hand: standard scanners cannot find them, and they yield high-impact findings. For each major workflow:
|
||||||
|
- **State machine violations**: Can you skip steps? Go backwards? Reach an invalid state? What happens if you replay a completed flow? What about partial failure — if step 2 of 3 fails, is step 1 rolled back?
|
||||||
|
- **Race conditions with business impact**: Concurrent operations that produce invalid states (double-spend, double-approve, lost updates). Focus on operations that check-then-act non-atomically.
|
||||||
|
- **Numeric/quantity manipulation**: Negative values, zero values, overflow, precision loss, type coercion between string and number.
|
||||||
|
- **Access boundary violations**: Not "does the permission check exist" but "is it the right check for the business rule?" Can input to one operation bypass a restriction enforced on a different operation for the same effect?
|
||||||
|
- **Implicit trust assumptions**: Data from storage, config, other components, or plugins assumed safe because "we validated it on the way in." What if a different code path wrote it?
|
||||||
|
- **Time-based logic**: Expiry checks, scheduling, rate windows, clock skew. What happens at exact boundary moments? What about timezone differences between components?
|
||||||
|
- **Default and fallback behavior**: What is the security posture when config is missing? When a feature flag is off? When a dependency is unavailable? When the system is mid-migration?
|
||||||
|
|
||||||
|
**Feature abuse and data leakage** (subagent_type: `general`)
|
||||||
|
Legitimate features used for unintended purposes. Look for bugs in the design, not only in the code:
|
||||||
|
- **Export/backup as exfiltration**: Can a low-privilege user trigger an export, snapshot, or backup that includes data above their access level? Can they export other users' data? Does the export include deleted/draft/private content? Revision history that was supposed to be pruned?
|
||||||
|
- **Import/restore as injection**: Can import overwrite existing data? Can it create records that bypass normal validation? Can it inject content into collections the user has no write access to? Does it respect the same permission model as the UI?
|
||||||
|
- **Search/filter/sort as oracle**: Can search queries reveal whether content exists that the user cannot directly access? Do filter parameters let users probe statuses, roles, or fields they should not know about? Does sorting by a hidden field reveal its values through result ordering?
|
||||||
|
- **Enumeration through side effects**: Do error messages differ between "does not exist" and "no access"? Do response times differ? Response sizes? HTTP status codes? Can you enumerate users through password reset, invite, or registration flows?
|
||||||
|
- **Preview/draft/staging leakage**: Are preview tokens scoped to one item or do they unlock broader access? Can draft content be discovered through search, RSS feeds, sitemaps, or API listing endpoints? Can cache headers cause a CDN to serve private content publicly?
|
||||||
|
- **Notification/webhook as SSRF**: Can a user set a notification URL, webhook URL, or callback URL that the server fetches? Is it validated against internal networks? What about after a redirect?
|
||||||
|
|
||||||
|
**Chained vulnerabilities and trust boundaries** (subagent_type: `general`)
|
||||||
|
Individually allowed or contained behavior can become a vulnerability when another component or lifecycle step relies on a stronger guarantee:
|
||||||
|
- **Multi-step boundary failures**: Map what a low-privilege principal may read, write, invoke, and retain, then connect only concrete outputs to later trust decisions. Confirm each prerequisite and do not assume a downstream effect.
|
||||||
|
- **Cross-component trust gaps**: Component A validates input and passes it to component B. Compare the exact guarantee A produces with what B assumes, including truncation, type coercion, normalization, tenant scope, and plugin/extension access.
|
||||||
|
- **Second-order use**: Data safe when stored may become dangerous in a later context. A field name becomes a JSON path, a slug becomes a file path, escaped text enters raw rendering, or a stored string becomes a URL, regex, template, or policy expression.
|
||||||
|
- **Scope and capability growth**: Token, API-key, plugin, OAuth, MCP, or AI capabilities become broader after delegation, refresh, caching, role change, or composition. Name the concrete operation the resulting principal should not have.
|
||||||
|
- **Timing and ordering**: Review setup, migration, soft-delete, revoke/cache expiry, check/use, and validate/consume windows. Confirm stale state is accepted before reporting.
|
||||||
|
- **Rollback and recovery**: Undelete, restore, revision rollback, and cancellation must apply current ownership, validation, and authorization. Confirm which invalid state is restored.
|
||||||
|
|
||||||
|
**Wildcard** (subagent_type: `general`)
|
||||||
|
You are not given a category. Find vulnerabilities outside the standard classes already assigned.
|
||||||
|
|
||||||
|
Read code that looks boring or disconnected from security. Follow incomplete, experimental, compatibility, and fallback features, but retain the same concrete boundary and validation requirements as every other class.
|
||||||
|
|
||||||
|
Use these starting points, but do not limit yourself to them:
|
||||||
|
- What is the strangest code in the codebase? Why does it exist? What happens if it is abused?
|
||||||
|
- Are there any features that feel half-finished, experimental, or bolted on? Those have the weakest security because they got the least review.
|
||||||
|
- What happens if you use the API in a way the frontend never would? The UI constrains users, but the API does not. What API calls are possible but never made by the client?
|
||||||
|
- Are there any hidden or undocumented endpoints, parameters, headers, or features? Look at route registrations, middleware, and config for things that are not in the docs.
|
||||||
|
- What happens when you mix features that were not designed to work together? Localization + preview + caching. Import + plugins + webhooks. OAuth + impersonation + API keys.
|
||||||
|
- Is there anything interesting in the git history? Reverted security fixes, commented-out auth checks, secrets that were committed then removed (still in history).
|
||||||
|
- Which valid-account actions affect other users, shared integrity, availability, or operator-owned cost? Verify containment, quotas, authorization, and recovery around those actions.
|
||||||
|
- Which operations are irreversible or require elevated confirmation? Bind authorization and approval to the final principal, action, and resource.
|
||||||
|
- What assumptions does the code make about the environment? That the database is local, that the clock is accurate, that DNS is trustworthy, that the filesystem is case-sensitive?
|
||||||
|
- Look at the test files — what are they **not** testing? Compare the edge cases the developer thought about (tests exist) with the ones they did not (no tests).
|
||||||
|
|
||||||
|
Pursue anomalies inside your assigned scope until the invariant is settled. If something looks strange, read it until you can state whether it is safe. If a function has a comment explaining why it is safe, verify the explanation. If a variable is named `temp` or `hack` or `legacy`, read it closely.
|
||||||
|
|
||||||
|
**Obvious things** (subagent_type: `general`)
|
||||||
|
Other agents hunt subtle bugs. This agent checks the basic exposures that are easy to overlook because everyone assumes someone else already checked them:
|
||||||
|
- Are there any hardcoded passwords, API keys, tokens, or secrets in the source? (grep for `password`, `secret`, `apikey`, `token`, `Bearer`, `-----BEGIN`, common default passwords)
|
||||||
|
- Are there any TODO/FIXME/HACK/XXX comments that reference security? (`TODO: add auth`, `FIXME: validate input`, `HACK: skip permission check`)
|
||||||
|
- Is debug mode / dev mode properly gated? Can it be enabled in production via environment variable, query parameter, or header?
|
||||||
|
- Are there test/example/seed credentials that work in production?
|
||||||
|
- Is there a `/debug`, `/admin`, `/test`, `/status`, `/health`, `/metrics`, `/env`, `/.env`, `/config` endpoint that is unprotected?
|
||||||
|
- Are there any `.env`, `.env.local`, `credentials.json`, `*.pem`, `*.key` files checked into the repo?
|
||||||
|
- Does the `.gitignore` actually cover secrets, uploads, and local config?
|
||||||
|
- Are dependencies pinned? Are there known CVEs in the dependency tree? (check lockfiles)
|
||||||
|
- Are there any `eval()`, `exec()`, `child_process`, `Function()`, `vm.runInContext`, `import()` with dynamic input?
|
||||||
|
- Are CORS headers set to `*` or overly permissive? Is `Access-Control-Allow-Credentials` combined with a wildcard origin?
|
||||||
|
- Are cookies missing `HttpOnly`, `Secure`, or `SameSite` attributes?
|
||||||
|
- Are there any open redirects? (parameters named `redirect`, `return`, `next`, `url`, `goto`, `continue` that feed into redirects without validation)
|
||||||
|
- Is TLS enforced? Are there any HTTP-only endpoints?
|
||||||
|
- Are error responses in production returning stack traces, internal paths, or SQL errors?
|
||||||
|
|
||||||
|
This agent does not need to be creative. It needs to be thorough and literal. Check every item. Report each result.
|
||||||
|
|
||||||
|
**Important**: For any finding this agent reports, it must verify the full code path, not just surface appearance. If a cookie is missing `HttpOnly`, check whether the cookie contains security-sensitive data and whether JS needs to read it by design. If an error message contains a field name, check whether the field is ever actually populated with sensitive data. A flag is not a finding — trace the impact before reporting.
|
||||||
83
.agents/skills/security-audit/CLIENT-SIDE.md
Normal file
83
.agents/skills/security-audit/CLIENT-SIDE.md
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
# Client-Side and Browser Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when meaningful trust decisions or untrusted rendering happen in a browser: single-page apps, browser extensions, embedded webviews, service workers, offline applications, and code that renders attacker-influenceable content into the DOM, receives cross-window messages, or uses browser storage. These paths include sources the server never sees, such as URL fragments, `window.name`, `postMessage`, and previously cached content.
|
||||||
|
|
||||||
|
Use alongside `ATTACK-CLASSES.md`. This file covers browser sources and sinks, origin boundaries, browser persistence, and cross-site state oracles. Use `DESKTOP-MOBILE-AND-LOCAL-IPC.md` for the native side of a webview bridge, and `WEB-PROTOCOL-AND-AUTH.md` for server-side CSRF, sessions, and auth callbacks.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- A client-side candidate needs a controllable source and an executing or disclosing sink. Name both and show attacker-influenced data reaching the sink.
|
||||||
|
- The impact must reach a victim's session, another origin, or shared persistence. Self-injection and disclosure of the attacker's own data are not findings.
|
||||||
|
- Framework escaping, browser same-origin policy, CSP, COOP/CORP, service-worker scope, and modern noopener defaults are real controls. Verify them before assigning impact.
|
||||||
|
- Browser storage and caches are shared by origin and may outlive login state. Identify who writes, who reads, and which account, tenant, or worker lifecycle clears each record.
|
||||||
|
- Use `confirmed` only for complete source evidence plus bounded local browser tests. Use `needs_validation` when renderer, extension permission, deployed header, or browser-policy behavior is required but unavailable.
|
||||||
|
```
|
||||||
|
|
||||||
|
## DOM and object-state attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**DOM-based XSS**
|
||||||
|
Trace `location` fields, `document.referrer`, `window.name`, message data, storage, and browser-controlled document state into `innerHTML`, `outerHTML`, `document.write`, string-evaluating APIs, executable URLs, jQuery HTML APIs, or framework escape hatches. Interpolation escaped by the framework is not a finding.
|
||||||
|
|
||||||
|
**DOM clobbering**
|
||||||
|
Attacker-injected `id` or `name` attributes shadow a global, form property, configuration object, or initialization flag later trusted by code. Require both a markup path that preserves the attribute and a security-relevant use of the clobbered value.
|
||||||
|
|
||||||
|
**Prototype pollution and gadget chain**
|
||||||
|
An attacker-controlled key reaches a recursive write such as deep merge or path assignment and modifies prototype state. Then a reachable gadget consumes the polluted property to change authorization, execution, navigation, or rendering. `JSON.parse`, a shallow copy, or pollution without a gadget is not enough.
|
||||||
|
|
||||||
|
## Cross-origin messaging and network attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**`postMessage` origin and source trust**
|
||||||
|
A handler performs a sensitive action with `event.data` without an exact origin allowlist and, where multiple frames share an origin, the expected `event.source`. On the send side, sensitive data sent to `*` reaches an unintended embedder. Weak substring, prefix, suffix, or unanchored-regex origin matching is not an origin check.
|
||||||
|
|
||||||
|
**Cross-site WebSocket request use**
|
||||||
|
A WebSocket upgrade accepts ambient cookies from an untrusted origin without an `Origin` check or channel-specific token, allowing the victim's session to read or mutate data. Confirm both the upgrade behavior and a security-relevant message handler.
|
||||||
|
|
||||||
|
**Credentialed CORS trust**
|
||||||
|
The server reflects or weakly matches `Origin` while allowing credentials and returns sensitive responses. A bare wildcard with credentials is rejected by browsers; report only the actual reflected/allowed origin path and cross-origin data or mutation.
|
||||||
|
|
||||||
|
## Service-worker and browser-storage attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Service-worker registration and scope takeover**
|
||||||
|
Attacker-influenceable content can become the registered worker script, control a path that receives an over-broad `Service-Worker-Allowed` scope, or alter update imports without integrity control. Verify the final script URL, response MIME type, origin, scope, and who controls every imported script. A normal same-origin worker with intended scope is not a defect.
|
||||||
|
|
||||||
|
**Service-worker cache and identity confusion**
|
||||||
|
The worker caches personalized responses without including account, tenant, authorization state, or request mode in its policy, then serves them after account switch or logout. Review fetch-event routing, cache names and keys, navigation fallbacks, cache cleanup, and whether error/offline paths return another user's prior response.
|
||||||
|
|
||||||
|
**Browser-storage disclosure and stale authorization**
|
||||||
|
Tokens, private responses, draft data, or authorization decisions remain in `localStorage`, `sessionStorage`, IndexedDB, Cache Storage, extension storage, or client state and become readable by another account or less-trusted same-origin component. Storage of a token alone is not a finding; require a realistic reader with less authority, or continued use after revocation/logout.
|
||||||
|
|
||||||
|
**Cross-context storage and broadcast confusion**
|
||||||
|
`storage` events, `BroadcastChannel`, shared workers, or origin-wide caches carry identity or commands between tabs without binding them to the current session. Check account switching, private/public windows, tenant changes, and stale tabs that can overwrite newer auth state.
|
||||||
|
|
||||||
|
## Cross-site information leak classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**XS-Leaks and cross-origin state oracles**
|
||||||
|
An attacker page can distinguish protected cross-origin state through resource load/error events, frame or window state, redirect behavior, timing, cache state, or response size while the browser attaches victim credentials. Require one concrete secret-bearing predicate such as whether a private object, role, or account exists. Generic timing variance or public-resource availability is not a finding.
|
||||||
|
|
||||||
|
**Window and opener state disclosure**
|
||||||
|
A cross-origin window's permitted metadata or navigation result reveals protected state, or a retained opener/named-window relationship lets an attacker-controlled page influence a privileged navigation. Check COOP, frame protections, `noopener`, exact origin, and whether the observable state is confidential.
|
||||||
|
|
||||||
|
## UI-redress and navigation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Clickjacking**
|
||||||
|
A framed, state-changing action lacks effective `frame-ancestors`, `X-Frame-Options`, or equivalent UI isolation. Require the sensitive action and confirm it can complete in the framed state; missing headers on read-only content are hardening notes.
|
||||||
|
|
||||||
|
**Client-side navigation confusion**
|
||||||
|
A client source controls redirect or navigation without scheme and destination policy, including executable `javascript:` or `data:` destinations. Reverse tabnabbing applies only where code explicitly keeps `window.opener`, uses `window.open` without isolation, or supports a browser without implicit `noopener`.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Start from DOM, navigation, worker, message, and storage sinks, then trace backward to browser-only and server-controlled sources. Record the browser policy that should stop the path.
|
||||||
|
- Test account switch, logout, worker update, offline fallback, and stale-tab state with a local test origin and dummy accounts. Do not use production users, origins, or shared services.
|
||||||
|
- For XS-Leaks, list only predicates proved by source and local browser behavior. Then identify the response headers or rendering choice that would remove the oracle.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Cite the source, sink, browser policy, affected origin/session, and observable mutation or disclosure.
|
||||||
|
2. For prototype pollution, prove the recursive write and a security-relevant gadget. For DOM clobbering, prove the markup survives and the shadowed value is used.
|
||||||
|
3. For service workers and storage, prove lifecycle reachability: an attacker-controlled write or cache entry must reach a different account, tenant, or later authorization state.
|
||||||
|
4. For messaging, CORS, WebSocket, and XS-Leaks, show exact origin/source validation and the protected state or action exposed. Confirm that CSP, COOP/CORP, cookies, and SameSite policy do not already block it.
|
||||||
|
5. Return `confirmed` findings only with a complete client path and bounded local evidence. Return `needs_validation` with the precise deployed header, extension permission, browser version, or renderer behavior an owner must verify.
|
||||||
86
.agents/skills/security-audit/CLOUD-AND-DEPLOYMENT.md
Normal file
86
.agents/skills/security-audit/CLOUD-AND-DEPLOYMENT.md
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
# Cloud and Deployment Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the repository defines cloud identity, infrastructure, containers, Kubernetes, service mesh, serverless functions, edge workers, ingress, object storage, managed services, or environment-specific configuration. This domain asks whether deployed components receive the intended identity, isolation, network reachability, secrets, and policy. Source often expresses intent rather than live fact, so separate source-confirmed defects from deployment validation needs.
|
||||||
|
|
||||||
|
Use `SUPPLY-CHAIN-AND-RELEASE.md` for build and promotion trust, `WEB-PROTOCOL-AND-AUTH.md` for HTTP proxy semantics, and `DATA-ISOLATION-AND-LIFECYCLE.md` for data-store tenant scope.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- Do not infer a live exposure from a manifest alone. Establish which environment consumes it, what defaults or overlays modify it, and whether the source path is active.
|
||||||
|
- Map each workload's identity to specific operations and resources. Broad policy is a finding only when lower-trust input can reach an unauthorized action.
|
||||||
|
- Ingress, proxies, service mesh, metadata services, and admission policy are real boundaries, but only count a control when its configuration and attachment are visible.
|
||||||
|
- Secret references are not secret disclosure. Require a lower-trust reader, output, artifact, log path, or unsafe fallback.
|
||||||
|
- Use `confirmed` for active in-repo configurations and local rendering/policy validation. Use `needs_validation` for account policy, network attachment, runtime admission, hosted metadata, or drift that needs owner observation.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Workload identity and IAM attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Workload identity overreach**
|
||||||
|
A workload, pod, function, edge worker, or node identity can act on tenants, accounts, resources, or APIs beyond its role, and untrusted request or job input selects that target. Review cloud policy conditions, resource patterns, service-account attachment, namespace mapping, and fallback credentials.
|
||||||
|
|
||||||
|
**Cross-account or cross-tenant role confusion**
|
||||||
|
Role assumption, external IDs, token exchange, workload federation, or resource policies accept identity claims not bound to the intended source account, audience, repository, namespace, or workload. Establish both trust policy and caller-controlled claim.
|
||||||
|
|
||||||
|
**Application authorization delegated to cloud metadata**
|
||||||
|
An app trusts caller-supplied identity headers, tags, labels, account IDs, or resource metadata without verifying they came from the cloud control plane or a trusted proxy. Cloud IAM and application authorization are separate checks.
|
||||||
|
|
||||||
|
## Ingress, network, and control-plane attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Unexpected service or management-plane reachability**
|
||||||
|
An ingress, service, listener, security group, load-balancer annotation, port mapping, or server bind exposes an admin, debug, metrics, node, control-plane, or internal API to a lower-trust network. Missing network controls alone are `needs_validation`; a repository-controlled public route to a sensitive handler can be `confirmed`.
|
||||||
|
|
||||||
|
**Trusted-proxy and mesh identity bypass**
|
||||||
|
A backend accepts forwarded identity, mTLS subject, or authorization metadata from peers outside the intended ingress/sidecar, or an alternate port and health/legacy path bypasses the mesh. Verify header stripping, peer reachability, and fail-open behavior when the proxy is absent.
|
||||||
|
|
||||||
|
**Metadata and internal-service reachability**
|
||||||
|
An untrusted URL, destination, or protocol selection reaches instance/container metadata, control-plane sockets, or internal APIs with workload credentials. Trace URL parsing and redirect handling under `ATTACK-CLASSES.md`; here establish deployed network, metadata-version, and identity boundaries.
|
||||||
|
|
||||||
|
## Container and orchestration attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Host or control-plane capability exposure**
|
||||||
|
A lower-trust workload can select privileged mode, capabilities, host namespaces, host paths, device mounts, container runtime sockets, or service-account tokens that cross into node/control-plane authority. Bare absence of seccomp or read-only filesystem is hardening unless a reachable operation crosses that boundary.
|
||||||
|
|
||||||
|
**Admission and policy path inconsistency**
|
||||||
|
One deployment route enforces image identity, namespace, resource, secret, or privilege policy while another controller, job, upgrade, restore, or compatibility path does not. Confirm the alternate route and resulting deployed object.
|
||||||
|
|
||||||
|
**Namespace and label trust confusion**
|
||||||
|
Network, admission, secret, or workload-identity policy relies on labels, annotations, names, or namespaces that a less-trusted principal can set. Compare who controls selectors with what authority matching grants.
|
||||||
|
|
||||||
|
## Configuration and secret lifecycle attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Security-control precedence drift**
|
||||||
|
Development values, chart defaults, environment variables, command-line flags, feature gates, sidecar injection, or per-region overlays disable authentication, transport security, tenant scoping, or audit policy in a deployed environment. Render the final configuration for each maintained deployment, not just the base file.
|
||||||
|
|
||||||
|
**Secret exposure across workload boundaries**
|
||||||
|
Secrets enter logs, crash reports, process arguments, shared environment, broad volumes, build outputs, service discovery, or read APIs accessible to another workload or tenant. Check secret type and authority; a public endpoint or key ID is not a credential.
|
||||||
|
|
||||||
|
**Credential renewal and outage fallback**
|
||||||
|
Failure to mount, refresh, rotate, or revoke a workload credential causes stale credentials to remain active or an app to accept a less trusted identity mode. Review startup, readiness, reconnect, and cached-client behavior.
|
||||||
|
|
||||||
|
## Managed storage, events, and edge attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Object and signed-URL policy confusion**
|
||||||
|
Bucket/container policy, object keys, CDN origins, or signed URLs fail to bind principal, operation, object namespace, audience, or expiry. Review list/version operations and write paths as well as reads.
|
||||||
|
|
||||||
|
**Event-source identity confusion**
|
||||||
|
A function or worker trusts event body fields as source identity without validating provider-signed envelope, subscription/topic, account, region, and replay state. Compare push, pull, retry, and dead-letter paths.
|
||||||
|
|
||||||
|
**Edge/runtime boundary mismatch**
|
||||||
|
An edge or serverless runtime assumes a secret, API, filesystem, isolation, or tenant policy that differs from the origin runtime, and fallback to origin changes authority or cache behavior. Confirm which configuration selects each path.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Render every maintained environment and make a matrix of external port, workload identity, network peers, mounted secrets, and cloud resources. Differences require an owner or policy explanation.
|
||||||
|
- Follow a lower-trust request, object, label, or event into cloud policy. Show which workload credential performs the final operation and what condition should scope it.
|
||||||
|
- Diff normal deploy, migration, restore, node maintenance, failover, and local/emulator paths. Review behavior when mesh, admission, identity, secret, or policy service is unavailable.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Establish the active source path and effective deployment object; otherwise use `needs_validation` and state which rendered manifest or owner-observed attachment is missing.
|
||||||
|
2. Name the lower-trust caller/workload, cloud or application identity, controllable selector, affected resource, and unauthorized operation or disclosure.
|
||||||
|
3. Verify provider and orchestrator defaults at the pinned version. Do not assume a public IP, reachable metadata service, permissive firewall, or absent admission attachment.
|
||||||
|
4. Local validation may render templates, evaluate policy, inspect container/user namespaces in an isolated fixture, or run an emulator with dummy identities. Do not probe live endpoints or alter shared cloud resources.
|
||||||
|
5. Return `confirmed` only with a complete active source trace and concrete boundary result. Return `needs_validation` with the exact deployed policy, identity attachment, overlay, network, or drift observation needed.
|
||||||
@ -0,0 +1,84 @@
|
|||||||
|
# Data Isolation and Lifecycle Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the target stores multi-tenant or access-controlled data, derives search/index/cache/analytics copies, issues object links, exports or restores records, migrates schemas, or promises deletion, revocation, and retention behavior. This domain follows one data item through every copy and state transition. Use `ATTACK-CLASSES.md` for endpoint-level access control and `CLOUD-AND-DEPLOYMENT.md` for provider-level storage policy.
|
||||||
|
|
||||||
|
Split large targets by primary storage, cache/search, object/blob storage, analytics/logging, export/backup, deletion/revocation, and migration.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- A tenant or owner field on a record is not isolation. Find the query, key, path, policy, or row-level control that enforces it for each read and write path.
|
||||||
|
- Trace derived copies. Sanitized primary data can become unsafe in search, cache, analytics, export, previews, logs, replicas, and backups with different ACL and retention rules.
|
||||||
|
- Deletion and revocation are lifecycle contracts. Check current, historical, cached, indexed, exported, restored, and queued copies within the product's stated boundary.
|
||||||
|
- Privacy or retention preference is not automatically a security vulnerability. Require an explicit data-access boundary or deletion/revocation guarantee and an unauthorized reader or later operation.
|
||||||
|
- Use `confirmed` for complete source-visible lineage and bounded dummy-tenant tests. Use `needs_validation` when external storage policy, retention, CDN behavior, replica lag, or backup access is unavailable.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tenant and object-isolation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Missing tenant or owner enforcement**
|
||||||
|
A read, update, delete, list, count, or bulk query identifies an object without binding it to the authenticated tenant/owner, or trusts body fields to supply that identity. Compare direct lookup, nested relationship, background, admin, import, and legacy paths.
|
||||||
|
|
||||||
|
**Composite-key and namespace collision**
|
||||||
|
Cache keys, object paths, database uniqueness, search document IDs, temporary files, or deduplication keys omit tenant or environment. Two principals can overwrite or retrieve the same logical key even though application records carry separate owners.
|
||||||
|
|
||||||
|
**Policy and query disagreement**
|
||||||
|
Row-level policy, ORM default scopes, authorization filters, and raw/bypass clients apply different predicates. Check joins, aggregates, aliases, views, transactions, `unscoped` or service clients, and error paths where context is missing.
|
||||||
|
|
||||||
|
**Blob and signed-reference overreach**
|
||||||
|
Object keys, attachment IDs, version IDs, shared links, or signed URLs permit operations or namespaces beyond the issuing principal's access, or remain valid after the underlying ACL changes. Bind operation, exact object/version, audience, expiry, and tenant.
|
||||||
|
|
||||||
|
## Derived-data and disclosure attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Search, cache, and index ACL drift**
|
||||||
|
A primary record's ACL or lifecycle changes without invalidating a searchable, cached, embedded, thumbnail, RSS, preview, or index copy. Validate filtering at retrieval time as well as document ingestion and invalidation.
|
||||||
|
|
||||||
|
**Analytics, logs, traces, and diagnostics as alternate readers**
|
||||||
|
Private content or credentials are emitted into systems with broader access, longer retention, or tenant mixing. Confirm the data class and realistic reader; field names, public identifiers, and operator-only content under intended policy are not enough.
|
||||||
|
|
||||||
|
**Enumeration and aggregate oracles**
|
||||||
|
Counts, filters, ordering, errors, unique constraints, timings, notification behavior, or existence checks disclose protected object or account state. Require a concrete confidential predicate and observable distinction, not general response variance.
|
||||||
|
|
||||||
|
## Export, backup, restore, and migration attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Export and backup scope expansion**
|
||||||
|
An export, snapshot, portability package, report, or backup includes other tenants, inaccessible object fields, soft-deleted data, secret values, or history above the requester's access. Check per-item authorization after selection and authorization to download the final artifact.
|
||||||
|
|
||||||
|
**Import and restore authority expansion**
|
||||||
|
Restore/import bypasses owner, schema, ACL, uniqueness, or validation rules, overwrites existing resources, or recreates records in a tenant the requester cannot write. Validate archive contents as untrusted and authorize the resulting operation rather than trusting prior provenance.
|
||||||
|
|
||||||
|
**Migration default and ownership confusion**
|
||||||
|
Old records lack tenant/ACL/lifecycle fields, incompatible IDs collide, or partial rollout makes new and old readers apply different defaults. Review backfill, dual-read/write, compatibility, rollback, and resumed-migration paths.
|
||||||
|
|
||||||
|
**Backup and replication boundary drift**
|
||||||
|
Encryption keys, storage accounts, cross-region replicas, restoration environments, or support snapshots have broader identity or tenant scope than primary data. Source can confirm only in-repo policy; hosted access and retention require `needs_validation`.
|
||||||
|
|
||||||
|
## Deletion, revocation, and lifecycle attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Soft-delete and tombstone bypass**
|
||||||
|
Direct lookup, search, relation traversal, object link, background processor, or restore ignores the lifecycle predicate and returns or acts on a deleted/revoked record. Check whether soft-deleted identifiers can be re-registered before all references are gone.
|
||||||
|
|
||||||
|
**Stale authorization and derived copy use**
|
||||||
|
Membership removal, ACL update, consent withdrawal, secret revocation, or role downgrade does not invalidate sessions, caches, subscriptions, jobs, or materialized data that continue to authorize future operations.
|
||||||
|
|
||||||
|
**Retention and queued-work overrun**
|
||||||
|
Deletion completes in primary storage while queued processors, retries, exports, analytics, or generated artifacts recreate or retain the data beyond the promised boundary. Find idempotent deletion and tombstone propagation.
|
||||||
|
|
||||||
|
**Restore reintroduces invalid state**
|
||||||
|
Backup, undo, undelete, or replica recovery restores data, credentials, memberships, or permissions that current policy no longer allows. Re-authorize restored state and reapply lifecycle changes made after the snapshot.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Pick one protected record and draw primary write, query, cache, index, event, export, backup, deletion, and restore paths. Mark principal and tenant at every edge.
|
||||||
|
- Compare two dummy tenants through the same local service methods, then repeat after ACL change, deletion, account switch, and restore. Do not use real user data.
|
||||||
|
- Start at bypass clients, background jobs, migrations, global uniqueness, and cache keys. These paths commonly omit request-scoped identity that interactive endpoints carry.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Name attacker or lower-trust principal, protected data/state, affected owner/tenant, alternate copy or operation, and unauthorized disclosure or mutation.
|
||||||
|
2. Cite both intended source-of-truth policy and the path that omits or disagrees with it. Confirm another layer does not enforce the same tenant/lifecycle condition.
|
||||||
|
3. Use local dummy tenants and non-sensitive fixtures to prove cross-scope access or stale lifecycle behavior. Stop at the minimum observable record or operation.
|
||||||
|
4. If external cache, object storage, replicas, analytics, backup, or retention policy is required, classify `needs_validation` and state the owner-observed check.
|
||||||
|
5. Return `confirmed` only with complete lineage and concrete boundary impact. Return `needs_validation` with the exact unresolved storage, ACL, invalidation, retention, or restore fact.
|
||||||
@ -0,0 +1,89 @@
|
|||||||
|
# Desktop, Mobile, and Local IPC Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the target is a desktop or mobile app, privileged helper, updater, local daemon, webview host, deep-link handler, browser native-messaging host, or local IPC client/server. Relevant untrusted actors may be a downloaded document, remote web content, another local app, another OS user, a sandboxed process, or a lower-privilege account. State that starting capability instead of treating all local users as equivalent.
|
||||||
|
|
||||||
|
Use `CLIENT-SIDE.md` for browser-side webview behavior, `MEMORY-SAFETY-AND-BINARY.md` for native memory and loader safety, and `SUPPLY-CHAIN-AND-RELEASE.md` for update authenticity.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- Establish the realistic local or remote-content attacker: another app, another OS user, a sandboxed child, an untrusted document, or a remote origin. Self-harm within the same account and authority is not a boundary violation.
|
||||||
|
- Paths, process names, bundle/package IDs, and claimed sender fields are not peer authentication. Use OS peer credentials, code identity, capability handles, or protected channel state.
|
||||||
|
- The native bridge or helper must authorize each operation and final resource after parsing. A trusted UI or broker does not make attacker-influenceable arguments trusted.
|
||||||
|
- OS sandbox, signing, entitlements, permissions, keychain ACLs, exported-component policy, and prompt behavior are real controls when pinned and visible.
|
||||||
|
- Use `confirmed` for source evidence plus bounded local/emulator tests. Use `needs_validation` when signing, manifest merge, OS version, device policy, installer ACL, or packaging is required but not observable.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deep-link, callback, and navigation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Custom-scheme and deep-link ambiguity**
|
||||||
|
Another app or page can invoke a route that mutates state, imports data, completes authentication, or selects an account without a current-session and one-time callback binding. Review URI normalization, duplicate query fields, scheme/host/path matching, exported activity/handler policy, and stale/replayed links.
|
||||||
|
|
||||||
|
**App and account handoff confusion**
|
||||||
|
OAuth, SSO, magic-link, invite, device pairing, passwordless, or payment callbacks return to the wrong installed app, profile, tenant, or pending transaction. Bind state to the initiating app identity, current session, account, provider, operation, and expiry.
|
||||||
|
|
||||||
|
**File-open and intent authority confusion**
|
||||||
|
An associated file, share intent, drag/drop item, pasteboard/clipboard record, notification action, or open-file event triggers a privileged operation without confirming content type, sender trust where applicable, current user intent, and final target.
|
||||||
|
|
||||||
|
## Webview and native-bridge attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Navigation-origin to bridge confusion**
|
||||||
|
Remote or attacker-controlled frames can reach a JavaScript/native bridge intended only for packaged content. Validate origin at call time and after every navigation, redirect, subframe creation, popup, and error/fallback page. URL-prefix checks and initial-load checks are insufficient.
|
||||||
|
|
||||||
|
**Over-broad native bridge capabilities**
|
||||||
|
Web content can select arbitrary files, commands, IPC methods, credentials, or system actions through a generic bridge. Check method allowlists, normalized arguments, user/tenant authority, gesture/confirmation requirements, and return-value disclosure.
|
||||||
|
|
||||||
|
**Webview file and universal access**
|
||||||
|
Remote content can read app-local files, privileged custom schemes, or internal origins because file access, universal access, mixed content, debug interfaces, or custom protocol handlers join origins unexpectedly. Missing a restrictive setting without reachable protected content is hardening.
|
||||||
|
|
||||||
|
## Local IPC and exported-component attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**IPC peer-authentication gaps**
|
||||||
|
Unix sockets, named pipes, XPC, Binder, D-Bus, native messaging, RPC, shared memory, or loopback listeners accept a lower-trust peer without checking OS credentials, code identity, sandbox token, or channel ownership. Require a meaningful method or disclosure behind the channel.
|
||||||
|
|
||||||
|
**Claimed principal versus channel identity**
|
||||||
|
The authenticated process/channel belongs to one app or user, but request fields select another user, tenant, profile, or capability. Bind each method and resource to the peer credential rather than a caller-declared identifier.
|
||||||
|
|
||||||
|
**Exported service, activity, receiver, or provider overreach**
|
||||||
|
A mobile component or local automation endpoint is externally invokable and performs an operation intended for the app itself. Review final merged manifests, intent filters, permission/signature level, path grants, and alternate aliases. Manifest status unknown after packaging requires `needs_validation`.
|
||||||
|
|
||||||
|
**IPC lifecycle and correlation confusion**
|
||||||
|
Predictable request IDs, reused handles, stale channels, inherited descriptors, world-writable socket paths, or restart behavior lets one peer answer, cancel, or reuse another peer's operation. Review creation permissions and cleanup of socket files, locks, ports, and shared mappings.
|
||||||
|
|
||||||
|
## Privileged-helper and local-file attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Privileged helper as confused deputy**
|
||||||
|
A low-privilege caller can select a privileged command, file, service, user, or system setting without per-operation authorization. Review sudo/polkit/UAC/XPC helper rules and ensure the helper independently validates normalized arguments.
|
||||||
|
|
||||||
|
**Install, update, and repair path trust**
|
||||||
|
A privileged installer/helper reads manifests, scripts, packages, symlinks, working directories, or repair state writable by a lower-trust actor after authorization. Bind authorization to immutable content and safe destination paths.
|
||||||
|
|
||||||
|
**Local file ownership and TOCTOU**
|
||||||
|
The app checks a file/path then follows replacement, symlink, mount, or case/normalization changes during a privileged read/write. Use descriptor-relative operations and verify final ownership. Focus `MEMORY-SAFETY-AND-BINARY.md` on parsing after the file is opened.
|
||||||
|
|
||||||
|
**Credential-store and local-secret boundary mismatch**
|
||||||
|
A keychain/keystore item, token file, backup, log, clipboard, notification preview, or local config is readable by another app/profile/user with less authority. Plaintext readable only by the same intended OS account is not automatically a vulnerability; state the lower-trust reader and credential power.
|
||||||
|
|
||||||
|
## Application-state and device-lifecycle attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Account switch, logout, and device restore leakage**
|
||||||
|
Cached data, background tasks, widgets, notifications, local databases, webview storage, or biometric approvals survive logout/account change and appear under a later account. Review backup/restore and multi-profile behavior.
|
||||||
|
|
||||||
|
**Pending-action and user-presence confusion**
|
||||||
|
Notification, widget, shortcut, share sheet, biometric prompt, or deferred operation authorizes a different action than displayed, executes after expiry, or uses another profile's pending state. Bind confirmation to normalized action, resource, account, and current foreground state.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Enumerate every process, app component, local endpoint, URI scheme, file association, webview origin, and helper. Record OS identity, runtime privilege, caller, and callable operation.
|
||||||
|
- Read final packaging inputs: merged manifest, entitlements, installer rules, native-messaging registration, protocol handlers, and ACL creation. Source declarations can be overwritten downstream.
|
||||||
|
- Validate with dummy profiles and non-sensitive local fixtures on an isolated machine/emulator. Do not interact with other users' apps, credentials, or production services.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Name the attacker starting capability, OS/app principal crossed, entry channel, accepted argument or state, and unauthorized operation or disclosure.
|
||||||
|
2. Confirm OS sandbox, peer credential, signing, entitlement, permission, user-consent, and installer controls that apply. Unknown packaging/runtime facts require `needs_validation`.
|
||||||
|
3. For webview bridges, cite both navigation/origin control and privileged native sink. For IPC, cite peer authentication and per-resource authorization. For helpers, verify final normalized destination.
|
||||||
|
4. Keep local tests bounded and use dummy content/accounts. Stop after proving the boundary result; do not extend proof into persistence or broader system modification.
|
||||||
|
5. Return `confirmed` only with a complete source and local evidence chain. Return `needs_validation` with the exact OS, manifest, signing, ACL, or device-lifecycle fact required.
|
||||||
251
.agents/skills/security-audit/HUNTING.md
Normal file
251
.agents/skills/security-audit/HUNTING.md
Normal file
@ -0,0 +1,251 @@
|
|||||||
|
# Vulnerability Hunting
|
||||||
|
|
||||||
|
### Phase 2: Run coverage-led hunting waves
|
||||||
|
|
||||||
|
The parent assigns `planned` ledger units to `general` agents. Use enough focused hunters to cover the units without combining unrelated boundaries. One hunter may own closely related units in one subsystem; no unit may be silently unassigned because of an agent-count limit — a unit the budget cannot reach is explicitly `deferred` with reason `budget_cannot_reserve_critics_and_validation`.
|
||||||
|
|
||||||
|
When a budget or profile caps hunter count, assign units in priority order and record the ordering rationale in the ledger. Rank by: (1) unauthenticated or lowest-trust entry surfaces before authenticated ones; (2) boundaries protecting the most valuable resources (credentials, cross-tenant data, code execution, release authority); (3) prior-run gaps, revalidation targets, and changed source before same-source re-passes; (4) units whose class historically yields confirmed findings for this target type over speculative ones. Ties break lexicographically by `coverage_id` so runs stay deterministic.
|
||||||
|
|
||||||
|
Before launch, the parent changes assigned units to `in_progress`, sets a canonical lowercase `agent_id`, and creates that agent's `scratch/` and parent-owned `artifacts/`. Hunters read source and parent-provided context, write only to their unique `scratch/`, and return one structured result through the Task tool. They never write retained artifacts or edit target source, `architecture.md`, `coverage-ledger.json`, `findings.json`, or another agent's files.
|
||||||
|
|
||||||
|
## Required hunter prompt
|
||||||
|
|
||||||
|
Every hunter prompt contains these parts in this order:
|
||||||
|
|
||||||
|
1. A two-sentence role preamble: the hunter's goal is to find source-grounded security invariant failures in its assigned units, and it must return exactly one JSON object matching the structured-result contract at the end of this prompt.
|
||||||
|
2. `architecture.md` verbatim.
|
||||||
|
3. Assigned coverage IDs, subsystem, boundary, repository-relative starting paths, and each unit's assignment block map from `coverage-ledger.json`.
|
||||||
|
4. The exact selected blocks, copied verbatim: each selected ordinary attack-class block from `ATTACK-CLASSES.md`, and from each selected companion its `Core discipline`, each chosen attack-class subsection, `Universal moves`, and `Validation rules`. Ordinary blocks are self-contained and carry no companion-style `Core discipline`, `Universal moves`, or `Validation rules` sections. Do not send block or companion names alone.
|
||||||
|
5. Explicit excluded ordinary and companion blocks with a reason for each exclusion.
|
||||||
|
6. The core hunting method below, followed by the promotion procedure block.
|
||||||
|
7. The core validation rules below.
|
||||||
|
8. Carried same-source prior confirmed exclusions, each limited to fingerprint, title, and root cause, plus peer-owned current coverage IDs that this hunter must not duplicate.
|
||||||
|
9. The unique scratch/artifact paths, safe agent ID, predeclared promotion allowlist and byte limits, and the structured-result contract, including the Structured hunter result block below and the `confirmed` and `needs_validation` branches of `report-schema.json` copied verbatim.
|
||||||
|
|
||||||
|
A prompt may select several companion blocks when the same path crosses several domains. Keep their constraints together. Scope is the hunter's coverage obligation, not permission to duplicate excluded work. If an unexpected different boundary appears, return it under `uncovered` so the parent creates a stable ledger unit and assigns it in the next wave.
|
||||||
|
|
||||||
|
#### Core hunting method — include in every hunter prompt
|
||||||
|
|
||||||
|
```text
|
||||||
|
## Defensive vulnerability-finding method
|
||||||
|
|
||||||
|
Your goal is to find source-grounded security invariant failures and the smallest fix,
|
||||||
|
not to expand harm beyond the boundary result. Stay within source review and bounded local execution.
|
||||||
|
Do not contact deployed endpoints, provider APIs, registries, identity systems,
|
||||||
|
message brokers, shared services, or other users. Use local dummy data only.
|
||||||
|
|
||||||
|
READ THE CODE AT DEPTH. Follow each assigned input through parsing, identity,
|
||||||
|
authorization, normalization, state, derived copies, and the final sink. Read sibling,
|
||||||
|
legacy, batch, retry, cancellation, migration, and error paths that produce the same
|
||||||
|
effect. Compare sibling controls for equivalence, not only presence, and compare what
|
||||||
|
one component guarantees with what the next component assumes.
|
||||||
|
|
||||||
|
WORK FROM A CONCRETE INVARIANT:
|
||||||
|
1. Name the lower-trust principal and starting capability.
|
||||||
|
2. Name the accepted value, action, state transition, or resource selector.
|
||||||
|
3. Locate the control that should reject, bind, isolate, limit, or revoke it.
|
||||||
|
4. Trace the exact source path after that decision.
|
||||||
|
5. Stop at the smallest affected dummy record, wrong return value, process-integrity
|
||||||
|
effect, or locally observable shared-resource effect.
|
||||||
|
6. State a source-level change and regression case that enforce the invariant.
|
||||||
|
|
||||||
|
DEPTH BOUND: trace only paths that can reach your assigned boundary or whose
|
||||||
|
guarantees that boundary relies on. Stop a line of investigation as soon as the
|
||||||
|
invariant is settled either way, and record the result in your structured output —
|
||||||
|
a covered, candidate, or blocked disposition, or an `uncovered` entry — instead of
|
||||||
|
continuing to search.
|
||||||
|
|
||||||
|
TEST SAD PATHS AND DISAGREEMENTS. Check absent, empty, zero, negative, maximum,
|
||||||
|
over-limit, duplicate, mixed encoding, stale, revoked, reordered, concurrent,
|
||||||
|
partially migrated, failed dependency, and rollback state only where the interface
|
||||||
|
accepts them. Compare canonicalization and units at every parser or policy handoff.
|
||||||
|
For multi-step issues, treat each output as a prerequisite and do not assume a later
|
||||||
|
boundary. If any prerequisite is not established, record a blocker.
|
||||||
|
|
||||||
|
When a proposed high or critical candidate reveals a reusable root cause, search paths
|
||||||
|
owned by the assigned coverage IDs for lexical, structural, and logical variants.
|
||||||
|
Consolidate the same root cause, but establish each variant's conditions and impact
|
||||||
|
independently. Do not investigate peer-owned units. Return a variant with no current
|
||||||
|
coverage unit as `uncovered`.
|
||||||
|
|
||||||
|
USE THE NARROWEST LOCAL CHECK THAT SETTLES THE CLAIM. Target-controlled builds,
|
||||||
|
tests, processes, browsers, emulators, fuzzers, and fixture processing may run only
|
||||||
|
inside the parent-approved OS-enforced sandbox. It must disable external networking,
|
||||||
|
start from an empty allowlisted environment, expose target and tools read-only, permit
|
||||||
|
writes only to your scratch directory, and apply low CPU, memory, process, file-size,
|
||||||
|
disk, and wall-clock limits. Isolated loopback is allowed only for a local fixture.
|
||||||
|
If any control is unavailable, do not execute: return needs_validation with that exact
|
||||||
|
blocker. Prefer an existing unit test, minimal function harness, dummy-tenant service
|
||||||
|
call, small malformed fixture, deterministic race schedule, or locally rendered policy.
|
||||||
|
Do not install or fetch tools.
|
||||||
|
|
||||||
|
Record the exact input, command, limits, and minimum result. For the environment,
|
||||||
|
record only allowlisted variable names and safe non-secret values needed to reproduce
|
||||||
|
the check. Never capture the ambient environment, inherited variables, credentials,
|
||||||
|
authentication state, or unrelated host paths. The target-controlled process writes
|
||||||
|
only in scratch. After the sandbox and all its processes terminate, only trusted
|
||||||
|
parent-side code may promote predeclared scratch-relative files, following the
|
||||||
|
promotion procedure block included verbatim in this prompt. You and target code never
|
||||||
|
write retained artifacts. If promotion is unavailable or fails for decisive evidence,
|
||||||
|
return needs_validation with the exact promotion blocker.
|
||||||
|
Never stress availability, invoke a live target, use a real credential, publish an
|
||||||
|
artifact, or continue past the minimum observed effect.
|
||||||
|
|
||||||
|
A deployment, browser, provider, broker, OS, proxy, package, secret, or identity fact
|
||||||
|
outside source is not proof either way. If one such fact is decisive, return a
|
||||||
|
needs_validation record with the exact missing observation and safe owner-observed check.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Promotion procedure — copy this promotion procedure verbatim into every hunter prompt
|
||||||
|
|
||||||
|
```text
|
||||||
|
Artifact promotion procedure (trusted parent-side code only):
|
||||||
|
Reference only for you: the parent performs these steps; you never perform them.
|
||||||
|
|
||||||
|
Before execution, the parent opens and retains trusted, non-inheritable directory
|
||||||
|
descriptors for the agent's scratch/ and artifacts/ roots, and records an allowlist
|
||||||
|
of expected scratch-relative artifact files plus explicit per-file and cumulative
|
||||||
|
byte limits. Never pass those descriptors to the agent or sandbox. After the sandbox
|
||||||
|
and all its processes terminate, trusted parent-side code promotes each allowlisted
|
||||||
|
file separately:
|
||||||
|
|
||||||
|
1. Validate the declared relative path: reject absolute, empty, `.`, `..`, or
|
||||||
|
symlinked components.
|
||||||
|
2. Walk each parent component from the retained scratch-root descriptor with
|
||||||
|
no-follow directory-relative operations; never reopen by path.
|
||||||
|
3. Open the leaf no-follow and nonblocking.
|
||||||
|
4. Verify with `fstat` that it is a regular file with link count exactly one and
|
||||||
|
within the recorded per-file and cumulative byte limits.
|
||||||
|
5. Enforce those limits again while reading from that descriptor.
|
||||||
|
6. Copy exactly the verified size, repeat `fstat`, and reject a changed identity,
|
||||||
|
type, link count, or size.
|
||||||
|
7. For the destination, walk every parent component from the retained
|
||||||
|
artifacts-root descriptor with no-follow directory-relative operations; require
|
||||||
|
each existing component to be a real directory, and create any missing directory
|
||||||
|
exclusively before reopening and verifying it no-follow.
|
||||||
|
8. Create the leaf exclusively without following links, verify that the opened
|
||||||
|
destination is a regular file with link count exactly one, and copy from the
|
||||||
|
verified source descriptor without reopening either path.
|
||||||
|
9. Use equivalent race-safe APIs on non-POSIX systems.
|
||||||
|
10. Never recursively copy or glob scratch, extract an archive into artifacts, or
|
||||||
|
open or promote a symlink, FIFO, socket, device, directory, hard-linked file,
|
||||||
|
changing file, or file that exceeds its bound.
|
||||||
|
11. If any check is unavailable, cannot be enforced, or fails, discard the scratch
|
||||||
|
entry; if it is decisive evidence, retain `needs_validation` with the exact
|
||||||
|
promotion blocker.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Core validation rules — include in every hunter prompt
|
||||||
|
|
||||||
|
```text
|
||||||
|
## Candidate gate
|
||||||
|
|
||||||
|
1. A candidate needs a complete repository-relative source trace and evidence for the
|
||||||
|
claimed root cause, including the strongest source-visible control.
|
||||||
|
2. A proposed confirmed record needs a bounded local observed result, meaningful impact
|
||||||
|
across a stated boundary, complete conditions, and no visible preventing layer.
|
||||||
|
3. Do not strengthen a crash into code execution, ordinary work into shared availability,
|
||||||
|
or a same-principal action into privilege gain.
|
||||||
|
4. If a required fact is not source-visible or locally observable, use
|
||||||
|
needs_validation. Name exact blockers; do not give it severity or speculative completion.
|
||||||
|
5. A missing best practice with no affected principal/resource is excluded or hardening,
|
||||||
|
not a finding. A candidate disproved by source is not needs_validation.
|
||||||
|
6. Use the same source-derived fingerprint for the same root cause in every state.
|
||||||
|
It must match `^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$` and must not include a line,
|
||||||
|
wave, agent, severity, or verdict.
|
||||||
|
7. Return an empty candidate array when nothing survives these gates.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Local validation boundaries
|
||||||
|
|
||||||
|
Local execution is for confirmation, not impact expansion:
|
||||||
|
|
||||||
|
- **Allowed only in the required OS sandbox:** offline builds with present dependencies; isolated-loopback processes using dummy state; unit and integration tests; small fixture processing; sanitizers; bounded fuzz/regression tests; deterministic concurrency checks; local browser/emulator tests with dummy accounts; rendered manifests and policy evaluation with dummy identities; mocked external or paid calls.
|
||||||
|
- **Disallowed:** live or deployed traffic; requests to services not started for this isolated check; network dependency installation; real accounts or credentials; production data; shared queues, cloud resources, runners, registries, signing or release services; publishing; stress, saturation, or cost generation; any work after the minimum dummy-data boundary result.
|
||||||
|
|
||||||
|
The sandbox starts with an empty environment, gives target code no external network or host writable path, and enforces explicit low resource and time limits for every check, not only checks expected to be expensive. Scratch output remains target-controlled after exit. Promote it only with the no-follow, path-confined, regular-file, bounded-size host procedure in `SKILL.md`. Missing any sandbox or promotion capability does not erase a source-grounded candidate; represent the exact blocker in `needs_validation`.
|
||||||
|
|
||||||
|
## Structured hunter result
|
||||||
|
|
||||||
|
Return exactly one JSON object, with no surrounding prose:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"units": [
|
||||||
|
{
|
||||||
|
"coverage_id": "one assigned ID",
|
||||||
|
"disposition": "covered|candidate|blocked",
|
||||||
|
"reviewed_paths": ["repo/relative/path"],
|
||||||
|
"checks": [
|
||||||
|
{
|
||||||
|
"agent_id": "canonical owner of this check",
|
||||||
|
"reviewed_paths": ["repo/relative/path owned by this check"],
|
||||||
|
"invariant": "specific control checked for this unit",
|
||||||
|
"method": "source|local",
|
||||||
|
"result": "what source or the bounded check established",
|
||||||
|
"artifact": "agents/<agent-id>/artifacts/file for local, null for source"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"candidate_fingerprints": [],
|
||||||
|
"unresolved": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"candidates": [],
|
||||||
|
"hardening": ["concrete non-finding note"],
|
||||||
|
"uncovered": [
|
||||||
|
{
|
||||||
|
"surface": "...",
|
||||||
|
"boundary": "...",
|
||||||
|
"subsystem": "...",
|
||||||
|
"attack_class": "...",
|
||||||
|
"starting_paths": ["repo/relative/path"],
|
||||||
|
"reason": "why this needs its own deterministic coverage unit"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each `candidates` entry is schema-shaped except that it uses `proposed_verdict` in place of `verdict`:
|
||||||
|
|
||||||
|
- `proposed_verdict: "confirmed"`: include every field required by the `confirmed` branch of `report-schema.json` other than `verdict`: `fingerprint`, title, description, `root_cause`, `intended_behavior`, ordered `trace`, `evidence`, `conditions`, target-neutral `execution`, `remediation`, `severity`, and `confidence`. The execution instructions describe only the bounded local check already performed. `payloads` holds the minimum test input, fixture, or native invocation. `observed_result` records actual local output. Overall severity must not exceed observed impact.
|
||||||
|
- `proposed_verdict: "needs_validation"`: include every field required by that schema branch other than `verdict`: `fingerprint`, title, description, `claimed_root_cause`, ordered `trace`, `evidence`, nonempty `blockers`, and `validation_plan` with at least one applicable `local` or `deployment` step. Do not invent an inapplicable context. Do not include severity, execution, remediation, reason, or a confirmed `root_cause`. `deployment` is an owner-observed check, not a request to probe a live target.
|
||||||
|
|
||||||
|
Every assigned coverage ID appears exactly once in `units`. A `covered` unit needs an owner, nonempty `reviewed_paths` and `checks`, no unresolved fact, and no candidate. A `candidate` unit has the same owned evidence and is the only state that carries linked fingerprints. A `blocked` unit is an owned partial review with nonempty paths, checks, and unresolved facts but no fingerprint. All source paths are repository-relative, never absolute or traversal paths. A trace with several entries begins at `entrypoint`, ends at `sink`, and labels intermediate steps `propagation`. Every check has its own canonical lowercase `agent_id` and nonempty `reviewed_paths`; the unit-level list is exactly the union of those owned paths. A `source` check uses `artifact: null`. A `local` check uses one successfully parent-promoted regular file beneath `agents/<check.agent_id>/artifacts/`; this permits a verifier to add independently owned evidence without taking ownership from the hunter. Never link scratch, an output-root file, or another check owner's artifact.
|
||||||
|
|
||||||
|
## Parent consolidation and ledger update
|
||||||
|
|
||||||
|
The parent validates each unit result, maps it to exactly one assigned `coverage_id`, and updates only that ledger unit. Reject duplicate or absent IDs, unsafe unit or check agent IDs, source checks with artifacts, and local artifacts that trusted parent-side code did not promote into the check owner's artifacts subtree. Copy the unit's `reviewed_paths`, its `checks` into the unit's `local_checks`, linked artifact paths, candidate fingerprints, and unresolved facts into the ledger. Retain each hunter's `hardening` list in a parent bookkeeping field on the relevant units (outside the semantic fields) so Phase 6 can report it. A failed, malformed, or unsupported conclusion leaves that unit `planned` for reassignment. Untouched budget/profile units become unassigned `deferred` units with empty evidence and a reason; do not hide partial evidence in `deferred`. Run `validate-coverage-ledger.cjs` after the update; an invalid ledger cannot drive another assignment. This per-unit contract allows one hunter to close one unit while returning a candidate or blocker for another.
|
||||||
|
|
||||||
|
Consolidate candidate entries by fingerprint and then by root cause. One root cause that exposes several entry paths or effects is one candidate with the strongest complete trace. Related but independent missing controls use separate fingerprints. Record duplicate fingerprints in the relevant ledger unit and do not send duplicate candidates to validation.
|
||||||
|
|
||||||
|
## Coverage-critic waves
|
||||||
|
|
||||||
|
Immediately after each hunter wave, spend the reserved invocation on one fresh `research` post-wave coverage critic. It receives `architecture.md`, the full coverage ledger including each assignment block map, current candidate fingerprints and states, and the prior-ledger gap summary. It reads source but does not write or run targets. Require exactly this JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"missing_units": [
|
||||||
|
{
|
||||||
|
"surface": "...",
|
||||||
|
"boundary": "...",
|
||||||
|
"subsystem": "...",
|
||||||
|
"attack_class": "...",
|
||||||
|
"starting_paths": ["repo/relative/path"],
|
||||||
|
"selected_companion_blocks": ["FILE.md#section"],
|
||||||
|
"excluded_blocks": [{"block": "FILE.md#section", "reason": "..."}],
|
||||||
|
"reason": "source-backed coverage gap"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"reassign_ids": ["existing-id-that-did-not-close"],
|
||||||
|
"resolved_prior_leads": ["fingerprint"],
|
||||||
|
"stop": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The critic checks for unmapped entry points, unchecked parallel paths, missing lifecycle modes, selected companion classes without a unit, unjustified exclusions, units closed without paths/checks, and prior `needs_validation` or changed-source gaps that no unit addresses. It proposes coverage, not findings. `stop` is the critic's own assessment: `true` only when it accepts no `missing_units` and no `reassign_ids`; the parent's loop condition below, not `stop` alone, decides whether another wave runs. For each fingerprint in `resolved_prior_leads`, the parent marks the linked unit or prior-lead entry resolved and records the critic's source-backed reason.
|
||||||
|
|
||||||
|
The parent rejects proposed units outside the review scope or source/local boundary, derives canonical IDs for accepted units, and deduplicates them against current units. A prior same-source completed unit may supply evidence; prior `deferred`, `blocked`, `out_of_scope`, or changed-source units become current work and never suppress an accepted unit. Fail rather than merge a canonical ID collision. For each legitimate `reassign_id` with live `blocked`, `covered`, or `candidate` evidence, append that exact terminal record to the unit's `attempts` with the critic's source-backed `reassignment_reason`. Preserve its owner, checks, artifacts, fingerprints, and unresolved facts in that archive. Increment the live `wave`; the next hunter must be a fresh owner and receives an `in_progress` unit with empty live evidence. The hunter's terminal result writes only its new evidence into the live fields. Never copy an archived owner's checks or artifacts into the new live attempt. Sort IDs and validate the ledger before another assignment. In `standard` and `deep`, when the post-wave critic reports no accepted `missing_units` or legitimate `reassign_ids` and no `planned` units remain, spend the separately reserved invocation on a distinct final-clean critic. Complete coverage only when that critic also returns no accepted work. If it finds work, queue it and repeat the wave, post-wave critic, and final-clean process. If time or resources force an early stop, mark every untouched unit `deferred`, preserve the critic's reason, and disclose the gap in the report. Never use a silent wave or agent cap as evidence of complete coverage.
|
||||||
|
|
||||||
|
The run profile bounds this loop. A `quick` run has exactly one hunter wave followed by exactly one final critic pass. Add each accepted `missing_unit` to the current ledger and mark it `deferred` with reason `quick_profile_final_critic`. For each legitimate evidence-bearing `reassign_id`, archive the live terminal state in `attempts`, increment `wave`, and set the live state to unassigned `deferred` with empty evidence and reason `quick_profile_final_critic`. Do not launch a second hunter wave or another critic. In a scoped run, the critic still reports out-of-scope gaps it notices, but the parent records them as `out_of_scope` with the critic's reason instead of assigning them. The early-stop rule above is the same mechanism: `quick` is a pre-declared early stop, not evidence of complete coverage.
|
||||||
|
|
||||||
|
A budget bounds it the same way. Before assigning each wave, compare remaining budget against its hunter count, the validation reserve, the immediate post-wave critic, and the retained final-clean critic (`quick` reserves only its single final post-wave critic). Shrink the hunter wave to fit, taking units in priority order. If those mandatory reserves do not fit, launch no hunter from that wave and mark its planned units `deferred` with reason `budget_cannot_reserve_critics_and_validation`. Critic-proposed units enter the same ranked queue rather than extending the budget. If surviving candidates exceed the validation reserve, follow the incomplete-run rule in `SKILL.md`: stop hunting, validate in fingerprint order, retain unvalidated units as unresolved candidates, and never present them as findings.
|
||||||
101
.agents/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md
Normal file
101
.agents/skills/security-audit/MEMORY-SAFETY-AND-BINARY.md
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
# Memory Safety, Binary, and Kernel Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the target processes untrusted bytes in a memory-unsafe or privileged context: C/C++/Objective-C, Rust `unsafe`, FFI, kernel modules and drivers, parsers and decoders, network daemons, firmware, binary loaders, language runtimes, and JITs. Use `PROTOCOLS-RPC-AND-MESSAGING.md` for protocol authorization and state-machine logic, and this file for process integrity, memory safety, ABI boundaries, and loader behavior.
|
||||||
|
|
||||||
|
Pick relevant classes from Phase 1 and split large targets by parser, allocator/lifetime, FFI, concurrency, loader, runtime, or privileged interface.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- Re-derive every bound and lifetime from attacker-controlled inputs and all callers. Validate against the worst accepted case, not a typical test vector.
|
||||||
|
- A panic, sanitizer finding, or crash proves a defect only when a realistic untrusted input reaches it. Do not infer memory corruption, code execution, or shared availability impact from a label alone.
|
||||||
|
- Validate in a local harness with sanitizers, deterministic concurrency tests, existing fuzz targets, and debugger-assisted fault classification. Stop after proving the violated invariant and observable impact; do not develop post-corruption techniques.
|
||||||
|
- Assembly, JIT code, custom allocators, intra-object accesses, and foreign libraries can escape sanitizer coverage. Identify which relevant instructions are instrumented.
|
||||||
|
- Classify as `confirmed` only after source evidence and bounded local validation establish the defect and effect. Use `needs_validation` when ABI, allocator, architecture, feature, deployment, or reachability facts remain unknown.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bounds, integer, and representation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Out-of-bounds read or write**
|
||||||
|
A length, offset, index, or terminator reaches a fixed or allocated buffer without a correct bound. Recalculate available headroom after prefixes, alignment, padding, and terminators. Check both source and destination capacity, and whether a short input is read before its declared length is trusted.
|
||||||
|
|
||||||
|
**Integer overflow, underflow, truncation, and signedness**
|
||||||
|
Review attacker-controlled arithmetic before allocation, copy, loop, indexing, and pointer operations. High-hit patterns include `a - b` with `b > a`, `count * element_size`, additions near the type maximum, negative values converted to unsigned, 64-bit lengths narrowed to 32-bit fields, and sentinel values such as `-1` becoming a large size. Confirm which checked representation is later used.
|
||||||
|
|
||||||
|
**Unit and pointer-depth confusion**
|
||||||
|
Code mixes bytes, elements, code units, pages, words, wire units, or nested pointer element sizes. Compare the unit at parse, validation, allocation, API boundary, and copy. A bounds check using the same wrong unit as the allocation is still wrong.
|
||||||
|
|
||||||
|
**Uninitialized or partially initialized data**
|
||||||
|
A buffer, padding, struct field, or vector capacity is returned, compared, hashed, serialized, or passed across a trust boundary before initialization. Require an observable consumer and realistic output length; stack allocation by itself is not disclosure.
|
||||||
|
|
||||||
|
## Lifetime, type, and concurrency attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Use-after-free, stale view, and double free**
|
||||||
|
Owners are released while callbacks, wait queues, timers, iterators, borrowed slices, or cached raw pointers can still use them. Review every error, cancellation, close, and realloc path. For embedded notification anchors, each free path must drain or detach all observers.
|
||||||
|
|
||||||
|
**Type confusion and invalid downcast**
|
||||||
|
A tag, vtable, union discriminator, object kind, or foreign handle is checked differently from the representation later read. Look for unchecked dynamic casts, stale tags after reuse, and serialized types whose validated element differs from the element consumed. Confirm a wrong-type read or write locally without extending the test beyond the violated invariant.
|
||||||
|
|
||||||
|
**Reference-count and ownership races**
|
||||||
|
Non-atomic retain/release, a check followed by an unlocked use, or inconsistent ownership across threads can free or mutate an object during access. Compare fast, error, shutdown, and compatibility paths for the same lock and ownership rules.
|
||||||
|
|
||||||
|
**Shared-state races and TOCTOU**
|
||||||
|
Concurrent parser streams, global caches, lazy initialization, signal handlers, and resource teardown can invalidate bounds, policy, or pointers established earlier. Verify the race with a repeatable local schedule, barrier, or thread sanitizer; a hypothetical interleaving without a security-relevant state transition remains `needs_validation`.
|
||||||
|
|
||||||
|
**Lock-order, deadlock, and starvation**
|
||||||
|
Externally reachable operations acquire locks in inconsistent order or hold them across callbacks and blocking I/O. Report under availability only when bounded input can stop shared progress; otherwise record it for fixing as a concurrency defect.
|
||||||
|
|
||||||
|
## FFI and ABI attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Pointer-length and ownership contract mismatch**
|
||||||
|
Caller and callee disagree on who allocates, frees, pins, or mutates a buffer, how long a pointer remains valid, or whether a length is bytes or elements. Trace both sides of every `extern`, CGo/JNI/Python/native binding, and generated wrapper. Check null, zero length, aliasing, and callback retention.
|
||||||
|
|
||||||
|
**Layout, alignment, and enum disagreement**
|
||||||
|
Foreign code receives a struct, bitfield, packed record, callback signature, integer width, enum, or calling convention that differs by architecture or build flag. Verify `repr`, packing, alignment, endianness, and ABI-specific types. An in-repo declaration mismatch can be confirmed locally; an opaque foreign implementation requires `needs_validation`.
|
||||||
|
|
||||||
|
**Unwind, exception, and thread-affinity violations**
|
||||||
|
Exceptions or panics cross an ABI that forbids unwinding, callbacks run after teardown, or APIs requiring one runtime thread are invoked elsewhere. Review error conversion and cancellation. Confirm whether the process aborts or state is corrupted before assigning impact.
|
||||||
|
|
||||||
|
## Binary loading and runtime attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Library, plugin, and executable search-order trust**
|
||||||
|
A privileged process loads a library, plugin, runtime image, or helper from a path writable by a less-trusted principal, or resolves a bare name through an attacker-influenceable working directory or environment. Compare intended installation ownership with each fallback and compatibility search path. A user loading their own plugin into their own process is not a boundary violation.
|
||||||
|
|
||||||
|
**Missing artifact identity or signature binding**
|
||||||
|
A loader verifies one file or metadata record but maps a different image because path resolution, file replacement, architecture slices, or embedded resources are not bound to the check. Supply-channel authenticity belongs in `SUPPLY-CHAIN-AND-RELEASE.md`; this class covers the local verification-to-map gap.
|
||||||
|
|
||||||
|
**Malformed binary metadata and relocation handling**
|
||||||
|
Offsets, counts, sections, relocations, symbols, bytecode, or debug metadata are trusted before range, overlap, and representation checks. Test parsers with bounded local fixtures and sanitizers. Separate memory corruption from a safely rejected malformed file.
|
||||||
|
|
||||||
|
**JIT and generated-code consistency**
|
||||||
|
Validator, interpreter, optimizer, and generated code disagree about types, bounds, side effects, or lifetime. Diff optimized and unoptimized paths using the same local input. Confirm a process-integrity effect; output variance that stays within language semantics is not a finding.
|
||||||
|
|
||||||
|
**Unload, reload, and teardown safety**
|
||||||
|
Live function pointers, callbacks, worker threads, or data views survive module unload or runtime reset. Review shutdown and failed-load cleanup as closely as startup.
|
||||||
|
|
||||||
|
## Kernel and privileged-interface attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**User-copy bounds and repeated reads**
|
||||||
|
A syscall, ioctl, driver, or kernel parser derives a trusted fact from user memory then reads the same mutable address again. Copy the full request once or revalidate the later copy. Also audit size, direction, and access checks at each user-copy primitive.
|
||||||
|
|
||||||
|
**Privileged object lifecycle and dispatch consistency**
|
||||||
|
Externally reachable objects have unbalanced retain/release, teardown without observer drain, unchecked selector/table indices, or duplicated compatibility paths that omit a guard. Diff each dispatch and free path side by side.
|
||||||
|
|
||||||
|
**Under-authorized powerful interfaces**
|
||||||
|
A device node, admin socket, helper, or management API validates shape but not the caller's authority over the resource. Establish actual interface ownership and reachability; permissions or sandbox policy outside the repository make this `needs_validation`.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Audit fixes and duplicated paths for the same source-to-sink shape. A check in one caller, architecture, protocol role, feature flag, or compatibility path does not protect its siblings.
|
||||||
|
- Build a table for every parser or FFI boundary: accepted length/type, checked representation, allocation owner, consumer, thread, and teardown. Most native findings are one disagreement in that table.
|
||||||
|
- Use existing corpora and small locally generated boundary fixtures. Save exact sanitizer/runtime output and the input property that triggers it; avoid large resource consumption and any live target.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Establish a realistic untrusted entry and exact operation that violates a bounds, type, lifetime, ABI, concurrency, loader, or authority invariant.
|
||||||
|
2. Classify the observable effect: invalid read, invalid write, stale alias, wrong object, uninitialized output, unauthorized image load, deadlock, or safe process termination. Do not claim a stronger effect than observed.
|
||||||
|
3. Run the narrowest local harness, existing test, sanitizer, or fuzzer needed to reproduce the effect. Verify sanitizer coverage of the faulting operation and record architecture/build conditions.
|
||||||
|
4. For concurrency, use a deterministic schedule or sanitizer trace. For binary loading, prove the checked identity differs from the mapped identity and name the lower-trust writer.
|
||||||
|
5. Return `confirmed` findings only with exact input, source trace, and observed result. Return `needs_validation` for a specific unresolved reachability, ABI, build, deployment, or runtime fact and state the bounded check needed.
|
||||||
81
.agents/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md
Normal file
81
.agents/skills/security-audit/PROTOCOLS-RPC-AND-MESSAGING.md
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
# Protocols, RPC, and Messaging Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the target uses gRPC, GraphQL transports, Cap'n Proto, Thrift, Protobuf, custom binary protocols, streaming RPC, webhooks, brokers, queues, pub/sub, or event buses. It covers peer identity, logical message interpretation, routing, replay, ordering, and delivery semantics. Use `MEMORY-SAFETY-AND-BINARY.md` for parser memory safety, `WEB-PROTOCOL-AND-AUTH.md` for HTTP framing, and `RESOURCE-EXHAUSTION-AND-AVAILABILITY.md` for availability impact.
|
||||||
|
|
||||||
|
Split large systems by producer/consumer pair, external/internal peer role, synchronous RPC, streaming, and asynchronous message path.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- "Internal" is not authentication. Name the peer identity at every hop and show how it becomes the application principal used for authorization.
|
||||||
|
- Schema validation proves message shape, not provenance, resource authority, ordering, or safe values. Follow decoded fields to policy and side effects.
|
||||||
|
- Broker guarantees and application guarantees differ. Write down retry, ordering, acknowledgement, deduplication, and transaction behavior before evaluating state changes.
|
||||||
|
- Parser disagreement requires two concrete consumers, schema versions, or wire representations and one security-relevant divergent value.
|
||||||
|
- Use `confirmed` for source-complete paths plus bounded local producer/consumer tests. Use `needs_validation` for broker ACL, service-mesh identity, topic attachment, or compatibility behavior outside the repository.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Framing, schema, and interpretation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Message boundary and canonicalization disagreement**
|
||||||
|
Components disagree on length, compression, duplicate fields, unknown fields, encoding, numeric width, normalization, or envelope/body precedence. Compare generated and custom parsers, gateways, language bindings, and version converters. Confirm which principal, resource, or operation differs after decoding.
|
||||||
|
|
||||||
|
**Union, enum, and default confusion**
|
||||||
|
Unknown variants, missing discriminators, zero values, default privileges, or compatibility mappings reach code that assumes a validated case. Review exhaustive dispatch, default branches, and how old consumers interpret newly added fields.
|
||||||
|
|
||||||
|
**Envelope and payload identity mismatch**
|
||||||
|
Authorization uses trusted-looking routing or envelope metadata while the handler acts on a conflicting tenant, account, subject, object, or sender in the body. Identify which source is authoritative and ensure clients cannot override it.
|
||||||
|
|
||||||
|
## RPC identity and authorization attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Interceptor and method-path inconsistency**
|
||||||
|
An authn/authz interceptor applies to unary methods but not streams, reflection, health, gateway-transcoded paths, compatibility services, or individual stream messages. Compare every registration and route to the same operation.
|
||||||
|
|
||||||
|
**Peer identity to application-principal confusion**
|
||||||
|
mTLS, workload identity, bearer metadata, forwarded identity, or broker credentials authenticate a channel, but a caller-controlled field selects the user or tenant. The channel identity and claimed principal must be bound by deterministic policy.
|
||||||
|
|
||||||
|
**Per-item and streaming authorization gaps**
|
||||||
|
A stream, subscription, batch, or bulk message is authorized once, then later items name different resources or continue after role, membership, or token revocation. Re-check where scope can change and bind subscriptions to their original principal.
|
||||||
|
|
||||||
|
**Callback and reply-correlation confusion**
|
||||||
|
Predictable, reused, or cross-tenant correlation IDs let a response, webhook, cancellation, or acknowledgment satisfy another caller's pending operation. Bind each outstanding request to authenticated peer, tenant, operation, and lifecycle.
|
||||||
|
|
||||||
|
## Broker and queue isolation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Topic, routing-key, and subscription scope gaps**
|
||||||
|
A publisher or subscriber can select another tenant's topic, wildcard, consumer group, partition, reply queue, or dead-letter route. Check broker-enforced ACLs where visible and application-side namespace construction. Tenant text inside a payload is not isolation.
|
||||||
|
|
||||||
|
**Dead-letter, retry, and diagnostic disclosure**
|
||||||
|
Messages routed to dead-letter queues, error topics, tracing, or operator views contain secrets or cross-tenant payloads accessible to a lower-trust consumer. Review policy and redaction at the failure path, not just normal delivery.
|
||||||
|
|
||||||
|
**Untrusted producer treated as control plane**
|
||||||
|
A message body can declare itself an admin event, provider callback, replication record, or migration instruction without an independently authenticated producer and event type. Verify signatures and source/account/audience binding before privileged handling.
|
||||||
|
|
||||||
|
## Replay, ordering, and transaction attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Duplicate delivery and idempotency gaps**
|
||||||
|
Retries or redelivery repeat a side effect because deduplication is absent, occurs after mutation, or uses a key that collides across tenants or operations. Confirm the broker's delivery model and the side effect that is not naturally idempotent.
|
||||||
|
|
||||||
|
**Out-of-order and stale message acceptance**
|
||||||
|
Older state, revoked membership, canceled work, or pre-step-up authorization arrives after newer state and overwrites it. Review sequence/version checks, tombstones, partition changes, and restore/replay workflows.
|
||||||
|
|
||||||
|
**Acknowledgment/commit ordering defects**
|
||||||
|
Acknowledgment occurs before durable commit and loses security-relevant work, or commit happens before an unreliable acknowledgment and duplicates a mutation. Evaluate transactional outbox/inbox behavior and failure recovery.
|
||||||
|
|
||||||
|
**Partial multi-consumer transitions**
|
||||||
|
Several consumers jointly implement one authorization or business transition, but retries and partial failure leave only a subset committed. Identify invariants that must become durable atomically or compensate with current authorization.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Draw producer → broker/transport → gateway → consumer → storage for each message family. At each hop record authenticated peer, authoritative tenant/resource fields, validation, and side effect.
|
||||||
|
- Feed the same small fixture to every in-repo schema version or language binding. Test duplicate, missing, unknown, boundary, replayed, and reordered messages without producing load.
|
||||||
|
- Compare normal, retry, dead-letter, replay, migration, reflection, stream, and gateway-transcoded routes. Security policy must survive transport changes.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Name the realistic producer or peer, accepted message, authenticated channel identity, affected principal/resource, and unauthorized mutation or disclosure.
|
||||||
|
2. For disagreement claims, cite both parsers/consumers and the divergent decoded value. Safe rejection by either side prevents confirmation.
|
||||||
|
3. For replay/order claims, establish actual delivery guarantees and reproduce the invariant failure with a bounded local/in-memory transport.
|
||||||
|
4. For authorization and isolation, verify all interceptor, broker ACL, gateway, and consumer layers visible in source. External attachments make the candidate `needs_validation`.
|
||||||
|
5. Return `confirmed` only with the complete message lifecycle and observed meaningful result. Return `needs_validation` with the exact broker, service identity, route, or delivery fact required.
|
||||||
156
.agents/skills/security-audit/RECONNAISSANCE.md
Normal file
156
.agents/skills/security-audit/RECONNAISSANCE.md
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
# Reconnaissance
|
||||||
|
|
||||||
|
### Phase 1: Map the source and plan coverage
|
||||||
|
|
||||||
|
The parent initializes `run-metadata.json`, applies the strict pre-reconnaissance budget gate in `SKILL.md`, then creates agent scratch roots and the shared ledger before hunting. If the gate fails, record the incomplete status in metadata and launch no reconnaissance agent. Reconnaissance reads the target and locally available build/configuration state only. It does not contact deployed endpoints, external identity providers, registries, brokers, cloud APIs, or other shared services.
|
||||||
|
|
||||||
|
Launch several `research` agents in parallel. They return structured facts to the parent and do not write files.
|
||||||
|
|
||||||
|
**Agent 1a: Product, stack, and local operation**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Read the target at <target>. Do not use network access. Return:
|
||||||
|
1. Product type, users, operators, and ordinary trust-sensitive actions.
|
||||||
|
2. Languages, frameworks, build system, runtimes, and locally visible deployment models.
|
||||||
|
3. Repository-relative entry points and subsystem boundaries.
|
||||||
|
4. Exact build and test commands that could run offline with local dependencies, their expected write locations, and the target-controlled inputs they process. Do not run them during reconnaissance.
|
||||||
|
5. Comparable software or protocol visible from local documentation and dependencies. If no useful comparison is source-grounded, say so.
|
||||||
|
6. Missing local toolchains or runtime facts that limit bounded execution.
|
||||||
|
Return only source facts with repository-relative file:line references.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Agent 1b: Principals, authority, and controls**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Read all source that establishes identity, authorization, isolation, and privilege. Map:
|
||||||
|
1. Each lower-trust principal and the actions it has by design.
|
||||||
|
2. Authentication or peer identity at each entry surface.
|
||||||
|
3. Per-resource authorization and tenant/owner scope.
|
||||||
|
4. Process, browser, workload, CI, plugin, model/tool, device, or local-IPC authority.
|
||||||
|
5. Privilege changes, confirmation, revocation, recovery, and fallback paths.
|
||||||
|
6. Which controls are source-visible and which depend on an unobserved deployment fact.
|
||||||
|
Return trust boundaries and control locations with repository-relative file:line references. Do not infer live reachability.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Agent 1c: Entry surfaces, copies, and sinks**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Inventory every source-visible place external or lower-trust input enters:
|
||||||
|
- HTTP/browser, RPC/message/protocol, files/archive/document, CLI/env/config, plugins/dependencies/CI, cloud events/IAM selectors, model context/tool arguments, mobile/deep-link/webview, and local IPC.
|
||||||
|
For each surface, follow major transformations, stored or derived copies, and security-relevant sinks. Record source-visible limits and parallel paths to the same effect.
|
||||||
|
Return repository-relative paths and line numbers. Be complete, but do not execute or send inputs.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Agent 1d: Local execution and deployment visibility**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Read tests, build definitions, manifests, packaging, and maintained environment overlays. Return:
|
||||||
|
1. Small offline tests or existing fixtures that could validate trust boundaries with dummy data inside the required OS-enforced sandbox.
|
||||||
|
2. Processes that could use an isolated loopback network namespace without external or shared dependencies.
|
||||||
|
3. Commands that would fetch dependencies, publish artifacts, contact paid/provider APIs, or affect shared state; mark them prohibited for this run.
|
||||||
|
4. Deployed controls and attachments that source cannot establish and therefore require needs_validation if decisive.
|
||||||
|
5. The final active source path for each deployment mode only where the repository selects it deterministically.
|
||||||
|
6. Whether the local platform can enforce an empty allowlisted environment, no external network, read-only target/toolchain mounts, scratch-only writes, and explicit CPU, memory, process, file-size, disk, and wall-clock limits. Missing controls block target-controlled execution.
|
||||||
|
7. Whether trusted parent-side code can promote predeclared scratch files with path-confined no-follow descriptor traversal, nonblocking regular-file checks, no-follow traversal of every destination parent, exclusive regular-file destination creation, and explicit per-file and cumulative size bounds. Missing promotion controls block use of scratch files as evidence.
|
||||||
|
```
|
||||||
|
|
||||||
|
Add focused reconnaissance agents for materially distinct deployment modes or subsystems that these four do not map. Do not silently omit them: if the budget gate in `SKILL.md` blocks a focused agent, launch nothing for it, seed the unmapped area as a `deferred` ledger unit with reason `budget_cannot_reserve_critics_and_validation`, and disclose the gap in the report.
|
||||||
|
|
||||||
|
## Prior-run input
|
||||||
|
|
||||||
|
Before selecting work, the parent reads every available prior `coverage-ledger.json` and `findings.json` for the same repo:
|
||||||
|
|
||||||
|
- Compare the source locations, controls, conditions, and source-derived identity for every prior record and unit against the current source.
|
||||||
|
- Carry an unchanged prior `confirmed` record into the current candidate set, with the same fingerprint, only when its relevant source, conditions, and qualifying evidence still apply. Link it to a current `planned` unit with `prior_status: "prior_confirmed_same_source"` and put only that root cause on the hunter exclusion list. The Phase 3 verifier that re-verifies the carried record becomes that unit's assignment owner; its source re-check is the unit's first check and moves the unit to `candidate` with the carried fingerprint.
|
||||||
|
- Build a current planned `prior_confirmed_changed_source` revalidation unit when any relevant source or condition changed. Do not exclude that root cause from hunting or assume the prior verdict still applies.
|
||||||
|
- Build current work units for every prior `needs_validation`, `deferred`, `blocked`, `out_of_scope`, and changed-source unit. These states are priority input, never deduplication or suppression keys.
|
||||||
|
- Carry a still-blocked prior `needs_validation` record with the same fingerprint only after current source supports its trace. Link it to a current `planned` unit with `prior_status: "prior_needs_validation"`; the record keeps the unresolved blocker. The Phase 3 verifier that re-checks the carried record becomes that unit's assignment owner; its re-check is the unit's first check and moves the unit to `candidate` with the carried fingerprint. Include the record in final verification.
|
||||||
|
- Treat prior rejected records as stale claims unless current evidence changes the failed trace or missing condition. An unchanged rejection suppresses only that exact claim, not review of the coverage unit.
|
||||||
|
- Record missing or incompatible ledgers instead of treating them as empty coverage.
|
||||||
|
|
||||||
|
State paths and source refs used in `run-metadata.json`. Summarize only the coverage consequences in `architecture.md`.
|
||||||
|
|
||||||
|
## Architecture summary and companion selection
|
||||||
|
|
||||||
|
The parent synthesizes `<output-dir>/architecture.md`, with a hard cap of about 1,000 words. Include:
|
||||||
|
|
||||||
|
1. Product, principals, normal authority, and protected resources.
|
||||||
|
2. The comparable-software baseline from Agent 1a, when one is source-grounded: what security trade-offs the comparable accepts. Use it to calibrate effort and severity, never to dismiss a demonstrated finding; if the comparable shares a defect pattern that has mattered in practice, that strengthens the finding. Omit this line when no meaningful comparable exists.
|
||||||
|
3. Tech stack, source-visible deployment paths, and offline build/test limits.
|
||||||
|
4. Entry surfaces and the important source-to-sink or lifecycle paths.
|
||||||
|
5. Trust boundaries and the strongest source-visible control on each.
|
||||||
|
6. Repository-relative starting paths.
|
||||||
|
7. Prior coverage gaps, changed-source and blocked revalidation targets, and same-source confirmed exclusions.
|
||||||
|
8. A short companion-selection summary derived from [ATTACK-CLASSES.md](ATTACK-CLASSES.md): selected files and the source-visible boundaries that require them.
|
||||||
|
|
||||||
|
Keep the assignment-level ordinary block, selected companion blocks, and excluded blocks with reasons in each ledger unit, not in `architecture.md`. This keeps the architecture cap valid for large runs and makes the exact hunter prompt map machine-checkable.
|
||||||
|
|
||||||
|
Do not select a companion file merely because the language or dependency name appears. Select it because reconnaissance found the trust-sensitive boundary described by its `When to use this file` section. Do not exclude a visible boundary just because another agent will review a related class.
|
||||||
|
|
||||||
|
## Deterministic coverage ledger
|
||||||
|
|
||||||
|
The parent writes `<output-dir>/coverage-ledger.json` as a top-level JSON array. Derive one unit for every material combination of entry surface, trust boundary, subsystem, and applicable ordinary or companion attack class at the granularity the run profile sets (`quick` uses one all-in-scope subsystem identity; `deep` adds lifecycle modes). For a scoped run, seed in-scope surfaces for assignment and retain discovered excluded surfaces as `out_of_scope` units so later full runs can turn them into current work.
|
||||||
|
|
||||||
|
Each dimension has a human label and a stable source-derived value in `canonical_refs`. Use the same canonical reference for the same source object across runs even if its display label changes. Suitable references include a repository-relative entry path plus exported scope, a route or message identity defined in source, the source control that defines a boundary, a repository package path, and the exact attack-class block reference. A block reference is `FILE.md#` plus the exact class name as written in bold or as a heading in that file — a stable identifier matched against the file text, not a rendered HTML anchor. For companion section blocks, use the heading text before any parenthetical qualifier (for example `Core discipline`). Do not derive references by lowercasing or slugging display labels.
|
||||||
|
|
||||||
|
Derive `coverage_id` without lossy slugs:
|
||||||
|
|
||||||
|
1. Require every reference to be Unicode NFC with valid scalar values, visible content, no control, format, line/paragraph separator, or default-ignorable code point, and no surrounding whitespace.
|
||||||
|
2. Encode its UTF-8 bytes with RFC 3986 percent encoding: leave only `A-Z a-z 0-9 - . _ ~` unescaped and use uppercase `%HH` for every other byte.
|
||||||
|
3. Join encoded `surface`, `boundary`, `subsystem`, and `attack_class` references with `::`; append encoded `lifecycle` when present.
|
||||||
|
|
||||||
|
Use the fixed canonical value `profile/quick/all-in-scope-subsystems` for the quick profile's coarsened subsystem dimension. Do not include wave number, agent, verdict, severity, or line number in a reference or ID. Sort units lexicographically by `coverage_id` before each assignment. Fail on every duplicate ID. If duplicate IDs have different semantic fields, treat that as a canonical identity collision; never merge or silently overwrite them. The validator also rejects one semantic tuple represented by different canonical references.
|
||||||
|
|
||||||
|
Each unit records:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"coverage_id": "...",
|
||||||
|
"canonical_refs": {
|
||||||
|
"surface": "src/router.ts#POST /users/:id",
|
||||||
|
"boundary": "src/authz.ts#requireOwner",
|
||||||
|
"subsystem": "packages/api",
|
||||||
|
"attack_class": "ATTACK-CLASSES.md#Access control"
|
||||||
|
},
|
||||||
|
"surface": "...",
|
||||||
|
"boundary": "...",
|
||||||
|
"subsystem": "...",
|
||||||
|
"attack_class": "...",
|
||||||
|
"starting_paths": ["repo/relative/path"],
|
||||||
|
"ordinary_attack_class_block": "ATTACK-CLASSES.md#Access control",
|
||||||
|
"selected_companion_blocks": ["FILE.md#section"],
|
||||||
|
"excluded_blocks": [{"block": "FILE.md#section", "reason": "..."}],
|
||||||
|
"prior_status": "new|prior_confirmed_same_source|prior_confirmed_changed_source|prior_needs_validation|prior_deferred|prior_blocked|prior_out_of_scope|prior_covered_same_source|prior_covered_changed_source|prior_rejected_claim_changed|none",
|
||||||
|
"attempts": [],
|
||||||
|
"wave": 1,
|
||||||
|
"status": "planned",
|
||||||
|
"agent_id": null,
|
||||||
|
"reviewed_paths": [],
|
||||||
|
"local_checks": [],
|
||||||
|
"result_fingerprints": [],
|
||||||
|
"unresolved": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When `lifecycle` is material, add both `canonical_refs.lifecycle` and a human `lifecycle` field. `ordinary_attack_class_block` is null only when no ordinary block applies. The selected companion list includes each applicable class plus its companion `Core discipline`, `Universal moves`, and `Validation rules`; `excluded_blocks` records every considered but unselected block and the source fact that excludes it.
|
||||||
|
|
||||||
|
The parent may add bookkeeping fields but keeps the semantic fields above stable. In `prior_status`, `new` marks a surface first seen in this run when compatible prior ledgers exist; `none` marks a unit seeded when no compatible prior ledger is available. Prior `deferred`, `blocked`, `out_of_scope`, and changed-source units initialize as current `planned` work when now in scope. A prior same-source covered unit remains visible in the current ledger; assign changed source, important lifecycle paths, and exact conflicts first, then use the coverage critic to decide whether it needs another pass.
|
||||||
|
|
||||||
|
`attempts` is an append-only archive for evidence-bearing assignments that a coverage critic reopens. Before reassignment, append the prior unit's exact `wave`, `status`, `agent_id`, `reviewed_paths`, `local_checks`, `result_fingerprints`, and `unresolved`, plus the critic's source-backed `reassignment_reason`. Only `blocked`, `covered`, and `candidate` states can be archived. Archived attempts retain the same state and evidence invariants as live units, use strictly increasing waves below the current wave, and retain their producing owners and artifacts. The next assignment increments `wave`, uses a fresh owner, and starts with empty live evidence. If the profile or budget prevents another assignment, increment `wave` and use live `deferred` state with null owner, empty evidence, and the stop reason. Never copy an archived owner's checks or artifacts into the live state. A later live terminal state contains only the new attempt's evidence; the archive remains unchanged.
|
||||||
|
|
||||||
|
Enforce this state table exactly:
|
||||||
|
|
||||||
|
| Status | Unit `agent_id` | `reviewed_paths` / `local_checks` | `result_fingerprints` | `unresolved` |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `planned` | null | empty | empty | empty |
|
||||||
|
| `not_applicable`, `out_of_scope`, `deferred` | null | empty | empty | nonempty reason |
|
||||||
|
| `in_progress` | canonical owner | empty | empty | empty |
|
||||||
|
| `blocked` | canonical owner | both nonempty owned partial evidence | empty | nonempty blocker |
|
||||||
|
| `covered` | canonical owner | both nonempty | empty | empty |
|
||||||
|
| `candidate` | canonical owner | both nonempty | nonempty | optional |
|
||||||
|
|
||||||
|
Canonical agent IDs match `^[a-z0-9][a-z0-9_-]{0,63}$` and are not Windows device names. Lowercase is mandatory, so one ledger cannot contain case-fold aliases. The unit `agent_id` records the assignment owner. Every check records its own `agent_id` and nonempty `reviewed_paths`; the unit-level `reviewed_paths` is exactly their union. A source-only check uses `artifact: null`. A local check requires a regular file promoted only by trusted parent-side code under exactly `agents/<check.agent_id>/artifacts/`. This lets hunter and verifier checks coexist in one unit. Scratch paths, output-root files, symlinks, special files, and another check owner's artifacts are not evidence.
|
||||||
|
|
||||||
|
The ledger is the coverage claim. An architecture summary, agent count, or generic "auth reviewed" sentence is not coverage evidence. Phase 2 closes units only from the paths and checks in a hunter's structured result.
|
||||||
|
|
||||||
|
Run `node <skill-dir>/validate-coverage-ledger.cjs <output-dir>/coverage-ledger.json` after seeding, after every parent update, and before Phase 6. The validator rejects input beyond 5 MiB, 64 nesting levels, 10,000 units, 1,000 entries in a nested collection, or 500,000 traversed values, and caps reported validation errors at 100. In practice the 5 MiB byte limit holds roughly 2,000-5,000 realistic units, so it binds before the 10,000-unit cap. Fix every error before assigning work or making a coverage claim.
|
||||||
@ -0,0 +1,78 @@
|
|||||||
|
# Resource Exhaustion and Availability Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when untrusted requests, messages, files, tenant state, or agent work can consume CPU, memory, disk, connections, worker slots, paid APIs, or queue capacity, or can deadlock/crash a shared service. This domain distinguishes a source-reviewable availability vulnerability from a general performance issue. Never validate by stressing a shared or live service.
|
||||||
|
|
||||||
|
Use `MEMORY-SAFETY-AND-BINARY.md` for memory-integrity defects and `PROTOCOLS-RPC-AND-MESSAGING.md` for broker delivery logic. A reachable fatal error belongs here for shared impact even when the underlying parser is covered elsewhere.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- Require an input-to-cost path, a missing effective bound, and impact on another user, shared service, safety function, or operator-owned spend. Self-limiting work in the requester's own process is not a service vulnerability.
|
||||||
|
- A missing rate limit is not enough. Check body/message/file caps, concurrency, queues, deadlines, database constraints, upstream gateways, and per-tenant quotas before calling a path unbounded.
|
||||||
|
- Do not run stress, saturation, or production tests. Use asymptotic analysis, small boundary fixtures, mocked paid calls, strict local resource limits, and deterministic cancellation tests.
|
||||||
|
- State attacker cost, service work, persistence, scope, and recovery. One bounded input with superlinear or persistent shared effect is materially different from sustained volume.
|
||||||
|
- Use `confirmed` for source-visible bounds failures demonstrated safely. Use `needs_validation` when upstream caps, deployed topology, autoscaling, paid quota, or recovery behavior is outside the repository.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Computational amplification attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Superlinear parsing, matching, or evaluation**
|
||||||
|
Small accepted input drives catastrophic regex backtracking, nested parsing, recursive validation, symbolic evaluation, graph traversal, template expansion, or adversarial sort/hash behavior. Derive accepted depth/cardinality and complexity, then demonstrate a bounded growth curve locally.
|
||||||
|
|
||||||
|
**Decompression and representation amplification**
|
||||||
|
Compressed, sparse, nested, aliased, or encoded input expands far beyond the checked transfer or file size. Verify limits after every expansion and across parser stages, including archives, images, fonts, structured documents, and protocol compression tables.
|
||||||
|
|
||||||
|
**Database and downstream query amplification**
|
||||||
|
A small request creates broad scans, pathological joins, fan-out, unbounded sort/aggregation, or many downstream calls because query depth, filter cardinality, pagination, or expansion fields are not bounded. Confirm authorization does not intentionally permit the same resource scope.
|
||||||
|
|
||||||
|
## Resource accumulation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Unbounded buffering and cardinality**
|
||||||
|
Bodies, out-of-order streams, uploads, sessions, unique cache keys, metrics labels, log fields, subscriptions, or pending jobs accumulate without per-item and aggregate limits. Find cleanup and expiration on disconnect, timeout, cancellation, and partial parse.
|
||||||
|
|
||||||
|
**File descriptor, handle, and temporary-resource leaks**
|
||||||
|
Malformed or canceled work misses cleanup and retains sockets, files, database cursors, timers, subprocesses, temporary files, or object references. Confirm the leak repeats through bounded local iterations and affects a shared pool.
|
||||||
|
|
||||||
|
**Detached work after cancellation**
|
||||||
|
Client timeout, disconnect, canceled job, or failed authorization returns control but leaves database, model, network, or worker work running. Trace cancellation and deadline propagation through every layer.
|
||||||
|
|
||||||
|
## Quota and scheduling attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Pre-authentication work imbalance**
|
||||||
|
Expensive parsing, key lookup, cryptography, decompression, or external requests happen before authentication and the earliest size/rate gate. Compare minimal requester effort to shared service cost and check upstream limits.
|
||||||
|
|
||||||
|
**Quota-accounting scope and reset gaps**
|
||||||
|
Accounting uses attacker-influenceable IP, route, tenant, key prefix, task ID, or other dimension, allowing one principal's work to escape its intended budget or consume another principal's allocation. Review integer overflow, distributed races, retries, reconnects, and account switching.
|
||||||
|
|
||||||
|
**Worker, pool, and priority starvation**
|
||||||
|
Low-priority or attacker-controlled jobs hold shared locks, workers, database pools, event-loop turns, or scheduler priority needed by unrelated users. Require a path that bypasses queue/concurrency fairness or retains a slot beyond its deadline.
|
||||||
|
|
||||||
|
## Failure and recovery attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Reachable fatal error or deadlock**
|
||||||
|
An untrusted input reaches `panic`, abort, fatal assertion, unhandled exception, process exit, lock cycle, or infinite loop in a shared process. Confirm supervisor scope and whether one worker or the whole service becomes unavailable. A restarted isolated worker may reduce impact but does not erase the defect.
|
||||||
|
|
||||||
|
**Retry storm and fail-open amplification**
|
||||||
|
Timeouts, dependency errors, partially processed messages, or health-check failures trigger synchronized or unbounded retries without jitter, ceilings, circuit breaking, or deduplication. Verify one bounded failure source can create persistent aggregate work.
|
||||||
|
|
||||||
|
**Poison-record and head-of-line blocking**
|
||||||
|
One malformed record or message repeatedly fails at the front of a shared queue, partition, startup scan, migration, or recovery loop. Review skip/quarantine policy, offsets, and whether other tenants share the blocked unit.
|
||||||
|
|
||||||
|
**Unsafe recovery and capacity rollback**
|
||||||
|
A restart, restore, fallback, or cleanup path rebuilds unbounded state, ignores current quotas, or restores the input that immediately repeats failure. Recovery correctness is part of availability.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Build an input-to-resource table: earliest accepted size/cardinality, work before auth, downstream fan-out, persistence, shared pool, limit and cleanup owner, recovery.
|
||||||
|
- Compare aggregate limits with per-object limits. Ten thousand valid one-byte items may evade a per-message cap while exhausting tenant-wide or process-wide state.
|
||||||
|
- Validate only in an isolated fixture with strict CPU/memory/time limits and small growth points. Mock external and paid calls and stop once the missing bound or cancellation is observable.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Name untrusted input, requester work, service amplification or retained resource, shared blast radius, and recovery. Missing limits without concrete shared impact are hardening.
|
||||||
|
2. Confirm no source-visible upstream, parser, queue, tenant, or framework bound prevents the path. Unknown deployed controls require `needs_validation`.
|
||||||
|
3. For superlinear behavior, establish the accepted complexity and bounded local growth. For leaks, show repeatable retention after cleanup should occur. For fatal paths, identify process/supervisor isolation.
|
||||||
|
4. Prioritize by low requester work, unauthenticated reachability, cross-tenant scope, persistence, and poor recovery; do not validate with availability impact.
|
||||||
|
5. Return `confirmed` only with safe local proof and meaningful shared effect. Return `needs_validation` with the exact upstream limit, topology, quota, or recovery observation an owner must check.
|
||||||
192
.agents/skills/security-audit/SKILL.md
Normal file
192
.agents/skills/security-audit/SKILL.md
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
---
|
||||||
|
name: security-audit
|
||||||
|
description: Security guidance and vulnerability review for codebases, APIs, services, CLI tools, libraries, and daemons. Use for security questions, focused reviews, vulnerability research, security audits, or pen tests. Run the complete workflow only for explicit codebase audit or pen-test requests, full/comprehensive/end-to-end reviews, or requested report artifacts.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Security Audit
|
||||||
|
|
||||||
|
Find vulnerabilities that violate a real trust boundary, then give owners the source evidence, safe reproduction, priority, and smallest effective fix. This is a defensive, source-first workflow. A candidate without a concrete affected principal, resource, or security outcome is not a confirmed finding.
|
||||||
|
|
||||||
|
## Operating modes
|
||||||
|
|
||||||
|
This skill is guidance by default. Loading it does not authorize the complete audit workflow or file creation.
|
||||||
|
|
||||||
|
- **Guidance mode**: For security questions, focused reviews, methodology, triage, or investigation of specific findings, use only the relevant parts of this skill. Do not automatically run all six phases, create an output directory, or write audit artifacts. You may launch focused agents when useful; they return results to the current task.
|
||||||
|
- **Full audit mode**: Use the complete workflow when the user explicitly asks to audit or pen-test a codebase, asks for a full, comprehensive, or end-to-end security review, or requests report artifacts. Run all six phases and write the files defined below.
|
||||||
|
|
||||||
|
If the request could mean either mode, ask one focused question before creating files or starting the complete workflow.
|
||||||
|
|
||||||
|
## Platform terminology
|
||||||
|
|
||||||
|
This skill is agent-neutral:
|
||||||
|
|
||||||
|
- **Parent** is the agent that coordinates the run and owns shared state.
|
||||||
|
- **Task tool** is the platform's delegation or sub-agent mechanism.
|
||||||
|
- **`research` agent** is a delegated agent for focused source exploration and factual verification.
|
||||||
|
- **`general` agent** is a delegated agent for broad investigation and bounded local execution.
|
||||||
|
- **`subagent_type:`** in a heading names which of these two delegated agent roles runs that work.
|
||||||
|
|
||||||
|
Use equivalent platform capabilities while preserving role, write-isolation, prompt, and independence boundaries.
|
||||||
|
|
||||||
|
## Universal execution safety
|
||||||
|
|
||||||
|
These rules apply in both operating modes. Source inspection is read-only. Run target-controlled builds, tests, processes, browsers, emulators, fuzzers, and fixture processing only inside an OS-enforced sandbox that provides all of these controls:
|
||||||
|
|
||||||
|
- no external network; use only an isolated loopback namespace when the check needs local client/server traffic;
|
||||||
|
- an empty environment populated from an explicit allowlist with safe values, with scratch-local `HOME`, temporary directories, and caches;
|
||||||
|
- a read-only target and toolchain, with the target-controlled process able to write only inside its assigned `scratch/` directory; and
|
||||||
|
- explicit low CPU, memory, process, file-size, disk, and wall-clock limits.
|
||||||
|
|
||||||
|
The agent, outside the target-controlled process, may make a disposable source copy in an assigned `scratch/` directory when a build must write beside source. In guidance mode, do not retain target-controlled files. In full audit mode, only trusted parent-side code may promote the minimum non-secret result to retained `artifacts/` using the procedure under Write isolation. Never expose a retained output directory (other than the agent's own assigned `scratch/`), another agent's directory, the host home directory, credentials, sockets, or shared services to target code. Do not install dependencies or let builds fetch them. Use only tools and dependencies already available locally. If every control cannot be enforced, do not execute target code: report the missing sandbox capability as a needs-validation blocker and give a safe validation plan.
|
||||||
|
|
||||||
|
Use dummy principals, fixtures, and secrets. Do not probe deployed endpoints, external services, shared infrastructure, production identities, other users' data, or live control planes. Do not test availability against a live or shared process, publish artifacts, alter releases, spend paid API quota, or continue beyond the minimum local effect needed to establish a defect. If the decisive fact is outside source or the sandboxed fixture, report it as needing validation.
|
||||||
|
|
||||||
|
## Full audit setup
|
||||||
|
|
||||||
|
In full audit mode, resolve these values before reconnaissance:
|
||||||
|
|
||||||
|
- **Skill directory**: the absolute directory containing this `SKILL.md`.
|
||||||
|
- **Target**: the absolute repository root under review.
|
||||||
|
- **Repo name**: a stable repository identifier from the directory or local Git remote.
|
||||||
|
- **Output directory**: a new writable directory outside the target, defaulting to `~/security-audit-skill/<repo-name>/run-<N>`, where `<N>` is the next unused integer. Use a directory inside the target only when the user explicitly selects it and the parent verifies that version control ignores the whole directory. Otherwise stop and request an external path.
|
||||||
|
- **Source ref**: the reviewed commit and whether the worktree is dirty. Do not treat unreviewed generated or modified files as another revision.
|
||||||
|
|
||||||
|
### Write isolation
|
||||||
|
|
||||||
|
The parent creates and is the only writer of shared run files:
|
||||||
|
|
||||||
|
- `run-metadata.json`
|
||||||
|
- `architecture.md`
|
||||||
|
- `coverage-ledger.json`
|
||||||
|
- `findings.json`
|
||||||
|
- `REPORT.md`
|
||||||
|
- `FINDINGS-DETAIL.md`
|
||||||
|
- `NEEDS-VALIDATION.md`
|
||||||
|
|
||||||
|
Each hunter or verifier receives a unique root under `<output-dir>/agents/<agent-id>/`, with separate `scratch/` and `artifacts/` directories. Canonical agent IDs match `^[a-z0-9][a-z0-9_-]{0,63}$` and must not equal a Windows device name such as `con`, `prn`, `aux`, `nul`, `com1` through `com9`, or `lpt1` through `lpt9`. Lowercase IDs prevent case-fold collisions. The agent and every target-controlled process may write only to `scratch/`; retained `artifacts/` is parent-owned, is never exposed to the sandbox, and is writable only by trusted parent-side promotion code. Agents may not change shared files, target source, retained artifacts, or another agent's directory. Do not use `/tmp` or the host home directory as a writable fallback.
|
||||||
|
|
||||||
|
Before execution, the parent opens and retains trusted, non-inheritable directory descriptors for the agent's `scratch/` and `artifacts/` roots, and records an allowlist of expected scratch-relative artifact files plus explicit per-file and cumulative byte limits. Never pass those descriptors to the agent or sandbox. After the sandbox and all its processes terminate, trusted parent-side code promotes each allowlisted file separately:
|
||||||
|
|
||||||
|
1. Validate the declared relative path: reject absolute, empty, `.`, `..`, or symlinked components.
|
||||||
|
2. Walk each parent component from the retained scratch-root descriptor with no-follow directory-relative operations; never reopen by path.
|
||||||
|
3. Open the leaf no-follow and nonblocking.
|
||||||
|
4. Verify with `fstat` that it is a regular file with link count exactly one and within the recorded per-file and cumulative byte limits.
|
||||||
|
5. Enforce those limits again while reading from that descriptor.
|
||||||
|
6. Copy exactly the verified size, repeat `fstat`, and reject a changed identity, type, link count, or size.
|
||||||
|
7. For the destination, walk every parent component from the retained artifacts-root descriptor with no-follow directory-relative operations; require each existing component to be a real directory, and create any missing directory exclusively before reopening and verifying it no-follow.
|
||||||
|
8. Create the leaf exclusively without following links, verify that the opened destination is a regular file with link count exactly one, and copy from the verified source descriptor without reopening either path.
|
||||||
|
9. Use equivalent race-safe APIs on non-POSIX systems.
|
||||||
|
10. Never recursively copy or glob scratch, extract an archive into artifacts, or open or promote a symlink, FIFO, socket, device, directory, hard-linked file, changing file, or file that exceeds its bound.
|
||||||
|
11. If any check is unavailable, cannot be enforced, or fails, discard the scratch entry; if it is decisive evidence, retain `needs_validation` with the exact promotion blocker.
|
||||||
|
|
||||||
|
[HUNTING.md](HUNTING.md) and [VALIDATION-AND-REPORTING.md](VALIDATION-AND-REPORTING.md) carry this procedure as one identical fenced block for hunter and verifier prompts; it states the same rules in the same order as this list.
|
||||||
|
|
||||||
|
For a reproduced check, record the command, exact test input, sandbox limits, and only the allowlisted environment variable names plus safe non-secret values needed to reproduce it. Never capture or copy the ambient environment, inherited variables, credential values, authentication state, or unrelated host paths. Launch from an empty environment rather than trying to redact one after execution.
|
||||||
|
|
||||||
|
Before delegation, the parent writes `run-metadata.json` with at least `run_id`, `repo`, `target`, `source_ref`, `profile`, `scope_paths`, `budget` (null if unset), `execution_policy: "sandboxed-source-and-local-only"`, selected companion files, prior-run paths, shared-file owners, and `run_status: "in_progress"`. Update metadata only when those facts change; candidate state belongs in the coverage ledger and `findings.json`.
|
||||||
|
|
||||||
|
## Full audit planning
|
||||||
|
|
||||||
|
The coverage, prior-run, profile, and budget requirements in this section apply only in full audit mode.
|
||||||
|
|
||||||
|
### Coverage and prior runs
|
||||||
|
|
||||||
|
No one pass is complete. Build a deterministic coverage plan before hunting and update it after every agent result. [RECONNAISSANCE.md](RECONNAISSANCE.md) defines the stable coverage units and [HUNTING.md](HUNTING.md) defines coverage-critic waves. The parent alone updates the ledger.
|
||||||
|
|
||||||
|
If prior runs exist, read every compatible `coverage-ledger.json` and `findings.json` before planning the current run:
|
||||||
|
|
||||||
|
1. Compare the relevant current source with each prior record and unit. A prior source ref alone is not evidence that a path is unchanged.
|
||||||
|
2. Carry a prior `confirmed` record into the current candidate set only when its relevant source and conditions are unchanged and its evidence still meets the current contract. Link it to a current ledger unit seeded `planned`, preserve its fingerprint, exclude only that carried root cause from hunters, and send the carried record through the current final verification path; the Phase 3 verifier that re-checks it becomes that unit's assignment owner and moves it to `candidate`.
|
||||||
|
3. When relevant source for a prior `confirmed` record changed, create a current planned revalidation unit. Do not put that record on the hunter exclusion list. It remains confirmed only if current independent validation establishes the current path and result.
|
||||||
|
4. Make prior `needs_validation`, `deferred`, `blocked`, `out_of_scope`, and any changed-source unit current work. A still-external `needs_validation` record may be carried only after the current source trace is checked and linked by fingerprint to a current `planned` unit whose verifier re-check supplies its owner and evidence; the record keeps the unresolved blocker. These prior states never suppress a current unit.
|
||||||
|
5. A prior same-source covered unit may inform priority, but it remains visible in the current ledger. A prior `rejected` record suppresses only the unchanged failed claim, not coverage of its unit; changed evidence creates current work.
|
||||||
|
6. Read the prior profile and scope. A prior `quick` or scoped ledger contributes only its recorded evidence and gaps, never an implied "rest is fine."
|
||||||
|
|
||||||
|
If no prior ledger exists, say so in the final coverage statement. Never imply that one run exhausts the target.
|
||||||
|
|
||||||
|
### Run profiles and scope
|
||||||
|
|
||||||
|
During full audit setup, pick a profile from the user's request or propose one from the target's size and stakes. Record it in `run-metadata.json` (`profile`, `scope_paths`) and state it in the report. The default is `standard`.
|
||||||
|
|
||||||
|
- **`quick`** — a bounded pass for small targets, re-runs, or a fast first look. Coarsen ledger units to surface × boundary × attack class (subsystem uses the fixed canonical `profile/quick/all-in-scope-subsystems` identifier), run exactly one hunter wave followed by exactly one final coverage-critic pass, and use one fresh verifier per candidate for both candidate validation and final record verification. Do not launch a follow-up hunter wave: record the critic's accepted discoveries and reassignments as `deferred`.
|
||||||
|
- **`standard`** — the workflow as written.
|
||||||
|
- **`deep`** — for high-stakes or large targets. Split ledger units per subsystem and lifecycle mode, run critic waves to a clean pass, keep candidate validation and final record verification as separate fresh agents, and give `prior_covered_same_source` units an independent second pass.
|
||||||
|
|
||||||
|
A **scoped run** audits a subset: named paths, one subsystem, one companion domain, or the diff between two source refs. Seed ledger units only for in-scope surfaces and record everything else as `out_of_scope` — never as `covered`. A scoped or `quick` run must present itself as partial coverage.
|
||||||
|
|
||||||
|
Profiles change breadth and redundancy, never the evidence bar. Do not scale away the candidate gate, the source/local execution boundary, `needs_validation` discipline, schema validation, or independent verification of `confirmed` records.
|
||||||
|
|
||||||
|
#### Cost budget
|
||||||
|
|
||||||
|
The ledger makes spend countable: one unit is roughly one hunter assignment, and one surviving candidate is one or two verifier assignments depending on profile. When the user sets a budget — or the parent proposes one for a large target — record `budget` in `run-metadata.json` as a maximum number of agent invocations across all phases.
|
||||||
|
|
||||||
|
Apply the strict budget gate before launching any reconnaissance agent. Reserve the four baseline reconnaissance calls, one final post-wave critic for `quick` or one post-wave plus one distinct final-clean critic for `standard`/`deep`, and at least one verifier call. Add focused reconnaissance only after repeating this gate for each extra call. If the requested budget cannot fund that minimum, launch no agent: ask for a larger budget, narrower scope, or different profile. If the request remains unchanged, set `run_status: "incomplete"` with `incomplete_reason: "budget_cannot_fund_reconnaissance_and_reserves"` and report that no audit pass ran.
|
||||||
|
|
||||||
|
Spend it in this order:
|
||||||
|
|
||||||
|
1. Count reconnaissance, every post-wave critic, and the separate final-clean critic as agent invocations.
|
||||||
|
2. **Reserve critics and validation before hunting.** For `quick`, reserve its one post-wave final critic. Before every `standard` or `deep` hunter wave, reserve one immediate post-wave critic plus one distinct final-clean critic. Also reserve verifier cost from the profile (about 1 or 2 agents per expected candidate; when in doubt reserve 30% of the balance after critic reservation). Never assign hunters into either reserve.
|
||||||
|
3. Assign hunters to units in priority order until the hunting allowance is spent. Spend the reserved post-wave critic immediately after that wave; keep the final-clean and validation reserves intact.
|
||||||
|
4. Before a later wave, reserve its new post-wave critic again. If the remaining budget cannot cover the required critic calls and validation reserve, launch no hunters from that wave, mark its planned units `deferred` with reason `budget_cannot_reserve_critics_and_validation`, and use the retained final-clean critic to record the resulting gap.
|
||||||
|
|
||||||
|
Before wave 1, update the pre-recon estimate with seeded units, implied hunter count, mandatory critic calls, validation reserve, and whether the remaining budget covers the plan. If it clearly cannot, say so and propose either a tighter scope or a coarser profile instead of silently thinning evidence. If later facts consume the required final-critic reserve, launch no hunters, mark all planned work deferred, set the run incomplete with reason `critic_budget_exhausted`, and make no complete-coverage claim.
|
||||||
|
|
||||||
|
A strict total-agent budget can still be exceeded by an unexpectedly large candidate set or by a material Phase 5 replacement that needs another independent verifier. If the remaining budget cannot validate every candidate, stop hunting, validate candidates in fingerprint order while the budget permits, and set `run_status: "incomplete"` plus `incomplete_reason: "validation_budget_exhausted"`. Keep each unvalidated fingerprint linked to a `candidate` ledger unit with that unresolved reason. Do not put an unvalidated candidate in `findings.json`, relabel it `needs_validation`, or report the run as complete. Phase 6 may produce a partial report only if its first section states that candidate validation is incomplete and lists the affected fingerprints and units. Never exceed a user-set strict budget silently.
|
||||||
|
|
||||||
|
## Core principles
|
||||||
|
|
||||||
|
### Require a boundary and result
|
||||||
|
|
||||||
|
For every candidate, name the lower-trust principal, accepted input or action, intended control, crossed boundary, affected principal or resource, and concrete observed or owner-observable result. Do not elevate a missing best practice, guessed deployment behavior, generic parser crash, or self-impact into a security finding.
|
||||||
|
|
||||||
|
### Use bounded local evidence
|
||||||
|
|
||||||
|
Static analysis establishes the source path. Sandboxed local tests resolve behavior when all execution controls are available: a minimal function harness, existing unit test, small parser fixture, dummy-tenant integration test, locally rendered configuration, or bounded isolated-loopback client. Stop at a wrong return value, unauthorized dummy record, sanitizer finding, policy difference, or other minimum effect. Do not extend the local check beyond the minimum boundary result or produce persistence, post-fault, or concealment material.
|
||||||
|
|
||||||
|
### Respect source visibility
|
||||||
|
|
||||||
|
Deployment controls, proxy behavior, provider settings, browser headers, identity policy, broker ACLs, packaging, and topology are real controls. If they are required and absent from the repository, do not assume either presence or absence. Use `needs_validation` with the exact missing fact and a safe owner-observed or local plan.
|
||||||
|
|
||||||
|
### Separate priority from certainty
|
||||||
|
|
||||||
|
Only `confirmed` records receive severity. Likelihood and impact must reflect the demonstrated conditions and result; overall severity cannot exceed demonstrated impact. `needs_validation` means a specific source-grounded boundary hypothesis is blocked, not a low-confidence confirmed vulnerability, and it has no severity.
|
||||||
|
|
||||||
|
Calibrate overall severity with these anchors:
|
||||||
|
|
||||||
|
- **critical** — an unauthenticated actor gains code execution, full data-store access, or takeover of arbitrary accounts.
|
||||||
|
- **high** — an actor fully defeats an explicit security control with real consequences: authentication bypass, cross-tenant read or write, stored script execution affecting other users, authenticated code execution, or an unauthenticated remote stop of a shared service.
|
||||||
|
- **medium** — a real boundary violation with limited blast radius, uncommon preconditions, or consequences confined to a narrow resource set.
|
||||||
|
- **low** — disclosure of non-secret internals, or an effect requiring sustained effort for minimal gain.
|
||||||
|
- **informational** — a confirmed but minimal-impact observation, useful mainly as a prerequisite inside a larger finding.
|
||||||
|
|
||||||
|
The high/medium discriminator: does the demonstrated result fully defeat an explicit control for an action with real consequences, or only weaken it? If you cannot state the concrete damage, the severity is lower than it feels.
|
||||||
|
|
||||||
|
### Recommend the smallest effective source fix
|
||||||
|
|
||||||
|
For each confirmed finding, identify the invariant the code must enforce and the narrowest source change that enforces it at the last trusted decision point. Prefer specific repository-relative changes and regression tests over generic hardening advice. The audit describes fixes; it does not modify target source.
|
||||||
|
|
||||||
|
## Full audit workflow
|
||||||
|
|
||||||
|
In full audit mode, follow all six phases in order:
|
||||||
|
|
||||||
|
1. **Reconnaissance** — map the source, trust boundaries, local build paths, companion selections, prior evidence, and initial deterministic coverage ledger with [RECONNAISSANCE.md](RECONNAISSANCE.md).
|
||||||
|
2. **Coverage-led hunting waves** — assign isolated hunters from the ledger and collect structured candidate results with [HUNTING.md](HUNTING.md), [ATTACK-CLASSES.md](ATTACK-CLASSES.md), and the selected domain companions.
|
||||||
|
3. **Candidate validation** — consolidate fingerprints and give every candidate to a fresh source verifier as defined in [VALIDATION-AND-REPORTING.md](VALIDATION-AND-REPORTING.md).
|
||||||
|
4. **Structured output** — write all final `confirmed`, `needs_validation`, and `rejected` records to `findings.json`; validate it with `report-schema.json` and `validate-findings.cjs`, and validate the coverage claim with `validate-coverage-ledger.cjs`.
|
||||||
|
5. **Independent record verification** — use fresh agents to verify final source claims and reconcile corrections or state changes.
|
||||||
|
6. **Target-neutral report** — derive `REPORT.md`, `FINDINGS-DETAIL.md`, and `NEEDS-VALIDATION.md` from the final records, with no live-probe instructions.
|
||||||
|
|
||||||
|
Do not end the run before one of exactly two terminal states: (a) all Phase 6 artifacts are written and both validators pass, or (b) `run_status: "incomplete"` is recorded with its exact reason and the gap is disclosed in the report. Never stop mid-phase.
|
||||||
|
|
||||||
|
## Anti-patterns
|
||||||
|
|
||||||
|
1. Checklist deviations presented as vulnerabilities.
|
||||||
|
2. Defense-in-depth advice with no reachable boundary violation.
|
||||||
|
3. Live or shared-environment testing where bounded local evidence is insufficient.
|
||||||
|
4. Guessing provider, proxy, browser, identity, or deployment behavior not present in source.
|
||||||
|
5. Treating intended same-principal authority or self-impact as a cross-boundary result.
|
||||||
|
6. Reporting a parser or runtime effect stronger than the observed effect.
|
||||||
|
7. Emitting prose-only hunter results that cannot be deduplicated or verified.
|
||||||
|
8. Re-reporting carried same-source prior confirmed records or using them as exemplars that anchor the hunt.
|
||||||
|
9. Assigning severity to `needs_validation` records.
|
||||||
|
10. Writing the report before independent verification or letting prose and JSON disagree.
|
||||||
73
.agents/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md
Normal file
73
.agents/skills/security-audit/SUPPLY-CHAIN-AND-RELEASE.md
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
# Supply Chain and Release Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the target resolves dependencies, builds from untrusted contributions, runs CI, creates release artifacts, signs or promotes builds, loads plugins, or updates deployed software. This domain covers trust handoffs from source and dependency to the artifact a user runs. Use `MEMORY-SAFETY-AND-BINARY.md` for flaws inside a local binary loader and `CLOUD-AND-DEPLOYMENT.md` for runtime workload authority.
|
||||||
|
|
||||||
|
Split large targets into dependency resolution, CI isolation, artifact provenance, release authorization, and updater/plugin trust.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- A mutable or known-vulnerable dependency is not a finding by itself. Show who can influence resolution, which build consumes it, and what execution or release boundary follows.
|
||||||
|
- Follow integrity across every handoff: source identity, resolved inputs, build worker, artifact identity, test result, signature/attestation, promotion, and update consumer.
|
||||||
|
- CI configuration is authorization code. Establish which event triggered a workflow, whose code runs, which secrets and tokens exist, and what it may publish or mutate.
|
||||||
|
- A checksum fetched from the same untrusted location as the artifact does not establish independent integrity. Identify the trusted root and failure behavior.
|
||||||
|
- Use `confirmed` for in-repo control-flow failures with bounded local validation. Use `needs_validation` for branch protection, hosted-runner, registry, signing-service, or production promotion facts that are not observable.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dependency and build-input attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Dependency source and namespace confusion**
|
||||||
|
Resolver configuration can select an unintended public/private namespace, fallback registry, mirror, repository, or source URL. Review package names, source priority, lockfile and checksum use, alternate build files, platform-specific resolution, and first-install versus update behavior.
|
||||||
|
|
||||||
|
**Mutable and unbound build inputs**
|
||||||
|
Builds consume branches, tags, unverified submodules, downloaded tools, generated assets, remote includes, floating CI actions, or container tags whose content can change without source review. Require a lower-trust writer and a path into trusted build output; reproducibility by itself does not prove authenticity.
|
||||||
|
|
||||||
|
**Generated-source and codegen provenance gaps**
|
||||||
|
Schemas, vendored archives, generated clients, localization, documentation examples, or binary blobs produce executable or shipped content without the same review and integrity gate as source. Compare local regeneration with committed output and verify who controls input and generator.
|
||||||
|
|
||||||
|
**Build-context inclusion**
|
||||||
|
Secrets, local configuration, repository metadata, test fixtures, or developer artifacts enter a package or image because the build context and ignore rules exceed intended release inputs. Confirm that the resulting artifact exposes a real credential, private data, or privileged configuration.
|
||||||
|
|
||||||
|
## CI and automation attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Untrusted code in a privileged workflow**
|
||||||
|
A pull request, issue comment, fork, dependency update, or external event runs contributor-controlled code with protected secrets, write tokens, deployment authority, or a trusted runner. Compare trigger type, checkout ref, approval gate, environment protection, and permission narrowing. Do not assume repository-host defaults that are not in source.
|
||||||
|
|
||||||
|
**Workflow command and expression confusion**
|
||||||
|
Attacker-controlled branch names, commit messages, issue fields, artifact names, matrix values, or generated output enter shell commands, template expressions, paths, or privileged workflow inputs without canonical validation.
|
||||||
|
|
||||||
|
**Cache, artifact, and workspace trust mixing**
|
||||||
|
A lower-trust job can populate a cache, artifact, shared workspace, or output that a higher-trust job later restores and executes or releases. Review cache keys and namespaces, artifact producer identity, digest binding, retention, and whether promotion re-resolves by mutable name.
|
||||||
|
|
||||||
|
**Automation identity overreach**
|
||||||
|
CI jobs receive permissions beyond the operation, repository, environment, or duration needed, and untrusted job inputs can select the affected resource. Missing least privilege alone is hardening; require a reachable privileged action.
|
||||||
|
|
||||||
|
## Release and update attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Build-to-promotion substitution**
|
||||||
|
Tests, review, signature, and publication refer to mutable tags, filenames, channels, or artifact IDs rather than the same immutable digest. Check every copy, repack, architecture merge, and provenance step between build and release.
|
||||||
|
|
||||||
|
**Release authorization and signing-policy gaps**
|
||||||
|
A release or signature is accepted from the wrong workflow, repository, branch, environment, key role, or threshold. Review identity claims inside attestations and verify the consumer validates them, not just a valid signature. Rotation, expiry, and revocation must fail closed where policy requires.
|
||||||
|
|
||||||
|
**Update metadata and rollback confusion**
|
||||||
|
An updater authenticates payload bytes but not version, product, platform, channel, target path, expiry, or rollback state, or it accepts metadata and payload from different authorized transactions. Verify atomic installation and recovery behavior. A signature API call without policy binding is incomplete.
|
||||||
|
|
||||||
|
**Plugin and extension trust expansion**
|
||||||
|
An extension package gains host authority beyond its declared scope, a lower-trust publisher can replace another publisher's identity, or install/update hooks run before authenticity and capability checks. Intended installation of arbitrary same-user plugins is not a privilege boundary.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Walk backward from a released digest or installed update to every source, generated input, credential, worker, cache, test result, and authorization decision.
|
||||||
|
- Compare untrusted and protected workflow events side by side. Mark each persisted channel crossing between them and require an immutable identity plus producer trust.
|
||||||
|
- Review revoked key, failed download, missing attestation, partial platform release, rollback, and registry outage paths. The failure policy is part of release integrity.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Name the lower-trust actor, controllable source/cache/artifact/metadata, consuming trusted job or updater, and resulting unauthorized publication, code inclusion, secret disclosure, or privileged execution.
|
||||||
|
2. Prove artifact identity across the broken handoff. A different mutable name or unbound digest must reach a real consumer.
|
||||||
|
3. Verify built-in package-manager, repository-host, registry, and signing defaults for the pinned version. Unknown hosted controls require `needs_validation`.
|
||||||
|
4. Keep local validation bounded: use a harmless fixture repository, dummy credential marker, local registry/config, and non-production artifact namespace. Do not publish or alter a real release.
|
||||||
|
5. Return `confirmed` only with a complete source-visible handoff and meaningful result. Return `needs_validation` with the precise branch, runner, registry, signing, or deployment fact an owner must observe.
|
||||||
186
.agents/skills/security-audit/VALIDATION-AND-REPORTING.md
Normal file
186
.agents/skills/security-audit/VALIDATION-AND-REPORTING.md
Normal file
@ -0,0 +1,186 @@
|
|||||||
|
# Validation, Structured Output, Verification, and Reporting
|
||||||
|
|
||||||
|
### Phase 3: Independently validate every candidate
|
||||||
|
|
||||||
|
After the clean coverage-critic pass or an explicitly recorded early stop, consolidate Phase 2 candidates and carried same-source prior confirmations by stable fingerprint and root cause. Give every unique proposed `confirmed` and `needs_validation` candidate to a fresh `general` verifier that did not hunt it. A carried prior confirmation follows the same current verification path even though hunters exclude that unchanged root cause. A verifier may read hunter or prior artifacts but must re-read every cited current source location and independently run any decisive check it can reproduce safely.
|
||||||
|
|
||||||
|
Assign each verifier a canonical lowercase unique ID and `<output-dir>/agents/<verifier-id>/scratch/` plus parent-owned `artifacts/`. The verifier writes only to `scratch/` and never writes retained artifacts. It receives only the candidate, its linked coverage-unit checks and artifact paths, architecture facts needed to interpret the path, exact relevant companion validation blocks, the promotion procedure block below, the source/local execution boundary, the `confirmed`, `needs_validation`, and `rejected` branches of `report-schema.json` copied verbatim, and prior records with the same fingerprint. It must not receive another verifier's conclusion.
|
||||||
|
|
||||||
|
#### Candidate-verifier prompt
|
||||||
|
|
||||||
|
```text
|
||||||
|
You did not write this candidate. Try to refute it from repository source and bounded
|
||||||
|
local evidence. Do not contact deployed endpoints or external/shared services. Run
|
||||||
|
target-controlled code only inside the approved OS-enforced sandbox: no external
|
||||||
|
network, empty allowlisted environment, read-only target and tools, scratch-only
|
||||||
|
writes, and explicit low resource and wall-clock limits. If any control is unavailable,
|
||||||
|
do not execute; retain the exact missing capability as a needs_validation blocker.
|
||||||
|
Treat every scratch entry as target-controlled after execution. After the sandbox and
|
||||||
|
all its processes terminate, only trusted parent-side code may promote a predeclared
|
||||||
|
scratch-relative file, following the promotion procedure block included verbatim in
|
||||||
|
this prompt. You and target code never write retained artifacts. If promotion is
|
||||||
|
unavailable or fails, do not use that file as evidence.
|
||||||
|
|
||||||
|
1. Verify every trace and evidence file, positive line number, scope, and description.
|
||||||
|
Confirm the first entry is a real lower-trust entrypoint and the last is the
|
||||||
|
claimed sink or boundary effect.
|
||||||
|
2. Reconstruct the strongest source-visible validation, identity, authorization,
|
||||||
|
normalization, lifecycle, framework, and containment controls on the path.
|
||||||
|
Where the architecture summary names a comparable baseline, note whether it
|
||||||
|
shares the pattern — as calibration, never as grounds to dismiss.
|
||||||
|
3. For a proposed confirmed candidate, independently reproduce the minimum observed
|
||||||
|
result when possible. Verify inputs, interface shape, conditions, and affected
|
||||||
|
dummy principal/resource. Do not infer a stronger result or continue after it.
|
||||||
|
4. Verify that likelihood, impact, confidence, and the proposed source fix match only
|
||||||
|
what the evidence establishes.
|
||||||
|
5. For a proposed needs_validation candidate, decide whether the blocker is genuinely
|
||||||
|
outside source/local observation. If source refutes the trace, reject it. If the
|
||||||
|
missing fact remains decisive, keep needs_validation and make the local and
|
||||||
|
owner-observed plans exact and non-destructive.
|
||||||
|
6. Preserve the fingerprint for the same source-derived root cause across every state.
|
||||||
|
|
||||||
|
Return exactly one JSON object and no surrounding prose:
|
||||||
|
{"decision": "confirmed|needs_validation|rejected", "record": { ... }}
|
||||||
|
where record exactly matches the decision's verdict branch of the schema included
|
||||||
|
in this prompt. A corrected record replaces the hunter's wording.
|
||||||
|
```
|
||||||
|
|
||||||
|
Copy this promotion procedure verbatim into every candidate-verifier prompt:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Artifact promotion procedure (trusted parent-side code only):
|
||||||
|
Reference only for you: the parent performs these steps; you never perform them.
|
||||||
|
|
||||||
|
Before execution, the parent opens and retains trusted, non-inheritable directory
|
||||||
|
descriptors for the agent's scratch/ and artifacts/ roots, and records an allowlist
|
||||||
|
of expected scratch-relative artifact files plus explicit per-file and cumulative
|
||||||
|
byte limits. Never pass those descriptors to the agent or sandbox. After the sandbox
|
||||||
|
and all its processes terminate, trusted parent-side code promotes each allowlisted
|
||||||
|
file separately:
|
||||||
|
|
||||||
|
1. Validate the declared relative path: reject absolute, empty, `.`, `..`, or
|
||||||
|
symlinked components.
|
||||||
|
2. Walk each parent component from the retained scratch-root descriptor with
|
||||||
|
no-follow directory-relative operations; never reopen by path.
|
||||||
|
3. Open the leaf no-follow and nonblocking.
|
||||||
|
4. Verify with `fstat` that it is a regular file with link count exactly one and
|
||||||
|
within the recorded per-file and cumulative byte limits.
|
||||||
|
5. Enforce those limits again while reading from that descriptor.
|
||||||
|
6. Copy exactly the verified size, repeat `fstat`, and reject a changed identity,
|
||||||
|
type, link count, or size.
|
||||||
|
7. For the destination, walk every parent component from the retained
|
||||||
|
artifacts-root descriptor with no-follow directory-relative operations; require
|
||||||
|
each existing component to be a real directory, and create any missing directory
|
||||||
|
exclusively before reopening and verifying it no-follow.
|
||||||
|
8. Create the leaf exclusively without following links, verify that the opened
|
||||||
|
destination is a regular file with link count exactly one, and copy from the
|
||||||
|
verified source descriptor without reopening either path.
|
||||||
|
9. Use equivalent race-safe APIs on non-POSIX systems.
|
||||||
|
10. Never recursively copy or glob scratch, extract an archive into artifacts, or
|
||||||
|
open or promote a symlink, FIFO, socket, device, directory, hard-linked file,
|
||||||
|
changing file, or file that exceeds its bound.
|
||||||
|
11. If any check is unavailable, cannot be enforced, or fails, discard the scratch
|
||||||
|
entry; if it is decisive evidence, retain `needs_validation` with the exact
|
||||||
|
promotion blocker.
|
||||||
|
```
|
||||||
|
|
||||||
|
A verifier can promote `needs_validation` to `confirmed` only after independently establishing the complete path and bounded observed result. Demote proposed confirmation to `needs_validation` when a specific deployment or runtime fact remains unknown. Use `rejected` when source, local behavior, a visible control, missing meaningful impact, or an impossible prerequisite refutes the claim. `needs_validation` is never a parking place for a speculative idea.
|
||||||
|
|
||||||
|
The parent checks that each verifier returned the same fingerprint unless it identified a genuinely different root cause. Merge corrections, record the decision in every linked coverage unit, and ensure there is one final record per fingerprint. Discard a malformed or prose-wrapped verifier result without repairing it; re-run that candidate with a fresh verifier when the budget permits, otherwise it remains an unvalidated ledger candidate under the incomplete-run rule.
|
||||||
|
|
||||||
|
When verifier evidence updates a ledger check, set that check's `agent_id` to the verifier's canonical ID and list its nonempty repository-relative `reviewed_paths`. Keep the unit-level `reviewed_paths` equal to the union across checks. Use `method: "source"` with `artifact: null` for source-only review. Use `method: "local"` only with a file successfully promoted by trusted parent-side code below `agents/<check.agent_id>/artifacts/`. The unit retains its original assignment owner, so independently owned hunter and verifier checks can coexist. For a carried prior record's seeded `planned` unit there is no prior owner: the verifier that re-checks it becomes the unit's assignment owner, and its re-check is the unit's first check, moving the unit to `candidate` with the carried fingerprint.
|
||||||
|
|
||||||
|
If a strict total-agent budget cannot cover every candidate, set the run status to incomplete and follow the deterministic budget rule in `SKILL.md`. An unvalidated candidate remains only in the ledger. It does not enter `findings.json` under any verdict.
|
||||||
|
|
||||||
|
### Phase 4: Write and validate `findings.json`
|
||||||
|
|
||||||
|
The parent writes all independently decided records to `<output-dir>/findings.json`, sorted by fingerprint. Include:
|
||||||
|
|
||||||
|
- `confirmed`: source-grounded vulnerabilities with complete local execution evidence, conditions, specific remediation, likelihood/impact/overall severity, and confidence.
|
||||||
|
- `needs_validation`: source-grounded candidates with an exact unresolved blocker and at least one applicable local or owner-observed deployment plan.
|
||||||
|
- `rejected`: source-grounded candidates disproved during validation, retained so future runs do not repeat the unsupported claim without changed evidence.
|
||||||
|
|
||||||
|
Read `report-schema.json` immediately before writing. It uses `additionalProperties: false`; do not carry hunter wrapper fields into a record. Keep these verdict contracts distinct:
|
||||||
|
|
||||||
|
- A `confirmed` record uses `root_cause`, `intended_behavior`, `conditions`, `execution`, `remediation`, `severity`, and `confidence`. It must not use `claimed_root_cause`, `blockers`, `validation_plan`, or `reason`. `execution` is target-neutral and uses the target's native interface: API/HTTP input, CLI call, library call, message, file fixture, browser action, rendered policy, or local harness as applicable. `observed_result` is nonempty and factual.
|
||||||
|
- A `needs_validation` record uses `claimed_root_cause`, `trace`, `evidence`, `blockers`, and at least one nonempty `validation_plan.local` or `validation_plan.deployment` field. Include both only when both contexts can resolve distinct facts. It must not use severity, execution, remediation, reason, or confirmed root cause.
|
||||||
|
- A `rejected` record uses `claimed_root_cause`, `trace`, `evidence`, and `reason`. It must not use severity, execution, remediation, blockers, validation plan, or confirmed root cause.
|
||||||
|
|
||||||
|
Every record has a stable fingerprint, title, description, and repository-relative source paths. A multi-step trace begins with `entrypoint`, ends with `sink`, and uses `propagation` only between them. One-entry traces use `entrypoint` or `sink`. Overall severity cannot exceed demonstrated impact.
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node <skill-dir>/validate-findings.cjs <output-dir>/findings.json
|
||||||
|
node <skill-dir>/validate-coverage-ledger.cjs <output-dir>/coverage-ledger.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Fix every structural and semantic error before continuing. The findings validator rejects input beyond 5 MiB, 1,000 top-level findings, or 64 nesting levels, and caps reported error output at 100 messages. Validator success proves format and ledger consistency only.
|
||||||
|
|
||||||
|
### Phase 5: Verify the final records with fresh eyes
|
||||||
|
|
||||||
|
Launch one fresh `research` verifier per final `confirmed` and `needs_validation` record, in parallel. This verifier checks the structured record, not the hunter write-up, and remains inside source/local boundaries.
|
||||||
|
|
||||||
|
In a `quick` run, Phase 3 and Phase 5 merge: the Phase 3 verifier also performs these record checks and returns the final schema-shaped record, so each candidate gets one fresh independent reviewer instead of two. Every other profile keeps the two passes separate. Never skip independent review of a `confirmed` record in any profile.
|
||||||
|
|
||||||
|
For `confirmed`, require it to check:
|
||||||
|
|
||||||
|
1. Every repository-relative trace/evidence path, line, scope, and described operation.
|
||||||
|
2. Real entry interface and exact local input shape.
|
||||||
|
3. Every condition, parser/policy step, source-visible preventing layer, and observed local result.
|
||||||
|
4. Affected principal/resource and demonstrated impact.
|
||||||
|
5. Severity separation: realistic likelihood, demonstrated impact, overall no greater than impact.
|
||||||
|
6. Remediation strategy and any `code_changes`, including whether the fix enforces the invariant without merely moving trust.
|
||||||
|
|
||||||
|
For `needs_validation`, require it to check:
|
||||||
|
|
||||||
|
1. The source path is real and supports only the `claimed_root_cause` stated.
|
||||||
|
2. Every listed blocker is decisive and not already answerable locally.
|
||||||
|
3. The candidate names a boundary and a possible concrete result rather than a generic concern.
|
||||||
|
4. At least one validation-plan field is present and exact. `local` uses a bounded fixture; `deployment` asks an owner to observe a configuration, identity, route, policy, or runtime fact. Do not invent a plan for an inapplicable context, and never send audit traffic to a deployment.
|
||||||
|
5. The fingerprint matches prior/current records for the same root cause.
|
||||||
|
|
||||||
|
Each verifier returns exactly one JSON object: `{"decision":"verified","fingerprint":"..."}` or `{"decision":"replace","reason":"...","record":{...}}`, with no surrounding prose. A replacement record must match its `confirmed`, `needs_validation`, or `rejected` schema branch. Treat a malformed or prose-wrapped Phase 5 result the same way as in Phase 3: discard it without repairing it and re-run with a fresh verifier when the budget permits.
|
||||||
|
|
||||||
|
Do not apply a Phase 5 replacement as final when it promotes a record to a stronger verdict, including any promotion to `confirmed`, or materially changes the root cause, trace, execution input or observed result, demonstrated impact, or severity. Give that complete replacement to a new independent verifier that did not hunt, perform Phase 3 validation, or propose the Phase 5 replacement. The new verifier rechecks the current source and independently reproduces any decisive local result under the execution boundary, then returns `verified` or another replacement. Apply a material replacement only after this fresh verification. If another material replacement results, repeat with a fresh verifier. If budget or independence is unavailable, remove the disputed record from `findings.json`, keep its ledger unit as an unresolved candidate, and set `run_status: "incomplete"` with an exact `incomplete_reason`. Non-material wording or repository-line corrections may be applied directly when they do not change meaning or evidence.
|
||||||
|
|
||||||
|
After every applied replacement, rerun both validators and update linked ledger decisions. If a final verifier identifies a separate root cause, assign a new fingerprint and send it through independent candidate validation before inclusion. Set `run_status: "complete"` only when every ledger candidate has an independent final disposition and every retained record passes Phase 5.
|
||||||
|
|
||||||
|
Do not verify only `confirmed` records. A misleading `needs_validation` handoff wastes owner time and can preserve a false premise.
|
||||||
|
|
||||||
|
### Phase 6: Produce target-neutral reports from final records
|
||||||
|
|
||||||
|
Only after Phase 5 passes for every record retained in `findings.json`, derive prose from the final records, the ledger, and the hunter `hardening` notes retained in ledger bookkeeping. An incomplete run may report independently verified records, but it must identify each unresolved ledger candidate and must not present it as a finding. The prose files never change a verdict, severity, blocker, or demonstrated impact.
|
||||||
|
|
||||||
|
#### `REPORT.md`
|
||||||
|
|
||||||
|
Write:
|
||||||
|
|
||||||
|
1. Run profile, scope, budget (if set) with agents spent versus planned, source ref, sandboxed source-and-local-only execution statement, prior-run use, and explicit deferred and out-of-scope coverage. Name carried same-source confirmations and changed-source revalidations. A `quick`, scoped, budget-limited, or incomplete run states plainly that it is a partial pass. If candidate validation exhausted a strict budget, state that the run is incomplete and list every unvalidated fingerprint and linked unit; do not describe those candidates as findings. If the budget prevented a mandatory critic, state which critic did not run and make no clean-coverage claim.
|
||||||
|
2. One short security posture summary.
|
||||||
|
3. A confirmed-findings table: severity, title, affected boundary, and one-line observed result.
|
||||||
|
4. Each confirmed finding: repository source location, lower-trust principal, target-native bounded reproduction, conditions, actual result, impact, priority rationale, and smallest source fix.
|
||||||
|
5. A separate `NEEDS VALIDATION` table. Give each lead's title, repository trace, exact blocker, bounded local next step, and safe owner-observed deployment check. Do not assign severity or call it a confirmed vulnerability.
|
||||||
|
6. Separate hardening notes and positive source patterns.
|
||||||
|
7. Coverage summary from the ledger: covered, candidate, blocked, and deferred counts, plus important exclusions and the final critic result.
|
||||||
|
|
||||||
|
Do not describe rejected records as findings. Mention their fingerprints only when they explain a prior disagreement or coverage decision.
|
||||||
|
|
||||||
|
#### `FINDINGS-DETAIL.md`
|
||||||
|
|
||||||
|
For each confirmed `medium`, `high`, or `critical` record, copy the complete source path and target-neutral local reproduction:
|
||||||
|
|
||||||
|
- ordered repository-relative trace and evidence;
|
||||||
|
- dummy attacker/principal and affected dummy resource;
|
||||||
|
- native input, invocation, or fixture and exact bounded instructions;
|
||||||
|
- observed output and the security invariant it proves;
|
||||||
|
- conditions and containment;
|
||||||
|
- source-level remediation and regression case.
|
||||||
|
|
||||||
|
#### `NEEDS-VALIDATION.md`
|
||||||
|
|
||||||
|
For every unresolved record, copy the source trace, verified evidence, exact blocker, affected boundary, and each applicable bounded local or owner-observed resolution plan. Keep these as prioritized leads without severity. Do not turn them into live test guidance or assume the missing deployment fact.
|
||||||
|
|
||||||
|
HTTP is one possible native interface, not the default. A library finding may use a function call, a parser a fixture, a CLI a command, a desktop app an IPC or file action, and infrastructure a locally rendered policy. Do not require an endpoint, external account, or live environment that the target does not have.
|
||||||
|
|
||||||
|
Keep the report proportional to the evidence. A clean run may have zero confirmed records. State that result and the remaining coverage/validation limits without inventing LOW findings.
|
||||||
105
.agents/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md
Normal file
105
.agents/skills/security-audit/WEB-PROTOCOL-AND-AUTH.md
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
# HTTP-Protocol and Authentication Hunting
|
||||||
|
|
||||||
|
#### When to use this file
|
||||||
|
|
||||||
|
Reach for this file when the target speaks HTTP at a parsing, caching, browser-authentication, or identity boundary: web applications, APIs, reverse proxies, CDNs, gateways, custom HTTP servers, and services implementing sessions, JWT, OAuth/OIDC, SAML, password recovery, MFA, passkeys, API keys, or mTLS. Use this with `ATTACK-CLASSES.md`: access-control review asks whether a principal may perform an operation; this file asks whether the HTTP or identity layer can confuse which principal, request, assurance level, or token the operation belongs to.
|
||||||
|
|
||||||
|
Pick classes from Phase 1. Split a large target into request framing and cache policy, browser authentication, federated identity, strong authentication and recovery, service credentials, and session lifecycle. A single server behind an unobserved managed proxy has little source-confirmable smuggling surface; a proxy or custom parser has much more.
|
||||||
|
|
||||||
|
## Core discipline (include in every agent prompt for this domain)
|
||||||
|
|
||||||
|
```
|
||||||
|
- Framing and cache findings require two interpretations of the same request, response, or key. Name both components and the exact normalized value on each side.
|
||||||
|
- For every credential, find the signature or secret verification and every binding required for its role: issuer, audience, origin, RP, client, session, principal, resource, assurance, expiry, and one-time state.
|
||||||
|
- Host, Forwarded, X-Forwarded-*, Origin, Referer, redirect targets, callback state, and request-derived URLs are trust decisions. Trace each to the affected identity or response.
|
||||||
|
- A missing header, cookie attribute, MFA prompt, or rate limit is not a finding alone. Require an accepted invalid request, cross-principal impact, assurance downgrade, or credential disclosure.
|
||||||
|
- Classify `confirmed` only from complete source evidence and bounded local request/token tests. Use `needs_validation` when proxy, IdP, browser, certificate, secret, or deployed configuration is required but not visible.
|
||||||
|
```
|
||||||
|
|
||||||
|
## HTTP framing and cache attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Request framing and desynchronization**
|
||||||
|
Front end and back end disagree on request length or header normalization. Review multiple `Content-Length` values, `Transfer-Encoding`, HTTP/2 or HTTP/3 downgrade, header-name normalization, forbidden connection headers, and CR/LF conversion. Confirm which bytes one component assigns to a request and which bytes its peer assigns to the next request.
|
||||||
|
|
||||||
|
**Web cache poisoning through unkeyed input**
|
||||||
|
A request value changes cached content or security-relevant headers but is absent from the cache key. Compare cache key construction with every response variant, including forwarded host/scheme, selected cookies, query normalization, language/device headers, and authorization state.
|
||||||
|
|
||||||
|
**Cache deception and private-response caching**
|
||||||
|
Cache routing treats a private dynamic path as a public static asset, or caches a response whose identity and authorization inputs are missing from policy. Compare edge cacheability with application route parsing, suffix/path-parameter normalization, and response cache directives.
|
||||||
|
|
||||||
|
**Host and forwarded-header trust**
|
||||||
|
Untrusted host/proxy metadata determines absolute URLs, tenant routing, callbacks, reset links, cache keys, or the client address used by authorization. Confirm who can supply the header and whether trusted ingress removes client-provided copies.
|
||||||
|
|
||||||
|
**Response-header injection**
|
||||||
|
Untrusted data reaches `Location`, `Set-Cookie`, CSP, or another response header with unsafe control characters or normalization. Verify framework rejection before reporting and require a security-relevant response change.
|
||||||
|
|
||||||
|
## Browser-session attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**Ordinary CSRF**
|
||||||
|
A browser sends ambient credentials to a state-changing endpoint that accepts a cross-site request without an effective anti-CSRF token, same-site request binding, or strict Origin/Referer validation. Inventory every cookie-authenticated mutation, including form, JSON-like, multipart, method-override, and legacy routes. SameSite is effective only for the cookie and browser contexts actually used; login CSRF and cross-site subresource requests can have different requirements.
|
||||||
|
|
||||||
|
**Session fixation and invalidation**
|
||||||
|
Session identifiers are not rotated on login, account switch, MFA completion, impersonation, or other privilege changes, or remain valid after logout, password change, revocation, and account disable. Check server sessions, refresh tokens, signed cookies, websocket state, cache copies, and fallback endpoints.
|
||||||
|
|
||||||
|
**Cookie scope and transport**
|
||||||
|
A sensitive cookie has an over-broad `Domain` or `Path`, can cross an insecure transport, or conflicts with a sibling cookie that another component selects differently. Bare missing flags remain hardening notes unless a realistic less-trusted origin, network position, or browser path can gain or replace the credential.
|
||||||
|
|
||||||
|
## Federated-identity attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
First establish role. Authorization-server controls such as redirect allowlisting and code issuance do not belong to a relying-party client. Verification and binding defects belong to the component consuming the artifact.
|
||||||
|
|
||||||
|
**JWT verification and claim binding**
|
||||||
|
Check signature verification, server-pinned algorithm and key source, then `exp`, `nbf`, `aud`, and `iss`. Review `kid`, `jku`, and `x5u` as untrusted key selectors, duplicate/header normalization, and decode-without-verify paths. A valid token for another service is invalid here even when signed by a trusted issuer.
|
||||||
|
|
||||||
|
**OAuth/OIDC request and callback binding**
|
||||||
|
Validate exact `redirect_uri` ownership where the target is the authorization server; session-bound `state`; PKCE and authorization-code binding where applicable; ID-token issuer/audience/signature/nonce; and selected-IdP binding in multi-provider flows. Compare initial callback, retry, mobile/deep-link, and account-link routes.
|
||||||
|
|
||||||
|
**SAML signed-object and assertion binding**
|
||||||
|
Ensure the element whose signature is validated is the element used as identity. Review unsigned/fallback paths, safe XML parser configuration, canonicalization differences, and freshness/binding fields such as validity windows, audience/recipient, request correlation, and replay state.
|
||||||
|
|
||||||
|
## MFA, passkey, and account-transition attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**MFA enrollment and assurance downgrade**
|
||||||
|
Enrollment, replacement, disablement, recovery-code generation, trusted-device creation, and fallback login require the intended prior assurance. Check that a valid first factor cannot enroll or replace the second factor without policy-required fresh authentication, and that disabled or stale factors stop authorizing sessions.
|
||||||
|
|
||||||
|
**Step-up binding and bypass**
|
||||||
|
A successful challenge upgrades the wrong session, account, tenant, action, or API request, or an alternate route omits the assurance check. Bind the challenge to principal, current session, assurance target, operation or resource when required, expiry, and one-time completion. Compare UI, API, batch, recovery, and resumed-flow paths.
|
||||||
|
|
||||||
|
**WebAuthn and passkey verification**
|
||||||
|
At registration, bind challenge, RP ID, expected origin, credential, user/userHandle, algorithm, and policy-required user verification to the initiating session. At authentication, verify challenge, RP/origin, credential membership, signature, and intended user presence/verification. Check account-discovery and linking flows for userHandle or credential-to-account confusion. Signature-counter handling is meaningful only when the product treats regressions as a clone signal.
|
||||||
|
|
||||||
|
**Account linking and identity collision**
|
||||||
|
Adding an IdP, passkey, email, phone, device, or external account to an existing account must require a current authenticated session, verified ownership of the new identity, policy-required step-up, and callback state bound to the account that initiated linking. Review unlink/relink and invite-acceptance paths for verified-identifier or tenant collisions.
|
||||||
|
|
||||||
|
**Password reset and broader recovery**
|
||||||
|
Recovery tokens, support/admin recovery, backup codes, device migration, and email or phone change often become the weakest authentication path. Verify token randomness, user/action binding, expiry, one-time state, rate/accounting controls, delivery URL trust, and invalidation of prior tokens and sessions. Different responses that only reveal public account existence are not automatically security findings.
|
||||||
|
|
||||||
|
## API-key and mTLS attack classes (subagent_type: `general`)
|
||||||
|
|
||||||
|
**API-key scope and resource binding**
|
||||||
|
A key authenticates to broader tenants, resources, actions, or environments than its server-side record grants, or request parameters override those bindings. Review key lookup, prefix/full-secret verification, type confusion between publishable and secret keys, scope checks, rotation, revocation caches, and bulk endpoints.
|
||||||
|
|
||||||
|
**API-key exposure and unsafe transport**
|
||||||
|
Keys appear in client bundles, URLs, redirects, logs, error paths, build artifacts, or responses accessible to a lower-trust principal. A public identifier called a key is not a secret. Confirm key type and the authority gained by disclosure.
|
||||||
|
|
||||||
|
**mTLS peer and application-identity confusion**
|
||||||
|
A process trusts client-certificate identity headers from any network peer, verifies a chain but maps attacker-influenceable subject text to an account incorrectly, or accepts a certificate for the wrong trust domain, extended usage, audience, or validity policy. Where a trusted proxy terminates mTLS, verify only that proxy can connect, it removes incoming identity headers, and the backend binds the sanitized identity to the request.
|
||||||
|
|
||||||
|
**Certificate lifecycle fallback**
|
||||||
|
Expired, revoked, missing, or renewal-failed certificates cause silent fallback to bearer-only or anonymous operation, or long-lived pooled connections retain authorization after revocation. Missing deployment revocation data makes the result `needs_validation`; an in-repo fail-open branch is source-confirmable.
|
||||||
|
|
||||||
|
## Universal moves (apply across the above)
|
||||||
|
|
||||||
|
- Walk issue → store → transmit → consume → refresh → revoke for every credential and challenge. Compare normal, error, retry, migration, legacy, and account-switch paths.
|
||||||
|
- Enumerate every door to the same identity and every route to the same sensitive operation. The effective policy is the weakest parallel path, not the most polished UI.
|
||||||
|
- Diff parser, proxy, router, cache, and application normalization side by side. For local validation, feed identical bounded request fixtures into each component rather than sending traffic to a live deployment.
|
||||||
|
- For recovery and linking, draw the account before/after graph. Each edge must name the current principal, proof of the new identity, required assurance, callback/session binding, and revocation effect.
|
||||||
|
|
||||||
|
## Validation rules (apply before reporting ANY finding here)
|
||||||
|
|
||||||
|
1. Apply a source-visibility gate. Proxy chains, edge cache keys, IdP policy, certificate trust, browser cookie behavior, secrets, and deployed auth modes may be outside the repository. Record a precise `needs_validation` candidate instead of asserting missing infrastructure behavior.
|
||||||
|
2. For framing and cache findings, name both components and the divergent parse/key. Confirm cross-request, cross-user, or private-response impact with bounded local fixtures.
|
||||||
|
3. For token, MFA, passkey, account-link, recovery, API-key, and mTLS findings, cite the verification line and missing principal/session/resource/origin/audience/action/assurance binding. Prove the server accepts the invalid transition or credential.
|
||||||
|
4. For CSRF, name the ambient credential, state-changing route, accepted cross-site request shape, browser cookie policy, and missing effective check. Read-only actions and routes requiring a non-ambient bearer token do not qualify.
|
||||||
|
5. Verify framework and library defaults. If version or configuration is unknown, use `needs_validation`; do not turn an unverified critical claim into a lower-severity confirmed finding.
|
||||||
|
6. Return `confirmed` only with a complete source trace and observable unauthorized identity, state, or disclosure. For `needs_validation`, name the missing fact and safe local or owner-observed check that resolves it.
|
||||||
461
.agents/skills/security-audit/report-schema.json
Normal file
461
.agents/skills/security-audit/report-schema.json
Normal file
@ -0,0 +1,461 @@
|
|||||||
|
{
|
||||||
|
"$comment": "Top-level contract for findings.json. validate-findings.cjs interprets and checks this schema directly.",
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"description": "A source-grounded vulnerability that was independently demonstrated.",
|
||||||
|
"properties": {
|
||||||
|
"verdict": {
|
||||||
|
"type": "string",
|
||||||
|
"const": "confirmed"
|
||||||
|
},
|
||||||
|
"fingerprint": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$",
|
||||||
|
"description": "A stable source-derived identifier that does not change between validation states."
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"root_cause": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"intended_behavior": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"trace": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["entrypoint", "propagation", "sink"]
|
||||||
|
},
|
||||||
|
"file": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"line": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"scope": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["kind", "file", "line", "scope", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"evidence": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"file": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"line": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["file", "line", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"conditions": {
|
||||||
|
"type": "array",
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["authentication_level", "authorization_role", "user_interaction", "system_configuration", "network_routing", "environmental_dependency", "data_state", "timing_dependency", "third_party_dependency"]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["kind", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"execution": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Target-neutral reproduction in the target's native interface.",
|
||||||
|
"properties": {
|
||||||
|
"attacker_perspective": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"payloads": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"instructions": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"items": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"observed_result": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["attacker_perspective", "payloads", "instructions", "observed_result"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"remediation": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"strategy": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"code_changes": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"file_name": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"fixed_code": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["file_name", "fixed_code"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["strategy"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"severity": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"likelihood": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"score": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["informational", "low", "medium", "high", "critical"]
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["score", "reason"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"impact": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"score": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["informational", "low", "medium", "high", "critical"]
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["score", "reason"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"overall_severity": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["informational", "low", "medium", "high", "critical"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["likelihood", "impact", "overall_severity"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"confidence": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"score": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["low", "medium", "high"]
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["score", "reason"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["verdict", "fingerprint", "title", "description", "root_cause", "intended_behavior", "trace", "evidence", "conditions", "execution", "remediation", "severity", "confidence"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"description": "A source-grounded candidate whose decisive validation is blocked.",
|
||||||
|
"properties": {
|
||||||
|
"verdict": {
|
||||||
|
"type": "string",
|
||||||
|
"const": "needs_validation"
|
||||||
|
},
|
||||||
|
"fingerprint": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"claimed_root_cause": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"trace": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["entrypoint", "propagation", "sink"]
|
||||||
|
},
|
||||||
|
"file": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"line": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"scope": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["kind", "file", "line", "scope", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"evidence": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"file": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"line": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["file", "line", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"blockers": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"validation_plan": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"local": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"deployment": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["verdict", "fingerprint", "title", "description", "claimed_root_cause", "trace", "evidence", "blockers", "validation_plan"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"description": "A source-grounded candidate refuted during validation.",
|
||||||
|
"properties": {
|
||||||
|
"verdict": {
|
||||||
|
"type": "string",
|
||||||
|
"const": "rejected"
|
||||||
|
},
|
||||||
|
"fingerprint": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"claimed_root_cause": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"trace": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["entrypoint", "propagation", "sink"]
|
||||||
|
},
|
||||||
|
"file": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"line": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"scope": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["kind", "file", "line", "scope", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"evidence": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"uniqueItems": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"file": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"line": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["file", "line", "description"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"visibleContent": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["verdict", "fingerprint", "title", "description", "claimed_root_cause", "trace", "evidence", "reason"],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
872
.agents/skills/security-audit/validate-coverage-ledger.cjs
Executable file
872
.agents/skills/security-audit/validate-coverage-ledger.cjs
Executable file
@ -0,0 +1,872 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates coverage-ledger.json and its canonical coverage IDs.
|
||||||
|
* Usage: node validate-coverage-ledger.cjs <path-to-coverage-ledger.json>
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const path = require("node:path");
|
||||||
|
const { TextDecoder } = require("node:util");
|
||||||
|
|
||||||
|
// Conservative bounds apply before JSON.parse and again to the parsed document.
|
||||||
|
const LIMITS = Object.freeze({
|
||||||
|
inputBytes: 5 * 1024 * 1024,
|
||||||
|
units: 10000,
|
||||||
|
collectionItems: 1000,
|
||||||
|
objectFields: 1000,
|
||||||
|
nestingDepth: 64,
|
||||||
|
preflightValues: 500000,
|
||||||
|
validationErrors: 100,
|
||||||
|
});
|
||||||
|
const MAX_INPUT_BYTES = LIMITS.inputBytes;
|
||||||
|
const MAX_UNITS = LIMITS.units;
|
||||||
|
const MAX_LIST_ITEMS = LIMITS.collectionItems;
|
||||||
|
const MAX_TEXT_LENGTH = 4096;
|
||||||
|
const REQUIRED_FIELDS = [
|
||||||
|
"coverage_id",
|
||||||
|
"canonical_refs",
|
||||||
|
"surface",
|
||||||
|
"boundary",
|
||||||
|
"subsystem",
|
||||||
|
"attack_class",
|
||||||
|
"starting_paths",
|
||||||
|
"ordinary_attack_class_block",
|
||||||
|
"selected_companion_blocks",
|
||||||
|
"excluded_blocks",
|
||||||
|
"prior_status",
|
||||||
|
"attempts",
|
||||||
|
"wave",
|
||||||
|
"status",
|
||||||
|
"agent_id",
|
||||||
|
"reviewed_paths",
|
||||||
|
"local_checks",
|
||||||
|
"result_fingerprints",
|
||||||
|
"unresolved",
|
||||||
|
];
|
||||||
|
const REF_FIELDS = ["surface", "boundary", "subsystem", "attack_class"];
|
||||||
|
const STATUSES = new Set([
|
||||||
|
"planned",
|
||||||
|
"not_applicable",
|
||||||
|
"out_of_scope",
|
||||||
|
"in_progress",
|
||||||
|
"covered",
|
||||||
|
"candidate",
|
||||||
|
"blocked",
|
||||||
|
"deferred",
|
||||||
|
]);
|
||||||
|
const ATTEMPT_STATUSES = new Set(["covered", "candidate", "blocked"]);
|
||||||
|
const ATTEMPT_FIELDS = [
|
||||||
|
"wave",
|
||||||
|
"status",
|
||||||
|
"agent_id",
|
||||||
|
"reviewed_paths",
|
||||||
|
"local_checks",
|
||||||
|
"result_fingerprints",
|
||||||
|
"unresolved",
|
||||||
|
"reassignment_reason",
|
||||||
|
];
|
||||||
|
const PRIOR_STATUSES = new Set([
|
||||||
|
"new",
|
||||||
|
"prior_confirmed_same_source",
|
||||||
|
"prior_confirmed_changed_source",
|
||||||
|
"prior_needs_validation",
|
||||||
|
"prior_deferred",
|
||||||
|
"prior_blocked",
|
||||||
|
"prior_out_of_scope",
|
||||||
|
"prior_covered_same_source",
|
||||||
|
"prior_covered_changed_source",
|
||||||
|
"prior_rejected_claim_changed",
|
||||||
|
"none",
|
||||||
|
]);
|
||||||
|
const FINGERPRINT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$/;
|
||||||
|
const AGENT_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
||||||
|
const WINDOWS_RESERVED_AGENT_ID = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
|
||||||
|
const VISIBLE_CONTENT = /[^\p{White_Space}\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]/u;
|
||||||
|
const PATH_FORBIDDEN_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
|
||||||
|
const WINDOWS_RESERVED_COMPONENT = /^(?:con|prn|aux|nul|clock\$|conin\$|conout\$|com[1-9\u00b9\u00b2\u00b3]|lpt[1-9\u00b9\u00b2\u00b3])(?:\.|$)/iu;
|
||||||
|
const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||||
|
const UNSAFE_DIAGNOSTIC_CHARACTER = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
|
||||||
|
const MAX_DIAGNOSTIC_STRING_LENGTH = 256;
|
||||||
|
|
||||||
|
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
||||||
|
|
||||||
|
class JsonStructureError extends Error {}
|
||||||
|
class SafeInputError extends Error {}
|
||||||
|
|
||||||
|
function escapeUnsafeDiagnosticCharacters(value) {
|
||||||
|
return String(value).replace(UNSAFE_DIAGNOSTIC_CHARACTER, (character) => {
|
||||||
|
const codePoint = character.codePointAt(0);
|
||||||
|
return codePoint <= 0xffff
|
||||||
|
? `\\u${codePoint.toString(16).padStart(4, "0")}`
|
||||||
|
: `\\u{${codePoint.toString(16)}}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeQuote(value) {
|
||||||
|
let serialized;
|
||||||
|
if (typeof value === "string") {
|
||||||
|
const clipped = value.length > MAX_DIAGNOSTIC_STRING_LENGTH
|
||||||
|
? `${value.slice(0, MAX_DIAGNOSTIC_STRING_LENGTH)}...`
|
||||||
|
: value;
|
||||||
|
serialized = JSON.stringify(clipped);
|
||||||
|
} else if (value === null || typeof value === "boolean") {
|
||||||
|
serialized = String(value);
|
||||||
|
} else if (typeof value === "number" && Number.isFinite(value)) {
|
||||||
|
serialized = String(value);
|
||||||
|
} else {
|
||||||
|
serialized = `"<${Array.isArray(value) ? "array" : typeof value}>"`;
|
||||||
|
}
|
||||||
|
return escapeUnsafeDiagnosticCharacters(serialized);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createErrorList() {
|
||||||
|
const errors = [];
|
||||||
|
Object.defineProperty(errors, "push", {
|
||||||
|
value(...messages) {
|
||||||
|
const remaining = LIMITS.validationErrors - this.length;
|
||||||
|
if (remaining > 0) {
|
||||||
|
Array.prototype.push.apply(this, messages.slice(0, remaining).map(escapeUnsafeDiagnosticCharacters));
|
||||||
|
}
|
||||||
|
return this.length;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObject(value) {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function preflightJsonText(contents) {
|
||||||
|
const containers = [];
|
||||||
|
let rootState = "value";
|
||||||
|
let inString = false;
|
||||||
|
let escaped = false;
|
||||||
|
let totalValues = 0;
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
throw new JsonStructureError(`input ${message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentContainer() {
|
||||||
|
return containers[containers.length - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
function countValue() {
|
||||||
|
totalValues++;
|
||||||
|
if (totalValues > LIMITS.preflightValues) {
|
||||||
|
fail(`exceeds ${LIMITS.preflightValues} total value limit`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function beginValue() {
|
||||||
|
const container = currentContainer();
|
||||||
|
if (!container) {
|
||||||
|
if (rootState !== "value") fail("has malformed JSON structure");
|
||||||
|
rootState = "end";
|
||||||
|
} else if (container.type === "array") {
|
||||||
|
if (container.state !== "firstValueOrEnd" && container.state !== "value") {
|
||||||
|
fail("has malformed JSON array structure");
|
||||||
|
}
|
||||||
|
container.items++;
|
||||||
|
const limit = container.topLevel ? MAX_UNITS : LIMITS.collectionItems;
|
||||||
|
if (container.items > limit) {
|
||||||
|
fail(container.topLevel
|
||||||
|
? `exceeds ${limit} top-level unit limit`
|
||||||
|
: `exceeds ${limit} item array limit`);
|
||||||
|
}
|
||||||
|
container.state = "commaOrEnd";
|
||||||
|
} else {
|
||||||
|
if (container.state !== "value") fail("has malformed JSON object structure");
|
||||||
|
container.state = "commaOrEnd";
|
||||||
|
}
|
||||||
|
countValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
function beginString() {
|
||||||
|
const container = currentContainer();
|
||||||
|
if (container && container.type === "object" &&
|
||||||
|
(container.state === "firstKeyOrEnd" || container.state === "key")) {
|
||||||
|
container.fields++;
|
||||||
|
if (container.fields > LIMITS.objectFields) {
|
||||||
|
fail(`exceeds ${LIMITS.objectFields} field object limit`);
|
||||||
|
}
|
||||||
|
container.state = "colon";
|
||||||
|
} else {
|
||||||
|
beginValue();
|
||||||
|
}
|
||||||
|
inString = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function beginContainer(type) {
|
||||||
|
beginValue();
|
||||||
|
if (containers.length >= LIMITS.nestingDepth) {
|
||||||
|
fail(`exceeds nesting depth limit ${LIMITS.nestingDepth}`);
|
||||||
|
}
|
||||||
|
containers.push(type === "array"
|
||||||
|
? { type, state: "firstValueOrEnd", items: 0, topLevel: containers.length === 0 }
|
||||||
|
: { type, state: "firstKeyOrEnd", fields: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeContainer(type) {
|
||||||
|
const container = currentContainer();
|
||||||
|
if (!container || container.type !== type) fail("has mismatched JSON containers");
|
||||||
|
const canClose = type === "array"
|
||||||
|
? container.state === "firstValueOrEnd" || container.state === "commaOrEnd"
|
||||||
|
: container.state === "firstKeyOrEnd" || container.state === "commaOrEnd";
|
||||||
|
if (!canClose) fail(`has malformed JSON ${type} structure`);
|
||||||
|
containers.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWhitespace(character) {
|
||||||
|
return character === " " || character === "\t" || character === "\r" || character === "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTokenDelimiter(character) {
|
||||||
|
return isWhitespace(character) || character === "," || character === ":" ||
|
||||||
|
character === "[" || character === "]" || character === "{" ||
|
||||||
|
character === "}" || character === "\"";
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let index = 0; index < contents.length; index++) {
|
||||||
|
const character = contents[index];
|
||||||
|
if (inString) {
|
||||||
|
if (escaped) {
|
||||||
|
escaped = false;
|
||||||
|
} else if (character === "\\") {
|
||||||
|
escaped = true;
|
||||||
|
} else if (character === "\"") {
|
||||||
|
inString = false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isWhitespace(character)) continue;
|
||||||
|
|
||||||
|
if (character === "\"") {
|
||||||
|
beginString();
|
||||||
|
} else if (character === "[") {
|
||||||
|
beginContainer("array");
|
||||||
|
} else if (character === "{") {
|
||||||
|
beginContainer("object");
|
||||||
|
} else if (character === "]") {
|
||||||
|
closeContainer("array");
|
||||||
|
} else if (character === "}") {
|
||||||
|
closeContainer("object");
|
||||||
|
} else if (character === ":") {
|
||||||
|
const container = currentContainer();
|
||||||
|
if (!container || container.type !== "object" || container.state !== "colon") {
|
||||||
|
fail("has malformed JSON object structure");
|
||||||
|
}
|
||||||
|
container.state = "value";
|
||||||
|
} else if (character === ",") {
|
||||||
|
const container = currentContainer();
|
||||||
|
if (!container || container.state !== "commaOrEnd") fail("has malformed JSON collection structure");
|
||||||
|
container.state = container.type === "array" ? "value" : "key";
|
||||||
|
} else {
|
||||||
|
beginValue();
|
||||||
|
while (index + 1 < contents.length && !isTokenDelimiter(contents[index + 1])) index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inString) fail("has an unterminated JSON string");
|
||||||
|
if (containers.length > 0) fail("has truncated JSON structure");
|
||||||
|
if (rootState !== "end") fail("has no JSON value");
|
||||||
|
}
|
||||||
|
|
||||||
|
function preflightDocument(root) {
|
||||||
|
const errors = createErrorList();
|
||||||
|
const stack = [{ value: root, depth: 0, location: "$" }];
|
||||||
|
let visited = 0;
|
||||||
|
|
||||||
|
while (stack.length > 0) {
|
||||||
|
const { value, depth, location } = stack.pop();
|
||||||
|
visited++;
|
||||||
|
if (visited > LIMITS.preflightValues) {
|
||||||
|
errors.push(`$: exceeds ${LIMITS.preflightValues} total values`);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
if (value === null || typeof value !== "object") continue;
|
||||||
|
if (depth >= LIMITS.nestingDepth) {
|
||||||
|
errors.push(`${location}: exceeds nesting depth limit ${LIMITS.nestingDepth}`);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
const limit = location === "$" ? MAX_UNITS : MAX_LIST_ITEMS;
|
||||||
|
if (value.length > limit) {
|
||||||
|
errors.push(`${location}: exceeds ${limit} entries`);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
for (let index = value.length - 1; index >= 0; index--) {
|
||||||
|
stack.push({ value: value[index], depth: depth + 1, location: `${location}[${index}]` });
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keys = Object.keys(value);
|
||||||
|
if (keys.length > LIMITS.objectFields) {
|
||||||
|
errors.push(`${location}: exceeds ${LIMITS.objectFields} object fields`);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
for (let index = keys.length - 1; index >= 0; index--) {
|
||||||
|
const key = keys[index];
|
||||||
|
stack.push({ value: value[key], depth: depth + 1, location: `${location}{${index}}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasValidUnicodeScalarValues(value) {
|
||||||
|
let index = 0;
|
||||||
|
while (index < value.length) {
|
||||||
|
const first = value.charCodeAt(index++);
|
||||||
|
if (first >= 0xd800 && first <= 0xdbff) {
|
||||||
|
if (index >= value.length) return false;
|
||||||
|
const second = value.charCodeAt(index++);
|
||||||
|
if (second < 0xdc00 || second > 0xdfff) return false;
|
||||||
|
} else if (first >= 0xdc00 && first <= 0xdfff) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasVisibleProse(value) {
|
||||||
|
return hasValidUnicodeScalarValues(value) && VISIBLE_CONTENT.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isVisibleText(value, maxLength = MAX_TEXT_LENGTH) {
|
||||||
|
return typeof value === "string" &&
|
||||||
|
value.length > 0 &&
|
||||||
|
value.length <= maxLength &&
|
||||||
|
value.trim() === value &&
|
||||||
|
hasVisibleProse(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCanonicalRef(value) {
|
||||||
|
return isVisibleText(value, 1024) &&
|
||||||
|
!PATH_FORBIDDEN_CHARACTER.test(value) &&
|
||||||
|
value.normalize("NFC") === value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeCanonicalRef(value) {
|
||||||
|
if (!isCanonicalRef(value)) throw new TypeError("invalid canonical reference");
|
||||||
|
let encoded = "";
|
||||||
|
for (const byte of Buffer.from(value, "utf8")) {
|
||||||
|
const unreserved =
|
||||||
|
(byte >= 0x41 && byte <= 0x5a) ||
|
||||||
|
(byte >= 0x61 && byte <= 0x7a) ||
|
||||||
|
(byte >= 0x30 && byte <= 0x39) ||
|
||||||
|
byte === 0x2d || byte === 0x2e || byte === 0x5f || byte === 0x7e;
|
||||||
|
encoded += unreserved ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
return encoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonicalCoverageId(refs) {
|
||||||
|
if (!isObject(refs)) throw new TypeError("canonical_refs must be an object");
|
||||||
|
const fields = hasOwn(refs, "lifecycle") ? [...REF_FIELDS, "lifecycle"] : REF_FIELDS;
|
||||||
|
if (Object.keys(refs).length !== fields.length || fields.some((field) => !hasOwn(refs, field))) {
|
||||||
|
throw new TypeError("canonical_refs has missing or unexpected fields");
|
||||||
|
}
|
||||||
|
return fields.map((field) => encodeCanonicalRef(refs[field])).join("::");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSafeRelativePath(value) {
|
||||||
|
if (typeof value !== "string" || value.length === 0 || !hasValidUnicodeScalarValues(value) || value.trim() !== value || PATH_FORBIDDEN_CHARACTER.test(value) || value.includes("\\") || value.includes(":")) return false;
|
||||||
|
if (path.posix.isAbsolute(value) || path.win32.isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.startsWith("~")) return false;
|
||||||
|
return value.split("/").every((segment) =>
|
||||||
|
segment !== "" &&
|
||||||
|
segment !== "." &&
|
||||||
|
segment !== ".." &&
|
||||||
|
!/[ .]$/u.test(segment) &&
|
||||||
|
!WINDOWS_RESERVED_COMPONENT.test(segment));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSafeAgentId(value) {
|
||||||
|
return typeof value === "string" &&
|
||||||
|
AGENT_ID_PATTERN.test(value) &&
|
||||||
|
!WINDOWS_RESERVED_AGENT_ID.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isOwnedArtifactPath(value, agentId) {
|
||||||
|
if (!isSafeAgentId(agentId) || !isSafeRelativePath(value)) return false;
|
||||||
|
const prefix = `agents/${agentId}/artifacts/`;
|
||||||
|
return value.startsWith(prefix) && value.length > prefix.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateStringArray(value, location, errors, options = {}) {
|
||||||
|
const { allowEmpty = true, fingerprint = false, pathValue = false } = options;
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
errors.push(`${location}: expected array`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!allowEmpty && value.length === 0) errors.push(`${location}: must not be empty`);
|
||||||
|
if (value.length > MAX_LIST_ITEMS) errors.push(`${location}: exceeds ${MAX_LIST_ITEMS} entries`);
|
||||||
|
const seen = new Set();
|
||||||
|
value.slice(0, MAX_LIST_ITEMS).forEach((entry, index) => {
|
||||||
|
const entryLocation = `${location}[${index}]`;
|
||||||
|
const valid = pathValue ? isSafeRelativePath(entry) : isVisibleText(entry);
|
||||||
|
if (!valid) errors.push(`${entryLocation}: invalid ${pathValue ? "repository-relative path" : "text"}`);
|
||||||
|
if (fingerprint && typeof entry === "string" && !FINGERPRINT_PATTERN.test(entry)) {
|
||||||
|
errors.push(`${entryLocation}: invalid fingerprint`);
|
||||||
|
}
|
||||||
|
if (typeof entry === "string" && seen.has(entry)) errors.push(`${entryLocation}: duplicate entry`);
|
||||||
|
if (typeof entry === "string") seen.add(entry);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateChecks(value, location, errors) {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
errors.push(`${location}: expected array`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (value.length > MAX_LIST_ITEMS) errors.push(`${location}: exceeds ${MAX_LIST_ITEMS} entries`);
|
||||||
|
value.slice(0, MAX_LIST_ITEMS).forEach((check, index) => {
|
||||||
|
const base = `${location}[${index}]`;
|
||||||
|
if (!isObject(check)) {
|
||||||
|
errors.push(`${base}: expected object`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const field of ["agent_id", "reviewed_paths", "invariant", "method", "result", "artifact"]) {
|
||||||
|
if (!hasOwn(check, field)) errors.push(`${base}: missing required field ${safeQuote(field)}`);
|
||||||
|
}
|
||||||
|
if (!isSafeAgentId(check.agent_id)) errors.push(`${base}.agent_id: expected a canonical lowercase agent ID`);
|
||||||
|
validateStringArray(check.reviewed_paths, `${base}.reviewed_paths`, errors, { allowEmpty: false, pathValue: true });
|
||||||
|
if (!isVisibleText(check.invariant)) errors.push(`${base}.invariant: invalid text`);
|
||||||
|
if (check.method !== "source" && check.method !== "local") errors.push(`${base}.method: expected "source" or "local"`);
|
||||||
|
if (!isVisibleText(check.result)) errors.push(`${base}.result: invalid text`);
|
||||||
|
if (check.method === "source" && check.artifact !== null) {
|
||||||
|
errors.push(`${base}.artifact: source-only check must use null`);
|
||||||
|
} else if (check.method === "local") {
|
||||||
|
if (!isOwnedArtifactPath(check.artifact, check.agent_id)) {
|
||||||
|
errors.push(`${base}.artifact: local check requires an artifact owned by agent ${safeQuote(isSafeAgentId(check.agent_id) ? check.agent_id : "<agent-id>")}`);
|
||||||
|
}
|
||||||
|
} else if (check.method !== "source" && check.method !== "local" && check.artifact !== null && !isSafeRelativePath(check.artifact)) {
|
||||||
|
errors.push(`${base}.artifact: expected null or a safe output-relative path`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateReviewedPathOwnership(unit, base, errors) {
|
||||||
|
if (!Array.isArray(unit.reviewed_paths) || !Array.isArray(unit.local_checks)) return;
|
||||||
|
const aggregatePaths = new Set(unit.reviewed_paths.filter((value) => typeof value === "string"));
|
||||||
|
const ownedPaths = new Set();
|
||||||
|
for (const check of unit.local_checks) {
|
||||||
|
if (!isObject(check) || !Array.isArray(check.reviewed_paths)) continue;
|
||||||
|
for (const reviewedPath of check.reviewed_paths) {
|
||||||
|
if (typeof reviewedPath === "string") ownedPaths.add(reviewedPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const reviewedPath of aggregatePaths) {
|
||||||
|
if (!ownedPaths.has(reviewedPath)) errors.push(`${base}.reviewed_paths: ${safeQuote(reviewedPath)} has no check owner`);
|
||||||
|
}
|
||||||
|
for (const reviewedPath of ownedPaths) {
|
||||||
|
if (!aggregatePaths.has(reviewedPath)) errors.push(`${base}.local_checks: owned path ${safeQuote(reviewedPath)} is absent from aggregate reviewed_paths`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateExcludedBlocks(value, location, errors) {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
errors.push(`${location}: expected array`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (value.length > MAX_LIST_ITEMS) errors.push(`${location}: exceeds ${MAX_LIST_ITEMS} entries`);
|
||||||
|
const seen = new Set();
|
||||||
|
value.slice(0, MAX_LIST_ITEMS).forEach((entry, index) => {
|
||||||
|
const base = `${location}[${index}]`;
|
||||||
|
if (!isObject(entry)) {
|
||||||
|
errors.push(`${base}: expected object`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isVisibleText(entry.block)) errors.push(`${base}.block: invalid text`);
|
||||||
|
if (!isVisibleText(entry.reason)) errors.push(`${base}.reason: invalid text`);
|
||||||
|
if (typeof entry.block === "string" && seen.has(entry.block)) errors.push(`${base}.block: duplicate entry`);
|
||||||
|
if (typeof entry.block === "string") seen.add(entry.block);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function semanticKey(unit) {
|
||||||
|
return JSON.stringify([
|
||||||
|
unit.surface,
|
||||||
|
unit.boundary,
|
||||||
|
unit.subsystem,
|
||||||
|
unit.attack_class,
|
||||||
|
hasOwn(unit, "lifecycle") ? unit.lifecycle : null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasValidSemanticFields(unit) {
|
||||||
|
return ["surface", "boundary", "subsystem", "attack_class"].every((field) => isVisibleText(unit[field])) &&
|
||||||
|
(!hasOwn(unit, "lifecycle") || isVisibleText(unit.lifecycle));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireEmptyArray(unit, field, base, errors) {
|
||||||
|
if (Array.isArray(unit[field]) && unit[field].length > 0) {
|
||||||
|
errors.push(`${base}.${field}: unit with status ${safeQuote(unit.status)} must keep this array empty`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireNonemptyArray(unit, field, base, errors) {
|
||||||
|
if (!Array.isArray(unit[field]) || unit[field].length === 0) {
|
||||||
|
errors.push(`${base}.${field}: unit with status ${safeQuote(unit.status)} requires entries`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateStateInvariants(unit, base, errors) {
|
||||||
|
const emptyEvidence = () => {
|
||||||
|
requireEmptyArray(unit, "reviewed_paths", base, errors);
|
||||||
|
requireEmptyArray(unit, "local_checks", base, errors);
|
||||||
|
};
|
||||||
|
const requireOwner = () => {
|
||||||
|
if (!isSafeAgentId(unit.agent_id)) errors.push(`${base}.agent_id: unit with status ${safeQuote(unit.status)} requires a canonical lowercase agent ID`);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (unit.status !== "candidate") requireEmptyArray(unit, "result_fingerprints", base, errors);
|
||||||
|
|
||||||
|
switch (unit.status) {
|
||||||
|
case "planned":
|
||||||
|
if (unit.agent_id !== null) errors.push(`${base}.agent_id: planned unit must be unassigned`);
|
||||||
|
emptyEvidence();
|
||||||
|
requireEmptyArray(unit, "unresolved", base, errors);
|
||||||
|
break;
|
||||||
|
case "not_applicable":
|
||||||
|
case "out_of_scope":
|
||||||
|
case "deferred":
|
||||||
|
if (unit.agent_id !== null) errors.push(`${base}.agent_id: unit with status ${safeQuote(unit.status)} must be unassigned`);
|
||||||
|
emptyEvidence();
|
||||||
|
requireNonemptyArray(unit, "unresolved", base, errors);
|
||||||
|
break;
|
||||||
|
case "in_progress":
|
||||||
|
requireOwner();
|
||||||
|
emptyEvidence();
|
||||||
|
requireEmptyArray(unit, "unresolved", base, errors);
|
||||||
|
break;
|
||||||
|
case "blocked":
|
||||||
|
requireOwner();
|
||||||
|
requireNonemptyArray(unit, "reviewed_paths", base, errors);
|
||||||
|
requireNonemptyArray(unit, "local_checks", base, errors);
|
||||||
|
requireNonemptyArray(unit, "unresolved", base, errors);
|
||||||
|
break;
|
||||||
|
case "covered":
|
||||||
|
requireOwner();
|
||||||
|
requireNonemptyArray(unit, "reviewed_paths", base, errors);
|
||||||
|
requireNonemptyArray(unit, "local_checks", base, errors);
|
||||||
|
requireEmptyArray(unit, "unresolved", base, errors);
|
||||||
|
break;
|
||||||
|
case "candidate":
|
||||||
|
requireOwner();
|
||||||
|
requireNonemptyArray(unit, "reviewed_paths", base, errors);
|
||||||
|
requireNonemptyArray(unit, "local_checks", base, errors);
|
||||||
|
requireNonemptyArray(unit, "result_fingerprints", base, errors);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateAttempts(value, unit, base, errors) {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
errors.push(`${base}.attempts: expected array`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (value.length > MAX_LIST_ITEMS) errors.push(`${base}.attempts: exceeds ${MAX_LIST_ITEMS} entries`);
|
||||||
|
|
||||||
|
const priorOwners = new Set();
|
||||||
|
const priorArtifacts = new Set();
|
||||||
|
let previousWave = 0;
|
||||||
|
value.slice(0, MAX_LIST_ITEMS).forEach((attempt, index) => {
|
||||||
|
const attemptBase = `${base}.attempts[${index}]`;
|
||||||
|
if (!isObject(attempt)) {
|
||||||
|
errors.push(`${attemptBase}: expected object`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const field of ATTEMPT_FIELDS) {
|
||||||
|
if (!hasOwn(attempt, field)) errors.push(`${attemptBase}: missing required field ${safeQuote(field)}`);
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(attempt.wave) || attempt.wave < 1) {
|
||||||
|
errors.push(`${attemptBase}.wave: expected a positive integer`);
|
||||||
|
} else {
|
||||||
|
if (attempt.wave <= previousWave) errors.push(`${attemptBase}.wave: archived attempt waves must be strictly increasing`);
|
||||||
|
if (Number.isInteger(unit.wave) && attempt.wave >= unit.wave) {
|
||||||
|
errors.push(`${attemptBase}.wave: archived attempt wave must precede current wave ${safeQuote(unit.wave)}`);
|
||||||
|
}
|
||||||
|
previousWave = attempt.wave;
|
||||||
|
}
|
||||||
|
if (!ATTEMPT_STATUSES.has(attempt.status)) {
|
||||||
|
errors.push(`${attemptBase}.status: expected "covered", "candidate", or "blocked"`);
|
||||||
|
}
|
||||||
|
let hasFreshOwner = false;
|
||||||
|
if (!isSafeAgentId(attempt.agent_id)) {
|
||||||
|
errors.push(`${attemptBase}.agent_id: archived attempt requires a canonical lowercase agent ID`);
|
||||||
|
} else if (priorOwners.has(attempt.agent_id)) {
|
||||||
|
errors.push(`${attemptBase}.agent_id: assignment owner must be fresh for each attempt`);
|
||||||
|
} else {
|
||||||
|
hasFreshOwner = true;
|
||||||
|
}
|
||||||
|
validateStringArray(attempt.reviewed_paths, `${attemptBase}.reviewed_paths`, errors, { pathValue: true });
|
||||||
|
validateChecks(attempt.local_checks, `${attemptBase}.local_checks`, errors);
|
||||||
|
validateReviewedPathOwnership(attempt, attemptBase, errors);
|
||||||
|
validateStringArray(attempt.result_fingerprints, `${attemptBase}.result_fingerprints`, errors, { fingerprint: true });
|
||||||
|
validateStringArray(attempt.unresolved, `${attemptBase}.unresolved`, errors);
|
||||||
|
if (!isVisibleText(attempt.reassignment_reason)) errors.push(`${attemptBase}.reassignment_reason: invalid text`);
|
||||||
|
validateStateInvariants(attempt, attemptBase, errors);
|
||||||
|
|
||||||
|
if (Array.isArray(attempt.local_checks)) {
|
||||||
|
attempt.local_checks.forEach((check, checkIndex) => {
|
||||||
|
if (!isObject(check)) return;
|
||||||
|
if (priorOwners.has(check.agent_id)) {
|
||||||
|
errors.push(`${attemptBase}.local_checks[${checkIndex}].agent_id: prior assignment owner evidence must remain in its earlier attempt`);
|
||||||
|
}
|
||||||
|
if (typeof check.artifact === "string" && priorArtifacts.has(check.artifact)) {
|
||||||
|
errors.push(`${attemptBase}.local_checks[${checkIndex}].artifact: artifact from an earlier attempt cannot be reused`);
|
||||||
|
}
|
||||||
|
if (check.method === "local" && typeof check.artifact === "string") priorArtifacts.add(check.artifact);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (hasFreshOwner) priorOwners.add(attempt.agent_id);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isSafeAgentId(unit.agent_id) && priorOwners.has(unit.agent_id)) {
|
||||||
|
errors.push(`${base}.agent_id: current assignment owner must be fresh after reassignment`);
|
||||||
|
}
|
||||||
|
if (Array.isArray(unit.local_checks)) {
|
||||||
|
unit.local_checks.forEach((check, index) => {
|
||||||
|
if (!isObject(check)) return;
|
||||||
|
if (priorOwners.has(check.agent_id)) {
|
||||||
|
errors.push(`${base}.local_checks[${index}].agent_id: prior assignment owner evidence must remain in its archived attempt`);
|
||||||
|
}
|
||||||
|
if (typeof check.artifact === "string" && priorArtifacts.has(check.artifact)) {
|
||||||
|
errors.push(`${base}.local_checks[${index}].artifact: artifact from an archived attempt cannot be reused`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectUnitErrors(unit, index) {
|
||||||
|
const errors = createErrorList();
|
||||||
|
const base = `$[${index}]`;
|
||||||
|
if (!isObject(unit)) return [`${base}: expected object`];
|
||||||
|
|
||||||
|
for (const field of REQUIRED_FIELDS) {
|
||||||
|
if (!hasOwn(unit, field)) errors.push(`${base}: missing required field ${safeQuote(field)}`);
|
||||||
|
}
|
||||||
|
for (const field of ["surface", "boundary", "subsystem", "attack_class"]) {
|
||||||
|
if (!isVisibleText(unit[field])) errors.push(`${base}.${field}: invalid text`);
|
||||||
|
}
|
||||||
|
if (hasOwn(unit, "lifecycle") && !isVisibleText(unit.lifecycle)) errors.push(`${base}.lifecycle: invalid text`);
|
||||||
|
|
||||||
|
let expectedId = null;
|
||||||
|
if (!isObject(unit.canonical_refs)) {
|
||||||
|
errors.push(`${base}.canonical_refs: expected object`);
|
||||||
|
} else {
|
||||||
|
const expectedFields = hasOwn(unit.canonical_refs, "lifecycle") ? [...REF_FIELDS, "lifecycle"] : REF_FIELDS;
|
||||||
|
for (const field of expectedFields) {
|
||||||
|
if (!hasOwn(unit.canonical_refs, field)) {
|
||||||
|
errors.push(`${base}.canonical_refs: missing required field ${safeQuote(field)}`);
|
||||||
|
} else if (!isCanonicalRef(unit.canonical_refs[field])) {
|
||||||
|
errors.push(`${base}.canonical_refs.${field}: invalid canonical reference`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(unit.canonical_refs).some((field) => !expectedFields.includes(field))) {
|
||||||
|
errors.push(`${base}.canonical_refs: contains unexpected fields`);
|
||||||
|
}
|
||||||
|
if (hasOwn(unit, "lifecycle") !== hasOwn(unit.canonical_refs, "lifecycle")) {
|
||||||
|
errors.push(`${base}: lifecycle and canonical_refs.lifecycle must appear together`);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
expectedId = canonicalCoverageId(unit.canonical_refs);
|
||||||
|
} catch {
|
||||||
|
// The specific reference errors above are more useful.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isVisibleText(unit.coverage_id, 65536)) {
|
||||||
|
errors.push(`${base}.coverage_id: invalid text`);
|
||||||
|
} else if (expectedId !== null && unit.coverage_id !== expectedId) {
|
||||||
|
errors.push(`${base}.coverage_id: expected canonical ID ${safeQuote(expectedId)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
validateStringArray(unit.starting_paths, `${base}.starting_paths`, errors, { allowEmpty: false, pathValue: true });
|
||||||
|
if (unit.ordinary_attack_class_block !== null && !isVisibleText(unit.ordinary_attack_class_block)) {
|
||||||
|
errors.push(`${base}.ordinary_attack_class_block: expected null or non-empty text`);
|
||||||
|
}
|
||||||
|
validateStringArray(unit.selected_companion_blocks, `${base}.selected_companion_blocks`, errors);
|
||||||
|
validateExcludedBlocks(unit.excluded_blocks, `${base}.excluded_blocks`, errors);
|
||||||
|
if (Array.isArray(unit.selected_companion_blocks) && Array.isArray(unit.excluded_blocks)) {
|
||||||
|
const selected = new Set(unit.selected_companion_blocks);
|
||||||
|
unit.excluded_blocks.forEach((entry, blockIndex) => {
|
||||||
|
if (isObject(entry) && selected.has(entry.block)) {
|
||||||
|
errors.push(`${base}.excluded_blocks[${blockIndex}].block: block is also selected`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!PRIOR_STATUSES.has(unit.prior_status)) errors.push(`${base}.prior_status: invalid value ${safeQuote(unit.prior_status)}`);
|
||||||
|
if (!STATUSES.has(unit.status)) errors.push(`${base}.status: invalid value ${safeQuote(unit.status)}`);
|
||||||
|
if (!Number.isInteger(unit.wave) || unit.wave < 1) errors.push(`${base}.wave: expected a positive integer`);
|
||||||
|
if (unit.agent_id !== null && !isSafeAgentId(unit.agent_id)) errors.push(`${base}.agent_id: expected null or a safe agent ID`);
|
||||||
|
|
||||||
|
validateAttempts(unit.attempts, unit, base, errors);
|
||||||
|
validateStringArray(unit.reviewed_paths, `${base}.reviewed_paths`, errors, { pathValue: true });
|
||||||
|
validateChecks(unit.local_checks, `${base}.local_checks`, errors);
|
||||||
|
validateReviewedPathOwnership(unit, base, errors);
|
||||||
|
validateStringArray(unit.result_fingerprints, `${base}.result_fingerprints`, errors, { fingerprint: true });
|
||||||
|
validateStringArray(unit.unresolved, `${base}.unresolved`, errors);
|
||||||
|
|
||||||
|
validateStateInvariants(unit, base, errors);
|
||||||
|
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readFileWithinLimit(file) {
|
||||||
|
const noFollow = fs.constants.O_NOFOLLOW;
|
||||||
|
const nonBlock = fs.constants.O_NONBLOCK;
|
||||||
|
if (!Number.isInteger(noFollow) || noFollow === 0 || !Number.isInteger(nonBlock) || nonBlock === 0) {
|
||||||
|
// Node exposes no race-safe fallback on these platforms, so reject all inputs.
|
||||||
|
throw new SafeInputError("OS no-follow and nonblocking input protection is unavailable");
|
||||||
|
}
|
||||||
|
|
||||||
|
let descriptor;
|
||||||
|
try {
|
||||||
|
descriptor = fs.openSync(file, fs.constants.O_RDONLY | noFollow | nonBlock);
|
||||||
|
} catch (error) {
|
||||||
|
if (error && (error.code === "ELOOP" || error.code === "EMLINK")) throw new SafeInputError("input must not be a symlink");
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const stat = fs.fstatSync(descriptor);
|
||||||
|
if (!stat.isFile()) throw new SafeInputError("input must be a regular file");
|
||||||
|
if (stat.size > MAX_INPUT_BYTES) throw new SafeInputError(`input exceeds ${MAX_INPUT_BYTES} byte limit`);
|
||||||
|
|
||||||
|
const chunks = [];
|
||||||
|
const buffer = Buffer.allocUnsafe(64 * 1024);
|
||||||
|
let bytesRead = 0;
|
||||||
|
while (true) {
|
||||||
|
const count = fs.readSync(descriptor, buffer, 0, buffer.length, null);
|
||||||
|
if (count === 0) break;
|
||||||
|
bytesRead += count;
|
||||||
|
if (bytesRead > MAX_INPUT_BYTES) throw new SafeInputError(`input exceeds ${MAX_INPUT_BYTES} byte limit`);
|
||||||
|
chunks.push(Buffer.from(buffer.subarray(0, count)));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return UTF8_DECODER.decode(Buffer.concat(chunks, bytesRead));
|
||||||
|
} catch {
|
||||||
|
throw new SafeInputError("input is not valid UTF-8");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
fs.closeSync(descriptor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateDocument(ledger) {
|
||||||
|
const errors = createErrorList();
|
||||||
|
if (!Array.isArray(ledger)) {
|
||||||
|
errors.push("$: expected a top-level array");
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
if (ledger.length > MAX_UNITS) {
|
||||||
|
errors.push(`$: exceeds ${MAX_UNITS} coverage units`);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
errors.push(...preflightDocument(ledger));
|
||||||
|
if (errors.length > 0) return errors;
|
||||||
|
|
||||||
|
const ids = new Map();
|
||||||
|
const semantics = new Map();
|
||||||
|
let previousId = null;
|
||||||
|
for (let index = 0; index < ledger.length && errors.length < LIMITS.validationErrors; index++) {
|
||||||
|
const unit = ledger[index];
|
||||||
|
errors.push(...collectUnitErrors(unit, index));
|
||||||
|
if (errors.length >= LIMITS.validationErrors) break;
|
||||||
|
if (!isObject(unit) || typeof unit.coverage_id !== "string") continue;
|
||||||
|
|
||||||
|
const key = hasValidSemanticFields(unit) ? semanticKey(unit) : null;
|
||||||
|
if (ids.has(unit.coverage_id)) {
|
||||||
|
const previous = ids.get(unit.coverage_id);
|
||||||
|
const qualifier = key !== null && previous.key !== null && previous.key !== key
|
||||||
|
? "canonical identity collision with different semantic fields"
|
||||||
|
: "duplicate coverage ID";
|
||||||
|
errors.push(`$[${index}].coverage_id: ${qualifier} at $[${previous.index}]`);
|
||||||
|
} else {
|
||||||
|
ids.set(unit.coverage_id, { index, key });
|
||||||
|
}
|
||||||
|
if (key !== null && semantics.has(key) && semantics.get(key).id !== unit.coverage_id) {
|
||||||
|
const previous = semantics.get(key);
|
||||||
|
errors.push(`$[${index}].canonical_refs: semantic tuple already uses coverage ID ${safeQuote(previous.id)} at $[${previous.index}]`);
|
||||||
|
} else if (key !== null) {
|
||||||
|
semantics.set(key, { id: unit.coverage_id, index });
|
||||||
|
}
|
||||||
|
if (previousId !== null && previousId > unit.coverage_id) {
|
||||||
|
errors.push(`$[${index}].coverage_id: units must be sorted lexicographically`);
|
||||||
|
}
|
||||||
|
previousId = unit.coverage_id;
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(file) {
|
||||||
|
if (!file) {
|
||||||
|
console.error("Usage: node validate-coverage-ledger.cjs <path-to-coverage-ledger.json>");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let contents;
|
||||||
|
try {
|
||||||
|
contents = readFileWithinLimit(file);
|
||||||
|
} catch (error) {
|
||||||
|
const reason = error instanceof SafeInputError ? error.message : "input could not be opened or read safely";
|
||||||
|
console.error(`Failed to read coverage ledger: ${reason}`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let ledger;
|
||||||
|
try {
|
||||||
|
preflightJsonText(contents);
|
||||||
|
} catch (error) {
|
||||||
|
const reason = error instanceof JsonStructureError ? error.message : "invalid JSON structure";
|
||||||
|
console.error(`Failed to parse coverage ledger: ${reason}`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
ledger = JSON.parse(contents);
|
||||||
|
} catch {
|
||||||
|
console.error("Failed to parse coverage ledger: invalid JSON syntax");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let errors;
|
||||||
|
try {
|
||||||
|
errors = validateDocument(ledger);
|
||||||
|
} catch {
|
||||||
|
console.error("Failed to validate coverage ledger: unexpected validation error");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
for (const message of errors) console.error("ERROR:", message);
|
||||||
|
if (errors.length > 0) {
|
||||||
|
const cap = errors.length === LIMITS.validationErrors ? `; output capped at ${LIMITS.validationErrors}` : "";
|
||||||
|
console.error(`FAIL: ${errors.length} validation error(s)${cap}`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
console.log(`PASS: ${ledger.length} coverage units valid`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
LIMITS,
|
||||||
|
PATH_FORBIDDEN_CHARACTER,
|
||||||
|
UNSAFE_DIAGNOSTIC_CHARACTER,
|
||||||
|
VISIBLE_CONTENT,
|
||||||
|
WINDOWS_RESERVED_COMPONENT,
|
||||||
|
canonicalCoverageId,
|
||||||
|
encodeCanonicalRef,
|
||||||
|
hasVisibleProse,
|
||||||
|
isSafeAgentId,
|
||||||
|
isSafeRelativePath,
|
||||||
|
preflightJsonText,
|
||||||
|
readFileWithinLimit,
|
||||||
|
safeQuote,
|
||||||
|
validateDocument,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (require.main === module) process.exit(run(process.argv[2]));
|
||||||
740
.agents/skills/security-audit/validate-coverage-ledger.test.cjs
Normal file
740
.agents/skills/security-audit/validate-coverage-ledger.test.cjs
Normal file
@ -0,0 +1,740 @@
|
|||||||
|
const assert = require("node:assert/strict");
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const os = require("node:os");
|
||||||
|
const path = require("node:path");
|
||||||
|
const { spawnSync } = require("node:child_process");
|
||||||
|
const test = require("node:test");
|
||||||
|
const {
|
||||||
|
LIMITS,
|
||||||
|
canonicalCoverageId,
|
||||||
|
encodeCanonicalRef,
|
||||||
|
isSafeAgentId,
|
||||||
|
isSafeRelativePath,
|
||||||
|
preflightJsonText,
|
||||||
|
validateDocument,
|
||||||
|
} = require("./validate-coverage-ledger.cjs");
|
||||||
|
|
||||||
|
const validatorPath = path.join(__dirname, "validate-coverage-ledger.cjs");
|
||||||
|
const CLI_TIMEOUT_MS = 5000;
|
||||||
|
const HOSTILE_CLI_TIMEOUT_MS = 15000;
|
||||||
|
const HAS_SAFE_INPUT_OPEN = Number.isInteger(fs.constants.O_NOFOLLOW) &&
|
||||||
|
fs.constants.O_NOFOLLOW !== 0 &&
|
||||||
|
Number.isInteger(fs.constants.O_NONBLOCK) &&
|
||||||
|
fs.constants.O_NONBLOCK !== 0;
|
||||||
|
|
||||||
|
function unit(overrides = {}) {
|
||||||
|
const canonicalRefs = overrides.canonical_refs || {
|
||||||
|
surface: "src/router.ts#POST /users/:id",
|
||||||
|
boundary: "src/authz.ts#requireOwner",
|
||||||
|
subsystem: "packages/api",
|
||||||
|
attack_class: "ATTACK-CLASSES.md#Access control",
|
||||||
|
};
|
||||||
|
const value = {
|
||||||
|
coverage_id: canonicalCoverageId(canonicalRefs),
|
||||||
|
canonical_refs: canonicalRefs,
|
||||||
|
surface: "Update-user route",
|
||||||
|
boundary: "Object ownership",
|
||||||
|
subsystem: "API",
|
||||||
|
attack_class: "Access control",
|
||||||
|
starting_paths: ["src/router.ts", "src/authz.ts"],
|
||||||
|
ordinary_attack_class_block: "ATTACK-CLASSES.md#Access control",
|
||||||
|
selected_companion_blocks: [],
|
||||||
|
excluded_blocks: [{ block: "WEB-PROTOCOL-AND-AUTH.md#Cache behavior", reason: "The route is not cached." }],
|
||||||
|
prior_status: "new",
|
||||||
|
attempts: [],
|
||||||
|
wave: 1,
|
||||||
|
status: "planned",
|
||||||
|
agent_id: null,
|
||||||
|
reviewed_paths: [],
|
||||||
|
local_checks: [],
|
||||||
|
result_fingerprints: [],
|
||||||
|
unresolved: [],
|
||||||
|
};
|
||||||
|
return Object.assign(value, overrides, { canonical_refs: canonicalRefs });
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorsFor(value) {
|
||||||
|
return validateDocument(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runCli(contents, options = {}) {
|
||||||
|
const { nodeArgs = [], timeout = CLI_TIMEOUT_MS } = options;
|
||||||
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-"));
|
||||||
|
const ledgerPath = path.join(directory, "coverage-ledger.json");
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(ledgerPath, contents);
|
||||||
|
return spawnSync(process.execPath, [...nodeArgs, validatorPath, ledgerPath], {
|
||||||
|
encoding: "utf8",
|
||||||
|
timeout,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cliOutput(result) {
|
||||||
|
return `${result.stdout}${result.stderr}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TERMINAL_CONTROL_PAYLOAD = "\u001b\u0007\u0085\u202e";
|
||||||
|
const TERMINAL_CONTROL_BYTES = [
|
||||||
|
Buffer.from([0x1b]),
|
||||||
|
Buffer.from([0x07]),
|
||||||
|
Buffer.from("\u0085"),
|
||||||
|
Buffer.from("\u202e"),
|
||||||
|
];
|
||||||
|
|
||||||
|
function assertNoInjectedControlBytes(output) {
|
||||||
|
const bytes = Buffer.isBuffer(output) ? output : Buffer.from(output, "utf8");
|
||||||
|
for (const marker of TERMINAL_CONTROL_BYTES) {
|
||||||
|
assert.equal(bytes.indexOf(marker), -1, `found raw control bytes ${marker.toString("hex")}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sourceCheck(agentId = "hunter-1", overrides = {}) {
|
||||||
|
return {
|
||||||
|
agent_id: agentId,
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
invariant: "The route checks object ownership.",
|
||||||
|
method: "source",
|
||||||
|
result: "The owner check applies before the update.",
|
||||||
|
artifact: null,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function localCheck(agentId = "hunter-1", overrides = {}) {
|
||||||
|
return sourceCheck(agentId, {
|
||||||
|
method: "local",
|
||||||
|
result: "The bounded fixture accepted the other owner's object.",
|
||||||
|
artifact: `agents/${agentId}/artifacts/result.txt`,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function archivedAttempt(overrides = {}) {
|
||||||
|
const value = {
|
||||||
|
wave: 1,
|
||||||
|
status: "blocked",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
result_fingerprints: [],
|
||||||
|
unresolved: ["The deployed policy is unavailable."],
|
||||||
|
reassignment_reason: "The critic found an unchecked parallel path.",
|
||||||
|
};
|
||||||
|
return Object.assign(value, overrides);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("accepts an empty ledger and complete units", () => {
|
||||||
|
assert.deepEqual(errorsFor([]), []);
|
||||||
|
assert.deepEqual(errorsFor([unit()]), []);
|
||||||
|
|
||||||
|
const missingAttempts = unit();
|
||||||
|
delete missingAttempts.attempts;
|
||||||
|
assert(errorsFor([missingAttempts]).some((error) => error.includes('missing required field "attempts"')));
|
||||||
|
|
||||||
|
const covered = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([covered]), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("accepts a complete ledger through the CLI", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const result = runCli(JSON.stringify([unit()]));
|
||||||
|
assert.equal(result.status, 0, cliOutput(result));
|
||||||
|
assert.match(result.stdout, /PASS: 1 coverage units valid/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("text preflight ignores structural characters and escapes inside strings", () => {
|
||||||
|
const value = unit({
|
||||||
|
surface: "Route \\ slash [list] {object}, colon: quoted \"value\"",
|
||||||
|
excluded_blocks: [{
|
||||||
|
block: "COMPANION.md#Literal [brackets] {braces}",
|
||||||
|
reason: "The text contains a backslash \\ before an escaped \"quote\".",
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
const contents = JSON.stringify([value]);
|
||||||
|
assert.doesNotThrow(() => preflightJsonText(contents));
|
||||||
|
assert.deepEqual(JSON.parse(contents), [value]);
|
||||||
|
if (HAS_SAFE_INPUT_OPEN) {
|
||||||
|
const result = runCli(contents);
|
||||||
|
assert.equal(result.status, 0, cliOutput(result));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("text preflight enforces structural cardinality limits", () => {
|
||||||
|
const depthLimit = LIMITS.nestingDepth;
|
||||||
|
assert.doesNotThrow(() => preflightJsonText(`${"[".repeat(depthLimit)}0${"]".repeat(depthLimit)}`));
|
||||||
|
assert.throws(
|
||||||
|
() => preflightJsonText(`${"[".repeat(depthLimit + 1)}0${"]".repeat(depthLimit + 1)}`),
|
||||||
|
/exceeds nesting depth limit 64/,
|
||||||
|
);
|
||||||
|
|
||||||
|
const tooManyUnits = `[${"null,".repeat(LIMITS.units)}null]`;
|
||||||
|
assert.throws(() => preflightJsonText(tooManyUnits), /exceeds 10000 top-level unit limit/);
|
||||||
|
|
||||||
|
const tooManyItems = `[[${"null,".repeat(LIMITS.collectionItems)}null]]`;
|
||||||
|
assert.throws(() => preflightJsonText(tooManyItems), /exceeds 1000 item array limit/);
|
||||||
|
|
||||||
|
const objectFields = Array.from(
|
||||||
|
{ length: LIMITS.objectFields + 1 },
|
||||||
|
(_, index) => `"field${index}":null`,
|
||||||
|
).join(",");
|
||||||
|
assert.throws(() => preflightJsonText(`[{${objectFields}}]`), /exceeds 1000 field object limit/);
|
||||||
|
|
||||||
|
const fullArray = `[${"null,".repeat(LIMITS.collectionItems - 1)}null]`;
|
||||||
|
const arraysNeeded = Math.floor(LIMITS.preflightValues / (LIMITS.collectionItems + 1)) + 1;
|
||||||
|
const tooManyValues = `[${Array.from({ length: arraysNeeded }, () => fullArray).join(",")}]`;
|
||||||
|
assert.throws(() => preflightJsonText(tooManyValues), /exceeds 500000 total value limit/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("text preflight rejects malformed structural truncation cleanly", () => {
|
||||||
|
assert.throws(() => preflightJsonText("["), /truncated JSON structure/);
|
||||||
|
assert.throws(() => preflightJsonText("[\"unterminated"), /unterminated JSON string/);
|
||||||
|
assert.throws(() => preflightJsonText("[{\"field\":1]"), /mismatched JSON containers/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("derives collision-free canonical IDs from exact UTF-8 references", () => {
|
||||||
|
assert.equal(encodeCanonicalRef("route:POST /users"), "route%3APOST%20%2Fusers");
|
||||||
|
assert.notEqual(encodeCanonicalRef("route name"), encodeCanonicalRef("route-name"));
|
||||||
|
assert.equal(
|
||||||
|
canonicalCoverageId({ surface: "a", boundary: "b", subsystem: "c", attack_class: "d", lifecycle: "retry" }),
|
||||||
|
"a::b::c::d::retry",
|
||||||
|
);
|
||||||
|
assert.throws(() => encodeCanonicalRef("e\u0301"), /invalid canonical reference/);
|
||||||
|
assert.throws(() => encodeCanonicalRef("bad\u0000ref"), /invalid canonical reference/);
|
||||||
|
assert.throws(() => encodeCanonicalRef("hidden\u200bref"), /invalid canonical reference/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects noncanonical, duplicate, and colliding IDs", () => {
|
||||||
|
const wrong = unit({ coverage_id: "display-label-slug" });
|
||||||
|
assert(errorsFor([wrong]).some((error) => error.includes("expected canonical ID")));
|
||||||
|
|
||||||
|
const duplicate = unit();
|
||||||
|
assert(errorsFor([duplicate, unit()]).some((error) => error.includes("duplicate coverage ID")));
|
||||||
|
|
||||||
|
const collision = unit();
|
||||||
|
const differentMeaning = unit({ surface: "Delete-user route" });
|
||||||
|
assert(errorsFor([collision, differentMeaning]).some((error) => error.includes("canonical identity collision")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires canonical references to be own properties", () => {
|
||||||
|
const inherited = Object.create(unit().canonical_refs);
|
||||||
|
const value = unit();
|
||||||
|
value.canonical_refs = inherited;
|
||||||
|
assert(errorsFor([value]).some((error) => error.includes("missing required field")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects aliases for one semantic tuple", () => {
|
||||||
|
const first = unit();
|
||||||
|
const refs = { ...first.canonical_refs, surface: "src/alias.ts#updateUser" };
|
||||||
|
const alias = unit({ canonical_refs: refs });
|
||||||
|
const ledger = [first, alias].sort((left, right) => left.coverage_id.localeCompare(right.coverage_id));
|
||||||
|
assert(errorsFor(ledger).some((error) => error.includes("semantic tuple already uses coverage ID")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires lexicographic order", () => {
|
||||||
|
const secondRefs = {
|
||||||
|
surface: "zzz",
|
||||||
|
boundary: "src/authz.ts#requireOwner",
|
||||||
|
subsystem: "packages/api",
|
||||||
|
attack_class: "ATTACK-CLASSES.md#Access control",
|
||||||
|
};
|
||||||
|
assert(errorsFor([unit({ canonical_refs: secondRefs }), unit()])
|
||||||
|
.some((error) => error.includes("sorted lexicographically")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("validates assignment block maps", () => {
|
||||||
|
const overlap = unit({
|
||||||
|
selected_companion_blocks: ["AI-AND-LLM.md#Tool calls"],
|
||||||
|
excluded_blocks: [{ block: "AI-AND-LLM.md#Tool calls", reason: "Claimed irrelevant." }],
|
||||||
|
});
|
||||||
|
assert(errorsFor([overlap]).some((error) => error.includes("also selected")));
|
||||||
|
|
||||||
|
const noReason = unit({ excluded_blocks: [{ block: "AI-AND-LLM.md#Tool calls", reason: "" }] });
|
||||||
|
assert(errorsFor([noReason]).some((error) => error.includes("reason")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires owned artifacts for local checks and null artifacts for source checks", () => {
|
||||||
|
const local = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [localCheck()],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([local]), []);
|
||||||
|
|
||||||
|
const independentlyVerified = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts", "src/authz.ts"],
|
||||||
|
local_checks: [sourceCheck(), localCheck("verifier-1", { reviewed_paths: ["src/authz.ts"] })],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([independentlyVerified]), []);
|
||||||
|
|
||||||
|
const unownedPath = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts", "src/authz.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
});
|
||||||
|
assert(errorsFor([unownedPath]).some((error) => error.includes("has no check owner")));
|
||||||
|
|
||||||
|
for (const [checkAgentId, artifact] of [
|
||||||
|
[null, "agents/hunter-1/artifacts/result.txt"],
|
||||||
|
["hunter-1", null],
|
||||||
|
["hunter-1", "result.txt"],
|
||||||
|
["hunter-1", "agents/hunter-2/artifacts/result.txt"],
|
||||||
|
["../hunter", "agents/../hunter/artifacts/result.txt"],
|
||||||
|
]) {
|
||||||
|
const value = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [localCheck(checkAgentId, { artifact })],
|
||||||
|
});
|
||||||
|
assert.notEqual(errorsFor([value]).length, 0, `${checkAgentId}: ${artifact}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const unownedSource = unit({
|
||||||
|
status: "blocked",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
unresolved: ["The boundary behavior is not source-visible."],
|
||||||
|
});
|
||||||
|
assert(errorsFor([unownedSource]).some((error) => error.includes("unit with status \"blocked\" requires a canonical lowercase agent ID")));
|
||||||
|
|
||||||
|
const sourceWithArtifact = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck("hunter-1", { artifact: "agents/hunter-1/artifacts/source.txt" })],
|
||||||
|
});
|
||||||
|
assert(errorsFor([sourceWithArtifact]).some((error) => error.includes("source-only check must use null")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires canonical lowercase filesystem-safe agent IDs", () => {
|
||||||
|
for (const value of ["hunter-1", "verifier_2", "a0"]) assert.equal(isSafeAgentId(value), true, value);
|
||||||
|
for (const value of ["Hunter-1", "hunter.1", "hunter-1.", "hunter ", "con", "prn", "aux", "nul", "com1", "lpt9", "../hunter"]) {
|
||||||
|
assert.equal(isSafeAgentId(value), false, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const caseAlias = unit({ status: "in_progress", agent_id: "Hunter-1" });
|
||||||
|
assert(errorsFor([caseAlias]).some((error) => error.includes("canonical lowercase agent ID")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("enforces state evidence", () => {
|
||||||
|
assert(errorsFor([unit({ status: "in_progress" })]).some((error) => error.includes("unit with status \"in_progress\" requires")));
|
||||||
|
assert(errorsFor([unit({ status: "blocked" })]).some((error) => error.includes("unresolved")));
|
||||||
|
assert(errorsFor([unit({ status: "candidate" })]).some((error) => error.includes("reviewed_paths")));
|
||||||
|
|
||||||
|
assert.deepEqual(errorsFor([unit({ status: "in_progress", agent_id: "hunter-1" })]), []);
|
||||||
|
const inProgressEvidence = unit({
|
||||||
|
status: "in_progress",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
});
|
||||||
|
assert(errorsFor([inProgressEvidence]).some((error) => error.includes("must keep this array empty")));
|
||||||
|
|
||||||
|
const assignedPlanned = unit({
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
});
|
||||||
|
assert(errorsFor([assignedPlanned]).some((error) => error.includes("planned unit must be unassigned")));
|
||||||
|
|
||||||
|
const candidate = unit({
|
||||||
|
status: "candidate",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck("hunter-1", { invariant: "Ownership is required.", result: "No check exists." })],
|
||||||
|
result_fingerprints: ["src-router-missing-owner-check"],
|
||||||
|
unresolved: ["validation_budget_exhausted"],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([candidate]), []);
|
||||||
|
|
||||||
|
const blocked = unit({
|
||||||
|
status: "blocked",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
unresolved: ["The deployed policy is unavailable."],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([blocked]), []);
|
||||||
|
const blockedFingerprint = { ...blocked, result_fingerprints: ["forbidden-fingerprint"] };
|
||||||
|
assert(errorsFor([blockedFingerprint]).some((error) => error.includes("result_fingerprints")));
|
||||||
|
|
||||||
|
for (const status of ["not_applicable", "out_of_scope", "deferred"]) {
|
||||||
|
assert.deepEqual(errorsFor([unit({ status, unresolved: ["Reason recorded."] })]), []);
|
||||||
|
const invalid = unit({
|
||||||
|
status,
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
result_fingerprints: ["forbidden-fingerprint"],
|
||||||
|
unresolved: ["Reason recorded."],
|
||||||
|
});
|
||||||
|
const errors = errorsFor([invalid]);
|
||||||
|
assert(errors.some((error) => error.includes("must be unassigned")), status);
|
||||||
|
assert(errors.some((error) => error.includes("reviewed_paths")), status);
|
||||||
|
assert(errors.some((error) => error.includes("result_fingerprints")), status);
|
||||||
|
}
|
||||||
|
|
||||||
|
const coveredFingerprint = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
result_fingerprints: ["forbidden-fingerprint"],
|
||||||
|
});
|
||||||
|
assert(errorsFor([coveredFingerprint]).some((error) => error.includes("result_fingerprints")));
|
||||||
|
|
||||||
|
const coveredUnresolved = unit({
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
unresolved: ["Unexpected unresolved claim."],
|
||||||
|
});
|
||||||
|
assert(errorsFor([coveredUnresolved]).some((error) => error.includes("unresolved")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("archives prior evidence when a critic assigns a fresh owner", () => {
|
||||||
|
const reassigned = unit({
|
||||||
|
attempts: [archivedAttempt()],
|
||||||
|
wave: 2,
|
||||||
|
status: "in_progress",
|
||||||
|
agent_id: "hunter-2",
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([reassigned]), []);
|
||||||
|
|
||||||
|
const finalClosure = unit({
|
||||||
|
attempts: [archivedAttempt()],
|
||||||
|
wave: 2,
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-2",
|
||||||
|
reviewed_paths: ["src/authz.ts"],
|
||||||
|
local_checks: [sourceCheck("hunter-2", { reviewed_paths: ["src/authz.ts"] })],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([finalClosure]), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("preserves candidate provenance when reassignment must be deferred", () => {
|
||||||
|
const candidateAttempt = archivedAttempt({
|
||||||
|
status: "candidate",
|
||||||
|
result_fingerprints: ["src-router-missing-owner-check"],
|
||||||
|
unresolved: ["validation_budget_exhausted"],
|
||||||
|
});
|
||||||
|
const deferred = unit({
|
||||||
|
attempts: [candidateAttempt],
|
||||||
|
wave: 2,
|
||||||
|
status: "deferred",
|
||||||
|
unresolved: ["quick_profile_final_critic"],
|
||||||
|
});
|
||||||
|
assert.deepEqual(errorsFor([deferred]), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects reassignment owner reuse and evidence mixing", () => {
|
||||||
|
const reusedOwner = unit({
|
||||||
|
attempts: [archivedAttempt()],
|
||||||
|
wave: 2,
|
||||||
|
status: "in_progress",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
});
|
||||||
|
assert(errorsFor([reusedOwner]).some((error) => error.includes("current assignment owner must be fresh")));
|
||||||
|
|
||||||
|
const mixedEvidence = unit({
|
||||||
|
attempts: [archivedAttempt({ local_checks: [localCheck()] })],
|
||||||
|
wave: 2,
|
||||||
|
status: "covered",
|
||||||
|
agent_id: "hunter-2",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [localCheck()],
|
||||||
|
});
|
||||||
|
const errors = errorsFor([mixedEvidence]);
|
||||||
|
assert(errors.some((error) => error.includes("prior assignment owner evidence must remain")));
|
||||||
|
assert(errors.some((error) => error.includes("artifact from an archived attempt cannot be reused")));
|
||||||
|
|
||||||
|
const mixedHistory = unit({
|
||||||
|
attempts: [
|
||||||
|
archivedAttempt({ local_checks: [localCheck()] }),
|
||||||
|
archivedAttempt({
|
||||||
|
wave: 2,
|
||||||
|
agent_id: "hunter-2",
|
||||||
|
local_checks: [localCheck()],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
wave: 3,
|
||||||
|
status: "in_progress",
|
||||||
|
agent_id: "hunter-3",
|
||||||
|
});
|
||||||
|
const historyErrors = errorsFor([mixedHistory]);
|
||||||
|
assert(historyErrors.some((error) => error.includes("prior assignment owner evidence must remain in its earlier attempt")));
|
||||||
|
assert(historyErrors.some((error) => error.includes("artifact from an earlier attempt cannot be reused")));
|
||||||
|
|
||||||
|
const unordered = unit({
|
||||||
|
attempts: [archivedAttempt(), archivedAttempt({
|
||||||
|
wave: 1,
|
||||||
|
agent_id: "hunter-2",
|
||||||
|
local_checks: [sourceCheck("hunter-2")],
|
||||||
|
})],
|
||||||
|
wave: 3,
|
||||||
|
status: "in_progress",
|
||||||
|
agent_id: "hunter-3",
|
||||||
|
});
|
||||||
|
assert(errorsFor([unordered]).some((error) => error.includes("strictly increasing")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects unsafe paths and malformed fingerprints", () => {
|
||||||
|
for (const value of [
|
||||||
|
"/etc/passwd",
|
||||||
|
"../src/file.js",
|
||||||
|
"src/../file.js",
|
||||||
|
"src/con.txt",
|
||||||
|
"src/PRN",
|
||||||
|
"src/AUX.c",
|
||||||
|
"src/NUL",
|
||||||
|
"src/CLOCK$.txt",
|
||||||
|
"src/conin$.txt",
|
||||||
|
"src/conout$",
|
||||||
|
"src/COM1.log",
|
||||||
|
"src/lpt9",
|
||||||
|
"src/COM\u00b9.log",
|
||||||
|
"src/COM\u00b2.log",
|
||||||
|
"src/COM\u00b3.log",
|
||||||
|
"src/lpt\u00b9",
|
||||||
|
"src/lpt\u00b2",
|
||||||
|
"src/lpt\u00b3",
|
||||||
|
"src/file.js.",
|
||||||
|
"C:/src/file.js",
|
||||||
|
"src/file\n.js",
|
||||||
|
"src/file\u0085.js",
|
||||||
|
"src/file\u2028.js",
|
||||||
|
"src/file\u200b.js",
|
||||||
|
"src/file\u034f.js",
|
||||||
|
"src/file\ufe0f.js",
|
||||||
|
]) {
|
||||||
|
assert.equal(isSafeRelativePath(value), false, value);
|
||||||
|
}
|
||||||
|
assert.equal(isSafeRelativePath("src/handler.js"), true);
|
||||||
|
assert.equal(isSafeRelativePath("src/caf\u00e9/handler.js"), true);
|
||||||
|
assert(errorsFor([unit({ starting_paths: ["../src/router.ts"] })]).some((error) => error.includes("repository-relative path")));
|
||||||
|
assert(errorsFor([unit({
|
||||||
|
status: "candidate",
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: ["src/router.ts"],
|
||||||
|
local_checks: [sourceCheck("hunter-1", { invariant: "Ownership is required.", result: "No check exists." })],
|
||||||
|
result_fingerprints: ["not stable"],
|
||||||
|
})]).some((error) => error.includes("invalid fingerprint")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects format, default-ignorable, and invalid-scalar prose", () => {
|
||||||
|
for (const invisible of ["\u200b", "\u034f", "\ufe0f", "\ud800"]) {
|
||||||
|
assert(errorsFor([unit({ surface: invisible })]).some((error) => error.includes("surface")), JSON.stringify(invisible));
|
||||||
|
assert(errorsFor([unit({
|
||||||
|
excluded_blocks: [{ block: "ATTACK-CLASSES.md#Access control", reason: invisible }],
|
||||||
|
})]).some((error) => error.includes("reason")), JSON.stringify(invisible));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("quotes input-derived controls in direct validation errors", () => {
|
||||||
|
const invalidStatus = `invalid-${TERMINAL_CONTROL_PAYLOAD}`;
|
||||||
|
const invalidPath = `src/${TERMINAL_CONTROL_PAYLOAD}.js`;
|
||||||
|
const value = unit({
|
||||||
|
status: invalidStatus,
|
||||||
|
agent_id: "hunter-1",
|
||||||
|
reviewed_paths: [invalidPath],
|
||||||
|
local_checks: [sourceCheck()],
|
||||||
|
result_fingerprints: ["force-state-error"],
|
||||||
|
});
|
||||||
|
const output = errorsFor([value]).join("\n");
|
||||||
|
|
||||||
|
assert.match(output, /\$\[0\]\.status/);
|
||||||
|
assert.match(output, /\$\[0\]\.reviewed_paths/);
|
||||||
|
assert.match(output, /\\u001b/);
|
||||||
|
assert.match(output, /\\u0007/);
|
||||||
|
assert.match(output, /\\u0085/);
|
||||||
|
assert.match(output, /\\u202e/);
|
||||||
|
assertNoInjectedControlBytes(output);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("quotes input-derived controls in CLI validation errors", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const value = unit({
|
||||||
|
status: `invalid-${TERMINAL_CONTROL_PAYLOAD}`,
|
||||||
|
result_fingerprints: ["force-state-error"],
|
||||||
|
});
|
||||||
|
const result = runCli(JSON.stringify([value]));
|
||||||
|
|
||||||
|
assert.equal(result.status, 1, cliOutput(result));
|
||||||
|
assert.match(result.stderr, /\$\[0\]\.status/);
|
||||||
|
assert.match(result.stderr, /\\u001b/);
|
||||||
|
assertNoInjectedControlBytes(result.stderr);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns a generic syntax error without parser-supplied controls", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const malformed = Buffer.concat([
|
||||||
|
Buffer.from("["),
|
||||||
|
Buffer.from(TERMINAL_CONTROL_PAYLOAD),
|
||||||
|
Buffer.from("]"),
|
||||||
|
]);
|
||||||
|
const result = runCli(malformed);
|
||||||
|
|
||||||
|
assert.equal(result.status, 1, cliOutput(result));
|
||||||
|
assert.equal(result.stderr, "Failed to parse coverage ledger: invalid JSON syntax\n");
|
||||||
|
assertNoInjectedControlBytes(result.stderr);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not reflect controls from a failed CLI input path", () => {
|
||||||
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-path-"));
|
||||||
|
const missingPath = path.join(directory, `missing-${TERMINAL_CONTROL_PAYLOAD}.json`);
|
||||||
|
try {
|
||||||
|
const result = spawnSync(process.execPath, [validatorPath, missingPath], {
|
||||||
|
encoding: "utf8",
|
||||||
|
timeout: CLI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
assert.equal(result.status, 1, cliOutput(result));
|
||||||
|
assert.match(result.stderr, /Failed to read coverage ledger:/);
|
||||||
|
assertNoInjectedControlBytes(result.stderr);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects invalid UTF-8 through the CLI", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const encoded = Buffer.from(JSON.stringify([unit()]));
|
||||||
|
const marker = Buffer.from("Update-user route");
|
||||||
|
const markerOffset = encoded.indexOf(marker);
|
||||||
|
assert.notEqual(markerOffset, -1);
|
||||||
|
const malformed = Buffer.concat([
|
||||||
|
encoded.subarray(0, markerOffset),
|
||||||
|
Buffer.from([0x80]),
|
||||||
|
encoded.subarray(markerOffset + marker.length),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = runCli(malformed);
|
||||||
|
const output = cliOutput(result);
|
||||||
|
assert.equal(result.status, 1, output);
|
||||||
|
assert.match(output, /input is not valid UTF-8/);
|
||||||
|
assert.doesNotMatch(output, /TypeError|stack|at validate-coverage-ledger/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects a FIFO through the CLI without blocking", { skip: process.platform === "win32" || !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-fifo-"));
|
||||||
|
const fifoPath = path.join(directory, "coverage-ledger.json");
|
||||||
|
try {
|
||||||
|
const created = spawnSync("mkfifo", [fifoPath], { encoding: "utf8", timeout: CLI_TIMEOUT_MS });
|
||||||
|
assert.equal(created.status, 0, cliOutput(created));
|
||||||
|
|
||||||
|
const result = spawnSync(process.execPath, [validatorPath, fifoPath], {
|
||||||
|
encoding: "utf8",
|
||||||
|
timeout: CLI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
const output = cliOutput(result);
|
||||||
|
assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
|
||||||
|
assert.equal(result.status, 1, output);
|
||||||
|
assert.match(output, /input must be a regular file/);
|
||||||
|
assert.doesNotMatch(output, /stack|at validate-coverage-ledger/i);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects a symlink through the CLI", { skip: process.platform === "win32" || !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "validate-coverage-ledger-symlink-"));
|
||||||
|
const targetPath = path.join(directory, "target.json");
|
||||||
|
const symlinkPath = path.join(directory, "coverage-ledger.json");
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(targetPath, JSON.stringify([unit()]));
|
||||||
|
fs.symlinkSync(targetPath, symlinkPath);
|
||||||
|
const result = spawnSync(process.execPath, [validatorPath, symlinkPath], {
|
||||||
|
encoding: "utf8",
|
||||||
|
timeout: CLI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
const output = cliOutput(result);
|
||||||
|
assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
|
||||||
|
assert.equal(result.status, 1, output);
|
||||||
|
assert.match(output, /input must not be a symlink/);
|
||||||
|
assert.doesNotMatch(output, /stack|at validate-coverage-ledger/i);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects deeply nested input without recursion failure", () => {
|
||||||
|
let nested = 0;
|
||||||
|
for (let depth = 0; depth < 20000; depth++) nested = [nested];
|
||||||
|
assert(errorsFor(nested).some((error) => error.includes("exceeds nesting depth limit 64")));
|
||||||
|
if (!HAS_SAFE_INPUT_OPEN) return;
|
||||||
|
|
||||||
|
const result = runCli(`${"[".repeat(20000)}0${"]".repeat(20000)}`);
|
||||||
|
const output = cliOutput(result);
|
||||||
|
assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
|
||||||
|
assert.equal(result.status, 1, output);
|
||||||
|
assert.match(output, /exceeds nesting depth limit 64/);
|
||||||
|
assert.doesNotMatch(output, /RangeError|Maximum call stack|stack|at validate-coverage-ledger/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects multi-megabyte nesting under a constrained Node heap", { skip: !HAS_SAFE_INPUT_OPEN }, () => {
|
||||||
|
const openContainers = "[".repeat(2000000);
|
||||||
|
const cases = [
|
||||||
|
openContainers,
|
||||||
|
`${openContainers}0${"]".repeat(2000000)}`,
|
||||||
|
];
|
||||||
|
for (const contents of cases) {
|
||||||
|
const result = runCli(contents, {
|
||||||
|
nodeArgs: ["--max-old-space-size=64"],
|
||||||
|
timeout: HOSTILE_CLI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
const output = cliOutput(result);
|
||||||
|
assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
|
||||||
|
assert.equal(result.status, 1, output);
|
||||||
|
assert.match(output, /exceeds nesting depth limit 64/);
|
||||||
|
assert.doesNotMatch(output, /heap out of memory|allocation failed|RangeError|Maximum call stack|stack|at validate-coverage-ledger/i);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("caps malformed 10000-unit validation output", () => {
|
||||||
|
assert.equal(errorsFor(Array.from({ length: LIMITS.units }, () => null)).length, LIMITS.validationErrors);
|
||||||
|
if (!HAS_SAFE_INPUT_OPEN) return;
|
||||||
|
|
||||||
|
const result = runCli(JSON.stringify(Array.from({ length: LIMITS.units }, () => null)));
|
||||||
|
const output = cliOutput(result);
|
||||||
|
assert.notEqual(result.error && result.error.code, "ETIMEDOUT", output);
|
||||||
|
assert.equal(result.status, 1, output);
|
||||||
|
assert.match(output, /output capped at 100/);
|
||||||
|
assert(output.length < 20000, `unexpected output length ${output.length}`);
|
||||||
|
assert.doesNotMatch(output, /RangeError|Maximum call stack|stack|at validate-coverage-ledger/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects malformed top-level data and excessive unit counts", () => {
|
||||||
|
assert.deepEqual(errorsFor({ units: [] }), ["$: expected a top-level array"]);
|
||||||
|
const tooMany = Array.from({ length: 10001 }, () => null);
|
||||||
|
const errors = errorsFor(tooMany);
|
||||||
|
assert.deepEqual(errors, ["$: exceeds 10000 coverage units"]);
|
||||||
|
|
||||||
|
const oversizedCollection = unit({ extra: Array.from({ length: LIMITS.collectionItems + 1 }, () => null) });
|
||||||
|
assert(errorsFor([oversizedCollection]).some((error) => error.includes("exceeds 1000 entries")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("accepts a canonical ID derived from near-maximum multibyte references", () => {
|
||||||
|
const canonicalRefs = {
|
||||||
|
surface: "\u6f22".repeat(1024),
|
||||||
|
boundary: "\u00e9".repeat(1024),
|
||||||
|
subsystem: "packages/api",
|
||||||
|
attack_class: "\u6f22".repeat(1023) + "\u00e9",
|
||||||
|
};
|
||||||
|
const value = unit({ canonical_refs: canonicalRefs });
|
||||||
|
assert(value.coverage_id.length > 16384, `coverage_id length ${value.coverage_id.length}`);
|
||||||
|
assert(value.coverage_id.length <= 65536, `coverage_id length ${value.coverage_id.length}`);
|
||||||
|
assert.deepEqual(errorsFor([value]), []);
|
||||||
|
|
||||||
|
if (HAS_SAFE_INPUT_OPEN) {
|
||||||
|
const result = runCli(JSON.stringify([value]));
|
||||||
|
assert.equal(result.status, 0, cliOutput(result));
|
||||||
|
}
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user