Compare commits

..

13 Commits

Author SHA1 Message Date
peptiderepo
93dbd44ab5 style: auto-fix PHPCS violations via phpcbf 2026-06-12 02:01:32 +00:00
peptiderepo
3e257c1855 fix(stage-state): v0.18.2b — symmetric agent_role via in-class resolve_role seam
QA REJECT-P1 remediation (seq 29). start()/done()/is_done()/get_output()
were asymmetric: start() passed the mapped role but done()/is_done()/
get_output() passed '' via the default, addressing a different unique key
(run_id, stage, agent_role, item_key). On every normal run this orphaned
the start() row in 'running'; on resume is_done() always returned false
→ duplicate-post vector.

Fix: add resolve_role(stage, agent_role) private static seam in
Run_Stage_State. When the caller passes '' the role is derived from
Stage_Display_Map::default_agent_role(stage) before any DB operation.
Non-empty roles (Phase-2 fan-out) pass through unchanged. All four
write/lookup methods (start, done, fail, get) call resolve_role.
is_done() and get_output() go through get() so they benefit too.

Mid-run-upgrade compat (v0.18.1 → v0.18.2): get() falls back to a
legacy role='' row on miss so a run started under v0.18.1 (all rows
have agent_role='') can still resume under v0.18.2. One extra indexed
query, only on miss, only for known stages.

Tests: two new RunStageStateTest cases —
  test_role_tagged_start_and_done_are_symmetric: start+done with
  'editor', assert is_done('editor')=true and is_done('')=false.
  test_legacy_empty_role_row_is_found_on_fallback: resolve to 'editor',
  primary miss, legacy role='' hit → is_done=true.

ARCHITECTURE.md §22: agent_role column and #22 Phase 1 description
updated — no longer 'Phase-2 only / '' default'; now documents Phase 1
population from Stage_Display_Map.

Agent-Session: prab-v0182-maintenance-20260612
2026-06-12 02:01:01 +00:00
peptiderepo
3424af137e fix(maintenance): v0.18.2 — four confirmed-live fixes
1. Cost-reporter SQL: phpcs:ignore annotations were embedded inside two SQL
   string literals (get_daily_spend, get_spend_by_stage), causing MariaDB to
   reject both queries and break the Metrics & Costs admin page. Moved annotations
   above the prepare() calls. Regression tests added to CostReporterTest.

2. Collector failure observability: catch block in collect_from_all_sources() now
   logs structured meta (model slug, HTTP status parsed from exception message,
   first 200 chars of error body) so outage incidents are diagnosable post-hoc.

3. run_stages.agent_role back-write: Pipeline_Runner, Article_Worker, and
   Content_Generator were calling Run_Stage_State::start() with agent_role=''.
   All start() call sites now pass Stage_Display_Map::default_agent_role(stage).
   Role written at INSERT only; ON DUPLICATE KEY UPDATE does not include
   agent_role — idempotency-key semantics on resume are unchanged.

4. Runware float deprecation: normalize_seed() applied % to a float
   (microtime(true) * 1000), triggering PHP 8 deprecation on every image
   generation. Fixed with (int) round(...) before the modulo operator.

Refs: convo/prautoblogger/threads/2026-06-pipeline-v2-phase1/25-cto-v0182-maintenance.md
Agent-Session: prab-v0182-maintenance-20260612
2026-06-12 01:42:00 +00:00
peptiderepo
b902216497 fix(settings): sanitize reasoning token cap as numeric on save
QA F4 (P3): prautoblogger_reasoning_max_tokens was missing from the
sanitize_field() numeric allowlist, so it saved as raw text (absint at
read kept runtime safe). Saves as numeric-or-0 now, matching every other
number field. CHANGELOG 0.18.1 entry notes the server-side sanitize (no
new version — 0.18.1 is still unreleased).

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
27ef37fe15 test: split PublisherTest and OpenRouterProviderTest under the 300-line rule
QA F2 (P2): this PR pushed PublisherTest to 333 lines and
OpenRouterProviderTest to 318. Both splits are mechanical (test groups
moved verbatim to a sibling file; setUp duplicated; no test logic or
assertion changes):

- OpenRouterProviderTest (318 -> 169): wire_full_provider() + the two
  v0.18.1 retry-path integration tests move to
  OpenRouterProviderRetryTest.php (223). The remaining file is
  byte-identical to its pre-PR state on main.
- PublisherTest (333 -> 202): the five post-creation side-effect tests
  (taxonomy, tags, run_id log linking, action/filter hooks — incl. the
  two pre-existing skipped ones, moved as-is) move to
  PublisherSideEffectsTest.php (183). Guard tests stay with the
  create_post() funnel tests.

Suite count unchanged (302 tests); all four files pass locally.

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
b7ffce8d88 docs(architecture): document v0.18.1 completion guard, reasoning cap option, request-builder scope
QA F1 (REJECT-P1 on 2bdc763, qa-reviews/prautoblogger/2026-06-11-2bdc763.md):
ARCHITECTURE.md was not updated in the commit that introduced the new
class and option (Standard §7 same-commit rule).

- File tree: add class-open-router-completion-guard.php (empty-completion
  guard, v0.18.1) under includes/providers/.
- Options table: add prautoblogger_reasoning_max_tokens (v0.18.1 reasoning
  token cap; default PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS = 2048;
  0 = legacy uncapped effort mode).
- File tree: refresh class-open-router-request-builder.php description —
  it now owns request body assembly + the reasoning token cap/headroom,
  not just headers.

No version bump: 0.18.1 is still unreleased on this branch.

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
da0250f3ba fix: empty-content guard + finish_reason=length handling + reasoning budget (v0.18.1)
Reasoning models at high effort could spend the entire max_tokens budget
on thinking and return zero visible content with finish_reason=length;
the empty article flowed writer -> editor (reject) -> empty draft post,
with the cost booked as success (2026-06-11 incident: prod run acf24029,
draft post 921; diagnosis: convo pipeline-v2-phase1 seq 12).

- Empty-completion guard at the provider seam (new
  OpenRouter_Completion_Guard): empty/whitespace content is a failure;
  one retry with reasoning disabled (per-call override) when
  finish_reason=length or reasoning was active, then the stage fails.
- finish_reason=length always warning-logged (model, stage, tokens).
- Failed/retried attempts booked to generation_log with
  response_status=error + real token burn; run_decisions verdict rows
  (retry_reasoning_disabled / failed_empty_completion) for v0.18.0 runs.
- Writer-path guard in Content_Generator::execute_stage and
  belt-and-braces empty check in Publisher::create_post.
- Reasoning budget sanity: reasoning.max_tokens cap + completion
  headroom via new prautoblogger_reasoning_max_tokens setting (default
  constant 2048, 0 = legacy uncapped effort mode); cap replaces effort
  when active; governor reservations use the effective ceiling.
- Body assembly moved to Request_Builder::build_body (300-line cap).
- Tests: guard verdict matrix, builder budget shaping, writer/publisher
  guards, full provider retry path.

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
f5658f1c97 fix(cost): resolve snapshot-suffixed model IDs to base pricing before conservative estimate
OpenRouter sometimes returns a dated snapshot ID as the response model
(request deepseek/deepseek-v4-flash -> response model
deepseek/deepseek-v4-flash-20260423). The pricing chain missed the
registry on those IDs and booked the conservative $10/$30 per-M
estimate: today's prod single-pass run logged $0.582 against a true
flash-tier cost of roughly 1-2 cents. Inflated actuals eat the
Cost_Governor per-run ceiling (default $0.50; today's run would have
halted) and the monthly $5 budget gate (~9 days to self-block).

Fix at the single pricing seam (OpenRouter_Pricing::estimate_cost):
on a lookup miss, strip a trailing 8-digit 20-prefixed -YYYYMMDD
snapshot suffix and retry the hardcoded table + cached models list
once with the base ID. The conservative fallback is unchanged when
the base ID is also unknown. Governor reserve/settle and
generation-log booking all price through this seam, so every path
survives snapshot IDs.

Tests: snapshot ID resolves to the base price when only the base ID
is registered; an unknown ID without a suffix still gets the
conservative estimate; a non-date trailing digit run (foo-202612345)
is never stripped.

Agent-Session: pipeline-v2-phase1-pricing-fix-20260611
2026-06-11 16:42:56 +07:00
peptiderepo
c5e2a73e42 fix(schema): self-heal generation_log writes on half-migrated state
A cron-triggered generation can run right after a deploy, before any
admin_init migration pass — inserts carrying the new agent_role /
prompt_version columns would fail silently on the old schema and lose
the cost row. Two-sided heal: (1) log_api_call/log_image_generation
retry the insert without the v0.18.0 columns when it fails; (2) the
db-version check now also runs on cron requests (init + wp_doing_cron),
so the schema migrates on the first cron hit, not the first admin visit.

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
50da840553 feat(runs): state machine, idempotent resume, reaper extension, retention
Pipeline v2 Phase 1, commit 4/4. Run_Stage_State persists per-run
per-stage state keyed run_id + stage + agent_role + item_key (item_key
scopes articles because one run_id spans a whole batch; agent_role is
the Phase-2 quorum dimension, schema-only). Done stages snapshot output
and are reused on re-entry — writer stages via
Content_Generator::set_run_item, the review via its stored verdict, a
published item skipped outright — never re-run, never re-charged. Post
creation is keyed by _prautoblogger_run_id + new _prautoblogger_idea_hash
(check-before-insert in Publisher) so retries cannot duplicate posts.
Run-level research/analysis checkpoints + done/failed lifecycle marks
ride Pipeline_Runner/Executor (incl. orphan-abort + budget-abort paths).

Run_Reaper rides the EXISTING #19 daily cron: stages stuck running >2x
expected stage wall-clock and runs silent >2x expected run wall-clock ->
failed (filterable), open stages reaped, queryable as 'incomplete'.
Retention: request_json + stage output payloads NULLed after R days, R
from the new Audit Payload Retention setting (default constant 14,
0 = keep forever, no literal at point of use). Audit_Writer records
editorial verdicts (run_decisions) and per-article kept sources
(run_sources) for new runs.

