# Agent Handoff — READ THIS FIRST

If you are an AI coding agent or developer taking over this project, you MUST read this document completely before writing any code. It is the single fastest path to full context and outlines your mandatory documentation duties.

---

## 🚀 NEXT AGENT START HERE

Welcome! This is **TFB Engine (Telegram Funnel Builder Bot)**, a hardened, production-ready marketing-funnel engine built on Telegram, currently running a staged personality/career quiz funnel with full interactive controls, unique analytics, and an integrated admin builder directly inside Telegram.

Before doing any work, ensure you understand the engineering constraints:
1. **PHP 8.1+ & UTF-8:** Native OOP, strictly typed (`declare(strict_types=1)` on every file).
2. **Zero Runtime Composer Dependencies:** Must run cleanly on shared cPanel hosting out of the box. No heavy frameworks.
3. **Prepared SQL Only:** All database operations use prepared queries and reside strictly in `src/Repositories/*`.
4. **Single-Surface Admin UI:** Virtually all admin navigation edits the same workspace message in-place to avoid chat spam.
5. **No Bottom Keyboards (Except Admin Start):** Everything interactive runs on InlineKeyboard (glass) buttons. The student has no bottom keyboard at all. The admin has exactly one bottom keyboard button: `/start` (for easy resets).

---

## 📋 BEFORE YOU DELIVER A ZIP / SAY DONE

Every coding agent working on this project inherits an absolute, non-negotiable documentation duty. Before declaring any task "done" and producing a release ZIP:

1. **Verify Syntax:** Run `find . -name '*.php' -exec php -l {} \;` and verify 0 errors.
2. **Run All Unit Tests:** Run `php tests/smoke.php`, `php tests/phase3_unit.php`, `php tests/phase05_score_engine_test.php`, and `php tests/phase06_admin_unit.php` and ensure they are all 100% green.
3. **Update `docs/PROJECT_STATUS.md`:** Mark what is completed, partial, or backlog.
4. **Update `docs/STATUS.json`:** Update the version, date, and module state.
5. **Update `docs/CHANGELOG.md`:** Document your changes clearly.
6. **No Secrets:** Ensure no real bot tokens, passwords, or secrets are left in docs, logs, or comments.
7. **Perform Handoff:** Write or append a handoff section at the bottom of this file (`docs/AGENT_HANDOFF.md`) detailing exactly what you changed, why, how verified, and what risks remain.

---

## 📜 PERMANENT AGENT GOVERNANCE PROTOCOL

> **MANDATORY POLICY FOR ALL FUTURE CODING AGENTS:**
> 
> "Documentation is part of the product.
> Any coding agent working on TFB MUST, after every complete change and BEFORE delivering zip/final output:
> - update project status
> - update affected docs
> - update changelog
> - keep comments accurate
> - record what was done, how, what remains, and risks
> This duty transfers to every future coding agent. If docs are stale, the task is not done."

---

## 📌 CURRENT PROJECT SNAPSHOT (1.6.0)

- **Version:** v1.6.0
- **Status:** Production-ready MVP + Update Pack + Smart .htaccess hardening fully implemented and audited.
- **Key Modules:** 
  - **Student Flow:** Inline options only, clean in-place edits, strictly ordered results (voice last), and single CTA attached once.
  - **Admin Flow:** Sticky workspace edits, automatic prompt message cleanup, +/- scoring draft UI, campaign time ranges, and secure backup deletion.
  - **Operations:** Pre-filled installer defaults, post-install self-cleanup, automated cron broadcast pump, and smart layered `.htaccess` protection.

---

## 🤝 AGENT HANDOFF RECORD (2026-08-18 — v1.7.1 perf/transition)

Transition setting is 0..5000 but must never be implemented as multi-second webhook sleep. `PerfTrace` is opt-in (`app.perf_trace` or `TFB_PERF_TRACE`) and writes compact `storage/logs/perf.log`; keep default OFF. Callback order on touched paths is dedupe → authz/state validation → ACK → mutation/render. Measured before/after and host-latency math: `docs/PERF_TRANSITION_REPORT.md`. Successor must measure before further optimization and preserve idempotency/security/product flows.

## 🤝 AGENT HANDOFF RECORD (2026-08-17 — v1.7.0 secondary/ops)

