<metadata>
purpose: Deep dive into Through-Agent Leverage Points (5-12)
type: technical-reference
domain: agentic-coding
category: through-agent-leverage
audience: LLM-optimized
last-updated: 2025-09-30
</metadata>

<overview>
Through-Agent Leverage Points optimize the environment surrounding the agent rather than the agent itself. These points create persistent infrastructure that compounds benefits over time, scales across multiple agents/developers, and enables systematic velocity improvements. Unlike In-Agent points (tactical), Through-Agent points are strategic investments.
</overview>

<leverage-point-5>
<name>DOCUMENTATION: Agent-specific context</name>
<priority>critical</priority>
<impact-rating>9/10</impact-rating>
<type>environmental-infrastructure</type>

<definition>
Agent-specific documentation provides persistent knowledge bases optimized for LLM consumption. Unlike human documentation (tutorials, explanations), agent documentation is structured data: architecture maps, decision rationale, constraints, patterns, and conventions. This is the agent's external memory.
</definition>

<documentation-types>
  <type name="CLAUDE.md">
    <purpose>Project-level instructions and conventions</purpose>
    <location>Project root and ~/.claude/</location>
    <content>
      <item>Coding standards and patterns</item>
      <item>Architecture overview</item>
      <item>Common workflows</item>
      <item>Tool usage preferences</item>
      <item>Security requirements</item>
    </content>
    <example>
      "# CRITICAL: Store decisions in ken-you-remember
       # Use TypeScript strict mode
       # Tests with Vitest, not Jest
       # Store passwords with bcrypt, min 12 rounds"
    </example>
  </type>

  <type name="UFC Context Files">
    <purpose>Layered domain knowledge</purpose>
    <location>~/.claude/context/</location>
    <structure>
      <layer1>tools/ - Available capabilities</layer1>
      <layer2>patterns/ - Reusable solutions</layer2>
      <layer3>domain/ - Business logic context</layer3>
    </structure>
    <benefit>Agent hydrates only relevant context per task</benefit>
  </type>

  <type name="Architecture Decision Records (ADRs)">
    <purpose>Why decisions were made</purpose>
    <format>
      "# ADR-001: Use PostgreSQL over MongoDB
       Date: 2025-01-15
       Decision: PostgreSQL for ACID guarantees
       Rationale: Financial transactions require consistency
       Consequences: Requires schema migrations"
    </format>
  </type>

  <type name="API Documentation">
    <purpose>Endpoint specifications for agent consumption</purpose>
    <optimization>OpenAPI/Swagger schemas over prose descriptions</optimization>
  </type>
</documentation-types>

<optimization-strategies>
  <strategy name="LLM-First Writing">
    <description>Structure for machine parsing, not human reading</description>
    <techniques>
      <technique>XML tags for hierarchical structure</technique>
      <technique>Bullet lists over paragraphs</technique>
      <technique>Code examples over explanations</technique>
      <technique>Explicit constraints ("NEVER do X", "ALWAYS do Y")</technique>
    </techniques>
    <example>
      Human doc: "When handling user input, it's important to consider security..."
      Agent doc: "USER INPUT RULES:
                  - ALWAYS validate type/length/format
                  - NEVER trust client-side validation
                  - Use parameterized queries for SQL"
    </example>
  </strategy>

  <strategy name="Living Documentation">
    <description>Update docs as code evolves</description>
    <pattern>
      1. Make architectural decision
      2. store_fr3k: Record decision
      3. Update CLAUDE.md or ADR
      4. Agent sees updated context in next session
    </pattern>
  </strategy>

  <strategy name="Context Layering">
    <description>Hierarchical organization prevents context bloat</description>
    <structure>
      README.md (human overview)
      ├── CLAUDE.md (agent project context)
      ├── docs/architecture/ (system design)
      ├── docs/patterns/ (implementation patterns)
      └── docs/api/ (endpoint specs)
    </structure>
    <rule>Agent loads README + CLAUDE.md always, others on-demand</rule>
  </strategy>
</optimization-strategies>

<antipatterns>
  <antipattern>Writing documentation for humans when agent is consumer</antipattern>
  <antipattern>Stale docs that contradict current codebase</antipattern>
  <antipattern>Verbose explanations that waste context window</antipattern>
</antipatterns>

<implementation>
  <beginner>Start with CLAUDE.md in project root</beginner>
  <intermediate>Add ADRs for major decisions</intermediate>
  <advanced>Full UFC context hierarchy</advanced>
</implementation>
</leverage-point-5>

<leverage-point-6>
<name>TYPES: Structured information</name>
<priority>high</priority>
<impact-rating>8/10</impact-rating>
<type>validation-infrastructure</type>

<definition>
Type systems provide machine-readable contracts that enable agents to validate correctness automatically. Strong typing reduces hallucination by making invalid code syntactically impossible. Types are documentation that compilers enforce.
</definition>

<type-system-benefits>
  <benefit category="agent-guidance">
    <description>Autocomplete/IntelliSense shows valid operations</description>
    <example>
      Without types: agent guesses user.getName() exists
      With types: agent knows user has only user.name property
    </example>
  </benefit>

  <benefit category="early-error-detection">
    <description>Catch mistakes at write-time, not runtime</description>
    <example>
      TypeScript: Type 'string' is not assignable to type 'number'
      Agent sees error immediately, corrects before generating more code
    </example>
  </benefit>

  <benefit category="refactoring-safety">
    <description>Type checker validates changes across codebase</description>
    <example>
      Rename function parameter → TypeScript finds all call sites
      Agent can refactor confidently without breaking code
    </example>
  </benefit>

  <benefit category="documentation-as-code">
    <description>Types document expected shapes</description>
    <example>
      interface User {
        id: string;
        email: string;
        role: 'admin' | 'user';
      }
      Agent knows exactly what User contains
    </example>
  </benefit>
