# Safely Build and Review a Multi-Tenant Laravel Feature

Workflow ID: AMO-W-000041
Workflow URL: https://amo.ng/workflows/safely-build-and-review-a-multi-tenant-laravel-feature

## Outcome

A review-ready, bounded multi-tenant Laravel change with approved tenancy rules, migration and policy review, synthetic cross-tenant evidence, actual test results, unresolved limitations and a human-owned release/rollback handoff. It is not an automatic merge or deployment decision.

## Before you begin

- Approved feature specification, acceptance criteria, roles, tenant boundaries, and user journeys
- Repository access, existing Laravel architecture, routes, models, policies, jobs, caches, storage, and search context
- Proposed schema or data changes, rollout constraints, feature flag expectations, and deployment environment notes
- Testing commands, CI/CD workflows, rollback requirements, and production-readiness standards

## Step 1 — Plan the long-horizon Laravel feature build

**Prompt**

Codex Evidence-Grounded Long-Horizon Feature Build Planner

**Instructions**

Use this prompt to inspect the repository and create a phased implementation plan with architecture impact, migration and release controls, verification gates, rollback paths, and file- or symbol-level change manifests. Use planning/read-only mode; inspection and planning do not authorize implementation.

**Input for this step**

Provide the approved feature request, tenant model, acceptance criteria, related routes/controllers/models/policies, existing tests, and deployment constraints.

**Carry forward**

Pass the phased implementation plan, affected files, risk register, proposed schema changes, verification matrix, and rollout strategy to the migration safety review.

**Review note**

Engineering and the security owner approve one bounded journey, actual tenant-resolution rules, roles, permitted files/commands and acceptance criteria. Missing tenancy rules block 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 2 — Review zero-downtime Laravel migration safety

**Prompt**

Zero-Downtime Laravel Migration Review

**Instructions**

Use this prompt to evaluate proposed schema and data migrations for lock risk, rolling-release compatibility, backfill controls, recovery planning, and measurable deployment acceptance criteria. Use the proposed migration evidence; record a reasoned Not applicable when there is no migration, and revisit the gate if the design changes. Do not run production migrations.

**Input for this step**

Provide the migration proposal from AMO-P-000083, database engine context, table sizes or write patterns if known, queue-worker compatibility needs, and rollback constraints.

**Carry forward**

Pass the migration safety findings, required migration revisions, backfill controls, acceptance checks, and rollback or forward-recovery plan to the authorization review.

**Review note**

Database/release owners approve applicable migration and backfill evidence before execution. If no schema/data change exists, record Not applicable with rationale; otherwise missing evidence blocks the change.

**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 3 — Audit Laravel authorization policy coverage

**Prompt**

Laravel Authorization Policy Coverage Audit Planner

**Instructions**

Use this prompt to review authorization coverage across policies, gates, middleware, route protection, roles, ownership rules, denial paths, and tenant access-control tests. Before implementation, assess supplied access rules and plan tests. After implementation, reconcile this matrix with actual code and results; never label unrun checks passed.

**Input for this step**

Provide the feature plan, route and controller map, role matrix, tenant boundary rules, policy files, middleware, and expected denial behavior.

**Carry forward**

Pass the authorization gap list, required tests, tenant-isolation risks, and policy recommendations to the authorized build step.

**Review note**

The security owner accepts the intended authorization matrix before implementation. Proposed coverage is not passed testing; revisit this review against the implemented diff and actual tests.

**Prompt ID**

AMO-P-000180

**Prompt URL**

https://amo.ng/prompts/laravel-authorization-policy-coverage-audit-planner

**Prompt content**

You are an expert Laravel security engineer specializing in authorization policy audits, access-control design, permission coverage, and regression-safe security testing.

Inspect the supplied Laravel authorization context, identify permission gaps, ambiguous access rules, inconsistent enforcement, missing denial paths, and regression-test needs without weakening existing protections or changing access behavior prematurely.

The goal is to help Codex audit authorization coverage safely before modifying policies, gates, middleware, route protection, role checks, or permission logic.

## Context Placeholders

Use the context below. If the route or module scope, user roles, sensitive actions, or expected permission rules are missing, ask for them before making risky recommendations.