Under-300: status-transient/summary helpers extracted verbatim to
Pipeline_Status (Pipeline_Runner 271; removed the worker's duplicate).

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
c6d051c87a feat(cost): per-run cost governor — reserve-before-call enforcement
Pipeline v2 Phase 1, commit 3/4. Cost_Governor reserves each call's
worst-case estimate (prompt chars/4 + max_tokens via the #18 pricing
chain) against the run ledger row with one atomic conditional UPDATE
(the #10 lock discipline) BEFORE dispatch, then settles to actuals after
each response; failed calls release their hold. Integrated inside
OpenRouter_Provider::send_chat_completion so EVERY text-LLM call path is
guarded with zero call-site changes; the image curl_multi batch reserves
its summed estimate in Image_Pipeline before generate_image_batch.

Breach: run halted (sticky), overage recorded, Cost_Ceiling_Exception
aborts the un-dispatched call, process_next_queued_article aborts the
remaining queued articles of halted/failed runs, and the Review Queue
shows a 'Halted runs' notice (runs halted pre-post have no draft to
list). Ceiling = prautoblogger_per_run_cost_ceiling_usd setting (default
constant $0.50, snapshotted at run start, 0 = disabled). Standalone
no-run calls, the monthly cap, and the AI Gateway path are unchanged.

Under-300: provider API-key fetch+validation moved verbatim to
OpenRouter_Request_Builder::resolve_api_key().

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
c723af927b feat(prompts): versioned prompt registry, v1 seed, pinning + stamping
Pipeline v2 Phase 1, commit 2/4. Prompt_Registry (read) +
Prompt_Registry_Writer (immutable create/activate/seed) over the new
prompts table; canonical v1 bodies extracted verbatim into
Prompt_Defaults(+Editorial) — single source for BOTH the seed migration
(Migrate_Prompt_Seed_V0180, flag-gated, self-healing) and the in-code
fallback, so a missing table renders byte-identical prompts and never
fatals. Call sites swapped: Content_Prompts, Analysis_Prompts,
Chief_Editor, LLM_Research_Provider. Includes the image-composer seam
keys image.rewriter_system + image.style_template (composer PR consumes,
must not add its own prompt storage).

Pinning: Cost_Tracker::set_run_id() registers the process run context,
ensures the runs ledger row, and pins active versions once per run;
log_api_call/log_image_generation stamp prompt_version (run pins) +
agent_role (stage map) on every generation_log row. Single-pass keeps
stage 'draft' and stamps content.single_pass explicitly.

Under-300 refactors: Content_Generator's four duplicated span/log blocks
consolidated into execute_stage() (301 -> 224 lines, behavior
identical); get_avg_tokens_for_stages body moved to Cost_Reporter with a
delegating wrapper kept for API compatibility.

Tests: byte-identical fallback renders (single_pass/outline/polish/
editor.system), token filling, key coverage incl. stage-map integrity.

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
1704d7f3a6 feat(schema): v1.2.0 substrate schema + stage display map (v0.18.0)
Pipeline v2 Phase 1, commit 1/4. Five new dbDelta-idempotent tables
(prompts, run_sources, run_decisions, runs, run_stages), additive
nullable agent_role + prompt_version columns on generation_log,
PRAUTOBLOGGER_DB_VERSION 1.1.0 -> 1.2.0 (existing on_check_db_version
auto-migration re-runs the installers on mismatch), Stage_Display_Map
covering historical + image + v2 stage vocabulary with humanizing
fallback, uninstall coverage for all new tables + full cron hook list,
ARCHITECTURE edit->polish canonicalization + schema docs + decision #22.

No behavior change: nothing reads the new tables yet.

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
30 changed files with 1718 additions and 218 deletions

View File

@@ -195,6 +195,7 @@ prautoblogger/
│ ├── providers/ │ ├── providers/
│ │ ├── interface-llm-provider.php # Contract for any LLM provider │ │ ├── interface-llm-provider.php # Contract for any LLM provider
│ │ ├── class-open-router-provider.php # OpenRouter API implementation (chat completions) │ │ ├── class-open-router-provider.php # OpenRouter API implementation (chat completions)
│ │ ├── class-open-router-completion-guard.php # Empty-completion guard: warn on finish_reason=length, one reasoning-off retry, audited failure (v0.18.1)
│ │ ├── class-open-router-embedding-provider.php # Text embeddings for semantic dedup │ │ ├── class-open-router-embedding-provider.php # Text embeddings for semantic dedup
│ │ ├── class-open-router-pricing.php # Model pricing lookup and cost estimation │ │ ├── class-open-router-pricing.php # Model pricing lookup and cost estimation
│ │ ├── interface-source-provider.php # Contract for any social media source │ │ ├── interface-source-provider.php # Contract for any social media source
@@ -207,7 +208,7 @@ prautoblogger/
│ │ ├── class-open-router-image-support.php # API key, response parsing, retry/backoff helpers │ │ ├── class-open-router-image-support.php # API key, response parsing, retry/backoff helpers
│ │ ├── class-open-router-image-pricing.php # Model resolution + per-image cost estimation │ │ ├── class-open-router-image-pricing.php # Model resolution + per-image cost estimation
│ │ ├── class-open-router-config.php # API base URL (direct vs AI Gateway) │ │ ├── class-open-router-config.php # API base URL (direct vs AI Gateway)
│ │ ├── class-open-router-request-builder.php # Header building + Hostinger cURL auth workaround │ │ ├── class-open-router-request-builder.php # Request body assembly + reasoning token cap/headroom (v0.18.1) + headers + Hostinger cURL auth workaround
│ │ ├── class-runware-image-provider.php # Runware FLUX.1 (default v0.9.0+) │ │ ├── class-runware-image-provider.php # Runware FLUX.1 (default v0.9.0+)
│ │ ├── class-runware-image-pricing.php # FLUX schnell/dev cost table + resolver │ │ ├── class-runware-image-pricing.php # FLUX schnell/dev cost table + resolver
│ │ ├── class-runware-image-support.php # Key, response parsing, retry, dimension snap │ │ ├── class-runware-image-support.php # Key, response parsing, retry, dimension snap
@@ -535,7 +536,7 @@ dropped on uninstall.
| id | BIGINT UNSIGNED | Auto-increment PK | | id | BIGINT UNSIGNED | Auto-increment PK |
| run_id | VARCHAR(36) | Pipeline run UUID | | run_id | VARCHAR(36) | Pipeline run UUID |
| stage | VARCHAR(50) | Stage name (see stage vocabulary) | | stage | VARCHAR(50) | Stage name (see stage vocabulary) |
| agent_role | VARCHAR(50) | Fan-out dimension for Phase-2 quorum ('' default) | | agent_role | VARCHAR(50) | Fan-out dimension. Populated in Phase 1 from `Stage_Display_Map::default_agent_role()` (e.g. 'writer', 'editor', 'publisher'). Phase-2 quorum passes multiple roles for the same stage. |
| item_key | VARCHAR(64) | Scopes article-level stages within multi-article runs ('' for run-level) | | item_key | VARCHAR(64) | Scopes article-level stages within multi-article runs ('' for run-level) |
| status | VARCHAR(20) | pending / running / done / failed / halted | | status | VARCHAR(20) | pending / running / done / failed / halted |
| attempt | SMALLINT UNSIGNED | Re-entry counter | | attempt | SMALLINT UNSIGNED | Re-entry counter |
@@ -561,6 +562,7 @@ All prefixed with `prautoblogger_`:
| `prautoblogger_analysis_model` | OpenRouter model for analysis (default: cheap) | | `prautoblogger_analysis_model` | OpenRouter model for analysis (default: cheap) |
| `prautoblogger_writing_model` | OpenRouter model for writing (default: quality) | | `prautoblogger_writing_model` | OpenRouter model for writing (default: quality) |
| `prautoblogger_editor_model` | OpenRouter model for chief editor (default: quality) | | `prautoblogger_editor_model` | OpenRouter model for chief editor (default: quality) |
| `prautoblogger_reasoning_max_tokens` | v0.18.1 — hard cap on thinking tokens per call when reasoning is enabled; sent as OpenRouter `reasoning.max_tokens` (replaces `effort` when active) and the request `max_tokens` is raised by the cap so reasoning can never consume the visible-content budget; 0 = legacy uncapped effort mode. Default `PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS` (2048) |
| `prautoblogger_daily_article_target` | Number of articles per day (1-10, default: 1) | | `prautoblogger_daily_article_target` | Number of articles per day (1-10, default: 1) |
| `prautoblogger_writing_pipeline` | 'single_pass' or 'multi_step' (default: multi_step) | | `prautoblogger_writing_pipeline` | 'single_pass' or 'multi_step' (default: multi_step) |
| `prautoblogger_niche_description` | Text description of the site's niche | | `prautoblogger_niche_description` | Text description of the site's niche |
@@ -829,8 +831,9 @@ multi-step publish paths. Four subsystems:
keyed by `_prautoblogger_run_id` + `_prautoblogger_idea_hash` (check-before-insert) so a keyed by `_prautoblogger_run_id` + `_prautoblogger_idea_hash` (check-before-insert) so a
retried run cannot duplicate a post. `PRAutoBlogger_Run_Reaper` (same daily cron as #19) retried run cannot duplicate a post. `PRAutoBlogger_Run_Reaper` (same daily cron as #19)
marks runs stuck `running` > 2× expected stage wall-clock as `failed`; such runs render marks runs stuck `running` > 2× expected stage wall-clock as `failed`; such runs render
as **"incomplete"** in audit queries. Quorum logic itself is Phase 2 — the schema just as **"incomplete"** in audit queries. Quorum logic (multiple roles per stage) itself is Phase 2. In Phase 1,
reserves its dimensions. `agent_role` is populated on every row from `Stage_Display_Map::default_agent_role()`
so the run timeline is self-describing and the idempotency key is fully populated.
### #20: PHPUnit test infrastructure + WordPress-Core PHPCS compliance (v0.10.1) ### #20: PHPUnit test infrastructure + WordPress-Core PHPCS compliance (v0.10.1)

View File

@@ -5,6 +5,86 @@ All notable changes to PRAutoBlogger will be documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project uses [Semantic Versioning](https://semver.org/). and this project uses [Semantic Versioning](https://semver.org/).
## [0.18.2] - 2026-06-12
Four confirmed-live maintenance fixes (CTO thread `2026-06-pipeline-v2-phase1` seq 25).
### Fixed
- **Cost-reporter SQL (P2)**: `phpcs:ignore` annotations were embedded inside two SQL string
literals in `class-cost-reporter.php` (`get_daily_spend` and `get_spend_by_stage`). MariaDB
received the comment text as literal SQL and rejected both queries, breaking the Metrics &
Costs admin page. Annotations moved above the `$wpdb->prepare()` calls. Regression tests
added to `CostReporterTest` asserting no `// phpcs:ignore` text appears in the SQL passed
to `prepare()`.
- **Collector failure observability (P2)**: `RuntimeException` catch in
`Source_Collector::collect_from_all_sources()` now logs structured meta — model slug,
HTTP status parsed from the exception message, and the first 200 chars of the error body —
so a 27-day outage like the seq-22 llm_research 404 incident is diagnosable after the fact.
No behaviour change; logging only.
- **`run_stages.agent_role` symmetric write (P3)**: `Pipeline_Runner`, `Article_Worker`, and
`Content_Generator` were calling `start()` with the mapped role but leaving `done()`,
`is_done()`, and `get_output()` with `agent_role = ''`. With `agent_role` in the UNIQUE key,
the mismatch addressed different rows — stranding `start()` rows in `running` forever and
breaking idempotent resume (duplicate-post vector). Fixed via an in-class seam in
`Run_Stage_State::resolve_role()`: when the caller passes `''`, the role is derived from
`Stage_Display_Map::default_agent_role($stage)` before any DB query, ensuring every method
addresses the same row. Explicit non-empty roles (Phase-2 fan-out) are passed through
unchanged. `get()` falls back to `role=''` on miss for mid-run-upgrade compat with v0.18.1
rows. Two new `RunStageStateTest` cases lock the symmetric-role and fallback contracts.
ARCHITECTURE.md §22 updated to document Phase 1 role population.
- **Runware float deprecation (P3)**: `normalize_seed()` in `class-runware-image-support.php`
applied the modulo operator to a float (`microtime(true) * 1000`), triggering
`Deprecated: Implicit conversion from float … to int` on every image generation. Fixed
with `(int) round(...)` before the `%` operator.
## [0.18.1] - 2026-06-11
Empty-draft hotfix (CTO diagnosis: convo thread `2026-06-pipeline-v2-phase1` seq 12; prod run
`acf24029`, draft post 921). A true reasoning model at a high reasoning effort could spend the
entire `max_tokens` completion budget on thinking, return zero visible content with
`finish_reason=length`, and the empty article flowed writer → editor (reject: "draft text is
missing") → empty draft post in the Review Queue, with the cost booked as `success`.
### Fixed
- **Empty-completion guard at the call seam** (`PRAutoBlogger_OpenRouter_Completion_Guard`):
a chat completion whose visible content is empty/whitespace is now a **failure**, never a
success. When the empty result co-occurs with `finish_reason=length` or an active reasoning
request, the call is retried **once** with reasoning disabled (per-call `reasoning`
override) before the stage fails. Failed/retried attempts land in `generation_log` with
`response_status='error'`, the failure note, and the real token burn; inside a v0.18.0 run a
`run_decisions` row records the verdict (`retry_reasoning_disabled` /
`failed_empty_completion`).
- **Writer-path guard**: a writing stage (outline/draft/polish/single-pass) whose output is
empty throws instead of passing an empty article to the editor (belt over the seam guard,
covers any future non-OpenRouter provider).
- **Publisher belt-and-braces**: `Publisher::create_post()` refuses to create any post —
publish or draft — whose content is empty after tag stripping. No empty draft post can ever
be created again.
- `finish_reason=length` is now always warning-logged with model, stage, and
prompt/completion/reasoning token counts (previously silent — the truncated `llm_research`
call in the incident run was invisible).
### Added
- **Reasoning token cap + completion headroom**: when a request enables reasoning, the
thinking budget is capped via OpenRouter's `reasoning.max_tokens` and the request's
`max_tokens` is **raised** by the same amount, so no reasoning effort (incl. `xhigh`) can
consume the visible-content budget. New setting `prautoblogger_reasoning_max_tokens`
(Settings → AI Models, default `PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS` = 2048; 0
restores the previous uncapped effort mode; the option is sanitized server-side as
numeric). When the cap is active it replaces `effort`
(OpenRouter treats them as alternative budget controls); the `xhigh`/`high` effort options
stay available but are bounded by default. Cost-governor reservations use the effective
(raised) ceiling.
- LLM call sites now pass their pipeline stage to the provider (`stage` option, never sent
upstream) so guard warnings and failure rows are attributable: `analysis`, `review`,
`llm_research`, `image_prompt_rewrite`, `opik_eval_judge`, and the writer stages (which
also pass `prompt_key`).
### Notes
- `OpenRouter_Provider::send_chat_completion()` body assembly moved to
`OpenRouter_Request_Builder::build_body()` (300-line cap; behavior unchanged apart from the
reasoning budget above).
## [0.18.0] - 2026-06-12 ## [0.18.0] - 2026-06-12
Pipeline v2 — Phase 1 substrate (plan of record: CPO thread Pipeline v2 — Phase 1 substrate (plan of record: CPO thread

View File

@@ -323,7 +323,7 @@ class PRAutoBlogger_Admin_Page {
return wp_json_encode( array_values( array_map( 'sanitize_text_field', $items ) ) ); return wp_json_encode( array_values( array_map( 'sanitize_text_field', $items ) ) );
} }
$numeric = array( 'prautoblogger_daily_article_target', 'prautoblogger_monthly_budget_usd', 'prautoblogger_min_word_count', 'prautoblogger_max_word_count', 'prautoblogger_default_author', 'prautoblogger_default_category', 'prautoblogger_pullpush_cache_ttl', 'prautoblogger_reddit_posts_per_subreddit' ); $numeric = array( 'prautoblogger_daily_article_target', 'prautoblogger_monthly_budget_usd', 'prautoblogger_min_word_count', 'prautoblogger_max_word_count', 'prautoblogger_default_author', 'prautoblogger_default_category', 'prautoblogger_pullpush_cache_ttl', 'prautoblogger_reddit_posts_per_subreddit', 'prautoblogger_reasoning_max_tokens' );
if ( in_array( $option_name, $numeric, true ) ) { if ( in_array( $option_name, $numeric, true ) ) {
return is_numeric( $value ) ? $value : 0; return is_numeric( $value ) ? $value : 0;
} }

View File

@@ -78,7 +78,17 @@ class PRAutoBlogger_Settings_Fields_Extended {
'low' => __( 'Low — light reasoning, lower cost', 'prautoblogger' ), 'low' => __( 'Low — light reasoning, lower cost', 'prautoblogger' ),
'minimal' => __( 'Minimal — barely any reasoning', 'prautoblogger' ), 'minimal' => __( 'Minimal — barely any reasoning', 'prautoblogger' ),
), ),
'description' => __( 'How much effort the model spends reasoning before answering. Higher effort = more reasoning tokens = higher cost. Only applies when reasoning is enabled above.', 'prautoblogger' ), 'description' => __( 'How much effort the model spends reasoning before answering. Higher effort = more reasoning tokens = higher cost. Only applies when reasoning is enabled above. When the Reasoning Token Cap below is set (default), the cap is sent instead of the effort level — set the cap to 0 to use effort only.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_reasoning_max_tokens',
'label' => __( 'Reasoning Token Cap', 'prautoblogger' ),
'type' => 'number',
'section' => 'prautoblogger_models',
'default' => PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS,
'min' => 0,
'max' => 32000,
'description' => __( 'Hard ceiling on thinking tokens per call when reasoning is enabled. The completion budget is raised by this amount so reasoning can never crowd out the article text — an uncapped high effort can spend the entire budget thinking and return an empty draft. 0 = no cap (uncapped effort mode, not recommended).', 'prautoblogger' ),
), ),
// ── Schedule & Budget ─────────────────────────────────────── // ── Schedule & Budget ───────────────────────────────────────

View File

@@ -103,7 +103,7 @@ class PRAutoBlogger_Article_Worker {
$review = $this->review_with_state( $editor, $content, $idea, $run_id, $item ); $review = $this->review_with_state( $editor, $content, $idea, $run_id, $item );
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Saving and publishing…', 'prautoblogger' ) ); PRAutoBlogger_Pipeline_Status::broadcast( __( 'Saving and publishing…', 'prautoblogger' ) );
PRAutoBlogger_Run_Stage_State::start( $run_id, 'publish', '', $item ); PRAutoBlogger_Run_Stage_State::start( $run_id, 'publish', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'publish' ), $item );
$this->publish_or_draft( $this->publish_or_draft(
$content, $content,
$idea, $idea,
@@ -174,7 +174,7 @@ class PRAutoBlogger_Article_Worker {
return new PRAutoBlogger_Editorial_Review( $data ); return new PRAutoBlogger_Editorial_Review( $data );
} }
} }
PRAutoBlogger_Run_Stage_State::start( $run_id, 'review', '', $item ); PRAutoBlogger_Run_Stage_State::start( $run_id, 'review', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'review' ), $item );
} }
$review = $editor->review( $content, $idea ); $review = $editor->review( $content, $idea );

