How to Use AI Agents to Optimize Image Compression with Spec-Driven Development

AI agents streamline image optimization by automatically testing codecs and quality levels during the build. With clear specs guiding size and visual thresholds, the pipeline picks the smallest acceptable image, making performance gains consistent and hands-free.
Shan is a contributor at Aviator’s blog, where they cover developer experience tooling, CI/CD workflows, and engineering productivity trends. With a knack for breaking down complex tech topics into clear, actionable insights, Shan helps teams streamline developer workflows and ship high-quality software faster.

How to Use AI Agents to Optimize Image Compression with Spec-Driven Development

AI agents streamline image optimization by automatically testing codecs and quality levels during the build. With clear specs guiding size and visual thresholds, the pipeline picks the smallest acceptable image, making performance gains consistent and hands-free.

spec driven development banner

TL;DR

  • Specification-Driven Development (SDD) replaces ad-hoc Docker tweaks with a clean spec and runbook that define what to optimize and how to verify it.
  • Using Aviator’s optimize_image_compression_in_build.md template, you can define compression goals, run automated steps, and get measurable before/after results.
  • AI agents analyze Dockerfiles, reorder layers, prune large assets, and rebuild images, all version-controlled and validated through CI.
  • The system automatically opens a pull request summarizing build time improvements and image size savings, ready for review and merge.
  • This spec-driven approach turns build optimization into a repeatable engineering workflow, no guesswork, no manual compression, just traceable automation.

Why Build Pipelines Become Slower Over Time

As applications evolve, container builds quietly accumulate weight: uncompressed image assets, redundant layers, missing .dockerignore entries, and base images that were never revisited. This adds up to slower CI/CD pipelines, longer feedback loops, and higher storage and transfer costs. Teams often mention in internal chats or r/devops threads that they “aren’t fully sure what’s inside their images anymore,” which increases both maintenance overhead and operational risk.

Instead of manually inspecting Dockerfiles or experimenting with different compression steps, AI agents can analyze the build context, detect what is contributing to image bloat, and apply optimizations automatically. These agents can reorder layers, introduce multi-stage builds, generate or refine .dockerignore files, and compress assets, while ensuring the optimized build still runs correctly.

Specification-Driven Development (SDD) defines what should be optimized (e.g., target image size, directories to compress), and a runbook defines how to apply those optimizations. Aviator Runbooks capture this process as a version-controlled Markdown workflow that multiple engineers and agents can collaborate on, review, refine, and reuse. The result is a repeatable, auditable, team-wide process rather than a one-off local tuning effort. The optimize_image_compression_in_build.md runbook template in Aviator’s public library provides this structure out of the box.

Aviator’s open Runbooks Library includes a ready-to-use template named optimize_image_compression_in_build.md, designed specifically for this purpose. The template encodes a structured workflow: discover large or redundant image layers, compress and rebuild them, validate build success, and create a pull request with before/after metrics.

In this tutorial, we’ll use that template directly, authoring a concise spec-image-opt.json to define compression thresholds and validation parameters, running the runbook through Aviator’s agentic workflow, and examining its output. You’ll see how agents automatically detect image assets, optimize them, validate the results through CI, and open a PR that documents measurable improvements in build size and efficiency.

Aviator SDD optimization metrics: build efficiency, CI/CD speed, error reduction, and resource utilization.

AI can now write code faster than any human, but there’s a catch, it can’t decide what to build or how to architect it.” — Ran Aroussi, Spec-Driven AI Development.

What Is Specification-Driven Development (SDD)?

Specification-Driven Development (SDD) is a structured method for defining what a software change should achieve before executing how it will be carried out. Instead of relying on ad-hoc scripts or individual developer intuition, SDD encodes intent in a specification file that can be parsed, validated, and executed consistently by agents or automated workflows.

Key elements of SDD

  • Specification file (JSON/YAML): Defines scope (repositories, file paths), desired transformations or actions (tests to add, APIs to migrate), and validation rules (lint, compile, unit tests).
  • Runbook template (Markdown): Encodes the ordered steps, discover, execute, validate, and create pull requests, used by agents to apply the spec.
  • Execution agents: Run the steps in isolated sandboxes or CI environments, applying transformations, generating artifacts, and reporting progress.
  • Validation rules: Ensure that results meet predefined conditions, such as all tests passing or code style conformity.

How spec-driven development improves AI coding quality

By separating intent from execution, teams gain:

  • Consistency: Identical logic applied across multiple repositories and services.
  • Reproducibility: Any engineer or agent can re-run a spec to achieve the same outcome.
  • Auditability: Each change can be traced to a specific spec and runbook version.
  • Reduced manual overhead: AI agents automate boilerplate work like test scaffolding or repetitive edits.

Aviator Runbooks bring this framework into existing developer workflows. Each runbook acts as a living document that records prompts, ordered steps, validation criteria, and environment configuration. Engineers can fork, version, and improve these runbooks over time, transforming them into a shared knowledge base that evolves with the codebase. When paired with AI agents, SDD enables true team-level collaboration: multiple developers and agents can contribute, review, and refine specifications together, ensuring that test generation and maintenance remain systematic rather than manual.

