# Safely Plan, Build, Review, and Release a High-Risk Laravel Feature

Workflow ID: AMO-W-000039
Workflow URL: https://amo.ng/workflows/safely-plan-build-review-and-release-a-high-risk-laravel-feature

## Outcome

A bounded, authorized Laravel implementation with repository evidence, applicable migration and feature-flag controls, actual verification results, independent change review and a human-owned release/rollback handoff. Planning is not implementation, and this Workflow does not itself authorize deployment.

## Before you begin

- Existing Laravel repository and any current repository instructions
- Approved feature requirements, acceptance criteria, and non-goals
- Affected routes, models, policies, queues, jobs, APIs, Blade views, and data migrations if known
- Production constraints such as deployment style, database engine, queue workers, cache behavior, and rollback limits
- Available test, lint, build, CI, staging, and monitoring evidence or commands

## Step 1 — Inspect repository instructions and agree the safety boundary

**Prompt**

Codex AGENTS.md Safety and Verification Instructions Generator

**Instructions**

Inspect existing repository instructions and supplied evidence first. Use the source to propose additions only if needed; do not overwrite existing AGENTS.md or unrelated work. Record protected paths, allowed commands and actual authority before editing.

**Input for this step**

Provide repository structure, existing contributor instructions, protected files, approved commands, forbidden operations, deployment constraints, and verification expectations.

**Carry forward**

Carry approved instructions, permissions, protected paths, verified commands and unresolved constraints into feature planning.

**Review note**

A maintainer approves the safety boundary and any instruction-file change before implementation. Unconfirmed commands remain unrun.

**Prompt ID**

AMO-P-000080

**Prompt URL**

https://amo.ng/prompts/codex-agents-md-project-instructions-generator

**Prompt content**

Create a copy-ready AGENTS.md that governs how Codex may inspect, modify, verify, and report work in this repository.

Project inputs
- Project name: [Project name]
- Project purpose: [Project purpose]
- Repository map: [Repository map]
- Tech stack and package managers: [Tech stack and package managers]
- Editable paths: [Editable paths]
- Protected paths: [Protected paths]
- Coding conventions: [Coding conventions]
- Verification commands: [Verification commands]
- CI, build, deployment, and cache commands: [CI build deployment and cache commands]
- Environment and secret-handling rules: [Environment and secret-handling rules]
- Known fragile areas: [Known fragile areas]
- High-risk operations and approval rules: [High-risk operations and approval rules]
- Definition of done: [Definition of done]
- Workflow preferences: [Workflow preferences]

Input and evidence rules
1. Treat the project name, purpose, repository map, editing boundaries, approval rules, and definition of done as required. A verification command may be unknown, but that unknown must be preserved explicitly.
2. Useful supporting evidence includes an accessible repository tree, an existing AGENTS.md, README files, package manifests and lockfiles, formatter or linter configuration, test configuration, framework configuration, CI workflow files, deployment documentation, and contributor guidance.
3. If Codex has repository access, it may perform read-only inspection of relevant files to ground the draft. It must not edit files, run commands, install dependencies, modify configuration, create commits, open pull requests, deploy, migrate data, clear production caches, rotate credentials, or publish anything while generating this document unless the user separately authorizes that action.
4. Distinguish each instruction or command source as owner-supplied, repository-observed, inferred, or unknown. Repository-observed means the exact value appears in inspected project evidence. Inferred content must be labeled for owner review and must not be presented as established fact.
5. Never expose or reproduce secrets, tokens, private keys, credentials, customer data, or sensitive environment values. Refer only to environment variable names or redacted examples when necessary.
6. Do not invent commands, path permissions, deployment procedures, rollback steps, or approval authority. When a required fact is missing or conflicting, ask a focused clarification question if it blocks a safe boundary. Otherwise, produce a bounded draft with a clearly marked owner decision item.
7. If an existing AGENTS.md is present, do not silently replace its instructions. Compare it with the supplied requirements, identify conflicts and scope differences, and produce a proposed consolidated draft plus a short change summary.
8. Account for AGENTS.md scope: repository-root instructions establish the default, while a more specific AGENTS.md in a descendant directory may refine instructions for that subtree. Do not claim that repository instructions override system, platform, user, security, or organizational policy.

Drafting workflow
1. Inspect the supplied evidence and identify the repository architecture, package managers, generated artifacts, test layers, CI entry points, deployment-sensitive files, migration paths, caches, and security boundaries that are actually evidenced.
2. Reconcile editable and protected paths. A protected path takes precedence when lists overlap. Mark ambiguous, missing, generated, vendored, lockfile, schema, infrastructure, credential, and production configuration boundaries for owner review.
3. Convert coding conventions into actionable rules tied to the actual stack, such as formatting, static analysis, dependency policy, framework conventions, database migration practices, backward compatibility, generated-file handling, and test placement. Include only applicable rules.
4. Build a workflow that requires Codex to inspect before editing, state its intended files and approach, keep changes within scope, preserve unrelated work, make the smallest coherent change, and stop when repository state or instructions conflict.
5. Build a command matrix from owner-supplied or repository-observed commands. Separate fast targeted checks from broader tests, linting, static analysis, builds, integration tests, and release checks. Never imply that a command was executed merely because it appears in AGENTS.md.
6. Define approval gates for consequential operations. Deployment, production access, destructive database operations, irreversible migrations, dependency upgrades with broad impact, secret handling, force pushes, history rewrites, cache clearing in shared environments, external communications, and deletion of user or production data must require explicit human authorization when applicable.
7. Define stop conditions and recovery controls. Codex must stop on suspected secret exposure, unexpected destructive output, permission uncertainty, failing preconditions, unrelated repository changes, ambiguous environment targets, unavailable rollback paths, or a verification failure that makes further action unsafe.
8. Define truthful reporting states so future Codex sessions keep proposed, changed, executed, passed, failed, blocked, skipped, unavailable, and unverified work distinct.

Required AGENTS.md structure
Return the complete file in one Markdown code block using these sections:

# Project Instructions
State the project purpose, relevant architecture, primary stack, and the evidence basis for the instructions.

## Instruction Scope and Precedence
Explain repository-root and descendant-directory scope, conflict handling, and the precedence of system, platform, organizational, security, and explicit user instructions.

## Repository Map
Describe important source, test, configuration, generated, vendor, migration, infrastructure, and documentation locations that are supported by evidence. Mark unknown locations rather than guessing.

## Change Authority Matrix
Provide a table with columns for path or resource, allowed action, prohibited action, approval required, evidence source, and notes. Cover editable paths, protected paths, generated files, dependencies, database schemas or migrations, CI configuration, deployment configuration, secrets, and production data when applicable.

## Coding and Change Rules
Specify stack-relevant conventions, dependency and lockfile policy, generated-file policy, migration compatibility requirements, security expectations, scope control, and treatment of unrelated changes.

## Required Work Sequence
Define the inspect, clarify, plan, edit, verify, review, and report sequence. Require Codex to name intended files before editing and to pause when the requested work exceeds authority.

## Verification Matrix
Provide a table with columns for change type, exact command, source, execution authority, expected successful observation, failure handling, and unavailable-command fallback. Include targeted tests, broader tests, linting, formatting, static analysis, builds, and relevant CI or release checks only when applicable. Unknown commands must remain explicit owner action items.

## High-Risk and Production Operations
List applicable approval gates, environment confirmation requirements, backup or rollback prerequisites, dry-run expectations, monitoring or post-change checks, and stop conditions. State that documentation of a command is not authorization to execute it.

## Security and Data Handling
Cover secret redaction, least privilege, sensitive logs, personal or production data, dependency provenance, and incident escalation appropriate to the supplied project.

## Definition of Done
Translate the supplied definition into observable acceptance criteria. Require scope reconciliation, applicable verification evidence, documentation updates where needed, no unauthorized protected-path changes, and disclosure of unresolved failures or skipped checks.

## Completion Report Contract
Require future Codex sessions to report changed files, concise change summary, commands actually executed, actual outcomes, checks not run and why, assumptions, residual risks, approval-dependent actions, and recommended human follow-up. Prohibit claims such as fixed, tested, verified, approved, deployed, rolled back, or completed unless the corresponding action occurred and evidence is available.

After the code block, provide these companion sections:

## Evidence and Decision Register
Use a table with columns for item, classification, source, confidence, conflict or gap, and owner action. Classifications must distinguish supplied fact, repository observation, inference, unknown, and conflict.

## Owner Review Checklist
Include concrete checks for path scope, command accuracy, nested AGENTS.md behavior, secret safety, approval ownership, destructive operations, rollback readiness, verification expectations, and definition-of-done acceptance.

## Proposed Change Summary
If an existing AGENTS.md was inspected, summarize retained, changed, added, and unresolved instructions. Otherwise state that this is a new proposed file.

Final validation
- Confirm every project-specific statement is traceable to supplied or inspected evidence, or is labeled as an inference or unknown.
- Confirm protected paths override editable paths where they overlap.
- Confirm every command is exact and sourced, or explicitly unknown.
- Confirm command documentation and command execution authority are separate.
- Confirm consequential actions require the stated human approval and applicable recovery controls.
- Confirm no secret values or sensitive data are included.
- Confirm acceptance criteria are observable and unresolved states remain visible.
- Confirm no execution, test, approval, deployment, rollback, or completion claim is made without actual evidence.
- Confirm the AGENTS.md is internally consistent and copy-ready, while remaining a proposal until the project owner reviews and installs it.


