Commit Graph

14 Commits

Author SHA1 Message Date
peptiderepo
573520558c fix(images): CTO review blockers on PR #9
Addresses four blockers from CTO review in
convo/prautoblogger/threads/2026-04-image-pipeline/04-cto-block-pr9.md:

1. PHPUnit red — 2 retry-path tests failing on bad mocks.
   The success-after-retry branch calls wp_remote_retrieve_header()
   only on the success attempt; the original mocks queued two mime
   values and popped the first (text/plain), which made the provider's
   normalize_response_body() throw "unexpected shape". Replaced the
   pop-queue with a single justReturn('image/png'). The retry-after
   header read on the 5xx/429 branch still works (coerces to int 0,
   falls back to exponential backoff).

2. XSS defense-in-depth — wrap untrusted API response bodies in
   esc_html() before they land in exception / user-facing messages.
   - class-cloudflare-image-provider.php: 4xx-throw and
     retry-exhaustion-throw now escape substr($raw, 0, 300) and
     $last_error respectively.
   - class-cloudflare-image-validator.php: network-error and
     HTTP-error-body messages now use esc_html__() on the template
     and esc_html() on the substituted values.

3. PHPCS hygiene on the 4 new files (CTO path A). Converted the
   one-line private-method docblocks to full multi-line format with
   @param / @return / @throws tags. Added a docblock to __construct.

4. File-size cap. The docblock expansion pushed
   class-cloudflare-image-provider.php over 300 lines. Extracted
   credential lookups + URL builder + log forwarders into a new
   class-cloudflare-image-support.php (101 lines). Provider is now
   271 lines, all new files under the 300-line cap.

No production behaviour changed beyond the escape wrapping. The
provider's public API, retry policy, and response handling are
identical to c823618.

File sizes after fix:
- interface-image-provider.php:         100
- class-cloudflare-image-provider.php:  271
- class-cloudflare-image-pricing.php:    78
- class-cloudflare-image-validator.php: 116
- class-cloudflare-image-support.php:   101

Agent-Session: cowork-2026-04-15-image-pipeline-commit-1a-cto-blockers
2026-04-15 14:16:39 +07:00
peptiderepo
11108b3bb5 feat(images): Cloudflare Workers AI image provider (commit 1a)
First commit of the image + Instagram A/B pipeline workstream. Ships the
Cloudflare Workers AI image provider, its pricing + validator helpers,
four new settings fields in a new "Images" admin section, and unit tests
with mocked HTTP. Nothing calls the provider yet from the article
pipeline — integration lands in commit 1b.

Why: CEO-approved on 2026-04-15 (see
convo/prautoblogger/threads/2026-04-image-pipeline/01-cto-handoff.md).
Style is locked to the 90s infomercial pastiche; default model is FLUX.1
[schnell] at ~$0.0011/MP (~$0.01/article for 8 images across 4 placements
x 2 variants).

Risk flags:
- Direct call to Cloudflare Workers AI bypassing AI Gateway (decision
  D-001, documented in convo/prautoblogger/decisions/). Gateway route
  to Workers AI currently 403s; OpenRouter gateway path unaffected.
- prab_event_log structured writes deferred to commit 1b when the
  table lands (decision D-002). Logger-based logging is in place now.
- No schema changes. No existing code paths touched outside settings.
- Backward compatible: provider is instantiable but not wired to any
  consumer yet.

Test plan:
- CI runs PHPUnit including the new CloudflareImageProviderTest.
- After merge: verify the new Images section appears on the settings
  page, the style-suffix textarea pre-fills with the infomercial prompt,
  and entering the existing CLOUDFLARE_AI_TOKEN + account UUID lets a
  future "Test Connection" button return OK (button ships in a later
  commit; the underlying validate_credentials_detailed() works today).