* [Routes, modules, and sensitive actions]
* [Roles, permissions, and expected rules]
* [Policies, gates, middleware, and controllers]
* [Models, ownership, and tenant rules]
* [Existing tests and denial behavior]
* [Allowed files and scope limits]
* [Security concerns or known incidents]

## Important Constraints

* Inspect before editing. Identify relevant routes, controllers, policies, gates, middleware, form requests, models, observers, Blade views, Livewire or Inertia components if relevant, API resources, auth guards, config, packages, and tests.
* Do not change unrelated files, public UI, data, generated assets, lockfiles, or out-of-scope areas unless explicitly requested.
* Respect allowed file scopes. If required changes fall outside scope, explain why before touching them.
* Protect existing behavior. Prefer characterization tests or focused regression tests before risky authorization edits.
* Avoid destructive commands such as `git reset`, `git checkout`, `rm`, database wipes, production mutations, or broad permission changes.
* Do not broaden access without explicit human approval.
* Do not treat hidden UI as sufficient authorization. Backend enforcement must be checked for sensitive actions.
* Do not assume role names, permission semantics, tenant boundaries, or ownership rules if they are not supplied or visible in code.
* Separate confirmed code behavior from assumptions, risks, and recommendations.
* Provide exact verification commands and explain what each command proves.

## Step-by-Step Instructions

1. Inspect the authorization surface:

   * route definitions
   * route groups
   * route middleware
   * controllers
   * controller authorization calls
   * policies
   * gates
   * form request `authorize()` methods
   * model ownership rules
   * tenant scoping
   * Blade `@can`, `@cannot`, or role checks
   * Livewire or Inertia authorization if relevant
   * API guards and tokens if relevant
   * role or permission packages if present
   * existing tests

2. Map protected actions:

   * view list
   * view detail
   * create
   * update
   * delete
   * restore
   * force delete
   * approve
   * reject
   * publish
   * export
   * impersonate
   * manage roles
   * manage billing
   * perform bulk action
   * access admin-only route
   * access another user’s or tenant’s record

3. Review Laravel authorization mechanisms:

   * policy methods such as `viewAny`, `view`, `create`, `update`, `delete`, `restore`, and `forceDelete`
   * `before()` methods
   * `Gate::define`
   * `Gate::allows`
   * `Gate::authorize`
   * `$this->authorize()`
   * `authorizeResource()`
   * `can` route middleware
   * custom middleware
   * package-based roles or permissions
   * form request authorization
   * route model binding assumptions

4. Identify permission gaps:

   * route has no auth middleware
   * route has auth but no authorization
   * controller action lacks policy check
   * policy method missing
   * policy method too broad
   * owner and non-owner behavior unclear
   * tenant boundary not enforced
   * admin bypass too broad
   * UI hides action but backend allows it
   * API and web behavior differ
   * bulk action lacks per-record authorization
   * export/download route lacks authorization
   * denied path is untested
   * unauthenticated path is untested
   * wrong-role path is untested

5. Review denial behavior:

   * expected `403`
   * expected redirect
   * expected JSON error
   * expected validation vs authorization separation
   * unauthenticated behavior
   * unauthorized authenticated behavior
   * policy denial messages if relevant
   * logging or audit needs for sensitive denials

6. Design regression tests:

   * allowed user succeeds
   * unauthenticated user is blocked
   * wrong role is blocked
   * non-owner is blocked
   * cross-tenant access is blocked
   * admin path is explicitly tested
   * sensitive action requires correct permission
   * bulk action checks each target record
   * export/download is protected
   * API returns expected denial format
   * existing allowed behavior remains unchanged

7. Recommend the smallest safe remediation sequence:

   * add tests first where possible
   * clarify expected rules
   * adjust policy or gate only where evidence supports it
   * avoid broad middleware changes unless justified
   * preserve existing route behavior unless explicitly approved
   * list human review gates for security-sensitive decisions

## Output Format

### 1. Missing Context

List missing inputs needed before a safe authorization coverage audit can be completed. If enough context is available, say so.

### 2. Authorization Map

Use this table:

| Route or Action | Current Enforcement | Expected Rule | Evidence | Risk or Assumption |
| --------------- | ------------------- | ------------- | -------- | ------------------ |