</type-system-benefits>

<type-system-examples>
  <system language="TypeScript">
    <strengths>
      <strength>Gradual typing - adopt incrementally</strength>
      <strength>Rich inference - types without annotations</strength>
      <strength>Ecosystem support - DefinitelyTyped</strength>
    </strengths>
    <use-cases>JavaScript projects wanting safety</use-cases>
  </system>

  <system language="Python + Pydantic">
    <strengths>
      <strength>Runtime validation via Pydantic</strength>
      <strength>Data parsing with automatic conversion</strength>
      <strength>FastAPI integration</strength>
    </strengths>
    <example>
      from pydantic import BaseModel

      class User(BaseModel):
          id: int
          email: str
          role: Literal['admin', 'user']

      # Agent knows structure + gets validation
      user = User(id="123", email="test@test.com", role="admin")
      # Raises ValidationError - id must be int
    </example>
  </system>

  <system language="Rust">
    <strengths>
      <strength>Compile-time guarantees - no null, no data races</strength>
      <strength>Ownership system prevents entire bug classes</strength>
    </strengths>
    <agent-impact>Rust compiler is agent's pair programmer</agent-impact>
  </system>

  <system language="Database Schemas">
    <description>Types for data persistence</description>
    <example>
      CREATE TABLE users (
        id UUID PRIMARY KEY,
        email VARCHAR(255) UNIQUE NOT NULL,
        role user_role NOT NULL
      );

      Agent knows:
      - id is UUID, not arbitrary string
      - email must be unique and present
      - role must match enum
    </example>
  </system>

  <system language="API Schemas (OpenAPI, JSON Schema)">
    <description>Types for service boundaries</description>
    <benefit>Agent can validate requests/responses automatically</benefit>
  </system>
</type-system-examples>

<optimization-strategies>
  <strategy name="Progressive Typing">
    <description>Start with minimal types, expand over time</description>
    <path>
      <step1>Type function signatures</step1>
      <step2>Type data models/DTOs</step2>
      <step3>Type internal functions</step3>
      <step4>Enable strict mode</step4>
    </path>
  </strategy>

  <strategy name="Validation at Boundaries">
    <description>Enforce types where data enters system</description>
    <boundaries>
      <boundary>API requests (Zod, Joi, Pydantic)</boundary>
      <boundary>Database queries (ORM types)</boundary>
      <boundary>External service responses</boundary>
      <boundary>User input</boundary>
    </boundaries>
    <pattern>
      const userSchema = z.object({
        email: z.string().email(),
        age: z.number().min(18)
      });

      // Agent knows validation rules
      const validated = userSchema.parse(input);
    </pattern>
  </strategy>

  <strategy name="Type-Driven Development">
    <description>Define types first, implement second</description>
    <workflow>
      1. Define data structures as types
      2. Define function signatures
      3. Let type checker guide implementation
      4. Agent fills in implementation knowing contracts
    </workflow>
  </strategy>

  <strategy name="Discriminated Unions">
    <description>Type-safe enums and variants</description>
    <example>
      type Result<T> =
        | { success: true; data: T }
        | { success: false; error: string };

      // Agent knows to check success before accessing data
      if (result.success) {
        console.log(result.data); // TypeScript knows this is safe
      }
    </example>
  </strategy>
</optimization-strategies>

<agent-specific-benefits>
  <benefit>Reduces hallucination - invalid code won't compile</benefit>
  <benefit>Speeds up iteration - agent catches errors immediately</benefit>
  <benefit>Enables confident refactoring - type checker validates changes</benefit>
  <benefit>Improves agent understanding - types document intent</benefit>
</agent-specific-benefits>
</leverage-point-6>

<leverage-point-7>
<name>ARCHITECTURE: Code-based navigation</name>
<priority>high</priority>
<impact-rating>8/10</impact-rating>
<type>organizational-infrastructure</type>

<definition>
Architecture determines how easily agents can understand system boundaries, dependencies, and where to make changes. Well-architected code is self-documenting; poorly architected code requires extensive context loading and explanation.
</definition>

<agent-friendly-architecture>
  <principle name="Modular Organization">
    <description>Clear separation of concerns</description>
    <structure>
      src/
        ├── api/           # HTTP handlers
        ├── services/      # Business logic
        ├── models/        # Data structures
        ├── utils/         # Pure functions
        └── tests/         # Test files
    </structure>
    <benefit>Agent knows where to find/add functionality</benefit>
  </principle>

  <principle name="Dependency Direction">
    <description>Clear import hierarchy</description>
    <rule>
      Core <- Services <- API <- UI
      (Inner layers have no knowledge of outer layers)
    </rule>
    <benefit>Agent understands impact radius of changes</benefit>
  </principle>

  <principle name="Single Responsibility">
    <description>One file/function does one thing</description>
    <example>
      Bad:  userController.js (handles auth, CRUD, validation, emails)
      Good: userAuth.js, userCrud.js, userValidation.js, userEmails.js
    </example>
    <benefit>Agent can reason about changes in isolation</benefit>
  </principle>

  <principle name="Consistent Naming">
    <description>Predictable file/function names</description>
    <patterns>
      <pattern>Services: *Service.ts (userService.ts, orderService.ts)</pattern>
      <pattern>Controllers: *Controller.ts</pattern>
      <pattern>Models: *.model.ts</pattern>
      <pattern>Tests: *.test.ts</pattern>
    </patterns>
    <benefit>Agent can find related files without guidance</benefit>
  </principle>

  <principle name="Bounded Contexts">
    <description>Domain-driven design modules</description>
    <example>
      src/
        ├── auth/     # All authentication logic
        ├── payments/ # All payment logic
        └── inventory/ # All inventory logic
    </example>
    <benefit>Agent understands domain boundaries</benefit>
  </principle>