## Step 2 — Plan the bounded feature and acceptance evidence

**Prompt**

Codex Evidence-Grounded Long-Horizon Feature Build Planner

**Instructions**

Run the source in planning/read-only mode. Map affected behaviour, dependencies, public contracts, test evidence and rollback. Do not treat the plan as permission to implement, migrate or deploy.

**Input for this step**

Provide the approved feature requirements, repository instructions, acceptance criteria, architectural context, expected data changes, operational constraints, and risk areas.

**Carry forward**

Carry the approved plan, authorized files/commands, proposed migration diff where available, verification cases and rollback constraints into safety review.

**Review note**

Engineering approves scope, acceptance criteria, mutation permissions and consequential design decisions. Missing authority blocks implementation.

**Prompt ID**

AMO-P-000083

**Prompt URL**

https://amo.ng/prompts/codex-long-horizon-feature-build-planner

**Prompt content**

Develop an evidence-grounded plan for the following long-horizon feature change.

## Change inputs
Feature goal: [Feature goal]
Repository context and architecture: [Repository context and architecture]
Current and expected behavior: [Current and expected behavior]
Scope and non-goals: [Scope and non-goals]
Relevant paths: [Relevant paths]
Technical constraints: [Technical constraints]
Data and migration requirements: [Data and migration requirements]
Interface and integration requirements: [Interface and integration requirements]
Access and security requirements: [Access and security requirements]
Operational requirements: [Operational requirements]
Verification commands and environments: [Verification commands and environments]
Release and rollback policy: [Release and rollback policy]
Definition of done: [Definition of done]
Codex authorization mode: [Codex authorization mode]

## Operating boundaries
Use the authorization mode to determine what Codex may do:
- Plan-only: analyze supplied material without changing files or running commands.
- Inspect-and-plan: inspect accessible repository files and read-only project state, then produce the plan.
- Execute approved phases: inspect first and modify or run commands only within the explicitly approved phase and accessible environment.

Do not assume repository, shell, network, database, CI, deployment, monitoring, or production access. State which capabilities are available and which are unavailable. Never invent file contents, command results, test outcomes, approvals, deployments, or production observations.

Require human authorization before destructive migrations, data mutation, credential or permission changes, external side effects, dependency upgrades with broad impact, deployment, rollback, or production operations. Do not expose secrets, tokens, personal data, or sensitive configuration. Stop and request direction if a proposed action could cause irreversible data loss, security exposure, an uncontrolled outage, or work outside the approved scope.

## Input and uncertainty rules
Treat the feature goal, observable current behavior, expected behavior, repository or source snapshot, applicable constraints, definition of done, and authorization mode as blocking inputs for an implementation-ready plan. If one is missing or materially conflicting, ask the smallest set of clarifying questions needed for safe progress. You may still provide a bounded preliminary plan, but mark affected decisions as blocked.

Treat architecture diagrams, issue history, traffic profiles, incident records, API specifications, schema documentation, deployment runbooks, and monitoring details as useful optional context. Do not infer them as facts when absent.

Classify important statements as one of:
- Supplied fact: stated in the inputs but not independently confirmed.
- Observed: confirmed from an accessible file, symbol, configuration, schema artifact, or command result; cite the path and symbol, line range, command, or artifact.
- Assumption: a bounded premise needed to continue; explain its effect and how to validate it.
- Hypothesis: a possible explanation or design implication requiring inspection or testing.
- Unknown: information not available.
- Conflict: incompatible evidence or requirements requiring reconciliation.

Prefer repository evidence over convention. If the repository differs from the supplied description, record the discrepancy rather than silently choosing one account.

## Planning workflow

### 1. Establish the evidence baseline
- Record the repository revision, branch, working-tree state, environment, accessible tools, and authorization mode when observable.
- List supplied artifacts and inspected artifacts separately.
- Identify blocking gaps, conflicting requirements, and any uncommitted changes that must not be overwritten.

### 2. Trace current behavior
Inspect relevant entry points and follow the behavior through routes or commands, middleware, validation, authorization, controllers or handlers, services, domain logic, persistence, events, queues, caches, templates or clients, integrations, and observability hooks. Cite concrete files and symbols for observed behavior.

For Laravel repositories, inspect applicable routes, middleware, Form Requests, policies and gates, controllers, service or action classes, Eloquent models and relationships, casts and scopes, migrations, jobs and listeners, scheduler entries, cache usage, Blade, Livewire or Inertia surfaces, API resources, service providers, configuration, and PHPUnit or Pest tests. Include only components that exist or are supported by evidence.

Map callers, callees, state transitions, data ownership, transaction boundaries, synchronous and asynchronous side effects, public contracts, compatibility assumptions, and existing tests. Flag dead paths, duplicated behavior, hidden coupling, and uncertain runtime behavior without presenting them as confirmed defects.

### 3. Analyze change impact and design choices
- Compare current and expected behavior using explicit scenarios, actors, permissions, inputs, state transitions, outputs, side effects, and failure responses.
- Identify affected API, event, queue, database, UI, cache, configuration, and observability contracts.
- Present viable design options where material trade-offs exist. Compare complexity, compatibility, operability, performance, security, reversibility, and testability, then recommend one with evidence and assumptions.
- Prefer localized changes. Justify every broad refactor, dependency addition, public contract change, or abstraction.

For schema or data changes, assess nullability, defaults, indexes, uniqueness, foreign keys, lock duration, table size, transaction behavior, replication effects, backfill cost, resumability, idempotency, mixed-version compatibility, and downgrade limitations. Use expand-migrate-contract or another justified compatibility strategy when zero-downtime delivery is required. Do not label a migration reversible merely because a down method exists; explain whether rollback would preserve data.

For asynchronous or integrated behavior, assess duplicate delivery, ordering, retries, timeouts, idempotency keys, poison messages, partial failure, rate limits, webhook verification, contract versioning, and reconciliation.

For access and security, assess authentication, authorization at every entry point, tenant isolation, input validation, mass assignment, injection, CSRF where applicable, sensitive logging, secret handling, file access, and abuse or privilege-escalation paths.

### 4. Build gated implementation phases
Create the smallest coherent phases that preserve deployability and existing behavior. Each phase must specify:
- Objective and user-visible effect.
- Preconditions and required approval.
- Exact files and symbols to inspect, add, or modify, with a justification.
- Schema, code, configuration, dependency, interface, and observability changes.
- Compatibility strategy for old and new application versions.
- Tests and commands to run.
- Expected observations and evidence to retain.
- Failure signals, stop conditions, and recovery action.
- Exit gate before the next phase.

Separate preparation, compatibility scaffolding, data migration or backfill, behavior activation, cleanup, and contract removal when those operations carry different risks. Use feature flags or staged rollout only when their lifecycle, default state, ownership, monitoring, and removal plan are defined.

### 5. Design verification and acceptance
Build a verification matrix covering applicable unit, feature, integration, contract, authorization, migration, regression, concurrency, queue, cache, UI, performance, and security checks. Include negative and boundary cases, not only the happy path.

For every check, provide the requirement or risk covered, setup, command or manual procedure, expected observation, actual observation if executed, evidence location, and status. Valid statuses are proposed, unavailable, blocked, failed, passed, and not applicable. Use passed only when the check actually ran successfully and supporting evidence exists. If execution did not occur, actual observation must say not observed.

Reconcile verification results against the definition of done. A failing, blocked, unavailable, or contradictory check remains unresolved and must have an owner or decision before acceptance.

### 6. Plan release, monitoring, and recovery
Define deployment order, migration timing, worker or scheduler coordination, cache and configuration handling, health checks, canary or staged rollout where justified, relevant metrics and logs, alert thresholds, observation period, and rollback decision authority.

Distinguish code rollback, feature disablement, forward fix, schema rollback, and data restoration. Document recovery point limitations, irreversible transformations, backup or restore prerequisites, backfill cancellation behavior, and how partially processed records will be reconciled.

### 7. Execute only when authorized
If execution is authorized, work one approved phase at a time. Before each phase, show its scope, commands, side effects, and stop conditions. Preserve unrelated changes. After the phase, report changed files, command results, evidence, deviations, and unresolved issues, then wait for approval when the next phase is consequential.

Do not say fixed, tested, verified, approved, deployed, rolled back, or complete unless that action occurred in the accessible environment and evidence is recorded. Keep planned work, inspected findings, executed changes, unavailable checks, and human approvals visibly separate.

## Required deliverable

### A. Capability and Evidence Ledger
Provide repository state, authorization mode, available and unavailable capabilities, supplied artifacts, inspected artifacts with citations, assumptions, unknowns, conflicts, and blocking questions.

### B. Current-to-Target Behavior Matrix
Use columns for scenario, actor or permission, current behavior and evidence, target behavior, affected contracts, side effects, edge cases, and unresolved questions.

### C. Architecture and Dependency Trace
Describe entry points, call paths, state transitions, transaction boundaries, data stores, queues, caches, integrations, user interfaces, and observability. Cite files and symbols for observations.

### D. Design Decision Record
For each material decision, provide options considered, evidence, assumptions, trade-offs, recommendation, rejected alternatives, compatibility impact, and approval required.

### E. File and Contract Change Manifest
Use columns for phase, path and symbol, change type, intended modification, justification, dependent contracts, compatibility concern, and test coverage. Do not list speculative paths as confirmed files.

### F. Phased Implementation Plan
Provide phase objectives, prerequisites, approvals, ordered implementation steps, migration or rollout strategy, verification gate, failure signals, stop conditions, recovery procedure, and handoff state.

