Writing instructions were framed as a weak "Additional instructions:"
block at the end of the system prompt. Models prioritized competing
format directives in each stage's user prompt and ignored the style
guide. Now: system prompt wraps instructions as "MANDATORY STYLE GUIDE"
with override language, every stage user prompt reinforces compliance,
polish stage explicitly preserves lists and links, and chief editor
revision preserves structural formatting.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Research LLM call runs once per pipeline but was logged with no run_id
or post_id, making it invisible in per-article cost breakdowns. Now the
pipeline's cost tracker flows through Source_Collector to the research
provider, tagging costs with the run_id. After all articles complete,
amortize_research_costs() divides the cost evenly and inserts one row
per article. link_generation_logs() excludes llm_research stage so the
first article doesn't grab the full cost.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
New submenu page showing all article ideas from the content analyzer.
Displays title, type, relevance score, frequency, key points, and
keywords with type filtering and pagination. Gives live visibility
into the idea pipeline.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
New data source that sends a configurable research prompt to a
reasoning-capable model (Grok 4.1 Fast, DeepSeek-R1, etc.) to identify
trending topics, content gaps, and emerging questions. Findings feed
into the content analyzer alongside Reddit data, combining real-time
community signals with deep knowledge-base research.
New admin settings: Research Model picker, Research Prompt textarea,
and LLM Deep Research toggle in Enabled Sources.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Enables reasoning-capable models (Grok 4.1 Fast, DeepSeek-R1, etc.)
via new admin settings: Enable Reasoning toggle and Reasoning Effort
selector. Provider auto-injects reasoning params when enabled; callers
can override per-call via options array. Response parser captures
reasoning_tokens and reasoning_content for visibility.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
GLM 4.7 Flash was timing out at 120s on large analysis prompts.
Parse failure errors now log the raw LLM response at error level
(not debug) so the root cause is always visible.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Cost column is now clickable — hovering shows a per-step breakdown
with stage name, model, token count, and cost for every LLM call.
Pure CSS popover, no JS dependency.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
New toggle in Images settings controls whether the source-data-based
second image is generated. Disabling saves one image gen call + one
LLM prompt rewrite per article. Defaults to enabled.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Two new textareas in Content settings let admins provide custom
instructions for the analysis and chief editor LLM stages, matching
the Writing Instructions field added in v0.4.4. All three pipeline
stages now have user-controllable system prompt customization.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
New textarea in Content settings lets admins provide custom instructions
appended to the writer's system prompt. Steers style, structure, voice,
and formatting without editing code.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Models like GPT 5.1 Nano ignore response_format: json_object and wrap
their JSON in ```json fences or add preamble text. New Json_Extractor
utility tries: (1) direct decode, (2) strip markdown fences, (3) find
outermost { ... } substring. Applied to analyzer and chief editor
parsers. Raw response logged on parse failure for debugging.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Title column was compressed to ~30px making post titles unreadable.
Give title 35% min-width with word-wrap, trim model columns to 100px
with text-overflow ellipsis, cost column to 55px.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Columns were crushed to 1-char width by WordPress's auto-layout.
Added 120px for model columns and 60px for cost.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
v0.4.1 — Three new columns on the WordPress Posts admin page showing
which LLM wrote each article, which model generated its featured image,
and the total API cost. Model names shortened for compact display with
full ID in tooltip. Cost queries the generation_log table, skipping
the DB hit entirely for non-generated posts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Two-pronged fix for repeated article topics:
1. Feed last 30 days of published article titles into the LLM analysis
prompt with explicit "avoid these" instruction. Zero cost — just
extra context in an existing API call.
2. Replace keyword-overlap dedup (60% word match) with embedding-based
cosine similarity via sentence-transformers/all-MiniLM-L12-v2 on
OpenRouter. Catches rephrasings that keyword matching misses
(e.g. "BPC-157 dosing" vs "how much BPC-157 to take"). Falls back
to keyword matching if the embedding API is unavailable.
Cost: ~$0.00001 per generation run ($0.02/M tokens, ~500 tokens/run).
New files:
- class-semantic-dedup.php — Embedding cosine similarity + keyword fallback
- class-open-router-embedding-provider.php — OpenRouter /embeddings client
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The status poller's orphan-recovery logic re-scheduled cron events for
articles already being generated. During the ~90s generation window, the
queue option in the DB still contained the in-progress idea because the
process only deleted/updated it AFTER generation completed.
Fix: persist the consumed queue to the DB BEFORE starting generation.
When the poller checks get_option(), it now sees either an empty queue
(for the last article) or a queue without the current idea, so orphan
recovery cannot duplicate work.
Root cause: process_next_queued_article() did array_shift on a local
variable but left the DB unchanged until after the slow LLM+image
generation finished. The poller saw the stale DB state, assumed the
cron event had died, and re-scheduled it — producing a 4th post from
3 ideas on every run.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The frontend status poller measured elapsed time from `started` (set once
at the beginning of the run) and declared a stall at 300s. Three articles
take ~6 minutes total, so the poller always false-alarmed on article 3.
Now every stage broadcast writes `last_updated` into the transient, and
the stall check compares idle time since the last update — not since the
run started. This lets N-article runs complete without false timeout as
long as each individual article finishes within 5 minutes.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The pipeline previously ran all articles sequentially in a single PHP
process. On Hostinger, this timed out at ~120s — enough for 1 article
but not 2+. Now the pipeline generates article 1 in-process, then
queues articles 2..N as individual WP-Cron events. Each article gets
its own PHP process with its own execution time budget, so we can
generate any number of articles regardless of server time limits.
Architecture:
- Pipeline_Runner: orchestrate (collect+analyze+score) + first article,
then serialize remaining ideas to wp_options and chain cron events
- Article_Worker (new): focused single-article worker extracted from
the pipeline loop — content gen + editorial + publish
- Executor: new on_process_article_queue() handler for chained events;
status poller re-schedules orphaned queue jobs automatically
- Article_Idea: added to_array() for queue serialization
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The collector used INSERT IGNORE which silently skipped duplicate items
without updating their collected_at timestamp. After 24 hours, these
items fell out of the analyzer's window permanently — even though they
kept appearing in the RSS feed. This caused "No new source data to
analyze" on every run once the initial batch aged out.
Switch to INSERT ... ON DUPLICATE KEY UPDATE to refresh collected_at
(plus score and comment_count, which change over time on Reddit).
The analyzer's 24-hour window now sees re-fetched items again.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Dedup now has two narrow scopes instead of checking all posts ever:
1. Intra-batch: prevents proposing two articles on the same topic
within a single pipeline run (keyword overlap ≥60%)
2. Recent posts: checks only posts from the last 7 days to avoid
back-to-back similar content
Older articles are intentionally NOT checked — revisiting a topic
weeks later is fine. This prevents the dedup from becoming
increasingly aggressive as the blog grows, which was the root cause
of "no viable article ideas found" with 125 collected items.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The old has_similar_post() used WordPress search ('s' parameter) which
matches ANY word in the query. On a niche peptide blog, every topic
shares vocabulary like "BPC-157", "peptide", "dosage" — so all 125
ideas were false-positive deduped against existing posts, producing
zero viable article ideas.
New approach: extract meaningful keywords (strip stopwords), compare
against each existing post title, and only dedup when ≥60% of the
topic's keywords overlap with a single title. Also caches the title
list per pipeline run to avoid repeated queries.
Added summary logging so we can see exactly how many ideas pass
through each filter stage.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Both Image A and Image B now fire concurrently through a single
generate_image_batch() call instead of sequentially. Total wall-clock
time equals the slowest image (~20s), not the sum (~40s), which
eliminates the Image B timeout problem on Hostinger where
max_execution_time killed the cron before the second request finished.
New files:
- class-open-router-image-batch.php — curl_multi orchestrator
- generate_image_batch() added to image provider interface
Pipeline refactored: prompts built upfront, single batch call, results
processed per-key. Cloudflare provider gets a sequential fallback.
Tests updated for batch API. All files under 300-line cap.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Three fixes in one:
1. Duplicate image: prepend_caption_to_post() was embedding the full
image + caption as a <figure> block, but the theme already displays
the featured image. Now only the caption text is prepended — no
second copy of the image.
2. Hardcoded model names: removed all FLUX.1/FLUX.2 references from
model-agnostic code (pipeline, prompt builder, sideloader, OpenRouter
provider, interface, admin labels). The Cloudflare provider still
references FLUX since it specifically wraps that model family.
3. Test alignment: OpenRouterImagePricingTest was asserting against
removed models (flux-2-pro, seedream). Updated to match current
COST_PER_IMAGE entries (Gemini Flash, GPT-5 Image).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The status endpoint waited 300 seconds before checking if the pipeline
had produced output. On Hostinger, PHP's max_execution_time kills the
cron process after ~120s. The pipeline publishes the post before images,
so the post exists but the transient never transitions to 'complete'.
The user sees "Generating…" for 5 minutes, then gives up.
Now the status endpoint proactively checks for recently-created posts
after just 90 seconds. If found, it reports success immediately. The
300-second hard-fail threshold is still there for genuinely dead runs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Captions were being baked into the image by the FLUX model, causing
text to get cut off at the edges. Now the LLM generates scene and
caption separately — the scene drives image gen (with explicit
"no text in the image" instruction), and the caption is inserted
as a styled <figure>/<figcaption> HTML block at the top of the post.
Changes:
- rewrite_via_llm() returns array{scene, caption} instead of string
- build_article_prompt() and build_source_prompt() return {prompt, caption}
- Style suffix v4: removes "caption text" instruction, adds "no text" directive
- Image pipeline destructures prompt/caption, stores caption in attachment meta
- prepend_caption_to_post() inserts figure+figcaption HTML into post content
- Deduplicated generate_image_a/b into shared generate_single_image()
- One-time v4 migration auto-updates existing style suffix on deploy
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Pipeline with 3 articles + GPT-5 Image generation legitimately takes
3-4 minutes. The 180-second fallback was triggering before the pipeline
finished, incorrectly reporting "no content" when it was still running.
Increase to 300 seconds to give the pipeline room to complete.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
media_handle_sideload() is only available in admin context. When the
pipeline runs via WP-Cron (background generation), the function is
undefined. Add require_once guards for media.php, file.php, and
image.php before calling sideload.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Extract PRAutoBlogger_Generation_Lock (DB mutex) and
PRAutoBlogger_Ajax_Handlers (image/model/test AJAX) from the
482-line executor. Executor retains generation cron/AJAX + model
registry at 299 lines. Document background generation flow in
ARCHITECTURE.md.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The WP-Cron loopback is also subject to Hostinger's 120s timeout.
Adding ignore_user_abort(true) keeps the PHP process alive after
LiteSpeed closes the connection.
Also adds fallback completion detection: if the transient is stuck
at "running" but the generation lock was released (pipeline finished),
the status endpoint now checks for recently-created posts to confirm
success and recover gracefully.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Hostinger's LiteSpeed web server kills any HTTP connection that runs
longer than 120 seconds with a 500 "Request Timeout" error. The full
pipeline (Reddit fetch → topic scoring → article generation → editorial
pass → image gen ×2) takes 120-180s, causing "Request failed: error"
on every manual generation attempt.
Architecture change:
- Generate Now AJAX handler now schedules a one-shot WP-Cron event
and returns immediately (~100ms response time)
- New prautoblogger_manual_generation cron action runs the pipeline
in a separate PHP process free from the connection timeout
- Pipeline progress is written to a transient at each stage
- New prautoblogger_generation_status AJAX endpoint lets the frontend
poll progress every 5 seconds
- Frontend auto-resumes polling on page load if a generation is running
- Direct wp-cron.php loopback ensures cron fires even if DISABLE_WP_CRON
is set (common on Hostinger)
Version bump: 0.2.9 → 0.3.0
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace photography-style prompts with a comedy writer system prompt
that generates Far Side-style single-panel comic concepts with punchy
captions. The LLM rewriter now outputs a comic scene + caption line,
and the style suffix renders as classic black-ink newspaper comic on
yellowed newsprint.
Includes v3 style migration to auto-replace both the old infomercial
and the short-lived photography style in wp_options. Bumped max_tokens
to 180 to accommodate scene + caption output.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Two fixes:
1. Image attachment: moved set_post_thumbnail() and Image B post meta
into generate_and_attach_images() so they persist immediately after
each image generates. Previously the caller set them after both images
completed — if the process timed out (common with GPT-5 Image at
~30s/image), the featured image was never attached and Image B was
never attempted.
2. Image prompts: replaced FLUX.1-optimized rewriter system prompt and
90s infomercial style suffix with prompts optimized for Gemini Flash
Image and GPT-5 Image. New style: premium scientific lifestyle
photography with golds/teals color grading. Includes one-time migration
to update stored style suffix.
Also logs when Image B is skipped due to missing source data (previously
silent), helping diagnose why some posts only get one image.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Gemini image models reject arbitrary aspect ratios like 150:79
(computed via GCD from 1200×632 pixels). Replace GCD-based calculation
with a snap-to-nearest approach using 7 standard ratios (1:1, 3:2,
2:3, 4:3, 3:4, 16:9, 9:16). Also set modalities to ["image", "text"]
as required by some providers.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Don't silently swap to a different model when the user's selection is
unknown. Pass whatever the user configured to OpenRouter and let the
API error clearly. Fallback chain: caller hint → saved option →
PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL constant. Cost estimation for
unknown models logs a warning and uses a conservative $0.05 estimate.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Three issues found in activity logs:
1. Image model IDs stale — FLUX and Seedream removed from OpenRouter.
Updated to current models: Gemini 2.5/3.1 Flash Image, Gemini 3 Pro
Image, GPT-5 Image/Mini. Default changed to gemini-2.5-flash-image.
2. openrouter/free router wraps upstream 429 errors in HTTP 200 body
with error object. Both text and image response parsers now detect
this pattern and surface a proper RuntimeException.
3. Image request used modalities: ["image"] but Gemini needs
["image", "text"]. Updated to include both.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Some models (and the openrouter/free router) may return null content
instead of a string. The old check used isset() which returns false
for null, triggering the "unexpected response format" error.
Now: checks for choices[0].message (not content), treats null content
as empty string, and logs the actual response shape on failure so we
can diagnose what the model returned.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The free models router (openrouter/free) doesn't use the :free suffix,
so it needs an explicit check alongside the suffix-based one.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Models with the :free suffix (e.g. google/gemini-2.5-flash-preview:free)
are served at no charge by OpenRouter. The cost estimator now returns
$0.00 for these models instead of falling through to the conservative
$10/$30 per-million-token fallback.
No changes needed in the model picker or provider — :free models use
the same API endpoint and already appear in the registry.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
PHP 8.3 TypeError and Error extend \Throwable but NOT \Exception,
so catch(\Exception) silently drops them — explaining why the
generation pipeline fails at the publishing step with no activity
log entry. Now every catch in the generation path catches
\Throwable and logs the exception class name for diagnostics.
Bump to v0.2.7.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The autoloader splits CamelCase on lowercase→uppercase transitions, so
PRAutoBlogger_OpenRouter_Image_Provider maps to class-open-router-image-provider.php.
Files were named class-openrouter-* (missing hyphen), causing a PHP fatal
error when the pipeline tried to instantiate the provider — which killed
the process before any logging could fire.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The field renderer still checked for the old 'cloudflare_image' capability
but the setting was changed to 'image_generation'. Updated to resolve
model name/price from the shared get_image_models() list. Bumped to
v0.2.5 to bust browser JS/CSS cache.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replaces Cloudflare Workers AI (FLUX.1 schnell) as the default image
provider with OpenRouter, which offers FLUX.2 Pro, Seedream 3.0,
Gemini Flash Image, and GPT Image 1 at comparable or better pricing.
- New provider class (3-file split: provider, pricing, support) reuses
the existing OpenRouter API key and Cloudflare AI Gateway
- Admin settings: new Image Provider dropdown (openrouter/cloudflare),
model picker shows all available image models from both providers
- Image pipeline auto-selects the configured provider at construction
- Cost logging now uses actual model name instead of hardcoded flux-1-schnell
- Default model changed to black-forest-labs/flux-2-pro ($0.03/image)
- Unit tests for pricing resolution and provider response parsing
Cost impact: FLUX.2 Pro at $0.03/image vs schnell at $0.0007/image —
~43x more expensive per image, but dramatically better quality. At 2
images/article × 1 article/day = ~$1.80/month. Seedream 3.0 ($0.003)
available as a budget alternative.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Root cause: both attach_generated_images() in post-assembler and the
retroactive handler in executor passed null as source_data to the image
pipeline. The pipeline's Image B branch requires non-null source_data
to fire, so Image B was silently skipped on every article since the
feature was built.
Fix: added get_source_data_for_image() to Source_Collector to retrieve
the original Reddit post title/content by source_ids. Post-assembler
now pulls source_ids from the Article_Idea; executor pulls them from
the _prautoblogger_source_ids post meta saved by the publisher.
Also added a regression test proving Image B is skipped when source_data
is null, so this handoff gap will be caught if re-introduced.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
FLUX.1 [dev] was removed from Cloudflare Workers AI in April 2026,
returning HTTP 400 "No route for that URI". This removes it from the
static model picker list and pricing calculations. Any saved setting
referencing flux-1-dev gracefully falls through to flux-1-schnell
via the null-coalesce in resolve_model().
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
prautoblogger_cloudflare_ai_token was missing from the $encrypted array
in sanitize_field(), so the token was stored as plaintext. On read,
decrypt() failed on the non-encrypted value and returned empty string,
causing HTTP 401 on every Cloudflare Workers AI call.
Fix: add the field to the encrypted list so future saves encrypt it.
Also add legacy plaintext detection in get_api_token() and the validator
so the existing DB value works immediately and gets auto-encrypted on
first use.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Apply the same interactive model picker UI to the image model field.
Since Cloudflare models don't come from OpenRouter's registry, the
two FLUX models are embedded as static data in the page config and
the JS popup renders cost-per-image instead of token pricing.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace plain text inputs for analysis/writing/editor model fields
with a rich model picker that fetches the OpenRouter model registry
and displays a searchable popup with model name, provider, input/output
pricing per 1M tokens, and context window. Also extracts source status
and model field renderers into dedicated field classes to keep
class-admin-page.php under the 300-line cap.
New files:
- assets/js/model-picker.js — popup UI with search, filtering, caching
- assets/css/model-picker.css — popup styles matching admin design system
- includes/admin/fields/class-open-router-model-field.php — server render
- includes/admin/fields/class-source-status-field.php — extracted field
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replaces the rule-based prompt builder with a cheap LLM call
(analysis model via OpenRouter) that distills article content into
concise visual scene descriptions. The old rule-based method becomes
the fallback if the LLM call fails.
Key design decisions:
- System prompt teaches the LLM to describe objects/setting/lighting
instead of abstract concepts, and to avoid faces (FLUX.1 weakness)
- Uses the analysis model (gemini-2.5-flash-lite) at ~$0.001/call
- Cost is logged to the analytics dashboard via log_api_call()
- Style suffix is still appended separately so the rewriter only
handles scene composition
Cost impact: +~$0.001 per image on top of ~$0.0008 generation cost.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Adds wp_ajax_prautoblogger_generate_image so images can be generated
for existing posts that were published before image gen was enabled
or fixed. Uses set_time_limit(120) to handle the Cloudflare API
latency that caused fatals when run via Code Snippets init hook.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>