</agent-friendly-architecture>

<architectural-patterns>
  <pattern name="Hexagonal (Ports and Adapters)">
    <structure>
      core/        # Business logic (pure)
      ports/       # Interfaces
      adapters/    # Implementations (DB, API, etc.)
    </structure>
    <agent-benefit>Clear boundary between logic and infrastructure</agent-benefit>
  </pattern>

  <pattern name="Feature-Based">
    <structure>
      features/
        ├── user-registration/
        │   ├── api.ts
        │   ├── service.ts
        │   ├── validation.ts
        │   └── tests.ts
        └── order-processing/
            └── ...
    </structure>
    <agent-benefit>All related code co-located</agent-benefit>
  </pattern>

  <pattern name="Clean Architecture">
    <layers>
      <layer>Entities (domain models)</layer>
      <layer>Use Cases (application logic)</layer>
      <layer>Interface Adapters (controllers, presenters)</layer>
      <layer>Frameworks & Drivers (UI, DB, external services)</layer>
    </layers>
    <agent-benefit>Dependency inversion makes testing easy</agent-benefit>
  </pattern>
</architectural-patterns>

<navigation-optimization>
  <strategy name="Entry Point Documentation">
    <description>README.md maps major components</description>
    <example>
      # Codebase Structure
      - `api/` - REST endpoints (Express)
      - `services/` - Business logic
      - `db/` - Database access (Prisma)
      - Entry: `src/index.ts`
    </example>
  </strategy>

  <strategy name="Import Graphs">
    <description>Visualize dependencies</description>
    <tool>dependency-cruiser, madge</tool>
    <benefit>Agent sees system topology</benefit>
  </strategy>

  <strategy name="Convention Over Configuration">
    <description>Predictable patterns reduce explanation</description>
    <example>
      Agent assumes: *Service.ts files in services/ directory
      No need to explain: "Services are in services/ folder"
    </example>
  </strategy>
</navigation-optimization>

<antipatterns>
  <antipattern name="God Objects">
    <description>Files with 1000+ lines doing everything</description>
    <consequence>Agent overwhelmed, changes risky</consequence>
  </antipattern>

  <antipattern name="Circular Dependencies">
    <description>A imports B imports A</description>
    <consequence>Agent cannot reason about change impact</consequence>
  </antipattern>

  <antipattern name="Inconsistent Structure">
    <description>Every module organized differently</description>
    <consequence>Agent must learn structure per module</consequence>
  </antipattern>

  <antipattern name="Hidden Dependencies">
    <description>Global state, singletons, implicit coupling</description>
    <consequence>Agent makes changes unaware of side effects</consequence>
  </antipattern>
</antipatterns>

<agent-impact>
  <metric>Time to locate relevant code: 80% reduction with clear architecture</metric>
  <metric>Incorrect file modifications: 60% reduction</metric>
  <metric>Refactoring confidence: Dramatic increase with modular design</metric>
</agent-impact>
</leverage-point-7>

<leverage-point-8>
<name>TESTS: Validation and self-correction</name>
<priority>critical</priority>
<impact-rating>10/10</impact-rating>
<type>validation-infrastructure</type>

<definition>
Tests enable agents to validate their own work autonomously. Without tests, agents require human verification for every change. With tests, agents self-correct through rapid iteration, dramatically increasing autonomy and velocity.
</definition>

<test-categories>
  <category name="Unit Tests">
    <purpose>Validate individual functions in isolation</purpose>
    <agent-value>Fast feedback on logic correctness</agent-value>
    <example>
      test('calculateDiscount returns correct percentage', () => {
        expect(calculateDiscount(100, 0.2)).toBe(20);
      });

      // Agent runs test after implementation
      // If fails, agent sees exact assertion failure and fixes
    </example>
  </category>

  <category name="Integration Tests">
    <purpose>Validate component interactions</purpose>
    <agent-value>Catches interface mismatches</agent-value>
    <example>
      test('API returns 401 for invalid token', async () => {
        const res = await request(app)
          .get('/api/user')
          .set('Authorization', 'invalid');
        expect(res.status).toBe(401);
      });
    </example>
  </category>

  <category name="End-to-End Tests">
    <purpose>Validate full user flows</purpose>
    <agent-value>Ensures no regression in critical paths</agent-value>
    <example>
      test('User can complete purchase flow', async () => {
        await page.goto('/products');
        await page.click('[data-testid="add-to-cart"]');
        await page.click('[data-testid="checkout"]');
        await page.fill('[name="card"]', '4242424242424242');
        await page.click('[data-testid="complete-order"]');
        await expect(page).toHaveURL('/order-confirmation');
      });
    </example>
  </category>

  <category name="Property-Based Tests">
    <purpose>Validate behavior across input range</purpose>
    <agent-value>Finds edge cases automatically</agent-value>
    <example>
      test('sort is idempotent', () => {
        fc.assert(
          fc.property(fc.array(fc.integer()), (arr) => {
            const sorted1 = sort(arr);
            const sorted2 = sort(sorted1);
            expect(sorted1).toEqual(sorted2);
          })
        );
      });
    </example>
  </category>
