summaryrefslogtreecommitdiff
path: root/docs/proposals/feature-task-templates.md
blob: 98abde9c5df57f0987961c5e80716896b33ae8f1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# Feature Proposal: Reusable Task Templates & Meta-Commands

> **Priority:** Medium
> **Complexity:** Medium
> **Estimated Effort:** 8-12 days
> **Status:** Proposal
> **Date:** 2026-02-09
> **Dependencies:** None (standalone, but complements [Workflow Presets](feature-workflow-presets.md))
> **Related:** [Overview Analysis](compound-engineering-analysis.md) · [Workflow Presets](feature-workflow-presets.md) · [Multi-Agent Review](feature-multi-agent-review.md)

---

## Problem Statement

Makima tasks are created with **ad-hoc plans** every time:

- **No plan reuse** — even when spawning the same type of task (e.g., "add API endpoint"), the plan is written from scratch
- **No standardization** — different supervisors produce different quality plans for the same task type
- **No best practices encoding** — hard-won knowledge about how to structure certain tasks isn't captured
- **No variable substitution** — plans can't be parameterized for reuse
- **No validation** — there's no way to verify a plan includes required steps before execution
- **No meta-creation** — the system cannot create its own task templates or improve its own capabilities

The compound engineering plugin addresses this with meta-commands (`/create-agent-skill`, `/heal-skill`) that allow the system to create and repair its own specialized capabilities.

---

## How Compound Engineering Solves This

### `/create-agent-skill`

Creates new specialized agents and skills on demand:

```bash
/create-agent-skill "database migration reviewer"
```

This generates:
1. An agent definition file with specialized prompts
2. A skill file that exposes the agent as a command
3. Registration in the agent/skill registry

### `/heal-skill`

When a skill breaks (e.g., after a dependency change), this meta-command:
1. Analyzes the error
2. Identifies the root cause
3. Patches the skill definition
4. Tests the fix

The key insight: **the system should be able to improve and extend itself**.

---

## Proposed Makima Implementation

### 1. Task Recipe Format

Task recipes are parameterized plan templates with validation and metadata:

```yaml
# .makima/recipes/api-endpoint.yaml
name: api-endpoint
description: "Create a new REST API endpoint"
version: 1
author: "team"
tags: [api, backend, rest]

# Input variables
variables:
  endpoint_name:
    required: true
    description: "Name of the endpoint (e.g., 'users', 'orders')"
    validation: "^[a-z][a-z0-9-]*$"

  http_method:
    required: true
    description: "HTTP method"
    enum: [GET, POST, PUT, PATCH, DELETE]
    default: GET

  resource_name:
    required: true
    description: "Name of the resource/model"

  requires_auth:
    required: false
    default: true
    description: "Whether the endpoint requires authentication"

  database_table:
    required: false
    description: "Database table name (if applicable)"

# Plan template with variable substitution
plan: |
  ## Task: Create {{ http_method }} /api/{{ endpoint_name }} Endpoint

  ### Step 1: Define Route
  Add the `{{ http_method }} /api/{{ endpoint_name }}` route to the router.
  {% if requires_auth %}
  Apply authentication middleware to this route.
  {% endif %}

  ### Step 2: Create Handler
  Create the handler function for {{ endpoint_name }}.
  {% if database_table %}
  The handler should query the `{{ database_table }}` table.
  {% endif %}

  ### Step 3: Request/Response Models
  Define request and response types for the {{ resource_name }} resource.
  Include validation for all input fields.

  ### Step 4: Error Handling
  Implement proper error responses:
  - 400 for validation errors
  - 401 for authentication failures
  {% if requires_auth %}
  - 403 for authorization failures
  {% endif %}
  - 404 for not found
  - 500 for server errors

  ### Step 5: Tests
  Write tests covering:
  - Happy path
  - Input validation
  {% if requires_auth %}
  - Authentication required
  - Authorization check
  {% endif %}
  - Error cases
  - Edge cases

  ### Step 6: Documentation
  Update API documentation with:
  - Endpoint URL and method
  - Request/response schemas
  - Example requests and responses
  - Error codes

# Validation rules — checks that must pass before execution
validation:
  - check: "file_exists"
    path: "src/api/mod.rs"
    message: "API module must exist"
  - check: "grep"
    pattern: "Router"
    path: "src/api/mod.rs"
    message: "Router must be defined in API module"

# Expected outputs
outputs:
  files:
    - "src/api/{{ endpoint_name }}.rs"
    - "src/api/{{ endpoint_name }}_test.rs"
  tests:
    - "cargo test {{ endpoint_name }}"

# Metadata for recipe discovery
metadata:
  estimated_time: "30-60 minutes"
  difficulty: "easy"
  example_usage: |
    makima recipe run api-endpoint \
      --var endpoint_name=users \
      --var http_method=GET \
      --var resource_name=User \
      --var database_table=users
```