### G. Risk and Control Register
Use columns for failure mode, trigger or cause, affected users or systems, likelihood, impact, detectability, preventive control, detection signal, mitigation or recovery, owner, phase, and residual risk. Include applicable data-loss, authorization, compatibility, race-condition, migration-lock, queue-duplication, cache-staleness, integration, performance, and deployment risks.

### H. Verification and Acceptance Matrix
Use columns for requirement or risk, test level, setup, command or procedure, expected observation, actual observation, evidence, status, and follow-up owner. Clearly separate proposed checks from executed checks.

### I. Release, Monitoring, and Rollback Runbook
Specify release sequence, approval points, feature-flag state, migration and backfill coordination, worker handling, health checks, metrics, logs, thresholds, observation window, rollback triggers, recovery path, and irreversible limitations.

### J. Definition-of-Done Reconciliation
For each supplied completion criterion, report its evidence, status, unresolved gap, and acceptance authority. End with one handoff state: ready for human review, blocked pending information, ready for an approved implementation phase, or executed with unresolved verification. Do not imply approval or completion from the handoff state alone.


## Step 3 — Review applicable migration and backfill safety

**Prompt**

Zero-Downtime Laravel Migration Review

**Instructions**

Review proposed migration/schema changes before their execution, against the actual database engine and operational evidence. If no schema/data change is needed, record a reasoned Not applicable. Missing migration evidence for an applicable change remains a blocker. Revisit this gate if implementation changes the migration plan.

**Input for this step**

Provide migration files or proposed migration design, database engine details, table sizes if known, deployment topology, queue-worker behavior, backfill approach, and rollback constraints.

**Carry forward**

Carry approved migration conditions or the justified Not-applicable record, rollout compatibility, stop criteria and unresolved blockers into rollout planning.

**Review note**

Database and release owners approve applicable data-changing plans, rehearsal and recovery gates; no production migration is executed here.

**Prompt ID**

AMO-P-000110

**Prompt URL**

https://amo.ng/prompts/zero-downtime-laravel-migration-review

**Prompt content**

Review the proposed Laravel schema and data migration change set for zero-downtime feasibility and production safety using Codex and the actual repository.

Use only repository content, database evidence, command output, and operational facts that are supplied or genuinely accessible in the current Codex workspace.

## Required inputs

- Repository and change set: [Repository and change set]
- Framework and database versions: [Framework and database versions]
- Production schema evidence: [Production schema evidence]
- Workload and table evidence: [Workload and table evidence]
- Deployment topology and compatibility window: [Deployment topology and compatibility window]
- Backfill and recovery constraints: [Backfill and recovery constraints]
- Operational limits and approvals: [Operational limits and approvals]
- Acceptance evidence: [Acceptance evidence]

The repository and change-set input should identify, where relevant:

- the exact release, commit, branch, or diff under review;
- migration files;
- raw SQL;
- related models and casts;
- accessors and mutators;
- validation rules;
- services and query builders;
- controllers and API resources;
- jobs and queue payloads;
- events and listeners;
- scheduled commands;
- factories and seeders;
- tests;
- feature flags;
- application deployment order.

Production schema evidence should include, where available:

- current columns and data types;
- defaults;
- nullability;
- indexes;
- constraints;
- foreign keys;
- generated columns;
- approximate row counts;
- duplicate, null, orphan, or invalid-data counts;
- relevant database metadata;
- observed schema drift.

Workload and table evidence should describe, where available:

- read and write rates;
- transaction duration;
- long-running transactions;
- high-traffic periods;
- table growth;
- replica use and acceptable lag;
- connection pooling;
- lock or statement timeouts;
- queue throughput;
- scheduled workloads;
- disk, transaction-log, or WAL constraints.

Deployment topology should identify:

- environments;
- promotion order;
- application instances;
- queue workers;
- scheduled processes;
- deployment strategy;
- mixed-version window;
- maintenance constraints;
- maximum acceptable interruption or degradation.

Backfill and recovery constraints should identify:

- whether data transformation is required;
- acceptable batch and runtime limits;
- retry and resume requirements;
- backup scope and freshness;
- restore evidence;
- rollback and roll-forward expectations;
- data-loss tolerance.

Operational limits and approvals should state:

- permitted read-only inspection;
- permitted local commands;
- whether file edits are permitted;
- prohibited actions;
- production-access restrictions;
- database-owner and release-owner responsibilities;
- required human approval gates.

Acceptance evidence should define the observable conditions required before:

- rehearsal;
- schema expansion;
- backfill;
- read switching;
- constraint validation;
- contract work;
- cleanup;
- production completion.

## Zero-downtime standard

Do not interpret “zero downtime” as a literal guarantee of zero locks, zero latency change, or zero operational impact.

Evaluate zero-downtime feasibility against the supplied service objectives and acceptance constraints, including:

- permitted service interruption;
- acceptable latency or error-rate change;
- write availability;
- queue delay;
- replica lag;
- maintenance allowance;
- user-visible degradation;
- compatibility requirements.

If those thresholds are not supplied, mark zero-downtime feasibility as unverified. Do not invent an acceptable outage or degradation threshold.

## Input and evidence rules

1. Begin with an input-status table. Classify every required input as:

   - supplied;
   - observed in the accessible workspace;
   - missing;
   - ambiguous;
   - conflicting;
   - not applicable.

2. Bind all material evidence to the exact release under review where possible. Record:

   - commit, revision, or diff;
   - migration filename and identifier;
   - database engine and version;
   - target environment;
   - schema snapshot date;
   - workload measurement window;
   - command or rehearsal timestamp;
   - artifact or output identity.

   Evidence from another commit, migration set, database version, schema state, environment, or execution window is not automatically evidence for this release.

3. Cite repository findings using available file paths, line ranges, classes, methods, migration names, or symbols.

4. Cite operational findings by naming the supplied:

   - schema snapshot;
   - command output;
   - metric;
   - query result;
   - runbook;
   - deployment record;
   - backup record;
   - rehearsal artifact;
   - user statement.

5. Label every material statement as one of:

   - confirmed;
   - inferred;
   - assumed;
   - unknown;
   - conflicting.

   Never convert an assumption or generic database practice into a confirmed finding.

6. If migration files are unavailable, stop after listing the exact migrations and related code required. Do not issue a deployment or zero-downtime decision.

7. If the database engine or exact version is missing or conflicting, do not make engine-specific claims about:

   - locking;
   - online DDL;
   - table rewrites;
   - transactional behavior;
   - concurrent index creation;
   - instant or in-place alterations.

   Request authoritative version output.

8. If table size, write load, production schema, long-running transactions, or deployment topology is unknown, mark lock duration and zero-downtime feasibility unknown. Do not automatically classify the operation as safe or unsafe.

9. Reconcile repository migrations with the actual production schema.

   Production schema evidence governs operational risk. Repository history remains evidence of intended state.

   Unexplained schema drift is a release blocker.

10. Distinguish clearly:

    - requested work;
    - proposed edits or commands;
    - executed checks;
    - supplied execution evidence;
    - unavailable checks;
    - unverified results.

    A command is executed only when Codex actually runs it in an authorized environment and captures its result.

    Command output supplied by the user is supplied evidence, not independently reproduced evidence.

11. Do not invent:

    - row counts;
    - batch sizes;
    - operation duration;
    - lock duration;
    - throughput;
    - replica lag;
    - backup validity;
    - restore success;
    - database behavior;
    - test output;
    - deployment success.

12. When a numerical recommendation cannot be supported, provide a calibration method or bounded range instead of false precision.

## Codex authority boundaries

Unless [Operational limits and approvals] explicitly restricts it, permit:

- read-only repository inspection;
- inspection of supplied schema metadata;
- non-mutating local diagnostics;
- review of existing test and deployment configuration.

Treat the following as unauthorized unless expressly approved:

- file edits;
- mutating commands;
- dependency changes;
- database writes;
- migrations;
- backfills;
- destructive SQL;
- production queries;
- load tests;
- cache or queue changes;
- deployments;
- rollbacks;
- external-service changes.

Even where local edits are authorized, do not execute:

- production migrations;
- production backfills;
- destructive SQL;
- production rollback commands;
- deployment;
- DNS or infrastructure changes.

Production execution, restore decisions, destructive changes, and release approval remain human-controlled actions.

Do not expose credentials, connection strings, customer records, personal data, payment data, or confidential production rows. Request redacted schema metadata, aggregate counts, and sanitized samples.

If repository edits are separately authorized, make only the smallest reviewable changes required to reduce migration risk. Keep applied changes separate from proposed but unapplied work.

## Focused review workflow

### 1. Establish the release identity and review scope

Record:

- release or commit identity;
- migration files;
- related application components;
- target database engine and version;
- target environment;
- deployment strategy;
- compatibility window;
- maintenance limits;
- supplied acceptance criteria.

State explicitly what Codex inspected and what remained unavailable.

### 2. Reconcile the migration surface

Inventory every `up` and `down` operation and every raw SQL statement.

For each operation, identify:

- migration file and location;
- table or relation;
- columns;
- data types;
- defaults;
- nullability;
- generated values;
- indexes;
- uniqueness rules;
- foreign keys;
- check constraints;
- data transformations;
- application dependencies.

Trace old and new schema names through:

- models;
- casts;
- accessors and mutators;
- validation;
- services;
- queries;
- API resources;
- events and listeners;
- queue payloads;
- scheduled work;
- reports;
- imports and exports;
- factories and seeders;
- tests.

