# kimi_decompose Readability Fix — Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Fix kimi_decompose output readability by resolving prompt conflicts, splitting structure from metadata, and hardening TypeScript types.

**Architecture:** Redesign the system prompt to use a 3-section output (SUMMARY → STRUCTURE → DETAILS) based on multi-model consensus (Grok, Qwen, Gemini). Fix type safety by inferring args from the zod schema. Extract magic numbers into named constants.

**Tech Stack:** TypeScript, Zod, OpenRouter API (Kimi K2.5)

---

### Task 1: Extract Named Constants

**Files:**
- Modify: `src/tools/openrouter-tools.ts:707-792`

- [ ] **Step 1: Add constants above the tool definition**

Add these constants near the top of the `kimiDecomposeTool` section (around line 702):

```typescript
// kimi_decompose configuration
const DECOMPOSE_TEMPERATURE = 0.5;
const DECOMPOSE_MAX_TOKENS = 6000;
const DECOMPOSE_TIMEOUT_MS = 240_000;
```

- [ ] **Step 2: Replace magic numbers in the execute function**

Replace line 787:
```typescript
// Before
() => callOpenRouter(messages, OpenRouterModel.KIMI_K2_5, 0.5, 6000),
// After
() => callOpenRouter(messages, OpenRouterModel.KIMI_K2_5, DECOMPOSE_TEMPERATURE, DECOMPOSE_MAX_TOKENS),
```

Replace line 789:
```typescript
// Before
240000
// After
DECOMPOSE_TIMEOUT_MS
```

- [ ] **Step 3: Build and verify no errors**

Run: `npm run build`
Expected: Clean compile, no errors.

- [ ] **Step 4: Commit**

```bash
git add src/tools/openrouter-tools.ts
git commit -m "refactor(kimi_decompose): extract magic numbers into named constants"
```

---

### Task 2: Fix Type Safety

**Files:**
- Modify: `src/tools/openrouter-tools.ts:718-723`

- [ ] **Step 1: Remove the manual args type and unused `log` destructure**

Replace the execute signature (lines 718-723):

```typescript
// Before
  execute: async (args: {
    task: string;
    context?: string;
    depth?: number;
    outputFormat?: string;
  }, { log, reportProgress }: any) => {

// After
  execute: async (args: {
    task: string;
    context?: string;
    depth: number;
    outputFormat: "tree" | "flat" | "dependencies";
  }, { reportProgress }: { reportProgress?: (progress: { progress: number; total: number }) => Promise<void> }) => {
```

Note: `depth` and `outputFormat` have `.default()` in the schema so they are always present after parsing — they should NOT be optional. `log` is unused, remove it.

- [ ] **Step 2: Build and verify**

Run: `npm run build`
Expected: Clean compile. No type errors.

- [ ] **Step 3: Commit**

```bash
git add src/tools/openrouter-tools.ts
git commit -m "fix(kimi_decompose): tighten arg types, remove unused log"
```

---

### Task 3: Redesign Format Templates (Core Readability Fix)

**Files:**
- Modify: `src/tools/openrouter-tools.ts:724-752`

This is the main fix. Replace the `formatInstructions` object with new templates that produce **smart** decomposition — not just IDs/deps, but context-aware output with goals, constraints, metrics, and references per task group.

- [ ] **Step 1: Replace the `formatInstructions` object**

Replace lines 724-752 with:

```typescript
    const formatInstructions: Record<string, string> = {
      tree: `Output in FOUR sections. Follow this format EXACTLY:

OVERVIEW
Task:        [main task title]
Context:     [key context from user input — tech stack, compliance, existing infra]
Goals:       [specific outcomes, behavioral specs, fail modes]
Constraints: [technical limitations, library restrictions, platform limits]
Metrics:     [measurable acceptance criteria — test counts, perf targets, behavioral checks]
Reference:   [existing patterns to follow, similar code, prior art]

