# Goal-Oriented Checkpoints 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:** Make planner_maker/planner_runner checkpoints verify goal alignment ("are we building the right thing?") instead of just progress ("did step 3 get done?"), using GPT + Gemini as dual judges.

**Architecture:** Add `goal` parameter to planner_maker that gets saved in plan file frontmatter. planner_runner reads the goal from the plan and checks against it at every checkpoint (50%, 80%, 100%). Each checkpoint returns a `nextTool` coordinator instruction (GPT first judge, Gemini final judge) instead of just text prompts. The runner switches from advisory text to the same coordinator pattern used by planner_maker.

**Tech Stack:** TypeScript, zod, MCP coordinator pattern

---

## File Structure

| File | Responsibility | Action |
|------|---------------|--------|
| `src/tools/planner-tools.ts` | All planner logic | Modify (lines 953-994, 1351-1642) |
| `skills/blueprint/SKILL.md` | Blueprint skill docs | Modify (add goal param, wire runner) |

This is a single-file change (planner-tools.ts) plus a skill doc update. The file is large (~1650 lines) but changes are isolated to the `plannerMakerTool` parameter schema, `savePlanToFile` frontmatter, and `plannerRunnerTool` verify mode.

---

### Task 1: Add `goal` parameter to planner_maker

**Files:**
- Modify: `src/tools/planner-tools.ts:974-994` (parameter schema)
- Modify: `src/tools/planner-tools.ts:996-1010` (execute function signature)
- Modify: `src/tools/planner-tools.ts:1054-1062` (savePlanToFile call — pass goal to frontmatter)

- [ ] **Step 1: Add `goal` to the zod parameter schema**

In `src/tools/planner-tools.ts`, inside `plannerMakerTool.parameters` (line 974), add after the `task` parameter:

```typescript
    goal: z.string().optional().describe("Success criteria for this plan — what must be true when done. Checked at every checkpoint. Example: 'GDPR compliant, fail-closed, admin-only toggle'"),
```

- [ ] **Step 2: Add `goal` to execute function signature**

In the `execute` function args type (line 996-1009), add:

```typescript
    goal?: string;
```

And in the destructuring (line 1010), add:

```typescript
    const { task, codeContext = "", answers = "", mode = "start", devlog = true } = args;
    const goal = args.goal || "";  // Add this line
```

- [ ] **Step 3: Embed goal in plan file frontmatter**

In the `savePlanToFile` function (line 224-283), add `goal` to the `PlanMetadata` interface (line 210):

```typescript
interface PlanMetadata {
  phases: string[];
  tools_used: string[];
  scores?: Record<string, number>;
  goal?: string;  // Add this
}
```

In the frontmatter generation (after line 250), add:

```typescript
  if (metadata.goal) {
    lines.push(`planGoal: "${metadata.goal.replace(/"/g, '\\"')}"`);
  }
```

- [ ] **Step 4: Pass goal through to ALL THREE savePlanToFile calls**

There are 3 call sites — all need `goal` added to the metadata object:

**Call 1 — Initial save (line 1058, `mode === "start"`):**
```typescript
        const filepath = savePlanToFile(task, initialBody, {
          phases: workflow.map(s => s.phase),
          tools_used: [],
          goal,  // Add this
        }, { planStatus: "in-progress" });
```

**Call 2 — Incremental save (line 1084, `mode === "continue"`):**
```typescript
            const filepath = savePlanToFile(task, incrementalBody, {
              phases: workflow.map(s => s.phase),
              tools_used: completedTools,
              goal,  // Add this
            }, { planStatus: "in-progress", existingFilepath: existingPath });
```

**Call 3 — Final save (line 1157, completion block):**
```typescript
        savedPath = savePlanToFile(task, planBody, {
          phases: workflow.map(s => s.phase),
          tools_used: workflow.map(s => s.tool),
          scores: Object.keys(scores).length > 0 ? scores : undefined,
          goal,  // Add this
        }, { planStatus: "pending", existingFilepath: existingPath });