</test-categories>

<agent-workflow-with-tests>
  <workflow name="Self-Correcting Implementation">
    <step1>Agent implements feature</step1>
    <step2>Agent runs tests via Bash tool</step2>
    <step3>
      <if-pass>Mark task complete</if-pass>
      <if-fail>
        <action>Read test output</action>
        <action>Identify failure cause</action>
        <action>Fix implementation</action>
        <action>Re-run tests</action>
        <action>Repeat until pass</action>
      </if-fail>
    </step3>
    <step4>store_fr3k: Record solution pattern</step4>
  </workflow>

  <benefit>Agent iterates to solution without human intervention</benefit>
  <metric>Average 3-5 iterations to passing tests vs 10+ without</metric>
</agent-workflow-with-tests>

<test-optimization-for-agents>
  <strategy name="Test-First Development">
    <description>Write test before implementation</description>
    <agent-benefit>Test defines success criteria clearly</agent-benefit>
    <workflow>
      1. Human writes failing test
      2. Agent implements until test passes
      3. Agent knows exactly when done
    </workflow>
  </strategy>

  <strategy name="Descriptive Test Names">
    <description>Test name documents expected behavior</description>
    <example>
      Bad:  test('user test')
      Good: test('createUser throws ValidationError when email is invalid')
    </example>
    <agent-benefit>Agent understands requirement from test name</agent-benefit>
  </strategy>

  <strategy name="Assertion Messages">
    <description>Include context in assertion failures</description>
    <example>
      expect(result.status).toBe(200, `Expected success but got ${result.status}: ${result.error}`);
    </example>
    <agent-benefit>Agent sees exact failure context without reading code</agent-benefit>
  </strategy>

  <strategy name="Fast Test Suites">
    <description>Tests must run in seconds, not minutes</description>
    <target>Unit tests: <100ms each, Integration: <1s each</target>
    <agent-benefit>Enables rapid iteration loops</agent-benefit>
  </strategy>

  <strategy name="Test Coverage Tracking">
    <description>Identify untested code paths</description>
    <agent-workflow>
      1. Agent adds new function
      2. Runs coverage report
      3. Sees function uncovered
      4. Adds test for function
    </agent-workflow>
  </strategy>
</test-optimization-for-agents>

<test-driven-agents>
  <principle>Tests are executable specifications</principle>
  <principle>Tests enable autonomous validation</principle>
  <principle>Tests reduce hallucination via rapid feedback</principle>
  <principle>Tests make refactoring safe</principle>

  <impact-metrics>
    <metric>First-attempt success rate: 30% → 75% with comprehensive tests</metric>
    <metric>Debugging time: 60% reduction (agent sees exact failure)</metric>
    <metric>Regression rate: 80% reduction (tests catch breaks)</metric>
  </impact-metrics>
</test-driven-agents>

<antipatterns>
  <antipattern name="No Tests">
    <consequence>Agent cannot validate work, human becomes bottleneck</consequence>
  </antipattern>

  <antipattern name="Slow Tests">
    <consequence>Agent avoids running tests, misses errors</consequence>
  </antipattern>

  <antipattern name="Brittle Tests">
    <consequence>Tests fail on irrelevant changes, agent learns to ignore</consequence>
  </antipattern>

  <antipattern name="Vague Assertions">
    <example>expect(result).toBeTruthy()</example>
    <consequence>Agent doesn't understand what broke</consequence>
  </antipattern>
</antipatterns>
</leverage-point-8>

<leverage-point-9>
<name>PLANNING: Meta-work for agents</name>
<priority>high</priority>
<impact-rating>8/10</impact-rating>
<type>cognitive-infrastructure</type>

<definition>
Planning is the process of decomposing complex tasks into structured steps before implementation. Agents without planning hallucinate, lose context, and produce inconsistent work. Agents with systematic planning maintain coherence across multi-step tasks.
</definition>

<planning-tools>
  <tool name="TodoWrite">
    <purpose>Track task decomposition and progress</purpose>
    <structure>
      {
        content: "Imperative: Fix auth bug",
        activeForm: "Present continuous: Fixing auth bug",
        status: "pending" | "in_progress" | "completed"
      }
    </structure>
    <workflow>
      <step>Create todos for all subtasks</step>
      <step>Mark ONE todo in_progress before starting</step>
      <step>Complete immediately after finishing</step>
      <step>Add new todos as discovered during work</step>
    </workflow>
    <benefit>Prevents agent from losing track mid-task</benefit>
  </tool>

  <tool name="ken-you-remember (store_fr3k)">
    <purpose>Persist plans across context resets</purpose>
    <usage>
      store_fr3k: "Plan: 1) Add JWT refresh endpoint 2) Update middleware 3) Add tests 4) Update docs"
    </usage>
    <benefit>Agent retrieves plan after context loss</benefit>
  </tool>

  <tool name="hey-daddy Tasks">
    <purpose>Full task lifecycle with validation workflow</purpose>
    <statuses>todo → coding_done → validated → complete (with needs_fixes loop)</statuses>
    <benefit>Structured workflow prevents premature completion</benefit>
  </tool>
</planning-tools>