Flag behavior dependent on:

- Laravel version;
- database driver;
- doctrine/dbal;
- database-server version;
- migration configuration;
- transactional DDL support.

Do not infer the current production schema solely from migration history.

### 3. Analyze database-engine behavior

For MySQL or MariaDB, assess the supplied version and operation against applicable:

- instant, in-place, or table-copy behavior;
- metadata-lock acquisition;
- index-build concurrency;
- implicit commits;
- foreign-key checks;
- generated-column behavior;
- default-expression support;
- row format;
- online-DDL options;
- replica effects.

Treat `ALGORITHM`, `LOCK`, online DDL, or similar clauses as proposals until their support is validated against the exact engine and version.

Identify long transactions that could delay metadata locks.

For PostgreSQL, assess:

- catalog-only versus table-rewrite behavior;
- required lock level and likely duration;
- transaction boundaries;
- `CREATE INDEX CONCURRENTLY`;
- `DROP INDEX CONCURRENTLY`;
- invalid indexes after failure;
- `NOT VALID` constraints;
- later constraint validation;
- default-value behavior;
- type-change rewrites;
- long-running transactions;
- dead tuples;
- WAL growth;
- replica lag.

Identify where Laravel migration transaction behavior conflicts with concurrent operations.

For another engine, limit conclusions to documented behavior supported by supplied evidence.

SQLite development success is not evidence that a MySQL, MariaDB, or PostgreSQL production migration is safe.

Do not recommend an external online-schema-change tool unless its suitability, operational ownership, constraints, and approval requirements have been evaluated separately.

### 4. Analyze operation-specific failure modes

If this is a prospective review, analyze credible migration failure modes without pretending a failure has already occurred.

If an actual migration has failed, reconstruct the failure using supplied evidence and establish root cause only where the causal chain is supported.

Check for:

- non-null additions before compatible writes and backfill completion;
- expensive defaults or table rewrites;
- in-place type changes;
- truncation;
- collation or encoding changes;
- lossy casts;
- renames or drops while old code still uses the schema;
- unique indexes before duplicate and null-semantics checks;
- foreign keys before orphan and supporting-index review;
- cascade effects;
- indexes that do not match observed query predicates or ordering;
- blocked writes;
- metadata-lock queues;
- statement or lock timeouts;
- disk or temporary-space pressure;
- transaction-log or WAL growth;
- replica lag;
- failover exposure;
- schema and data changes combined into one irreversible unit;
- unbounded updates;
- offset-based backfills;
- mutable pagination keys;
- hot-row contention;
- retries that duplicate effects;
- queue flooding;
- `down` methods that destroy data or restore structure without restoring meaning;
- migration ordering and timestamp collisions;
- environment-dependent migrations;
- non-idempotent raw SQL;
- mixed-version incompatibility.

A migration `down` method is not, by itself, a complete rollback or recovery plan.

### 5. Evaluate mixed-version compatibility

Determine whether old and new application versions can coexist with the intermediate schema.

Include:

- web processes;
- API processes;
- queue workers;
- delayed jobs;
- scheduled commands;
- reports;
- exports;
- integrations;
- external consumers.

Check:

- reads from old and new columns;
- writes to old and new columns;
- dual-write behavior;
- default and null handling;
- serialized queue payloads;
- cache-key or serialization changes;
- deployment and worker restart order;
- feature-flag ownership and defaults.

Do not allow contract work while old application or worker versions may still depend on the old schema.

### 6. Determine the compatible release sequence

For every risky change, decide whether it requires:

1. expand;
2. compatibility code;
3. dual write;
4. backfill;
5. reconciliation;
6. read switch;
7. constraint validation;
8. contract;
9. cleanup.

For every phase, define:

- compatible application versions;
- compatible worker versions;
- required entry evidence;
- proposed action;
- monitoring signals;
- pause conditions;
- acceptance criteria;
- recovery path;
- approval gate.

Use feature flags only where ownership, default state, rollback behavior, and removal criteria are supplied or explicitly proposed.

### 7. Design a controlled backfill

Do not place a large backfill inside a schema migration.

When a backfill is required, specify:

- a versioned Artisan command, controlled job, or reviewed script;
- stable keyset batching;
- candidate batch-size range;
- staging calibration method;
- transaction scope;
- idempotency predicate or key;
- throttling signal;
- checkpointing;
- progress metrics;
- retry behavior;
- pause and resume behavior;
- failed-record quarantine;
- observability;
- termination criteria.

Base numerical recommendations on supplied measurements. Otherwise mark them for calibration.

Define reconciliation using:

- candidate count;
- processed count;
- success count;
- skipped count;
- failure count;
- remaining count;
- invariant checks.

Unexplained differences must block progression.

### 8. Design rollback and forward recovery

Separate:

- application rollback;
- schema rollback;
- backfill pause;
- backfill reversal;
- data restoration;
- forward-compatible recovery.

Prefer forward recovery when:

- a destructive `down` method would lose data;
- old code cannot operate against the new schema;
- a partial backfill has changed business meaning;
- contract work has already removed compatibility.

Identify:

- the last reversible phase;
- failure indicators;
- immediate safe response;
- data-loss exposure;
- backup dependencies;
- restore dependencies;
- partial-failure handling;
- approval gates;
- evidence required before resuming.

A backup claim is insufficient without evidence of:

- scope;
- freshness;
- retention;
- encryption handling;
- access;
- restore testing appropriate to the change.

### 9. Define verification and acceptance evidence

Propose repository-appropriate checks. Do not imply that SQL generation or `migrate --pretend` proves online execution safety.

Where applicable, include:

- migration-operation reconciliation;
- production-schema reconciliation;
- generated-SQL review;
- engine-supported DDL validation;
- duplicate checks;
- orphan checks;
- null and range checks;
- truncation and cast-failure checks;
- representative query plans;
- old-version application tests;
- mixed-version tests;
- new-version tests;
- queue-worker compatibility tests;
- production-like rehearsal;
- lock-wait observations;
- blocked-session observations;
- disk and temporary-space observations;
- transaction-log or WAL growth;
- replica-lag observations;
- backfill reconciliation;
- post-phase schema and data checks;
- rollback or forward-recovery rehearsal.

For every proposed command or query, state:

- purpose;
- target environment;
- expected observation;
- failure meaning;
- safety caveat;
- work state: proposed, executed, supplied, unavailable, or unverified.

Avoid production-wide scans unless an authorized operator confirms:

- acceptable execution plan;
- timeout;
- replica or primary target;
- impact window;
- cancellation method.

## Risk classification

Use only these qualitative states:

- Critical — credible risk of data loss, corruption, prolonged outage, irreversible change, uncontrolled production impact, or a release state from which neither old nor new code can recover safely.

- High — material lock, availability, compatibility, integrity, backfill, rollback, or recovery risk requiring correction or explicit evidence before progression.

- Medium — a meaningful but controllable risk requiring defined safeguards, monitoring, ownership, or a phased release condition.

- Low — evidence supports limited blast radius and acceptable behavior within the supplied operational constraints.

- Unknown — available evidence is insufficient to classify the risk defensibly.

Do not rate a risk Low solely because the migration is small, passes locally, or uses a familiar Laravel schema method.

## Output contract: zero-downtime migration review deliverable

Keep the report concise and proportional to the migration scope, risk, and available evidence.

Do not repeat the same evidence or limitation across multiple sections. Use operation IDs, finding IDs, and evidence IDs for cross-reference.

Where a subsection is genuinely not applicable, retain the heading, state `Not applicable`, and explain briefly why.

Never omit:

- evidence and coverage;
- schema-operation register;
- blockers;
- compatibility analysis;
- recovery;
- verification;
- release decision.

### A. Review basis and evidence coverage

Report:

- exact release identity;
- target environment;
- database engine and version;
- migration files and related code inspected;
- unavailable materials;
- supplied, observed, missing, ambiguous, and conflicting inputs;
- zero-downtime acceptance definition;
- review limitations.

### B. Schema-operation register

For every operation provide:

- operation ID;
- migration and location;
- generated or intended DDL;
- affected object;
- data touch;
- engine and version dependency;
- expected lock or rewrite behavior;
- rolling-code compatibility;
- reversibility;
- supporting evidence;
- risk state.

### C. Blocking findings and risk register

For every material finding provide:

- finding ID;
- operation or release phase;
- failure scenario;
- triggering condition;
- impact;
- risk state;
- supporting evidence;
- uncertainty;
- minimum risk-reducing change;
- required owner;
- closure evidence.

Treat these as blockers until resolved:

- unknown engine-specific lock or rewrite behavior for a material operation;
- unreconciled production-schema drift;
- unbounded backfills;
- destructive changes without recovery;
- incompatible mixed-version operation;
- missing required acceptance evidence.

### D. Compatible phased migration design

Provide the ordered release plan.

For each phase state:

- migration or code change;
- compatible application and worker versions;
- entry evidence;
- proposed action;
- monitoring signals;
- pause thresholds;
- acceptance criteria;
- rollback or forward-recovery path;
- approval gate.

If a single-phase release is sufficient, justify that conclusion using engine-specific, workload, compatibility, and recovery evidence.

### E. Backfill control sheet

State:

- selection predicate;
- stable cursor;
- batching method;
- calibration method;
- idempotency behavior;
- transaction boundary;
- throttle and pause signals;
- retry handling;
- checkpoint storage;
- progress metrics;
- reconciliation equations;
- anomaly handling;
- completion criteria;
- read-switch and contract prerequisites.

