Source version 1.0.0
Published
Initial: Initial published snapshot.
Published version comparison
1.0.0 → 2.0.0
1.0.0Published
Initial: Initial published snapshot.
2.0.0Published
Major: Replace the legacy Laravel Controller Behavior Map and Refactor Safety Plan template with a domain-specific input, evidence, authority, safety, workflow, output, and verification contract.
Laravel Controller Behavior Map and Refactor Safety Plan
Laravel Controller Behavior Map and Refactor Safety Plan
Map a large Laravel controller, identify behavior and risk, design tests, and plan a safe refactor sequence for Codex.
Inspect a Laravel controller and its execution paths, establish evidence-backed behavioral invariants, design characterization tests, and produce an approval-gated extraction plan with concrete acceptance checks.
Use this for inspecting large Laravel controllers, protecting behavior, planning regression tests, and refactoring safely with Codex.
Use this prompt to analyze a complex Laravel controller, protect route and HTTP behavior, plan regression coverage, and prepare a safely scoped service or action extraction in Codex.
Large Laravel Controller Refactor Controller Behavior Mapping Regression Test Planning Route and Caller Impact Review Service or Action Extraction Production Risk Review
Behavior mapping for large Laravel controllers with routes, policies, model effects, and asynchronous side effects Characterization test planning before extracting Laravel actions, services, requests, queries, or resources Route, middleware, binding, authorization, validation, and response-contract impact review Risk-controlled refactor planning for tenant-aware, transactional, queued, or externally integrated controller flows Approval-gated Laravel controller edits and isolated regression verification in Codex
Target controller path Relevant route names or URLs Allowed files Out-of-scope files Known bug risks Existing tests Business-critical flows Database assumptions Preferred test command Refactor goal
Target controller path Repository context Laravel and PHP environment Relevant routes and callers Allowed files Out-of-scope areas Refactor goal Business-critical invariants Existing tests Runtime and data assumptions Preferred verification commands Authorized action mode
Paste this into Codex with the controller path, route context, existing tests, allowed files, out-of-scope areas, and refactor goal filled in. Ask Codex to inspect and produce the behavior map, test plan, and refactor sequence before making implementation edits.
Open Codex in the relevant Laravel repository or provide it with the necessary source files. Replace every bracketed variable, include route definitions, controller dependencies, tests, configuration, CI scripts, and runtime assumptions as task evidence, then run the prompt. Use inspect-and-plan mode unless a human has explicitly authorized scoped edits and isolated test execution.
A Laravel admin controller has grown to 900 lines and needs service extraction without changing validation, redirects, authorization, database writes, or permission behavior.
An admin controller handles validation, policy checks, tenant-scoped writes, event dispatch, queued notifications, and redirects across several actions. Codex traces those contracts, identifies transaction and after-commit risks, proposes HTTP characterization tests, and prepares an approval-gated action extraction without claiming unrun tests passed.
Expert
Expert
Codex
Codex
refactor
refactor
codex laravel controller-refactor regression-testing behavior-map routes safe-refactor php tests risk-reduction
codex laravel php controller-refactor behavior-mapping characterization-tests regression-testing route-analysis authorization safe-refactor
Laravel Controller Refactor Safety Prompt for Codex
Laravel Controller Refactor Safety Plan for Codex
Plan safe Laravel controller refactors with behavior mapping, risk analysis, regression tests, route checks, and Codex verification commands.
Map Laravel controller behavior, design regression tests, and plan approval-gated service or action extraction with evidence-based verification.
Removed Added Unchanged context
You are an expert Laravel engineer specializing in safe controller refactors, regression testing, and production-risk reduction. Inspect the supplied Laravel repository context and produce an evidence-backed controller behavior map, regression test design, and approval-gated refactor plan. Preserve observable behavior unless a requested change is explicitly identified. Your task is to inspect the target Laravel controller, map current behavior, identify refactor risks, design protective tests, and propose a safe refactor sequence before implementation. ## Inputs Replace every placeholder before running: - Target controller: [Target controller path] - Repository or supplied source context: [Repository context] - Laravel and PHP environment: [Laravel and PHP environment] - Relevant route names, URLs, or callers: [Relevant routes and callers] - Allowed files and directories: [Allowed files] - Explicitly excluded files or concerns: [Out-of-scope areas] - Requested controller outcome: [Refactor goal] - Behavior that must remain stable: [Business-critical invariants] - Existing relevant tests and known coverage gaps: [Existing tests] - Database, tenancy, queue, cache, and external-service assumptions: [Runtime and data assumptions] - Repository-approved verification commands or scripts: [Preferred verification commands] - Authorized action mode, either inspect-and-plan or edit-and-test: [Authorized action mode] ## Context Placeholders Use the context below. If a required placeholder is missing, ask for it before making risky recommendations. - [Target controller path] - [Relevant route names or URLs] - [Allowed files] - [Out-of-scope files] - [Known bug risks] - [Existing tests] - [Business-critical flows] - [Database assumptions] - [Preferred test command] - [Refactor goal] The blocking inputs are the target controller, accessible repository or supplied source, allowed scope, refactor goal, critical invariants, and authorized action mode. If one is absent or contradictory, stop before edits and return a Missing or Conflicting Inputs section. Route context, framework versions, tests, runtime assumptions, and verification commands may sometimes be derived from repository evidence; when they cannot be established, preserve them as unknowns and explain how that limits the plan. Never invent files, routes, schema, commands, test results, or runtime behavior. ## Important Constraints - Inspect before editing. Identify relevant files, callers, routes, tests, models, jobs, policies, middleware, config, and database assumptions where applicable. - Do not change unrelated files, public UI, data, generated assets, lockfiles, or out-of-scope areas unless the user explicitly asks. - Protect existing behavior. Prefer characterization tests or focused regression tests before risky implementation edits. - Respect allowed file scopes and mention any required files outside scope before touching them. - Avoid destructive commands such as git reset, git checkout, rm, database wipes, or production mutations. - Provide exact verification commands and explain what each command proves. - Distinguish confirmed code behavior from assumptions, likely causes, and recommendations. - If the controller returns views or API resources, inspect the related Blade files, resources, serializers, and frontend assumptions before recommending changes. ## Codex access and authority Use only files and command capabilities actually available in the Codex session. State whether each conclusion comes from supplied context, repository inspection, command output, or an explicit assumption. Do not imply access to production traffic, deployed configuration, databases, queues, observability systems, secrets, or external services unless evidence was supplied in the session. ## Step-by-Step Instructions 1. Inspect the controller, routes, request validation, models, services, jobs, policies, middleware, views or API resources, and current tests. 2. Create a behavior map covering inputs, branches, side effects, redirects, responses, authorization, validation, database writes, events, and external calls. 3. Identify risks, hidden coupling, missing tests, unclear ownership, and database or config assumptions. 4. Design focused characterization or regression tests before proposing implementation edits. 5. Produce a sequenced refactor plan with file scope, rollback notes, and exact verification commands. In inspect-and-plan mode, do not modify files or run commands that mutate application state. Read-only repository inspection and non-mutating discovery commands are permitted when available. In edit-and-test mode, edits and non-destructive tests are permitted only inside the allowed scope. Before touching a required file outside that scope, stop and request human approval with the file, reason, and consequence. ## Output Format ### Behavior Map Provide concise, specific, review-ready details. Never deploy, merge, push, alter production data, run migrations, refresh or wipe databases, clear shared caches, dispatch real jobs or notifications, call live third-party endpoints, rotate secrets, or use destructive Git or filesystem commands. Do not bypass authorization, weaken validation, expose sensitive data, or silently change route contracts. Database-writing tests require an isolated test environment confirmed by repository configuration or the user. Any schema change, route change, public response change, package change, or production operation is a separate approval point. ### Risk Register Provide concise, specific, review-ready details. Stop and escalate if secrets or personal data appear in output, the environment cannot be shown to be isolated, generated edits exceed allowed scope, baseline tests fail for unexplained reasons, required behavior conflicts across code and tests, or preservation would require a consequential change not authorized by the refactor goal. ### Test Plan Provide concise, specific, review-ready details. ## Inspection and behavioral analysis 1. Establish the controller's reachable surface. Trace route definitions, HTTP verbs, names, prefixes, middleware, domain constraints, parameter constraints, route model binding, scoped bindings, invokable methods, and direct callers. Note dead or apparently unreachable methods separately; do not assume they are safe to delete. 2. Trace framework and application collaborators for each action: Form Requests or inline validation, policies and gates, guards, middleware, models, relationships, global scopes, casts, accessors and mutators, observers, service-container bindings, services, actions, repositories, events, listeners, jobs, notifications, mail, storage, cache, sessions, feature flags, configuration, views, Blade components, API resources, serializers, and frontend response assumptions. 3. Map each execution branch from input to observable outcome. Include validated and unvalidated inputs, authorization order, model lookup and not-found behavior, transaction boundaries, reads and writes, mass assignment, soft deletes, locking, idempotency, event or observer effects, queued work and after-commit behavior, external calls, redirects, status codes, response bodies or resource shapes, headers, cookies, session flashes, validation error bags, pagination metadata, and exception handling. 4. Separate evidence classes: - Confirmed: directly supported by a cited file location or captured command output. - Inferred: strongly suggested by framework conventions or connected code but not executed. - Assumed: supplied by the user or required for planning but not independently established. - Unknown or conflicting: unavailable evidence or disagreement among routes, code, tests, configuration, and stated requirements. 5. Identify coupling and failure modes specific to extraction: changed middleware or policy timing; validation or exception changes; altered dependency resolution; lost transactions; duplicated queries or N+1 regressions; observer or event duplication; jobs dispatched before commit; changed redirect, flash, resource, pagination, or serialization behavior; route-binding differences; tenant or global-scope leakage; stale cache; non-idempotent retries; external side effects in tests; and behavior hidden in model hooks or service-provider bindings. ### Refactor Sequence Provide concise, specific, review-ready details. ## Test design Design the smallest protective characterization suite that covers the critical behavior and highest-risk branches. Prefer HTTP feature tests for the controller contract and focused unit tests only for extracted logic with a stable boundary. For each proposed test, specify the route or method, setup and isolation, actor and permissions, input, mocked or faked boundary, expected HTTP or domain result, expected database changes or non-changes, expected emitted or suppressed side effects, and the regression it detects. ### Verification Commands Provide concise, specific, review-ready details. Cover applicable happy paths and negative paths, including authentication, authorization, validation, missing models, scoped or tenant-bound records, transaction rollback, duplicate submission or retry behavior, event and queue behavior, external-service failure, redirects and flashes, JSON error envelopes, API resource fields, pagination, and unchanged records. Use Laravel fakes or mocks only at true process boundaries and explain what the fake cannot prove. Do not over-mock Eloquent or framework behavior that the characterization test is intended to protect. ## Verification - Confirm no unrelated files are included in the proposed edit scope. - Confirm existing behavior is protected before extraction or restructuring. - Separate confirmed behavior or evidence from assumptions. - List missing inputs, unresolved risks, and exact checks a human should complete before acting. ## Refactor design Propose seams based on observed responsibilities rather than controller size alone. Compare viable boundaries such as a Form Request for validation and authorization, an application action for one use case, a domain service for reusable domain rules, a query object for complex reads, a resource for response transformation, or a job for genuinely asynchronous work. Do not introduce layers without a demonstrated responsibility or test seam. ## Final Instruction to Begin Begin now. Inspect the supplied context first, ask for missing context if required, and then produce the full output in the requested markdown format. Sequence the work into reviewable increments: establish baseline evidence, add protective tests, introduce one seam, delegate without changing the route contract, verify, and only then remove duplication. For every increment, identify files, preserved invariants, expected diff shape, dependencies, risks, rollback method, approval requirement, and acceptance gate. A rollback must mean reverting the isolated increment through normal version control review; do not recommend destructive workspace commands. ## Verification rules Derive commands from repository evidence such as composer scripts, PHPUnit or Pest configuration, CI workflows, and project documentation. Do not guess a command merely because it is conventional. Prefer the narrowest relevant test command first, then the repository-approved broader suite and static analysis or formatting checks when configured. For every command, report its purpose, prerequisites, whether it was proposed or actually run, exit status when run, expected observation, actual observation when available, and evidence location. Never describe a test as passing unless the command ran and its output supports that claim. If execution is unavailable, label all checks Not run and provide them as a human verification handoff. Acceptance requires all of the following to be evidenced or explicitly unresolved: - Every reachable controller action and material branch is represented in the behavior map. - Critical invariants map to existing or proposed tests. - Route names, methods, middleware, binding, authorization, validation, status codes, redirects, response shapes, database effects, and side effects remain unchanged unless the refactor goal authorizes a difference. - Focused tests pass in an isolated test environment if execution was authorized. - Relevant broader tests and configured quality checks pass, or failures are reconciled as baseline, introduced, environmental, or unresolved. - The final file list stays within scope, and repository diff inspection shows no unexplained changes. - No migration, deployment, production operation, or public contract change is represented as approved without separate human authorization. ## Required deliverable Return these sections in order. ### 1. Intake and Authority Status State the action mode, available evidence, blocking omissions, conflicting inputs, allowed scope, prohibited actions, and whether analysis may proceed. Record any approval needed before edits or execution. ### 2. Reachability and Dependency Inventory Provide a table with controller method, route or caller, middleware and guard, binding, request validator, policy or gate, models and scopes, synchronous collaborators, asynchronous or external collaborators, response renderer, and evidence citation. ### 3. Branch-Level Behavior Map Provide one row per material branch with action and branch condition, inputs, authentication and authorization, validation, reads, writes and transaction boundary, events or observers, jobs or notifications, cache or external effects, response or redirect contract, failure behavior, evidence class, citation, and unresolved question. ### 4. Invariant Ledger List each behavior to preserve, its source, business impact, current protective test, proposed protection, and status as confirmed, inferred, assumed, unknown, or conflicting. ### 5. Coupling and Risk Register For each risk, identify the concrete coupling or failure mode, triggering refactor step, likelihood, impact, detection evidence, mitigation, rollback point, owner or approval needed, and residual risk. Rank risks rather than labeling all items high. ### 6. Characterization Test Matrix For each test, provide priority, route or method, branch protected, setup and isolation, actor and permission state, input, fake or mock boundary, expected response, expected database delta, expected side effects or non-effects, failure signal, and invariant covered. ### 7. Extraction Decision Record Describe current responsibilities, candidate seams, evidence supporting each seam, rejected alternatives, trade-offs, selected boundary, dependencies, transaction ownership, exception mapping, and why the choice preserves Laravel HTTP and domain behavior. ### 8. Approval-Gated Refactor Sequence For each increment, provide proposed files, exact change, preserved invariants, prerequisite tests, expected diff, verification gate, stop condition, approval point, and rollback method. Clearly separate proposed work from any authorized and executed work. ### 9. Verification and Acceptance Matrix Provide the command or manual check, evidence source, prerequisite, expected observation, execution state, actual observation, exit status, evidence reference, acceptance result, and failure classification. Include focused tests, relevant suite coverage, configured static analysis or formatting, route inspection when needed, and final diff and scope review. ### 10. Human Handoff Summarize decisions required, files requiring scope expansion, unresolved assumptions or conflicts, residual production risks, checks not run, and the exact next authorized step. Use one final state: Ready for human review, Blocked on input, Blocked on approval, or Verification incomplete. Do not claim that the controller was refactored, tested, verified, approved, merged, or deployed unless those actions occurred in the session and corresponding evidence is included.