View File

@@ -64,6 +64,7 @@ class PRAutoBlogger_Chief_Editor {
'temperature' => 0.3, 'temperature' => 0.3,
'max_tokens' => 5000, 'max_tokens' => 5000,
'response_format' => array( 'type' => 'json_object' ), 'response_format' => array( 'type' => 'json_object' ),
'stage' => 'review',
) )
); );

View File

@@ -78,6 +78,7 @@ class PRAutoBlogger_Content_Analyzer {
'temperature' => 0.5, 'temperature' => 0.5,
'max_tokens' => 8000, 'max_tokens' => 8000,
'response_format' => array( 'type' => 'json_object' ), 'response_format' => array( 'type' => 'json_object' ),
'stage' => 'analysis',
) )
); );

View File

@@ -194,9 +194,15 @@ class PRAutoBlogger_Content_Generator {
); );
return $cached; return $cached;
} }
PRAutoBlogger_Run_Stage_State::start( $this->run_id, $stage, '', $this->item_key ); PRAutoBlogger_Run_Stage_State::start( $this->run_id, $stage, (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( $stage ), $this->item_key );
} }
// v0.18.1: stage metadata for the provider's empty-completion
// guard — warning logs and failed-attempt audit rows carry the
// real stage + registry key (never sent upstream).
$options['stage'] = $stage;
$options['prompt_key'] = $prompt_key;
$ctx = PRAutoBlogger_Opik_Trace_Context::current(); $ctx = PRAutoBlogger_Opik_Trace_Context::current();
$span_id = $ctx->start_span( $span_id = $ctx->start_span(
@@ -223,6 +229,21 @@ class PRAutoBlogger_Content_Generator {
$options $options
); );
// v0.18.1 writer-path guard (belt over the provider seam, which
// already throws for OpenRouter): no empty article may ever leave
// a writing stage — it would flow to the editor, be rejected as
// "draft text is missing", and land as an empty draft post.
if ( '' === trim( (string) $response['content'] ) ) {
throw new \RuntimeException(
sprintf(
/* translators: 1: writing stage name, 2: model identifier. */
__( 'Writing stage "%1$s" produced empty content (model %2$s) — failing the stage instead of passing an empty article downstream.', 'prautoblogger' ),
$stage,
(string) $response['model']
)
);
}
$ctx->end_span( $ctx->end_span(
$span_id, $span_id,
array( array(

View File

@@ -65,8 +65,9 @@ class PRAutoBlogger_Cost_Reporter {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$results = $wpdb->get_results( $results = $wpdb->get_results(
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$wpdb->prepare( $wpdb->prepare(
"SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost
FROM {$table} FROM {$table}
WHERE created_at >= %s AND response_status = 'success' WHERE created_at >= %s AND response_status = 'success'
GROUP BY DATE(created_at) GROUP BY DATE(created_at)
@@ -102,11 +103,12 @@ class PRAutoBlogger_Cost_Reporter {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$results = $wpdb->get_results( $results = $wpdb->get_results(
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$wpdb->prepare( $wpdb->prepare(
"SELECT stage, "SELECT stage,
SUM(estimated_cost) as total_cost, SUM(estimated_cost) as total_cost,
SUM(prompt_tokens + completion_tokens) as total_tokens, SUM(prompt_tokens + completion_tokens) as total_tokens,
COUNT(*) as call_count // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared COUNT(*) as call_count
FROM {$table} FROM {$table}
WHERE created_at BETWEEN %s AND %s AND response_status = 'success' WHERE created_at BETWEEN %s AND %s AND response_status = 'success'
GROUP BY stage", GROUP BY stage",

View File

@@ -200,6 +200,7 @@ PROMPT;
array( array(
'temperature' => 0.7, 'temperature' => 0.7,
'max_tokens' => self::REWRITER_MAX_TOKENS, 'max_tokens' => self::REWRITER_MAX_TOKENS,
'stage' => 'image_prompt_rewrite',
) )
); );

View File

@@ -185,14 +185,14 @@ class PRAutoBlogger_Pipeline_Runner {
$source_labels = is_array( $enabled ) ? implode( ', ', $enabled ) : 'reddit'; $source_labels = is_array( $enabled ) ? implode( ', ', $enabled ) : 'reddit';
/* translators: %s is a comma-separated list of enabled source names, e.g. "reddit, llm_research". */ /* translators: %s is a comma-separated list of enabled source names, e.g. "reddit, llm_research". */
PRAutoBlogger_Pipeline_Status::broadcast( sprintf( __( 'Collecting sources from %s…', 'prautoblogger' ), $source_labels ) ); PRAutoBlogger_Pipeline_Status::broadcast( sprintf( __( 'Collecting sources from %s…', 'prautoblogger' ), $source_labels ) );
PRAutoBlogger_Run_Stage_State::start( $run_id, 'research' ); PRAutoBlogger_Run_Stage_State::start( $run_id, 'research', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'research' ) );
( new PRAutoBlogger_Source_Collector() ) ( new PRAutoBlogger_Source_Collector() )
->set_cost_tracker( $cost_tracker ) ->set_cost_tracker( $cost_tracker )
->collect_from_all_sources(); ->collect_from_all_sources();
PRAutoBlogger_Run_Stage_State::done( $run_id, 'research' ); PRAutoBlogger_Run_Stage_State::done( $run_id, 'research' );
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Analyzing topics and scoring…', 'prautoblogger' ) ); PRAutoBlogger_Pipeline_Status::broadcast( __( 'Analyzing topics and scoring…', 'prautoblogger' ) );
PRAutoBlogger_Run_Stage_State::start( $run_id, 'analysis' ); PRAutoBlogger_Run_Stage_State::start( $run_id, 'analysis', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'analysis' ) );
$llm = new PRAutoBlogger_OpenRouter_Provider(); $llm = new PRAutoBlogger_OpenRouter_Provider();
$analyzer = new PRAutoBlogger_Content_Analyzer( $llm, $cost_tracker ); $analyzer = new PRAutoBlogger_Content_Analyzer( $llm, $cost_tracker );
$analysis = $analyzer->analyze_recent_data( max( $target * 2, 6 ) ); $analysis = $analyzer->analyze_recent_data( max( $target * 2, 6 ) );

View File

@@ -82,6 +82,23 @@ class PRAutoBlogger_Publisher {
?string $run_id = null, ?string $run_id = null,
?PRAutoBlogger_Cost_Tracker $cost_tracker = null ?PRAutoBlogger_Cost_Tracker $cost_tracker = null
): int { ): int {
// v0.18.1 belt-and-braces: never create a post whose content is
// empty once tags and whitespace are stripped — an empty "draft
// for human review" (2026-06-11 incident, post 921) reviews
// nothing and hides the underlying generation failure. The
// provider/writer guards make this unreachable on OpenRouter
// paths; this protects every other path into post creation.
if ( '' === trim( wp_strip_all_tags( $content ) ) ) {
throw new \RuntimeException(
sprintf(
/* translators: 1: intended post status, 2: article title. */
__( 'Refusing to create %1$s post "%2$s": generated content is empty.', 'prautoblogger' ),
$post_status,
$idea->get_suggested_title()
)
);
}
// v0.18.0 idempotency: post creation is keyed by run + idea // v0.18.0 idempotency: post creation is keyed by run + idea
// (check-before-insert) so a retried/resumed run cannot create a // (check-before-insert) so a retried/resumed run cannot create a
// duplicate post. One run_id spans all N articles of a batch, so // duplicate post. One run_id spans all N articles of a batch, so

View File

@@ -6,40 +6,33 @@ declare(strict_types=1);
* *
* Per-run per-stage state machine over `wp_prautoblogger_run_stages`. * Per-run per-stage state machine over `wp_prautoblogger_run_stages`.
* *
* What: One row per (run_id, stage, agent_role, item_key) holding * One row per (run_id, stage, agent_role, item_key) holding
* pending|running|done|failed|halted plus the stage's output * pending|running|done|failed|halted plus the output snapshot (meta_json).
* snapshot (meta_json). This is what makes resume idempotent on the * Done stages are sticky and never re-charged on resume. Self-healing:
* chained-cron architecture: a `done` stage is NEVER re-run or
* re-charged — re-entry reuses its stored output; `done` is sticky
* (an upsert cannot demote it). agent_role is the Phase-2 fan-out
* dimension (quorum members; the quorum logic itself is Phase 2);
* item_key scopes article-level stages because one run_id spans all
* N articles of a batch run ('' for run-level stages). Self-healing:
* a missing table degrades every method to a no-op/false. * a missing table degrades every method to a no-op/false.
* Who triggers it: Pipeline_Runner (run-level research/analysis), *
* Article_Worker (per-article generate/review/publish), * v0.18.2: role is resolved from Stage_Display_Map when caller passes ''
* Content_Generator (per-LLM-stage outline/draft/polish), * so start/done/is_done/get_output are always symmetric. Explicit non-empty
* Run_Reaper (stuck-stage sweep + payload pruning). * roles (Phase-2 fan-out) are honoured as-is. get() falls back to role=''
* Dependencies: WordPress $wpdb, wp_json_encode. * on miss for mid-run-upgrade compat with v0.18.1 rows.
* *
* @see core/class-run-state.php — Run-level lifecycle + ledger row. * @see core/class-run-state.php — Run-level lifecycle + ledger row.
* @see core/class-run-reaper.php — Sweeps stages stuck in 'running'. * @see core/class-run-reaper.php — Sweeps stages stuck in 'running'.
* @see ARCHITECTURE.md #21 — Idempotency-key design. * @see ARCHITECTURE.md #22 — Pipeline v2 Phase 1 substrate.
*/ */
class PRAutoBlogger_Run_Stage_State { class PRAutoBlogger_Run_Stage_State {
/** @var bool|null Per-request "run_stages table exists" probe result. */ /** @var bool|null Per-request "run_stages table exists" probe result. */
private static ?bool $table_ok = null; private static ?bool $table_ok = null;
/** Fully-qualified run_stages table name. */ /** @return string Fully-qualified run_stages table name. */
public static function table_name(): string { public static function table_name(): string {
global $wpdb; global $wpdb;
return $wpdb->prefix . 'prautoblogger_run_stages'; return $wpdb->prefix . 'prautoblogger_run_stages';
} }
/** /**
* Whether the run_stages table exists and is queryable. Cached per * Whether the run_stages table exists and is queryable. Cached per request.
* request; never throws.
* *
* @return bool * @return bool
*/ */
@@ -49,7 +42,7 @@ class PRAutoBlogger_Run_Stage_State {
} }
global $wpdb; global $wpdb;
if ( null === $wpdb ) { if ( null === $wpdb ) {
return false; // Not cached: $wpdb may appear later in boot. return false;
} }
$table = self::table_name(); $table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
@@ -59,18 +52,17 @@ class PRAutoBlogger_Run_Stage_State {
} }
/** /**
* Stable hash identifying one article idea within a run (post-creation * Stable 16-hex hash for one article idea within a run.
* idempotency + stage item scoping both key off this).
* *
* @param PRAutoBlogger_Article_Idea $idea The idea. * @param PRAutoBlogger_Article_Idea $idea The idea.
* @return string 16-hex-char hash. * @return string
*/ */
public static function idea_hash( PRAutoBlogger_Article_Idea $idea ): string { public static function idea_hash( PRAutoBlogger_Article_Idea $idea ): string {
return substr( md5( $idea->get_suggested_title() . '|' . $idea->get_topic() ), 0, 16 ); return substr( md5( $idea->get_suggested_title() . '|' . $idea->get_topic() ), 0, 16 );
} }
/** /**
* Stage item_key for an article idea ('' is reserved for run-level stages). * Stage item_key for an article idea ('' reserved for run-level stages).
* *
* @param PRAutoBlogger_Article_Idea $idea The idea. * @param PRAutoBlogger_Article_Idea $idea The idea.
* @return string e.g. 'idea:1a2b3c4d5e6f7a8b'. * @return string e.g. 'idea:1a2b3c4d5e6f7a8b'.
@@ -80,22 +72,18 @@ class PRAutoBlogger_Run_Stage_State {
} }
/** /**
* Mark a stage as entered (running). Upsert: first entry inserts the * Mark a stage as running. Sticky: done stages are never demoted.
* row; re-entry bumps `attempt` — but a `done` stage is sticky and is
* neither demoted nor re-counted.
*
* Side effects: one INSERT … ON DUPLICATE KEY UPDATE.
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $stage Stage name (see Stage_Display_Map). * @param string $stage Stage name (see Stage_Display_Map).
* @param string $agent_role Fan-out dimension ('' default in Phase 1). * @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope ('' for run-level stages). * @param string $item_key Article scope ('' for run-level stages).
* @return void
*/ */
public static function start( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void { public static function start( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void {
if ( '' === $run_id || ! self::is_available() ) { if ( '' === $run_id || ! self::is_available() ) {
return; return;
} }
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb; global $wpdb;
$table = self::table_name(); $table = self::table_name();
$now = current_time( 'mysql' ); $now = current_time( 'mysql' );
@@ -120,22 +108,20 @@ class PRAutoBlogger_Run_Stage_State {
} }
/** /**
* Mark a stage done, persisting its output for resume-without-recharge. * Mark a stage done and persist its output for resume-without-recharge.
*
* Side effects: one INSERT … ON DUPLICATE KEY UPDATE.
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $stage Stage name. * @param string $stage Stage name.
* @param string $agent_role Fan-out dimension. * @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope. * @param string $item_key Article scope.
* @param string|null $output Stage output to snapshot (pruned after R days). * @param string|null $output Stage output snapshot (pruned after R days).
* @param float $cost_usd Cost attributed to the stage. * @param float $cost_usd Cost attributed to this stage.
* @return void
*/ */
public static function done( string $run_id, string $stage, string $agent_role = '', string $item_key = '', ?string $output = null, float $cost_usd = 0.0 ): void { public static function done( string $run_id, string $stage, string $agent_role = '', string $item_key = '', ?string $output = null, float $cost_usd = 0.0 ): void {
if ( '' === $run_id || ! self::is_available() ) { if ( '' === $run_id || ! self::is_available() ) {
return; return;
} }
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb; global $wpdb;
$table = self::table_name(); $table = self::table_name();
$now = current_time( 'mysql' ); $now = current_time( 'mysql' );
@@ -166,18 +152,18 @@ class PRAutoBlogger_Run_Stage_State {
} }
/** /**
* Mark a stage failed (does not demote a `done` stage). * Mark a stage failed (does not demote a done stage).
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $stage Stage name. * @param string $stage Stage name.
* @param string $agent_role Fan-out dimension. * @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope. * @param string $item_key Article scope.
* @return void
*/ */
public static function fail( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void { public static function fail( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void {
if ( '' === $run_id || ! self::is_available() ) { if ( '' === $run_id || ! self::is_available() ) {
return; return;
} }
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb; global $wpdb;
$table = self::table_name(); $table = self::table_name();
$now = current_time( 'mysql' ); $now = current_time( 'mysql' );
@@ -197,18 +183,20 @@ class PRAutoBlogger_Run_Stage_State {
} }
/** /**
* Fetch one stage row. * Fetch one stage row. Falls back to role='' on miss for mid-run-upgrade
* compat with v0.18.1 rows (one extra indexed query, only on miss).
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $stage Stage name. * @param string $stage Stage name.
* @param string $agent_role Fan-out dimension. * @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope. * @param string $item_key Article scope.
* @return array<string, mixed>|null Row or null. * @return array<string, mixed>|null
*/ */
public static function get( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): ?array { public static function get( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): ?array {
if ( '' === $run_id || ! self::is_available() ) { if ( '' === $run_id || ! self::is_available() ) {
return null; return null;
} }
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb; global $wpdb;
$table = self::table_name(); $table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
@@ -222,7 +210,25 @@ class PRAutoBlogger_Run_Stage_State {
), ),
ARRAY_A ARRAY_A
); );
return is_array( $row ) ? $row : null; if ( is_array( $row ) ) {
return $row;
}
// v0.18.1 upgrade compat: rows started before this fix carry role=''.
// One extra indexed query, only on miss, only for known stages.
if ( '' !== $agent_role ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$legacy = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE run_id = %s AND stage = %s AND agent_role = '' AND item_key = %s",
$run_id,
$stage,
$item_key
),
ARRAY_A
);
return is_array( $legacy ) ? $legacy : null;
}
return null;
} }
/** /**
@@ -230,7 +236,7 @@ class PRAutoBlogger_Run_Stage_State {
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $stage Stage name. * @param string $stage Stage name.
* @param string $agent_role Fan-out dimension. * @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope. * @param string $item_key Article scope.
* @return bool * @return bool
*/ */
@@ -244,7 +250,7 @@ class PRAutoBlogger_Run_Stage_State {
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $stage Stage name. * @param string $stage Stage name.
* @param string $agent_role Fan-out dimension. * @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope. * @param string $item_key Article scope.
* @return string|null * @return string|null
*/ */
@@ -258,13 +264,10 @@ class PRAutoBlogger_Run_Stage_State {
} }
/** /**
* Fail every still-open (pending/running) stage of one item — used by * Fail every still-open stage of one item. Done stages are untouched.
* the worker's catch-all so a crashed article leaves no stage stuck
* in 'running' until the reaper. Done stages are untouched.
* *
* @param string $run_id Run UUID. * @param string $run_id Run UUID.
* @param string $item_key Stage item key ('' = run-level stages). * @param string $item_key Stage item key ('' = run-level stages).
* @return void
*/ */
public static function fail_open_for_item( string $run_id, string $item_key ): void { public static function fail_open_for_item( string $run_id, string $item_key ): void {
if ( '' === $run_id || ! self::is_available() ) { if ( '' === $run_id || ! self::is_available() ) {
@@ -290,4 +293,21 @@ class PRAutoBlogger_Run_Stage_State {
public static function flush_cache(): void { public static function flush_cache(): void {
self::$table_ok = null; self::$table_ok = null;
} }
/**
* Resolve the effective agent role for a stage.
*
* '' → derive from Stage_Display_Map (unknown stages map to '').
* Non-empty → returned as-is (Phase-2 explicit fan-out role).
*
* @param string $stage Stage name.
* @param string $agent_role Caller-supplied role ('' = auto-resolve).
* @return string Effective agent role.
*/
private static function resolve_role( string $stage, string $agent_role ): string {
if ( '' !== $agent_role ) {
return $agent_role;
}
return (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( $stage );
}
} }

View File

@@ -76,8 +76,33 @@ class PRAutoBlogger_Source_Collector {
'collector' 'collector'
); );
} catch ( \Throwable $e ) { } catch ( \Throwable $e ) {
PRAutoBlogger_Logger::instance()->error( sprintf( 'Collection %s from %s: %s', get_class( $e ), $source_type, $e->getMessage() ), 'collector' ); // Structured failure meta: model slug, HTTP status (parsed from message),
// Continue with other sources — one failure shouldn't stop everything. // and first ~200 chars of the error body — enables post-incident diagnosis
// without needing to re-run the failing collection. Added v0.18.2.
$config_for_log = $this->get_config_for_source( $source_type );
$model_slug = (string) ( $config_for_log['model'] ?? '' );
$err_msg = $e->getMessage();
// Extract HTTP status from "OpenRouter API error (HTTP NNN): ..." pattern.
$http_status = 0;
if ( preg_match( '/HTTP (\d{3})/', $err_msg, $m ) ) {
$http_status = (int) $m[1];
}
PRAutoBlogger_Logger::instance()->error(
sprintf(
'Collection %s from %s: %s',
get_class( $e ),
$source_type,
$e->getMessage()
),
'collector',
array(
'source' => $source_type,
'model' => $model_slug,
'http_status' => $http_status,
'error_body' => mb_substr( $err_msg, 0, 200 ),
)
);
// Continue with other sources — one failure should not stop everything.
} }
} }

View File

@@ -70,6 +70,7 @@ class PRAutoBlogger_LLM_Research_Provider implements PRAutoBlogger_Source_Provid
'temperature' => 0.7, 'temperature' => 0.7,
'max_tokens' => 8000, 'max_tokens' => 8000,
'response_format' => array( 'type' => 'json_object' ), 'response_format' => array( 'type' => 'json_object' ),
'stage' => 'llm_research',
) )
); );

View File

@@ -0,0 +1,168 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Empty-completion guard for OpenRouter chat responses (v0.18.1).
*
* What: Treats a chat completion whose visible content is empty/whitespace
* as a FAILURE, never a success — per the LLM-call discipline:
* schema-validate every output, retry/fall back, never silently
* pass. The incident this prevents (2026-06-11, prod run acf24029,
* draft post 921): a true reasoning model at a high reasoning effort
* spent the entire max_tokens completion budget on thinking,
* finished with finish_reason='length', and emitted zero visible
* content — which flowed writer → editor (reject: "draft text is
* missing") → an empty draft post in the Review Queue, with the
* cost booked as 'success'.
*
* Behavior on every parsed response:
* - finish_reason='length' is warning-logged (model, stage, prompt/
* completion/reasoning tokens) whether or not content survived.
* - Empty content + (finish_reason='length' OR reasoning active on
* the request) → ONE retry with reasoning disabled for that call
* (per-call `reasoning` override), then fail the stage.
* - Every failed/retried attempt lands in generation_log with its
* REAL response_status ('error') and token burn, and — inside a
* v0.18.0 run — a run_decisions row records the verdict.
* Who triggers it: PRAutoBlogger_OpenRouter_Provider::send_chat_completion()
* on every successfully parsed response.
* Dependencies: Logger, Cost_Tracker (failure rows), Run_Context (run
* attribution), Audit_Writer (run_decisions verdicts).
*
* @see class-open-router-provider.php — Integration point; supplies the retry callable.
* @see class-open-router-response-parser.php — Produces the parsed array assessed here.
* @see class-open-router-request-builder.php — Reasoning token cap (first line of defense).
* @see core/class-audit-writer.php — run_decisions verdict rows.
*/
class PRAutoBlogger_OpenRouter_Completion_Guard {
/** Verdict recorded when an empty attempt is retried with reasoning disabled. */
public const VERDICT_RETRY = 'retry_reasoning_disabled';
/** Verdict recorded when a call finally fails for empty content. */
public const VERDICT_FAIL = 'failed_empty_completion';
/**
* Assess a parsed completion: pass it through, retry once, or fail loudly.
*
* @param array<string, mixed> $parsed Parsed response from Response_Parser::parse_success().
* @param array<string, mixed> $options Original call options. Reads the caller-metadata keys
* 'stage' / 'prompt_key' (audit attribution) and
* 'empty_retry' (marks the retry attempt — never retried twice).
* @param bool $reasoning_active Whether the dispatched request had reasoning enabled.
* @param callable $retry Re-dispatches the call with the options it is given.
* Invoked at most once, with reasoning disabled.
*
* @return array<string, mixed> A completion whose visible content is non-empty.
*
* @throws \RuntimeException When content is empty and the retry budget is spent or a retry
* cannot plausibly help.
*/
public function finalize( array $parsed, array $options, bool $reasoning_active, callable $retry ): array {
$stage = (string) ( $options['stage'] ?? 'unknown' );
$finish_reason = (string) ( $parsed['finish_reason'] ?? 'unknown' );
if ( 'length' === $finish_reason ) {
PRAutoBlogger_Logger::instance()->warning(
sprintf(
'Completion hit its max_tokens ceiling (finish_reason=length): model=%s, stage=%s, prompt_tokens=%d, completion_tokens=%d, reasoning_tokens=%d.',
(string) $parsed['model'],
$stage,
(int) $parsed['prompt_tokens'],
(int) $parsed['completion_tokens'],
(int) $parsed['reasoning_tokens']
),
'openrouter'
);
}
if ( '' !== trim( (string) ( $parsed['content'] ?? '' ) ) ) {
return $parsed; // Healthy completion — visible content present.
}
$already_retried = ! empty( $options['empty_retry'] );
// A reasoning-disabled retry can plausibly help when the budget was
// exhausted (length) or when reasoning was eating the budget.
$retry_can_help = 'length' === $finish_reason || $reasoning_active;
if ( $retry_can_help && ! $already_retried ) {
$note = sprintf(
'Empty completion (finish_reason=%s, completion_tokens=%d, reasoning_tokens=%d) — retrying once with reasoning disabled.',
$finish_reason,
(int) $parsed['completion_tokens'],
(int) $parsed['reasoning_tokens']
);
$this->record_attempt( $parsed, $options, $stage, self::VERDICT_RETRY, $note );
PRAutoBlogger_Logger::instance()->warning(
sprintf( 'Stage %s: %s (model %s)', $stage, $note, (string) $parsed['model'] ),
'openrouter'
);
$retry_options = $options;
$retry_options['reasoning'] = array( 'enabled' => false );
$retry_options['empty_retry'] = true;
return $retry( $retry_options );
}
$note = sprintf(
'Empty completion (finish_reason=%s, completion_tokens=%d, reasoning_tokens=%d)%s — failing the call.',
$finish_reason,
(int) $parsed['completion_tokens'],
(int) $parsed['reasoning_tokens'],
$already_retried ? ' after a reasoning-disabled retry' : ''
);
$this->record_attempt( $parsed, $options, $stage, self::VERDICT_FAIL, $note );
throw new \RuntimeException(
sprintf(
/* translators: 1: pipeline stage, 2: model identifier, 3: finish_reason value, 4: retry note. */
__( 'LLM call for stage "%1$s" returned empty content (model %2$s, finish_reason=%3$s)%4$s.', 'prautoblogger' ),
$stage,
(string) $parsed['model'],
$finish_reason,
$already_retried ? __( ' after a reasoning-disabled retry', 'prautoblogger' ) : ''
)
);
}
/**
* Book a failed/retried attempt: a generation_log row with the REAL
* response_status and token burn (the empty call still cost money),
* plus a run_decisions verdict for new-style runs. Both writes are
* self-healing no-ops on a half-migrated schema; neither can throw.
*
* @param array<string, mixed> $parsed Parsed response of the failed attempt.
* @param array<string, mixed> $options Call options ('prompt_key' attribution).
* @param string $stage Stage label for the log row.
* @param string $verdict VERDICT_RETRY or VERDICT_FAIL.
* @param string $note Human-readable failure note.
* @return void
*/
private function record_attempt( array $parsed, array $options, string $stage, string $verdict, string $note ): void {
$run_id = PRAutoBlogger_Run_Context::current_run_id();
$tracker = new PRAutoBlogger_Cost_Tracker();
if ( null !== $run_id && '' !== $run_id ) {
// Attribute the row to the surrounding run. Idempotent: the
// run context, ledger row, and prompt pins already exist.
$tracker->set_run_id( $run_id );
}
$tracker->log_api_call(
null,
$stage,
'OpenRouter',
(string) $parsed['model'],
(int) $parsed['prompt_tokens'],
(int) $parsed['completion_tokens'],
'error',
$note,
null,
isset( $options['prompt_key'] ) ? (string) $options['prompt_key'] : null
);
// run_decisions verdict — no-op outside a run or pre-1.2.0 schema.
PRAutoBlogger_Audit_Writer::record_decision( (string) ( $run_id ?? '' ), $stage, $verdict, $note );
}
}

View File

@@ -19,8 +19,9 @@ declare(strict_types=1);
* @see class-open-router-config.php — Config helpers (base URL, cache TTL). * @see class-open-router-config.php — Config helpers (base URL, cache TTL).
* @see class-open-router-pricing.php — Pricing and model list lookups. * @see class-open-router-pricing.php — Pricing and model list lookups.
* @see class-open-router-validator.php — Credential validation (delegated). * @see class-open-router-validator.php — Credential validation (delegated).
* @see class-open-router-request-builder.php — Request header building + cURL filter. * @see class-open-router-request-builder.php — Request body/header building + cURL filter.
* @see class-open-router-response-parser.php — Response parsing + error classification. * @see class-open-router-response-parser.php — Response parsing + error classification.
* @see class-open-router-completion-guard.php — Empty-completion guard + reasoning-off retry (v0.18.1).
* @see class-cost-tracker.php — Called after every request to log token usage. * @see class-cost-tracker.php — Called after every request to log token usage.
* @see ARCHITECTURE.md — Data flow diagram showing where this fits. * @see ARCHITECTURE.md — Data flow diagram showing where this fits.
*/ */
@@ -40,8 +41,15 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
* temperature?: float, * temperature?: float,
* max_tokens?: int, * max_tokens?: int,
* response_format?: array{type: string}, * response_format?: array{type: string},
* reasoning?: array{enabled: bool, effort?: string}, * reasoning?: array{enabled: bool, effort?: string, max_tokens?: int},
* } $options Optional parameters. Pass 'reasoning' to override the global setting. * stage?: string,
* prompt_key?: string,
* empty_retry?: bool,
* } $options Optional parameters. Pass 'reasoning' to override the global
* setting. 'stage'/'prompt_key' are caller metadata for the
* empty-completion guard's logging + audit rows (never sent
* upstream); 'empty_retry' is set internally by the guard's
* single reasoning-disabled retry.
* *
* @return array{ * @return array{
* content: string, * content: string,
@@ -52,46 +60,39 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
* finish_reason: string, * finish_reason: string,
* } * }
* *
* @throws \RuntimeException On API error after retries exhausted. * @throws \RuntimeException On API error after retries exhausted, or when the
* completion's visible content is empty/whitespace
* (v0.18.1 guard — after at most one reasoning-disabled retry).
* @throws PRAutoBlogger_Cost_Ceiling_Exception When the per-run cost governor blocks * @throws PRAutoBlogger_Cost_Ceiling_Exception When the per-run cost governor blocks
* the call (run already halted). * the call (run already halted).
*/ */
public function send_chat_completion( array $messages, string $model, array $options = array() ): array { public function send_chat_completion( array $messages, string $model, array $options = array() ): array {
$builder = new PRAutoBlogger_OpenRouter_Request_Builder();
// Fetch + format-validate the key (moved to Request_Builder in // Fetch + format-validate the key (moved to Request_Builder in
// v0.18.0 for the 300-line cap; behavior unchanged — throws the // v0.18.0 for the 300-line cap; behavior unchanged — throws the
// same messages on missing/corrupted keys). // same messages on missing/corrupted keys).
$api_key = ( new PRAutoBlogger_OpenRouter_Request_Builder() )->resolve_api_key(); $api_key = $builder->resolve_api_key();
$body = array( // Body assembly — incl. global/per-call reasoning and the v0.18.1
'model' => $model, // reasoning token cap + completion headroom — lives in the builder.
'messages' => $messages, $body = $builder->build_body( $messages, $model, $options );
);
if ( isset( $options['temperature'] ) ) { // Whether the outgoing request has reasoning enabled — drives the
$body['temperature'] = $options['temperature']; // empty-completion retry decision after parse.
} $reasoning_active = isset( $body['reasoning'] ) && false !== ( $body['reasoning']['enabled'] ?? true );
if ( isset( $options['max_tokens'] ) ) {
$body['max_tokens'] = $options['max_tokens'];
}
if ( isset( $options['response_format'] ) ) {
$body['response_format'] = $options['response_format'];
}
// Reasoning mode: explicit caller override takes priority, then global setting.
if ( isset( $options['reasoning'] ) ) {
$body['reasoning'] = $options['reasoning'];
} elseif ( '1' === get_option( 'prautoblogger_reasoning_enabled', '0' ) ) {
$body['reasoning'] = array(
'enabled' => true,
'effort' => get_option( 'prautoblogger_reasoning_effort', 'medium' ),
);
}
// v0.18.0 — per-run cost governor: reserve the worst-case estimate // v0.18.0 — per-run cost governor: reserve the worst-case estimate
// BEFORE any dispatch. Throws (and the run is already halted) when // BEFORE any dispatch. Throws (and the run is already halted) when
// the reservation would breach the run ceiling; returns null when // the reservation would breach the run ceiling; returns null when
// this process is not inside a governed run (historical behavior). // this process is not inside a governed run (historical behavior).
$reservation = PRAutoBlogger_Cost_Governor::open_chat_reservation( $model, $messages, $options ); // v0.18.1: the estimate uses the EFFECTIVE completion ceiling from
// the built body (incl. reasoning headroom), not the raw option.
$govern_options = $options;
if ( isset( $body['max_tokens'] ) ) {
$govern_options['max_tokens'] = $body['max_tokens'];
}
$reservation = PRAutoBlogger_Cost_Governor::open_chat_reservation( $model, $messages, $govern_options );
$last_error = ''; $last_error = '';
@@ -101,7 +102,6 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
$cache_ttl = $config->get_cache_ttl_seconds(); $cache_ttl = $config->get_cache_ttl_seconds();
$via_gateway = $config->is_via_gateway(); $via_gateway = $config->is_via_gateway();
$builder = new PRAutoBlogger_OpenRouter_Request_Builder();
$request_headers = $builder->build_headers( $api_key, $via_gateway, $cache_ttl ); $request_headers = $builder->build_headers( $api_key, $via_gateway, $cache_ttl );
$curl_auth_filter = $builder->register_curl_auth_filter( $request_headers, $base_host ); $curl_auth_filter = $builder->register_curl_auth_filter( $request_headers, $base_host );
@@ -190,7 +190,21 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
$this->estimate_cost( $model, (int) $parsed['prompt_tokens'], (int) $parsed['completion_tokens'] ) $this->estimate_cost( $model, (int) $parsed['prompt_tokens'], (int) $parsed['completion_tokens'] )
); );
$reservation = null; $reservation = null;
return $parsed;
// v0.18.1 — empty-completion guard: empty visible content
// is a FAILURE, never a success. Warns on finish_reason=
// length, retries ONCE with reasoning disabled when that
// can plausibly help, books failed attempts with their
// real status, and otherwise throws. The recursive retry
// manages its own reservation and cURL filter.
return ( new PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$parsed,
$options,
$reasoning_active,
function ( array $retry_options ) use ( $messages, $model ): array {
return $this->send_chat_completion( $messages, $model, $retry_options );
}
);
} }
// All retries exhausted. // All retries exhausted.

View File

@@ -18,6 +18,100 @@ declare(strict_types=1);
*/ */
class PRAutoBlogger_OpenRouter_Request_Builder { class PRAutoBlogger_OpenRouter_Request_Builder {
/**
* Build the JSON request body for a chat-completion call.
*
* Centralizes option handling (v0.18.1, moved from the provider for
* the 300-line cap): temperature, max_tokens, response_format, and
* the reasoning block — an explicit caller override takes priority
* over the global setting (that per-call override is how the
* empty-completion retry disables reasoning for its second attempt).
*
* Caller-metadata keys ('stage', 'prompt_key', 'empty_retry') are
* deliberately NOT copied into the HTTP body.
*
* @param array<int, array{role: string, content: string}> $messages Chat messages.
* @param string $model Model identifier.
* @param array<string, mixed> $options Call options.
*
* @return array<string, mixed> Request body ready for wp_json_encode().
*/
public function build_body( array $messages, string $model, array $options ): array {
$body = array(
'model' => $model,
'messages' => $messages,
);
if ( isset( $options['temperature'] ) ) {
$body['temperature'] = $options['temperature'];
}
if ( isset( $options['max_tokens'] ) ) {
$body['max_tokens'] = $options['max_tokens'];
}
if ( isset( $options['response_format'] ) ) {
$body['response_format'] = $options['response_format'];
}
// Reasoning mode: explicit caller override takes priority, then global setting.
if ( isset( $options['reasoning'] ) ) {
$body['reasoning'] = $options['reasoning'];
} elseif ( '1' === get_option( 'prautoblogger_reasoning_enabled', '0' ) ) {
$body['reasoning'] = array(
'enabled' => true,
'effort' => get_option( 'prautoblogger_reasoning_effort', 'medium' ),
);
}
return $this->apply_reasoning_budget( $body );
}
/**
* Reasoning budget sanity (v0.18.1): cap thinking, protect content.
*
* When the outgoing request enables reasoning and carries a completion
* ceiling, the thinking budget is capped via OpenRouter's
* `reasoning.max_tokens` and the completion ceiling is raised by the
* same amount — so no reasoning effort (incl. xhigh) can consume the
* entire completion budget and emit an empty message (the 2026-06-11
* empty-draft incident, prod run acf24029). The cap is SETTINGS-backed
* (`prautoblogger_reasoning_max_tokens`, default
* PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS, 0 = pure effort mode:
* no cap, no headroom — the historical behavior). When the cap is
* active it replaces `effort` — OpenRouter treats the two as
* alternative budget controls and normalizes max_tokens per model.
*
* No-op when reasoning is absent/disabled on the request, when the
* request has no completion ceiling, or when the cap setting is 0.
*
* @param array<string, mixed> $body Assembled request body.
*
* @return array<string, mixed> Body with the reasoning budget applied.
*/
private function apply_reasoning_budget( array $body ): array {
if ( ! isset( $body['reasoning'] ) || false === ( $body['reasoning']['enabled'] ?? true ) ) {
return $body;
}
if ( ! isset( $body['max_tokens'] ) ) {
return $body; // No completion ceiling to protect.
}
if ( ! isset( $body['reasoning']['max_tokens'] ) ) {
$cap = absint( get_option( 'prautoblogger_reasoning_max_tokens', PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS ) );
if ( $cap < 1 ) {
return $body; // Cap disabled — pure effort mode.
}
$body['reasoning']['max_tokens'] = $cap;
unset( $body['reasoning']['effort'] );
}
// Headroom: models that spend reasoning from the completion budget
// (e.g. deepseek/deepseek-v4-flash) must still have the caller's
// full max_tokens available for visible content.
$body['max_tokens'] = (int) $body['max_tokens'] + (int) $body['reasoning']['max_tokens'];
return $body;
}
/** /**
* Build request headers for OpenRouter API call. * Build request headers for OpenRouter API call.
* *

View File

@@ -181,7 +181,8 @@ class PRAutoBlogger_Runware_Image_Support {
*/ */
public function normalize_seed( ?int $seed ): int { public function normalize_seed( ?int $seed ): int {
if ( null === $seed || $seed < 1 ) { if ( null === $seed || $seed < 1 ) {
$derived = (int) ( ( microtime( true ) * 1000 ) % 2147483647 ); // Cast to int before modulo — float % int is deprecated in PHP 8 (v0.18.2).
$derived = (int) round( microtime( true ) * 1000 ) % 2147483647;
return $derived > 0 ? $derived : 1; return $derived > 0 ? $derived : 1;
} }
return $seed; return $seed;

View File

@@ -82,6 +82,7 @@ class PRAutoBlogger_Opik_Eval_Scorer {
array( array(
'temperature' => 0.1, 'temperature' => 0.1,
'max_tokens' => 200, 'max_tokens' => 200,
'stage' => 'opik_eval_judge',
) )
); );

View File

@@ -9,7 +9,7 @@
* Plugin Name: PRAutoBlogger * Plugin Name: PRAutoBlogger
* Plugin URI: https://peptiderepo.com/prautoblogger * Plugin URI: https://peptiderepo.com/prautoblogger
* Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics. * Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics.
* Version: 0.18.0 * Version: 0.18.2
* Requires at least: 6.0 * Requires at least: 6.0
* Requires PHP: 7.4 * Requires PHP: 7.4
* Author: PeptideRepo * Author: PeptideRepo
@@ -35,7 +35,7 @@ if ( ! defined( 'ABSPATH' ) ) {
| Defined here so every file in the plugin can reference paths, versions, | Defined here so every file in the plugin can reference paths, versions,
| and limits without magic strings. | and limits without magic strings.
*/ */
define( 'PRAUTOBLOGGER_VERSION', '0.18.0' ); define( 'PRAUTOBLOGGER_VERSION', '0.18.2' );
define( 'PRAUTOBLOGGER_DB_VERSION', '1.2.0' ); define( 'PRAUTOBLOGGER_DB_VERSION', '1.2.0' );
define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ ); define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ );
define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
@@ -49,6 +49,12 @@ define( 'PRAUTOBLOGGER_MAX_RETRIES', 3 );
// the named get_option() fallbacks — never inline the literals. // the named get_option() fallbacks — never inline the literals.
define( 'PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD', 0.50 ); define( 'PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD', 0.50 );
define( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS', 14 ); define( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS', 14 );
// v0.18.1: ceiling on "thinking" tokens per reasoning-enabled LLM call. The
// request's completion budget (max_tokens) is RAISED by this amount so
// reasoning can never consume the visible-content budget and return an empty
// message (the 2026-06-11 empty-draft incident). SETTINGS-backed
// (prautoblogger_reasoning_max_tokens); 0 disables the cap (pure effort mode).
define( 'PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS', 2048 );
define( 'PRAUTOBLOGGER_RETRY_BASE_DELAY_SECONDS', 2 ); define( 'PRAUTOBLOGGER_RETRY_BASE_DELAY_SECONDS', 2 );
define( 'PRAUTOBLOGGER_API_TIMEOUT_SECONDS', 180 ); define( 'PRAUTOBLOGGER_API_TIMEOUT_SECONDS', 180 );
define( 'PRAUTOBLOGGER_CACHE_TTL_SECONDS', 3600 ); define( 'PRAUTOBLOGGER_CACHE_TTL_SECONDS', 3600 );

View File

@@ -28,6 +28,9 @@ if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD' ) ) {
if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS' ) ) { if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS' ) ) {
define( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS', 14 ); define( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS', 14 );
} }
if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS' ) ) {
define( 'PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS', 2048 );
}
// WordPress time constants used by CostTracker and ContentAnalyzer. // WordPress time constants used by CostTracker and ContentAnalyzer.
if ( ! defined( 'DAY_IN_SECONDS' ) ) { if ( ! defined( 'DAY_IN_SECONDS' ) ) {

View File

@@ -0,0 +1,164 @@
<?php
/**
* Tests for PRAutoBlogger_Content_Generator (v0.18.1 writer-path guard).
*
* Validates that a writing stage whose LLM output is empty/whitespace
* throws instead of passing an empty article downstream, that healthy
* output passes through, and that the stage metadata for the provider's
* empty-completion guard rides the options array.
*
* execute_stage() is exercised via reflection: generate() defines the
* PRAUTOBLOGGER_EVAL_MODE constant, which cannot be redefined across
* tests in one PHP process.
*
* @package PRAutoBlogger\Tests\Core
*/
namespace PRAutoBlogger\Tests\Core;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class ContentGeneratorTest extends BaseTestCase {
private \PRAutoBlogger_Content_Request $request;
protected function setUp(): void {
parent::setUp();
\PRAutoBlogger_Prompt_Registry::flush_cache();
$this->stub_get_option( [
'prautoblogger_log_level' => 'error',
] );
// Content_Prompts::build_system() lists recent posts for the
// linking rules — none exist in the unit environment.
Functions\when( 'get_posts' )->justReturn( [] );
$idea = new \PRAutoBlogger_Article_Idea( $this->get_article_idea_fixture() );
$this->request = new \PRAutoBlogger_Content_Request(
$idea,
'single_pass',
'informational',
800,
2000,
'',
[],
''
);
}
protected function tearDown(): void {
\PRAutoBlogger_Prompt_Registry::flush_cache();
parent::tearDown();
}
/**
* Invoke the private execute_stage() on a generator wired to the
* given LLM response.
*
* @param array $llm_response Response the mock provider returns.
* @param array|null $captured Receives the options passed to the LLM.
* @return string Stage output.
*/
private function run_stage( array $llm_response, ?array &$captured = null ): string {
$llm = $this->createMock( \PRAutoBlogger_LLM_Provider_Interface::class );
$llm->method( 'send_chat_completion' )->willReturnCallback(
function ( array $messages, string $model, array $options ) use ( $llm_response, &$captured ) {
$captured = $options;
return $llm_response;
}
);
$llm->method( 'get_provider_name' )->willReturn( 'OpenRouter' );
$llm->method( 'estimate_cost' )->willReturn( 0.001 );
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
$generator = new \PRAutoBlogger_Content_Generator( $llm, $cost_tracker );
$method = new \ReflectionMethod( \PRAutoBlogger_Content_Generator::class, 'execute_stage' );
$method->setAccessible( true );
return $method->invoke(
$generator,
'draft',
'draft_generation',
'Write the article.',
$this->request,
'model/test',
[
'temperature' => 0.7,
'max_tokens' => 4000,
],
'content.single_pass'
);
}
/**
* Healthy stage output passes through unchanged.
*/
public function test_non_empty_stage_output_passes_through(): void {
$output = $this->run_stage( [
'content' => '<p>A real article.</p>',
'model' => 'model/test',
'prompt_tokens' => 100,
'completion_tokens' => 200,
] );
$this->assertSame( '<p>A real article.</p>', $output );
}
/**
* Empty stage output throws — no empty article may leave the writer.
*/
public function test_empty_stage_output_throws(): void {
$this->expectException( \RuntimeException::class );
$this->expectExceptionMessage( 'produced empty content' );
$this->run_stage( [
'content' => '',
'model' => 'model/test',
'prompt_tokens' => 100,
'completion_tokens' => 4000,
] );
}
/**
* Whitespace-only output counts as empty (the guard trims).
*/
public function test_whitespace_stage_output_throws(): void {
$this->expectException( \RuntimeException::class );
$this->expectExceptionMessage( 'draft' );
$this->run_stage( [
'content' => " \n\t ",
'model' => 'model/test',
'prompt_tokens' => 100,
'completion_tokens' => 4000,
] );
}
/**
* The stage + prompt_key metadata for the provider's empty-completion
* guard rides the LLM options (v0.18.1).
*/
public function test_stage_metadata_rides_the_llm_options(): void {
$captured = null;
$this->run_stage(
[
'content' => 'ok',
'model' => 'model/test',
'prompt_tokens' => 1,
'completion_tokens' => 1,
],
$captured
);
$this->assertSame( 'draft', $captured['stage'] );
$this->assertSame( 'content.single_pass', $captured['prompt_key'] );
$this->assertSame( 4000, $captured['max_tokens'] );
}
}

View File

@@ -90,4 +90,60 @@ class CostReporterTest extends BaseTestCase {
$this->assertIsFloat( $utilization ); $this->assertIsFloat( $utilization );
$this->assertGreaterThanOrEqual( 0.0, $utilization ); $this->assertGreaterThanOrEqual( 0.0, $utilization );
} }
/**
* Regression: get_daily_spend SQL must not embed phpcs:ignore inside the
* string literal (MariaDB would receive the comment as literal SQL text and
* reject the query). Captures the first argument passed to prepare() and
* asserts the SQL is clean.
*
* @see includes/core/class-cost-reporter.php — fixed in v0.18.2
*/
public function test_get_daily_spend_sql_contains_no_inline_phpcs_ignore(): void {
$captured_sql = null;
$this->wpdb->method( 'prepare' )->willReturnCallback(
function ( $sql, ...$args ) use ( &$captured_sql ) {
$captured_sql = $sql;
return 'prepared';
}
);
$this->wpdb->method( 'get_results' )->willReturn( [] );
$reporter = new \PRAutoBlogger_Cost_Reporter();
$reporter->get_daily_spend( 7 );
$this->assertNotNull( $captured_sql, 'prepare() was not called' );
$this->assertStringNotContainsString(
'// phpcs:ignore',
(string) $captured_sql,
'SQL string must not contain phpcs:ignore comment — MariaDB rejects it'
);
}
/**
* Regression: get_spend_by_stage SQL must not embed phpcs:ignore inside
* the string literal.
*
* @see includes/core/class-cost-reporter.php — fixed in v0.18.2
*/
public function test_get_spend_by_stage_sql_contains_no_inline_phpcs_ignore(): void {
$captured_sql = null;
$this->wpdb->method( 'prepare' )->willReturnCallback(
function ( $sql, ...$args ) use ( &$captured_sql ) {
$captured_sql = $sql;
return 'prepared';
}
);
$this->wpdb->method( 'get_results' )->willReturn( [] );
$reporter = new \PRAutoBlogger_Cost_Reporter();
$reporter->get_spend_by_stage( '2026-06-01', '2026-06-30' );
$this->assertNotNull( $captured_sql, 'prepare() was not called' );
$this->assertStringNotContainsString(
'// phpcs:ignore',
(string) $captured_sql,
'SQL string must not contain phpcs:ignore comment — MariaDB rejects it'
);
}
} }

View File

@@ -0,0 +1,183 @@
<?php
/**
* Side-effect tests for PRAutoBlogger_Publisher::publish().
*
* Validates the post-creation side effects: taxonomy assignment
* (category from article_type, tags from keywords), generation-log
* linking by run_id, and the public action/filter hooks. Split from
* PublisherTest.php to keep both files under the 300-line rule;
* post-creation/status/metadata/guard tests stay in PublisherTest.
*
* @package PRAutoBlogger\Tests\Core
*/
namespace PRAutoBlogger\Tests\Core;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
use Brain\Monkey\Actions;
use Brain\Monkey\Filters;
class PublisherSideEffectsTest extends BaseTestCase {
private \PRAutoBlogger_Article_Idea $idea;
private \PRAutoBlogger_Editorial_Review $review;
protected function setUp(): void {
parent::setUp();
$this->idea = new \PRAutoBlogger_Article_Idea( $this->get_article_idea_fixture() );
$this->review = new \PRAutoBlogger_Editorial_Review( $this->get_editorial_review_fixture() );
// Common stubs needed by Publisher.
$this->stub_get_option( [
'prautoblogger_writing_pipeline' => 'multi_step',
'prautoblogger_writing_model' => 'anthropic/claude-sonnet-4',
'prautoblogger_default_author' => 1,
] );
Functions\when( 'sanitize_text_field' )->returnArg();
Functions\when( 'wp_kses_post' )->returnArg();
// v0.18.1 empty-content guard strips tags before the emptiness check.
Functions\when( 'wp_strip_all_tags' )->alias( function ( $text ) {
return trim( strip_tags( (string) $text ) );
} );
Functions\when( 'is_wp_error' )->justReturn( false );
Functions\when( 'apply_filters' )->returnArg( 2 );
Functions\when( 'absint' )->alias( function ( $val ) { return abs( (int) $val ); } );
Functions\when( 'get_users' )->justReturn( [ 1 ] );
Functions\when( 'get_term_by' )->justReturn( false );
Functions\when( 'wp_insert_term' )->justReturn( [ 'term_id' => 5 ] );
Functions\when( 'wp_set_post_categories' )->justReturn( true );
Functions\when( 'wp_set_post_tags' )->justReturn( true );
}
/**
* Test that taxonomy terms are assigned based on article_type from the idea.
*/
public function test_publish_assigns_category_from_article_type(): void {
Functions\when( 'wp_insert_post' )->justReturn( 46 );
// get_term_by returns false (category doesn't exist), so wp_insert_term is called.
$captured_category = null;
Functions\when( 'wp_insert_term' )->alias( function ( $name, $taxonomy ) use ( &$captured_category ) {
$captured_category = $name;
return [ 'term_id' => 10 ];
} );
$captured_category_ids = null;
Functions\when( 'wp_set_post_categories' )->alias( function ( $post_id, $cat_ids ) use ( &$captured_category_ids ) {
$captured_category_ids = $cat_ids;
return true;
} );
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
// Article type is 'guide' → category should be 'Guides'.
$this->assertSame( 'Guides', $captured_category );
$this->assertSame( [ 10 ], $captured_category_ids );
}
/**
* Test that target keywords are set as post tags.
*/
public function test_publish_sets_tags_from_keywords(): void {
Functions\when( 'wp_insert_post' )->justReturn( 47 );
$captured_tags = null;
Functions\when( 'wp_set_post_tags' )->alias( function ( $post_id, $tags, $append ) use ( &$captured_tags ) {
$captured_tags = $tags;
return true;
} );
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
$this->assertSame( [ 'test', 'keyword', 'example' ], $captured_tags );
}
/**
* Test that generation log entries are linked via run_id.
*/
public function test_publish_links_generation_logs_by_run_id(): void {
Functions\when( 'wp_insert_post' )->justReturn( 48 );
// Create an idea fixture without source_ids to avoid triggering SourceCollector
// queries that would overwrite captured_query in the mock.
$fixture = $this->get_article_idea_fixture();
$fixture['source_ids'] = [];
$idea = new \PRAutoBlogger_Article_Idea( $fixture );
$captured_query = null;
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'prepare' )->willReturnCallback( function ( $sql, ...$args ) use ( &$captured_query ) {
$captured_query = $sql;
return $sql;
} );
$wpdb->method( 'query' )->willReturn( 1 );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $idea, $this->review, 'run_link_test' );
// Should use run_id-based query, not timestamp-based.
$this->assertStringContainsString( 'run_id', $captured_query );
$this->assertStringNotContainsString( 'created_at', $captured_query );
}
/**
* Test that the prautoblogger_post_created action is fired after publishing.
*/
public function test_publish_fires_post_created_action(): void {
// TODO(peptiderepo): this test is latently broken — Mockery expects do_action_prautoblogger_post_created
// to be called, but Publisher::publish() is not firing it in the current mock setup. Track in a follow-up
// PR; skipping for now so CI parity can land. The bug is likely a mis-mocked do_action or a refactor
// that removed the action fire.
$this->markTestSkipped( 'Latent bug — see TODO; tracked for follow-up PR.' );
Functions\when( 'wp_insert_post' )->justReturn( 49 );
Functions\when( 'do_action' )->alias( function () {} );
Actions\expectDone( 'prautoblogger_post_created' )
->once()
->with( 49, 'publish', $this->idea, $this->review );
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
}
/**
* Test that the prautoblogger_filter_post_data filter is applied.
*/
public function test_publish_applies_post_data_filter(): void {
// TODO(peptiderepo): latently broken alongside test_publish_fires_post_created_action.
// apply_filters('prautoblogger_post_data', ...) expected but not called. Follow-up PR.
$this->markTestSkipped( 'Latent bug — see TODO; tracked for follow-up PR.' );
Functions\when( 'wp_insert_post' )->justReturn( 50 );
Filters\expectApplied( 'prautoblogger_filter_post_data' )->once();
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
}
}

View File

@@ -13,8 +13,6 @@ namespace PRAutoBlogger\Tests\Core;
use PRAutoBlogger\Tests\BaseTestCase; use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions; use Brain\Monkey\Functions;
use Brain\Monkey\Actions;
use Brain\Monkey\Filters;
class PublisherTest extends BaseTestCase { class PublisherTest extends BaseTestCase {
@@ -36,6 +34,10 @@ class PublisherTest extends BaseTestCase {
Functions\when( 'sanitize_text_field' )->returnArg(); Functions\when( 'sanitize_text_field' )->returnArg();
Functions\when( 'wp_kses_post' )->returnArg(); Functions\when( 'wp_kses_post' )->returnArg();
// v0.18.1 empty-content guard strips tags before the emptiness check.
Functions\when( 'wp_strip_all_tags' )->alias( function ( $text ) {
return trim( strip_tags( (string) $text ) );
} );
Functions\when( 'is_wp_error' )->justReturn( false ); Functions\when( 'is_wp_error' )->justReturn( false );
Functions\when( 'apply_filters' )->returnArg( 2 ); Functions\when( 'apply_filters' )->returnArg( 2 );
Functions\when( 'absint' )->alias( function ( $val ) { return abs( (int) $val ); } ); Functions\when( 'absint' )->alias( function ( $val ) { return abs( (int) $val ); } );
@@ -168,131 +170,33 @@ class PublisherTest extends BaseTestCase {
} }
/** /**
* Test that taxonomy terms are assigned based on article_type from the idea. * v0.18.1 belt-and-braces: save_as_draft() with empty content throws
* and never reaches wp_insert_post — no empty draft post can be
* created (the 2026-06-11 post-921 incident shape).
*/ */
public function test_publish_assigns_category_from_article_type(): void { public function test_save_as_draft_refuses_empty_content(): void {
Functions\when( 'wp_insert_post' )->justReturn( 46 ); Functions\expect( 'wp_insert_post' )->never();
// get_term_by returns false (category doesn't exist), so wp_insert_term is called.
$captured_category = null;
Functions\when( 'wp_insert_term' )->alias( function ( $name, $taxonomy ) use ( &$captured_category ) {
$captured_category = $name;
return [ 'term_id' => 10 ];
} );
$captured_category_ids = null;
Functions\when( 'wp_set_post_categories' )->alias( function ( $post_id, $cat_ids ) use ( &$captured_category_ids ) {
$captured_category_ids = $cat_ids;
return true;
} );
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher(); $publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
// Article type is 'guide' → category should be 'Guides'. $this->expectException( \RuntimeException::class );
$this->assertSame( 'Guides', $captured_category ); $this->expectExceptionMessage( 'generated content is empty' );
$this->assertSame( [ 10 ], $captured_category_ids );
$publisher->save_as_draft( '', $this->idea, $this->review, 'run_empty_draft' );
} }
/** /**
* Test that target keywords are set as post tags. * v0.18.1 belt-and-braces: publish() refuses content that is empty
* once tags and whitespace are stripped (an empty HTML shell).
*/ */
public function test_publish_sets_tags_from_keywords(): void { public function test_publish_refuses_whitespace_only_html_content(): void {
Functions\when( 'wp_insert_post' )->justReturn( 47 ); Functions\expect( 'wp_insert_post' )->never();
$captured_tags = null;
Functions\when( 'wp_set_post_tags' )->alias( function ( $post_id, $tags, $append ) use ( &$captured_tags ) {
$captured_tags = $tags;
return true;
} );
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher(); $publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
$this->assertSame( [ 'test', 'keyword', 'example' ], $captured_tags ); $this->expectException( \RuntimeException::class );
} $this->expectExceptionMessage( 'generated content is empty' );
/** $publisher->publish( "<p> \n\t </p>", $this->idea, $this->review );
* Test that generation log entries are linked via run_id.
*/
public function test_publish_links_generation_logs_by_run_id(): void {
Functions\when( 'wp_insert_post' )->justReturn( 48 );
// Create an idea fixture without source_ids to avoid triggering SourceCollector
// queries that would overwrite captured_query in the mock.
$fixture = $this->get_article_idea_fixture();
$fixture['source_ids'] = [];
$idea = new \PRAutoBlogger_Article_Idea( $fixture );
$captured_query = null;
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'prepare' )->willReturnCallback( function ( $sql, ...$args ) use ( &$captured_query ) {
$captured_query = $sql;
return $sql;
} );
$wpdb->method( 'query' )->willReturn( 1 );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $idea, $this->review, 'run_link_test' );
// Should use run_id-based query, not timestamp-based.
$this->assertStringContainsString( 'run_id', $captured_query );
$this->assertStringNotContainsString( 'created_at', $captured_query );
}
/**
* Test that the prautoblogger_post_created action is fired after publishing.
*/
public function test_publish_fires_post_created_action(): void {
// TODO(peptiderepo): this test is latently broken — Mockery expects do_action_prautoblogger_post_created
// to be called, but Publisher::publish() is not firing it in the current mock setup. Track in a follow-up
// PR; skipping for now so CI parity can land. The bug is likely a mis-mocked do_action or a refactor
// that removed the action fire.
$this->markTestSkipped( 'Latent bug — see TODO; tracked for follow-up PR.' );
Functions\when( 'wp_insert_post' )->justReturn( 49 );
Functions\when( 'do_action' )->alias( function () {} );
Actions\expectDone( 'prautoblogger_post_created' )
->once()
->with( 49, 'publish', $this->idea, $this->review );
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
}
/**
* Test that the prautoblogger_filter_post_data filter is applied.
*/
public function test_publish_applies_post_data_filter(): void {
// TODO(peptiderepo): latently broken alongside test_publish_fires_post_created_action.
// apply_filters('prautoblogger_post_data', ...) expected but not called. Follow-up PR.
$this->markTestSkipped( 'Latent bug — see TODO; tracked for follow-up PR.' );
Functions\when( 'wp_insert_post' )->justReturn( 50 );
Filters\expectApplied( 'prautoblogger_filter_post_data' )->once();
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'query' )->willReturn( 0 );
$wpdb->method( 'prepare' )->willReturn( '' );
$GLOBALS['wpdb'] = $wpdb;
$publisher = new \PRAutoBlogger_Publisher();
$publisher->publish( '<p>Content</p>', $this->idea, $this->review );
} }
} }