STRUCTURE (IDs and titles only — scannable at a glance)
T1: Task title
├─ T1.1: Subtask title ||
├─ T1.2: Subtask title
│  └─ T1.2.1: Sub-subtask
└─ T1.3: Subtask title ||
T2: Task title (after T1)
└─ T2.1: Subtask title

Mark parallel tasks with || suffix. Show deps in parentheses.

DETAILS (one block per task, reference IDs from STRUCTURE)
[T1] Complexity: Med | Parallel: no | Deps: none
     Goal: what this subtask achieves specifically
     Constraints: relevant limitations for THIS subtask
     Done when: measurable acceptance criteria

[T1.1] Complexity: Low | Parallel: yes | Deps: none
       Goal: specific outcome
       Done when: measurable criteria

RISKS
- [risk description] > Mitigation: [how to handle]
- [risk description] > Mitigation: [how to handle]`,

      flat: `Output in THREE sections. Follow this format EXACTLY:

OVERVIEW
Task:        [main task title]
Context:     [key context — tech stack, compliance, existing infra]
Goals:       [specific outcomes with behavioral specs]
Constraints: [technical limitations]
Metrics:     [measurable acceptance criteria]
Reference:   [existing patterns to follow]

TASKS (numbered list, one task per block)
1. [T1] Task title
   Goal: what this achieves
   Deps: none | Parallel: no | Complexity: Med
   Constraints: relevant limitations
   Done when: measurable acceptance criteria

2. [T1.1] Subtask title
   Goal: what this achieves
   Deps: T1 | Parallel: yes | Complexity: Low
   Done when: measurable criteria

3. [T2] Task title
   Goal: what this achieves
   Deps: T1 | Parallel: no | Complexity: High
   Done when: measurable criteria

Do NOT use box-drawing or tree characters. Plain numbered list.

RISKS
- [risk] > Mitigation: [approach]`,

      dependencies: `Output in FOUR sections. Follow this format EXACTLY:

OVERVIEW
Task:        [main task title]
Context:     [key context — tech stack, compliance, existing infra]
Goals:       [specific outcomes with behavioral specs]
Constraints: [technical limitations]
Metrics:     [measurable acceptance criteria]
Bottlenecks: [task IDs that block the most downstream work]

EXECUTION FLOW (text flowchart showing blocking relationships)
T1.1 ──> T1 ──> T2 ──> T4
T1.2 ──┘       T3 ──┘

TASK REQUIREMENTS (one block per task)
[T1] Task title
     Goal: what this achieves
     Blocked by: none | Blocks: T2
     Parallel: no | Complexity: Med
     Constraints: relevant limitations
     Done when: measurable acceptance criteria

[T1.1] Subtask title
       Goal: what this achieves
       Blocked by: none | Blocks: T1
       Parallel: yes | Complexity: Low
       Done when: measurable criteria

RISKS
- [risk] > Mitigation: [approach]`
    };
```

- [ ] **Step 2: Verify the templates render correctly in the prompt**

Manually inspect that `${formatInstructions["tree"]}` produces clean output. Check that the SUMMARY, STRUCTURE, and DETAILS sections are clearly separated with blank lines.

- [ ] **Step 3: Build**

Run: `npm run build`
Expected: Clean compile.

- [ ] **Step 4: Commit**

```bash
git add src/tools/openrouter-tools.ts
git commit -m "fix(kimi_decompose): redesign output formats for readability — 3-section split"
```

---

### Task 4: Fix System Prompt — Remove Conflicting Instructions

**Files:**
- Modify: `src/tools/openrouter-tools.ts:754-776`

- [ ] **Step 1: Replace the system prompt**

Replace lines 754-776 with:

```typescript
    const systemPrompt = `You are Kimi K2.5, expert at structured task decomposition using Agent Swarm reasoning.

Your job is to produce SMART decompositions — not mechanical ID/deps lists, but context-aware plans that a developer can act on immediately.