Implemented gated phases 0–8: category migration/backfill, single-active secondary, E1–E7 routing, six media types, multistage callbacks/keyboard/protect, global update and callback dedupe, transactional session/back locks, files-channel-independent update safety, rollback/log paths, ZIP limits, SQL hardening, health no-migrate, retention/pump/reminder/cache/default/deep-link controls. Proof and residuals: `docs/V1_7_ACCEPTANCE_REPORT.md`.

## 🤝 AGENT HANDOFF RECORD (2026-08-17 — v1.6.1 production stability)

Implemented and executable-tested phases 0–13: secondary schema reconciliation; back rewind; safe Telegram edits; 512KB×3 logs and warning throttle; weak-host timing limits; JSON test transfer; manifest/wrapper-aware update with safety/lock/maintenance/apply→migrate→verify; ZIP backup metadata; streamed current/old restore with future refusal; terminal downgrade; installer convergence; Ads/student/admin regression. Dogfood package validation and exact proof are in `docs/PRODUCTION_STABILITY_REPORT.md`.

## 🤝 AGENT HANDOFF RECORD (2026-08-17 — v1.6.0 hotfix B1–B4)

Campaign payload routing is now independent of the bare `/start` default toggle. Secondary text is published to the files channel and text/voice/document delivery uses anonymous `copyMessage`; captions and ordered source references are persisted. The legacy plain-text quiz answer path was removed from `UpdateRouter`, so arbitrary text always reaches the exact help fallback while callbacks still score. Verified with live PHP HTTP, MariaDB, mock Telegram, the full legacy suite, and the S1–S28 matrix. No unrelated product behavior or version number changed.

## 🤝 AGENT HANDOFF RECORD (2026-08-16 — v1.6.0)

### What changed
Universal prompt cleanup; valid bold/inline numbered questions; fresh link starts; no result previews; global transition milliseconds; inline-only broadcasts with working scoped filters; test-first user filters; editable current-only slugs; configurable gates; multi-item secondary packs; editable channel IDs; admin student-link flow; corrected per-test/campaign analytics; one-time reminder worker; and terminal update/downgrade reporting.

### Verification
PHP lint across every PHP file; live PHP server + MariaDB + mock Telegram; 16 automated scripts with 587 PASS / 0 FAIL; legacy smoke/unit/domain/admin/ops/update-pack suites; dedicated 10-second reminder and campaign-attribution tests; direct DB verification for migrations, scoped audiences, slug invalidation, secondary no-session behavior, gate rendering, channel config writes, and update/downgrade terminal errors. Final package verification is recorded in the delivery report.

### Residual risks
Only the limits documented in `KNOWN_ISSUES.md`: cron granularity, Telegram button constraints, supported secondary media types, and non-atomic shared-host file swapping.

## 🤝 AGENT HANDOFF RECORD (2026-07-28)

### What Was Changed & Why
1. **Resolved Bot Silence with .htaccess Active (F1):** Replaced the root `.htaccess` file's unconditional `Require all denied` with a secure, layered rewrite and block model. It blocks direct public access to sensitive directories (`config/`, `src/`, `storage/`, etc.) and extensions (`.sql`, `.log`, `.bak`, `.env`, `.git`) with `403 Forbidden` but cleanly allows webhook POSTs and health GETs to flow to `/public/index.php`. Added `Require all granted` at the top of `/public/.htaccess` to ensure maximum compatibility.
2. **Audited Zip Size Variance & Verified Package Integrity (F2):** Re-extracted the original project ZIP and ran a recursive file comparison. Confirmed that **0 files** (PHP, tests, DB scripts, templates) were lost. The small 1% size difference is purely due to text updates in docs and differences in zip utility compression.
3. **Previous Releases Changes:** Added sticky workspace navigation, centrally automated prompts/inputs cleanup, unique analytics with time ranges, non-member broadcast SQL fix, profile scoring in-place edit, settings audit, and secure backup deletion.

### How Verified
* Ran a recursive file check confirming no files from the original zip were omitted (0 missing).
* Re-ran all unit/smoke tests (smoke, phase3, phase5, phase6, installer) and verified 100% green.
* Verified that both health URL and webhook endpoint work flawlessly with `.htaccess` active.

### Residual Risks
* Ensure the bot remains an administrator of the main channel for accurate membership logging.
* Some cPanel shared hosts might restrict `AllowOverride` in Apache config; ensure they support `.htaccess` overrides.
* Verify webroot maps to `/public/` if possible, otherwise rely on the fallback rewrite in the root `.htaccess`.