<planning-strategies>
  <strategy name="Top-Down Decomposition">
    <description>Break complex task into hierarchical subtasks</description>
    <example>
      Task: Implement user authentication
      ├── 1. Design auth architecture
      │   ├── 1.1 Choose JWT vs session
      │   └── 1.2 Design token refresh flow
      ├── 2. Implement backend
      │   ├── 2.1 Login endpoint
      │   ├── 2.2 Token validation middleware
      │   └── 2.3 Refresh endpoint
      ├── 3. Add tests
      └── 4. Update documentation
    </example>
    <agent-benefit>Clear roadmap prevents wandering</agent-benefit>
  </strategy>

  <strategy name="Dependency Ordering">
    <description>Sequence tasks by prerequisites</description>
    <example>
      Cannot write tests before implementation
      Cannot deploy before tests pass
      Cannot update docs before feature complete
    </example>
    <agent-benefit>Prevents out-of-order work</agent-benefit>
  </strategy>

  <strategy name="Checkpoint-Based Planning">
    <description>Define validation points throughout task</description>
    <example>
      1. Implement login endpoint → Checkpoint: Endpoint returns 200
      2. Add validation → Checkpoint: Invalid input returns 400
      3. Add tests → Checkpoint: All tests pass
      4. Complete → Checkpoint: Manual login succeeds
    </example>
    <agent-benefit>Clear success criteria at each step</agent-benefit>
  </strategy>

  <strategy name="Risk-First Ordering">
    <description>Tackle highest-risk/unknowns first</description>
    <rationale>Fail fast if approach won't work</rationale>
    <example>
      Task: Add real-time notifications
      1. Spike: Test WebSocket library (unknown)
      2. Implement connection handling (risky)
      3. Add message routing (straightforward)
      4. Add UI components (easy)
    </example>
  </strategy>
</planning-strategies>

<anti-hallucination-planning>
  <principle>Planning forces explicit thinking before action</principle>

  <technique name="Pre-Implementation Verification">
    <description>Agent states plan, human approves before code</description>
    <workflow>
      Agent: "Here's my plan: 1) Modify auth.ts 2) Update middleware 3) Add tests. Proceed?"
      Human: "Approved" or "No, also update the config"
    </workflow>
    <benefit>Catches misunderstandings before wasted work</benefit>
  </technique>

  <technique name="Constraint Documentation">
    <description>Record what NOT to do in plan</description>
    <example>
      Todo: "Add JWT refresh ONLY to auth.ts. DO NOT modify user.model.ts or database schema."
    </example>
    <benefit>Prevents scope creep and unintended changes</benefit>
  </technique>

  <technique name="Progress Journaling">
    <description>Agent records what was done and why</description>
    <pattern>
      store_fr3k: "Completed JWT refresh. Used 7-day expiry per security req. Token stored in DB refresh_tokens table."
    </pattern>
    <benefit>Context preservation for later sessions</benefit>
  </technique>
</anti-hallucination-planning>

<planning-antipatterns>
  <antipattern name="No Planning">
    <description>Jump directly to implementation</description>
    <consequence>Missed requirements, inconsistent approach, context loss</consequence>
  </antipattern>

  <antipattern name="Over-Planning">
    <description>Spend 90% time planning, 10% doing</description>
    <consequence>Analysis paralysis, outdated plans</consequence>
  </antipattern>

  <antipattern name="Abandoned Plans">
    <description>Create TodoWrite, then ignore it</description>
    <consequence>Defeats purpose of planning</consequence>
  </antipattern>

  <antipattern name="Vague Tasks">
    <description>Todo: "Fix the thing"</description>
    <consequence>Agent doesn't know when task is complete</consequence>
  </antipattern>
</planning-antipatterns>

<agent-impact>
  <metric>Consistency: 90% improvement with planning vs none</metric>
  <metric>Context retention: 3x better with TodoWrite tracking</metric>
  <metric>Scope adherence: 80% fewer unintended changes</metric>
</agent-impact>
</leverage-point-9>

<leverage-point-10>
<name>AI DEVELOPER WORKFLOWS (ADWs)</name>
<priority>medium</priority>
<impact-rating>7/10</impact-rating>
<type>process-infrastructure</type>

<definition>
AI Developer Workflows are repeatable, documented procedures for common development scenarios. ADWs capture proven approaches and enable consistent, high-quality execution by agents across diverse tasks. They are the difference between ad-hoc problem-solving and systematic mastery.
</definition>