If no backfill is required, state `Not applicable` and explain why.

### F. Mixed-version compatibility record

Report compatibility for:

- old application with expanded schema;
- new application with intermediate schema;
- queue workers and delayed jobs;
- scheduled commands;
- APIs and integrations;
- caches and serialized data;
- feature flags;
- contract and cleanup timing.

Identify the last point at which old code remains safe.

### G. Recovery matrix

Cover failure:

- before DDL;
- during DDL;
- after schema expansion;
- during backfill;
- after read switch;
- during contract;
- after application rollback.

For each case state:

- observable symptoms;
- immediate safe response;
- approval-required action;
- data-loss exposure;
- recovery evidence;
- whether old and new code remain operable.

### H. Verification runbook

List commands, SQL, tests, and observations in release order.

For each item provide:

- check ID;
- purpose;
- target environment;
- command or method;
- expected result;
- actual supplied or observed result;
- evidence;
- safety limit;
- status: proposed, executed, supplied, unavailable, or unverified;
- acceptance result: pass, fail, investigate, or not assessed.

Never fabricate command output.

### I. Release decision record

Choose exactly one status:

- Ready for authorized rehearsal
- Ready for authorized phased production rollout
- Changes required
- Blocked by missing evidence
- Unsafe as proposed

State:

- zero-downtime feasibility;
- highest residual risks;
- required changes;
- unresolved assumptions;
- required human approvals;
- next evidence-producing action.

Do not use “safe to deploy” unless every mandatory acceptance criterion is supported by current, release-bound evidence.

## Final quality gate

Before returning the report, verify that:

1. Every migration operation is accounted for.
2. The reviewed evidence is bound to the exact release where possible.
3. Production schema drift is reconciled or explicitly blocking.
4. Database-engine and version dependencies are addressed.
5. Lock, rewrite, index, constraint, and transaction behavior are assessed.
6. Mixed-version application and worker compatibility is evaluated.
7. Backfills are bounded, resumable, idempotent, observable, and reconciled where required.
8. Rollback and forward-recovery paths are distinguished.
9. Proposed commands include expected observations and safety limits.
10. Acceptance criteria reconcile schema, data, application behavior, workers, and operations.
11. Zero-downtime feasibility is tied to supplied service constraints.
12. No execution, verification, approval, deployment, recovery, or completion is claimed without evidence.


## Step 4 — Plan feature-flag rollout and rollback controls

**Prompt**

Laravel Feature Flag Rollout and Rollback Planner

**Instructions**

Plan default states, scoped exposure, monitoring, queue/cache effects and rollback using the supplied flag mechanism. Do not invent a flag system or enable anything. Record Not applicable with owner rationale if flags are not appropriate; retain a reversible release plan.

**Input for this step**

Provide the approved feature design, migration review output, actual flag mechanism, deployment constraints, target segments, monitoring requirements and rollback boundaries. No implemented change is assumed at this planning stage.

**Carry forward**

Carry approved defaults, test cases, disablement and rollback criteria into implementation; no rollout is claimed.

**Review note**

Release and engineering owners accept the rollout/rollback design before implementation. Unknown recovery or unresolved migration risk blocks consequential changes.

**Prompt ID**

AMO-P-000187

**Prompt URL**

https://amo.ng/prompts/laravel-feature-flag-rollout-rollback-planner

**Prompt content**

You are an expert Laravel release engineer specializing in feature flags, rollout safety, regression testing, deployment sequencing, and rollback planning.

Your task is to inspect the supplied Laravel feature area and produce a practical feature flag rollout and rollback plan that protects current production behavior, reduces deployment risk, and gives operators a clear kill-switch path.

## Context Placeholders

Use the context below. If an important detail is missing, ask a brief clarification before making risky rollout or rollback recommendations.

- [Feature/change]
- [Flag or config mechanism]
- [Affected area or files]
- [Users or segments]
- [Data/database impact]
- [Scope limits]
- [Rollback and launch notes]

## Important Constraints

- Inspect before editing. Identify relevant routes, controllers, services, models, policies, middleware, views, config files, migrations, seeders, jobs, events, listeners, notifications, commands, scheduled tasks, and tests where applicable.
- Do not change unrelated files, public UI, data, generated assets, lockfiles, or out-of-scope areas unless explicitly requested.
- Respect the allowed file scope. If required changes fall outside the allowed scope, stop and explain why those files matter.
- Protect existing behavior. Prefer characterization tests or focused regression tests before risky implementation edits.
- Treat flag-off behavior as the production baseline unless told otherwise.
- Avoid destructive commands such as `git reset`, `git checkout`, `rm`, database wipes, irreversible migrations, or production mutations.
- Consider Laravel deployment realities, including `config:cache`, route cache, view cache, queue workers, Horizon, scheduler behavior, environment variables, config defaults, and stale deployed code.
- Separate confirmed code behavior from assumptions, likely risks, and recommendations.
- Provide exact verification commands and explain what each command proves.

## Step-by-Step Instructions

1. Inspect the supplied feature/change and discover every relevant Laravel entry point, including web/API code, models, authorization, config, database changes, background jobs, scheduled tasks, views, and tests.

2. Map the current production behavior:
   - what happens today
   - who can access it
   - which data is read or written
   - which side effects occur
   - which external services are touched
   - which tests currently protect it

3. Map the flagged behavior:
   - flag name and default value
   - flag source, such as config, env, database, LaunchDarkly, Pennant, or custom helper
   - flag-off behavior
   - flag-on behavior
   - targeted user segments
   - excluded users
   - admin/operator controls
   - expected fallback behavior

4. Identify rollout risks:
   - broken flag defaults
   - cached config or stale environment values
   - route or view cache mismatch
   - queue workers running old code
   - migrations coupled too tightly to feature release
   - partial database state
   - unauthorized access
   - inconsistent behavior across web, API, jobs, and scheduled tasks
   - external integration failures
   - missing logs or metrics
   - rollback blockers

5. Design a test matrix covering:
   - flag off
   - flag on
   - targeted user allowed
   - excluded user denied or preserved
   - unauthorized user
   - missing or invalid config
   - stale cache where relevant
   - database state before and after migration
   - rollback behavior
   - queue/job/scheduler behavior if applicable

6. Provide an implementation sequence:
   - tests first where practical
   - config or flag setup
   - guarded code path
   - migration sequencing if needed
   - deployment order
   - cache clearing or warming
   - queue restart instructions
   - rollout stages
   - monitoring checks
   - rollback steps

7. Provide exact verification commands:
   - focused test commands
   - full relevant test suite command
   - route/config/cache inspection commands where useful
   - migration status command if relevant
   - queue or scheduler verification command if relevant

## Output Format

### 1. Missing Context

List any missing inputs that are required before a safe rollout decision can be made. If enough context is available, say so.

### 2. Current Behavior Map

Describe the confirmed current behavior, affected files, data flow, authorization rules, side effects, and existing tests.

### 3. Flagged Behavior Map

Describe the proposed flag, default state, flag-on behavior, flag-off behavior, target users, excluded users, fallback behavior, and operational control points.

### 4. Rollout Risk Register

Use this table:

| Risk | Why It Matters | Evidence | Mitigation | Owner |
|---|---|---|---|---|

### 5. Test Matrix

Use this table:

| Scenario | Flag State | User/Segment | Expected Result | Test Type | File/Command |
|---|---|---|---|---|---|

### 6. Implementation Sequence

Provide a safe step-by-step sequence for implementation, deployment, rollout, monitoring, and rollback.

### 7. Rollback Plan

Explain exactly how to disable the feature safely, including config changes, cache clearing, queue restarts, database concerns, and verification steps.

### 8. Verification Commands

List exact commands and explain what each command proves.

### 9. Assumptions and Human Checks

Separate assumptions from confirmed behavior. List the final checks a human should complete before rollout.

## Verification Requirements

Before finalizing, confirm that:

- flag-off behavior preserves current production behavior
- rollback does not require destructive database changes
- migrations, if any, are backward compatible or explicitly called out as a risk
- cached config and queue worker behavior have been considered
- tests cover both enabled and disabled states
- monitoring or logs are available for rollout decisions
- unresolved risks are clearly stated

## 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.


## Step 5 — Implement only the authorized feature

**Prompt**

Feature Implementation Prompt

**Instructions**

Begin only after the preceding human gates pass. Inspect the repository and preserve existing work. Implement the bounded approved plan in the authorized environment, run only permitted checks and record commands/results. Return to planning for scope, migration or security changes outside approval. Do not merge, deploy or mutate production.

**Input for this step**

Use the approved feature plan, AGENTS.md instructions, acceptance criteria, change boundaries, test commands, and any required human approvals for edits.

**Carry forward**

Carry the real change set, artifact references, actual test evidence, migration/flag review decisions and unresolved risks to PR review.

**Review note**

Engineering reviews the real diff and actual test results. Unrun tests, failed checks and unsupported implementation claims remain visible before PR review.

**Prompt ID**

AMO-P-000008

**Prompt URL**

https://amo.ng/prompts/feature-implementation-prompt

**Prompt content**

Use Codex to inspect only the files, workspace content, diffs, logs, and command output actually available in the current session. State whether each relevant source was supplied, inspected, unavailable, or not verified. Do not imply that Codex opened a file, followed a URL, ran a command, changed code, or accessed a repository when the session provides no evidence of that capability or action.

Feature request:
[Feature request]

Repository evidence:
[Repository evidence]