```

- [ ] **Step 5: Include goal in final plan output**

In the `buildIncrementalPlan` or final result assembly (around line 1098-1198), prepend the goal to the plan body when it exists:

```typescript
    // At the top of the final plan text, before the executive summary
    if (goal) {
      finalPlan = `## 🎯 Goal\n\n> ${goal}\n\n---\n\n${finalPlan}`;
    }
```

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

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

- [ ] **Step 7: Commit**

```bash
git add src/tools/planner-tools.ts
git commit -m "feat(planner): add goal parameter to planner_maker for checkpoint alignment"
```

---

### Task 2: Add `goal` parameter to planner_runner and parse from plan

**Files:**
- Modify: `src/tools/planner-tools.ts:1364-1390` (runner parameter schema + execute signature)

- [ ] **Step 1: Add `goal` to runner parameter schema**

In `plannerRunnerTool.parameters` (line 1364), add:

```typescript
    goal: z.string().optional().describe("Success criteria — extracted from plan frontmatter or provided manually. Verified at every checkpoint."),
```

- [ ] **Step 2: Add goal extraction from plan frontmatter**

Add a helper function before `plannerRunnerTool` (around line 1350):

```typescript
/**
 * Extract goal from plan frontmatter (planGoal field)
 */
function extractGoalFromPlan(plan: string): string | undefined {
  const match = plan.match(/planGoal:\s*"([^"]+)"/);
  if (match) return match[1];
  // Also try the ## Goal section
  const goalSection = plan.match(/##\s*🎯\s*Goal\s*\n+>\s*(.+)/);
  if (goalSection) return goalSection[1].trim();
  return undefined;
}
```

- [ ] **Step 3: Use goal in execute function**

In the execute destructuring (line 1390), add goal resolution:

```typescript
    const { plan, mode = "start", stepNum, checkpoint, code, completed = [], devlog = true, ux = false, responsive = false } = args;
    const goal = args.goal || extractGoalFromPlan(plan) || "";  // Add this
```

- [ ] **Step 4: Show goal in start mode**

In `mode === "start"` (after line 1401), add:

```typescript
      if (goal) {
        lines.push(`**🎯 Goal:** ${goal}`);
        lines.push("");
      }
