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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions .agents/tdd/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
name: tdd-red-green-refactor
description: >
Enforces a disciplined Red-Green-Refactor (TDD) workflow in TypeScript/Node.js.
Use this whenever creating new features, fixing bugs, or migrating logic to ensure
high-quality, verifiable implementations.
---

# Red-Green-Refactor (TDD) Skill: TypeScript Edition

This skill implements a structural framework for AI-assisted programming to ensure every line of code is verifiable, typed, and purposeful.

## The Three-Phase Cycle

### Phase 1: Red (Establish Failure)
You must prove the feature does not exist and that your test is valid.
1. **Write One Test**: Create a single test case (e.g., in Vitest or Jest) for the next small piece of behavior.
2. **Execute & Fail**: Run the test. It must fail.
3. **Verify**: Ensure the failure is related to the missing logic (e.g., `ReferenceError: add is not defined`) and not a configuration error.

### Phase 2: Green (Minimal Pass)
Make the test pass as quickly and simply as possible.
1. **Minimal Implementation**: Write the simplest code that satisfies the test. Do not build for the future; focus strictly on the current "Red" test.
2. **Run Tests**: Execute the suite. All tests must be Green.
3. **Evidence**: The transition from Red to Green is the "Proof of Work" for the developer.

### Phase 3: Refactor (Clean Up)
Improve the code structure while maintaining the "Green" state.
1. **Clean Up**: Improve naming, remove duplication, and optimize the code written in Phase 2.
2. **Safety Net**: Rerun the tests after every change. If they turn Red, revert the change immediately.

---

## Core Operational Rules

### 1. No "Horizontal Splurging"
You are strictly forbidden from writing a large "splurge" of multiple tests at once. You must follow a strictly incremental loop:
- **Write 1 Test -> See it Fail -> Write 1 Fix -> See it Pass**.
- Repeat this loop for every sub-feature.

### 2. Impose Backpressure
Use automated assertions and strong typing (TypeScript) as backpressure to prevent the AI from "guessing" the solution or "playing in the mud" with low-quality code.

### 3. Verification of Integrity
Never modify an existing test to make a failing implementation pass. If a test must change, it must be because the requirement changed, not because the code is difficult to write.

---

## Example Workflow (TypeScript + Vitest)

**Step 1: Red**
```typescript
// math.test.ts
import { describe, it, expect } from 'vitest';
import { add } from './math';

describe('add', () => {
it('should sum two numbers', () => {
expect(add(2, 2)).toBe(4); // Fails: ReferenceError: add is not defined
});
});
```

**Step 2: Green**
```typescript
// math.ts
export const add = (a: any, b: any) => {
return 4; // Passes: Minimal code to satisfy the test
};
```

**Step 3: Refactor**
```typescript
// math.ts
/**
* Sums two numbers with explicit type safety.
*/
export const add = (a: number, b: number): number => {
return a + b; // Passes: Proper implementation with safety net
};
```
190 changes: 190 additions & 0 deletions .agents/typed-service-contracts/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
---
name: typed-service-contracts
description: Architecture standard for building robust, type-safe TypeScript services using the "Spec and Handler" pattern. Use when building CLIs, libraries, or complex business logic.
---

# Typed Service Contracts (Spec & Handler Pattern)

This skill defines a **Vertical Slice Architecture** backed by **Design by Contract (DbC)** principles. It treats application logic as rigorously defined Units of Work where inputs are parsed (not just validated) and errors are treated as values (Result Pattern) rather than exceptions.

## When to use this skill

- **Building CLIs or Libraries:** When you need strict boundaries between user input and system logic.
- **Complex Validation:** When inputs require transformation (parsing) before being useful (e.g., ensuring a string is a valid file path).
- **High-Reliability Requirements:** When you cannot afford unhandled runtime exceptions and need exhaustive error handling.
- **Testing Focus:** When you want to separate data validation tests from business logic tests.

## Architecture Components

### 1. The Spec (`spec.ts`)
The "Contract" or "Port". It defines the *What*. It must contain:
- **Input Schema:** A Zod schema that parses raw input into a valid DTO.
- **Output Schema:** A Zod schema defining the successful data structure.
- **Error Schema:** A discriminated union of specific failure modes (not generic errors).
- **Result Type:** A `DiscriminatedUnion` of `Success | Failure`.
- **Interface:** The capability definition (e.g., `interface ConfigureSpec`).

### 2. The Handler (`handler.ts`)
The "Implementation" or "Adapter". It defines the *How*. It must:
- Implement the Interface defined in the Spec.
- Be an "Impure" class that handles side effects (File System, API calls).
- **NEVER throw** exceptions. It must catch internal errors and map them to the `Result` type.