### 2. Recipe Registry

Recipes are discovered from three sources (same hierarchy as workflow presets):

| Level | Location | Scope |
|-------|----------|-------|
| Built-in | Shipped with makima | All users |
| Repository | `.makima/recipes/` | All users of the repo |
| User | `~/.makima/recipes/` | Single user |

**Precedence**: User > Repository > Built-in (same name overrides)

### 3. Supervisor Commands

#### List Available Recipes

```bash
makima recipe list

# Output:
# NAME              DESCRIPTION                          SOURCE     TAGS
# api-endpoint      Create a new REST API endpoint        built-in   api, backend
# db-migration      Create a database migration           built-in   database
# react-component   Create a React component              built-in   frontend, react
# unit-test         Create unit tests for a module        built-in   testing
# bug-fix           Structured bug fix workflow            built-in   debugging
# custom-validator  Create input validation module         repo       validation
```

#### Run a Recipe

```bash
# Run with explicit variables
makima recipe run api-endpoint \
  --var endpoint_name=users \
  --var http_method=GET \
  --var resource_name=User \
  --var database_table=users

# Run with interactive variable input
makima recipe run api-endpoint

# Preview the generated plan (dry run)
makima recipe preview api-endpoint \
  --var endpoint_name=users \
  --var http_method=GET
```

#### Create a Recipe

```bash
# Create recipe from scratch
makima recipe create --name "my-recipe" --edit

# Generate recipe from a completed task (meta-creation)
makima recipe create --from-task <task-id> --name "my-recipe"

# Generate recipe from a plan file
makima recipe create --from-plan plan.md --name "my-recipe"
```

#### Validate a Recipe

```bash
# Validate recipe file
makima recipe validate .makima/recipes/my-recipe.yaml

# Validate recipe variables
makima recipe validate api-endpoint \
  --var endpoint_name=users \
  --var http_method=GET
```

### 4. Meta-Commands: Self-Improving Templates

The most powerful aspect of the compound engineering plugin is its ability to **create its own capabilities**. Makima can implement similar meta-commands:

#### `makima recipe generate`

The system analyzes completed tasks and suggests recipe templates:

```bash
# Analyze recent tasks and suggest recipes
makima recipe generate --analyze-last 20

# Output:
# Detected patterns:
# 1. "API endpoint creation" — 7 tasks followed similar pattern
#    Suggested recipe: api-endpoint (confidence: 0.89)
#    Variables: endpoint_name, http_method, resource_name
#
# 2. "Database migration" — 4 tasks followed similar pattern
#    Suggested recipe: db-migration (confidence: 0.76)
#    Variables: table_name, migration_type
#
# Generate these recipes? [y/N]
```

#### `makima recipe heal`

When a recipe fails repeatedly, the system can analyze and fix it:

```bash
# Analyze recipe failures and suggest fixes
makima recipe heal api-endpoint

# Output:
# Analyzed 3 recent failures of 'api-endpoint':
# Root cause: Step 1 references 'src/api/mod.rs' but project uses 'src/routes/mod.rs'
# Suggested fix: Change validation path and plan references
# Apply fix? [y/N]
```

#### `makima recipe evolve`

Improve recipes based on review findings:

```bash
# Check if review findings suggest recipe improvements
makima recipe evolve api-endpoint --from-findings

# Output:
# Review findings from tasks using 'api-endpoint' recipe:
# - SEC-001: "Missing rate limiting" (3 occurrences)
# - PERF-001: "Missing pagination" (2 occurrences)
#
# Suggested additions to recipe:
# 1. Add "Rate Limiting" step after Step 1
# 2. Add pagination to Step 2 for GET endpoints
# Apply improvements? [y/N]
```

### 5. Built-In Recipes

#### `api-endpoint`

Creates a REST API endpoint with handler, models, validation, tests, and docs.

#### `db-migration`

Creates a database migration with up/down scripts, validation, and rollback plan.