```

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

Run: `npm run build`
Expected: Clean build

- [ ] **Step 6: Commit**

```bash
git add src/tools/planner-tools.ts
git commit -m "feat(planner): add goal param to planner_runner with frontmatter extraction"
```

---

### Task 3: Convert checkpoint verification from advisory text to coordinator response

This is the core change. Instead of generating text that says "Run qwen_reason with this prompt", the runner returns a `nextTool` instruction like planner_maker does — GPT as first judge, Gemini as final judge.

**Files:**
- Modify: `src/tools/planner-tools.ts:1496-1638` (verify mode)

- [ ] **Step 1: Refactor the verify mode to return structured JSON**

Replace the entire `mode === "verify"` block (lines 1496-1638) with a coordinator-style response. The key changes:

1. **50% checkpoint** — returns `openai_reason` as nextTool (GPT first judge) with goal-alignment prompt
2. **80% checkpoint** — returns `kimi_decompose` as nextTool (keep existing decomposition) BUT adds goal alignment check in the prompt
3. **100% checkpoint** — returns `gemini_analyze_text` as nextTool (Gemini final judge) with goal-alignment scoring

```typescript
    } else if (mode === "verify" && checkpoint) {
      // ═══════════════════════════════════════════════════════════════
      // VERIFY: Goal-oriented checkpoint with dual-judge verification
      // ═══════════════════════════════════════════════════════════════
      const completedSteps = steps.filter((_, i) => completed.includes(i + 1));
      const remainingSteps = steps.filter((_, i) => !completed.includes(i + 1));

      lines.push(`## 🔍 ${checkpoint} Checkpoint Verification`);
      lines.push("");
      lines.push(`Progress: ${completed.length}/${totalSteps} steps complete`);
      if (goal) {
        lines.push(`**🎯 Goal:** ${goal}`);
      }
      lines.push("");

      // What's done
      if (completedSteps.length > 0) {
        lines.push("✅ Completed:");
        for (const step of completedSteps) {
          lines.push(`- ${step.title}`);
        }
        lines.push("");
      }

      // What's left (for 50% and 80%)
      if ((checkpoint === "50%" || checkpoint === "80%") && remainingSteps.length > 0) {
        lines.push("⏳ Remaining:");
        for (const step of remainingSteps) {
          lines.push(`- ${step.title}`);
        }
        lines.push("");
      }

      // Build goal-alignment prompt section
      const goalPrompt = goal
        ? `\n\nGOAL ALIGNMENT CHECK:\nThe stated goal is: "${goal}"\n- Does current progress serve this goal?\n- Is there any drift from the goal?\n- Are remaining steps still aligned with the goal?\n- Flag any steps that might CONTRADICT the goal.`
        : "";

      // ═══════════════════════════════════════════════════════════════
      // CHECKPOINT-SPECIFIC VERIFICATION TOOLS
      // ═══════════════════════════════════════════════════════════════

      if (checkpoint === "50%") {
        // GPT first judge — progress + goal alignment
        const verifyPrompt = `50% CHECKPOINT — Progress & Goal Alignment Review

COMPLETED STEPS:
${completedSteps.map((s, i) => `${i + 1}. ${s.title}`).join('\n')}

REMAINING STEPS:
${remainingSteps.map((s, i) => `${i + 1}. ${s.title}`).join('\n')}
${goalPrompt}
${code ? `\nCODE SNAPSHOT:\n${code.substring(0, 1500)}` : ""}

RESPOND WITH:
1. Progress assessment — are completed steps implemented correctly?
2. Goal alignment — does current work serve the stated goal? Any drift?
3. Remaining plan — should we adjust remaining steps to better serve the goal?
4. Verdict: ON_TRACK or DRIFTING (with explanation)`;

        lines.push("### 🧠 GPT First Judge");
        lines.push("");
        lines.push("Execute this verification tool:");
        lines.push("");
        lines.push("```json");
        lines.push(JSON.stringify({
          tool: "openai_reason",
          params: {
            task: verifyPrompt,
            reasoning_effort: "high",
          },
        }, null, 2));
        lines.push("```");
        lines.push("");
        lines.push("After GPT judge, continue to next step or adjust plan based on verdict.");

      } else if (checkpoint === "80%") {
        // Kimi decompose remaining work — with goal context
        const decomposeContext = `Remaining steps:\n${remainingSteps.map((s, i) => `${i + 1}. ${s.title}${s.details ? ': ' + s.details.substring(0, 100) : ''}`).join('\n')}\n\nCompleted: ${completedSteps.map(s => s.title).join(', ')}${goal ? `\n\nGOAL: ${goal}\nEnsure all remaining subtasks serve this goal. Flag any that don't.` : ""}`;

        lines.push("### 🔬 Kimi Decompose + Goal Check");
        lines.push("");
        lines.push("Execute this decomposition tool:");
        lines.push("");
        lines.push("```json");
        lines.push(JSON.stringify({
          tool: "kimi_decompose",
          params: {
            task: "Complete remaining implementation steps — verify each subtask serves the stated goal",
            context: decomposeContext,
            depth: 3,
            outputFormat: "dependencies",
          },
        }, null, 2));
        lines.push("```");
        lines.push("");
        lines.push("Review subtasks for goal alignment, then continue.");

      } else {
        // 100% — Gemini final judge with goal-alignment scoring
        const finalPrompt = `100% FINAL REVIEW — Quality + Goal Alignment

ALL STEPS:
${steps.map((s, i) => `${i + 1}. ${s.title} ${completed.includes(i + 1) ? '✅' : '❌'}`).join('\n')}
${goalPrompt}
${code ? `\nFINAL CODE:\n${code.substring(0, 2000)}` : ""}

SCORE EACH /10:
1. Quality — code correctness, error handling
2. Completeness — all steps done, no gaps
3. Goal alignment — does the implementation serve "${goal || 'the stated task'}"?
4. Security — no vulnerabilities introduced
5. Performance — no obvious bottlenecks

VERDICT: APPROVED or NEEDS_REVISION
If NEEDS_REVISION, list specific items to fix.`;

        lines.push("### 🏛️ Gemini Final Judge");
        lines.push("");
        lines.push("Execute this final verification tool:");
        lines.push("");
        lines.push("```json");
        lines.push(JSON.stringify({
          tool: "gemini_analyze_text",
          params: {
            text: finalPrompt,
          },
        }, null, 2));
        lines.push("```");
        lines.push("");
        lines.push("If APPROVED: Done! If NEEDS_REVISION: Address feedback and re-verify.");
      }

      // UX verification (when enabled) — two-step: Kimi flow analysis + Gemini scoring
      if (ux) {
        lines.push("");
        lines.push("### 🎨 UX Verification (2-step)");
        lines.push("");
        lines.push("**Step 1 — Kimi UX flow analysis:**");
        lines.push("```json");
        lines.push(JSON.stringify({
          tool: "kimi_thinking",
          params: {
            task: `Trace the user journey for the ${checkpoint} implementation. Check: initial state, interactions, error states, empty states, loading states, keyboard/screen reader access.${goal ? ` Goal: ${goal}` : ""}`,
          },
        }, null, 2));
        lines.push("```");
        lines.push("");
        lines.push("**Step 2 — Gemini UX scoring:**");
        lines.push("```json");
        lines.push(JSON.stringify({
          tool: "gemini_analyze_text",
          params: {
            text: `Score /10: Usability, Accessibility (WCAG 2.1 AA), Interaction Design, Consistency, Performance UX. List top 3 UX blockers.${goal ? ` Goal alignment: ${goal}` : ""}`,
          },
        }, null, 2));
        lines.push("```");
      }

      // Responsiveness verification (when enabled)
      if (responsive) {
        lines.push("");
        lines.push("### 📱 Responsiveness Verification");
        lines.push("");
        lines.push("```json");
        lines.push(JSON.stringify({
          tool: "gemini_analyze_text",
          params: {
            text: `Responsive Design Review at ${checkpoint}:
1. BREAKPOINTS: Are mobile (≤640px), tablet (641-1024px), desktop (>1024px) handled?
2. TOUCH TARGETS: Minimum 44x44px for interactive elements?
3. LAYOUT: Does content reflow correctly? Any horizontal scroll?
4. TYPOGRAPHY: Font sizes readable on mobile? Line lengths appropriate?
5. NAVIGATION: Does nav collapse/adapt? Hamburger menu on mobile?
6. IMAGES/MEDIA: Responsive images? Aspect ratios maintained?
7. FORMS: Input fields usable on mobile? Appropriate input types?
Score each /10 and list specific breakpoint issues.`,
          },
        }, null, 2));
        lines.push("```");
      }

      // Devlog hint
      if (devlog) {
        lines.push("");
        lines.push(`📝 Devlog: \`devlog_session_log({ entry: "${checkpoint} checkpoint - ${completed.length}/${totalSteps} steps${goal ? ` - goal: ${goal.substring(0, 40)}` : ""}", type: "progress" })\``);
      }

      // Next action
      lines.push("");
      lines.push("---");
      if (checkpoint === "50%" || checkpoint === "80%") {
        const nextStep = completed.length + 1;
        lines.push(`▶ After verification, continue: \`planner_runner({ plan, mode: "step", stepNum: ${nextStep}, completed: [${completed.join(", ")}] })\``);
      } else {
        lines.push("▶ If APPROVED: Done! If NEEDS_REVISION: Address feedback and re-verify.");
      }
    }