### 3. Sensitive Action Coverage

Use this table:

| Sensitive Action | Required Role or Permission | Policy/Gate/Middleware | Owner or Tenant Rule | Denial Behavior |
| ---------------- | --------------------------- | ---------------------- | -------------------- | --------------- |

### 4. Permission Gap Register

Use this table:

| Gap | Evidence | Security Impact | Severity | Recommended Check |
| --- | -------- | --------------- | -------- | ----------------- |

### 5. Ownership and Tenant Boundary Review

Use this table:

| Model or Resource | Boundary Rule | Current Evidence | Gap or Risk | Test Needed |
| ----------------- | ------------- | ---------------- | ----------- | ----------- |

### 6. Denial Path Review

Use this table:

| Scenario | Expected Result | Current Evidence | Missing Test |
| -------- | --------------- | ---------------- | ------------ |

Cover unauthenticated, wrong-role, non-owner, cross-tenant, admin-only, and API denial behavior where relevant.

### 7. Regression Test Plan

Use this table:

| Scenario | Expected Access Result | Test Type | Suggested Test Name |
| -------- | ---------------------- | --------- | ------------------- |

### 8. Remediation Sequence

Provide a step-by-step plan for safely improving authorization coverage without broadening access or changing unrelated behavior.

### 9. Verification Commands

List exact commands and explain what each command proves.

### 10. Assumptions and Human Checks

Separate confirmed behavior from assumptions. List unresolved risks and checks a human should complete before changing policies, gates, middleware, roles, or permission rules.

## Verification Checklist

Before finalizing, confirm that:

* no recommendation broadens access without explicit human approval
* backend authorization is checked, not only UI visibility
* sensitive admin actions are covered
* owner and non-owner behavior is considered
* tenant boundary risks are considered where relevant
* unauthenticated and unauthorized denial paths are covered
* API and web denial behavior are considered where relevant
* bulk actions and exports are reviewed
* authorization tests are specific and runnable
* confirmed behavior is separated from assumptions
* missing inputs and human checks are clearly listed

## Final Instruction to Begin

Begin now. Inspect the supplied Laravel authorization context first. If required context is missing, ask for it. Otherwise, produce the full Laravel authorization policy coverage audit plan in the requested markdown format.


## Step 4 — Build the multi-tenant SaaS vertical slice from the approved specification

**Prompt**

Build a Multi-Tenant SaaS Vertical Slice from an Approved Specification

**Instructions**

Use this prompt to implement the approved tenant-scoped journey with server-side tenant isolation across authorization, persistence, jobs, caches, storage, search, exports, tests, and rollback controls. Implement only after the preceding gates pass, in the authorized environment. Inspect first, preserve unrelated work, record exact commands/results and rollback, and do not deploy or broaden permissions.

**Input for this step**

Provide the approved feature specification, outputs from planning, migration safety review, authorization audit, repository constraints, test commands, and approved feature-flag or rollout rules.

**Carry forward**

Pass the implementation summary, changed files, test evidence, known limitations, rollback notes, and unresolved risks to the Laravel pull-request review step.

**Review note**

Engineering and security reviewers inspect the real diff and actual isolation tests using at least two synthetic tenants and multiple roles. Failed or unrun required checks block release; no production data or secrets.

**Prompt ID**

AMO-P-000346

**Prompt URL**

https://amo.ng/prompts/build-multi-tenant-saas-vertical-slice-approved-specification

**Prompt content**

Implement one complete, approved tenant-isolated user journey through the existing application stack. Build only the vertical slice defined in the supplied specification. Do not expand the work into an entire SaaS product, a generic tenancy framework, or an architecture document.

## Required inputs

Approved vertical-slice specification:
{{approved_vertical_slice_specification}}

Repository and stack context:
{{repository_and_stack_context}}

Tenancy, identity, and authorization model:
{{tenancy_identity_and_authorization_model}}

Data interfaces and test fixtures:
{{data_interfaces_and_test_fixtures}}

Acceptance criteria and authorized scope:
{{acceptance_criteria_and_authorized_scope}}

## Evidence and assumption rules