How Runbooks Turn AI Output Into Team-Repeatable Workflows

Aviator Runbooks AI: structured workflows, automated execution, integration, and flexible control

Aviator Runbooks provide the operational layer that turns a written specification into an executable, traceable workflow. Each runbook is a structured Markdown document that defines what to do (the ordered steps) and how to validate the outcome. Every section, metadata, numbered steps, and validation rules are machine-readable so Aviator’s execution agents can interpret and perform actions in a predictable sequence.

When you trigger a runbook in Aviator, it uses Claude Code but users can add their agents to handle the heavy lifting: they clone repositories, execute discovery and generation scripts, run tests, capture validation results, and open pull requests automatically. This built-in PR automation, integrated with GitHub via Aviator’s MergeQueue, ensures every change passes through standard review and CI pipelines before merge. Runbooks also support step-by-step and execute-all modes, allowing engineers to either observe each stage interactively or run the entire process unattended for trusted templates.

What You’ll Build and Prerequisites

Before diving into the steps, let’s establish what you’ll create and the environment required to follow along.

What You’ll Build

  • Automated build optimization changes applied via the Aviator runbook template. The workflow detects large or redundant image layers, compresses them, adjusts build steps where necessary (e.g., introducing .dockerignore or switching base image layers), and commits the results to a new branch. The system then opens a pull request summarizing the improvements.
  • Continuous Integration (CI) validation for optimized builds, ensuring that compressed images build successfully, run as expected, and meet the defined optimization criteria (e.g., maximum image size, acceptable build duration). Validation is managed through Aviator’s built-in review and MergeQueue mechanisms to maintain consistency across repositories.

Prerequisites

To reproduce this workflow in your own setup, ensure you have the following in place:

  • A GitHub repository with a build pipeline that produces container or static image artifacts. Example: a Docker-based FastAPI app such as tiangolo/uvicorn-gunicorn-fastapi-docker or any repository containing a Dockerfile or build configuration referencing image assets.
  • An Aviator account with permission to create and execute runbooks.
  • Docker and BuildKit installed, with permissions to run local builds and view layer statistics (docker history, docker buildx du).
  • Familiarity with basic image-build concepts, such as Dockerfile structure, build context, and caching layers. While the runbook automates optimization, understanding how build stages interact helps interpret the results and validation output.

Walkthrough: Running the Template Step by Step

This section walks you through the exact sequence of steps and UI actions to run the optimize_image_compression_in_build template from Aviator’s Runbooks Library. You’ll create a build optimization spec, bind it to the runbook, run the compression steps, validate image size and build success, and review the resulting pull request.

Follow each step in order, screenshot placeholders are provided for where to capture UI or console output in your final article.

Step 1: Select / Import the Template

Open the Aviator Runbooks Library and locate templates/optimize_image_compression_in_build.md. (If you cloned the library locally, open that file in your editor.)

In the Aviator UI, go to Runbooks → Library → Import Template and select this file.

Note: You can use this template standalone in tools like Claude Code, but in this guide we’ll execute it through Aviator so the run, validation, and PR creation happen automatically.

Dashboard showing a list of runbooks in the Aviator Runbook Library

Step 2: Select Repository and Add Custom Instructions

Once you click Use Template on the Optimize Image Compression in Build runbook, Aviator opens a setup dialog. Here you’ll specify which repository the runbook should target and optionally provide additional context that tailors the optimization to your specific build setup.

2.1 Select Repository

Use the dropdown to choose the repository that contains your build pipeline, for example:

  • uvicorn-gunicorn-fastapi-docker (in our case) 
  • docker-getting-started
  • or any repo with a valid Dockerfile or build configuration.

When you select a repository, Aviator automatically analyzes its structure (e.g., Dockerfile, asset folders, base images) to infer the initial build context.

Dialog for creating a new runbook from a template with optional custom instructions.

2.2 Add Custom Instructions (Embedded Spec)

The Custom instructions field acts as a lightweight, inline specification. It lets you define what optimization goals to achieve, how aggressive compression should be, and any validation constraints.

Paste the following example into the field:

Analyze the Dockerfile and build context for this repository. 
Optimize for smaller image size and faster builds by:
1. Compressing image assets under app/static/images or similar directories.
2. Excluding unnecessary files from build context via a generated .dockerignore.
3. Reordering Dockerfile layers to maximize caching efficiency.
4. Enabling multi-stage builds (builder → runtime) if not already used.
5. Using python:3.11-slim or an equivalent lightweight base image.
6. Validate that the optimized image builds successfully and all runtime checks pass.
Output before/after image sizes and build durations in the runbook summary.

This instruction set provides Aviator’s agent or user’s connected agents with structured context ,  effectively a spec-inlined directive ,  that replaces the need for a separate JSON spec file.

You can further refine it by specifying your compression tool preference or layer naming conventions (e.g., “prefer buildkit cache-from directives” or “target a final image size under 250 MB”).

Once ready, click Use Template to instantiate the runbook plan.