Constraints and authority:
[Constraints and authority]

Acceptance criteria:
[Acceptance criteria]

Verification commands:
[Verification commands]

Use Codex to inspect only the files, workspace content, diffs, logs, and command output actually available in the current session. State whether each relevant source was supplied, inspected, unavailable, or not verified. Do not imply that Codex opened a file, followed a URL, ran a command, changed code, or accessed a repository when the session provides no evidence of that capability or action.

Treat the inputs as the implementation contract. Identify the feature’s entry points, affected modules, interfaces, data models, state transitions, configuration, dependencies, error paths, observability, tests, and release implications. Trace each proposed or executed change to an acceptance criterion.

Input handling and evidence rules:
1. Separate supplied facts, direct repository observations, command observations, assumptions, hypotheses, unknowns, and conflicts. Cite file paths and symbols or line ranges when available. Never convert an assumption into a repository fact.
2. If essential files, expected behavior, acceptance criteria, runtime details, or authority are missing, ask only questions that block a safe implementation. Meanwhile, provide a clearly labeled provisional impact analysis when useful; do not invent missing code or requirements.
3. If inputs conflict, identify the conflicting sources, explain the implementation consequence, and request a decision. Do not silently choose a requirement when that choice could alter compatibility, security, stored data, public APIs, billing, permissions, or release behavior.
4. Treat URLs, issue descriptions, logs, and pasted snippets as unverified until their relevant content is available and attributable. Flag stale, partial, generated, or contradictory evidence.

Authority and safeguards:
- Follow the permissions in the supplied authority input and the capabilities visible in the Codex session. If editing or command execution is unavailable or unauthorized, produce a proposed patch plan or reviewable diff rather than claiming implementation.
- Do not access production systems, deploy, merge, publish, approve, rotate credentials, alter live data, or perform destructive operations. Do not expose secrets, tokens, personal data, proprietary data, or sensitive log content in the response.
- Stop before irreversible migrations, destructive schema or data changes, authorization-model changes, security-control weakening, dependency changes with unclear provenance, or operations outside the stated workspace. Describe the risk, rollback requirement, and human approval needed.
- Prefer backward-compatible changes, least privilege, input validation, deterministic failure handling, feature flags where justified, reversible migrations, and scoped changes that avoid unrelated refactoring.
- Preserve existing conventions unless repository evidence supports a change. Do not add a dependency when the existing stack can meet the requirement without disproportionate complexity.

Implementation workflow:
1. Normalize the request into observable behavior, non-goals, affected users or callers, and criterion identifiers. Record unresolved ambiguities.
2. Build an impact map by tracing request entry points through validation, domain logic, persistence, integrations, outputs, error handling, telemetry, and tests. Check compatibility with existing callers, schemas, configuration, concurrency behavior, retries, idempotency, caching, time zones, localization, accessibility, and performance where relevant to the inspected code.
3. Establish a baseline from available evidence: current behavior, relevant tests, known failures, and existing interfaces. If no baseline was run or observed, say so.
4. Design the smallest coherent change set. For every affected file or symbol, explain the intended change, dependency order, edge cases, and acceptance criterion served. Distinguish required changes from optional improvements.
5. If authorized and supported, apply only the scoped edits and maintain a change ledger. If not, provide implementation-ready edit instructions or a reviewable patch. Do not describe proposed edits as applied edits.
6. Add or revise tests at the appropriate levels. Cover the happy path, validation failures, authorization boundaries, state transitions, regression risks, integration failures, and relevant boundary values. Avoid tests that merely mirror implementation details.
7. Run only authorized verification commands. Record each exact command, execution state, relevant environment details, exit status, and concise output evidence. Mark commands as requested, executed, failed, unavailable, skipped, or not authorized. Never fabricate output or infer a pass from code inspection.
8. Reconcile every acceptance criterion against implementation and test evidence. Classify it as demonstrated, partially demonstrated, not demonstrated, blocked, or out of scope, with the supporting evidence or gap.
9. Prepare a release handoff covering configuration, migration order, feature-flag behavior, observability, rollback, compatibility, and post-release checks. This is a proposed handoff unless release actions are separately authorized and evidenced.

Return this feature-specific deliverable:

A. Contract and evidence register
- Normalized behaviors and non-goals
- Assumptions, unknowns, conflicts, and blocking questions
- Evidence table with source, classification, location, relevance, and verification state

B. Repository impact map
- Entry points and execution flow
- Affected files, symbols, interfaces, data, configuration, dependencies, and tests
- Regression surfaces and edge cases, each tied to repository evidence or explicitly labeled as a hypothesis

C. Change-set ledger
For each change, provide: criterion identifier; file and symbol; change description; rationale; status as proposed or applied; compatibility or data risk; reviewer focus; and evidence. Include code or a patch only when grounded in available source content.

D. Test and verification matrix
For each check, provide: criterion identifier; test level; scenario; setup; exact command when known; expected observation; execution state; actual observation if executed; and evidence location. Include targeted regression tests and explain any omitted test layer.

E. Acceptance reconciliation
List every acceptance criterion with its result, implementation evidence, test evidence, remaining gap, and required owner or approval. No criterion may be marked demonstrated solely because code was proposed or edited.

F. Release and rollback handoff
Provide prerequisites, configuration or migration sequencing, monitoring signals, failure thresholds, rollback steps, data-recovery considerations, and human approval gates. Do not claim deployment readiness when required verification is missing.

G. Completion statement
State separately what was requested, proposed, applied, executed, unavailable, and unverified. Claims such as fixed, tested, verified, approved, merged, deployed, or complete are permitted only when the response includes direct evidence for that exact state. End with the smallest safe next action and its owner.


## Step 6 — Review the implemented Laravel change

**Prompt**

Evidence-Grounded Laravel Pull Request Review with Codex

**Instructions**

Review the real diff and execution evidence against approved scope, authorization, data boundaries, migration conditions, feature-flag defaults and rollback. A proposed plan alone is not a change set. Resolve blocking findings or keep the release held.

**Input for this step**

Provide the pull request diff or branch, feature requirements, AGENTS.md instructions, implementation summary, migration review, rollout plan, and available test evidence.

**Carry forward**

Carry reviewed change locations, resolved and open findings, actual verification evidence and conditional release recommendation to the final deployment-safety checklist.

**Review note**

A qualified engineering reviewer makes the merge recommendation; authorized owners decide merge and release separately. AI output is not approval.

**Prompt ID**

AMO-P-000069

**Prompt URL**

https://amo.ng/prompts/safe-thorough-pull-request-review-laravel-codex

**Prompt content**

Review the supplied Laravel pull request as a bounded, evidence-grounded assessment. Identify defects, security risks, regressions, migration hazards, compatibility problems, and verification gaps without changing the repository or making the merge decision.

## Review inputs
- Pull request objective and acceptance criteria: [Pull request objective and acceptance criteria]
- Pull request diff or commit range: [Pull request diff or commit range]
- Repository context and relevant files: [Repository context and relevant files]
- Laravel stack and target environments: [Laravel stack and target environments]
- Project conventions and risk constraints: [Project conventions and risk constraints]
- Authorized Codex access and execution scope: [Authorized Codex access and execution scope]
- Verification commands and supplied evidence: [Verification commands and supplied evidence]
- Deployment, migration, and rollback context: [Deployment migration and rollback context]

## Input gate
The minimum prerequisites are the pull request objective, acceptance criteria, diff or commit range, Laravel and PHP versions, relevant repository access, and the authorized inspection scope. If the diff, objective, or access boundary is missing or unusable, stop and request it rather than producing a merge assessment.

Treat tests, logs, deployment details, schema snapshots, production topology, traffic assumptions, and rollback procedures as optional unless the change affects those areas. When optional context is absent, continue only with a bounded static review, identify the resulting blind spots, and mark affected conclusions as unverified. If inputs conflict, record the conflict and do not silently choose one version. Never infer omitted code, configuration, database state, runtime behavior, or organizational policy.

## Codex access and authority boundaries
1. Inspect only the supplied diff, files, repository content, and artifacts that Codex can actually access. State what was and was not inspected.
2. Default to read-only review. Do not edit files, create commits, push branches, merge or approve the pull request, deploy code, run production migrations, alter data, rotate credentials, contact people, or change external systems.
3. Run commands only when the authorized scope explicitly permits execution and the environment is confirmed non-production. Do not run destructive commands, commands requiring secrets, dependency updates, irreversible migrations, or commands that may affect shared services. Stop and request human authorization if a command could mutate persistent or shared state.
4. Redact secrets, tokens, credentials, personal data, and sensitive tenant data from quotations and command output. Flag exposed secrets without reproducing their values.
5. Recommendations are advisory. A human maintainer retains responsibility for remediation, risk acceptance, merge approval, rollout, and rollback decisions.

## Evidence and claim rules
- Separate supplied facts, direct code observations, command execution evidence, assumptions, hypotheses, unknowns, and conflicts.
- Support every finding with a file and line, diff hunk, configuration location, schema artifact, log excerpt, or command result. If exact lines are unavailable, cite the nearest symbol or file and say why precision is limited.
- Explain the failure mechanism and affected request, job, migration, data path, or deployment phase. Do not report a theoretical pattern as a confirmed defect without showing that the relevant code path is reachable.
- Assign confidence as high, medium, or low and explain material uncertainty. Downgrade or omit findings that cannot be connected to the supplied change.
- Code inspection is not execution evidence. Supplied historical test output is not evidence that the reviewed commit currently passes unless its commit and environment match.
- Use the terms passed, failed, fixed, tested, verified, deployed, approved, or completed only when corresponding actions actually occurred and evidence is available. Otherwise use proposed, not run, unavailable, blocked, or unverified.