View File

@@ -137,4 +137,76 @@ class RunStageStateTest extends BaseTestCase {
$this->assertFalse( \PRAutoBlogger_Run_Stage_State::is_done( 'run-1', 'draft' ) ); $this->assertFalse( \PRAutoBlogger_Run_Stage_State::is_done( 'run-1', 'draft' ) );
$this->assertNull( \PRAutoBlogger_Run_Stage_State::get_output( 'run-1', 'draft' ) ); $this->assertNull( \PRAutoBlogger_Run_Stage_State::get_output( 'run-1', 'draft' ) );
} }
/**
* start(role) → done(role) → is_done(role) must be true; is_done('') must
* be false — this catches the v0.18.2 regression where done() passed ''
* while start() passed a real role, so done() addressed a different row.
*
* In this test the wpdb mock records inserts via query() and simulates
* the SELECT via get_row():
* is_done('review','editor') → get_row finds the done row → true.
* is_done('review','') → resolve_role→'editor'; primary: miss;
* legacy fallback (role=''): miss → false.
*/
public function test_role_tagged_start_and_done_are_symmetric(): void {
$get_row_results = array(
array( 'status' => 'done', 'meta_json' => null ), // primary hit for 'editor'.
null, // primary miss for legacy check (role='editor' resolved, not '').
null, // legacy fallback (role='') also not found.
);
$call_index = 0;
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
$this->wpdb->method( 'query' )->willReturn( 1 );
$this->wpdb->method( 'get_row' )->willReturnCallback(
static function () use ( &$get_row_results, &$call_index ) {
$result = $get_row_results[ $call_index ] ?? null;
++$call_index;
return $result;
}
);
\PRAutoBlogger_Run_Stage_State::start( 'run-2', 'review', 'editor', 'idea:xyz' );
\PRAutoBlogger_Run_Stage_State::done( 'run-2', 'review', 'editor', 'idea:xyz' );
// Explicit role finds the done row.
$this->assertTrue(
\PRAutoBlogger_Run_Stage_State::is_done( 'run-2', 'review', 'editor', 'idea:xyz' ),
'is_done with explicit role should be true'
);
// '' resolves to 'editor'; primary misses; legacy '' fallback also misses.
$this->assertFalse(
\PRAutoBlogger_Run_Stage_State::is_done( 'run-2', 'review', '', 'idea:xyz' ),
'is_done with legacy empty role should be false (no legacy row exists)'
);
}
/**
* Mid-run-upgrade resume: a row created by v0.18.1 (agent_role='') must
* still be found by is_done('') under v0.18.2 via the legacy fallback.
* resolve_role('review','') → 'editor'; primary query misses; legacy
* fallback (role='') hits → is_done returns true.
*/
public function test_legacy_empty_role_row_is_found_on_fallback(): void {
$call_index = 0;
$get_row_results = array(
null, // primary query (role='editor'): miss.
array( 'status' => 'done', 'meta_json' => null ), // legacy fallback (role=''): hit.
);
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
$this->wpdb->method( 'get_row' )->willReturnCallback(
static function () use ( &$get_row_results, &$call_index ) {
$result = $get_row_results[ $call_index ] ?? null;
++$call_index;
return $result;
}
);
// is_done('') resolves to 'editor', misses, falls back to role='',
// finds the v0.18.1 row → true.
$this->assertTrue(
\PRAutoBlogger_Run_Stage_State::is_done( 'run-3', 'review', '', 'idea:abc' ),
'v0.18.1 empty-role row must be found via legacy fallback'
);
}
} }

