Files
pr-vision/CONVENTIONS.md
peptiderepo 4eee9f5f64 PR Vision v0.3.0: per-call cost accountability + LLM call audit trail
P0 security:
- PRV_Gateway_Client: remove response body from RuntimeException (HTTP status only)
- PRV_Capture_Writer: allowlist-only write (prompt/response text, never headers/auth)
- Mandatory capture order: can_afford → probe → persist_result → update_row_cost → write_meta → capture_io
- capture_io last and wrapped in swallowing try/catch

New tables (SCHEMA_VERSION 3):
- prv_call_meta: cost/metadata per call, kept indefinitely
- prv_call_io: rendered prompt + raw response, pruned on retention window (default 90d)

New classes:
- PRV_Call_Meta_Table, PRV_Call_Io_Table: table schema + dbDelta
- PRV_Capture_Writer: metadata + I/O write; security allowlist enforced
- PRV_Prune_Cron: daily prv_daily_prune cron deletes aged prv_call_io rows only
- PRV_Cost_Rollup_Query: MTD summary, model breakdown, drill-down, projection
- PRV_Call_Log_Query: paginated + filtered call-log query + per-call I/O fetch
- PRV_Costs_Page + PRV_Costs_Renderer: Costs admin sub-page (cap progress, bento, model table, drill-down)
- PRV_Call_Log_Page + PRV_Call_Log_Table_Renderer: Call Log admin sub-page (filter bar, paginated table, WCAG AA pagination)
- PRV_Call_Drawer_Renderer: non-modal complementary drawer (5 states: Normal/Pruned/Legacy/Failed/Loading)
- PRV_Call_Drawer_Script: inline JS for drawer (300-line split from renderer)
- PRV_Call_Detail_Ajax: wp_ajax_prv_call_detail AJAX handler
- PRV_Admin_Page_Css: CSS provider (300-line split from PRV_Admin_Page)
- PRV_Probe_Run_Executor: inner probe loop (300-line split from PRV_Probe_Runner)

Updated:
- PRV_Probe_Result: tokens_in/tokens_out params + getters
- Both providers: report tokens_in/tokens_out from usage.prompt_tokens/completion_tokens
- PRV_Probe_Runner: slimmed to lock+UUID+delegation; injects PRV_Capture_Writer
- PRV_Config: get_io_retention_days(); PRV_IO_RETENTION_DEFAULT_DAYS constant
- PRV_Upgrader/Activator/Deactivator/Plugin: register new tables, cron, pages, AJAX
- Settings: retention days field + save in controller
- uninstall.php: DROP both new tables, clear prv_daily_prune cron
- Subnav 4-tab strip (Dashboard | Costs | Call Log | Settings) on all pages
- ARCHITECTURE.md, CHANGELOG.md, CONTEXT.md, CONVENTIONS.md updated

Tests:
- test-capture-writer.php: write_meta, write_io, P0 security (401 record has no key/Bearer/sk-or-)
- test-cost-audit.php: MTD reconciliation, projection, prune, forced capture_io exception, table drops

Agent-Session: peptiderepo-geomonitor-v0.3.0-cost-audit
2026-06-15 09:09:29 +00:00

104 lines
4.5 KiB
Markdown

