Steven's Knowledge

Daily Workflows with AI

Practical patterns for using AI tools in everyday engineering work, with concrete prompt examples and output quality assessment

Daily Workflows with AI

This page covers practical, daily-use patterns for AI-assisted development. Each section includes the workflow, concrete prompt examples, and an honest assessment of how well AI typically performs at the task.

Code Generation

Writing Implementations from Descriptions

Give AI a clear description of what you need, including language, framework, and constraints.

Prompt example:

Implement a rate limiter using the sliding window algorithm in TypeScript.
Requirements:
- Store counts in Redis using sorted sets
- Accept windowMs (window size in ms) and maxRequests as config
- Return { allowed: boolean, remaining: number, retryAfter?: number }
- Export as a class with a check(key: string) method

Quality assessment: AI handles algorithmic implementations well when the algorithm is well-known. The output typically needs review for error handling (what if Redis is down?) and edge cases (clock skew, concurrent access). Expect 80-90% usable code that needs 10-20% human refinement.

Generating Tests from Implementation

Provide the function and ask for comprehensive test coverage.

Prompt example:

Write unit tests for this function using Vitest. Cover:
- Happy path with valid inputs
- Edge cases (empty array, single element, null/undefined)
- Error cases (invalid types, out of range)
- Boundary conditions

[paste function here]

Quality assessment: AI generates good test structure and catches obvious edge cases. It often misses subtle domain-specific edge cases and sometimes generates tests that pass trivially (testing the mock, not the function). Always verify that tests actually exercise the code path you care about.

Boilerplate Reduction

AI excels at generating repetitive structural code.

Prompt example:

Create an Express route handler for a CRUD API for a "Project" resource.
- Use Zod for request validation
- Use Prisma as the ORM
- Include proper error handling with appropriate HTTP status codes
- Follow RESTful conventions

Project schema:
- id: string (cuid)
- name: string (required, 1-100 chars)
- description: string (optional, max 1000 chars)
- status: enum (active, archived, draft)
- ownerId: string (relation to User)

Quality assessment: Excellent for this task. AI produces clean, conventional CRUD code. Review for: authorization checks (AI often forgets to verify the user owns the resource), pagination defaults, and whether the validation schema matches your existing patterns.

From Signature to Implementation

Provide a function signature with a docstring and let AI fill in the implementation.

/**
 * Merges two sorted arrays into a single sorted array.
 * Both input arrays must be sorted in ascending order.
 * Uses O(n + m) time and O(n + m) space.
 *
 * @param a - First sorted array
 * @param b - Second sorted array
 * @returns A new sorted array containing all elements from both inputs
 */
export function mergeSorted<T>(a: T[], b: T[], compare: (x: T, y: T) => number): T[] {
  // AI implements this
}

Quality assessment: This works very well. The docstring provides enough specification for AI to produce a correct implementation. This pattern — human writes the contract, AI writes the implementation — is one of the most reliable AI workflows.

Code Understanding

Explaining Unfamiliar Codebases

When you join a new project or encounter unfamiliar code, AI can accelerate onboarding.

Prompt example:

Explain what this file does and its main responsibilities.
What are the key functions and how do they relate to each other?
What patterns or frameworks does it use?

[paste file content]

Quality assessment: AI is very good at identifying patterns, frameworks, and the general purpose of code. It occasionally misidentifies custom patterns as standard library features, so cross-reference with the actual documentation. Best used as a starting point for understanding, not as the final word.

Tracing Data Flow

Prompt example:

Trace how a user login request flows through this application.
Starting from the POST /api/auth/login endpoint, follow the data through:
1. Route handler
2. Validation
3. Service layer
4. Database query
5. Token generation
6. Response

Here are the relevant files:
[paste route file]
[paste auth service file]
[paste user repository file]

Quality assessment: Good when you provide all relevant files. AI traces the flow logically and identifies where data is transformed. It cannot discover files you did not provide, so make sure to include the complete chain. In CLI-based tools like Claude Code, the AI can read the files directly from your project.

Understanding Legacy Code

Prompt example:

Explain this regex and suggest a more readable alternative:

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

