# **Appendix B: Working With AI Agents — A Contract for Machine Learners**
> This appendix is written for **AI coding agents** (and the developers who
> drive them). Everything here is the workflow this book itself was produced
> with: every code sample in Chapters 1-22 was written by an agent, run against
> a live server, and only then documented.
---
## **B.1 Where an Agent Learns SartajPhp (in order)**
1. **Router skill**: `.cursor/skills/sartajphp/SKILL.md` — decides which topic
file to open
2. **Topic skills**: `.cursor/skills/sartajphp/NN-*.md` (or the sources in
`docs/sartajphp/`)
3. **API stubs**: `vendor/sartajphp/sartajphp/res/Score/SphpDoc/Sphp/{Core,Dev,Gates,Kit,Lib,Tools}/`
+ `SphpDoc/global/` — real signatures, readable PHPDoc, no ionCube
4. **Runnable examples**: `apps/examples/` (topics) and `apps/examples/`
(this book's gates) — copy, run, modify
5. **Ebook**: https://www.sartajphp.com/ebook2-fullbook.html
Do **not** answer framework questions from general PHP knowledge or old blog
posts — the runtime core is ionCube-encoded, so stubs + skills + examples are
the ground truth. If a method is not in `SphpDoc` or a tested example, it does
not exist.
## **B.2 Naming Contract (Latest Framework)**
| Thing | Convention | Example |
|-------|-----------|---------|
| Classes, methods, functions, variables | CamelCase | `sphpApi`, `jsServer`, `$debugMode`, `getSphpApi()` |
| Gate event handlers | snake_case | `page_new`, `page_submit`, `page_event_rowclick` |
| Constants | UPPER_SNAKE | `PROJ_PATH`, `START_PATH` |
| Front fusion attributes | `fui-*` / `fun-*` / `fur-*` (kebab) | `fui-setForm`, `fun-setAJAX` |
| PHP fusion methods | `fi_*` / `fu_*` + CamelCase tail | `fu_setPerPageRows` |
| DB columns by prefix | `txt`, `txa`, `slt`, `num`, `dat`, `sqldata` | `txttitle`, `datdue_date` |
Skills ship with the matching vendor package — no old-version migration maps.
## **B.3 The Develop / Run / Test Loop (non-negotiable)**
A skill or doc is only true when it has been executed. The loop this book uses:
1. **Write** the Gate + Fronts under an app root (folder with `start.php`)
2. **Register** in `reg.php`
3. **Install schema** via a `*-install.html` event (`db/db_index.php` pattern,
Chapter 15)
4. **Run** against a live server — Apache sub-folder
(`http://localhost/SartajPhpDoc/`) or SphpServer
5. **Verify** every route: status 200 AND no `Fatal error|Parse error|Uncaught`
in the body AND the expected status message in the page
6. **Check** `cache/Sphp_errorLog.txt` for silent soft failures (Chapter 19)
A PowerShell sweep is the agent's unit test:
```powershell
$urls = @('http://localhost/SartajPhpDoc/blog.html', 'http://localhost/SartajPhpDoc/task.html')
foreach ($u in $urls) {
$r = Invoke-WebRequest -Uri $u -UseBasicParsing
$bad = if ($r.Content -match 'Fatal error|Parse error|Uncaught') {'ERR'} else {'ok'}
"{0} {1} {2}" -f $r.StatusCode, $bad, $u
}
```
POST flows need their CSRF-ish token: GET the form, extract
`name="form2re" value="..."`, re-post it with the fields (the hidden recID
field is `txtid`/`form2re` — see Chapter 15's edit flow).
## **B.4 Verified Pitfall Catalog (what actually broke during this book)**
Each of these cost a debugging cycle; agents should check them first:
1. **PHP class names are case-insensitive** — `class Pdo extends BasicGate`
collides with `PDO`. Use `PdoDemo`. (`Pdo`, `Sql`, `Db` are all risky.)
2. **Apache sub-folder ≠ root** — never hard-code `/gate.html`; always
`getGateUrl()`, `getThisGateUrl()`, `getEventUrl()` (they honor
`$projectUrl`).
3. **`viewData` sets the recID; your own `viewForm` must too** — a custom
model helper that fills values but skips `$form->setRecId($id)` makes the
edit form POST as an INSERT (duplicate rows). (Chapters 12, 15)
4. **SafeEval in Fronts is not full PHP** — no `(int)` casts; use
`intval($val)`.
5. **Calling `page_new()` inside an event wipes `statusMsg`** — factor a
`renderX($msg)` helper. (Chapter 12)
6. **Custom dbEngine must auto-connect in `executeQuery`** (Pagination calls
it cold), must NOT override `fetchQuery` with a flat array (Pagination
reads `$data["news"]`), and must not disconnect mid-request in
`executeQueryQuick`. (Chapter 12)
7. **FileUploader settings are `fui-*` on the Front** — the upload is saved
during `new FrontFile(...)`; setting the path in `page_submit` is too late.
`uploadDir` needs a trailing slash. (Chapter 17)
8. **`fun-setAJAX` forms still need normal validation flow** — check
`getCheckErr()` before and after `insertData`. (Chapter 17)
9. **Permission map comes from the session** — `getAuthenticatePerm()` loads
it; manually calling `sphpPermissions()->setPermissions()` creates ghost
permissions. (Chapter 14)
10. **ConsoleGate/NativeGate don't run under Apache** — CLI needs
`php -f start.php -- --gate …`, WebSocket needs SphpServer; the UI page
still renders under Apache, which is a useful half-test. (Chapters 21-22)
## **B.5 Reading Traces Like the Framework**
- Skip every `vendor/sartajphp/` frame; fix the first `apps/`, `fronts/`,
`masters/` frame (Chapter 19)
- `Couldn't Execute Query` inner errors carry the full SQL — read it, fix the
value escaping or schema, don't guess
- `Undefined array key "news"` from Pagination = engine/data-shape bug in
YOUR code
- Timestamped entries in `cache/Sphp_errorLog.txt` include the URL — correlate
with the request you just made
## **B.6 Authoring Rules When an Agent Writes Docs/Skills**
1. **Test before writing** — no code block goes into `docs/` or the ebook
unless it ran on the current vendor package
2. **Teach develop / run / test** — every topic needs create + run + verify
steps, not concepts alone
3. **Preserve author hints** (`docs2/`), complete with verified learning —
paths, classes, pitfalls, URLs
4. **No invented APIs** — verify against `SphpDoc` stubs and the ebook
5. **Current version only** — no old-API migration notes in skills
6. **No secrets** — admin passwords, OAuth keys, DB passwords never enter
docs; `comp.php` samples use placeholders
7. **Cite runnable paths** — `apps/examples/Ex17comps.gate.php`, not "an
example gate"
## **B.7 A Prompt That Works**
When tasking an agent with a new feature chapter or skill, the prompt shape
that produced this book:
> Study `apps/examples/ExNN*.gate.php` and its fronts. Create a gate
> `feature` under `apps/examples/`, register it, install schema via
> `db/db_book2.php`, and verify every event URL against
> `http://localhost/SartajPhpDoc/` (200 + no error tokens + expected status).
> Then write `ebook/book2/chapterNN.md` using ONLY the tested code, with a
> "Verify It Yourself" section listing the exact URLs.
The last sentence is the contract: **documentation may not exceed what was
executed.**
---
**Previous:** [Appendix A — Minimum Project Files](appendixA.md) ·
**Back to:** [Table of Contents](index.md)