```

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

Run: `npm run build`
Expected: Clean build

- [ ] **Step 3: Run tests**

Run: `npm test`
Expected: All tests pass (3 suites, 4 tests)

- [ ] **Step 4: Commit**

```bash
git add src/tools/planner-tools.ts
git commit -m "feat(planner): goal-oriented checkpoints with GPT+Gemini dual judges"
```

---

### Task 4: Update runner description and step mode with goal reminders

**Files:**
- Modify: `src/tools/planner-tools.ts:1353-1362` (description)
- Modify: `src/tools/planner-tools.ts:1456-1494` (step mode — add goal reminder)

- [ ] **Step 1: Update tool description**

Replace the `description` string (lines 1353-1362):

```typescript
  description: `Execute implementation plans step-by-step with goal-oriented verification.

COORDINATOR PATTERN - tracks actual plan steps:
1. Call with mode: "start" to parse plan and begin
2. Call with mode: "step" and stepNum to work on specific step
3. Call with mode: "verify" at 50%, 80%, and 100% for checkpoints

Checkpoints verify GOAL ALIGNMENT, not just progress:
- 50%: GPT judge — "does current work serve the stated goal?"
- 80%: Kimi decompose remaining work + goal alignment check
- 100%: Gemini final judge — quality + goal alignment scoring

Pass goal= explicitly, or it's extracted from plan frontmatter (planGoal field).`,
```

- [ ] **Step 2: Add goal reminder to step mode**

In the step mode (after line 1464, after showing step details), add:

```typescript
      // Goal reminder at every step
      if (goal) {
        lines.push(`> 🎯 **Goal:** ${goal}`);
        lines.push("");
      }