Quality assessment: Excellent. AI is arguably better than most humans at explaining regular expressions. It breaks down each component and suggests alternatives like using a validation library or named capture groups. One of the highest-value use cases.

Debugging

Error Diagnosis

Paste the error, stack trace, and relevant code. AI can often identify the root cause faster than manual debugging.

Prompt example:

This error occurs intermittently in production:

TypeError: Cannot read properties of undefined (reading 'map')
    at UserList (/app/components/UserList.tsx:24:31)
    at renderWithHooks (/app/node_modules/react-dom/cjs/react-dom.development.js:14985:18)

Here is the component:
[paste UserList.tsx]

Here is the hook that fetches the data:
[paste useUsers.ts]

The API response shape is:
[paste example response]

Quality assessment: AI is strong at diagnosing common errors. For this example, it would immediately identify the race condition: data.users.map(...) is called before the API response arrives. It suggests adding a loading check or optional chaining. For intermittent errors, AI is particularly helpful because it recognizes timing and concurrency patterns.

Flaky Test Diagnosis

Prompt example:

This test fails intermittently in CI (about 1 in 10 runs) but passes locally.

[paste test file]
[paste relevant CI logs showing the failure]
[paste the function being tested]

What could cause this flakiness?

Quality assessment: Good at identifying common flakiness causes: timing dependencies, shared state between tests, date/time sensitivity, network calls not properly mocked, random ordering issues. Less effective when the flakiness is caused by infrastructure-level issues (memory pressure, container resource limits) since it cannot observe the CI environment.

Rubber Duck Debugging

Use AI as an interactive rubber duck. Explain the problem and let it ask clarifying questions.

Prompt example:

I am debugging a memory leak in a Node.js Express application.
The heap grows steadily by about 50MB per hour.
I have already checked for:
- Unclosed database connections (using connection pooling, looks fine)
- Event listener accumulation (no warnings in logs)
- Global variable accumulation (grep shows nothing obvious)

What else should I investigate?

Quality assessment: Good for expanding your debugging checklist. AI suggests avenues you might not have considered: closure references in middleware, response objects not being properly ended, caching layers without eviction, large object retention in error handling. It works as a brainstorming partner rather than a definitive diagnosis tool.

Code Review Assistance

Pre-Review Your Own PR

Before submitting a PR, ask AI to review it.

Prompt example:

Review this diff for bugs, security issues, and style improvements.
Focus on:
- Logic errors and edge cases
- Security vulnerabilities (injection, auth bypass, data exposure)
- Error handling gaps
- Performance concerns

[paste diff]

Quality assessment: AI catches surface-level issues well: missing null checks, potential injection points, inconsistent error handling. It is less reliable for deep logic errors that require understanding the broader system context. Think of it as a first-pass reviewer, not a replacement for human code review.

Edge Case Analysis

Prompt example:

Are there edge cases this function does not handle?

[paste function]

Known usage: called from an API endpoint that receives user input.
The input is validated with Zod before reaching this function,
but the Zod schema allows empty strings and arrays.

Quality assessment: Good at identifying mechanical edge cases (empty inputs, boundary values, type edge cases). Less reliable for domain-specific edge cases that depend on business rules it does not know about. Providing the validation schema and usage context significantly improves the output.

Refactoring

Breaking Up Large Functions

Prompt example:

Refactor this 200-line function into smaller, testable functions.
Requirements:
- Each extracted function should have a single responsibility
- Maintain the same external behavior
- Add TypeScript types to all function signatures
- Name functions descriptively

[paste function]

Quality assessment: AI does this well. It identifies logical groupings, extracts helper functions, and names them reasonably. Review the boundaries it chose — sometimes it splits in awkward places or introduces unnecessary indirection. The key value is that it does the mechanical work of extraction so you can focus on whether the decomposition makes sense.

Pattern Conversion

Prompt example:

Convert this callback-based Node.js code to async/await.
Preserve all error handling behavior.
Maintain the same function signatures where possible.

[paste callback-based code]

Quality assessment: Excellent. Pattern conversion is one of AI's strongest capabilities. Callbacks to promises, class components to hooks, imperative to declarative — these are well-defined transformations with clear rules. Still review for subtle changes in error propagation behavior.

