Laravel Controller Behavior Map and Refactor Safety Plan
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.
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. ## 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] 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. ## 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. 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. 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. 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. ## 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. ## 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. 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. ## 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. 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.
Variables to Replace
- 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
How to Use This Prompt
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.
Example Use Case
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.