<adw-examples>
  <workflow name="Bug Fixing Workflow">
    <steps>
      <step>1. recall_fr3k: Check if bug encountered before</step>
      <step>2. Reproduce: Read error logs, stack trace</step>
      <step>3. Locate: Grep for error source, read relevant files</step>
      <step>4. Diagnose: Identify root cause (not symptom)</step>
      <step>5. Fix: Edit code with minimal change</step>
      <step>6. Validate: Run tests, verify fix</step>
      <step>7. Prevent: Add test for bug if missing</step>
      <step>8. store_fr3k: Record bug pattern and solution</step>
    </steps>
    <benefit>Systematic debugging prevents guess-and-check</benefit>
  </workflow>

  <workflow name="Feature Implementation Workflow">
    <steps>
      <step>1. Clarify: Understand requirements, ask if ambiguous</step>
      <step>2. Research: Check existing patterns in codebase</step>
      <step>3. Design: Identify files to modify, new files needed</step>
      <step>4. Plan: TodoWrite with subtasks</step>
      <step>5. Implement: Code per plan, one todo at a time</step>
      <step>6. Test: Write/run tests for new functionality</step>
      <step>7. Document: Update relevant docs</step>
      <step>8. Validate: Complete todo, mark task coding_done</step>
    </steps>
  </workflow>

  <workflow name="Refactoring Workflow">
    <steps>
      <step>1. Safety: Ensure tests exist and pass</step>
      <step>2. Scope: Define exact files/functions to refactor</step>
      <step>3. Constraint: NO behavior changes, structure only</step>
      <step>4. Incremental: Small, testable refactorings</step>
      <step>5. Validate: Run tests after each change</step>
      <step>6. Commit: Git commit each successful refactoring</step>
    </steps>
    <benefit>Safe refactoring without breaking changes</benefit>
  </workflow>

  <workflow name="PR Creation Workflow">
    <steps>
      <step>1. git status: Check uncommitted changes</step>
      <step>2. git diff: Review changes</step>
      <step>3. git add: Stage relevant files</step>
      <step>4. git commit: Commit with descriptive message</step>
      <step>5. git push: Push to remote branch</step>
      <step>6. gh pr create: Create PR with title and body</step>
      <step>7. Link issues: Reference related issues/tasks</step>
    </steps>
  </workflow>

  <workflow name="Dependency Update Workflow">
    <steps>
      <step>1. Review: Check changelog for breaking changes</step>
      <step>2. Update: Modify package.json/requirements.txt</step>
      <step>3. Install: Run npm install / pip install</step>
      <step>4. Migrate: Update code for breaking changes</step>
      <step>5. Test: Run full test suite</step>
      <step>6. Validate: Manual testing of affected features</step>
    </steps>
  </workflow>
</adw-examples>

<adw-encoding>
  <location>
    CLAUDE.md (common workflows)
    ~/.claude/context/workflows/ (detailed ADWs)
    UFC system context files
  </location>

  <format>
    # Workflow: Bug Fixing
    STEPS:
    1. recall_fr3k: Prior solutions
    2. Reproduce: Error logs + stack trace
    3. Locate: Grep source
    4. Fix: Minimal edit
    5. Validate: Run tests
    6. store_fr3k: Record solution

    CONSTRAINTS:
    - Fix root cause, not symptom
    - Add test if missing
    - No refactoring during bug fix
  </format>
</adw-encoding>

<optimization-strategies>
  <strategy name="Workflow Invocation">
    <description>Human triggers workflow by name</description>
    <example>
      Human: "Follow the Bug Fixing Workflow for the login error"
      Agent: Executes steps systematically
    </example>
  </strategy>

  <strategy name="Workflow Chaining">
    <description>Link workflows for complex scenarios</description>
    <example>
      1. Feature Implementation Workflow (build feature)
      2. Testing Workflow (validate feature)
      3. PR Creation Workflow (ship feature)
    </example>
  </strategy>

  <strategy name="Workflow Refinement">
    <description>Improve workflows based on outcomes</description>
    <pattern>
      1. Execute workflow
      2. Identify inefficiencies
      3. Update workflow documentation
      4. store_fr3k: Record improvement
    </pattern>
  </strategy>

  <strategy name="SlashCommand Integration">
    <description>Encode workflows as /commands</description>
    <examples>
      <example>/debug → Bug Fixing Workflow</example>
      <example>/check → Testing + Validation Workflow</example>
      <example>/api → API Development Workflow</example>
    </examples>
    <benefit>One-word workflow invocation</benefit>
  </strategy>
</optimization-strategies>

<agent-impact>
  <metric>Consistency: Same approach every time</metric>
  <metric>Quality: Proven workflows avoid common mistakes</metric>
  <metric>Velocity: No decision fatigue, immediate action</metric>
  <metric>Knowledge capture: Best practices encoded permanently</metric>
</agent-impact>
</leverage-point-10>

<leverage-point-11>
<name>AGENTIC CODING KPIs</name>
<priority>medium</priority>
<impact-rating>6/10</impact-rating>
<type>measurement-infrastructure</type>

<definition>
Agentic Coding KPIs are metrics that quantify agent effectiveness and guide optimization decisions. What gets measured gets improved. KPIs transform intuition into data-driven strategy.
</definition>

