| name | kubernetes-readiness-migration |
| description | Two-phase Kubernetes containerisation workflow: analyses a codebase against all 12-factor app principles and Kubernetes compatibility requirements to produce a readiness report with detailed microservice decomposition plan (minimal and full recommendations), then systematically resolves all findings by externalising configuration, migrating persistent storage to object store (S3/GCS/Azure Blob), externalising sessions for horizontal scaling, redirecting logging to stdout/stderr, executing decomposition assessments, and generating complete Kubernetes YAML manifests. Validates via three-tier pipeline: docker build, kubeconform, optional cluster. Supports decomposition_scope parameter: minimal (default) or full. Triggers: containerisation, Kubernetes, 12-factor, cloud-native, readiness, migration. |
Kubernetes Readiness Analysis and Migration
A comprehensive two-phase transformation that first assesses any codebase for containerisation and Kubernetes readiness (including detailed microservice decomposition planning with both minimal and full recommendations), then transforms it for full Kubernetes deployment — executing decomposition where feasible.
Entry Criteria
- The codebase is available for static analysis and contains application source code in one or more programming languages.
- The application is currently running in a non-containerised environment (bare metal, VMs, or traditional deployment) or is being assessed before an initial containerisation effort.
- Build and dependency configuration files are present (e.g., build manifests, package lock files, or equivalent for any language/framework).
- Windows-only runtimes (.NET Framework, IIS, COM+) → Phase 1 Blocker requiring Linux-compatible migration as a prerequisite before containerisation.
- Decomposition scope:
minimal (default) or full. Controls whether Phase 2 generates manifests only for the primary Deployment and required support resources (minimal) or for all viable Low/Medium complexity candidates from the Named Service Inventory (full). When absent or unset, apply minimal.
- Primary Deployment = the service handling the majority of inbound HTTP traffic, or the service named in the project root package manifest (package.json/pom.xml/go.mod main module).
Examples
Example 1 — PHP/Laravel monolith (interpreted, minimal scope):
- Input: Single-repo Laravel app with Blade templates, Redis sessions, MySQL DB, file uploads to local disk.
- Key signals:
composer.json, env() calls in config/, FILESYSTEM_DISK=local.
- Output: Readiness report (21-area scorecard) + 7 manifests (Namespace, Deployment, Service, ConfigMap, Secret, NetworkPolicy, ServiceAccount) + ENV_VARIABLES.md + INFRASTRUCTURE_REQUIREMENTS.md + TRANSFORMATION_SUMMARY.md.
Example 2 — Java/Spring Boot with Maven (compiled language, pre-build gate):
- Input: Multi-module Maven project, Spring Boot 3.x, Liquibase migrations, Quartz scheduler.
- Key signals:
pom.xml, @Value("${...}"), System.getenv(), spring-boot-starter-quartz.
- Output: Same as above + migration Job manifest +
mvn package -DskipTests passes before docker build.
Example 3 — Python/Django (interpreted, standard 12-factor):
- Input: Django REST API with Celery workers, S3 file storage, PostgreSQL.
- Key signals:
requirements.txt, os.environ.get(), CELERY_BROKER_URL, DEFAULT_FILE_STORAGE.
- Output: Same as above + worker Deployment manifest + CronJob for Celery Beat.
Limitations
- Compiled languages require matching host toolchain: Java, Go, C#, Rust projects require the correct SDK version installed on the host for the pre-Docker compilation gate. Version mismatches produce CONDITIONAL PASS, not PASS.
- Interpreted languages with version constraints: Ruby (Bundler), Python (pyproject.toml
python_requires) — host interpreter version mismatch causes dependency install failures → CONDITIONAL PASS.
- Tier 3 KWOK validates API acceptance only: KWOK cluster validation confirms Kubernetes API schema and resource relationships — it does NOT execute containers or verify runtime behaviour.
- Docker-absent environments produce static-checklist results only: Without Docker, Tier 1 falls back to a 5-point static verification checklist. Image correctness is unverifiable.
- Windows-only runtimes require Linux migration prerequisite: .NET Framework, IIS, COM+ are Phase 1 Blockers — containerisation cannot proceed without a Linux-compatible rewrite.
- Integration tests requiring live infrastructure are excluded: Criterion 13 covers unit tests only. Tests needing running databases, message brokers, or external APIs are out of scope.
- DB-stored configuration cannot be externalised to ConfigMap: Settings managed via admin UI (e.g., OpenMRS GlobalProperty, WordPress wp_options) remain database-stored. Document as post-install admin configuration.
- Plugin-registry architectures may require single-replica Recreate strategy: OSGi, JNLP plugin registries with local plugin state may not support RollingUpdate without shared storage.
- Version mismatches that cannot be resolved by toolchain installation produce CONDITIONAL PASS: Before recording CONDITIONAL PASS for a version mismatch, attempt
mise install for the required toolchain (see language reference §Toolchain Bootstrap). Only record CONDITIONAL PASS if mise is absent or installation fails.
- Interpreted languages require host-side validation gate: PHP, Python, Ruby, Node.js projects MUST pass language-native syntax/dependency validation on the host BEFORE
docker build. See each language reference §Pre-Docker Local Validation and references/docker-build-validation.md §Step 0b.
- Multi-stage Dockerfiles complement but do NOT replace the host-side validation gate: Host-side compilation/validation is ALWAYS attempted first for fast feedback. Docker build further validates the Dockerfile itself. The sequence is always: (1) host-side compile/check → (2) docker build. The host-side gate is only recorded as CONDITIONAL PASS (not skipped) when the toolchain is unavailable and mise installation fails.
§0 Initial Entry Interview
Before any analysis or file reads, gather user preferences in two blocks. Record all answers before proceeding.
Block A — Always Asked
- Phase selection: "Run Phase 1 (analysis report) only, or Phase 1 + Phase 2 (analysis + transformation)?"
- Report output path: "Where should the readiness report be written?" (default: current directory)
- Report format: "Markdown or HTML?" (default: Markdown)
- Report detail level: "Full 21-area scorecard, or executive summary only?" (default: full)
Block B — Asked Only If Phase 2 Selected
- Decomposition scope: "Minimal (primary Deployment only) or full (all viable services)?" (default: minimal)
- Validation tooling: Auto-detect availability of Docker, Minikube, kind, k3s, and kwokctl. Check each tool independently (do NOT chain checks — individual tool absences must remain individually visible). Then confirm: "Detected: [tools]. Use these for validation? Any additional preferences?" (default: use whatever is detected; attempt KWOK download if nothing found)
Non-Interactive / CI Defaults
When no interactive prompt is possible, apply: Phase 1+2, Markdown, full detail, minimal scope, KWOK attempted if available (Docker used if present). Log all defaults applied.
Implementation Steps
Phase 1 - Containerisation Readiness Analysis
§0 Initial Entry Interview MUST complete before Phase 1 steps begin.
Perform a comprehensive static analysis of the codebase to identify containerisation blockers, risks, and remediation steps. Follow references/skill-a-readiness-analysis.md.
This phase covers:
- Analysis of all 12 factors of the 12-factor app methodology
- Kubernetes-specific compatibility checks
- Horizontal scaling and singleton pattern challenges
- Local filesystem usage assessment and replacement recommendations
- Credentials, API keys, and secrets management audit
- Monolith decomposition assessment with Named Service Inventory, Data Ownership Matrix, and Decomposition Complexity ratings — see
references/microservice-decomposition-patterns.md
- Database connection and data integrity analysis
- Memory growth and leak pattern detection
- Startup order dependency mapping
- User session externalisation assessment
- Local caching strategy recommendations
- In-memory state sharing between microservice candidates
Output: A single consolidated readiness report (HTML or markdown) with visual readiness scorecard (21 areas), executive summary table, per-section structured finding tables, colour-coded severity badges, Named Service Inventory table with complexity ratings, both Minimal and Full Decomposition Recommendations, and singleton risk summary table.
Zero decomposition candidates rule: When the Named Service Inventory contains only the primary service (or is empty), the Microservice Decomposition Roadmap section MUST state "No additional decomposition candidates identified" rather than being omitted.
Refer to references/skill-a-readiness-analysis.md for the full implementation steps, validation criteria, and formatting rules.
Phase 2 - Kubernetes Containerisation Transformation
Consume the Phase 1 readiness report and systematically resolve every finding. Follow references/skill-b-containerisation-transformation.md.
Pre-flight codebase existence check (FIRST action): Before any file_read or shell command referencing the codebase path, verify the path exists and contains files. If check fails: write ERROR_REPORT.md and exit 1.
Execution Scope: Determined by decomposition_scope (Entry Criteria §5 / §0 Block B):
minimal (default): Primary Deployment + required supporting resources only. See references/minimal-execution-set.md.
full: Generate manifests for all Low and Medium complexity candidates from the Named Service Inventory, in addition to the primary Deployment and required support resources.
If the Phase 1 readiness report is unavailable, Phase 2 workers derive blocker context directly from source files using analysis patterns in references/skill-a-readiness-analysis.md.
This phase covers 20 sub-phases:
Execution Philosophy: All procedural steps in this specification describe OUTCOMES to achieve. The specific tools, commands, and exact syntax used to achieve each outcome are the worker's choice based on the available environment. No command string in this specification or its reference files is mandatory — only the described outcome is mandatory. Exception: Validation commands (kubeconform flags, structural assertion patterns, stale-claim grep patterns) define outcomes themselves — their flags and patterns are normative, not merely illustrative.
-
Initial Setup — Parse report, copy codebase, gather user preferences (if not already gathered via §0). Backup file rule: After every file modification, immediately remove any backup files (.bak, .orig, ~) created by the editing tool. Prefer file_write (full-file overwrite) over str_replace for documentation files to avoid creating backups. This applies to all editing operations throughout all tasks without exception. Non-interactive defaults: if preferences cannot be gathered interactively in CI mode, apply Minimal Execution Set defaults and skip Tier 3 cluster validation. See references/minimal-execution-set.md. See §Tier 3 Validation Decision Gate below for tooling resolution.
-
Decomposition Assessment — Ingest Phase 1 Named Service Inventory. When decomposition_scope=minimal (default): execution scope = primary Deployment + required Jobs/workers only; full catalog goes to report/roadmap. When decomposition_scope=full: generate manifests for all Low/Medium complexity candidates; High candidates still documented only. See references/microservice-decomposition-patterns.md Phase 2 Execution Rules. ⚠ Guard: Verify Named Service Inventory is current — if source structure has diverged from Phase 1, re-derive service boundaries from package manifests before proceeding. ⚠ Guard: P0/P1 structural blockers identified during Phase 1 (e.g., pom.xml scope=provided on embedded server, missing dependencies) MUST appear as explicit dedicated Phase 2 tasks — do NOT rely on them being handled incidentally by other tasks.
-
Configuration Externalisation — Mandatory first action: source-authoritative env var discovery (5-pass algorithm). Before writing ENV_VARIABLES.md, complete ALL five passes from repo root (never scoped to a single module):
Pass 1 — Full-tree literal-string discovery (from repo root, pattern [A-Za-z][A-Za-z0-9_]+):
Use language-specific env-read patterns from the Reference Dispatch table. Scan the ENTIRE repo tree, not a single module. For multi-module projects, scan from root — never a single module subdirectory.
Pass 2 — Data-structure literal scan: Scan for uppercase identifiers stored in config maps/dictionaries/collections (e.g., Python dicts, JS objects, Java Maps with string keys matching [A-Z][A-Z0-9_]+). Disambiguation rule: identifiers appearing in subprocess child-env dict assignments (e.g., subprocess.Popen(env={...})) or SDK wire-protocol Map.put() constants (e.g., Kafka ) are output/injected — NOT application input. Exclude from ENV_VARIABLES.md. : (a) Property-file LHS keys: identifiers on the left side of in files are property bindings, not env var reads — exclude unless the value side contains placeholder syntax. (b) WSGI CGI meta-variables: for Python WSGI apps, exclude RFC 3875 §4.1 CGI meta-variable names (, , , , , , , , , ) — these are per-request environ dict keys, not OS env vars. See §WSGI Environ False-Positive Exclusion.
Post-generation validation guards: (a) Security Hardening status cells must not contain 'Required'/'Recommended' — only 'Applied'/'Configured'. (b) Scope Comparison Actual Outcome column must match ls kubernetes/*.yaml disk state. (c) Three-Tier Validation cells must contain 'PASSED' with tool flags — never blank.
SELF-REFERENCE GUARD: Audit trail row labels and Notes cells MUST NOT quote literal banned tokens or search phrases. Use functional abstractions: "Future-tense gate" (not "will/shall/would"), "Banned-phrase check" (not the specific phrase), "Resolved-issue verification" (not "Known-Issues scan"). Run banned-phrase check after EACH individual edit operation on TRANSFORMATION_SUMMARY.md, not only at task close. See references/validation-patterns.md §Stale-Claim Sweep for safe label templates.
Safe-label substitution table (use these to avoid triggering the stale-claim sweep):
| ❌ Triggers sweep | ✓ Safe replacement |
|---|
All 6 required fields | All 6 mandatory fields |
recommended approach | supported approach |
not generated | roadmap only |
Action Required | Operator Setup Step |
Known-issue resolution | Prior-findings verification |
Required / Recommended (in Security status cells) | Applied / Configured |
must be (requirement context) | is a prerequisite for |
would enable | enables once configured |
should be | is expected to be |
needs to be | requires |
must be configured by | operator configures |
The security-hardening grep targets status cells only — Notes/Details cells with natural adjective use of these words are false positives. Use the safe labels above to avoid triggering the sweep.
Self-referential trap — WRONG vs CORRECT:
- ❌ WRONG: Notes cell says
Scanned for 'will' — 0 hits (re-embeds the banned word)
- ✓ CORRECT: Notes cell says
Future-tense gate: clean (functional abstraction)
- ❌ WRONG: Notes cell says
CONDITIONAL PASS when tool was simply absent (misclassification)
- ✓ CORRECT: Notes cell says
PASSED (skipped — tool unavailable) for absent tools
- ❌ WRONG: Notes cell says
no Known-Issues entries (re-embeds banned phrase)
- ✓ CORRECT: Notes cell says
all prior issue annotations verified closed
- ❌ WRONG: Notes cell says
no Required or Recommended found (re-embeds banned tokens)
- ✓ CORRECT: Notes cell says
all cells reflect completed-state language
- ❌ WRONG: Notes cell says
Scanned for will — 0 hits (quotes the banned word)
- ✓ CORRECT: Notes cell says
Future-tense gate: clean
Post-debugger documentation sync: After applying any code fix via debugger, update affected documentation (ENV_VARIABLES.md, INFRASTRUCTURE_REQUIREMENTS.md, TRANSFORMATION_SUMMARY.md) in the same pass — do not leave stale 'out-of-scope' annotations.
Refer to references/skill-b-containerisation-transformation.md for the full implementation steps. The 12-Point Mandatory Closure Gate defined there applies to ALL tasks without exception (including documentation-only tasks).
Tier 3 Validation Decision Gate
If validation tooling was not resolved in §0 Block B, determine Tier 3 cluster validation availability during Sub-Phase §1:
- Auto-detect: Check independently for the availability of Minikube, kind, k3s, and kwokctl. Check each separately to avoid masking individual absences.
- If detected: Tier 3 is available — proceed with cluster validation after Tier 1 passes (or immediately for KWOK).
- If NOT detected — attempt kwokctl download (30-second timeout). Check whether kwokctl is already cached locally before attempting a download.
- Prompt the user (30-second timeout; no response = N):
Tier 3 cluster validation (Minikube/kind/k3s/KWOK) was not auto-detected.
Would you like to run Tier 3 cluster validation? [y/N]
- In fully automated (CI) mode: default to skip, emit visible NOTICE, log decision.
- Record the decision in task report AND TRANSFORMATION_SUMMARY.md.
Split-task guidance: When kubeconform/KWOK are absent at manifest-generation time, do NOT retry downloads within that task — close with PASSED (tool unavailable — skipped) and create a dedicated validation task. When populating TRANSFORMATION_SUMMARY.md Three-Tier Validation table, always read prior task reports for tool results — tool availability is environment-transient; prior task results are canonical.
Reference Dispatch
| Signal | Reference |
|---|
| Phase 1 work | references/skill-a-readiness-analysis.md |
| Phase 2 work | references/skill-b-containerisation-transformation.md |
| Docker build validation (§17b) | references/docker-build-validation.md |
| Minimal Execution Set scope decisions | references/minimal-execution-set.md |
| Decomposition plan with ≥2 service candidates | references/microservice-decomposition-patterns.md |
| Validation patterns (YAML, banned-phrase, .bak) | references/validation-patterns.md |
| Credential audit (docker-compose, AWS SDK, URLs) | references/credential-audit-patterns.md |
| Go project (go.mod) | references/go-patterns.md |
| Node.js project (package.json) | references/nodejs-patterns.md |
| PHP project (composer.json) | references/php-patterns.md |
| Java/Maven/Gradle (pom.xml / build.gradle) | references/java-jvm-patterns.md |
| Python project (requirements.txt/pyproject.toml) | references/python-patterns.md |
| Ruby/Rails project (Gemfile) | references/ruby-rails-patterns.md |
| C#/.NET project (.csproj/.sln) | references/dotnet-patterns.md |
Mixed-language dispatch: If primary runtime differs from build-time toolchain (e.g., PHP app + Node.js asset build, Java app + Angular frontend), consult BOTH relevant language references.
Reference Procedures
The procedures below describe mechanical transforms and verification sweeps the worker performs on demand using standard shell commands. There are no executable scripts — the worker reads each procedure and issues the commands directly.
-
Pre-migration procedures run BEFORE any file-by-file migration work.
-
Post-batch procedures run AFTER each batch of related changes.
-
Post-migration procedures run AFTER all code changes are complete.
-
references/docker-build-validation.md — Three-tier validation pipeline: docker build, kubeconform, cluster. Includes Step 0 (Pre-Docker Native Compilation Gate for compiled languages), Tier 3 ask-before-skip protocol, kwokctl binary download, KWOK Operational Checklist, 00-namespace.yaml convention. When to run: post-batch (Tier 1). Patterns: pom.xml, build.gradle, go.mod, .csproj, Cargo.toml, package.json (with build script).
-
references/minimal-execution-set.md — Resource-type classification and scope decisions. When to run: pre-migration planning.
-
references/microservice-decomposition-patterns.md — Decomposition workflow and templates including Scope Comparison table. When to run: pre-migration and post-batch.
-
references/validation-patterns.md — Reusable YAML, banned-phrase, reconciliation, stale-claim procedures, grep tempfile pattern, grep robustness rules, and assertion battery template. When to run: post-batch and post-migration.
-
references/credential-audit-patterns.md — Credential audit Forms A–G, IRSA, Secret classification, credential-only field scope rule, cross-profile consistency check, scan-vs-modify scope boundary, external-service username rule, nounset-safe credential removal. When to run: pre-migration and post-batch.
-
references/go-patterns.md — Go: Pre-Docker Local Validation (go vet, go build, go test -short), viper, gRPC probes (including distroless native K8s grpc: probe type), S3 mock, GOMEMLIMIT, probe ordering, mise bootstrap (three-step activation), Dockerfile pitfalls. When to run: pre-migration and post-batch.
-
references/nodejs-patterns.md — Node.js: Pre-Docker Local Validation (node --check, npm ci, tsc --noEmit), connect-redis, ioredis, multer-s3, CronJob patterns, probe ordering, config-module audit, mise bootstrap (three-step activation), JSDoc cron hazard, jest.mock virtual, S3 migration cascade, NestJS probe path verification, lock file desync pre-check, package removal ordering, Dockerfile pitfalls (dead multi-stage detection, HEALTHCHECK start-period). When to run: pre-migration and post-batch.
Validation / Exit Criteria
Phase 1 Validation
- User was prompted for output location and format preference before analysis began (§0 Block A).
- All findings produced in a single consolidated report at the user-specified location.
- Report begins with a visual readiness scorecard (21 areas) with correct status icons.
- Executive summary table follows with severity counts and narrative paragraph.
- Every source file scanned against all 12 factors and additional analysis areas.
- All findings categorised as Blocker, Warning, or Informational with consistent emoji icons.
- Per-section findings in structured tables with file:line references verified via grep.
- Named Service Inventory table with all 11 mandatory columns included. Must include both Minimal Decomposition Recommendation and Full Decomposition Recommendation subsections.
- Singleton risk summary table included.
Phase 2 Validation (Criteria 1-13)
-
Every blocker finding addressed by code change, manifest, or infrastructure requirement. CronJob extraction sub-check: after extracting a scheduled task to a CronJob manifest, grep the primary Deployment source for the original scheduler trigger (e.g., cron.AddFunc, @Scheduled, APScheduler.add_job, cron.schedule) and assert it is absent or disabled.
-
All hardcoded config replaced with env var reads.
-
Session state is non-local and safe for horizontal scaling. Session verification gate: before adding Redis for sessions, grep for DB-backed session patterns.
-
All logging redirected to stdout/stderr.
-
Persistent filesystem usage replaced with appropriate object store or shared volume.
-
All hardcoded credentials removed; sourced from Kubernetes Secrets. Verify credential-only field scope: null/empty defaults applied ONLY to credential fields, not to region/endpoint/bucket.
-
Complete Kubernetes manifests generated in kubernetes/ (or k8s/) directory for the execution scope (per decomposition_scope). ⚠ Guard: ConfigMap data values must be strings; CronJob podSelector label must match spec.jobTemplate.spec.template.metadata.labels, not top-level metadata.labels.
-
Every main container in Deployment, Job, and CronJob manifests includes: resource requests/limits, probes, and complete security context. ⚠ Guard: For UID/capability exceptions by base image, see references/skill-b-containerisation-transformation.md §Security Context Edge Cases. Container-level securityContext MUST include ALL six fields: runAsNonRoot: true, runAsUser: <UID>, runAsGroup: <UID>, readOnlyRootFilesystem: true, allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}. Pod-level securityContext alone is insufficient — container-level fields MUST be repeated. Probe rules by workload type: (a) Init containers: no probes. (b) Job/CronJob WITH HTTP endpoint: startupProbe + livenessProbe (omit readiness). (c) Job/CronJob WITHOUT HTTP endpoint: exec livenessProbe only — use shell form ["/bin/sh", "-c", "kill -0 1"] (not standalone binary path). Distroless exception: omit ALL probes — use activeDeadlineSeconds (≤80% schedule interval). (d) Deployment main containers: all three probes. Headless workers: exec probes only. startupProbe first-boot sizing: failureThreshold: 30, periodSeconds: 10 (300s budget). : For applications with database migration tooling (Liquibase, Flyway, Alembic, Django migrations, ActiveRecord migrations), use failureThreshold: 60, periodSeconds: 10 (600s budget) — migration at startup requires a larger window. Always review timing observations from the readiness report before setting final values. : use DB-migration budget (failureThreshold: 60) as conservative default for any app with database migration tooling detected in source. : Verify probe path returns HTTP 2xx WITHOUT auth. For WAR/servlet apps, include deployment context path from Dockerfile HEALTHCHECK in the probe path. For NestJS, use registration paths in , NOT route paths.