Files:
- includes/providers/interface-image-provider.php   (adopted from CTO draft)
- includes/providers/class-cloudflare-image-provider.php  (283 lines)
- includes/providers/class-cloudflare-image-pricing.php   (78 lines)
- includes/providers/class-cloudflare-image-validator.php (107 lines)
- includes/admin/class-settings-fields.php (+ Images section, 4 fields)
- prautoblogger.php (+ PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL, _STYLE_SUFFIX)
- tests/unit/Providers/CloudflareImageProviderTest.php
- ARCHITECTURE.md (file tree, integrations table, options table, decision #16)
- CONVENTIONS.md (How To: Add a New Image Provider)
- CHANGELOG.md (Unreleased section)

Agent-Session: cowork-2026-04-15-image-pipeline-commit-1a
2026-04-15 10:11:10 +07:00
peptiderepo
428a3d5861 feat: optional Cloudflare AI Gateway proxy for OpenRouter calls
Adds two WP options: prautoblogger_ai_gateway_base_url (routes OpenRouter calls through a Cloudflare AI Gateway when set to an https:// URL; empty = direct, the default) and prautoblogger_ai_gateway_cache_ttl (seconds for cf-aig-cache-ttl response caching; 0 = off).

The gateway is a transparent OpenRouter-compatible proxy, so no consuming class, no provider abstraction, and no response-parsing path changes. The http_api_curl belt-and-suspenders Authorization filter is rescoped to the configured upstream host so it still runs under gateway.ai.cloudflare.com.

Rationale: leverages existing Cloudflare infrastructure to satisfy the CTO cost-control rules (caching, cost tracking, rate limiting, fallback) without building equivalent middleware in-plugin. Fully opt-in and reversible from the admin UI.

Docs: ARCHITECTURE.md options + integrations tables updated; key decision #15 added. Uninstall is unaffected (wildcard prautoblogger_% delete).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 01:41:30 +07:00
Terence Ong
46d3a35c3a fix: decode HTML entities in posts widget titles and excerpts
WordPress's get_the_title() returns HTML-encoded entities (e.g., &#8217;
for smart quotes). Since the React component renders via createElement
(textContent, not innerHTML), these entities displayed as raw text.

Fix applied at two levels:
- PHP REST endpoint: html_entity_decode() before sending JSON response
- JS PostCard component: decodeEntities() safety net for any residual
  encoded entities from other sources

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 14:33:51 +07:00
Terence Ong
4f704a5dcd fix: add key format validation to validate_credentials_detailed()
Root cause of the 401 was a corrupted API key: the WordPress auth
salt changed after the key was encrypted, so decryption produced
garbage instead of sk-or-... OpenRouter interprets the garbled
Bearer token as "Missing Authentication header."

Adds the same sk-or- prefix check to the credential validation
method so users see a clear "re-enter your key" message instead
of a cryptic 401 error.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 08:48:32 +07:00
Terence Ong
98ef81f49a fix: resolve OpenRouter 401 by injecting auth header at cURL level
Hostinger's hosting environment appears to strip the Authorization
header from outgoing wp_remote_post requests before they reach the
cURL transport. This caused OpenRouter to respond with HTTP 401
"Missing Authentication header" even though the header was set in
the wp_remote_post args array.

Fixes:
- Add http_api_curl filter (priority 99) that re-sets the
  Authorization header directly on the cURL handle, bypassing any
  intermediate header stripping. Scoped to openrouter.ai URLs only.
- Applied to all three OpenRouter call sites: send_chat_completion,
  validate_credentials_detailed, and get_available_models.
- Filter is cleaned up in a finally block to avoid leaking.

Also:
- Add pre-flight key format validation (must start with "sk-or-")
  to catch corrupted decryption early with a clear error message.
- Fix retry condition: was `>= 429` (incorrectly retried 430-499),
  now `=== 429` (only retry rate-limit).
- Add detailed diagnostic logging on 401/403 auth failures.
- Add .env.credentials to .gitignore.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 08:30:37 +07:00
peptiderepo
b21d102afb feat: v0.2.2 — CI hardening, remove dead stubs, strengthen tests
Address CTO audit findings for PRAutoBlogger:
- CI pipeline now runs PHPCS (WordPress standards) and PHPUnit before deploy
- Removed TikTok/Instagram/YouTube stub providers (dead code, not registered)
- Rewrote PublisherTest with real behavioral assertions (post_status, metadata,
  taxonomy, log linking, hooks) instead of method-existence checks
- Added cross-system LLM budget coordination docs to ARCHITECTURE.md
- Bumped version to 0.2.2

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 22:41:10 +07:00
peptiderepo
03074180d4 fix: strip LLM output artifacts (code fences, HTML wrappers) before saving posts
LLMs sometimes ignore format instructions and wrap content in markdown
code fences or full HTML document structures. Added sanitize_llm_content()
to the publisher that strips these before wp_kses_post() runs, preventing
raw ```html blocks and <html><head><body> wrappers from reaching post_content.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 18:19:09 +07:00
peptiderepo
d9985f6dc2 refactor: remove PullPush.io, use Reddit RSS as primary data source
PullPush.io index was frequently stale/unavailable. Reddit RSS/Atom feeds
work reliably from datacenter IPs (Hostinger) where .json gets 403.

- RSS is now the primary source for post fetching
- .json endpoints kept as fallback for posts and sole source for comments
- Deleted class-pull-push-client.php
- Updated admin UI, test connection handler, docs, and ARCHITECTURE.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 14:00:55 +07:00
peptiderepo
b5cbbef804 feat: v0.2.1 — fix encryption, diverse multi-topic generation, UX fixes
- Rewrite encryption with "enc:" prefix to permanently eliminate
  the double-encryption bug on settings save
- Add one-time migration to clear legacy non-prefixed encrypted values
- Rewrite content analyzer prompts to request N distinct diverse topics
  across 5 categories (question, complaint, comparison, news, guide)
- Pass target_count*2 from pipeline to analyzer for headroom
- Add skip_dedup flag so manual Generate Now always produces content
- Generate Now button now sends force=1 to clear stale locks
- Rename OpenRouter provider files to PSR-4 convention (hyphenated)
- Switch default models to google/gemini-2.5-flash-lite
- Clean up reddit_debug log channel to standard 'reddit'
- Bump version to 0.2.1

Cost: ~$0.003/article with Gemini 2.0 Flash, ~34s pipeline.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 13:36:36 +07:00
peptiderepo
726b378a52 feat: v0.2.0 — PullPush.io admin UI, version bump, deploy fix
- Remove Reddit OAuth fields (Client ID/Secret) from admin settings
- Add source status indicator showing PullPush.io + .json fallback health
- Add configurable cache TTL, time window, and posts-per-subreddit settings
- Update Test Connections to report which Reddit source is active
- Bump version 0.1.0 → 0.2.0 across plugin header, constant, and readme
- Switch deploy pipeline from zip/REST API to SSH rsync with --delete
- Add LiteSpeed cache purge step to prevent stale OPcache after deploy
- Update CHANGELOG.md and readme.txt for 0.2.0 release

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 10:59:35 +07:00
peptiderepo
0db5096b31 feat: replace Reddit OAuth with PullPush.io + .json fallback 2026-04-12 09:16:46 +07:00
Terence Ong
88d674d679 Initial commit: PRAutoBlogger v0.1.0 with frontend posts widget 2026-04-10 23:33:42 +07:00
Terence Ong
68c6f67bcf Initial commit: AutoBlogger v0.1.0
WordPress plugin that auto-researches topics from Reddit, generates
SEO-optimized articles via OpenRouter LLMs, runs them through a chief
editor agent, and publishes on a daily schedule.

Includes:
- Full generation pipeline (collect → analyze → score → generate → review → publish)
- Cost tracking and budget enforcement
- Admin UI: settings, review queue, metrics, activity log
- CI/CD pipeline (GitHub Actions → WordPress REST deploy)
- Unit test suite (PHPUnit + Brain Monkey)
- Structured logging with configurable verbosity

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 16:10:27 +07:00