AGENTS.md@examples/glitch-payment-gateway/v1.1/codex/generated · git:20260408.61db2e8 · 2026-04-08 · sha256 f7c8a3f20f165793

AGENTS.md@examples/glitch-payment-gateway/v1.1/codex/generated git:20260408.61db2e8A

Immutable. This exact content never changes and is served at /api/v1/blob/f7c8a3f20f165793.

# Glitch Payment Gateway — Agent Instructions

> This file configures OpenAI Codex for this project. It is read automatically at session start.

## Project Overview

WooCommerce payment gateway plugin for **Glitch** — a major South African payment provider enabling merchants to accept card payments, instant EFT, digital wallet, and bank transfer payments through WooCommerce stores. All monetary amounts are in **ZAR (South African Rand)** expressed in **cents**.

- **Plugin bootstrap:** `glitch-payment-gateway.php` — main plugin file
- **Source:** `includes/` — core PHP classes (gateway, API client, webhooks, checkout, refunds, transactions)
- **Admin views:** `admin/views/` — WooCommerce admin settings screens
- **Templates:** `templates/checkout/` — checkout flow templates
- **Assets:** `assets/css/`, `assets/js/` — frontend styles and scripts (vanilla JS, no build step)
- **Tests:** `tests/phpunit/` — PHPUnit + WooCommerce test helpers
- **Docs:** `docs/` — architecture, features, task tracking, observations, reports
- **Skills:** `.agents/skills/` — reusable agent workflows (plan, commit, report, etc.)

## Stack

- **CMS:** WordPress 6.x
- **E-commerce:** WooCommerce 8.x
- **Language:** PHP 8.1+
- **Database:** MySQL (via WordPress `$wpdb` and WooCommerce CRUD APIs)
- **Package manager:** Composer
- **Testing:** PHPUnit + WooCommerce test helpers
- **Linting:** PHPCS with WordPress Coding Standards (WPCS)
- **Styling:** WordPress admin CSS + custom admin styles
- **JS:** Vanilla JavaScript (checkout integration) — no build step
- **Auth:** WordPress nonces + WooCommerce session tokens
- **Containerization:** Docker (WordPress + MySQL)

---

## Dev Server & Build

```bash
docker compose up -d            # Start containers
composer install                 # Install dependencies
composer test                    # Run PHPUnit tests
composer lint                    # Run PHPCS with WPCS
```

### Docker

- **WordPress container:** `glitch-wordpress` → `http://localhost:8080`
- **MySQL container:** `glitch-mysql` → port 3306

### Dev Login

- **URL:** `http://localhost:8080/wp-admin`
- **Username:** `admin`
- **Password:** `password`
- **WooCommerce Settings:** WooCommerce → Settings → Payments → Glitch

### Browser Verification

When verifying UI changes via Chrome MCP tools:
- Resize browser to **1900×1200** before screenshots
- Log in with the credentials above
- Navigate to affected admin/checkout pages

---

## CRITICAL: Never Push to Live

Never push, deploy, or sync code to production. All live deployments are the user's responsibility. You may deploy to **local** or **staging** environments only.

---

## CRITICAL: Never Auto-Commit or Auto-Push

Never commit or push without **explicit user approval**. When ready to commit:
1. Summarize what changed
2. Present **3 numbered commit message options** (concise → descriptive)
3. Wait for the user to pick one
4. After committing, ask before pushing

For the full commit workflow, invoke the `$commit` skill.

---

## Task Execution Rules

### Plan Node
- Treat any non-trivial request (≥3 steps, architectural, or behavioral change) as a planning task.
- Enter plan mode before implementation. Invoke the `$plan-task` skill.
- If new information invalidates the plan, STOP and re-plan immediately.

### Self-Improvement Loop
- After **any** user correction: update `docs/task/lessons.md` and encode a rule preventing recurrence.
- Review lessons at the start of each session or task.

### Verification Before Completion

**3-Tier Verification Gate Pipeline (BLOCKING):**

1. **Agent Self-Evaluation Gate** — Ask yourself: *"Is this the best solution?"* If NO, re-implement. Iterate until genuinely YES.
2. **Visual Verification Gate** — If the work affects UI/front-end: open a browser, navigate to affected pages, take screenshots, visually confirm. **Reading code or inspecting DOM does NOT count** — only rendered browser output. If purely back-end, this auto-passes.
3. **User Verification Gate** — STOP. Summarize changes and verification results. Include an explicit `Not Tested` list. Ask: "Would you like to test this before I proceed?" Wait for the user's response.