1. Classify material statements as supplied fact, repository observation, execution evidence, assumption, conflict, missing information, or unresolved uncertainty. Cite file paths, symbols, schema objects, routes, policy rules, commands, and test output where available.
2. Do not invent tenant-resolution rules, roles, permissions, ownership rules, database fields, lifecycle states, APIs, job behavior, cache behavior, storage conventions, search capabilities, test results, credentials, or approvals.
3. Treat the supplied tenancy and authorization model as the authority contract. If it conflicts with repository behavior or omits a rule that affects isolation, stop the affected implementation path and request a decision from the product owner and security reviewer.
4. UI visibility is not authorization evidence. Require server-side enforcement at every applicable entry point and data boundary.
5. Use synthetic tenants, identities, records, files, and search documents. Do not request secrets, production tenant access, or real customer data.
6. Preserve unrelated repository changes and existing tenant behavior. Do not reformat, replace, or repair work outside the approved slice.
7. Separate changes actually applied and tests actually run from proposed changes, expected behavior, and unverified assumptions.

## Authorization boundaries

- Implementation requires an authorized repository, a bounded journey specification, an explicit tenancy and identity model, safe fixtures, and permission to change the identified files.
- Inspect only the supplied workspace, configuration, schemas, interfaces, fixtures, and command output. Do not imply access to identity providers, production tenants, external storage, search services, queues, or deployment systems unless the session provides direct evidence.
- Change only the approved files, schemas, configuration, and test surfaces. Use local fakes, isolated services, or approved non-production endpoints for jobs, notifications, storage, search, and other integrations.
- Do not broaden roles or permissions, replace the identity provider, access production tenant data, activate live billing, deploy, merge, push, publish, communicate externally, or run destructive migrations.
- Obtain separate approval before any schema migration with data-loss or lock risk, dependency installation, identity-model change, new cross-system permission, destructive action, or production-adjacent operation.
- Stop with a blocked handoff when the approved specification, tenant boundary, safe environment, essential fixture, or authority is absent.

## Implementation method

### 1. Establish the vertical-slice contract

Restate the single triggering actor, tenant context, entry route or interface, authorized action, domain transition, persisted or returned result, and observable completion condition. List explicit non-goals.

Identify every actor and role in the journey, how the active tenant is resolved, which tenant owns each record, and what happens when the tenant is missing, disabled, deleted, mismatched, or changed. Do not add states or permissions that the specification does not authorize.

### 2. Inspect the repository and current tenant boundary

Before editing, inspect the working-tree state, framework and runtime, route and middleware registration, authentication integration, tenant resolver, policies or permission checks, request validation, domain services, models, schema and migrations, query scopes, API resources, jobs, events, notifications, caches, file or object storage, search or indexes, exports, tests, feature flags, and observability.

Trace the current journey end to end. Record each source as inspected, unavailable, or not relevant. Identify repository conventions and pre-existing isolation risks without broadening the repair scope.

### 3. Set a concise implementation checkpoint

Map every acceptance criterion to affected files, symbols, data objects, authorization rules, test cases, commands, external-effect fakes, and rollback actions. State the smallest coherent change set and the approved schema effect, if any.

If implementation would require inventing the tenancy model, replacing foundational identity behavior, changing unrelated modules, accessing production, or using unavailable systems, stop. Provide a precise blocked handoff instead of a fictional implementation.

### 4. Implement trusted tenant resolution

Resolve the active tenant from the approved trusted identity, membership, route-binding, or server-side context. Do not trust a client-supplied tenant identifier by itself. Validate membership status, tenant status, and permitted role before entering domain logic.

Ensure modified URLs, query parameters, request bodies, headers, object identifiers, and API payloads cannot select another tenant or elevate a role. Return the approved denied or not-found behavior without leaking whether another tenant’s object exists.

### 5. Implement validation, authorization, and domain behavior

Apply server-side request validation and explicit authorization before reads, writes, exports, jobs, notifications, or other effects. Keep policy, service, and persistence rules aligned with the approved ownership and role model.

Implement the specified domain transition and its loading, empty, denied, validation, conflict, error, and recovery states. Keep the change bounded to the approved journey. Do not add generic administration, billing, onboarding, or unrelated tenant features.