<kpi-categories>
  <category name="Success Metrics">
    <kpi name="First-Attempt Success Rate">
      <definition>% of tasks completed correctly without revision</definition>
      <target>75%+ (with optimized leverage points)</target>
      <measurement>Track tasks marked "validated" without "needs_fixes"</measurement>
    </kpi>

    <kpi name="One-Shot Success Rate">
      <definition>% of prompts that succeed without clarification</definition>
      <target>60%+</target>
      <improvement-levers>Better Context (LP#1), Better Prompts (LP#3)</improvement-levers>
    </kpi>

    <kpi name="Test Pass Rate">
      <definition>% of agent-generated code that passes tests first try</definition>
      <target>80%+</target>
      <improvement-levers>Types (LP#6), Better Tests (LP#8)</improvement-levers>
    </kpi>
  </category>

  <category name="Efficiency Metrics">
    <kpi name="Context Utilization">
      <definition>% of provided context actually used in solution</definition>
      <target>70-90% (higher = better targeting)</target>
      <measurement>Track which files/docs agent references</measurement>
    </kpi>

    <kpi name="Clarification Rate">
      <definition>Average # of follow-up questions per task</definition>
      <target><2</target>
      <improvement-levers>Better Prompts (LP#3), Documentation (LP#5)</improvement-levers>
    </kpi>

    <kpi name="Iteration Count">
      <definition>Average # of attempts before success</definition>
      <baseline>5-7 without optimization</baseline>
      <target>1-2 with optimization</target>
    </kpi>

    <kpi name="Time to First Output">
      <definition>Seconds from prompt to initial response</definition>
      <factors>Model choice (LP#2), Context size (LP#1)</factors>
    </kpi>
  </category>

  <category name="Quality Metrics">
    <kpi name="Hallucination Rate">
      <definition>% of agent outputs containing invented facts/APIs</definition>
      <target><5%</target>
      <improvement-levers>Types (LP#6), Tests (LP#8), Planning (LP#9)</improvement-levers>
    </kpi>

    <kpi name="Regression Introduction Rate">
      <definition>% of agent changes that break existing functionality</definition>
      <target><2%</target>
      <improvement-levers>Tests (LP#8), Architecture (LP#7)</improvement-levers>
    </kpi>

    <kpi name="Code Review Approval Rate">
      <definition>% of agent-generated PRs approved without changes</definition>
      <target>90%+</target>
    </kpi>
  </category>

  <category name="Autonomy Metrics">
    <kpi name="Self-Correction Rate">
      <definition>% of agent errors fixed autonomously (via tests)</definition>
      <target>80%+</target>
      <improvement-levers>Tests (LP#8), Planning (LP#9)</improvement-levers>
    </kpi>

    <kpi name="Human Intervention Rate">
      <definition>Average # of human corrections per task</definition>
      <target><1</target>
    </kpi>

    <kpi name="Tool Use Efficiency">
      <definition>% of tool calls that succeed first attempt</definition>
      <target>95%+</target>
      <improvement-levers>Better Prompts (LP#3), Documentation (LP#5)</improvement-levers>
    </kpi>
  </category>
</kpi-categories>

<measurement-implementation>
  <approach name="Manual Tracking">
    <description>Spreadsheet logging of outcomes</description>
    <effort>Low initial, high ongoing</effort>
    <use-case>Individual developers, early-stage</use-case>
  </approach>

  <approach name="Automated Instrumentation">
    <description>Code tracks metrics automatically</description>
    <implementation>
      - Log agent tool calls and outcomes
      - Track task status transitions (hey-daddy)
      - Parse test results
      - Measure response times
    </implementation>
    <effort>High initial, low ongoing</effort>
    <use-case>Teams, mature setups</use-case>
  </approach>

  <approach name="Periodic Review">
    <description>Weekly/monthly retrospective analysis</description>
    <questions>
      <question>Which tasks succeeded first-attempt this week?</question>
      <question>Which required multiple iterations?</question>
      <question>What were common failure patterns?</question>
      <question>Which leverage points need optimization?</question>
    </questions>
  </approach>
</measurement-implementation>

<optimization-cycle>
  <step1>Measure: Track KPIs for baseline</step1>
  <step2>Identify: Find lowest-performing metrics</step2>
  <step3>Hypothesize: Which leverage point(s) to optimize?</step3>
  <step4>Intervene: Improve targeted leverage point</step4>
  <step5>Measure: Track KPI change post-intervention</step5>
  <step6>Iterate: Repeat for next bottleneck</step6>
</optimization-cycle>

<example-analysis>
  <scenario>
    <observation>First-attempt success rate: 40%</observation>
    <analysis>
      - High clarification rate (4 questions per task)
      - Context utilization: 30% (most provided context unused)
    </analysis>
    <diagnosis>Context over-provisioning, vague prompts</diagnosis>
    <intervention>
      1. Optimize LP#1 Context: Provide only relevant files
      2. Optimize LP#3 Prompt: Add explicit constraints
    </intervention>
    <result>
      - First-attempt success: 40% → 72%
      - Clarification rate: 4 → 1.5
      - Context utilization: 30% → 75%
    </result>
  </scenario>
</example-analysis>

<agent-impact>
  KPIs transform agentic coding from art to engineering.
  Data-driven decisions beat intuition.
  Systematic improvement compounds over time.
</agent-impact>
</leverage-point-11>

<leverage-point-12>
<name>ONE-SHOT SUCCESS</name>
<priority>high</priority>
<impact-rating>10/10</impact-rating>
<type>emergent-capability</type>

<definition>
One-Shot Success is the ability for an agent to complete a task correctly on the first attempt, without clarifying questions, failed tests, or revisions. This is the ultimate goal of agentic coding optimization and the emergent property of all 11 preceding leverage points working in harmony.
</definition>

<prerequisites>
  <requirement>LP#1 Context: Agent sees all relevant information upfront</requirement>
  <requirement>LP#2 Model: Appropriate LLM for task complexity</requirement>
  <requirement>LP#3 Prompt: Clear, constrained, with examples</requirement>
  <requirement>LP#4 Tools: Agent can execute necessary actions</requirement>
  <requirement>LP#5 Documentation: Agent has persistent knowledge</requirement>
  <requirement>LP#6 Types: Agent validates correctness automatically</requirement>
  <requirement>LP#7 Architecture: Agent navigates codebase easily</requirement>
  <requirement>LP#8 Tests: Agent self-validates output</requirement>
  <requirement>LP#9 Planning: Agent approaches systematically</requirement>
  <requirement>LP#10 ADWs: Agent follows proven procedures</requirement>
  <requirement>LP#11 KPIs: Continuous measurement and improvement</requirement>
</prerequisites>

<characteristics>
  <characteristic>Zero clarifying questions</characteristic>
  <characteristic>Zero test failures</characteristic>
  <characteristic>Zero human corrections</characteristic>
  <characteristic>First output is final output</characteristic>
  <characteristic>Complete, not partial solution</characteristic>
</characteristics>

<enabling-factors>
  <factor name="Complete Context">
    <description>Agent has everything needed before starting</description>
    <example>
      Prompt: "Add password reset feature"
      Context provided:
      - Existing auth implementation (for consistency)
      - Email service setup (for sending reset emails)
      - Token generation pattern (for reset tokens)
      - Test examples (for validation)

      Result: Agent implements complete feature correctly first try
    </example>
  </factor>

  <factor name="Unambiguous Requirements">
    <description>No room for interpretation or guessing</description>
    <example>
      Vague: "Make login faster"
      Precise: "Add Redis caching for user sessions. Cache for 1 hour. Invalidate on logout."
    </example>
  </factor>

  <factor name="Constrained Scope">
    <description>Clear boundaries prevent scope creep</description>
    <example>
      "Add JWT refresh endpoint to auth/routes.ts.
       DO NOT modify auth/middleware.ts.
       DO NOT change database schema.
       Use existing token generation function."
    </example>
  </factor>

  <factor name="Validation Mechanisms">
    <description>Agent can verify correctness autonomously</description>
    <mechanisms>
      <mechanism>Type checking catches errors at write-time</mechanism>
      <mechanism>Tests validate behavior automatically</mechanism>
      <mechanism>Linters enforce code standards</mechanism>
    </mechanisms>
  </factor>

  <factor name="Pattern Recognition">
    <description>Task matches documented workflows</description>
    <example>
      Task: "Add new API endpoint"
      Agent recognizes: This is Feature Implementation Workflow
      Agent executes: Proven procedure for API additions
    </example>
  </factor>
</enabling-factors>

<achieving-one-shot>
  <phase name="Foundation (Months 1-2)">
    <focus>Core Four In-Agent Points</focus>
    <actions>
      <action>Master Context provision (LP#1)</action>
      <action>Write clear, constrained Prompts (LP#3)</action>
      <action>Ensure agent has necessary Tools (LP#4)</action>
    </actions>
    <milestone>First-attempt success: 30% → 50%</milestone>
  </phase>

  <phase name="Infrastructure (Months 3-4)">
    <focus>Through-Agent Points</focus>
    <actions>
      <action>Create CLAUDE.md documentation (LP#5)</action>
      <action>Add comprehensive tests (LP#8)</action>
      <action>Use TodoWrite consistently (LP#9)</action>
    </actions>
    <milestone>First-attempt success: 50% → 70%</milestone>
  </phase>

  <phase name="Optimization (Months 5-6)">
    <focus>Advanced leverage points</focus>
    <actions>
      <action>Add types where missing (LP#6)</action>
      <action>Document common workflows (LP#10)</action>
      <action>Track and optimize KPIs (LP#11)</action>
    </actions>
    <milestone>First-attempt success: 70% → 85%+</milestone>
  </phase>

  <phase name="Mastery (Ongoing)">
    <focus>One-Shot Success as default</focus>
    <actions>
      <action>Continuous KPI monitoring</action>
      <action>Workflow refinement based on failures</action>
      <action>Leverage point optimization per task type</action>
    </actions>
    <milestone>One-Shot Success Rate: 60%+ of all tasks</milestone>
  </phase>
</achieving-one-shot>

<one-shot-antipatterns>
  <antipattern name="Premature Optimization">
    <description>Trying for one-shot before foundations exist</description>
    <consequence>Frustration, inconsistent results</consequence>
    <fix>Build leverage points 1-9 first</fix>
  </antipattern>

  <antipattern name="Incomplete Context">
    <description>Assuming agent will "figure it out"</description>
    <consequence>Clarification questions, iterations</consequence>
    <fix>Over-provide context initially, refine based on KPIs</fix>
  </antipattern>

  <antipattern name="Vague Requirements">
    <description>Open-ended prompts expecting mind-reading</description>
    <consequence>Agent guesses, likely wrong direction</consequence>
    <fix>Explicit constraints, examples, success criteria</fix>
  </antipattern>
</one-shot-antipatterns>

<impact>
  <velocity>10x increase in implementation speed</velocity>
  <quality>Consistent, predictable outcomes</quality>
  <confidence>Human trusts agent to work autonomously</confidence>
  <scalability>Same principles apply across projects</scalability>
</impact>

<philosophy>
One-Shot Success is not about agent perfection.
It's about human-agent system optimization.
Every leverage point contributes to the whole.
Mastery emerges from systematic improvement.
</philosophy>
</leverage-point-12>

<through-agent-summary>
<synergy>
Through-Agent points build the environment for sustained excellence:
- Documentation (5) gives agents memory
- Types (6) give agents validation
- Architecture (7) gives agents navigation
- Tests (8) give agents self-correction
- Planning (9) gives agents coherence
- ADWs (10) give agents procedures
- KPIs (11) give agents improvement
- One-Shot (12) emerges from all above
</synergy>

<investment>
Through-Agent points require upfront effort but compound returns:
- In-Agent optimizations: Immediate wins, must repeat
- Through-Agent optimizations: Delayed wins, permanent benefits
</investment>

<next-steps>
  <step>Choose one Through-Agent point to implement this week</step>
  <step>Start with Documentation (LP#5) or Tests (LP#8) for highest ROI</step>
  <step>Measure baseline KPIs before optimization</step>
  <step>Iterate through leverage points systematically</step>
  <step>Track progress toward One-Shot Success</step>
</next-steps>
</through-agent-summary>