Living Documentation That Updates with Code Changes Using Kiro

Kiro generates and maintains documentation that stays synchronized with your codebase, eliminating the perpetual drift between docs and implementation.

#kiro#documentation#ai-agents#developer-experience
Cover image for the article: Living Documentation That Updates with Code Changes Using Kiro

Documentation is a lie — at least, it usually is. The moment code changes without a corresponding docs update, documentation becomes misleading. Most teams accept this as inevitable. We did too, until we started using Kiro to generate documentation that updates automatically when code changes. Six months later, our internal docs have a 94% accuracy rate (measured by quarterly audits), up from a dismal 52%.

The Problem: Documentation Drift Is Inevitable (Without Automation)

Our engineering team maintained documentation across three surfaces:

  • API docs — OpenAPI specs that described endpoints, request/response shapes, and error codes
  • Architecture docs — System diagrams, service interaction maps, and data flow descriptions
  • Runbooks — Operational procedures for deployment, rollback, and incident response

The pattern was always the same: someone wrote docs when shipping a feature, then the feature evolved over six months without doc updates. New engineers read outdated docs, made wrong assumptions, and either built on incorrect mental models or learned to distrust documentation entirely.

We audited our docs quarterly. The results were consistently poor:

  • 48% of API endpoint descriptions were inaccurate (missing parameters, wrong response shapes)
  • 61% of architecture diagrams were outdated (missing services, incorrect dependencies)
  • 35% of runbooks referenced commands or configs that no longer existed

How Kiro Keeps Documentation Alive

The core insight is that documentation should be derived from code, not maintained alongside it. Kiro generates docs from source code analysis and updates them when the underlying code changes.

Trigger: PostFileSave on source files updates related docs:

{
  "version": "v1",
  "hooks": [
    {
      "name": "Update API docs on handler change",
      "trigger": "PostFileSave",
      "matcher": "src/api/.*\\.ts$",
      "action": {
        "type": "command",
        "command": "scripts/regenerate-api-docs.sh ${FILE_PATH}"
      }
    },
    {
      "name": "Update architecture docs on service change",
      "trigger": "PostFileSave",
      "matcher": "src/services/.*\\.ts$",
      "action": {
        "type": "agent",
        "prompt": "The service file at ${FILE_PATH} was modified. Review the change and update docs/architecture.md if service interactions, dependencies, or contracts changed."
      }
    }
  ]
}

Agent-type hooks are particularly powerful here. Instead of running a static script, the agent reads the change, understands the semantic impact, and decides whether documentation needs updating — and what specifically to update.

Documentation Generation in Practice

Here is how Kiro generates API documentation from our route handlers:

// Source: src/api/orders.ts
import { z } from 'zod';

const CreateOrderSchema = z.object({
  customerId: z.string().uuid(),
  items: z.array(z.object({
    productId: z.string().uuid(),
    quantity: z.number().int().positive().max(100),
  })).min(1).max(50),
  shippingAddress: AddressSchema,
  notes: z.string().max(500).optional(),
});

router.post('/orders', authenticate, async (req, res) => {
  const body = CreateOrderSchema.parse(req.body);
  const order = await orderService.create(body);
  res.status(201).json({ data: order });
});

Kiro generates:

## POST /orders

Creates a new order for a customer.

**Authentication:** Required (Bearer token)

**Request Body:**

| Field | Type | Required | Constraints |
|-------|------|----------|-------------|
| customerId | string (UUID) | Yes | Valid UUID |
| items | array | Yes | 1-50 items |
| items[].productId | string (UUID) | Yes | Valid UUID |
| items[].quantity | integer | Yes | 1-100 |
| shippingAddress | Address | Yes | See Address schema |
| notes | string | No | Max 500 chars |

**Response:** 201 Created