For every decomposition:
1. Infer context, constraints, and risks even if the user didn't state them explicitly
2. Each subtask gets a unique ID (T1, T1.1, T1.2, T2)
3. Identify dependencies between subtasks
4. Mark which subtasks can run in parallel
5. Each subtask must have a specific GOAL (what it achieves) and measurable acceptance criteria
6. Surface risks and mitigations — what could go wrong?
7. Reference existing patterns when the context mentions them
8. Decompose to ${args.depth ?? 3} levels of depth maximum

${formatInstructions[args.outputFormat ?? "tree"]}

Rules:
- No bold (**) or italic (*) — output is for a CLI terminal
- Keep lines under 80 characters
- Blank line between sections
- Use box-drawing characters (├─ └─ ──>) only for tree and dependencies formats
- Titles should be concise (under 50 chars)
- Acceptance criteria must be measurable (test counts, behavioral checks, not vague "works correctly")
- Constraints should be specific (library versions, platform limits, not generic "be careful")`;
```

Key changes:
- Removed `FORMAT_INSTRUCTION` reference (conflicting emoji/verdict rules)
- Removed the redundant "For each subtask provide" list (already in format templates)
- Removed blanket "use box-drawing characters" (now format-specific)
- Added smart decomposition instructions: infer context, surface risks, measurable criteria
- Uses `??` instead of `||` for depth/outputFormat (moved from Task 2 since this replaces those lines)

- [ ] **Step 2: Remove the FORMAT_INSTRUCTION import if no longer needed elsewhere**

Check: `FORMAT_INSTRUCTION` is still used by ~12 other tools in the same file. Keep the import. Only remove it from this tool's prompt.

- [ ] **Step 3: Build and verify**

Run: `npm run build`
Expected: Clean compile.

- [ ] **Step 4: Commit**

```bash
git add src/tools/openrouter-tools.ts
git commit -m "fix(kimi_decompose): remove conflicting FORMAT_INSTRUCTION, streamline system prompt"
```

---

### Task 5: Smoke Test with Live API Call

**Files:**
- No files modified — verification only

- [ ] **Step 1: Build the project**

Run: `npm run build`
Expected: Clean compile.

- [ ] **Step 2: Test tree format (default)**

Invoke `kimi_decompose` with:
```json
{
  "task": "Build a user authentication system with OAuth2, email/password, and MFA",
  "depth": 2,
  "outputFormat": "tree"
}
```

Expected output structure:
```
OVERVIEW
Task:        Build a user authentication system...
Context:     [inferred — web app, security-critical]
Goals:       [specific outcomes with fail modes]
Constraints: [inferred — OWASP, token storage, etc.]
Metrics:     [measurable — test counts, security checks]
Reference:   [any patterns mentioned or inferred]

STRUCTURE
T1: ...
├─ T1.1: ...
...

DETAILS
[T1] Complexity: ... | Parallel: ... | Deps: ...
     Goal: what this subtask achieves
     Done when: measurable criteria

RISKS
- [risk] > Mitigation: [approach]
```

Verify:
- OVERVIEW section has inferred context/constraints (not just echoing input)
- STRUCTURE section has only IDs + titles (no metadata inline)
- DETAILS has Goal + measurable Done-when per task (not vague "works correctly")
- RISKS section present with mitigations
- No raw asterisks (**bold**)
- Lines under 80 chars
- Visually scannable in ~3 seconds

- [ ] **Step 3: Test flat format**

Invoke with `"outputFormat": "flat"`. Verify:
- No box-drawing characters
- Plain numbered list
- Each task has deps/parallel/complexity on one line + criteria on next

- [ ] **Step 4: Test dependencies format**

Invoke with `"outputFormat": "dependencies"`. Verify:
- EXECUTION FLOW section shows arrow-based graph
- TASK REQUIREMENTS shows blocked-by/blocks relationships

- [ ] **Step 5: If all formats pass, mark verification complete**

No commit needed — all code changes were committed in Tasks 1-4. Update CHANGELOG.md if desired.