## Review workflow
### 1. Establish scope and coverage
Summarize the intended behavior, affected entry points, trust boundaries, persistence changes, asynchronous paths, public contracts, and deployment implications. Map changed files to related Laravel components that may need inspection, including routes, middleware, controllers, Form Requests, policies and gates, models, casts, scopes, services, events, listeners, jobs, notifications, API resources, views, configuration, migrations, factories, seeders, and tests.

Identify related files that were expected but unavailable. Keep unrelated legacy issues out of scope unless the pull request activates or materially worsens them.

### 2. Trace behavior and framework interactions
Trace representative success, validation-failure, authorization-failure, not-found, retry, and exception paths from entry point to side effects. Check Laravel-specific behavior such as route-model binding, middleware order, container bindings, service-provider registration, Eloquent scopes and events, transaction boundaries, exception rendering, configuration caching, and environment-dependent behavior.

Compare actual behavior with the stated acceptance criteria. Note backward-compatibility effects on HTTP APIs, console commands, scheduled tasks, events, queue payloads, serialized models, webhooks, and package or PHP requirements.

### 3. Review security and tenant isolation
Check authentication and authorization at every protected operation, including policy coverage, ownership checks, tenant scoping, elevated roles, indirect object references, and administrative bypasses. Review validation and normalization, mass assignment, unsafe query construction, output escaping, CSRF exposure, SSRF paths, file uploads, signed URLs, rate limits, secret handling, and sensitive logging where relevant.

Treat a plausible cross-tenant access path, authorization bypass, credential disclosure, injection path, or destructive unauthenticated action as blocking unless evidence disproves reachability or impact.

### 4. Review database and rollout safety
For schema or data changes, evaluate table locks or rewrites, index creation, foreign keys, defaults, nullability, type narrowing, backfill cost, duplicate or invalid existing data, transaction behavior, and database-engine differences. Determine whether old and new application versions can safely coexist during rolling deployment.

Assess expand-and-contract sequencing, read/write compatibility, backfill observability, retry and resume behavior, rollback feasibility, and irreversible data loss. Do not assume a migration down method restores transformed or deleted data. Flag migrations that require production data profiling, maintenance windows, database-specific online DDL, or operator approval.

### 5. Review queues, transactions, caches, and concurrency
Where applicable, inspect job serialization, retry policy, idempotency, uniqueness, timeout handling, after-commit dispatch, stale model state, duplicate delivery, dead-letter handling, and side effects. Check race conditions, lost updates, locking, transaction isolation, cache-key scope, invalidation, and tenant leakage. Identify failures that could appear only under retries, concurrent requests, rolling deployment, or partial outages.

### 6. Evaluate tests and verification
Map each acceptance criterion and material risk to existing or missing tests. Consider feature, unit, authorization, validation, database, migration, queue, concurrency, contract, and regression coverage as applicable. Check whether assertions prove externally meaningful behavior rather than only status codes or implementation details.

If command execution is explicitly authorized, run only the smallest relevant safe commands first. Record the exact command, environment, expected observation, actual observation, exit status, and evidence location. Reconcile failures with the reviewed commit; do not dismiss them as unrelated without evidence. If execution is unavailable or unsafe, provide commands as proposed verification and mark them not run.

### 7. Determine disposition
Classify each issue as:
- Blocking: credible risk of security breach, cross-tenant exposure, data loss or corruption, production outage, irreversible migration failure, broken acceptance criterion, or incompatible public contract.
- Conditional: disposition depends on missing environment, data, traffic, deployment, or policy evidence that must be resolved before merging.
- Non-blocking: maintainability, clarity, resilience, or test improvement with no demonstrated merge-stopping impact.

Do not inflate severity. State when no blocking issue was found, but never translate that into approval. Base the recommendation on evidence coverage and unresolved blind spots.

## Required deliverable
Return Markdown with these sections:

# Laravel Pull Request Review

## Scope and Evidence Coverage
Include the reviewed objective, diff or commit range, files and components inspected, artifacts unavailable, execution access used, and material assumptions or conflicts.

## Change and Risk Map
Provide a table with columns: Area, Changed behavior, Related Laravel components, Trust or data boundary, Deployment concern, Coverage status.

## Findings Register
Provide a table with columns: ID, Disposition, Severity, Confidence, Location, Evidence type, Observation, Failure mechanism, Impact, Required remediation, Verification needed.

For each blocking or conditional finding, add a short evidence note quoting only the minimum safe excerpt and explain why the issue is reachable. If there are no supported findings in a disposition, write that none were found within inspected scope.

## Migration and Rollout Assessment
When relevant, report database engine assumptions, lock or rewrite risk, existing-data prerequisites, old/new version compatibility, expand-and-contract needs, backfill controls, observability, rollback limits, and required operator approval. If not relevant, state why.

## Acceptance and Test Coverage Matrix
Provide a table with columns: Acceptance criterion or risk, Existing evidence, Test level, Expected observation, Actual observation, Status, Gap or follow-up. Status must be Passed, Failed, Not run, Blocked, or Unverified and must match the evidence.

## Verification Ledger
List each executed or proposed command or manual check with its purpose, target environment, safety prerequisites, expected result, actual result, execution state, and evidence location. Never present proposed commands as executed.

## Merge Guidance and Human Handoff
Choose one advisory state: Block pending remediation, Hold pending evidence, or No blocking issue found within reviewed scope. Explain the evidence basis, unresolved unknowns, required owners or approvals, safest next actions, and any rollout or rollback checkpoints. Explicitly state that Codex did not merge, approve, deploy, or modify the pull request.


## Step 7 — Prepare the release safety and recovery handoff

**Prompt**

CI/CD Deployment Safety Checklist Generator

**Instructions**

Run the source against the reviewed change set and actual evidence. Produce a conditional deployment/rollback checklist; mark every unrun check and absent approval. This step prepares release decisions and performs no deployment.

**Input for this step**

Supply the approved change scope, real diff, test results, migration and flag decisions, CI/deployment procedures, monitoring evidence, recovery plan and authorized release owners. Use redacted metadata without secrets or production records.

**Carry forward**

Deliver the release evidence register, blockers, staged verification plan, monitoring and rollback triggers, owners and conditional go/hold recommendation. Preserve unperformed actions as proposed.

**Review note**

The authorized release owner reviews unresolved blockers, actual verification, rollback viability and required approvals. No generated checklist constitutes deployment authorization.

**Prompt ID**

AMO-P-000116

**Prompt URL**

https://amo.ng/prompts/ci-cd-deployment-safety-checklist-generator

**Prompt content**

Review the supplied release materials and produce an evidence-traceable CI/CD deployment safety assessment. Use Codex to inspect the repository and only files, text, command output, and repository context that are actually supplied or available in the current session. Do not imply access to a repository, CI provider, cloud account, secrets store, database, monitoring system, or production environment unless that access is demonstrably available.

Inputs

Repository and release scope: [Repository and release scope]
Pipeline and deployment artifacts: [Pipeline and deployment artifacts]
Platform and environment topology: [Platform and environment topology]
Migration and stateful workload details: [Migration and stateful workload details]
Verification and observability evidence: [Verification and observability evidence]
Rollback and governance requirements: [Rollback and governance requirements]

Input expectations

The repository and release scope should identify the change set, affected services, release reference, critical user flows, external dependencies, and known high-risk changes such as billing, authentication, authorization, data deletion, or infrastructure changes. Pipeline and deployment artifacts should include relevant workflow files, reusable workflows, deployment scripts, manifests, infrastructure definitions, build configuration, test commands, and release instructions. Platform and environment topology should describe environments, promotion flow, deployment strategy, runtime components, regions, traffic routing, queues, caches, scheduled jobs, and secret or identity mechanisms without exposing secret values. Migration and stateful workload details should cover schema and data migrations, compatibility assumptions, expected duration, locking risk, backups, restoration, and interactions with workers or older application versions. Verification and observability evidence should provide health checks, smoke tests, dashboards, alerts, logs, service-level indicators, prior command output, and acceptance thresholds. Rollback and governance requirements should identify rollback or roll-forward procedures, approval owners, change windows, incident contacts, communication requirements, and the release definition of done.

Input and evidence rules

1. Create an input ledger before drawing conclusions. Classify each needed item as supplied, observed in an accessible artifact, conflicting, missing, or not applicable. Cite file paths and line ranges when available; otherwise cite the supplied input section or evidence item.
2. Never invent workflow behavior, provider settings, branch protection, environment rules, test outcomes, secret values, migration reversibility, backup validity, monitoring coverage, approvals, or production state.
3. If inputs conflict, record both claims, identify their sources, explain the safety consequence, and request the authoritative source. Do not silently choose one.
4. If a critical fact is missing, mark the affected conclusion unverified and make the release disposition Blocked when safe deployment depends on that fact. Noncritical gaps may receive a clearly labeled conservative hypothesis, but a hypothesis is not evidence.
5. Treat documentation as evidence of an intended process, not proof that a control ran. Treat configuration as evidence of a configured control, not proof of successful execution. Treat logs, CI run records, signed approvals, artifact metadata, command output, or monitoring observations as execution evidence only when their source and release relevance are supplied.
6. Use these work-state labels consistently: Requested for work the user asked for; Proposed for changes or commands not applied; Executed only for an action actually performed in the current session; Unavailable when access or capability is absent; Unverified when evidence is insufficient. Every claim that something was tested, fixed, deployed, rolled back, approved, or verified must include execution evidence. Otherwise label it Proposed or Unverified.
7. Bind every material piece of evidence to the exact release under review. A passing test, approval, artifact, log entry, monitoring observation, or prior deployment from another commit, branch, artifact digest, environment, configuration state, or execution window is not evidence for this release unless a traceable relationship is supplied. Record the commit, release reference, artifact identity, target environment, and evidence timestamp where available.