View File

@@ -0,0 +1,240 @@
<?php
/**
* Tests for PRAutoBlogger_OpenRouter_Completion_Guard (v0.18.1).
*
* Validates the empty-completion verdict matrix: healthy pass-through,
* the single reasoning-disabled retry on length/reasoning empties, the
* never-retry-twice rule, and the hard failure for unexplained empties.
*
* @package PRAutoBlogger\Tests\Providers
*/
namespace PRAutoBlogger\Tests\Providers;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class OpenRouterCompletionGuardTest extends BaseTestCase {
protected function setUp(): void {
parent::setUp();
\PRAutoBlogger_Run_Context::clear();
\PRAutoBlogger_Audit_Writer::flush_cache();
$this->stub_get_option( [
'prautoblogger_log_level' => 'error',
] );
// Cost_Tracker::log_api_call() (failed-attempt booking) inserts a
// generation_log row and prices the burn via the pricing chain.
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'insert' )->willReturn( 1 );
$wpdb->insert_id = 7;
$GLOBALS['wpdb'] = $wpdb;
}
protected function tearDown(): void {
unset( $GLOBALS['wpdb'] );
\PRAutoBlogger_Run_Context::clear();
\PRAutoBlogger_Audit_Writer::flush_cache();
parent::tearDown();
}
/**
* Build a parsed-response fixture in the Response_Parser shape.
*
* @param string $content Visible content.
* @param string $finish finish_reason value.
* @return array
*/
private function parsed( string $content, string $finish ): array {
return [
'content' => $content,
'model' => 'deepseek/deepseek-v4-flash',
'prompt_tokens' => 1200,
'completion_tokens' => 4000,
'reasoning_tokens' => 4000,
'total_tokens' => 5200,
'finish_reason' => $finish,
'reasoning_content' => 'thinking…',
];
}
/**
* Healthy completion passes through untouched; the retry callable is
* never invoked.
*/
public function test_healthy_completion_passes_through(): void {
$parsed = $this->parsed( 'A full article.', 'stop' );
$invoked = 0;
$result = ( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$parsed,
[ 'stage' => 'draft' ],
false,
function () use ( &$invoked ) {
++$invoked;
return [];
}
);
$this->assertSame( $parsed, $result );
$this->assertSame( 0, $invoked );
}
/**
* The incident shape — empty content + finish_reason=length — retries
* exactly once with reasoning disabled and the empty_retry marker set,
* and returns the retry's result.
*/
public function test_empty_plus_length_retries_once_with_reasoning_disabled(): void {
$recovered = $this->parsed( 'Recovered article.', 'stop' );
$captured_opts = null;
$result = ( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$this->parsed( '', 'length' ),
[ 'stage' => 'draft', 'prompt_key' => 'content.single_pass' ],
true,
function ( array $retry_options ) use ( &$captured_opts, $recovered ) {
$captured_opts = $retry_options;
return $recovered;
}
);
$this->assertSame( $recovered, $result );
$this->assertSame( [ 'enabled' => false ], $captured_opts['reasoning'] );
$this->assertTrue( $captured_opts['empty_retry'] );
$this->assertSame( 'draft', $captured_opts['stage'] );
}
/**
* Whitespace-only content counts as empty (the guard trims).
*/
public function test_whitespace_only_content_counts_as_empty(): void {
$invoked = 0;
( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$this->parsed( " \n\t ", 'length' ),
[ 'stage' => 'polish' ],
true,
function ( array $retry_options ) use ( &$invoked ) {
++$invoked;
return $this->parsed( 'ok', 'stop' );
}
);
$this->assertSame( 1, $invoked );
}
/**
* An attempt already marked empty_retry is never retried again — the
* guard fails the call instead (no infinite retry loops).
*/
public function test_already_retried_empty_fails_without_second_retry(): void {
$invoked = 0;
try {
( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$this->parsed( '', 'length' ),
[ 'stage' => 'draft', 'empty_retry' => true ],
false,
function () use ( &$invoked ) {
++$invoked;
return [];
}
);
$this->fail( 'Expected RuntimeException for retried-and-still-empty completion.' );
} catch ( \RuntimeException $e ) {
$this->assertStringContainsString( 'empty content', $e->getMessage() );
$this->assertStringContainsString( 'after a reasoning-disabled retry', $e->getMessage() );
}
$this->assertSame( 0, $invoked );
}
/**
* Empty content with finish_reason=stop and no reasoning active: a
* reasoning-disabled retry cannot plausibly help — fail immediately.
*/
public function test_unexplained_empty_fails_without_retry(): void {
$invoked = 0;
try {
( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$this->parsed( '', 'stop' ),
[ 'stage' => 'review' ],
false,
function () use ( &$invoked ) {
++$invoked;
return [];
}
);
$this->fail( 'Expected RuntimeException for unexplained empty completion.' );
} catch ( \RuntimeException $e ) {
$this->assertStringContainsString( 'stage "review"', $e->getMessage() );
$this->assertStringContainsString( 'finish_reason=stop', $e->getMessage() );
}
$this->assertSame( 0, $invoked );
}
/**
* Empty content with reasoning active retries even when finish_reason
* is not 'length' (reasoning can eat the budget without a length flag).
*/
public function test_empty_with_reasoning_active_retries_on_any_finish_reason(): void {
$invoked = 0;
( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$this->parsed( '', 'stop' ),
[ 'stage' => 'draft' ],
true,
function ( array $retry_options ) use ( &$invoked ) {
++$invoked;
return $this->parsed( 'ok', 'stop' );
}
);
$this->assertSame( 1, $invoked );
}
/**
* The failed attempt is booked to generation_log with its REAL status:
* response_status='error', the stage, the model, and the token burn.
*/
public function test_failed_attempt_books_generation_log_row_with_error_status(): void {
$captured_row = null;
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'insert' )->willReturnCallback(
function ( $table, $row ) use ( &$captured_row ) {
if ( false !== strpos( (string) $table, 'generation_log' ) ) {
$captured_row = $row;
}
return 1;
}
);
$wpdb->insert_id = 9;
$GLOBALS['wpdb'] = $wpdb;
try {
( new \PRAutoBlogger_OpenRouter_Completion_Guard() )->finalize(
$this->parsed( '', 'stop' ),
[ 'stage' => 'draft' ],
false,
function () {
return [];
}
);
$this->fail( 'Expected RuntimeException.' );
} catch ( \RuntimeException $e ) {
$this->assertIsArray( $captured_row );
$this->assertSame( 'error', $captured_row['response_status'] );
$this->assertSame( 'draft', $captured_row['stage'] );
$this->assertSame( 'deepseek/deepseek-v4-flash', $captured_row['model'] );
$this->assertSame( 4000, $captured_row['completion_tokens'] );
$this->assertStringContainsString( 'Empty completion', $captured_row['error_message'] );
}
}
}