```yaml
name: db-migration
variables:
  table_name: { required: true }
  migration_type: { required: true, enum: [create-table, alter-table, add-index, seed-data] }
plan: |
  ## Create Database Migration: {{ migration_type }} on {{ table_name }}
  ### Step 1: Create migration file
  ### Step 2: Write up migration
  ### Step 3: Write down migration (rollback)
  ### Step 4: Test migration on clean database
  ### Step 5: Test rollback
  ### Step 6: Document migration in changelog
```

#### `react-component`

Creates a React component with props, state, styling, and tests.

#### `unit-test`

Generates unit tests for an existing module by analyzing its public API.

#### `bug-fix`

Structured bug fix workflow: reproduce → root cause → fix → test → document.

```yaml
name: bug-fix
variables:
  bug_description: { required: true }
  reproduction_steps: { required: false }
  affected_area: { required: false }
plan: |
  ## Bug Fix: {{ bug_description }}

  ### Step 1: Reproduce
  {% if reproduction_steps %}
  Follow these reproduction steps: {{ reproduction_steps }}
  {% else %}
  Identify and document reproduction steps.
  {% endif %}

  ### Step 2: Root Cause Analysis
  Trace the code path to identify the root cause.
  {% if affected_area %}
  Start in: {{ affected_area }}
  {% endif %}

  ### Step 3: Implement Fix
  Fix the root cause, not just the symptom.

  ### Step 4: Write Regression Test
  Create a test that would have caught this bug.

  ### Step 5: Verify Fix
  Run the reproduction steps and confirm the bug is fixed.
  Run the full test suite to check for regressions.

  ### Step 6: Document
  Document what caused the bug and how it was fixed.
```

---

## Integration with Existing Makima Features

### Supervisor Task Spawning

Recipes generate plans that are passed to `spawn-task`:

```rust
// Recipe execution
let plan = recipe.render_plan(&variables)?;
let task = spawn_task(SpawnTaskRequest {
    task_name: format!("{} ({})", recipe.name, variables.get("primary_var")),
    plan,
    // ... other params from context
})?;
```

### Contract Files

Recipe definitions can be stored as contract files for versioning:

```rust
File {
    contract_id: None, // Global, not contract-specific
    name: "Recipe: api-endpoint",
    body: vec![
        BodyElement::Code { language: Some("yaml"), content: recipe_yaml },
    ],
}
```

### Workflow Presets

Recipes and presets are complementary:
- **Presets** define the high-level workflow (which phases, what triggers)
- **Recipes** define the low-level task plans (what each task does)

A preset can reference recipes:

```yaml
# In a preset
phases:
  execute:
    recipe: api-endpoint    # Use the api-endpoint recipe for this phase's tasks
    recipe_vars:
      endpoint_name: "{{ task_description }}"
```

### Knowledge Accumulation

Recipes can be **evolved** based on learnings:
- When compound learning captures a pattern, check if it maps to an existing recipe
- If so, suggest recipe improvements
- If not, suggest creating a new recipe

### Directive System

For directive-based workflows, recipes can be used as task plan sources:

```rust
DirectiveStep {
    name: "create-users-endpoint",
    task_plan: recipe.render_plan(&variables)?,  // Generated from recipe
    // ...
}
```

---

## Implementation Plan

### Phase 1: Core Recipe System (3-4 days)

| Task | Effort | Description |
|------|--------|-------------|
| Recipe YAML schema | 0.5 days | Define format, validation rules |
| YAML parser with Jinja-like templating | 1 day | Variable substitution, conditionals |
| `recipe list` command | 0.5 days | Discover and list recipes |
| `recipe run` command | 1 day | Parse, validate, render, spawn task |
| `recipe preview` command | 0.5 days | Dry-run display |

### Phase 2: Recipe Management (2-3 days)

| Task | Effort | Description |
|------|--------|-------------|
| Multi-level discovery | 0.5 days | Built-in, repo, user resolution |
| `recipe create` command | 1 day | Create from scratch or from task |
| `recipe validate` command | 0.5 days | YAML validation, variable check |
| Built-in recipe definitions | 1 day | Write 5 default recipes |

### Phase 3: Meta-Commands (3-5 days)

| Task | Effort | Description |
|------|--------|-------------|
| `recipe generate` | 1.5 days | Pattern detection from task history |
| `recipe heal` | 1 day | Failure analysis and auto-fix |
| `recipe evolve` | 1 day | Improve recipes from findings/learnings |
| Recipe versioning | 0.5 days | Version tracking, deprecation |
| Documentation | 0.5 days | User guide, recipe authoring guide |

---

## Configuration Examples

### Running a Recipe