---

## How to use it

### Step 1: Define the Contract (`spec.ts`)

Follow this template to define the boundaries.

```typescript
import { z } from 'zod';

// 1. VALIDATION HELPERS (Reusable Refinements)
export const SafePathSchema = z.string()
.min(1)
.refine(p => !p.includes('..'), "No traversal allowed");

// 2. INPUT (The Command) - "Parse, don't validate"
export const MyTaskInputSchema = z.object({
path: SafePathSchema,
force: z.boolean().default(false),
});
export type MyTaskInput = z.infer<typeof MyTaskInputSchema>;

// 3. ERROR CODES (Exhaustive)
export const MyTaskErrorCode = z.enum([
'FILE_NOT_FOUND',
'PERMISSION_DENIED',
'UNKNOWN_ERROR'
]);

// 4. RESULT (The Monad)
export const MyTaskSuccess = z.object({
success: z.literal(true),
data: z.string(), // The output payload
});

export const MyTaskFailure = z.object({
success: z.literal(false),
error: z.object({
code: MyTaskErrorCode,
message: z.string(),
suggestion: z.string().optional(),
recoverable: z.boolean(),
})
});

export type MyTaskResult =
| z.infer<typeof MyTaskSuccess>
| z.infer<typeof MyTaskFailure>;

// 5. INTERFACE (The Capability)
export interface MyTaskSpec {
execute(input: MyTaskInput): Promise<MyTaskResult>;
}

```

### Step 2: Implement the Handler (`handler.ts`)

Follow this template to implement the logic.

```typescript
import { MyTaskSpec, MyTaskInput, MyTaskResult } from './spec.js';
import * as fs from 'fs';

export class MyTaskHandler implements MyTaskSpec {
async execute(input: MyTaskInput): Promise<MyTaskResult> {
try {
// 1. Business Logic
if (!fs.existsSync(input.path)) {
// 2. Explicit Error Return (No Throwing)
return {
success: false,
error: {
code: 'FILE_NOT_FOUND',
message: `Path does not exist: ${input.path}`,
recoverable: true
}
};
}

// 3. Success Return
return {
success: true,
data: 'Operation complete'
};

} catch (error) {
// 4. Safety Net: Catch unknown runtime errors
return {
success: false,
error: {
code: 'UNKNOWN_ERROR',
message: error instanceof Error ? error.message : String(error),
recoverable: false
}
};
}
}
}

```

### Step 3: Testing Strategy

Do not write monolithic tests. Split them into **Contract Tests** and **Logic Tests**.

#### A. Contract Tests (Schema)

Test the *Bouncer*. Ensure invalid data is rejected before it reaches the handler.

* **Focus:** Edge cases, validation rules, Zod refinements.
* **Style:** Data-driven (Table tests).

```typescript
// spec.test.ts
import { MyTaskInputSchema } from './spec';

const invalidCases = [
{ val: '../etc/passwd', err: 'No traversal allowed' },
{ val: '', err: 'min(1)' },
];

test.each(invalidCases)('validates paths', ({ val, err }) => {
const result = MyTaskInputSchema.safeParse({ path: val });
expect(result.success).toBe(false);
});

```

#### B. Logic Tests (Handler)

Test the *Chef*. Mock external dependencies (fs, network) and assert the Result Object.

* **Focus:** Business logic flow, error mapping, success states.
* **Style:** Mocked unit tests or Scenario Runners.

```typescript
// handler.test.ts
import { MyTaskHandler } from './handler';
import { vi } from 'vitest'; // or jest

test('returns FILE_NOT_FOUND if path missing', async () => {
// MOCK
vi.mocked(fs.existsSync).mockReturnValue(false);

// EXECUTE
const handler = new MyTaskHandler();
const result = await handler.execute({ path: '/fake' });

// ASSERT (Check the Result Object)
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.code).toBe('FILE_NOT_FOUND');
}
});

```
23 changes: 23 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
push:
branches: ['**']
pull_request:

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- uses: oven-sh/setup-bun@v2
with:
bun-version: latest

- name: Install dependencies
run: bun install

- name: Run tests
run: bun test
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules/
dist/
.env
*.local
bun.lockb
*.tgz
60 changes: 60 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "design-monorepo",
"private": true,
"workspaces": [
"packages/*"
],
"scripts": {
"build": "turbo build",
"test": "turbo test",
"lint": "turbo lint"
},
"devDependencies": {
"turbo": "latest",
"typescript": "latest"
}
}
Loading
Loading