### 6. Implement tenant-scoped persistence

Use the approved tenant key, ownership relationship, unique constraints, indexes, and transaction boundaries. Make query scoping explicit at trust-sensitive points. Validate that create, find, update, delete, aggregate, and export operations cannot cross the tenant boundary.

For approved schema changes, inspect existing data and migration conventions first. Use reversible migrations and explain lock, backfill, nullability, uniqueness, and rollback behavior. Do not run destructive or production migrations without separate approval.

Prevent global uniqueness assumptions from incorrectly blocking legitimate values across tenants or allowing duplicates where uniqueness is tenant-scoped. Do not treat a default model scope as the only protection for sensitive direct-object access.

### 7. Carry isolation across asynchronous and derived systems

Where the slice uses background jobs, events, notifications, cache entries, files, object storage, search indexes, or exports:

- include the approved tenant identity in the durable payload or storage namespace;
- re-resolve and validate tenant and actor authority at execution time where required;
- namespace cache keys and invalidation by tenant;
- isolate storage paths, retrieval policies, and generated URLs;
- apply tenant filters to search indexing and retrieval;
- ensure exports contain only the current authorized tenant’s rows;
- send notifications only to test sinks during verification;
- prevent stale jobs or cached data from surviving a disabled or deleted tenant contrary to the specification.

Do not claim these surfaces are isolated if they were unavailable or untested.

### 8. Implement interfaces and recovery states

Implement the approved web, API, or command interface using repository conventions. Preserve accessibility, keyboard behavior, responsive states, API contracts, pagination, error shapes, and rate controls where applicable.

Provide explicit behavior for loading, no eligible records, validation denial, authorization denial, missing tenant, disabled tenant, stale state, duplicate submission, partial failure, retriable failure, and rollback or feature disablement.

### 9. Add audit and observability evidence

Record the minimum safe tenant, actor, action, object, correlation, result, and failure metadata required by the supplied contract. Do not log secrets, sensitive payloads, or unnecessary personal data. Make authorization denial, cross-tenant attempts, job failures, export generation, and feature disablement observable where required.

Audit evidence records what the application attempted or decided. It does not itself prove isolation or authorize access.

### 10. Run the tenant-isolation test suite

Use at least two synthetic tenants and multiple roles, including an allowed and a denied role. Test the complete journey and all applicable supporting surfaces:

- authorized access inside the active tenant;
- unauthorized and inactive roles;
- another tenant’s valid object identifier;
- direct-object access and modified URLs, query parameters, request payloads, and headers;
- tenant-scoped create, read, update, aggregation, and delete behavior where included;
- duplicate submissions and validation failures;
- jobs executed with the expected tenant and attempts to substitute another tenant;
- cache-key isolation, stale cache, and invalidation;
- file paths, object retrieval, signed URLs, and storage namespace isolation;
- search indexing and result filtering;
- export row isolation and direct export retrieval;
- partial failure and retry behavior;
- missing, disabled, or deleted tenant behavior where specified;
- feature flag off and rollback behavior.

Record the exact fixture identities, commands, exit states, and relevant assertions without exposing secrets. Sequential happy-path tests are insufficient. A passing UI test does not prove server-side authorization, and one data-layer test does not prove jobs, caches, files, search, or exports.

### 11. Reconcile acceptance and prepare rollback

Map every acceptance criterion to code and execution evidence. Mark it demonstrated, partially demonstrated, failed, blocked, or not run. Preserve failures and pre-existing issues rather than weakening assertions.

Define feature-flag behavior or the smallest reversible control, schema rollback constraints, job and cache cleanup, search or file recovery, and restoration steps. Release remains a decision for the security reviewer and release owner.

## Stop conditions

Stop with a precise blocked handoff when:

- tenant resolution, ownership, role, or disabled-state rules are missing or conflicting;
- the authorized repository or safe test environment is unavailable;
- implementation would require production tenant access, live billing, an identity-provider replacement, or broader permission changes;
- the slice cannot be tested with two synthetic tenants and multiple roles;
- a required job, cache, storage, search, or export boundary cannot be inspected or safely faked;
- a destructive migration or irreversible operation lacks separate approval and recovery evidence;
- cross-tenant or direct-object tests fail and cannot be corrected within scope;
- rollback cannot preserve tenant data integrity.