Design Pattern Application

Prompt example:

Apply the strategy pattern to remove this switch statement.
The current code handles different notification types (email, SMS, push, Slack)
with a large switch in the send() method.
Each case has different configuration and retry logic.

[paste current code]

Quality assessment: AI produces textbook-quality pattern implementations. Review whether the pattern is actually the right abstraction for your case — AI tends to over-engineer when asked to apply patterns. Sometimes the switch statement was fine.

Documentation

Generating JSDoc from Code

Prompt example:

Add JSDoc comments to all exported functions in this file.
Include:
- Description of what the function does
- @param tags with types and descriptions
- @returns description
- @throws for known error conditions
- @example with a usage example

[paste file]

Quality assessment: Good structure, but descriptions tend to be surface-level ("takes a user and returns a boolean" instead of "checks whether the user has permission to access the given resource based on their role and the resource's visibility settings"). Edit the descriptions for specificity.

README from Project Structure

Prompt example:

Generate a README section explaining the project structure.
Here is the directory tree:

[paste output of: find src -type f | head -50]

And here is the main entry point:
[paste src/index.ts]

Quality assessment: Good at producing a structural overview. It correctly identifies patterns (MVC, feature folders, etc.) and describes the purpose of each directory. May get specific details wrong about files it has not seen, so verify descriptions against actual file contents.

API Documentation from Routes

Prompt example:

Generate API documentation in markdown for these route handlers.
Include: method, path, request body schema, response schema, status codes, and example curl commands.

[paste route file with Zod schemas]

Quality assessment: Excellent when the route file includes validation schemas. AI generates well-structured, accurate documentation. This is one of the highest-ROI uses of AI — documentation that would take an hour to write manually is produced in seconds and needs only minor corrections.

DevOps and Infrastructure

Generating Dockerfiles

Prompt example:

Create a multi-stage Dockerfile for a Next.js application.
Requirements:
- Use node:20-alpine as base
- Separate build and runtime stages
- Only copy necessary files to the runtime image
- Run as non-root user
- Include health check
- Optimize layer caching for node_modules

Quality assessment: AI generates solid Dockerfiles that follow best practices. Review for: correct COPY order for cache optimization, whether all build dependencies are excluded from the runtime stage, and whether the health check endpoint actually exists in your application.

CI/CD Pipeline Generation

Prompt example:

Create a GitHub Actions workflow for a TypeScript monorepo that:
- Runs on push to main and on pull requests
- Installs dependencies with pnpm
- Runs type checking, linting, and tests in parallel
- Only runs tests for changed packages (using turbo or nx)
- Caches node_modules and build outputs
- Deploys to Vercel on main branch push

Quality assessment: AI generates functional workflows, but CI/CD has many environment-specific details. The generated workflow will likely need adjustments for: specific secret names, deployment targets, caching paths, and runner specifications. Use it as a starting scaffold, not a drop-in solution.

Debugging Pipeline Failures

Prompt example:

This GitHub Actions workflow is failing. Here is the error output:

[paste CI log]

Here is the workflow file:
[paste .github/workflows/ci.yml]

What is wrong and how do I fix it?

Quality assessment: Good at identifying common CI issues: version mismatches, missing environment variables, incorrect caching keys, permission problems. Less effective for intermittent failures caused by runner environment differences or network issues.

Quality Assessment Summary

TaskAI QualityHuman Review Needed
Boilerplate/CRUD codeHighLow — check auth, pagination
Test generationMedium-HighMedium — verify tests are meaningful
Regex explanationVery HighLow
Error diagnosisHighLow-Medium — verify the fix
Code reviewMediumHigh — use as first pass only
RefactoringHighMedium — verify decomposition
DocumentationMedium-HighMedium — edit for specificity
CI/CD generationMediumHigh — environment-specific
Architecture decisionsLowDo not rely on AI

The pattern is consistent: AI excels at well-defined, pattern-based tasks and struggles with tasks that require broad system context or domain knowledge. Use it where it is strong, and apply human judgment where it is weak.

On this page