```json
{
  "data": {
    "id": "uuid",
    "customerId": "uuid",
    "status": "pending",
    "items": [...],
    "createdAt": "ISO-8601"
  }
}

Errors: 400 (validation), 401 (unauthorized), 500 (server error)


When someone modifies the zod schema — adding a field, changing a constraint — the PostFileSave hook detects the change and regenerates the documentation. The API docs are always in sync with the validation layer.

## Architecture Documentation

For architecture docs, Kiro analyzes import graphs, service client instantiations, and infrastructure configuration to produce accurate dependency maps:

```markdown
## Order Service Dependencies

### Upstream (calls these services)
- **Payment Service** — processes charges via gRPC (payment.proto)
- **Inventory Service** — reserves stock via REST (POST /reservations)
- **Notification Service** — sends order confirmation via EventBridge

### Downstream (called by these services)
- **API Gateway** — routes customer requests
- **Admin Dashboard** — queries order status

### Infrastructure
- **PostgreSQL** (RDS) — primary data store
- **Redis** (ElastiCache) — order status cache, TTL: 5 minutes
- **S3** — invoice PDF storage

### Event Bus
- **Publishes:** order.created, order.shipped, order.cancelled
- **Subscribes:** payment.completed, inventory.reserved

This documentation is generated by tracing actual code patterns — import statements, client configurations, event handlers — not by asking engineers to maintain a diagram manually.

Before and After: Documentation Quality

MetricBefore KiroAfter KiroChange
API doc accuracy52%94%+81%
Architecture diagram accuracy39%88%+126%
New engineer onboarding time3 weeks1.5 weeks-50%
"Is this still accurate?" Slack messages12/week2/week-83%

Documentation accuracy over time

The onboarding time reduction was the most impactful business outcome. New engineers trust the documentation because it is verifiably current. They read the docs, build correct mental models, and start contributing faster.

Runbook Generation

Operational runbooks are another category that drifts rapidly. We use Kiro to generate runbooks from deployment configurations and monitoring setup:

## Runbook: Order Service Deployment

### Pre-deployment
1. Check active orders in processing state: `SELECT count(*) FROM orders WHERE status = 'processing'`
   - If > 100: delay deployment until queue drains
2. Verify health of downstream services:
   - Payment Service: `curl https://payment.internal/health`
   - Inventory Service: `curl https://inventory.internal/health`

### Deployment
1. Deploy via: `aws ecs update-service --service order-service --force-new-deployment`
2. Monitor rolling update: `aws ecs describe-services --services order-service`
3. Verify new task health: check ALB target group health

### Rollback Trigger
- Error rate > 5% for 2 minutes
- P99 latency > 2000ms for 5 minutes
- Any 5xx responses on /orders endpoint

### Rollback Procedure
1. `aws ecs update-service --service order-service --task-definition order-service:PREVIOUS_VERSION`
2. Verify rollback: confirm old task definition is running
3. Page on-call if rollback fails

When the ECS task definition changes, the deployment commands in the runbook update. When monitoring thresholds change, the rollback triggers update. The runbook reflects reality.

Implementation Strategy

We rolled this out in three phases:

Phase 1: API docs — highest value, easiest to automate. Zod schemas provide a structured source of truth that maps directly to documentation.

Phase 2: Architecture docs — higher complexity, generated from code analysis. Required training Kiro on our service interaction patterns.

Phase 3: Runbooks — operational, generated from infrastructure configs. Required encoding deployment procedures in a format Kiro could update.

Conclusion

The choice is not between good documentation and no documentation. It is between automated documentation that stays current and manual documentation that lies. Kiro eliminates the maintenance burden by treating docs as a build artifact — generated from source, validated against reality, and updated automatically.

Start with your API documentation. If you use schema validation (zod, joi, class-validator), you already have a structured source of truth that maps cleanly to docs. Once API docs are automated, expand to architecture documentation and operational runbooks. The investment compounds: every hour saved reading outdated docs is an hour spent building instead.

Comments

    No comments yet. Be the first to share your thoughts.