# Conventions — PR Vision
**Version:** 0.3.0 | **Last updated:** 2026-06-15
Applies to all contributors and AI agents working in this repo. Where this document and `AGENT-OPERATING-STANDARD.md` conflict on process, the Standard wins; this document wins on code style.
---
## 1. PHP style
- **Standard:** WordPress Coding Standards (PHPCS `ruleset ref="WordPress"`).
- **Declare:** `declare(strict_types=1);` at the top of every PHP file.
- **Formatting:** Tabs for indentation (WP standard).
## 2. Naming
| Concept | Convention | Example |
|---------|-----------|---------|
| Class | `PRV_` prefix + PascalCase | `PRV_Cost_Ledger` |
| Interface | `PRV_` prefix + PascalCase | `PRV_Probe_Provider` |
| File | `class-prv-*.php` or `interface-prv-*.php` | `class-prv-probe-runner.php` |
| Option | `prv_` prefix | `prv_monthly_budget_usd` |
| Hook / cron | `prv_` prefix | `prv_weekly_probe` |
| Constant | `PRV_` prefix | `PRV_TARGET_DOMAIN` |
| wp-config key | `PRV_` prefix | `PRV_OPENROUTER_API_KEY` |
| Test file | `test-*.php` | `test-citation-detector.php` |
## 3. File structure
- **One class per file.** Interfaces get their own file.
- **300-line limit** (enforced by CI). Split at the method boundary when approaching the limit.
- Autoloader resolves `PRV_Foo_Bar` → `class-prv-foo-bar.php` via a search across `includes/` subdirectories.
## 4. Docblocks
Every class must have a preamble docblock:
```
/**
* <One-sentence what>.
*
* Who triggers: <which class/hook calls this>.
* Dependencies: <what this class needs to exist>.
*
* @see <cross-reference 1>
* @see <cross-reference 2>
* @package PrVision
*/
```
Every public method must have:
- `@param` with type + description.
- `@return` with type.
- A sentence listing side effects (DB writes, HTTP calls, option writes).
## 5. Security rules
- **Sanitize** all input at the boundary (`sanitize_text_field()`, `absint()`, `wp_unslash()`).
- **Escape** all output at render (`esc_html()`, `esc_url()`, `wp_json_encode()`, `wp_kses_post()`).
- **Nonce** every admin form action.
- **Capability** check (`manage_options`) every admin action handler.
- **No secrets in code** — read from wp-config constants at runtime.
## 6. Tests
- Tests live in `tests/unit/test-*.php` and are run by the CI `lint-php` job via `php $test`.
- Each test file `require_once`s `tests/bootstrap.php` and calls `exit( prv_test_summary() )`.
- Use `prv_assert()`, `prv_assert_equals()`, `prv_assert_throws()`.
- Mock HTTP via `$GLOBALS['prv_test_state']['remote_posts']` (queued responses).
- No PHPUnit dependency.
## 7. Adding a new provider
1. Create `includes/providers/class-prv-{name}-provider.php`.
2. Implement `PRV_Probe_Provider` (`probe()`, `get_name()`, `is_configured()`).
3. Add a branch in `PRV_Probe_Runner::resolve_provider()`.
4. Update `ARCHITECTURE.md` §5 (Providers table).
5. Add a parse test in `tests/unit/test-provider-parsing.php`.
## 8. Adding a new collector/panel pair
1. Implement `PRV_Data_Collector` in `includes/collector/`.
2. Implement `PRV_Dashboard_Panel` in `includes/panel/`.
3. Register both in `PRV_Plugin::init()` via `PRV_Collector_Registry::instance()`.
4. Update `ARCHITECTURE.md` §6 (Collector/Panel seam).
## 9. API key access (v0.2.3)
**Never read `PRV_OPENROUTER_API_KEY` directly in provider or handler code.**
All key reads must go through `PRV_Key_Store::get_key()`. This maintains the precedence chain (constant → encrypted option → none) and ensures a key set via the admin UI is used without code changes.
- Providers: call `PRV_Key_Store::get_key()` in `probe()`.
- AJAX handlers: call `PRV_Key_Store::get_key()` before any LLM call.
- New provider that needs the key: implement `is_configured()` as `'' !== PRV_Key_Store::get_key()`.
- Do NOT pass the resolved key to any client-side surface, log, exception message, or `error_log()`.
## 9. Capture pattern (v0.3.0+)
The call-audit trail follows a strict allowlist pattern:
- `PRV_Capture_Writer::write_meta()` accepts only: `visibility_row`, `run_id`, `peptide_slug`, `model`, `intent_label`, `tokens_in`, `tokens_out`, `cost_usd`, `latency_ms`, `cited`, `http_status`, `config_version`.
- `PRV_Capture_Writer::write_io()` accepts only: the rendered `prompt_text` (plain text) and `response_text` (LLM response content).
- **NEVER** pass `$headers`, `$parsed_args`, `Authorization`, raw HTTP request blobs, or any field not in the above lists.
- Capture calls are LAST in the probe loop and wrapped in a swallowing try/catch — failure must never propagate to the probe path or corrupt cap accounting.