```

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

Run: `npm run build`
Expected: Clean build

- [ ] **Step 4: Commit**

```bash
git add src/tools/planner-tools.ts
git commit -m "feat(planner): goal reminders in step mode + updated description"
```

---

### Task 5: Update /blueprint skill to wire planner_runner as default execution

**Files:**
- Modify: `skills/blueprint/SKILL.md` (execution options)

- [ ] **Step 1: Update the skill to pass goal and offer runner**

In `skills/blueprint/SKILL.md`, update Step 2 (line 55-68) to include goal:

```markdown
### Step 2: Start the Pipeline

```
mcp__tachibot-mcp__planner_maker({
  task: "[task]",
  goal: "[extract success criteria from task/context, or ask user]",
  context: "[context if any]",
  codeContext: "[code if any]",
  mode: "start",
  ux: [true if --ux],
  responsive: [true if --responsive],
  debate: [true if --debate],
  issueFile: "[path if --issue]"
})
```
```

- [ ] **Step 2: Update execution options (line 105-113)**

Replace the options section with:

```markdown
Present the full plan to the user. Then offer:

```
Blueprint complete. Options:

1. **Execute with planner_runner** (recommended) — Step-by-step execution with goal checkpoints at 50/80/100%
2. **Execute inline** — I'll implement the plan task by task in this session
3. **Save to file** — Save as docs/plans/YYYY-MM-DD-[feature].md for later
4. **Refine** — Adjust specific tasks or add more detail
```

### If User Chooses "Execute with planner_runner" (recommended)

Start the runner with the plan and goal:
```
planner_runner({
  plan: "[full plan text]",
  goal: "[goal from planner_maker]",
  mode: "start"
})
```

Then follow the coordinator pattern — execute each step, run checkpoints at 50/80/100%.
```

- [ ] **Step 3: Commit**

```bash
git add skills/blueprint/SKILL.md
git commit -m "feat(blueprint): wire planner_runner as default execution path with goal"
```

---

### Task 6: Final verification

- [ ] **Step 1: Full build**

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

- [ ] **Step 2: Run tests**

Run: `npm test`
Expected: All tests pass

- [ ] **Step 3: Verify tool schema shows goal parameter**

Run: `npm run inspect 2>&1 | grep -A5 planner_maker`
Expected: `goal` parameter visible in schema

- [ ] **Step 4: Manual smoke test**

Call `planner_maker` with a goal to verify it works:
```
planner_maker({
  task: "Add analytics toggle",
  goal: "Let admins control PostHog tracking per-site, GDPR compliant, fail-closed",
  mode: "start"
})
```
Expected: Plan file created with `planGoal` in frontmatter

- [ ] **Step 5: Commit if needed**

```bash
git add -A
git commit -m "feat(planner): goal-oriented checkpoints with dual GPT+Gemini judges (v2.18.0)"
```