Template dialog with custom instructions entered for optimizing Docker image build times.

Step 3: Review the Generated Plan

Aviator now creates a plan instance bound to your repository and the instructions you entered. You’ll see an ordered list of four steps (auto-populated from the runbook):

  1. Build Context Optimization: reduce the size of files sent to Docker during build.
  2. Dockerfile Layer Optimization: reorder and merge layers to improve caching.
  3. Multi-Stage Build Implementation: separate builder and runtime stages.
  4. Advanced Caching Strategies: enable BuildKit, cache-from, and prune stale layers.

Each step can be expanded to inspect substeps and preview commands. For instance, the discovery phase may run:

docker buildx du
find . -type f -size +100k

and the optimization phase might include:

optipng -o7 app/static/images/**/*.png
docker buildx build --progress=plain --no-cache -t optimized-app .
Runbook interface showing detailed optimization steps and instructions.

Step 4: Execute the Optimization

You can now choose one of two execution modes:

  • Step-by-Step (recommended for first runs): Execute each step interactively, starting with discovery, reviewing compression results, and confirming layer changes before proceeding.
Runbook interface showing the Execute Next and Execute All options.
  • Execute-All (agentic mode): Run the entire workflow unattended. Aviator’s agents will discover assets, compress them, rebuild images, validate results, and open a PR automatically.

As each step runs, logs will appear inline showing compression statistics, image size reduction, and validation results.

Step 5: Validate and Review Results

After the optimization completes, Aviator triggers the validation phase, which confirms that:

  • The optimized image builds successfully.
  • Application startup works (uvicorn app.main:app –port 8000).
  • The final image size and build time meet your defined targets.

If validation fails, the plan pauses and logs detailed diagnostics. You can refine your custom instructions or revert to the last passing version.

Runbook view showing execution logs on the left and build optimization steps on the right

Step 6: Create Pull Request and Merge

When all validations pass, Aviator automatically opens a PR summarizing results.
Typical PR title:

[From template: Optimize Docker Image Build Times] Testing and Validation

Review the PR, verify diffs, and merge once approved. The PR remains traceable with runbook metadata and execution logs attached.

Publish the Runbook as a Reusable Template (Optional)

If the optimization workflow you executed is relevant to other services or teams, you can publish it as a reusable runbook template. This allows other developers to apply the same process without recreating the steps or instructions. Open the runbook, select the actions menu in the top right, and choose Publish as template. The template will then appear in your organization’s runbook library and can also be used for batch operations across multiple repositories. If the workflow was one-off and will not be reused, you can instead archive it to preserve the execution record without cluttering active runbooks.

Automatically generated PR showing testing and validation details from a runbook.
Pull request merge view showing runbook-generated summary details.

Conclusion

In this walkthrough, we used Aviator’s Optimize Image Compression in Build template to improve Docker build efficiency with AI agents. We learned how to:

  • Select a repository and define optimization intent directly through custom instructions.
  • Let Aviator’s agents analyze your Dockerfile and image layers to identify inefficiencies.
  • Automatically apply compression, reorder layers, validate builds, and open a pull request summarizing the results.

This structured approach transforms what would normally be trial-and-error optimizations into a repeatable workflow. Every step, from discovery to validation, is version-controlled, replayable, and reviewable, creating an engineering paper trail that’s impossible to achieve with ad hoc shell scripts or manual Docker tweaks.

As Aviator continues to expand its Runbooks Library, workflows like image compression, build caching, base image migration, or multi-stage setup can all follow the same spec-driven pattern. Teams can codify best practices once, reuse them across repositories, and ensure every optimization is both measurable and reversible.

CTA

FAQs

  1. 1. What Is Specification-Driven Development (SDD)?

    Specification-Driven Development is a methodology where you define what needs to change in a structured specification, and automated agents or runbooks handle how to apply and validate those changes. In Aviator, the specification lives in your custom instructions, it tells the agent which assets to optimize, what validation rules to follow, and what outcomes to expect. The paired runbook (like optimize_image_compression_in_build.md) executes those steps consistently across repositories.

  2. 2. What Does “Spec” Mean in Programming?

    In programming, a spec (short for specification) defines the expected structure, rules, or behavior of a component or process. In Spec-Driven Development, a spec is machine-readable (JSON, YAML, or inline instructions) so agents can interpret it directly.
    Here, your “spec” is the custom instruction block you provide inside the Aviator Use Template dialog, it tells the agent how aggressively to compress images, which directories to target, and what validation thresholds (build time, image size) to enforce.

  3. 3. What Happens After the PR is Created?

    Once the PR is opened, you’ll see a complete before/after summary, typically including build time improvements, image size reduction, and compression logs. Reviewers can inspect diffs (Dockerfile changes, .dockerignore updates, or optimized assets) before merging. Aviator’s MergeQueue ensures merges are conflict-free and maintain branch health.

Subscribe

Be the first to know once we publish a new blog post

Join our Discord

Learn best practices from modern engineering teams

Get a free 30-min consultation with the Aviator team to improve developer experience across your organization.

Powered by WordPress