```bash
# Simple usage
makima recipe run api-endpoint \
  --var endpoint_name=orders \
  --var http_method=POST \
  --var resource_name=Order \
  --var requires_auth=true \
  --var database_table=orders

# This spawns a task with the rendered plan:
# "## Task: Create POST /api/orders Endpoint
#  ### Step 1: Define Route
#  Add the POST /api/orders route to the router.
#  Apply authentication middleware to this route.
#  ..."
```

### Creating a Recipe from a Completed Task

```bash
# After completing a successful task
makima recipe create --from-task abc-123 --name "graphql-resolver"

# Analyzes the task's plan and execution to generate:
# .makima/recipes/graphql-resolver.yaml
# with variables extracted from repeated patterns
```

### Recipe with Validation

```yaml
# .makima/recipes/react-component.yaml
name: react-component
variables:
  component_name:
    required: true
    validation: "^[A-Z][a-zA-Z]*$"  # PascalCase
  use_typescript:
    required: false
    default: true
  include_tests:
    required: false
    default: true
  styling:
    required: false
    enum: [css-modules, styled-components, tailwind]
    default: css-modules

validation:
  - check: "file_exists"
    path: "src/components"
    message: "Components directory must exist"
  - check: "not_exists"
    path: "src/components/{{ component_name }}"
    message: "Component {{ component_name }} already exists"

plan: |
  ## Create React Component: {{ component_name }}

  ### Step 1: Component File
  Create `src/components/{{ component_name }}/{{ component_name }}.{{ 'tsx' if use_typescript else 'jsx' }}`
  with the component skeleton.

  ### Step 2: Styling
  {% if styling == 'css-modules' %}
  Create `{{ component_name }}.module.css` with base styles.
  {% elif styling == 'styled-components' %}
  Create styled components in the component file.
  {% elif styling == 'tailwind' %}
  Use Tailwind CSS classes directly in the component.
  {% endif %}

  {% if include_tests %}
  ### Step 3: Tests
  Create `{{ component_name }}.test.{{ 'tsx' if use_typescript else 'jsx' }}`
  with tests for rendering, props, and user interactions.
  {% endif %}

  ### Step {{ '4' if include_tests else '3' }}: Export
  Add {{ component_name }} to the components index file.

outputs:
  files:
    - "src/components/{{ component_name }}/{{ component_name }}.{{ 'tsx' if use_typescript else 'jsx' }}"
    - "src/components/{{ component_name }}/index.{{ 'ts' if use_typescript else 'js' }}"
```

---

## Open Questions

1. **Templating language**: Should we use a full Jinja2-like syntax or a simpler `{{ variable }}` substitution? Jinja adds power but complexity.
2. **Recipe dependencies**: Can recipes depend on other recipes? (e.g., "api-endpoint requires db-migration to have run first")
3. **Recipe testing**: How do you test that a recipe produces valid plans? Should recipes have test cases?
4. **Recipe marketplace**: Should there be a community registry for sharing recipes?
5. **Pattern detection**: How sophisticated should `recipe generate` be? Simple plan comparison, or full semantic analysis?
6. **Recipe scope**: Should recipes generate just plans, or also pre-create file scaffolding (like code generators)?
7. **Backwards compatibility**: When a recipe is updated, what happens to tasks that were created with the old version?

---

## Alternatives Considered

| Alternative | Pros | Cons | Decision |
|-------------|------|------|----------|
| Plan library (copy-paste) | Simple | No variables, no validation | Rejected — not reusable enough |
| Code generators (scaffolding) | Creates actual files | Over-prescriptive; doesn't handle logic | Complement — recipes can reference generators |
| LLM-only planning | Maximum flexibility | Inconsistent; no standardization | Current state — recipes improve on this |
| Cookiecutter-style templates | Familiar | Wrong level (project-level vs task-level) | Rejected — different abstraction |
| Hardcoded task types | Fast | Not extensible; limited variety | Rejected — need flexibility |

---

## Priority & Complexity Assessment

- **Priority: MEDIUM** — Task templates improve consistency and speed but aren't required for makima to function. They become increasingly valuable as the system is used more (patterns emerge).
- **Complexity: MEDIUM** — YAML parsing and variable substitution are straightforward. Meta-commands (generate, heal, evolve) require sophisticated analysis of task history and are the main complexity drivers.
- **Risk: LOW-MEDIUM** — Core recipe system is low risk. Meta-commands (auto-generation, healing) involve AI-driven analysis that may produce variable quality. Mitigated by requiring human approval before applying changes.