feat(skills): import architecture and workflow skills

- Add api-design: REST membranes, contract-first schemas, and clamped validation
- Add database-design: SQLite WAL mode, repository pattern, and keyset pagination
- Add git-workflow: atomic staging, conventional commits, and non-destructive hygiene
- Add emergency-procedures: safe circuit breakers, backup snapshotting, and recovery
- Standardize all skills to 5-phase Skill Architect protocol
- Synchronize symlinks across OpenCode, Codex, and Claude Code
This commit is contained in:
vasily committed 2026-10-13 16:47:41 +08:00
1 parent 5a19e1cd9d
commit 3fe0d13dd6
4 files changed
+355

No files matched your search

+104
View File
@@ -0,0 +1,104 @@
---
name: api-design
description: >
Designs RESTful APIs, typed schema membranes, request/response validation contracts, and API documentation.
Use when creating or modifying API routes, defining request/response schemas, designing error responses,
or standardizing API contracts.
concerns: [security, system-one-balance]
---
# API Design & Membrane Architecture
Governs API design and boundary membranes, ensuring typed validation, input clamping, predictable HTTP semantics, and consistent structured error contracts.
---
## Phase 0: Setup and Protocols
1. **Membrane Principles**:
- **Boundary Isolation**: Route handlers serve as the transport membrane. Core business services and data access layers remain transport-agnostic (never import web framework request objects or HTTP status codes into domain logic).
- **Contract-First Validation**: Define typed schemas (e.g. Pydantic, Zod, TypeScript interfaces) before implementing endpoint logic.
- **Dependency Injection**: Inject database sessions, repositories, and authentication state into route handlers; avoid importing global singletons directly.
---
## Phase 1: Ingest and Check
1. **Identify Endpoint Requirements**:
- Resource name, target path, HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`).
- Expected input payload, query parameters, route path variables, and headers.
- Response model, status codes (200, 201, 204), and error failure modes.
2. **Input Boundary Clamping**:
- Enforce explicit upper bounds on all strings (e.g. `min_length=1`, `max_length=200` for names; `max_length=50000` for content).
- Enforce pagination limits: `1 <= limit <= 50` (or `100` max).
- Constrain array inputs: clamp batch endpoints to maximum batch sizes.
---
## Phase 2: Processing (Core Logic)
### Step 1: Define Typed Contracts
```python
# 1. Request & Response Schemas
class ResourceCreateRequest(BaseModel):
name: str = Field(..., min_length=1, max_length=200)
description: str | None = Field(None, max_length=2000)
class ResourceResponse(BaseModel):
id: str
name: str
description: str | None = None
created_at: datetime
```
### Step 2: Implement Route Handler
```python
# 2. Endpoint Implementation
@router.post("/resources", response_model=ResourceResponse, status_code=201)
async def create_resource(
payload: ResourceCreateRequest,
repo: ResourceRepository = Depends(get_resource_repo),
):
entity = await repo.create(payload.model_dump())
return ResourceResponse.model_validate(entity)
```
### Step 3: Enforce HTTP & Error Semantics
- **HTTP Methods**:
- `POST`: Resource creation / command execution (201 Created or 200 OK).
- `GET`: Idempotent retrieval (200 OK).
- `PUT`: Full resource replacement (200 OK).
- `PATCH`: Partial state update (200 OK).
- `DELETE`: Resource removal (204 No Content).
- **Structured Error Responses**:
- Return standardized error objects (e.g. RFC 7807 problem details or structured error payloads):
```json
{
"error": {
"code": "RESOURCE_NOT_FOUND",
"message": "Resource with id 'xyz' was not found",
"details": {}
}
}
```
- Standard status codes: 400 (Validation), 401 (Unauthenticated), 403 (Unauthorized), 404 (Not Found), 409 (Conflict).
- **Timezone Invariant**: Always serialize timestamps in UTC using ISO-8601 (`YYYY-MM-DDTHH:MM:SSZ`).
---
## Phase 3: The System One Balance Pass
- **Augment, Don't Handcuff**:
- Do NOT over-complicate simple internal endpoints with bloated enterprise middleware.
- Keep route handlers thin: route logic should unpack requests, call services/repos, and map to response models.
- Fail open on safe internal queries; enforce rigorous clamping at external boundary layers.
---
## Phase 4: Output Execution & Verification
1. Verify:
- Route docstrings populate OpenAPI / Swagger schemas accurately.
- All response models are strongly typed without bare `dict` or `Any` escapes.
- Input clamping fields prevent memory exhaustion and DoS.
2. Deliver the schema definition, route implementation, and corresponding test case.
+91
View File
@@ -0,0 +1,91 @@
---
name: database-design
description: >
Designs high-performance relational schemas, SQLite WAL storage, repository data access patterns,
composite indexing, and entity models. Use when creating or modifying database tables, defining entity models,
optimizing query performance, or planning migrations.
concerns: [system-one-balance]
---
# Database Design & Storage Architecture
Governs persistence, entity modeling, and high-concurrency relational/SQLite storage patterns across backend projects.
---
## Phase 0: Setup and Protocols
1. **Storage Invariants**:
- **SQLite WAL Mode**: Always enable Write-Ahead Logging (`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;`) for concurrent read/write throughput.
- **Connection Scoping**: Thread-safety and connection pooling must be explicit. Never share open database cursor connections across concurrent threads or asynchronous tasks.
- **Minimal Transaction Footprint**: Prepare data and run validation *before* opening a transaction. Commit writes swiftly to minimize table/row lock contention.
- **Entity Separation**: Keep domain entities (dataclasses, Pydantic models) decoupled from low-level SQL row drivers. Repositories map raw rows to domain objects.
---
## Phase 1: Ingest and Check
1. **Model Requirements**:
- Identify entities, relations (1:1, 1:N, N:M), cascade behaviors, and foreign key constraints.
- Determine write concurrency levels and access patterns (read-heavy vs. write-intensive).
- Identify query filter combinations to determine mandatory indexing.
---
## Phase 2: Processing (Core Logic)
### Step 1: Entity Definition
Define pure domain entities decoupled from SQL execution:
```python
@dataclass
class UserSession:
id: str
user_id: str
token_hash: str
created_at: datetime
expires_at: datetime
```
### Step 2: DDL & Migration Schema
Author DDL with strict types, primary keys, and foreign keys:
```sql
CREATE TABLE IF NOT EXISTS user_sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
token_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
```
### Step 3: Composite Indexing
Create composite indexes on high-cardinality filters and join columns:
```sql
CREATE INDEX IF NOT EXISTS idx_user_sessions_user_expires
ON user_sessions (user_id, expires_at);
```
### Step 4: Query Optimization & Pagination
- **Parameterized SQL**: Always bind query parameters with `:named` or `?` syntax. String interpolation or raw concatenation in SQL statements is strictly prohibited.
- **Clamped Limits**: Never execute unbounded `SELECT *` queries. Enforce default limits (`1 <= limit <= 50`).
- **Keyset Pagination**: For deep feeds or log tables, prefer keyset pagination (`WHERE id > :last_id ORDER BY id ASC LIMIT :limit`) over high-offset scans (`OFFSET 10000`) which cause linear disk scans in relational engines.
---
## Phase 3: The System One Balance Pass
- **Augment, Don't Handcuff**:
- Keep migration scripts straightforward and forward-compatible.
- Do NOT create premature indexes on low-cardinality flags (e.g. `is_active` boolean columns) where table scans are faster.
- Choose the simplest storage architecture that satisfies requirements (e.g. SQLite WAL is sufficient for thousands of writes/sec without external DBMS overhead).
---
## Phase 4: Output Execution & Verification
1. Verify:
- Foreign key constraints enabled (`PRAGMA foreign_keys=ON;`).
- All parameters sanitized via parameterized queries.
- Composite indexes cover common query filters and sorting keys.
2. Deliver the entity definition, DDL schema, repository access methods, and migration step.
+83
View File
@@ -0,0 +1,83 @@
---
name: emergency-procedures
description: >
Recovery protocols when development loops fail, agent context is corrupted, git state is tangled,
or quality gates break. Use when development becomes chaotic, thrashing loops occur, or when asked to recover state.
concerns: [system-one-balance]
---
# Emergency Recovery Procedures
Standardized protocols for halting cascading failures, stabilizing git state, restoring agent context, and recovering working development branches.
---
## Phase 0: Setup and Protocols
1. **Circuit-Breaker Invariants**:
- **Halt Implementation**: When an agent gets stuck in a thrashing loop, stop writing additional code immediately.
- **Zero Destructive Discards**: Never run destructive commands (`git reset --hard`, `git clean -fdx`) without creating a safe backup branch or stash first.
- **Isolate the Failure**: Determine whether the defect is environment, git state, code regression, or context divergence.
---
## Phase 1: Ingest and Check
1. Detect emergency signals:
- **Context Loss**: Agent suggests solutions contradicting established repo patterns or attempts wide, unsolicited rewrites.
- **Git Confusion**: Unmerged conflicts, detached HEAD state, or untracked changes scattered across directories.
- **Test Thrashing**: Attempted fixes repeatedly break tests in alternating cycles.
2. Freeze and document:
- Record the current git commit SHA, active branch, and modified file list (`git status`).
---
## Phase 2: Processing (Core Logic)
### Step 1: Secure Working State
Before making any changes, preserve the current uncommitted state:
```bash
# Create a safety branch with current WIP
git checkout -b emergency-backup-$(date +%Y%m%d%H%M%S)
git add -A
git commit -m "emergency: snapshot before recovery"
```
### Step 2: Roll Back to Last Known Good State
Return to the main branch or stable checkpoint:
```bash
git checkout -
git status
```
### Step 3: Re-anchor Context
1. Inspect the last stable commit and review actual working patterns in the codebase.
2. Read project README, architecture docs, or `SPEC.md` to re-align goals.
3. Formulate the single smallest task that can be verified in isolation.
### Step 4: Decompose Complex Tasks
If a task ballooned in complexity:
1. Break down the task into steps of ≤ 50 lines of change each.
2. Sequence steps so each can be independently tested and committed.
3. Obtain user confirmation on the refined task plan before re-attempting.
---
## Phase 3: The System One Balance Pass
- **Augment, Don't Handcuff**:
- Do NOT panic or spam long conversational apologies. State the issue concisely, show the preserved backup branch, and propose the recovery plan.
- Safe inspection (`git status`, `git diff`, `git log`) must be executed immediately without confirmation gates.
- Reserve confirmation prompts strictly for discarding branches or rolling back production databases.
---
## Phase 4: Output Execution & Verification
1. Verify:
- Workspace working tree is clean or returned to a stable, reproducible state.
- Test suite passes on the recovered base.
2. Deliver the incident summary:
- Root cause of the disruption.
- State of the backup branch.
- Concrete, small next step to resume forward progress safely.
+77
View File
@@ -0,0 +1,77 @@
---
name: git-workflow
description: >
Atomic commit grouping, selective staging, conventional commit messages, and clean git history hygiene.
Use when preparing commits, staging changes selectively, reviewing git diffs, or standardizing commit messages.
concerns: [system-one-balance]
---
# Git Workflow & Atomic Staging
Enforces clean, logical version control hygiene, atomic commits, and conventional commit standards across repositories.
---
## Phase 0: Setup and Protocols
1. **Non-Negotiable Invariants**:
- **Never Stage Unrelated Edits**: Inspect `git status` and diffs before staging. Stage only files directly relevant to the current task. Preserve untouched user work.
- **Never Use Destructive Resets**: Never execute `git reset --hard` or `git checkout .` without explicit user instruction.
- **Verify Before Committing**: Run quality gates (tests, linter) before creating commits.
---
## Phase 1: Ingest and Check
1. Run `git status` to inspect modified, staged, and untracked files.
2. Review `git diff` for staged vs. unstaged changes to ensure no extraneous edits or debug logs are included.
3. Identify the logical boundaries of the work to separate independent changes.
---
## Phase 2: Processing (Core Logic)
### Step 1: Logical Commit Grouping
Group changes into focused, cohesive commits rather than bulk-committing unrelated subsystems:
1. **Infrastructure & DDL**: Table migrations, config schemas, and models.
2. **Core Logic**: Services, domain algorithms, and processors.
3. **API & Routes**: Web endpoints, controllers, and schemas.
4. **Tests & Docs**: Automated tests, documentation, and specs.
### Step 2: Selective Staging
- Stage specific files explicitly:
```bash
git add path/to/file1 path/to/file2
```
- Avoid blanket `git add .` when unstaged experimental edits exist in the workspace.
### Step 3: Conventional Commit Formatting
Follow standard conventional commit prefixes:
- `feat(<scope>):` New functionality or feature.
- `fix(<scope>):` Bug fix or regression resolution.
- `refactor(<scope>):` Code restructuring without behavioral change.
- `perf(<scope>):` Performance optimization.
- `sec(<scope>):` Security hardening or vulnerability fix.
- `docs(<scope>):` Documentation updates.
- `test(<scope>):` Adding or updating tests.
- `chore(<scope>):` Tooling, dependencies, or maintenance.
---
## Phase 3: The System One Balance Pass
- **Augment, Don't Handcuff**:
- Safe operations (e.g. `git status`, `git diff`, staging known files, creating a commit) must be frictionless fast paths.
- Do NOT prompt the user with interactive confirmation modals for routine commits during an ongoing implementation.
- Reserve confirmation prompts strictly for irreversible actions (`git push --force`, `git branch -D`, `git clean -fdx`).
---
## Phase 4: Output Execution & Verification
1. Create the commit with a concise, descriptive message.
2. Verify commit creation:
```bash
git log -n 1 --oneline
```
3. Confirm working tree status remains clean and expected.