**Scenario Evidence Rule:** You may NOT claim work is complete unless all required behavior-path scenarios were executed end-to-end. If a scenario requires test data that doesn't exist, create a temporary fixture and clean up after.

**Blocker Protocol:** If any verification step cannot be completed, the work is unverified. Unverified work MUST NOT be committed. Report the blocker and leave changes uncommitted.

### Demand Elegance
- For non-trivial changes: pause and evaluate if a more elegant solution exists.
- Avoid over-engineering. Challenge your own output before presenting it.

---

## Task Management Protocol

1. **Plan first** — Write a checklist to `docs/task/todo.md` for multi-step work
2. **Track progress** — Mark completed items as work progresses
3. **Log observations** — Append to `docs/agent-observations/` logs before commit (or state "Observations: none")
4. **Document results** — Update task log and affected docs at batch boundaries
5. **Commit & push (after user approval)** — Invoke the `$commit` skill
6. **Capture lessons** — Update `docs/task/lessons.md` after corrections

### Batch Boundaries

Batch the documentation + commit cycle (don't run after every message). A batch triggers when:
- User signals completion or changes topic
- ~5 accumulated changes without a commit
- Session is ending
- User explicitly asks to commit

At each batch boundary:
0. Pass all 3 verification gates (blocking)
1. Log observations to `docs/agent-observations/`
2. Update today's task log: `docs/task/logs/YYYY-MM-DD.md`
3. Update affected documentation per trigger maps
4. Get user approval, present 3 commit message options
5. Commit & push (only after approval)

---

## Agent Observations — Mandatory Disclosure

During any task, you must proactively disclose findings. **Silence is a violation.**

- **`docs/agent-observations/critical.md`** — Blocking issues, security, data corruption
- **`docs/agent-observations/recommendations.md`** — Improvements, follow-up tasks
- **`docs/agent-observations/anomalies.md`** — Doc/code drift, inconsistencies

Before commit: review work, classify observations, append entries. If none: state "Observations: none."

Resolved items move from root files to `docs/agent-observations/closed/`.

---

## Documentation Sync

When modifying source files, update relevant documentation:
- Update "Last updated" dates on every doc edit
- Log completed work to `docs/task/logs/YYYY-MM-DD.md`

### Documentation Trigger Map

| Source Area | Update Doc | When |
|---|---|---|
| `includes/class-glitch-gateway.php` | `docs/plugin/architecture/1-gateway-core.md` | Payment method registration, order status mapping, supports changes |
| `includes/class-glitch-api-client.php` | `docs/plugin/architecture/2-api-integration.md` | Endpoint changes, auth headers, error handling, retry logic |
| `includes/class-glitch-webhook-handler.php` | `docs/plugin/architecture/3-webhook-system.md` | Event type routing, signature verification, idempotency changes |
| `includes/class-glitch-checkout.php`, `templates/checkout/` | `docs/plugin/features/1-checkout-flow.md` | Checkout flow, redirect, JS SDK integration, return URL handling |
| Refund handler classes | `docs/plugin/features/2-refund-processing.md` | Refund types, partial refund logic, chargeback handling |
| `admin/views/`, gateway settings | `docs/plugin/features/3-admin-settings.md` | Settings fields, mode switching, admin UI changes |
| Transaction manager classes | `docs/plugin/features/4-transaction-management.md` | Idempotency, transaction references, order meta |
| Environment config logic | `docs/plugin/features/5-environment-config.md` | Sandbox/production switching, debug logging, credential separation |

**Documentation is blocked until verification gates pass.** Never update docs before the user has verified or explicitly waived.

### Documentation Routing

When working on source code, search the doc index tables first:
```bash
rg -n -i "<task keywords>" docs/plugin/**/0-index.md
```

---

## Commit Rules (Quick Reference)

Full details: invoke the `$commit` skill.

- **Branch safety:** If on `master`/`main` — STOP. On `dev` — commit but ask before push.
- **Explicit staging:** Never `git add .` or `git add -A`. Always explicit file paths.
- **Subject format:** `<type>(<scope>): <summary>` — types: `feat`, `fix`, `refactor`, `docs`, `style`, `data`, `config`, `chore`
- **Present 3 options before committing.** User picks.
- **Never force push.**

---

## Task Ledger — Daily Logs (`docs/task/logs/YYYY-MM-DD.md`)

```markdown
# Task Log — MM/DD/YYYY

> 0 tasks

| Title | Description | Start Date | End Date | Category | Type |
| --- | --- | --- | --- | --- | --- |
```

- **Category:** One of: `Gateway`, `API`, `Webhooks`, `Checkout`, `Refunds`, `Admin`, `Security`, `Bug`, `Docs`
- **Type:** `Task` (single-scope) or `Sprint` (grouped multi-item)
- Prefer feature-focused consolidation over file-by-file rows

---

## Plan Lifecycle

Plans live in `docs/task/planning/` subdirectories:

| Folder | Meaning |
|--------|---------|
| `draft/` | New or in-progress plans |
| `pending/` | Approved but deferred |
| `completed/` | Done, tested, committed |

New plans always start in `draft/`. Invoke the `$plan-task` skill to create plans.

---

## Date-Prefix Rule

Files in date-scoped directories MUST use `YYYY-MM-DD-{slug}.md`:
- Plans: `docs/task/planning/draft/YYYY-MM-DD-{slug}.md`
- Reports: `docs/reports/YYYY-MM-DD-{slug}.md`

---

## No Backups in Source Directories

Never create `.bak`, `.old`, `.tmp`, `.orig`, or backup directories in source code. Use `docs/backups/` if needed.

---

## Element IDs on Every Rendered Element

> **Scope:** PHP templates in `templates/checkout/` and `admin/views/`.

Every HTML-producing element must have a descriptive `id` attribute: `{page-or-feature}-{section}-{element}` in kebab-case.
- No element may be rendered without an `id`
- Dynamic list items use the item's unique key
- Nested elements maintain parent hierarchy in their `id` prefix

### PHP Template Example

```php
<div id="glitch-checkout-form">
  <input id="glitch-checkout-card-number" type="text" name="card_number" />
  <button id="glitch-checkout-submit" type="submit"><?php esc_html_e( 'Pay Now', 'glitch-payment-gateway' ); ?></button>
</div>
```

---

## Coding Conventions

### PHP

- Follow **WordPress Coding Standards (WPCS)** — enforced by PHPCS
- Use strict typing: `declare(strict_types=1);` in all new files
- Sanitize all input: `sanitize_text_field()`, `absint()`, `wp_unslash()`
- Escape all output: `esc_html()`, `esc_attr()`, `esc_url()`, `wp_kses()`
- Use WordPress nonces for form security: `wp_nonce_field()` / `wp_verify_nonce()`
- Prefix all functions, hooks, and constants with `glitch_`

### File Naming

- Classes: `class-glitch-{name}.php` (e.g., `class-glitch-gateway.php`)
- Templates: kebab-case `.php` files in `templates/`
- Admin views: kebab-case `.php` files in `admin/views/`

### Database / Data

- Use WooCommerce CRUD APIs and order meta for transaction data — never raw SQL unless required
- All monetary amounts in **cents** (integer) — convert to ZAR display format only in templates
- Use `$wpdb->prepare()` for any custom queries

### Security

- Never store raw API keys in plain text logs or debug output
- Validate webhook signatures before processing any payload
- Use WordPress capabilities for admin actions: `current_user_can( 'manage_woocommerce' )`
- Rate-limit webhook endpoints to prevent abuse

---

## Rate Limit Prevention

- Be concise. Don't repeat the user's request.
- Plan before making tool calls. Prefer fewer, targeted calls.
- Batch independent operations. Reuse information.
- Target ~3–5 tool calls per response. ~300 lines per response.
- If output must be split, end with `... continuing` and proceed.

---

## Available Skills

Invoke these skills for structured workflows:

| Skill | Use when… |
|-------|-----------|
| `$plan-task` | Creating implementation plans before coding |
| `$execute-plan` | Executing a previously created plan |
| `$document-task` | Documenting completed work (task log + docs + observations) |
| `$commit` | Staging, committing, and pushing changes |
| `$commit-all` | Batch-committing all uncommitted changes |
| `$report` | Generating reports on work or topics |
| `$merge-master` | Merging dev into master/main |

---

## Related Documentation

- **Task tracking:** `docs/task/todo.md`, `docs/task/lessons.md`
- **Daily logs:** `docs/task/logs/YYYY-MM-DD.md`
- **Plans:** `docs/task/planning/` (draft → pending → completed)
- **Observations:** `docs/agent-observations/` (critical, recommendations, anomalies)
- **Reports:** `docs/reports/`

---

## Enforcement

These rules override all defaults. Never silently bypass any mandatory rule. If a required step cannot be completed, STOP and report the blocker. Only the user may waive a rule.