Authority and safeguards

Unless [Rollback and governance requirements] expressly restrict access, permit read-only repository inspection and non-mutating diagnostics within the workspace actually available to Codex.

Treat file edits, mutating commands, pipeline or configuration changes, database writes or migrations, secret rotation, infrastructure changes, deployment, rollback, production access, and external side effects as unauthorized unless expressly approved.

Do not deploy, merge, approve, rotate secrets, alter infrastructure, run migrations, modify production data, disable controls, or trigger rollback. If a read-only check against a production target is expressly authorized and Codex has demonstrable access, limit it to a clearly non-mutating command against the stated target. Record the exact command, target, exit status, relevant output, time, and limitations.

Never run destructive, state-changing, costly, financially consequential, or irreversibly production-affecting commands within this prompt. Otherwise provide commands as Proposed and do not fabricate output.

Do not reproduce secret values, tokens, credentials, private keys, customer data, or sensitive log content. Refer to secret names or redacted identifiers only. Flag excessive permissions, untrusted code paths with secret access, unsafe pull-request triggers, command injection surfaces, unpinned third-party actions, mutable artifacts, and credential persistence. Human approval remains mandatory for production release decisions and for changes involving billing, identity, permissions, security controls, destructive data operations, non-backward-compatible migrations, or infrastructure replacement.

Focused review workflow

1. Trace the failure modes and map the delivery path from source trigger to production: event and branch or tag filters, pull-request trust boundary, build, tests, artifact creation, provenance or digest handling, promotion, environment selection, deployment, verification, and rollback. Identify reusable workflows and dependencies that can alter this path.
2. Inspect trigger and concurrency safety. Check accidental production triggers, skipped required jobs, path-filter blind spots, duplicate deployments, cancellation behavior, race conditions, environment locks, release serialization, and whether the deployed commit or artifact is uniquely identified.
3. Inspect identity, permissions, and supply-chain controls. Check least-privilege workflow permissions, OIDC or credential scope where evidenced, secret availability by event and environment, masking and log exposure, dependency or action pinning, artifact integrity, provenance, retention, and separation between build and deploy authority.
4. Inspect build and test gates. Trace dependency installation, lockfile enforcement, deterministic builds, static checks, unit and integration tests, security checks where required, failure propagation, retry behavior, test exclusions, coverage of critical flows, and whether the exact promoted artifact passed the cited checks.
5. Inspect environment and deployment correctness. Check staging-to-production parity, configuration validation, immutable artifact promotion, deployment strategy, traffic shifting, readiness versus liveness semantics, timeout behavior, partial failure across services or regions, infrastructure ordering, external API dependencies, maintenance requirements, and idempotency of repeated deployment attempts.
6. Inspect migration and stateful-component safety. Evaluate expand-and-contract compatibility, application and migration order, mixed-version operation, transaction and lock behavior, table rewrites, long-running backfills, retry and resume behavior, data validation, queue payload compatibility, worker draining, cron overlap, cache-key or serialization changes, backup freshness, restore evidence, and whether rollback would leave code and schema compatible. Treat an unproven destructive or irreversible migration as a blocking risk.
7. Inspect observability and release control. Check that health endpoints test meaningful dependencies without leaking data; smoke tests cover critical user journeys; dashboards and alerts identify error rate, latency, saturation, queue lag, failed jobs, database health, and business-critical signals; thresholds, observation windows, owners, and escalation paths are defined.
8. Build rollback and roll-forward logic. Define measurable triggers, decision owner, last known good artifact, code and configuration restoration, schema mitigation, traffic restoration, queue and cache handling, external side-effect reconciliation, user communication, and post-recovery verification. Do not call rollback viable without evidence that required artifacts, procedures, permissions, and schema compatibility exist.
9. Prioritize findings using impact and likelihood rated Low, Medium, High, or Critical. Distinguish release blockers from required follow-ups and optional hardening. Prefer the smallest control that materially reduces the identified risk; do not recommend broad platform rewrites without evidence that they are necessary.  Base impact and likelihood on release-specific evidence. Do not infer likelihood solely from generic industry experience or the theoretical existence of a failure mode. When the available evidence cannot support a defensible likelihood rating, mark likelihood Unverified, explain the uncertainty, and state what evidence is needed.

Output contract: required CI/CD safety deliverable

Produce the following task-specific sections in markdown.

A. Review basis and evidence ledger

Provide a table with Evidence ID, item or artifact, source locator, relevance to this release, evidence class, and status. Evidence class must distinguish intended process, static configuration, and execution evidence. Follow it with missing and conflicting inputs, their consequences, and the exact evidence needed to resolve each one.

B. Delivery-path map

Describe the evidenced path from trigger to production in order. For every stage list trigger or input, responsible workflow or script, output artifact or state transition, environment, controlling gate, and evidence ID. Mark inferred or unknown transitions explicitly.

C. Risk register

Provide Finding ID, delivery stage, failure mode, supporting evidence IDs, impact, likelihood, severity, affected environment or service, release consequence, required mitigation, owner or approver if supplied, and state. Include concrete findings for triggers, permissions, secrets, artifact integrity, tests, environment drift, deployment ordering, migrations, stateful workers, health checks, monitoring, and rollback when relevant. Do not create findings unsupported by the supplied architecture; record missing evidence instead.

D. Release gate checklist

Create ordered Pre-deployment, Deployment, and Post-deployment gates. Each checklist row must contain Gate ID, check, reason, execution target, method or proposed command, expected observation, supplied actual observation, evidence ID, pass criterion, stop or pause condition, responsible human, and state. Leave actual observation as Not supplied unless real output exists. Commands must identify assumptions and must not expose secrets or mutate production.

Include, where applicable, confirmation of the exact commit and immutable artifact; required CI results; configuration-key presence without values; environment and identity target; backup and restoration evidence; backward-compatible migration sequence; worker, queue, cache, and scheduler coordination; approval and communication gates; deployment progress; health and readiness; critical API and user-flow smoke tests; error, latency, saturation, queue, database, and business-signal thresholds; and an observation window.

E. Migration and stateful-workload decision record

State the proposed sequence for application versions, schema changes, backfills, workers, queues, caches, and scheduled jobs. Document compatibility across old code, new code, old schema, and new schema; lock and duration concerns; abort criteria; backup or restoration prerequisites; data-integrity reconciliation; and rollback versus roll-forward constraints. For each conclusion cite evidence or mark it Unverified.

F. Rollback readiness record

Provide rollback trigger, decision owner, code or artifact action, configuration action, database mitigation, traffic action, queue and cache handling, external side-effect reconciliation, communications, verification check, expected observation, and evidence. Identify the point after which rollback becomes unsafe and a roll-forward is required. Mark readiness Unverified if no tested procedure or equivalent execution evidence is supplied.

G. Verification plan and evidence requirements

For each proposed verification, give the exact non-destructive command or manual action, target environment, prerequisite, expected observation, acceptance threshold, failure interpretation, evidence to retain, and current work state. Reconcile the deployed release identity with the reviewed commit and artifact digest. Reconcile migration version and data checks with the expected release state. Reconcile health and smoke-test results with monitoring over the stated observation window. Never populate actual results unless they were supplied or executed with recorded evidence.

H. Release disposition

Choose exactly one disposition: Blocked, Conditional candidate for human approval, or Ready for human approval. This is advice, not approval or authorization to deploy.

List the decisive evidence, unresolved blockers, conditions that must be satisfied, required human gates, monitoring obligations, and safest next action. A disposition of Ready for human approval requires traceable evidence that required tests passed for the reviewed release artifact, the deployment target is identified, migration and configuration prerequisites are satisfied, meaningful health and smoke checks have acceptance thresholds, observability and escalation are active, and rollback or roll-forward is operationally credible. If any required evidence is missing, use Blocked or Conditional candidate for human approval.

Keep every section concise and proportional to the release’s actual scope and risk. Do not repeat the same evidence across multiple sections unnecessarily. Where a section or control area is genuinely not applicable, retain the heading, state Not applicable, and explain briefly why using the supplied release evidence. Never omit the evidence ledger, risk register, release gates, release disposition, or completion-integrity distinctions.

Final integrity check

Before returning the deliverable, confirm that every material conclusion cites evidence or is marked Unverified; every proposed command has a target and expected observation; every completion claim has execution evidence; no secret value appears; migration, stateful components, artifact identity, monitoring, and rollback were addressed when applicable; and the disposition does not exceed the available evidence or human authority.


## Completion criteria

The workflow is complete when the team has an approved feature plan, scoped implementation or change set, migration and rollout controls, PR review findings, verification evidence requirements, and deployment checklist ready for human merge and release decisions.

- Every consequential gate has an explicit human decision; all unrun checks and blockers remain visible.
- The final release/rollback checklist exists and distinguishes proposed, authorized and actually executed work.
- All steps use Codex in an authorized external repository environment; Workplace can retain manually reviewed output but does not execute repository commands.