## Output contract

Return these sections:

1. **Vertical-slice implementation status**: `Implemented and tested in the authorized environment`, `Partially implemented`, or `Blocked`. Separate inspected, applied, executed, demonstrated, and unverified work.
2. **Evidence and assumptions register**: source, classification, location, relevance, conflict or limitation, and required owner.
3. **Tenant-boundary map**: entry point, trusted tenant source, actor and role, object ownership, authorization control, persistence scope, derived-system scope, denied behavior, and evidence.
4. **Specification-to-code traceability**: requirement or acceptance criterion, file and symbol, implementation, test, result, and unresolved gap.
5. **Repository change manifest**: file, schema, configuration, job, cache, storage, search, or test item changed; purpose; state; and rollback action.
6. **Schema and persistence record**: tenant keys, ownership links, constraints, indexes, query boundaries, transaction behavior, migration status, and rollback limits.
7. **Authorization matrix**: tenant state, actor role, action, resource ownership, expected result, enforcement location, test result, and evidence.
8. **Cross-tenant isolation test ledger**: test tenant and actor, target tenant and object, interface, attempted manipulation, expected denial, observed result, status, and evidence.
9. **Failure and recovery matrix**: failure, affected state, containment, retry rule, recovery, cleanup, owner, and test evidence.
10. **Feature-flag or rollback plan**: disablement, schema considerations, job and cache cleanup, storage/search recovery, data reconciliation, and verification.
11. **Security and release-owner handoff**: remaining risks, untested surfaces, schema approval, access review, release prerequisites, and accountable owners.
12. **Completion statement**: reconcile every acceptance criterion and end with the smallest safe next action.

Completion requires actual authorized code or configuration changes for the bounded journey, server-side tenant enforcement, matching immutable versioned evidence where applicable, executed cross-tenant tests using at least two synthetic tenants and multiple roles, coverage of every included derived-system boundary, and a viable rollback or feature-disablement path. Do not claim the whole SaaS product was built or that tenant isolation, security, or production readiness is established beyond the recorded evidence.


## Step 5 — Run an evidence-grounded Laravel pull-request review

**Prompt**

Evidence-Grounded Laravel Pull Request Review with Codex

**Instructions**

Use this prompt to conduct a read-only review of the resulting Laravel pull request across behavior, authorization, migrations, queues, caches, compatibility, deployment safety, and test coverage. Require a real diff and test evidence, retain unresolved findings, and do not merge automatically.

**Input for this step**

Provide the PR diff, implementation notes, test outputs, feature plan, migration findings, authorization requirements, and any known unresolved risks.

**Carry forward**

Pass the PR findings, merge blockers, verification gaps, and suggested remediation priorities to the deployment safety checklist step.

**Review note**

A qualified reviewer resolves blocking findings against the actual change set and test evidence. The merge decision remains with authorized humans.

**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 6 — Generate the CI/CD deployment safety checklist

**Prompt**

CI/CD Deployment Safety Checklist Generator

**Instructions**

Use this prompt to review supplied CI/CD workflows, deployment scripts, migration behavior, configuration controls, observability, rollback readiness, and release verification plans without implying production actions occurred. Separate proposed release steps from actions actually performed; no release follows automatically from this output.

**Input for this step**

Provide PR review results, CI/CD files, deployment scripts, migration plan, feature-flag settings, observability checks, rollback instructions, and release-owner expectations.

**Carry forward**

Deliver a final release-readiness checklist with gates, stop conditions, monitoring requirements, rollback checks, and unresolved approval items for the release owner.

**Review note**

The release owner accepts actual verification, monitoring, migration compatibility and rollback evidence before any separate release. This checklist performs no deployment.

**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 feature has an evidence-grounded plan, migration and authorization review, authorized implementation or change package, PR risk review, and CI/CD deployment safety checklist ready for human merge and release decisions.

- Each consequential step records an explicit human review decision and preserves blockers.
- Codex steps run externally in an authorized repository; Workplace does not perform repository inspection or execution.
- No merge, deployment or test success is claimed without actual evidence.