View File

@@ -0,0 +1,223 @@
<?php
/**
* Retry-path integration tests for PRAutoBlogger_OpenRouter_Provider.
*
* Wires the full send_chat_completion() path (decryptable API key,
* scripted HTTP responses, wpdb mock for failure bookkeeping) to verify
* the v0.18.1 empty-completion guard end to end: the incident-shape
* single retry with reasoning disabled, and the reasoning token cap
* shaping the outgoing request. Split from OpenRouterProviderTest.php
* to keep both files under the 300-line rule. All HTTP calls are
* mocked — no real API calls.
*
* @package PRAutoBlogger\Tests\Providers
*/
namespace PRAutoBlogger\Tests\Providers;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class OpenRouterProviderRetryTest extends BaseTestCase {
protected function setUp(): void {
parent::setUp();
// Stub get_option — provider calls get_option('prautoblogger_openrouter_api_key', '')
// for API key retrieval via private get_api_key() method.
// Return empty string so decryption is skipped (no key = empty return).
// Also include prautoblogger_log_level for Logger singleton.
$this->stub_get_option( [
'prautoblogger_openrouter_api_key' => '',
'prautoblogger_log_level' => 'info',
] );
// Stub wp_salt — called by PRAutoBlogger_Encryption during API key decryption.
Functions\when( 'wp_salt' )->justReturn( 'test_salt_key_for_unit_tests' );
// Stub get_transient/set_transient — used by OpenRouter_Pricing (called internally).
Functions\when( 'get_transient' )->alias(
function ( string $key ) {
if ( 'prautoblogger_openrouter_models' === $key ) {
return [
[
'id' => 'model/test',
'name' => 'Test Model',
'context_length' => 4096,
'pricing' => [ 'prompt' => 1.00, 'completion' => 2.00 ],
],
];
}
return false;
}
);
Functions\when( 'set_transient' )->justReturn( true );
// Stub URL parsing.
Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
// Stub HTTP functions for API calls.
Functions\when( 'wp_remote_post' )->justReturn( [
'body' => '{"choices":[{"message":{"content":"test"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}',
'response' => [ 'code' => 200 ],
] );
Functions\when( 'wp_remote_get' )->justReturn( [
'body' => '{}',
'response' => [ 'code' => 200 ],
] );
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 200 );
Functions\when( 'wp_remote_retrieve_body' )->justReturn(
'{"choices":[{"message":{"content":"test"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}'
);
Functions\when( 'is_wp_error' )->justReturn( false );
}
/**
* Wire the provider for a full send_chat_completion run: decryptable
* API key, reasoning settings, HTTP stubs that replay scripted
* responses, and a wpdb mock for the guard's failure bookkeeping.
*
* @param array $option_overrides Extra get_option values.
* @param array $responses Scripted JSON-decodable response bodies.
* @param array $requests (by ref) captures decoded request bodies.
*/
private function wire_full_provider( array $option_overrides, array $responses, array &$requests ): void {
\PRAutoBlogger_Run_Context::clear();
$encrypted_key = \PRAutoBlogger_Encryption::encrypt( 'sk-or-v1-unit-test-key-0000' );
$this->stub_get_option( array_merge( [
'prautoblogger_openrouter_api_key' => $encrypted_key,
'prautoblogger_log_level' => 'error',
], $option_overrides ) );
Functions\when( 'absint' )->alias( function ( $val ) {
return abs( (int) $val );
} );
Functions\when( 'wp_remote_post' )->alias(
function ( $url, $args ) use ( &$requests, $responses ) {
$requests[] = json_decode( $args['body'], true );
$body = $responses[ count( $requests ) - 1 ];
return [
'body' => $body,
'response' => [ 'code' => 200 ],
];
}
);
Functions\when( 'wp_remote_retrieve_response_code' )->alias(
function ( $response ) {
return $response['response']['code'];
}
);
Functions\when( 'wp_remote_retrieve_body' )->alias(
function ( $response ) {
return $response['body'];
}
);
// The guard books failed attempts through Cost_Tracker + Logger.
$wpdb = $this->create_mock_wpdb();
$wpdb->method( 'insert' )->willReturn( 1 );
$wpdb->insert_id = 11;
$GLOBALS['wpdb'] = $wpdb;
}
/**
* v0.18.1 incident shape, end to end: reasoning enabled (uncapped
* effort mode), the first response burns the whole completion budget
* on thinking and returns empty content with finish_reason=length —
* the provider retries exactly once with reasoning disabled and
* returns the recovered completion.
*/
public function test_empty_length_completion_retries_once_with_reasoning_disabled(): void {
$requests = [];
$empty_response = json_encode( [
'model' => 'deepseek/deepseek-v4-flash',
'choices' => [ [ 'message' => [ 'content' => '', 'reasoning' => 'endless thinking…' ], 'finish_reason' => 'length' ] ],
'usage' => [ 'prompt_tokens' => 1200, 'completion_tokens' => 4000, 'reasoning_tokens' => 4000, 'total_tokens' => 5200 ],
] );
$good_response = json_encode( [
'model' => 'deepseek/deepseek-v4-flash',
'choices' => [ [ 'message' => [ 'content' => 'Recovered article.' ], 'finish_reason' => 'stop' ] ],
'usage' => [ 'prompt_tokens' => 1200, 'completion_tokens' => 900, 'total_tokens' => 2100 ],
] );
$this->wire_full_provider(
[
'prautoblogger_reasoning_enabled' => '1',
'prautoblogger_reasoning_effort' => 'xhigh',
'prautoblogger_reasoning_max_tokens' => 0,
],
[ $empty_response, $good_response ],
$requests
);
try {
$provider = new \PRAutoBlogger_OpenRouter_Provider();
$result = $provider->send_chat_completion(
[ [ 'role' => 'user', 'content' => 'Write the article.' ] ],
'deepseek/deepseek-v4-flash',
[ 'temperature' => 0.7, 'max_tokens' => 4000, 'stage' => 'draft' ]
);
$this->assertSame( 'Recovered article.', $result['content'] );
$this->assertCount( 2, $requests );
// First attempt: global reasoning, uncapped effort mode.
$this->assertSame( [ 'enabled' => true, 'effort' => 'xhigh' ], $requests[0]['reasoning'] );
$this->assertSame( 4000, $requests[0]['max_tokens'] );
// Retry: reasoning disabled per call.
$this->assertSame( [ 'enabled' => false ], $requests[1]['reasoning'] );
// Caller metadata never reaches the HTTP body.
$this->assertArrayNotHasKey( 'stage', $requests[0] );
$this->assertArrayNotHasKey( 'empty_retry', $requests[1] );
} finally {
unset( $GLOBALS['wpdb'] );
\PRAutoBlogger_Run_Context::clear();
}
}
/**
* v0.18.1 reasoning budget: with the token cap active (default), the
* outgoing request caps thinking via reasoning.max_tokens and raises
* max_tokens by the cap — and a healthy completion needs no retry.
*/
public function test_reasoning_cap_shapes_the_outgoing_request(): void {
$requests = [];
$good_response = json_encode( [
'model' => 'deepseek/deepseek-v4-flash',
'choices' => [ [ 'message' => [ 'content' => 'Article text.' ], 'finish_reason' => 'stop' ] ],
'usage' => [ 'prompt_tokens' => 1200, 'completion_tokens' => 900, 'total_tokens' => 2100 ],
] );
$this->wire_full_provider(
[
'prautoblogger_reasoning_enabled' => '1',
'prautoblogger_reasoning_effort' => 'xhigh',
'prautoblogger_reasoning_max_tokens' => 2048,
],
[ $good_response ],
$requests
);
try {
$provider = new \PRAutoBlogger_OpenRouter_Provider();
$result = $provider->send_chat_completion(
[ [ 'role' => 'user', 'content' => 'Write the article.' ] ],
'deepseek/deepseek-v4-flash',
[ 'temperature' => 0.7, 'max_tokens' => 4000, 'stage' => 'draft' ]
);
$this->assertSame( 'Article text.', $result['content'] );
$this->assertCount( 1, $requests );
$this->assertSame( 2048, $requests[0]['reasoning']['max_tokens'] );
$this->assertArrayNotHasKey( 'effort', $requests[0]['reasoning'] );
$this->assertSame( 6048, $requests[0]['max_tokens'] );
} finally {
unset( $GLOBALS['wpdb'] );
\PRAutoBlogger_Run_Context::clear();
}
}
}

View File

@@ -0,0 +1,189 @@
<?php
/**
* Tests for PRAutoBlogger_OpenRouter_Request_Builder::build_body() (v0.18.1).
*
* Validates body assembly, the global-vs-per-call reasoning precedence, the
* reasoning token cap + completion headroom, and that caller-metadata keys
* never leak into the HTTP body.
*
* @package PRAutoBlogger\Tests\Providers
*/
namespace PRAutoBlogger\Tests\Providers;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class OpenRouterRequestBuilderTest extends BaseTestCase {
private const MESSAGES = [
[ 'role' => 'system', 'content' => 'sys' ],
[ 'role' => 'user', 'content' => 'usr' ],
];
protected function setUp(): void {
parent::setUp();
Functions\when( 'absint' )->alias( function ( $val ) {
return abs( (int) $val );
} );
}
/**
* Reasoning enabled globally + cap set: thinking is capped via
* reasoning.max_tokens, effort is dropped, and the completion budget
* is raised by the cap so content keeps its full allowance.
*/
public function test_reasoning_cap_replaces_effort_and_raises_headroom(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '1',
'prautoblogger_reasoning_effort' => 'xhigh',
'prautoblogger_reasoning_max_tokens' => 2048,
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body( self::MESSAGES, 'deepseek/deepseek-v4-flash', [ 'max_tokens' => 4000 ] );
$this->assertSame( 2048, $body['reasoning']['max_tokens'] );
$this->assertArrayNotHasKey( 'effort', $body['reasoning'] );
$this->assertSame( 6048, $body['max_tokens'] );
$this->assertTrue( $body['reasoning']['enabled'] );
}
/**
* Cap setting 0 = pure effort mode: the historical body shape is
* preserved exactly (effort kept, no reasoning.max_tokens, no headroom).
*/
public function test_cap_zero_keeps_pure_effort_mode(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '1',
'prautoblogger_reasoning_effort' => 'xhigh',
'prautoblogger_reasoning_max_tokens' => 0,
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body( self::MESSAGES, 'deepseek/deepseek-v4-flash', [ 'max_tokens' => 4000 ] );
$this->assertSame( [ 'enabled' => true, 'effort' => 'xhigh' ], $body['reasoning'] );
$this->assertSame( 4000, $body['max_tokens'] );
}
/**
* Per-call reasoning override (the guard's retry) beats the global
* setting; a disabled override gets no cap and no headroom.
*/
public function test_per_call_disabled_override_beats_global_setting(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '1',
'prautoblogger_reasoning_effort' => 'xhigh',
'prautoblogger_reasoning_max_tokens' => 2048,
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body(
self::MESSAGES,
'deepseek/deepseek-v4-flash',
[
'max_tokens' => 4000,
'reasoning' => [ 'enabled' => false ],
]
);
$this->assertSame( [ 'enabled' => false ], $body['reasoning'] );
$this->assertSame( 4000, $body['max_tokens'] );
}
/**
* Global reasoning off + no override: no reasoning key at all and no
* budget math (historical default path).
*/
public function test_reasoning_off_produces_no_reasoning_key(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '0',
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body(
self::MESSAGES,
'google/gemini-2.5-flash-lite',
[
'temperature' => 0.7,
'max_tokens' => 4000,
'response_format' => [ 'type' => 'json_object' ],
]
);
$this->assertArrayNotHasKey( 'reasoning', $body );
$this->assertSame( 0.7, $body['temperature'] );
$this->assertSame( 4000, $body['max_tokens'] );
$this->assertSame( [ 'type' => 'json_object' ], $body['response_format'] );
}
/**
* An explicit caller reasoning config with its own max_tokens is
* respected (no cap overwrite) but still gets completion headroom.
*/
public function test_caller_reasoning_max_tokens_respected_with_headroom(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '0',
'prautoblogger_reasoning_max_tokens' => 2048,
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body(
self::MESSAGES,
'deepseek/deepseek-v4-flash',
[
'max_tokens' => 1000,
'reasoning' => [ 'enabled' => true, 'max_tokens' => 512 ],
]
);
$this->assertSame( 512, $body['reasoning']['max_tokens'] );
$this->assertSame( 1512, $body['max_tokens'] );
}
/**
* Caller-metadata keys (stage, prompt_key, empty_retry) must never
* appear in the HTTP body.
*/
public function test_caller_metadata_keys_never_leak_into_body(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '0',
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body(
self::MESSAGES,
'google/gemini-2.5-flash-lite',
[
'max_tokens' => 4000,
'stage' => 'draft',
'prompt_key' => 'content.single_pass',
'empty_retry' => true,
]
);
$this->assertArrayNotHasKey( 'stage', $body );
$this->assertArrayNotHasKey( 'prompt_key', $body );
$this->assertArrayNotHasKey( 'empty_retry', $body );
$this->assertSame( [ 'model', 'messages', 'max_tokens' ], array_keys( $body ) );
}
/**
* Reasoning enabled but the call has no completion ceiling: nothing to
* protect, body passes through with effort untouched.
*/
public function test_no_max_tokens_means_no_budget_math(): void {
$this->stub_get_option( [
'prautoblogger_reasoning_enabled' => '1',
'prautoblogger_reasoning_effort' => 'high',
'prautoblogger_reasoning_max_tokens' => 2048,
] );
$body = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )
->build_body( self::MESSAGES, 'deepseek/deepseek-v4-flash', [] );
$this->assertSame( [ 'enabled' => true, 'effort' => 'high' ], $body['reasoning'] );
$this->assertArrayNotHasKey( 'max_tokens', $body );
}
}