Compare commits

..

6 Commits

Author SHA1 Message Date
peptiderepo
7669a9c199 chore: revert PHPCS to summary report 2026-04-24 01:34:09 +07:00
peptiderepo
97f5936d27 style: fix PSR2.Files.EndFileNewline — single trailing newline 2026-04-24 01:33:57 +07:00
peptiderepo
58496156ee chore: temp PHPCS full report for debug 2026-04-24 01:31:08 +07:00
peptiderepo
7b397d74c7 style: fix PHPCS — trailing ws + blank line before class } 2026-04-24 01:21:43 +07:00
peptiderepo
4b05180bca docs: add missing docblocks and parameter documentation
- Add comprehensive docblock to private get_style_suffix() method explaining empty-string safeguard
- Add @param documentation for new cost_tracker parameter in publish() and save_as_draft() methods
- Improves code clarity for future maintainers
2026-04-23 18:11:43 +00:00
peptiderepo
9bd843297d fix: image style suffix empty-string bypass and image cost run_id mismatch (v0.12.2)
Bug 1: Image style suffix empty-string bypass
- get_option() for prautoblogger_image_style_suffix returns empty string from DB instead of default
- Root cause of post #675 rendering photorealistically instead of newspaper comic
- Fixed by extracting private helper get_style_suffix() that treats both absent AND empty as default
- Applied to all three call sites in class-image-prompt-builder.php (lines 85, 107, 272)

Bug 2: Image cost logged under wrong run_id
- class-image-pipeline.php created fresh cost tracker when invoked without argument
- Image costs logged under different run_id than article's other stages
- Cost breakdowns aggregating by run_id silently excluded image line items
- Fixed by threading article worker's cost tracker through Publisher to image pipeline
- Modified publisher.php and post-assembler.php to accept and pass cost_tracker
- Updated article-worker.php to pass cost_tracker to publisher methods
- Image costs now share same run_id as analysis, draft, review, and llm_research stages

Version: 0.12.1 -> 0.12.2
CHANGELOG: Added comprehensive entry describing both fixes
2026-04-23 18:06:54 +00:00
169 changed files with 1636 additions and 22925 deletions

View File

@@ -21,7 +21,7 @@ jobs:
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.2', '8.3']
php: ['7.4', '8.1', '8.3']
steps:
- uses: actions/checkout@v4
- name: Setup PHP ${{ matrix.php }}
@@ -31,7 +31,7 @@ jobs:
coverage: none
- name: Syntax check all PHP files
# Exclude .github/mu-plugins — those run on the production server (PHP 8+)
# and may use PHP 8+ syntax (union types etc.) that older versions reject.
# and may use PHP 8+ syntax (union types etc.) that 7.4 rejects.
run: |
set -e
find . -name '*.php' \
@@ -44,14 +44,9 @@ jobs:
phpcs:
name: PHPCS (WordPress standards)
runs-on: ubuntu-latest
continue-on-error: false # strict after PHPCS cleanup in v0.8.3
permissions:
contents: write # allows phpcbf auto-fix commits back to the PR branch
continue-on-error: false # now strict after PHPCS cleanup in v0.8.3
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.head_ref || github.ref_name }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
@@ -60,34 +55,22 @@ jobs:
tools: composer:v2, phpcs
- name: Install WordPress Coding Standards
run: |
# Allow the PHPCS composer-installer plugin (auto-registers standards).
composer global config --no-plugins allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
# WPCS 3.x requires PHPCSExtra (for the Universal.* and NormalizedArrays.* sniffs)
# AND phpcsutils. Installing the installer itself lets it auto-register the standards path.
composer global require --no-interaction \
"dealerdirect/phpcodesniffer-composer-installer:^1.0" \
"wp-coding-standards/wpcs:^3.0" \
"phpcsstandards/phpcsutils:^1.0" \
"phpcsstandards/phpcsextra:^1.0"
- name: Auto-fix with phpcbf (commit back to branch if changed)
# phpcbf exits 1 when it makes fixes, 0 when nothing to fix — both are success here.
# Commits made via GITHUB_TOKEN do not trigger a new CI run (GitHub prevents loops).
run: |
phpcbf --standard=phpcs.xml \
--extensions=php \
--ignore=vendor/*,tests/*,node_modules/* \
includes/ prautoblogger.php uninstall.php || true
if ! git diff --quiet; then
git config user.name "peptiderepo"
git config user.email "peptiderepo@users.noreply.github.com"
git add -A
git commit -m "style: auto-fix PHPCS violations via phpcbf"
git push
fi
- name: Run PHPCS (only non-auto-fixable violations can fail here)
- name: Run PHPCS
run: |
phpcs --standard=phpcs.xml \
--extensions=php \
--ignore=vendor/*,tests/*,node_modules/* \
--warning-severity=0 \
--report=full \
--report=summary \
includes/ prautoblogger.php uninstall.php
phpunit:
@@ -96,7 +79,7 @@ jobs:
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.2', '8.3']
php: ['7.4', '8.1', '8.3']
steps:
- uses: actions/checkout@v4
- name: Setup PHP ${{ matrix.php }}

View File

@@ -123,18 +123,17 @@ jobs:
git fetch origin ${{ github.event.pull_request.base.ref }} --depth=50
BASE_SHA="${{ github.event.pull_request.base.sha }}"
HEAD_SHA="${{ github.event.pull_request.head.sha }}"
# Write the diff to a file, not a step output / env var. Passing a
# ~400KB diff through the process env (execve argv+envp) exceeds the
# runner ARG_MAX and fails the next step with "Argument list too long"
# (issue #110). File transport also sidesteps the ~1MB step-output cap.
git diff --no-color "$BASE_SHA" "$HEAD_SHA" | head -c 400000 > /tmp/cto-review-diff.txt
DIFF=$(git diff --no-color "$BASE_SHA" "$HEAD_SHA" | head -c 400000)
FILES=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA")
SIZE=$(wc -c < /tmp/cto-review-diff.txt)
SIZE=$(echo -n "$DIFF" | wc -c)
{
echo "size=$SIZE"
echo "files<<EOF_FILES"
echo "$FILES"
echo "EOF_FILES"
echo "diff<<EOF_DIFF"
echo "$DIFF"
echo "EOF_DIFF"
} >> "$GITHUB_OUTPUT"
- name: Load repo conventions
@@ -162,7 +161,7 @@ jobs:
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO_NAME: ${{ github.event.repository.name }}
DIFF_PATH: /tmp/cto-review-diff.txt
DIFF: ${{ steps.diff.outputs.diff }}
DIFF_SIZE: ${{ steps.diff.outputs.size }}
CHANGED_FILES: ${{ steps.diff.outputs.files }}
CONVENTIONS: ${{ steps.conventions.outputs.content }}
@@ -230,9 +229,7 @@ jobs:
user_blocks.append(f"**Changed files:**\n```\n{os.environ['CHANGED_FILES']}\n```\n")
if os.environ.get("CONVENTIONS", "").strip():
user_blocks.append(f"# Repo CONVENTIONS.md\n{os.environ['CONVENTIONS']}\n")
with open(os.environ["DIFF_PATH"], encoding="utf-8", errors="replace") as _df:
_diff_text = _df.read()
user_blocks.append(f"# Diff\n```diff\n{_diff_text}\n```\n")
user_blocks.append(f"# Diff\n```diff\n{os.environ['DIFF']}\n```\n")
user_message = "\n\n".join(user_blocks)
tools = [{
@@ -451,7 +448,7 @@ jobs:
if rev.get("concerns"):
lines.append("**Concerns:**")
for c in rev["concerns"]:
sev = c.get("severity", "UNKNOWN").upper()
sev = c["severity"].upper()
f = f"`{c['file']}`" if c.get("file") else ""
lines.append(f"- **{sev}** {f} — {c['issue']}")
lines.append("")

View File

@@ -4,20 +4,21 @@ on:
push:
branches: [main]
concurrency:
group: deploy-prautoblogger-${{ github.ref }}
cancel-in-progress: true
jobs:
validate:
name: PHP Lint Gate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
- name: Checkout code
uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
coverage: none
- name: PHP Lint Check
run: |
set -e
@@ -29,9 +30,60 @@ jobs:
-print0 | xargs -0 -n1 -P4 php -l > /dev/null
deploy:
name: Deploy (shared pipeline)
needs: validate
uses: peptiderepo/peptide-e2e/.github/workflows/deploy-app.yml@main
with:
target_path: wp-content/plugins/prautoblogger
secrets: inherit
name: Deploy to Production
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup SSH key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -p ${{ secrets.SSH_PORT }} ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts 2>/dev/null
- name: Deploy via rsync
run: |
rsync -avz --delete \
--exclude '.git' \
--exclude '.github' \
--exclude 'tests' \
--exclude 'phpunit.xml.dist' \
--exclude 'composer.json' \
--exclude 'composer.lock' \
--exclude 'vendor' \
--exclude '.distignore' \
--exclude 'ARCHITECTURE.md' \
--exclude 'CONVENTIONS.md' \
-e "ssh -i ~/.ssh/deploy_key -p ${{ secrets.SSH_PORT }}" \
./ ${{ secrets.SSH_USERNAME }}@${{ secrets.SSH_HOST }}:~/domains/peptiderepo.com/public_html/wp-content/plugins/prautoblogger/
- name: Purge LiteSpeed Cache
run: |
ssh -i ~/.ssh/deploy_key -p ${{ secrets.SSH_PORT }} \
${{ secrets.SSH_USERNAME }}@${{ secrets.SSH_HOST }} \
"cd ~/domains/peptiderepo.com/public_html && \
wp litespeed-purge all 2>/dev/null || \
(find wp-content/litespeed/ -type f -delete 2>/dev/null; touch .lscache_purge 2>/dev/null) || true"
- name: Health check
run: |
sleep 5
STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://peptiderepo.com)
# 200 = normal healthy response.
# 403 = peptide-starter-theme v1.5.2 CF-peer validator rejecting this
# GHA-runner direct-to-origin request as non-Cloudflare traffic.
# That rejection is the validator working — itself a positive
# liveness signal. Real user traffic via Cloudflare gets 200.
if [ "$STATUS" != "200" ] && [ "$STATUS" != "403" ]; then
echo "ERROR: Site returned unexpected HTTP $STATUS after deploy"
exit 1
fi
echo "Site is responsive (HTTP $STATUS)"
- name: Cleanup
if: always()
run: rm -f ~/.ssh/deploy_key

View File

@@ -29,22 +29,12 @@ jobs:
with:
script: |
const sha = context.sha;
// Squash-merge -> PR association is eventually-consistent; poll briefly
// before concluding this was a direct push (avoids false positives on merges).
async function findMergedPR() {
for (let attempt = 1; attempt <= 5; attempt++) {
const { data: prs } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner: context.repo.owner,
repo: context.repo.repo,
commit_sha: sha,
});
const m = prs.find(p => p.merged_at);
if (m) return m;
if (attempt < 5) await new Promise(r => setTimeout(r, 10000));
}
return null;
}
const merged = await findMergedPR();
const { data: prs } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner: context.repo.owner,
repo: context.repo.repo,
commit_sha: sha,
});
const merged = prs.find(p => p.merged_at);
if (merged) {
core.info(`OK: commit ${sha.substring(0,7)} came from PR #${merged.number}`);
return;

505
ARCHITECTURE.md Normal file → Executable file
View File

@@ -75,11 +75,6 @@ PRAutoBlogger is a WordPress plugin that monitors social media (starting with Re
│ │ retried once with a rule-based fallback
│ │ prompt via Image_NSFW_Retry; a second block
│ │ logs WARNING and publishes without that image.
│ │ v0.17.0: results then pass through the local
│ │ deterministic Image_Composer (corner mark +
│ │ branded OG/square variants for Image A; mark
│ │ only for Image B) with a capability ladder
│ │ (imagick → GD resize-only → pass-through).
│ │ Sideloads to media library, logs costs.
└────────────┬────────────┘
│
@@ -108,35 +103,16 @@ prautoblogger/
├── CHANGELOG.md # Semantic versioning changelog
│
├── assets/
│ ├── brand/ # Vendored brand PNGs rasterized from peptide-repo-brand SVGs (composer overlays)
│ │ ├── logo-mark-small-56.png # Corner mark, 1x
│ │ ├── logo-mark-small-112.png # Corner mark / OG band logo, 2x
│ │ ├── logo-horizontal-reverse-128.png # Square footer lockup, 1x
│ │ └── logo-horizontal-reverse-256.png # Square footer lockup, 2x
│ ├── fonts/ # Bundled OFL faces for deterministic text rendering
│ │ ├── Poppins-Bold.ttf # Square-card caption face
│ │ ├── Poppins-SemiBold.ttf # OG band caption face
│ │ └── OFL.txt # SIL Open Font License
│ ├── css/
│ │ ├── admin.css # Admin page styles (wp-admin conventions)
│ │ ├── board.css # Kanban board styles -- warm editorial palette (v0.19.0)
│ │ ├── dossier.css # Article dossier page styles: verdict pills, cost receipt, trace toggle (v0.19.2)
│ │ ├── dossier-edit.css # M3 edit/re-run layer: chips, edit panel, image grid, spend warning (v0.20.0)
│ │ └── posts-widget.css # Frontend posts widget styles (uses theme CSS vars)
│ └── js/
│ ├── admin.js # Admin page interactivity (vanilla JS / Alpine.js)
│ ├── board.js # Board poller: AJAX poll + DOM updates + backoff (v0.19.0)
│ ├── dossier.js # Per-stage raw-trace toggle: aria-expanded / aria-controls (v0.19.2)
│ ├── dossier-edit.js # M3 edit/re-run actions + stage-status polling (queued -> pickup -> result) (v0.20.0)
│ └── posts-widget.js # React component for frontend post cards (wp.element)
│
├── includes/
│ ├── class-prautoblogger.php # Main orchestrator — registers all hooks, delegates execution (split v0.19.2)
│ ├── class-db-migrations.php # DB migration methods extracted from class-prautoblogger.php (v0.19.2 split, binding 1)
│ ├── class-pipeline-schema-installer.php # Pipeline substrate tables (prompts, run_sources, run_decisions, runs, run_stages, stage_inputs)
│ ├── class-migrate-prompt-seed-v0180.php # One-shot v0.18.0 prompt-registry seed migration
│ ├── class-executor.php # Cron handlers, generation AJAX (delegates start + status to poller), model registry
│ ├── class-generation-status-poller.php # Generation AJAX handlers: status transient renewal, lock-age orphan detection (R2b/R3), abort_orphaned_run
│ ├── class-prautoblogger.php # Main orchestrator — registers all hooks, delegates execution
│ ├── class-executor.php # Cron handlers, generation AJAX (start + status), model registry
│ ├── class-ajax-handlers.php # Non-generation AJAX: images, models, test connections
│ ├── class-generation-lock.php # DB-level atomic mutex for single-writer generation
│ ├── class-activator.php # Activation: create DB tables, set defaults, schedule cron
@@ -144,15 +120,6 @@ prautoblogger/
│ ├── class-autoloader.php # PSR-4-style autoloader for plugin classes
│ │
│ ├── admin/
│ │ ├── class-board-page.php # Kanban board -- primary landing screen (v0.19.0)
│ │ ├── class-board-data-provider.php # Board orchestrator: 4-column snapshot + dossier deep-links (v0.19.0, v0.19.2)
│ │ ├── class-board-gen-log-query.php # Board gen_log queries: Generating + Failed column raw DB reads (v0.19.0)
│ │ ├── class-dossier-page.php # Article dossier admin page: options.php-parent hidden-page, priority 12, enqueue, nonce (v0.19.3)
│ │ ├── class-dossier-data-assembler.php # 5-query view-model builder: runs+stages+gen_log+decisions+meta (v0.19.2)
│ │ ├── class-dossier-gen-log-query.php # Dossier gen_log queries: per-stage cost receipt + raw trace (v0.19.2)
│ │ ├── class-dossier-actions.php # M3 AJAX: save fork / queue replay / queue rebuild / stage-status poll (v0.20.0)
│ │ ├── class-dossier-rerun-panel-data.php # M3 per-stage affordance + spend view model (v0.20.0)
│ │ ├── class-dossier-image-data.php # F3: post's pipeline attachments via _prautoblogger_image_role (v0.20.0)
│ │ ├── class-admin-page.php # Main settings page (tabbed SaaS-style UI)
│ │ ├── class-settings-fields.php # Declarative settings: sections + core fields (API/Models/Content/Sources)
│ │ ├── class-settings-fields-extended.php # Operational fields: schedule, publishing, display, analytics, images
@@ -180,37 +147,8 @@ prautoblogger/
│ │ ├── class-post-assembler.php # Post-creation helpers: taxonomy, log linking, images, sanitization
│ │ ├── class-image-pipeline.php # Orchestrates A/B image generation (parallel via batch)
│ │ ├── class-image-prompt-builder.php # Generates visual prompts from article/source data
│ │ ├── class-image-template-filler.php # Fills the editorial style template's {{ topic_summary }} slot (v0.16.0)
│ │ ├── interface-image-composer.php # Contract: provider bytes → featured-first variant list (v0.17.0)
│ │ ├── class-image-composer.php # Composer orchestrator: cached capability probe + degradation ladder
│ │ ├── class-image-composer-imagick.php # Imagick renderer: corner mark, OG band, square card (WP-free)
│ │ ├── class-image-composer-canvas.php # Imagick primitives: smoke test, cover-crop, logo, deterministic PNG (WP-free)
│ │ ├── class-image-composer-editor.php # Resize-only rung via wp_get_image_editor (GD path)
│ │ ├── class-image-composer-layout.php # Geometry defaults + caption clamp (pure, WP-free)
│ │ ├── class-image-attacher.php # Sideload + cost log + variant meta-linking + caption prepend
│ │ ├── class-image-media-sideloader.php # Imports images into WordPress media library
│ │ ├── class-cost-tracker.php # Logs all API costs, enforces budget limits
│ │ ├── class-stage-display-map.php # Stage vocabulary: labels + default roles + prompt keys (old + new + image stages)
│ │ ├── class-prompt-registry.php # Versioned prompt registry, read side (render, pins, self-healing fallback)
│ │ ├── class-prompt-registry-writer.php # Registry write side (create version, activate, seed) — versions immutable
│ │ ├── class-prompt-defaults.php # Canonical v1 bodies: content.* + analysis.* (seed + fallback single source)
│ │ ├── class-prompt-defaults-editorial.php # Canonical v1 bodies: editor.* / research.system / image.* (composer seam)
│ │ ├── class-run-context.php # Per-process active run id (set by Cost_Tracker::set_run_id)
│ │ ├── class-run-state.php # runs-table ledger + lifecycle row (ceiling/reserved/settled, pins, status)
│ │ ├── class-cost-governor.php # Per-run reserve-before-call enforcement (atomic conditional UPDATE)
│ │ ├── class-cost-ceiling-exception.php # Thrown on ceiling breach (run already halted)
│ │ ├── class-run-stage-state.php # Per-run per-stage state machine: read API + thin write proxies (split v0.20.0)
│ │ ├── class-run-stage-writes.php # Pipeline-path writes (start/done/fail; done clears stale) — extracted v0.20.0
│ │ ├── class-run-stage-rerun-state.php # M3 operator-action mutations: restart/mark_stale/demote (v0.20.0)
│ │ ├── class-stage-input-store.php # INSERT-only stage_inputs store: edit forks + idea seeds (v0.20.0)
│ │ ├── class-rerun-eligibility.php # M3 policy gates: frozen posts, editable stages, chain order (v0.20.0)
│ │ ├── class-stage-replay.php # M3 governed single-stage replay from a fork body (v0.20.0)
│ │ ├── class-rerun-executor.php # M3 cron handlers: replay + rebuild jobs (v0.20.0)
│ │ ├── class-rerun-job-support.php # M3 queue/lock/budget/status-transient plumbing (v0.20.0)
│ │ ├── class-request-recorder.php # B1: process-scoped outbound request-body stash -> generation_log.request_json (v0.20.0)
│ │ ├── class-run-reaper.php # Stuck-run sweep + audit-payload retention (rides the #19 cron)
│ │ ├── class-audit-writer.php # run_sources / run_decisions insert layer
│ │ ├── class-pipeline-status.php # Status-transient + summary helpers (extracted from runner/worker)
│ │ ├── class-logger.php # Structured logging singleton (error/warning/info/debug)
│ │ ├── class-article-worker.php # Single-article generation (content + edit + publish)
│ │ ├── class-pipeline-runner.php # Orchestrates pipeline; chains per-article cron jobs
@@ -220,7 +158,6 @@ prautoblogger/
│ ├── providers/
│ │ ├── interface-llm-provider.php # Contract for any LLM provider
│ │ ├── 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-pricing.php # Model pricing lookup and cost estimation
│ │ ├── interface-source-provider.php # Contract for any social media source
@@ -233,13 +170,11 @@ prautoblogger/
│ │ ├── 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-config.php # API base URL (direct vs AI Gateway)
│ │ ├── class-open-router-request-builder.php # Request body assembly + reasoning token cap/headroom (v0.18.1) + headers + Hostinger cURL auth workaround
│ │ ├── class-open-router-request-builder.php # Header building + Hostinger cURL auth workaround
│ │ ├── 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-support.php # Key, response parsing, retry, dimension snap
│ │ ├── class-runware-image-batch.php # True parallel curl_multi batch dispatcher
│ │ ├── class-runware-model-catalog.php # Live model catalog sync: modelSearch pagination, cache v2, failure cooldown
│ │ ├── class-runware-catalog-fetcher.php # HTTP fetch + normalize_models for Runware modelSearch (extracted for 300-line rule)
│ │ └── (new providers go here — see CONVENTIONS.md)
│ │
│ ├── services/
@@ -263,19 +198,11 @@ prautoblogger/
│
├── templates/
│ └── admin/
│ ├── board-page.php # Kanban board template (4-column editorial layout) (v0.19.0)
│ ├── dossier-page.php # Article dossier: two-column layout, sidebar, stage sections (v0.19.2)
│ ├── dossier-stage-section.php # Stage section partial: output, raw trace, M3 chips + rerun footer
│ ├── dossier-edit-panel.php # M3 per-stage edit panel: message textareas, fork info, spend strip (v0.20.0)
│ ├── dossier-log-stage-section.php # F3 log-only stage sections incl. image attachment grid (v0.20.0)
│ ├── dossier-sidebar-cards.php # M3 sidebar: run spend (guardrail 4) + models/pv consolidation (F2) (v0.20.0)
│ ├── dossier-stage-section.php # Per-stage block: rendered output + raw-trace toggle + cost receipt (v0.19.2)
│ ├── metabox-dossier-link.php # Slim post metabox: "View generation dossier →" link (v0.19.2)
│ ├── settings-page.php # Settings page template (tabbed sidebar layout)
│ ├── metrics-page.php # Metrics/cost dashboard template
│ ├── review-queue.php # Review queue table template
│ ├── log-viewer.php # Activity log viewer template
│ └── metabox-generation-info.php# Post metabox template (superseded by metabox-dossier-link.php in v0.19.2)
│ └── metabox-generation-info.php# Post metabox template
│
├── languages/
│ └── prautoblogger.pot # i18n translation template
@@ -372,19 +299,11 @@ Hostinger's 120-second LiteSpeed connection timeout. The frontend polls for stat
└──────────────────────────────┘
```
**Fallback detection (v0.18.3 R2b/R3):** The status transient is renewed on every stage
transition via `update_generation_stage()` (`Pipeline_Status::broadcast()`), so its TTL
always counts from the last activity rather than run start. When a status poll finds the
transient absent:
- **Lock within TTL (`lock_age ≤ STATUS_TTL = 600s`):** the background process is still alive
but has not broadcast yet (or the transient was evicted). `handle_missing_transient()` returns
`status: running` (R3) — button stays in-progress, no state change.
- **Lock exceeded TTL (`lock_age > STATUS_TTL`):** background process died without releasing the
lock. `abort_orphaned_run()` marks the `runs` row `failed`, releases the generation lock, deletes
the status transient and queue option, and returns `status: error` with "infrastructure timeout"
(R2b). A daily `Run_Reaper::sweep_stuck_runs()` at 2× `EXPECTED_RUN_SECONDS` (~3600s) remains
the backstop for runs the poll path never sees.
**Fallback detection:** If Hostinger kills the PHP process before it updates the
transient (despite `ignore_user_abort`), the status endpoint detects the orphan after
180 seconds by checking for recently-created posts with `_prautoblogger_run_id` meta.
It also releases any stale generation lock. After 600 seconds (STATUS_TTL), it gives
up unconditionally and reports a timeout.
---
@@ -438,7 +357,7 @@ All tables use `$wpdb->prefix` + `prautoblogger_` prefix.
| id | BIGINT UNSIGNED | Auto-increment PK |
| post_id | BIGINT UNSIGNED | WordPress post ID (nullable, set after publish)|
| run_id | VARCHAR(36) | UUID linking all entries from one pipeline run |
| stage | VARCHAR(50) | See "Stage vocabulary" below. Canonical edit-stage name is **'polish'** (this doc previously said 'edit'; the code always wrote 'polish') |
| stage | VARCHAR(50) | 'analysis', 'outline', 'draft', 'edit', 'review' |
| provider | VARCHAR(50) | 'openrouter' |
| model | VARCHAR(100) | Model identifier used |
| prompt_tokens | INT | Input tokens consumed |
@@ -447,8 +366,6 @@ All tables use `$wpdb->prefix` + `prautoblogger_` prefix.
| request_json | LONGTEXT | Full request payload (for debugging) |
| response_status | VARCHAR(20) | 'success', 'error', 'timeout' |
| error_message | TEXT | Error details if failed (nullable) |
| agent_role | VARCHAR(50) | v0.18.0, nullable. Role that made the call ('writer', 'editor', 'analyst', 'researcher', 'illustrator', …). Historical rows stay NULL |
| prompt_version | VARCHAR(20) | v0.18.0, nullable. Pinned prompt-registry version the call rendered with. Historical rows stay NULL |
| created_at | DATETIME | When the API call was made |
- INDEX: `post_id`
@@ -456,18 +373,6 @@ All tables use `$wpdb->prefix` + `prautoblogger_` prefix.
- INDEX: `created_at`
- INDEX: `stage`
**Stage vocabulary.** `stage` is a VARCHAR, not a SQL enum; the vocabulary lives in
`PRAutoBlogger_Stage_Display_Map` (PHP), which renders historical and new values coherently
and maps each stage to its default agent role + primary prompt-registry key:
- **Historical values (exist on prod):** `analysis`, `outline`, `draft`, `polish`, `review`,
`llm_research`, `image_a`, `image_b`, `image_prompt_rewrite`, `opik_eval_judge`.
Note: single-pass generation logs its one call as `draft` (no `outline` row — that absence
is how single-pass and multi-step runs are told apart in cost reporting).
- **Pipeline v2 values (new runs may write):** `research`, `curate`, `draft`, `editorial`,
`seo`, `publish`.
- Unknown values render via a humanizing fallback — the audit view never renders blank.
#### `prab_event_log` — Structured application logging
| Column | Type | Description |
@@ -500,124 +405,6 @@ and maps each stage to its default agent role + primary prompt-registry key:
- INDEX: `measured_at`
- INDEX: `composite_score`
#### Pipeline v2 substrate tables (v0.18.0, db 1.2.0)
Real table names use the standard prefix, e.g. `wp_prautoblogger_prompts` (the plan-of-record's
`prab_*` names are shorthand). Created by `PRAutoBlogger_Pipeline_Schema_Installer`; all are
dropped on uninstall.
##### `prautoblogger_prompts` — versioned prompt registry
| Column | Type | Description |
|-------------|-----------------|----------------------------------------------------------|
| id | BIGINT UNSIGNED | Auto-increment PK |
| prompt_key | VARCHAR(64) | Registry key, e.g. 'content.single_pass' (`key` is reserved SQL) |
| version | INT UNSIGNED | Monotonic per key; **rows are immutable** — edits create new versions |
| body | LONGTEXT | Prompt template; `{{ token }}` placeholders filled at render time |
| model | VARCHAR(100) | Optional model hint (informational in Phase 1) |
| params_json | LONGTEXT | Optional params snapshot (temperature, max_tokens, …) |
| author | VARCHAR(100) | Who created the version ('seed:v0.18.0', wp user login, agent) |
| created_at | DATETIME | Version creation time |
| active | TINYINT(1) | Exactly one active row per key |
- UNIQUE: `prompt_key, version` · INDEX: `prompt_key, active`
##### `prautoblogger_run_sources` — per-run source audit
| Column | Type | Description |
|---------------|--------------|----------------------------------------------|
| id | BIGINT UNSIGNED | Auto-increment PK |
| run_id | VARCHAR(36) | Pipeline run UUID |
| agent_role | VARCHAR(50) | Role that surfaced the source |
| source_url | VARCHAR(500) | Source URL (nullable) |
| doi | VARCHAR(255) | DOI when known (nullable) |
| kept | TINYINT(1) | Keep/discard decision |
| reason | TEXT | Why kept or discarded (nullable) |
| quality_score | FLOAT | Source quality weighting (nullable) |
| created_at | DATETIME | Row creation time |
- INDEX: `run_id` — consolidates the old `source_ids_json` + `_prautoblogger_research_sources`
scatter for **new** runs; historical runs are not backfilled.
##### `prautoblogger_run_decisions` — per-stage decision audit
| Column | Type | Description |
|----------------|-------------|-----------------------------------------------|
| id | BIGINT UNSIGNED | Auto-increment PK |
| run_id | VARCHAR(36) | Pipeline run UUID |
| stage | VARCHAR(50) | Stage that decided (see stage vocabulary) |
| verdict | VARCHAR(50) | e.g. 'approved', 'revised', 'rejected', 'halted' |
| rationale | TEXT | Decision rationale (nullable) |
| citation_score | FLOAT | Nullable until the Phase-2 editorial loop computes it |
| human_modified | TINYINT(1) | v0.20.0 — decision derives from a human-edited input (set on replay of the stage, or on decisions recorded while rebuilding a human-modified item) |
| created_at | DATETIME | Row creation time |
- INDEX: `run_id`
##### `prautoblogger_runs` — run ledger + lifecycle
| Column | Type | Description |
|---------------------|---------------|---------------------------------------------|
| run_id | VARCHAR(36) | PK — pipeline run UUID |
| status | VARCHAR(20) | pending / running / done / failed / halted |
| ceiling_usd | DECIMAL(10,6) | Per-run cost ceiling snapshotted at run start |
| reserved_usd | DECIMAL(10,6) | Outstanding reserve-before-call holds |
| settled_usd | DECIMAL(10,6) | Actual settled spend |
| overage_usd | DECIMAL(10,6) | Amount the breaching reservation exceeded the ceiling by |
| pinned_prompts_json | LONGTEXT | Map of prompt_key → version frozen at run start |
| started_at | DATETIME | Run start |
| updated_at | DATETIME | Last ledger/state write |
| finished_at | DATETIME | Set on done/failed/halted (nullable) |
- INDEX: `status` — the Cost_Governor's reserve is a single conditional UPDATE against this
row (same atomic discipline as the #10 generation lock), so concurrent `curl_multi`
writers cannot slip past the ceiling between check and call.
##### `prautoblogger_run_stages` — per-run per-stage state machine
| Column | Type | Description |
|-------------|-----------------|----------------------------------------------------|
| id | BIGINT UNSIGNED | Auto-increment PK |
| run_id | VARCHAR(36) | Pipeline run UUID |
| stage | VARCHAR(50) | Stage name (see stage vocabulary) |
| 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) |
| status | VARCHAR(20) | pending / running / done / failed / halted |
| attempt | SMALLINT UNSIGNED | Re-entry counter |
| cost_usd | DECIMAL(10,6) | Cost attributed to the stage |
| meta_json | LONGTEXT | Stage output snapshot — lets resume reuse a done stage instead of re-charging it (payload pruned on the retention cron) |
| human_modified | TINYINT(1) | v0.20.0 — set (sticky, never cleared) when an edited input fork enters execution for this row (CPO guardrail 2) |
| stale | TINYINT(1) | v0.20.0 — upstream changed after this row completed; row STAYS 'done' so resume never silently re-runs it; cleared only by a fresh done() |
| started_at | DATETIME | First entry |
| updated_at | DATETIME | Last transition |
| finished_at | DATETIME | Set on done/failed (nullable) |
- UNIQUE: `run_id, stage, agent_role, item_key` (the idempotency key) · INDEX: `status, updated_at`
##### `prautoblogger_stage_inputs` — immutable input-version store (v0.20.0, db 1.3.0)
| Column | Type | Description |
|--------------|-----------------|--------------------------------------------------|
| id | BIGINT UNSIGNED | Auto-increment PK |
| run_id | VARCHAR(36) | Pipeline run UUID |
| stage | VARCHAR(50) | Stage name ('' for idea seeds) |
| agent_role | VARCHAR(50) | Stage row agent role |
| item_key | VARCHAR(64) | Article scope |
| version | INT UNSIGNED | Monotonic per scope; **rows are INSERT-only** — edits create the next version, originals are never overwritten |
| source | VARCHAR(20) | 'human' (edit fork) or 'seed' (Article_Idea payload persisted at worker start) |
| request_json | LONGTEXT | Fork body / idea JSON. Human fork bodies pruned by the retention cron after R days; seed rows (~1KB) kept |
| author | VARCHAR(100) | WP user login, or 'pipeline' for seeds |
| created_at | DATETIME | Row creation time |
- UNIQUE: `run_id, stage, agent_role, item_key, version` · INDEX: `run_id`
- The ORIGINAL executed input of a stage is `generation_log.request_json` (B1) — it is
never copied or modified here; forks are the edit history (CPO guardrail 1).
**db version note:** `PRAUTOBLOGGER_DB_VERSION` moved 1.1.0 → 1.3.0 in v0.20.0. The
constant never actually carried the "db 1.2.0" this document used as shorthand for the
v0.18.0 substrate; 1.3.0 leapfrogs the phantom value so the version-compare self-healing
migration fires exactly once everywhere.
### WordPress Options (`wp_options`)
All prefixed with `prautoblogger_`:
@@ -632,14 +419,11 @@ All prefixed with `prautoblogger_`:
| `prautoblogger_analysis_model` | OpenRouter model for analysis (default: cheap) |
| `prautoblogger_writing_model` | OpenRouter model for writing (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_writing_pipeline` | 'single_pass' or 'multi_step' (default: multi_step) |
| `prautoblogger_niche_description` | Text description of the site's niche |
| `prautoblogger_target_subreddits` | JSON array of subreddits to monitor |
| `prautoblogger_monthly_budget_usd` | Monthly API spend limit in USD |
| `prautoblogger_per_run_cost_ceiling_usd` | v0.18.0 — per-run hard cost ceiling (USD); reserve-before-call enforced; snapshotted onto the runs row at run start; 0 = disabled. Default `PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD` ($0.50) |
| `prautoblogger_request_json_retention_days` | v0.18.0 — days before heavy audit payloads (generation_log.request_json, run_stages.meta_json) are NULLed by the daily cleanup cron; 0 = keep forever. Default `PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS` (14) |
| `prautoblogger_tone` | Content tone (informational, conversational, etc.) |
| `prautoblogger_min_word_count` | Minimum article word count (default: 800) |
| `prautoblogger_max_word_count` | Maximum article word count (default: 2000) |
@@ -653,22 +437,15 @@ All prefixed with `prautoblogger_`:
| `prautoblogger_schedule_time` | Daily generation time (HH:MM, default: '03:00') |
| `prautoblogger_image_model` | Image model slug from `Image_Model_Registry::get_models()`; provider is derived from this on save |
| `prautoblogger_image_provider` | Derived from the chosen model on save (v0.8.0+); not editable in admin UI |
| `prautoblogger_image_prompt_instructions` | System prompt given to the image rewriter LLM (v0.8.0+); falls back to `Image_Prompt_Builder::REWRITER_SYSTEM_PROMPT` when empty. v0.16.0: the default now instructs the LLM to emit a 1-2 sentence editorial topic/mechanism summary as the SCENE (was a comic gag) |
| `prautoblogger_image_prompt_instructions` | System prompt given to the image rewriter LLM (v0.8.0+); falls back to `Image_Prompt_Builder::REWRITER_SYSTEM_PROMPT` when empty |
| `prautoblogger_image_nsfw_retry` | Toggle: retry NSFW-blocked image slots with a rule-based fallback prompt (default: '1') |
| `prautoblogger_migrated_image_provider_v080` | One-shot migration flag — auto-heals mismatched provider/model pairs on first admin_init after v0.8.0 upgrade |
| `prautoblogger_article_font_family` | Font family key: 'default', 'inter', 'georgia', 'merriweather', 'lora', 'open_sans', 'roboto', 'system' |
| `prautoblogger_article_font_size` | Body font size in px (0 = theme default). Recommended: 16–18. |
| `prautoblogger_table_borders` | Toggle: add borders/padding/striping to tables (default: '1') |
| `prautoblogger_image_style_template` | Full image prompt template (v0.16.0+); contains exactly one `{{ topic_summary }}` token filled per-article with the rewriter scene. Default = `PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE` (editorial scientific illustration). Replaces the Style Suffix. Validated on save (single-token, brief A5) |
| `prautoblogger_image_style_suffix` | DEPRECATED (v0.16.0). Former comic style suffix appended to every image prompt; no longer read by the builder. Mirrored to `prautoblogger_image_style_suffix_deprecated` for one cycle and not deleted yet |
| `prautoblogger_image_style_suffix` | Text appended to every image prompt (default: CEO-locked 90s infomercial prompt) |
| `prautoblogger_openrouter_model_registry` | Normalized OpenRouter model list (JSON array, daily refresh, serves as durable cache) |
| `prautoblogger_openrouter_model_registry_fetched_at` | Unix timestamp of last successful model registry refresh |
| `prautoblogger_image_compose_enabled` | Toggle: run the deterministic image composer (default '1'; auto-degrades, never blocks publishing) |
| `prautoblogger_image_compose_variants` | Comma list of composed variants for Image A (default 'og,square'; whitelisted at point of use) |
| `prautoblogger_image_featured_mark_enabled` | Toggle: subtle corner mark on featured images (default '1') |
| `prautoblogger_image_compose_capability` | Cached capability probe `{fingerprint, capability}`; fingerprint = PHP version + imagick/gd presence, so it auto-invalidates on host changes |
| `prautoblogger_board_poll_interval` | Kanban board poll interval in seconds (default 5, min 3). Localized into board.js. |
| `prautoblogger_board_published_window_days` | Days back to show in the Published column (default 7). |
### Post Meta
@@ -687,15 +464,6 @@ Stored on every PRAutoBlogger-generated post:
| `_prautoblogger_editor_notes` | Chief editor's review notes |
| `_prautoblogger_generated_at` | ISO 8601 timestamp of generation |
| `_prautoblogger_research_sources` | JSON array of source URLs used |
| `_prautoblogger_idea_hash` | v0.18.0 — stable hash of the idea (title|topic); with `_prautoblogger_run_id` forms the post-creation idempotency key |
| `_prautoblogger_og_image_id` | Attachment ID of the composed 1200×630 OG variant (v0.17.0; the rebuilt SEO stage emits `og:image` from this — key name frozen) |
| `_prautoblogger_square_image_id` | Attachment ID of the composed 1080×1080 square variant (v0.17.0; stored now, no consumer yet) |
Composed-variant **attachment** meta (v0.17.0): every pipeline attachment gets
`_prautoblogger_image_role` (`featured`/`og`/`square`); OG/square variants also
get `_prautoblogger_base_attachment_id` pointing at the featured attachment
they derive from. All keys keep the `_prautoblogger_` prefix, so the uninstall
prefix-sweep purges them.
---
@@ -708,7 +476,7 @@ prefix-sweep purges them.
| Reddit RSS | Primary Reddit data source — Atom feeds for subreddit hot posts | None (unauthenticated) | No known rate limit; reliable from datacenter IPs | `providers/class-reddit-json-client.php` |
| Reddit .json | Fallback for posts + only source for comments | None (unauthenticated) | ~10 req/min (datacenter IPs often blocked) | `providers/class-reddit-json-client.php` |
| Google Analytics 4 | Post performance metrics | OAuth2 service account | Standard GA4 limits | `core/class-ga4-client.php`, `core/class-metrics-collector.php` |
| Runware (FLUX.1 via runware.ai) | **Default** image backend (v0.9.0+): schnell ~$0.0006/image, dev ~$0.02/image. True parallel generation via curl_multi. **v0.15.0: live model catalog sync** from `/v1/models` endpoint (task-based API); normalized to Image_Model_Registry shape; cached with 24h TTL; on-demand refresh via AJAX. | API key (encrypted in wp_options) | Account-level quotas | `providers/class-runware-image-provider.php`, `providers/class-runware-image-pricing.php`, `providers/class-runware-image-support.php`, `providers/class-runware-image-batch.php`, `providers/class-runware-model-catalog.php` |
| Runware (FLUX.1 via runware.ai) | **Default** image backend (v0.9.0+): schnell ~$0.0006/image, dev ~$0.02/image. True parallel generation via curl_multi. | API key (encrypted in wp_options) | Account-level quotas | `providers/class-runware-image-provider.php`, `providers/class-runware-image-pricing.php`, `providers/class-runware-image-support.php`, `providers/class-runware-image-batch.php` |
---
@@ -807,52 +575,6 @@ Reddit rejected our OAuth API application (April 2026). We initially switched to
The admin model picker (v1) needs to list OpenRouter models with pricing and capabilities. We fetch `https://openrouter.ai/api/v1/models` (free, unauthenticated) once daily and store the normalized payload in a WP option fronted by a 24h transient. On stale-and-fetch-fails, we serve last-good + surface a warning. The registry class (`class-open-router-model-registry.php`) takes all config via constructor (option name, transient name, endpoint URL) — no PRAUTOBLOGGER_* constants inside the class body. Phase 2 lifts it into a shared Composer package with zero internal edits. Phase 3 adds a parallel `Cloudflare_WorkersAI_Model_Registry` behind the same interface. Capability vocabulary: `text→text`, `text+image→text`, `text+audio→text`, `text→image`, `text→audio`, `text→video`, `text→embedding`. Cost: $0/month.
### #20: Editorial illustration prompt + style-template setting (v0.16.0, May 2026)
Commit 1 of the in-plugin editorial image pipeline (brief `docs/proposals/2026-05-29-image-pipeline-in-plugin-brief.md`). The image style pivots from a single-panel newspaper comic to a **text-free editorial scientific illustration**. Two changes ship here; the deterministic PHP composer is a later commit.
1. **Prompt structure.** `Image_Prompt_Builder::REWRITER_SYSTEM_PROMPT` now asks the rewriter LLM for a concise 1-2 sentence topic/mechanism summary (one concrete centered focal subject, no text/people-as-gag/logos) as the SCENE, keeping the short CAPTION line for the unchanged HTML-caption-below-image path. The scene/caption parsing contract (`Image_Scene_Parser`) is unchanged.
2. **Template substitution.** The old `trim($scene . ' ' . $style_suffix)` concat is replaced by `PRAutoBlogger_Image_Template_Filler::fill($scene)` in all three entry points (`build_article_prompt`, `build_source_prompt`, `build_fallback_prompt`). The filler resolves the active template (admin override → default), strips control chars and clamps the summary length (brief A5), then substitutes the single `{{ topic_summary }}` token. Degradation (brief A5/A6): if the template lacks exactly one token it appends the summary and logs a warning; if the summary is empty it emits the style-only prompt — a blank or token-only prompt is never sent to the provider.
3. **Setting.** New textarea `prautoblogger_image_style_template` (default `PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE`) replaces the Style Suffix field. On save it is sanitised with `sanitize_textarea_field` and validated to contain exactly one token (`Image_Template_Filler::sanitize_for_save`). The old `prautoblogger_image_style_suffix` is mirrored to `..._deprecated` for one cycle and not deleted (one-time migration `prautoblogger_migrated_style_template_v0160`).
Provider/model are unchanged — only the prompt text changes, so production keeps emitting via Runware FLUX.1 schnell but now produces text-free editorial base images.
### #21: Deterministic PHP image composer with capability ladder (v0.17.0, Jun 2026)
Commit 2 (and final scope) of the in-plugin editorial image pipeline (#20). Small diffusion
models cannot render clean text (2026-04-21 A/B finding), so base images are text-free —
but the one image that travels *without* its HTML caption is the social/OG share image.
A **deterministic local composer** (`PRAutoBlogger_Image_Composer` behind
`PRAutoBlogger_Image_Composer_Interface`) now runs between provider bytes and sideload:
1. **Variants.** Image A → corner-marked featured (1200×632) + branded OG (1200×630, teal
band, brand mark, baked caption in Poppins SemiBold) + square card (1080×1080: full base
downscaled into a 1080×569 top slice — no upscaling — cream caption panel in Poppins
Bold, teal footer with the horizontal reverse lockup). Image B → corner mark only. The
variant set is config-driven (`prautoblogger_image_compose_variants`, default `og,square`;
square has no consumer yet — CEO wants it rendered + stored now). Variants are
meta-linked via `_prautoblogger_image_role`, `_prautoblogger_base_attachment_id`,
`_prautoblogger_og_image_id`, `_prautoblogger_square_image_id`. The og key is **frozen**:
the rebuilt SEO stage (pipeline-redesign §4.8) emits `og:image` from it.
2. **Capability ladder, never fatal.** Imagick is probed once (PNG format + TTF annotate
smoke test) and cached in `prautoblogger_image_compose_capability`, fingerprinted by
PHP version + imagick/gd presence so host flips (hPanel/cagefs — it has happened)
auto-invalidate the cache. Rungs: imagick → `wp_get_image_editor()` resize-only
(unbranded, square skipped because it would upscale) → pass-through. Every render is
try/caught; degradation logs one WARNING per run; the publish always proceeds with the
editable HTML caption intact. Test/ops override: `prautoblogger_image_compose_capability`
filter.
3. **Determinism.** Bundled OFL fonts (no system-font queries), vendored brand PNGs (no
runtime SVG delegate variance), `stripImage()` + PNG date/time chunks excluded + fixed
compression → byte-stable output **per environment** (not across ImageMagick versions).
Composition is local CPU, $0, logged as a duration-only stage on the `image_composer`
channel — no cost-tracker rows.
4. **Layout tuning.** Geometry/opacity are constants in
`PRAutoBlogger_Image_Composer_Layout::defaults()` behind the
`prautoblogger_image_compose_layout` filter — deliberately not settings; promote only if
the CEO asks to tune them. The caption is hard-clamped (word-boundary wrap + ellipsis,
multibyte-safe) even though the rewriter LLM is already constrained to <15 words.
### #17: Runware as default image backend (v0.9.0, Apr 2026)
After a comic-style A/B round in Apr 2026, FLUX.1 schnell via Runware was chosen as the default image backend. Cost is ~$0.0006/image vs ~$0.039/image for Gemini 2.5 Flash Image via OpenRouter (≈65× cheaper), and the looser schnell fidelity reads as editorial-cartoon style — a feature, not a bug, for our single-panel comic aesthetic. FLUX.1 dev (~$0.02/image, 28 steps) remains available as an opt-in for higher-fidelity runs. The Runware layer mirrors the OpenRouter split (interface + provider + support + pricing + batch), all under the 300-line cap. The batch class dispatches `imageInference` POSTs via `curl_multi_init/exec/select` — wall-clock time for the A/B pair drops to ≈ the slowest single image. A v0.9.0 one-time migration (`prautoblogger_migrated_default_image_v090`) flips sites still on the legacy default; explicit user selections are preserved. Cloudflare Workers AI was removed as an image provider in v0.10.0 (see ADR #16 note below).
@@ -866,212 +588,11 @@ We already use Cloudflare for DNS/CDN on peptiderepo.com, so layering AI Gateway
---
### #22: Pipeline v2 Phase 1 substrate (v0.18.0, db 1.2.0, June 2026)
Phase 1 of the CEO-approved pipeline rebuild (plan of record:
`convo/cpo/threads/2026-06-prautoblogger-pipeline-redesign/03-cto-revised-brief.md`), built
**on the current pipeline with no behavior change** to the Economy (single-pass) and
multi-step publish paths. Four subsystems:
1. **Versioned prompt registry** (`prautoblogger_prompts`). All pipeline prompt copy
(content/analysis/editor/research + the illustration rewriter prompt and the image Style
Template) lives as immutable versioned rows; the hardcoded v0.16.0 texts are seeded as v1
and remain the in-code fallback, so a missing/empty table can never fatal — call sites
render through `PRAutoBlogger_Prompt_Registry` and fall back to the same constants the
seed used (byte-identical output). A run pins the active version of every key at start
(`runs.pinned_prompts_json`) and every generation_log row is stamped with the pinned
`prompt_version`. The image-composer PR **consumes** the `image.*` keys — it must not
grow its own prompt storage. No admin UI in Phase 1; the API supports list/activate/
create-version (never mutate) for the Phase-2 Prompts screen.
2. **Additive audit schema.** `agent_role` + `prompt_version` columns on generation_log;
`run_sources` + `run_decisions` child tables; `PRAutoBlogger_Stage_Display_Map` renders
historical + image + v2 stage values. `request_json` (and stage output payloads in
`run_stages.meta_json`) are nulled after R days — R from the
`prautoblogger_request_json_retention_days` setting (default 14), pruned on the existing
daily reaper cron.
3. **Per-run cost governor** (`PRAutoBlogger_Cost_Governor`). Reserve-before-call against the
per-run ledger row using a single conditional UPDATE (the #10 atomic-write discipline);
estimates come from the #18 pricing chain; `curl_multi` image batches reserve their summed
estimate before dispatch; reservations settle to actuals after each response. Breach →
run `halted`, overage recorded, un-dispatched work aborted, surfaced on the Review Queue.
Ceiling = `prautoblogger_per_run_cost_ceiling_usd` setting (default $0.50, 0 = disabled).
The monthly `Cost_Tracker` cap and the Cloudflare AI Gateway (#15) path are unchanged.
4. **Run state machine + idempotency** (`PRAutoBlogger_Run_State`). Per-run per-stage state
(pending/running/done/failed/halted) keyed `run_id + stage + agent_role + item_key`
(item_key scopes article-level stages because one run_id spans all N articles of a batch);
done stages persist output and are reused on re-entry, never re-charged; post creation is
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)
marks runs stuck `running` > 2× expected stage wall-clock as `failed`; such runs render
as **"incomplete"** in audit queries. Quorum logic (multiple roles per stage) itself is Phase 2. In Phase 1,
`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)
Tests use Brain\Monkey for WordPress function mocking (no database required). The BaseTestCase singleton handles setup/teardown of Monkey stubs and provides fixture helpers for common data shapes (SourceData, ArticleIdea, GenerationLog, etc.). All WordPress functions used by the plugin are stubbed in BaseTestCase::setUp() so individual test classes only override what they need. In v0.10.1, missing stubs for `post_type_exists()` were added to support PeptideLinker's PR-Core guards. All 1,362 WordPress-Core coding-standards violations (short array syntax, line length, spacing) were auto-fixed via phpcbf and the CI gate was flipped to strict mode — PHPCS failures now block CI. This prevents future regressions on the code style front.
### #22b: Kanban board as primary admin landing screen (v0.19.0 / v0.19.1)
**Hidden admin page convention (v0.19.3):** See CONVENTIONS.md §Hidden Admin Pages for the full rule. Summary: hidden admin pages (link-accessed only, not visible in nav) MUST use `options.php` as the `add_submenu_page()` parent. NEVER unset/remove registered pages from `$submenu` after registration -- doing so causes `get_admin_page_parent()` to fail at request time, which makes WP recompute the hookname in the `admin_page_*` orphan namespace, find no registered handler, and call `wp_die(403)`. This is the dossier 403 incident (v0.19.2→v0.19.3). Same hookname-mismatch class as the board 404 (v0.19.0→v0.19.1); the only difference is that the board bug was a priority-ordering issue at registration time while the dossier bug was a post-registration $submenu mutation.
The primary admin screen is now a kanban board (Direction C "Editorial Record") with four
columns: Generating | In Review | Published | Failed. A separate `class-board-page.php`
registers the `Board` submenu and a `$submenu` reorder makes it the first (primary) entry.
`class-board-data-provider.php` orchestrates the four columns and handles WP_Query columns
(In Review, Published). Raw `prab_generation_log` queries (Generating, Failed) are in the
extracted `class-board-gen-log-query.php` (split for 300-line compliance) -- no new schema
required for M1. The data provider uses the `prautoblogger_generation_status` transient
(written by the Executor for manual/daily runs) as the primary active-run signal, with a
secondary query on recent `prab_generation_log` run_ids that have no linked post as a
fallback. M2 will rename Runs & Audit -> Articles and wire board cards to the Article Dossier.
Poll interval and published window are settings-backed, localized into board.js, never
hardcoded.
**Menu-ordering constraint (v0.19.1 hotfix):** `PRAutoBlogger_Board_Page::on_register_menu`
MUST be hooked at `admin_menu` priority 11 (or higher), AFTER
`PRAutoBlogger_Admin_Page::on_register_menu` which runs at priority 10. Reason: WordPress
computes the page hookname via `get_plugin_page_hookname()` at `add_submenu_page()` call
time. If `add_menu_page()` has not yet run, `$admin_page_hooks['prautoblogger-settings']`
is unset and WordPress falls back to the `admin_page_*` hookname. At HTTP request time WP
recomputes the hookname as `prautoblogger_page_prautoblogger-board` and finds no registered
callback -> `wp_die("Invalid plugin page")` 404. The enqueue-gate in `on_enqueue_assets()`
checks `prautoblogger_page_prautoblogger-board` and would similarly never fire with the
wrong hookname (board.css/board.js would silently not load). Regression test:
`tests/unit/Admin/BoardMenuRegistrationTest.php`.
### #23: Article Dossier page — per-article inspection (v0.19.2)
The dossier is a read-only per-article admin page that exposes the full substrate view for
a single post: generation run, stage I/O, cost receipts, raw-trace toggles, editorial
decisions, and image A/B pairs. It is link-accessed only (hidden submenu) — no navigation
entry appears in the WP sidebar.
**Page registration** (`class-dossier-page.php`): uses the canonical hidden-admin-page
pattern -- registered under parent **`options.php`** at `admin_menu` priority **12**. The
hookname is `admin_page_prautoblogger-dossier` at BOTH registration time and request time,
so there is no hookname mismatch and no need to manipulate `$submenu`. The page does not
appear in the WP admin sidebar (options.php-parent pages are hidden by construction).
URL shape: `admin.php?page=prautoblogger-dossier&post_id=<int>` (unchanged from v0.19.2 --
deep-link URLs are parent-agnostic). Secured by `manage_options` capability. Static
`url_for_post(int $post_id): string` provides the canonical deep-link.
v0.19.2 used `prautoblogger-settings` as parent with post-registration `unset($submenu[...])` to
hide the page. This caused `get_admin_page_parent()` to fail at request time -> orphan
`admin_page_*` hookname -> no handler registered -> `wp_die(403)`. Fixed in v0.19.3 by switching
to `options.php` parent and removing all `$submenu` mutation. See CONVENTIONS.md §Hidden Admin
Pages for the full rule and ARCHITECTURE.md §22b for both incident records.
Regression test: `tests/unit/Admin/DossierMenuRegistrationTest.php` -- the
`test_request_time_hookname_matches_registration_hookname` test replicates the request-time
resolution algorithm (simulate `get_admin_page_parent()`) so it FAILS on hide-by-unset and
PASSES on options.php-parent.
**5-query data assembly** (`class-dossier-data-assembler.php`):
```
1. wp_prautoblogger_runs WHERE run_id = %s -- 1 row (run metadata)
2. wp_prautoblogger_run_stages WHERE run_id = %s -- N rows (per-stage status/cost)
3. wp_prautoblogger_generation_log WHERE run_id = %s -- N rows (model/pv/tokens/request)
4. wp_prautoblogger_run_decisions WHERE run_id = %s -- N rows (editorial rationale)
5. get_post_meta($post_id) -- WP object cache hit
```
All queries are keyed on `run_id` (indexed). No N+1. Stage output is reconstructed from
`run_stages.meta_json → json_decode → meta['output']` (same path as `Run_Stage_State::
get_output()`). The dossier assembler does NOT call `Run_Stage_State` directly; it performs
its own raw queries so the view is not coupled to the cache layer.
**Legacy graceful state (binding 5):** Posts published before v0.18.0 (no runs/run_stages
rows) and posts where `_prautoblogger_run_id` is absent or blank return `['has_run' => false]`.
The template renders a clean "No generation record for this article" notice. No PHP notices
or fatals.
**Amortized research rows:** `generation_log` rows with `prompt_version = NULL` and
`agent_role = ''` (from the `llm_research` stage orphan-reaper path) are rendered with
model shown as "—" and no raw-trace toggle (request_json may be NULL). No fatal/notice.
**Raw-trace security (binding 4):** `request_json` stores the OpenRouter request body —
model identifier, messages array, temperature. Authorization headers are never logged (the
outbound HTTP client strips them before logging, per the original architecture decision on
`wp_prautoblogger_generation_log`). The dossier template renders `request_json` via
`esc_html()` inside a `<pre>` block. All model-generated text rendered via `wp_kses_post()`
(rendered view) or `esc_html()` (raw trace). Both paths treat content as untrusted HTML.
**File naming note:** `PRAutoBlogger_DB_Migrations` is loaded via explicit `require_once`
in `prautoblogger.php` (not the autoloader). The autoloader converts `DB_Migrations` to the
kebab segment `d-b-migrations`, producing `class-d-b-migrations.php` — which does not match
the file `class-db-migrations.php`. Explicit loading is the canonical pattern for classes
whose names do not round-trip cleanly through the kebab converter. `class-prautoblogger.php`
uses the same pattern (also explicitly required in `prautoblogger.php`).
### #24: Edit + single-step re-run under CPO guardrails (v0.20.0, db 1.3.0, June 2026)
Phase 2 admin M3 (design contract: cpo seq 8 Proposal C + the five guardrails of the
edit+rerun delta ruling; decision `2026-06-12-admin-redesign-direction-c.md`).
**B1 — request_json persistence.** The OpenRouter provider stashes every outgoing chat
request BODY in the process-scoped `PRAutoBlogger_Request_Recorder` (the Run_Context
pattern) right after `build_body()`; `Cost_Tracker::log_api_call()` consumes it into
`generation_log.request_json`. Consume-once + overwrite-on-record means a stale body can
never attach to an unrelated row; recording happens pre-dispatch so error rows carry the
request too. Authorization can never be recorded: headers are built separately
(`build_headers()`) and `build_body()` copies only whitelisted option keys. Retention
rides the existing `prautoblogger_request_json_retention_days` prune unchanged.
**Two re-run primitives, both chained-cron (never synchronous):** the dossier AJAX layer
(`Dossier_Actions`) only validates + queues; the cron handlers (`Rerun_Executor`)
re-validate eligibility UNDER the generation lock before mutating anything.
1. **Replay** — one governed chat call from the latest edited input fork
(`stage_inputs`, INSERT-only versions). `Stage_Replay::options_from_body()` is the
exact inverse of `build_body()`+`apply_reasoning_budget()` (reasoning headroom
subtracted back out; reasoning pinned explicitly so global-setting drift cannot
reshape a replay). The call goes through `send_chat_completion`, so the cost
governor reserves against the SAME run ledger row (guardrail 4), with the normal
retry/empty-completion machinery. Output lands in the stage's run_stages snapshot —
the same place downstream rebuilds read from.
2. **Rebuild ("re-run from here")** — demotes the target + downstream chain stages to
`pending` and re-enters `Article_Worker` with the idea reconstructed from the stored
seed (`stage_inputs`, source='seed', persisted at worker start because re-deriving
the idea from post fields could break the item_key hash and duplicate a post).
Upstream done stages are reused (never re-charged); demoted stages rebuild their
prompts from CURRENT upstream snapshots — this is how an edit propagates downstream.
**Stale is a column, not a status.** A stale stage stays `done`, so
resume-without-recharge logic can never silently re-run it — guardrail 3 (no silent
auto-rerun; each downstream re-run is a deliberate operator action) holds by
construction. Only `Run_Stage_Writes::done()` clears `stale`; only
`Run_Stage_Rerun_State` (operator-action paths) may demote a done row. `human_modified`
is sticky for the life of the run (set when a fork enters execution, surfaced as header/
stage chips in the dossier, a board-card chip, and a Review Queue link-chip — the
run-list-level visibility the product AC requires).
**Run reopening.** `Run_State::reopen()` is the atomic terminal→running gate for re-run
spend; it RE-SNAPSHOTS `ceiling_usd` from the current setting (a deliberate re-run
adopts the operator's current per-run policy, exactly like a new run) and never resets
reserved/settled — re-runs are new spend on the same run. Handlers always restore a
terminal status (or record failed/halted) so the run-reaper's stuck-running sweep stays
meaningful; jobs hold the global generation lock and ride the M1 status transient, so
board/dossier polling shows queued → pickup → result and the existing R2/R3 orphan
recovery covers dead re-run processes unchanged.
**Eligibility (guardrail 5).** Posts with status publish/future/private freeze their
run server-side (and `Publisher` refuses to touch them: re-run output refreshes only
UNPUBLISHED posts, preserving their status — re-runs never publish). Editable stages
are the item-scoped writer chat stages (outline/draft/polish); review/publish re-run
via rebuild (their inputs are derived), run-level and image stages are excluded with
visible in-UI reasons. Phase-2b stages inherit the mechanism when they exist as
item-scoped chat calls.
**F2/F3 (QA M2):** the sidebar consolidates per-stage model/pv/role; image (and other
log-only) stages render from generation_log + the `_prautoblogger_image_role`
attachment set — wiring the dossier to real data was deliberately chosen over teaching
the live image pipeline to write run_stages (that belongs to the Phase-2b restructure).
## Cross-System LLM Budget Coordination
PRAutoBlogger and Peptide News both call OpenRouter and may share a single API key / billing account. Their combined spend should be considered when setting per-plugin budgets.

View File

@@ -5,470 +5,6 @@ All notable changes to PRAutoBlogger will be documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project uses [Semantic Versioning](https://semver.org/).
## [0.20.0] - 2026-06-12
### Added
- **Edit + single-step re-run (Phase 2 admin M3)** under the five CPO guardrails
(cpo seq 8, hard AC). From the Article Dossier, eligible stages can have their
input edited and re-run as QUEUED background jobs (chained-cron — the UI never
implies synchronous execution; board + dossier polling shows queued → pickup →
result).
- **Immutable input versions (guardrail 1).** Edits fork into the new INSERT-only
`prautoblogger_stage_inputs` table (monotonic versions per stage scope); the
executed original in `generation_log.request_json` is never overwritten. The
editor locks message structure (count/roles) so every fork stays replayable.
- **Visible human-modified audit (guardrail 2).** `run_stages.human_modified` +
`run_decisions.human_modified` set when an edited fork enters execution (sticky,
never cleared); surfaced as dossier header + stage chips, a board-card chip, and
decisions recorded while rebuilding a human-modified item are flagged too.
- **Explicit downstream invalidation (guardrail 3).** Re-running a stage marks all
downstream chain stages `stale` (new column — rows STAY 'done', so the resume
machinery can never silently auto-re-run them). Stale chips render per stage, in
the dossier header, and as a Review Queue warning chip linking to the dossier
(stale state visible at publish). Downstream re-runs are deliberate: per-stage
"Re-run from here" rebuilds the target + downstream from current upstream
snapshots via the existing worker resume path.
- **Cost governor applies to re-runs (guardrail 4).** Replays go through the normal
provider seam: reserve-before-call against the SAME run ledger row.
`Run_State::reopen()` re-snapshots the ceiling from the current setting and never
resets accumulated spend. The dossier shows a Run Spend card + per-panel spend
strip and warns when committed spend reaches the ceiling fraction (filterable,
`prautoblogger_rerun_ceiling_warn_fraction`, default 0.8).
- **Published posts are frozen (guardrail 5).** publish/future/private lock the run
server-side (not just hidden UI); `Publisher` refreshes re-run output onto
UNPUBLISHED posts only, preserving their status — a re-run never publishes.
- **B1 — `request_json` persisted on every chat LLM call** (QA M2 F1). The provider
records the outgoing request BODY pre-dispatch (process-scoped recorder, consume-once);
`log_api_call()` writes it to the row. Authorization headers can never be recorded
(built separately; body keys whitelisted — covered by tests). Retention rides the
existing `prautoblogger_request_json_retention_days` prune; the dossier raw-trace
"Request payload" section now renders for new runs.
- **Idea seeds.** `Article_Worker` persists the exact `Article_Idea` payload once per
item (stage_inputs, source='seed') so re-run-from-here reconstructs the precise idea
(re-deriving from post fields could break the item-key hash and duplicate a post).
- **Dossier sidebar consolidation (QA M2 F2).** New "Models & Prompts" card: per-stage
model + prompt version + agent role at a glance, plus the "Run Spend" card.
- **Image sections wired to real data (QA M2 F3).** image_a/image_b (and every
log-only stage: llm_research, image_prompt_rewrite, …) now render from their actual
generation_log rows, with the post's pipeline attachments (featured/og/square via
`_prautoblogger_image_role`) shown as an image grid — chosen/featured highlighted.
- **Schema (db 1.3.0).** `run_stages` + `human_modified`/`stale`; `run_decisions` +
`human_modified`; new `stage_inputs` table. dbDelta-idempotent via the standard
self-healing migration path (admin_init + cron init); half-migrated sites degrade
gracefully (done() retries the legacy statement; M3 features no-op until migrated).
Uninstall drops the new table and clears the two new cron hooks.
### Changed
- **`PRAutoBlogger_Run_Stage_State` split** (300-line cap, M2 pattern): pipeline write
bodies moved verbatim to `Run_Stage_Writes` (public API unchanged via thin proxies);
operator-action mutations (restart / mark_stale / demote_to_pending) isolated in
`Run_Stage_Rerun_State` — the ONLY code allowed to demote a done row. `done()` now
clears `stale` on fresh output.
- **Dossier is item-scoped** (M2 correctness fix): stage rows filter to THIS post's
item (idea-hash meta), and gen_log rows linked to OTHER posts of a multi-article run
are excluded (unlinked run-level rows are kept).
- **`Publisher` idempotency short-circuit** now refreshes existing UNPUBLISHED posts
with re-run content (title/content/verdict meta; status untouched) instead of
silently discarding regenerated output. Published posts remain untouched.
- Review Queue rows show a stale-stages warning chip linking to the dossier; board
cards show a "Human-modified" chip (single batched query, no N+1).
### Fixed
- Dossier "Request payload" raw trace was always empty (request_json never populated —
QA M2 F1); image sections always rendered the absent state (QA M2 F3).
## [0.19.4] - 2026-06-12
### Added
- **GD-rung unit tests.** New `ImageComposerEditorTest.php` (7 tests) covering
`PRAutoBlogger_Image_Composer_Editor`: `wp_get_image_editor` WP_Error, resize WP_Error,
upscale-guard size mismatch, save WP_Error, zero-width target geometry guard, missing-role
guard, and successful OG resize happy path. Orchestrator ladder test
`test_gd_rung_emits_passthrough_featured_and_single_warning` added to `ImageComposerTest.php`,
asserting the Imagick renderer is never called on the `gd` rung and pass-through featured is
always first.
(Source: QA verdict `Peptide Repo CTO/qa-reviews/prautoblogger/2026-06-11-6f76df1.md` P2-1.)
### Fixed
- **Dead layout keys removed.** `caption_margin_right` (og) and `caption_side_padding` (square)
were defined in `Layout::defaults()` and exposed via the `prautoblogger_image_compose_layout`
filter but never consumed by the Imagick renderer. The og renderer positions text from
`logo_x + logo_w + caption_gap` (left-anchor); the square renderer uses centered `x` alignment.
Right-edge overflow is enforced via `caption_chars_per_line` on both variants. Keys removed;
filter users tuning these values had no effect and received no error.
(Source: QA verdict `Peptide Repo CTO/qa-reviews/prautoblogger/2026-06-11-6f76df1.md` P3-3.)
- **Amortized research row now carries audit fields.** `Post_Assembler::amortize_research_costs()`
previously inserted per-article `llm_research` copies without `prompt_version` or `agent_role`,
leaving those columns NULL/empty while the original (correctly stamped) row was deleted.
SELECT now includes both columns; INSERT carries them forward from the original row.
(Source: phase-1 thread seq 49, seq 50 carried-list: "amortized llm_research rows pv=null/role
empty" — `convo/prautoblogger/threads/2026-06-pipeline-v2-phase1/`.)
- **`fetch_page()` error body included in exception.** Non-200 responses from the Runware
modelSearch API now include up to 200 chars of the response body in the `RuntimeException`
message, making diagnosis from logs actionable without re-reproducing the request.
(Source: phase-1 thread seq 50 carried-list: "`fetch_page()` error-body logging".)
### Notes
- cto-review.yml isinstance guard (handoff item 5): the fix (`c.get("severity", "UNKNOWN")`)
is already applied at HEAD (line 454 of the workflow). No changes made.
## [0.19.3] - 2026-06-12
### Fixed
- **Dossier page 403 (P0 hotfix).** `PRAutoBlogger_Dossier_Page::on_register_menu` registered the
dossier as a hidden submenu under `prautoblogger-settings` then called `unset($submenu[...])` to
hide it from the nav. This is the **hide-by-unset anti-pattern**: at registration time WP records
the render callback under hookname `prautoblogger_page_prautoblogger-dossier`; at request time
`get_admin_page_parent()` scans `$submenu`, finds the slug absent (it was unset), returns false,
and WP recomputes the hookname under the orphan `admin_page_*` namespace -- no handler registered
there -- `wp_die(403)`. Same hookname-mismatch class as the board 404 (v0.19.1), different vector.
**Fix:** register under parent `options.php` (canonical hidden-page pattern). Hookname is
`admin_page_prautoblogger-dossier` at both registration and request time. No `$submenu` mutation
required or permitted. Asset enqueue gate updated to match (`admin_page_*` prefix).
Deep-link URLs (`admin.php?page=prautoblogger-dossier&post_id=N`) are parent-agnostic and
unchanged. Board cards and the post metabox link continue to work without modification.
### Changed
- **Regression test upgraded to request-time faithful** (`DossierMenuRegistrationTest`).
New `test_request_time_hookname_matches_registration_hookname` simulates
`get_admin_page_parent()` against the post-registration `$submenu` state and asserts it
equals the registration-time hookname. FAILS on hide-by-unset (4 failures on v0.19.2 code,
captured in test evidence). PASSES on options.php-parent. New
`test_hide_by_unset_would_fail_request_time_check` documents the broken pattern inline.
- **CONVENTIONS.md §Hidden Admin Pages** added: options.php-parent is the only permitted
pattern for hidden admin pages; `$submenu` mutation after registration is explicitly
prohibited; full incident history (board 404 + dossier 403) and test methodology documented.
- **ARCHITECTURE.md §22b** updated with hidden-page convention cross-reference.
**§23** updated to reflect options.php-parent registration and the v0.19.2→v0.19.3 fix.
- **tests/bootstrap.php**: added `PRAUTOBLOGGER_PLUGIN_URL` and `PRAUTOBLOGGER_VERSION`
constants so admin enqueue tests resolve without "Undefined constant" errors.
## [0.19.2] - 2026-06-12
### Added
- **Article Dossier page (M2).** Per-article read-only inspection page at
`admin.php?page=prautoblogger-dossier&post_id=<id>`. Accessible via board card
deep-links and the slim post metabox link. Shows: header (title, verdict pill, tier,
status), sidebar (run metadata, per-stage cost receipt with model + prompt-version),
vertical stage sections (rendered output default, per-stage raw-trace toggle exposing
`generation_log` request JSON + tokens + cost + role), editorial decisions rationale,
image A/B pair sections.
- **Board card deep-links.** All Kanban cards now deep-link directly to the article
dossier page (`dossier_url` on card data; `click_action = dossier` in board JS).
- **Slim post metabox.** `PRAutoBlogger_Post_Metabox` now renders a single "View
generation dossier →" link (was a verbose generation-metadata dump).
- **Dossier CSS/JS.** `assets/css/dossier.css` (warm editorial palette, verdict pills,
cost receipt, raw-trace toggle) + `assets/js/dossier.js` (vanilla JS toggle,
`aria-expanded` / `aria-controls` accessible).
- **Menu registration test coverage.** `DossierMenuRegistrationTest.php` — asserts
dossier hook fires at priority > board (> parent), uses hidden-submenu pattern,
correct slug, and `url_for_post()` URL shape. Mirrors `BoardMenuRegistrationTest`.
- **Raw-trace credential check (binding 4).** `request_json` column contains only
OpenRouter request bodies (model, messages, temperature — no Authorization headers
per architecture). All model output escaped via `esc_html()` / `wp_kses_post()`;
treated as untrusted HTML throughout the render path.
- **Legacy graceful state (binding 5).** Posts with no run record (pre-v0.18.0) render
a clean "No generation record" notice — no notices, no fatals. Amortized research
rows (pv=null, role='') render model as "—" with no raw-trace toggle.
### Changed
- **`class-prautoblogger.php` → `class-db-migrations.php` split (binding 1).**
All DB-migration methods extracted byte-identically into new static class
`PRAutoBlogger_DB_Migrations` (`includes/class-db-migrations.php`, 129 lines).
`class-prautoblogger.php` shrinks from 407 → 258 lines; delegates via thin proxy.
Loaded via explicit `require_once` in `prautoblogger.php` (autoloader filename
collision avoidance — see ARCHITECTURE.md §File Naming Notes).
## [0.19.1] - 2026-06-12
### Fixed
- **Board admin submenu 404 (P0 hotfix).** `PRAutoBlogger_Board_Page::on_register_menu`
was hooked at `admin_menu` priority 10, identical to
`PRAutoBlogger_Admin_Page::on_register_menu`. Because the board hook was
registered first in `register_admin_hooks()`, `add_submenu_page()` fired while
`$admin_page_hooks['prautoblogger-settings']` was still unset. WordPress fell back
to the `admin_page_prautoblogger-board` hookname; at request time it recomputed
`prautoblogger_page_prautoblogger-board`, found no registered callback, and called
`wp_die()` with "Invalid plugin page". Board CSS/JS also never loaded (same
enqueue-gate mismatch). Fix: parent menu hook stays at priority 10; board submenu
hook moves to priority 11, guaranteeing `add_menu_page()` fires first. Board is
kept as the first submenu item via explicit `$submenu` reorder in
`PRAutoBlogger_Board_Page::on_register_menu()`.
- **Regression test added:** `tests/unit/Admin/BoardMenuRegistrationTest.php` —
three assertions covering priority relationship, execution order, and parent-slug
correctness. Includes a "documents the bug" test that fires the unfixed hook order
to prove the broken state.
## [0.19.0] - 2026-06-12
### Added
- **Kanban board dashboard (M1 — Phase 2 admin / Direction C).** New
`Board` submenu page is now the primary landing screen for the plugin.
Four columns — Generating | In Review | Published | Failed — with card
click-throughs: Generating/Failed → Activity Log; In Review → Review
Queue; Published → Post edit screen. (M2 will rewire all to the Article
Dossier.)
- **Live board polling.** AJAX action `prautoblogger_board_status` (nonce
`prautoblogger_board`) returns the full board snapshot every N seconds.
Poll interval backs off to 2× when no article is actively generating
and resets to base as soon as a generating card appears. All nonce and
capability checks enforced.
- **Two new settings** in Schedule & Budget: `prautoblogger_board_poll_interval`
(default 5s, min 3s) and `prautoblogger_board_published_window_days`
(default 7 days). Both localized into board.js — no hardcoded values.
- New files: `includes/admin/class-board-page.php`,
`includes/admin/class-board-data-provider.php`,
`templates/admin/board-page.php`, `assets/css/board.css`,
`assets/js/board.js`.
- PHPUnit behavioral tests: `tests/unit/Admin/BoardDataProviderTest.php`
(8 tests covering all column/state mappings) and
`tests/unit/Core/CostReporterSqlBugFixTest.php` (3 tests for the SQL
inline-comment fix).
### Fixed
- **Cost-reporter SQL inline-comment bug (P2).** `PRAutoBlogger_Cost_Reporter::get_daily_spend()`
and `get_spend_by_stage()` embedded PHP `// phpcs:ignore` annotations
inside SQL string literals, passing the comment text to MySQL. Moved
phpcs suppression annotations to standalone PHP line comments above the
`$wpdb->prepare()` call — matching the pattern already used in
`get_monthly_spend()`. No query behavior change; fixes malformed
prepared-statement strings visible in debug logging.
## [0.17.0] - 2026-06-11
### Added
- **Deterministic PHP image composer (Commit 2 of the in-plugin editorial image
pipeline).** Every generated image now passes through a local, $0,
deterministic composer between the provider's bytes and the media sideloader.
Image A yields a corner-marked featured image (1200×632) plus a branded
**OG/social variant** (1200×630, teal band, brand mark, baked editorial
caption in Poppins SemiBold) and a **square card variant** (1080×1080, image
slice + cream caption panel in Poppins Bold + teal footer with the horizontal
lockup). Image B gets the corner mark only. Variants are sideloaded with a
role filename suffix and meta-linked: attachment meta
`_prautoblogger_image_role` + `_prautoblogger_base_attachment_id`, post meta
`_prautoblogger_og_image_id` + `_prautoblogger_square_image_id` (the rebuilt
SEO stage will emit `og:image` from the frozen og key).
- **Capability ladder with cached probe.** Imagick (full compositing) →
`wp_get_image_editor()` GD path (resize-only, unbranded, single WARNING) →
pass-through (single WARNING). The probe result is cached in
`prautoblogger_image_compose_capability`, fingerprinted by PHP version +
imagick/gd presence so it auto-invalidates when the host changes. Override
filter: `prautoblogger_image_compose_capability`. Composition failure can
never block a publish (per-render try/catch + pipeline safety net).
- New Images settings: `prautoblogger_image_compose_enabled` (default on),
`prautoblogger_image_compose_variants` (default `og,square`),
`prautoblogger_image_featured_mark_enabled` (default on). Geometry ships as
layout-class constants behind the `prautoblogger_image_compose_layout`
filter. All keys keep the `prautoblogger_`/`_prautoblogger_` prefixes, so
the existing uninstall prefix-sweep purges them (no uninstall.php changes).
- Vendored brand rasters (`assets/brand/`, from peptide-repo-brand SVG masters)
and bundled OFL fonts (`assets/fonts/`: Poppins Bold + Poppins SemiBold +
OFL.txt) — no system-font or runtime-SVG dependency, byte-stable output per
environment (metadata stripped, PNG date/time chunks excluded).
### Fixed
- Featured/Image B **alt text is now the editorial caption** instead of the
generation model name (`sideload_and_log()` passed the model as `$alt_text`,
contradicting the sideloader docblock). The model keeps persisting in
`_prautoblogger_image_model`.
### Changed
- `PRAutoBlogger_Image_Media_Sideloader::sideload_image()` /
`generate_filename()` accept an optional filename role suffix
(back-compat default `''`).
- `PRAutoBlogger_Image_Pipeline` delegates sideload/cost-log, caption
prepending, and variant persistence to the new
`PRAutoBlogger_Image_Attacher` (300-line compliance); also declares the
previously-dynamic `$trace_context` property (PHP 8.2 deprecation).
## [0.16.0] - 2026-05-29
### Changed
- **Editorial image prompt (Commit 1 of the in-plugin editorial image pipeline).**
The image style pivots from a single-panel newspaper comic to a text-free
editorial scientific illustration. The rewriter LLM now emits a concise
1-2 sentence topic/mechanism summary as the SCENE (one centered focal
subject, no text/people-as-gag/logos), keeping the short CAPTION line for the
unchanged HTML-caption-below-image behavior. The scene/caption parsing
contract is unchanged. Provider/model are unchanged — production keeps
generating via Runware FLUX.1 schnell but now produces text-free editorial
base images. See `docs/proposals/2026-05-29-image-pipeline-in-plugin-brief.md`.
- The prompt builder now substitutes the rewriter scene into an editable style
template's `{{ topic_summary }}` slot via the new
`PRAutoBlogger_Image_Template_Filler`, replacing the old
`scene + style suffix` concatenation, across all three entry points
(`build_article_prompt`, `build_source_prompt`, `build_fallback_prompt`).
Before substitution the scene is stripped of control characters and
length-clamped (brief A5). If the template lacks exactly one token the
summary is appended and a warning logged; if the summary is empty the
style-only prompt is emitted — a blank or token-only prompt is never sent to
the provider (brief A5/A6).
### Added
- New setting **Style Template** (`prautoblogger_image_style_template`,
textarea) replacing the Style Suffix field. Default =
`PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE` (the editorial template). On save
it is validated to contain exactly one `{{ topic_summary }}` token; an invalid
template keeps the previous value and surfaces a settings error.
### Deprecated
- `prautoblogger_image_style_suffix` is deprecated and no longer read by the
prompt builder. A one-time migration (`prautoblogger_migrated_style_template_v0160`)
mirrors its value to `prautoblogger_image_style_suffix_deprecated` for one
version cycle and seeds the new template default. The old option is NOT
deleted this cycle.
## [0.15.1] - 2026-05-14
### Fixed
- Cost preview in AI Models settings tab no longer prints a WordPress database
error notice; query now uses canonical column names (`prompt_tokens`,
`completion_tokens`, `created_at`). Bug present since v0.11.0 (2026-04-23).
## [0.14.0] - 2026-04-26
## [0.15.0] - 2026-04-26
### Added
- **Live Runware Model Catalog Sync**: New `class-runware-model-catalog.php`
fetches the live Runware model list via their `/v1` endpoint (task-based API),
filters to `taskType=imageInference` (text-to-image only, excluding inpainting),
normalizes to the Image_Model_Registry shape, and caches in `prautoblogger_runware_model_cache`
with a 24-hour TTL. Fixes the pattern from v0.13.8 and v0.14.0 where the
hardcoded Runware model list was a maintenance burden and gaps (missing models,
wrong prices) went unnoticed until customer images generation broke.
- Daily WP-Cron sync (`prautoblogger_sync_runware_models`) scheduled on activation
and unscheduled on deactivation.
- On-demand "Sync now" AJAX button in PRAdmin (Images settings section) with
nonce protection and `manage_options` cap check. Refreshes model count and
last-synced timestamp in the UI without full page reload.
- Smart caching + fallback strategy: if cache is < 24h old, use it; if stale,
trigger a sync; if sync fails, use the last-known-good cache; if no cache,
fall back to hardcoded list (never returns empty array).
- Pricing merge: Runware API may not expose per-image cost. The catalog pulls
costs from `class-runware-image-pricing.php::COST_PER_IMAGE` on every sync,
ensuring pricing data is always authoritative and up-to-date.
- Unit tests for `PRAutoBlogger_Runware_Model_Catalog`: sync success/failure,
fallback on API unreachable, stale cache behavior, cost merge logic.
- `class-image-model-registry.php` refactored: `get_models()` now delegates to
the catalog for Runware models + static OpenRouter list. Extracted fallback
lists into private `get_runware_fallback_models()` and `get_openrouter_models()`
for clarity.
### Fixed
- Silent model list gaps no longer possible: Runware no longer depends on manual
model list maintenance in the pricing class. The live catalog is the source of
truth; pricing is merged in on every sync.
### Changed
- `class-image-model-registry.php`: `get_models()` is now a thin wrapper around
the catalog + OpenRouter static list. Breaking change: callers that expect a
specific static list should note the new dynamic Runware side.
### Fixed
- Runware image generation now correctly uses the admin-selected model instead
of silently falling back to FLUX.1 schnell (runware:100@1) for all non-schnell
and non-dev selections. Root cause: `class-runware-image-pricing.php` only
had 2 models in its `COST_PER_IMAGE` whitelist (schnell + dev), but the
image model registry was expanded to 15 Runware models in v0.13.8 without a
matching update to the pricing class. Any model ID not in the whitelist caused
`resolve_model()` to fall back to schnell, so every Stable Diffusion, FLUX.2,
HiDream, TwinFlow, Z-Image, Qwen-Image, Krea, and GLM-Image selection was
silently downgraded.
- Added all 15 Runware model IDs to `COST_PER_IMAGE` and `DEFAULT_STEPS` with
correct per-image costs and step counts sourced from runware.ai/pricing (April 2026).
- Added `@see` cross-reference to `class-image-model-registry.php` in pricing
class docblock to prevent future drift.
## [0.13.9] - 2026-04-26
### Fixed
- Model picker sort by price now works correctly for image models — previously
\`applySort\` always read \`input_price_per_m\` (undefined on image models),
so every image had an effective price of 0 and price sort was a no-op.
Fix: detect image models via \`cost_per_image\` and use that field instead.
## [0.13.8] - 2026-04-26
### Added
- Image model picker expanded from 7 to 21 models
- New Runware text-to-image models: Stable Diffusion 3, HiDream-I1 Full/Dev/Fast,
FLUX.1 Krea [dev], Qwen-Image, FLUX.2 [dev], FLUX.2 [klein] 9B, FLUX.2 [klein] 4B,
GLM-Image, Z-Image, Z-Image-Turbo, TwinFlow Z-Image-Turbo
- New OpenRouter model: openai/gpt-5.4-image-2
- Registry now includes last-verified date and update instructions in source comment
All notable changes to PRAutoBlogger will be documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project uses [Semantic Versioning](https://semver.org/).
## [0.13.7] - 2026-04-24
### Fixed
- Posts list column layout: title was set to 35% which, combined with 3 fixed-width PRAB columns, left ~50px for every remaining column (Author, Categories, Tags, Date all word-wrapping). Replaced with a balanced budget: title 22%, author 6%, categories 7%, tags 9%, date 8%, PRAB columns 85/85/50px, Peptide Topics 75px.
## [0.13.6] - 2026-04-24
### Fixed
- Peptide Topics column still rendering vertically: WordPress posts table uses `table-layout: fixed` which ignores `min-width` entirely. Changed to explicit `width: 80px` which is respected under fixed-layout tables.
## [0.13.5] - 2026-04-24
### Fixed
- Cost column in Posts list was always showing $0.00: a PHP `// phpcs:ignore` comment was embedded inside the SQL string literal, causing a MariaDB syntax error on every query. Moved comment above the `prepare()` call.
- Peptide Topics column header in Posts list was being squeezed to near-zero width by the fixed-width PRAB columns. Added `min-width: 80px` to `.column-taxonomy-peptide_topic`.
## [0.13.4] - 2026-04-24
### Fixed
- Model picker price column now consistently right-aligned. Root cause: price and description were siblings inside .ab-mp-row-meta, with description first and variable-length — this shifted price left/right per row. Fix: moved price to last position with flex-shrink: 0 so its right edge is always pinned to the row edge; capped description at max-width 200px with ellipsis; swapped column headers to match new DOM order.
## [0.13.3] - 2026-04-24
### Fixed
- Price column header now right-aligned with `min-width: 90px` to match data cells — header and prices now track the same column edge.
## [0.13.2] - 2026-04-24
### Changed
- Model picker: added sortable column headers (Model, Price, Context); clicking a header sorts the list ascending/descending; active column highlighted with sort arrow; sort preference persists while the picker is open.
## [0.12.3] — 2026-04-24
## [0.13.1] - 2026-04-24
### Fixed
- Model picker price column now right-aligned with a minimum width so values like `$0.0006/image` and `$0.0800/image` stack cleanly instead of floating at uneven offsets.
## [0.13.0] - 2026-04-24
### Added
- **Wave 2 Eval Harness**: Complete evaluation framework for PRAutoBlogger output quality
- Frozen eval dataset (`eval/dataset.json`) with 20 curated peptide topics
- LLM-as-judge scorer (`class-opik-eval-scorer.php`) using Gemini Flash 1.5
- Eval runner orchestrator (`class-opik-eval-runner.php`) with Opik experiment support
- WP-CLI command: `wp prautoblogger opik:eval [--limit=<n>] [--dry-run]`
- Image pipeline instrumentation: Opik span wrapping for `image_prompt_rewrite` step
- **Image Prompt Builder Refactor**: Extracted scene/caption parsing into `PRAutoBlogger_Image_Scene_Parser`
- Three static methods: `parse_scene_and_caption()`, `extract_first_paragraph()`, `synthesize_visual_concepts_fallback()`
- Cleaner separation of concerns; builder now ~255 lines (was 331)
- **Content Generator Eval Mode**: Added `$eval_mode` parameter to suppress publishing and image generation side effects
- **Trace Context Integration**: Optional trace instrumentation in `PRAutoBlogger_Image_Prompt_Builder` constructor
### Changed
- `PRAutoBlogger_Image_Prompt_Builder` constructor now accepts optional `PRAutoBlogger_Opik_Trace_Context` parameter
- `PRAutoBlogger_Image_Pipeline` constructor passes trace context through to prompt builder
- Image prompt rewrite LLM calls now emit Opik spans when trace context is available
### Fixed
- Image prompt builder now properly delegates to static parser methods
### Fixed
- **Opik autoloader gap** — `class-autoloader.php` listed `services/` as a scan directory but not `services/opik/`, where all four Opik classes live (`Opik_Client`, `Opik_Trace_Context`, `Opik_Span_Queue`, `Opik_Dispatcher`). Composer's classmap (used in PHPUnit) covers `includes/` recursively so tests passed, but the WordPress runtime autoloader would fatal on first Opik class reference in production. Added `services/opik/` to the scan list.
## [0.12.2] — 2026-04-24
### Fixed
@@ -1147,7 +683,6 @@ swap with no user-visible change in article quality.
run_id-based log linking, RuntimeException on WP_Error, action/filter
hook firing. Replaces previous method-existence-only checks.
## [0.2.1] — 2026-04-12
### Changed
@@ -1184,6 +719,14 @@ swap with no user-visible change in article quality.
- Posts-per-subreddit limit (5–100) in Sources tab.
- LiteSpeed cache purge step in CI/CD deploy pipeline.
### Removed
- `class-reddit-api-client.php` — replaced by `class-reddit-json-client.php`.
- Reddit OAuth credential fields and encrypted storage entry.
### Fixed
- Deploy pipeline now purges LiteSpeed/OPcache after file extraction,
preventing stale PHP bytecode from being served.
## [0.1.0] — 2026-04-10
### Added

View File

@@ -150,38 +150,6 @@ interface PRAutoBlogger_Image_Provider_Interface {
---
## How To: Tune the Image Composer (v0.17.0+)
The deterministic composer (ARCHITECTURE.md #21) renders branded variants between
provider bytes and sideload. Three rules when touching it:
1. **Geometry lives in code, not settings.** All sizes/colors/opacities come from
`PRAutoBlogger_Image_Composer_Layout::defaults()` and can be overridden via the
`prautoblogger_image_compose_layout` filter:
```php
add_filter( 'prautoblogger_image_compose_layout', function ( array $layout ): array {
$layout['featured']['mark_opacity'] = 0.40;
return $layout;
} );
```
Promote a value to a settings field only on explicit CEO request.
2. **Keep renderer classes WP-free.** `Image_Composer_Imagick`, `Image_Composer_Canvas`,
and `Image_Composer_Layout` must not call WordPress functions — they are exercised by
a standalone render harness (and the determinism test) without a WP bootstrap. Only
the orchestrator (`Image_Composer`) and the GD rung (`Image_Composer_Editor`) may
touch WP APIs.
3. **Never fatal a publish.** Any new render path needs a try/catch that degrades to
pass-through and logs at most one WARNING per run (`warn_once()`). Capability checks
go through the cached probe (`prautoblogger_image_compose_capability` option +
same-named override filter) — never re-probe per image.
Adding a new variant role: extend `Layout::defaults()` + the renderer, whitelist the
role in `Image_Composer::configured_variants()` and in
`Image_Attacher::ROLE_POST_META` (new `_prautoblogger_{role}_image_id` post meta keeps
the uninstall prefix-sweep effective), then cover it in the unit ladder tests.
---
## How To: Add a New Admin Setting
1. Define the option key in the settings array in `admin/class-admin-page.php` → `get_settings_fields()` method
@@ -204,18 +172,13 @@ the uninstall prefix-sweep effective), then cover it in the unit ladder tests.
## How To: Add a New Pipeline Stage
Writing stages are methods on `Content_Generator` that delegate to its `execute_stage()`
helper (Opik span + LLM dispatch + cost log + run-stage state in one place).
The writing pipeline is an ordered array of stages. Each stage is a class method on `Content_Generator`.
1. Add the stage method to `class-content-generator.php` and call
`$this->execute_stage( $stage, $span_name, $user_prompt, $request, $model, $options )`
2. Wire it into `generate_multi_step()` (or the relevant mode path)
3. Add the stage to `PRAutoBlogger_Stage_Display_Map` (label, default agent role, prompt key)
and — if it has registry-managed copy — a prompt key in the defaults classes
4. Cost logging and per-run stage state (idempotent resume, output snapshot) come free from
`execute_stage()`; the per-run cost governor guards the call inside the provider
5. If a stage fails after retries, the entire pipeline fails (no partial publishes); the
stage row is failed by the worker's catch-all and the run is swept by Run_Reaper
1. Add the stage method to `class-content-generator.php`: `protected function stage_{name}(PRAutoBlogger_Content_Request $request): string`
2. Register the stage in the `get_pipeline_stages()` method for the appropriate mode (single_pass or multi_step)
3. Each stage receives the accumulated context and returns its output
4. Each stage logs its cost via `Cost_Tracker::log_api_call()`
5. If a stage fails after retries, the entire pipeline fails (no partial publishes)
---
@@ -325,38 +288,6 @@ The field renderer, AJAX refresh, model picker JS, and capability filtering are
Phase 3 will add provider selection; v0.11.0 is OpenRouter-only.
## How To: Change a Pipeline Prompt (v0.18.0+)
Prompt copy is **versioned data**, not code. The bodies live in
`wp_prautoblogger_prompts` (one ACTIVE version per key); the hardcoded texts in
`class-prompt-defaults.php` / `class-prompt-defaults-editorial.php` are the canonical v1 seed
AND the fallback when the table is unavailable — never edit a stored version in place.
1. **Never `UPDATE` a body.** Create a new version and activate it:
```php
$v = PRAutoBlogger_Prompt_Registry_Writer::create_version(
'content.polish', $new_body, $model, $params, 'your-name', true
);
```
2. **Keys** are dot-namespaced: `content.system`, `content.single_pass`, `content.outline`,
`content.draft`, `content.polish`, `analysis.system`, `analysis.user`, `editor.system`,
`editor.review`, `research.system`, `image.rewriter_system`, `image.style_template`.
The two `image.*` keys are the image-composer seam — coordinate on the convo thread
before touching them.
3. **Tokens** use the `{{ name }}` syntax (exactly one space each side — same convention as
the Style Template's `{{ topic_summary }}`). Token VALUES are computed by code
(`Content_Prompts`, `Analysis_Prompts`, `Chief_Editor`); a new prompt version may reorder
or drop tokens but must not invent new ones without adding the value at the call site.
4. **Pinning.** A run pins the active version of every key at start
(`runs.pinned_prompts_json`, written by `Cost_Tracker::set_run_id()`); every
generation_log row is stamped with the pinned `prompt_version`. Activating a new version
affects the NEXT run, never a run in flight.
5. **Call sites** render via `PRAutoBlogger_Prompt_Registry::render( $key, $tokens )` and
must keep working when the table is absent (the registry falls back to the defaults
automatically — do not add your own fallback).
6. If you add a key: define the body in the appropriate defaults class, add it to `defs()`,
map its stage in `Stage_Display_Map`, and it will seed on the next migration pass.
## Git Workflow — PR-Gated, Soft-Enforced
This repo is private on GitHub's free plan, which does not support branch protection or rulesets. The review gate is enforced at the agent layer, not server-side. Every agent and human contributor follows these rules; the `.github/workflows/main-push-audit.yml` tripwire opens an audit issue on any direct push to `main` that did not come from a merged PR.
@@ -502,73 +433,3 @@ public function my_operation( $input ) {
```
That's it. No config, no feature-flag checks, no try/catch needed.
---
## Hidden Admin Pages (v0.19.3 convention, codified after two incidents)
### Rule: use options.php as parent; NEVER unset/remove registered pages from $submenu
When a WordPress admin page must be accessible by URL but hidden from the nav menu, use the
**options.php-parent pattern** exclusively:
```php
add_submenu_page(
'options.php', // parent: built-in WP page; pages hidden by construction
__( 'My Page', 'prautoblogger' ), // page title
__( 'My Page', 'prautoblogger' ), // menu title (never shown; options.php is hidden)
'manage_options', // capability
'my-page-slug', // page slug
array( $this, 'render_page' ), // callback
);
// No $submenu manipulation. options.php-parent pages are hidden from nav by construction.
```
The resulting hookname is `admin_page_my-page-slug` at BOTH registration time and request time.
### Why the hide-by-unset pattern causes 403 (the incident class)
WordPress computes the page hookname at two distinct moments:
**Registration time** (inside `add_submenu_page`):
WP resolves the parent slug against `$admin_page_hooks`. If found, hookname = `{parent_key}_page_{slug}`. WP registers the render callback and `$_registered_pages` entry under that name.
**Request time** (inside `wp-admin/admin.php`):
WP calls `get_admin_page_parent()` which scans `$submenu` for the page slug. If found, it derives the hookname the same way as (1). If **not found** (e.g., because the entry was unset), it falls back to `admin_page_{slug}`.
When these two hooknames diverge, WP dispatches the request to a hookname with no registered callback → `wp_die(403)`.
**Why options.php avoids this:** `options.php` is a built-in page that WordPress always keeps intact in `$admin_page_hooks` and `$submenu`. For its children, `get_admin_page_parent()` returns `options.php` consistently at both moments, so both produce `admin_page_{slug}`. No mutation required.
### Incident history
| Version | Symptom | Root cause | Fix |
|---------|---------|------------|-----|
| v0.19.1 | Board page 404 | Board submenu registered at same priority as parent (both 10) — add_submenu_page fired before add_menu_page → wrong hookname at registration time | Board moved to priority 11, after parent at 10 |
| v0.19.3 | Dossier page 403 | Dossier registered under `prautoblogger-settings` parent (priority 12, after parent ✓) but post-registration `unset($submenu[...])` removed the slug → get_admin_page_parent() returned false at request time → orphan `admin_page_*` hookname → no handler → 403 | Switched to `options.php` parent; removed all $submenu mutation |
Both incidents are in the same **hookname-mismatch class**: registration-time hookname ≠ request-time hookname.
### Test pattern
The `DossierMenuRegistrationTest::test_request_time_hookname_matches_registration_hookname` test
replicates the request-time resolution algorithm (scan `$submenu` for the slug; if found derive
hookname; if absent return `admin_page_*`) and asserts it equals the registration-time hookname.
This test FAILS on hide-by-unset implementations and passes on the options.php-parent pattern.
Apply the same test strategy to any new hidden admin page.
### Asset enqueue gate
For `options.php`-parent pages, the hook suffix passed to `admin_enqueue_scripts` is
`admin_page_{slug}`. For plugin-parent pages it would be `{parent_key}_page_{slug}`. Always
match the asset enqueue gate to the actual hookname for the chosen parent pattern:
```php
// options.php parent → 'admin_page_{slug}'
public function on_enqueue_assets( string $hook_suffix ): void {
if ( $hook_suffix !== 'admin_page_' . self::PAGE_SLUG ) {
return;
}
// ... enqueue
}
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,249 +0,0 @@
/**
* PRAutoBlogger — Kanban Board Styles
*
* Warm editorial style (Proposal C / Direction C).
* Inside wp-admin chrome; uses WP admin vars where available.
* No build step — plain CSS, no preprocessor.
*
* Palette:
* Teal #1B8A92 (brand primary — Generating pill, spinner)
* Cream #FAF6EE (card background)
* Ink #0D0D0D (primary text)
* Orange #FF8A3D (In Review pill)
* Lime #7FD600 (Published pill — success)
* Red #D94F4F (Failed pill)
* Mid-grey #8A8A8A (meta text, border)
*
* @see templates/admin/board-page.php — Rendered HTML structure.
* @see assets/js/board.js — DOM updates that match these selectors.
*/
/* ── Page wrapper ──────────────────────────────────────────────────────── */
.prab-board-wrap {
padding: 0;
}
.prab-board-heading {
font-size: 1.4rem;
font-weight: 700;
color: #0d0d0d;
margin: 20px 0 18px 0;
padding: 0 20px;
display: flex;
align-items: baseline;
gap: 10px;
}
.prab-board-heading-sub {
font-size: 1rem;
font-weight: 400;
color: #8a8a8a;
}
/* ── Four-column board grid ────────────────────────────────────────────── */
.prab-board {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16px;
padding: 0 20px 24px;
align-items: start;
}
@media (max-width: 1200px) {
.prab-board {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 720px) {
.prab-board {
grid-template-columns: 1fr;
}
}
/* ── Column ────────────────────────────────────────────────────────────── */
.prab-board-column {
background: #f8f7f5;
border: 1px solid #e2ddd6;
border-radius: 8px;
min-height: 180px;
}
.prab-col-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 14px 10px;
border-bottom: 1px solid #e2ddd6;
}
.prab-col-title {
font-size: 0.82rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: #4a4540;
}
.prab-col-cards {
padding: 10px 10px 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.prab-col-empty {
font-size: 0.82rem;
color: #b0a898;
text-align: center;
padding: 20px 0;
margin: 0;
}
/* ── Status pills ──────────────────────────────────────────────────────── */
.prab-pill {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 1px 8px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 600;
line-height: 1.5;
color: #fff;
min-width: 24px;
}
.prab-pill--generating {
background: #1b8a92;
}
.prab-pill--review {
background: #ff8a3d;
}
.prab-pill--published {
background: #5a9e28;
}
.prab-pill--failed {
background: #d94f4f;
}
/* ── Card ──────────────────────────────────────────────────────────────── */
.prab-board-card {
background: #faf6ee;
border: 1px solid #e0d8cc;
border-radius: 6px;
padding: 11px 12px 10px;
position: relative;
transition: box-shadow 0.15s ease, border-color 0.15s ease;
}
.prab-board-card:hover {
box-shadow: 0 2px 8px rgba(27, 138, 146, 0.12);
border-color: #b8cfd2;
}
.prab-board-card--generating {
border-left: 3px solid #1b8a92;
}
.prab-card-title {
font-size: 0.875rem;
font-weight: 500;
color: #0d0d0d;
line-height: 1.4;
margin-bottom: 6px;
padding-right: 20px; /* room for spinner */
}
.prab-card-meta {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 5px;
}
.prab-card-cost {
font-size: 0.75rem;
color: #5a8a50;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.prab-card-stage {
font-size: 0.74rem;
color: #1b8a92;
font-weight: 500;
margin-bottom: 5px;
}
.prab-card-error {
font-size: 0.74rem;
color: #d94f4f;
margin-bottom: 5px;
font-style: italic;
}
.prab-card-actions {
margin-top: 8px;
}
.prab-card-link {
display: inline-block;
font-size: 0.75rem;
color: #1b8a92;
text-decoration: none;
font-weight: 500;
border: 1px solid #b8d8db;
border-radius: 4px;
padding: 2px 8px;
transition: background 0.1s ease;
}
.prab-card-link:hover {
background: #e8f4f5;
color: #136870;
border-color: #8ac4c9;
}
/* ── Generating spinner ────────────────────────────────────────────────── */
.prab-card-spinner {
position: absolute;
top: 11px;
right: 11px;
width: 14px;
height: 14px;
border: 2px solid #c8e6e8;
border-top-color: #1b8a92;
border-radius: 50%;
animation: prab-spin 0.9s linear infinite;
}
@keyframes prab-spin {
to { transform: rotate(360deg); }
}
/* ── Board footer ──────────────────────────────────────────────────────── */
.prab-board-footer {
padding: 0 20px 16px;
font-size: 0.78rem;
color: #a0998f;
}
/* ── Poll-error banner ─────────────────────────────────────────────────── */
.prab-board-error {
background: #fff4f4;
border: 1px solid #f5c4c4;
color: #8b2020;
border-radius: 6px;
padding: 8px 14px;
margin: 0 20px 12px;
font-size: 0.82rem;
display: none;
}
.prab-board-error.is-visible {
display: block;
}

View File

@@ -1,240 +0,0 @@
/**
* PRAutoBlogger dossier — edit + re-run styles (M3, v0.20.0).
* Extends dossier.css (kept separate: dossier.css predates the
* 300-line discipline and is not grown further).
*/
/* ── Audit chips (stale / human-edited / attempt) ─────────────────── */
.prab-chip {
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
font-size: 11px;
font-weight: 600;
line-height: 1.6;
vertical-align: middle;
}
.prab-chip--stale {
background: #fcf0e4;
color: #8a4a0b;
border: 1px solid #e8c9a8;
}
.prab-chip--human {
background: #e9f2f4;
color: #1b5e6b;
border: 1px solid #b8d8de;
}
.prab-chip--attempt {
background: #f0f0f1;
color: #50575e;
border: 1px solid #dcdcde;
}
.prab-chip--chosen {
background: #edf7ed;
color: #1e6b2e;
border: 1px solid #b9dfc0;
}
.prab-chip--header {
margin-left: 6px;
font-size: 12px;
}
.prab-stage--stale {
border-left: 3px solid #d98c2b;
}
/* ── Stage footer actions ─────────────────────────────────────────── */
.prab-stage-rerun-footer {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin-top: 12px;
padding-top: 10px;
border-top: 1px dashed #e2dcd2;
}
.prab-edit-unavailable {
font-size: 12px;
color: #777;
font-style: italic;
max-width: 46em;
}
.prab-rerun-from--stale {
border-color: #d98c2b;
color: #8a4a0b;
}
/* ── Edit panel ───────────────────────────────────────────────────── */
.prab-edit-panel {
margin-top: 12px;
padding: 14px 16px;
background: #fbf8f2;
border: 1px solid #e2dcd2;
border-radius: 6px;
}
.prab-edit-copy {
font-size: 13px;
color: #50575e;
max-width: 60em;
}
.prab-edit-spend {
font-size: 12px;
color: #50575e;
}
.prab-edit-spend--warn,
.prab-spend-warning {
color: #8a2a0b;
font-weight: 600;
}
.prab-run-spend--warn {
border-left: 3px solid #c9501f;
}
.prab-edit-model {
font-size: 12px;
color: #777;
font-family: Consolas, Monaco, monospace;
}
.prab-edit-message {
margin-bottom: 10px;
}
.prab-edit-role {
display: block;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #8c8f94;
margin-bottom: 3px;
}
.prab-edit-textarea {
width: 100%;
font-family: Consolas, Monaco, monospace;
font-size: 12px;
line-height: 1.5;
}
.prab-edit-actions {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin-top: 8px;
}
.prab-edit-forkinfo {
font-size: 12px;
color: #777;
}
.prab-edit-feedback {
font-size: 12px;
color: #1e6b2e;
}
.prab-edit-feedback--error {
color: #b32d2e;
}
/* ── Image grid (F3) ──────────────────────────────────────────────── */
.prab-image-grid {
display: flex;
gap: 14px;
flex-wrap: wrap;
margin: 10px 0;
}
.prab-image-card {
margin: 0;
max-width: 220px;
}
.prab-image-card img {
width: 100%;
height: auto;
border-radius: 4px;
border: 1px solid #e2dcd2;
}
.prab-image-card--chosen img {
border: 2px solid #1b8a92;
}
.prab-image-card figcaption {
font-size: 12px;
color: #50575e;
margin-top: 4px;
}
/* ── Sidebar models card (F2) ─────────────────────────────────────── */
.prab-models-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.prab-models-table th {
text-align: left;
font-weight: 600;
padding: 4px 6px 4px 0;
vertical-align: top;
color: #50575e;
width: 38%;
}
.prab-models-table td {
padding: 4px 0;
}
.prab-models-model {
display: block;
font-family: Consolas, Monaco, monospace;
font-size: 11px;
word-break: break-all;
}
.prab-models-meta {
display: block;
color: #8c8f94;
font-size: 11px;
}
/* ── Board card human-modified dot ────────────────────────────────── */
.prab-card-human-chip {
display: inline-block;
margin-top: 4px;
padding: 1px 7px;
border-radius: 9px;
font-size: 10px;
font-weight: 700;
background: #e9f2f4;
color: #1b5e6b;
border: 1px solid #b8d8de;
}
/* ── Review queue stale warning ───────────────────────────────────── */
.prab-review-stale-chip {
display: inline-block;
margin-left: 6px;
padding: 1px 7px;
border-radius: 9px;
font-size: 10px;
font-weight: 700;
background: #fcf0e4;
color: #8a4a0b;
border: 1px solid #e8c9a8;
}

View File

@@ -1,441 +0,0 @@
/**
* PRAutoBlogger Article Dossier styles (M2).
*
* Design contract: Proposal C "Editorial Record" -- warm editorial,
* generous whitespace, typographic hierarchy, verdict pills, receipt
* sidebar. Scoped to .prab-dossier-wrap to avoid WP admin conflicts.
*
* @see admin/class-dossier-page.php
* @see templates/admin/dossier-page.php
*/
/* ── Layout ──────────────────────────────────────────────────────────── */
.prab-dossier-wrap {
max-width: 1400px;
}
.prab-dossier-back {
margin-bottom: 12px;
}
.prab-dossier-back a {
color: #1B8A92;
text-decoration: none;
}
.prab-dossier-back a:hover {
text-decoration: underline;
}
.prab-dossier--empty {
background: #fff;
border: 1px solid #ddd;
border-radius: 4px;
padding: 32px;
}
.prab-dossier-empty-notice h2 {
font-size: 1.3em;
margin: 0 0 12px;
color: #444;
}
.prab-dossier {
background: #fff;
}
/* ── Header ──────────────────────────────────────────────────────────── */
.prab-dossier-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 24px 28px 20px;
border-bottom: 1px solid #e8e0d8;
background: #FAF6EE;
border-radius: 4px 4px 0 0;
}
.prab-dossier-title {
font-size: 1.6em;
margin: 0 0 8px;
color: #1a1a1a;
line-height: 1.3;
}
.prab-dossier-header-meta {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
/* ── Body: two-column ─────────────────────────────────────────────────── */
.prab-dossier-body {
display: flex;
align-items: flex-start;
gap: 0;
}
.prab-dossier-main {
flex: 1;
min-width: 0;
padding: 24px 28px;
}
.prab-dossier-sidebar {
width: 260px;
flex-shrink: 0;
padding: 24px 20px;
border-left: 1px solid #e8e0d8;
}
/* ── Verdict pills ────────────────────────────────────────────────────── */
.prab-verdict-pill {
display: inline-block;
padding: 3px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.prab-verdict-pill--approved { background: #e6f5ee; color: #1a7a45; }
.prab-verdict-pill--revised { background: #fff4e0; color: #a06000; }
.prab-verdict-pill--rejected { background: #fde8e8; color: #b91c1c; }
.prab-verdict-pill--halted { background: #f0f0f0; color: #555; }
.prab-verdict-pill--pending { background: #e8f0fe; color: #1a55a0; }
/* ── Status pills ─────────────────────────────────────────────────────── */
.prab-dossier-tier {
font-size: 12px;
color: #666;
padding: 2px 8px;
border: 1px solid #ddd;
border-radius: 10px;
}
.prab-dossier-status {
font-size: 12px;
color: #777;
}
/* ── Stage sections ───────────────────────────────────────────────────── */
.prab-dossier-section {
margin-bottom: 28px;
border: 1px solid #e5ddd5;
border-radius: 4px;
overflow: hidden;
}
.prab-dossier-section--stage {
border-left: 4px solid #ccc;
}
.prab-stage-status--done { border-left-color: #1B8A92; }
.prab-stage-status--running { border-left-color: #FF8A3D; }
.prab-stage-status--failed { border-left-color: #e53e3e; }
.prab-stage-status--pending { border-left-color: #a0aec0; }
.prab-stage-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background: #faf8f5;
border-bottom: 1px solid #ede6dd;
}
.prab-section-title {
font-size: 1em;
font-weight: 600;
margin: 0;
color: #2d2d2d;
}
.prab-stage-role {
font-weight: 400;
color: #888;
font-size: 0.9em;
margin-left: 4px;
}
.prab-stage-header-meta {
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
color: #666;
}
.prab-stage-status-pill {
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
font-size: 11px;
font-weight: 600;
}
.prab-stage-status-pill--done { background: #e6f5ee; color: #1a7a45; }
.prab-stage-status-pill--running { background: #fff4e0; color: #a06000; }
.prab-stage-status-pill--failed { background: #fde8e8; color: #b91c1c; }
.prab-stage-status-pill--pending { background: #f0f0f0; color: #555; }
.prab-stage-cost {
color: #1B8A92;
font-weight: 600;
}
.prab-stage-pv {
background: #f0f0f0;
padding: 1px 6px;
border-radius: 8px;
font-size: 11px;
}
/* ── Stage output ─────────────────────────────────────────────────────── */
.prab-stage-output {
padding: 16px;
line-height: 1.7;
}
.prab-stage-output-rendered {
font-size: 14px;
color: #333;
max-height: 480px;
overflow-y: auto;
}
.prab-output-pruned,
.prab-output-absent {
color: #888;
font-style: italic;
margin: 0;
}
/* ── Raw trace toggle ─────────────────────────────────────────────────── */
.prab-stage-trace {
padding: 0 16px 12px;
border-top: 1px solid #f0ece6;
}
.prab-trace-toggle {
font-size: 12px;
color: #1B8A92;
cursor: pointer;
padding: 6px 0;
background: none;
border: none;
}
.prab-trace-toggle:hover {
color: #0d6066;
}
.prab-trace-detail {
margin-top: 8px;
}
.prab-trace-entry {
background: #f7f4ef;
border: 1px solid #e5ddd5;
border-radius: 4px;
padding: 10px 12px;
margin-bottom: 8px;
}
.prab-trace-meta {
display: flex;
gap: 12px;
font-size: 11px;
color: #666;
margin-bottom: 6px;
flex-wrap: wrap;
}
.prab-trace-status--success { color: #1a7a45; }
.prab-trace-status--error { color: #b91c1c; }
.prab-trace-request summary {
font-size: 12px;
cursor: pointer;
color: #888;
padding: 4px 0;
}
.prab-trace-pre {
background: #1a1a1a;
color: #e2e8f0;
padding: 10px;
border-radius: 3px;
font-size: 11px;
overflow-x: auto;
max-height: 300px;
white-space: pre-wrap;
word-break: break-all;
}
.prab-trace-error {
color: #b91c1c;
font-size: 12px;
margin: 4px 0 0;
}
/* ── Stage timestamps ─────────────────────────────────────────────────── */
.prab-stage-timestamps {
padding: 4px 16px 10px;
font-size: 11px;
color: #aaa;
}
.prab-ts-sep {
margin: 0 4px;
}
/* ── Decisions section ───────────────────────────────────────────────── */
.prab-dossier-section--decisions {
padding: 16px;
}
.prab-dossier-section--decisions .prab-section-title {
font-size: 1.1em;
margin-bottom: 12px;
}
.prab-decision-row {
display: flex;
align-items: flex-start;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 12px;
padding-bottom: 12px;
border-bottom: 1px solid #f0ece6;
}
.prab-decision-row:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
.prab-decision-stage {
font-weight: 600;
font-size: 13px;
min-width: 120px;
}
.prab-decision-rationale {
margin: 4px 0 0;
width: 100%;
color: #555;
font-size: 13px;
}
/* ── Sidebar ──────────────────────────────────────────────────────────── */
.prab-sidebar-card {
background: #faf8f5;
border: 1px solid #e5ddd5;
border-radius: 4px;
padding: 14px 16px;
margin-bottom: 16px;
}
.prab-sidebar-heading {
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
color: #888;
margin: 0 0 10px;
}
.prab-sidebar-dl {
margin: 0;
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 10px;
font-size: 12px;
}
.prab-sidebar-dl dt {
color: #888;
white-space: nowrap;
}
.prab-sidebar-dl dd {
margin: 0;
color: #333;
word-break: break-all;
}
.prab-run-id {
font-family: monospace;
font-size: 10px;
}
/* ── Cost receipt ─────────────────────────────────────────────────────── */
.prab-receipt-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.prab-receipt-table td {
padding: 3px 0;
}
.prab-receipt-stage {
color: #555;
}
.prab-receipt-cost {
text-align: right;
color: #1B8A92;
font-family: monospace;
}
.prab-receipt-total {
border-top: 1px solid #ddd;
font-weight: 700;
}
.prab-receipt-total td {
padding-top: 6px;
}
/* ── Run status ───────────────────────────────────────────────────────── */
.prab-run-status {
font-size: 12px;
}
.prab-run-status--done { color: #1a7a45; }
.prab-run-status--running { color: #a06000; }
.prab-run-status--failed { color: #b91c1c; }
/* ── No stages ─────────────────────────────────────────────────────────── */
.prab-dossier-no-stages {
padding: 24px 0;
color: #888;
}
/* ── Metabox ──────────────────────────────────────────────────────────── */
.prab-metabox-dossier .prab-run-id-label {
font-size: 11px;
color: #999;
margin-top: 4px;
}

View File

@@ -142,7 +142,6 @@
color: var(--ab-text-muted, #64748b);
font-variant-numeric: tabular-nums;
white-space: nowrap;
min-width: 90px; text-align: right; flex-shrink: 0;
}
.ab-mp-ctx {
@@ -151,7 +150,6 @@
background: var(--ab-bg, #f8fafc);
padding: 2px 6px; border-radius: 4px;
white-space: nowrap; min-width: 36px; text-align: center;
max-width: 200px; overflow: hidden; text-overflow: ellipsis;
}
/* ── Footer ─────────────────────────────────────────────────────────── */
@@ -206,59 +204,3 @@
.ab-mp-row { padding: 10px 14px; }
.ab-mp-row-meta { gap: 8px; }
}
/* ── Column headers (sortable) ──────────────────────────────────────── */
.ab-mp-col-headers {
display: flex; align-items: center; justify-content: space-between;
padding: 5px 20px;
border-bottom: 1px solid var(--ab-border, #e2e8f0);
background: var(--ab-bg, #f8fafc);
gap: 12px; /* must match .ab-mp-row gap */
}
.ab-mp-col-headers-meta {
display: flex; align-items: center;
gap: 16px; /* must match .ab-mp-row-meta gap */
flex-shrink: 0;
}
.ab-mp-col-header {
display: inline-flex; align-items: center;
font-size: 10px; font-weight: 700; text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--ab-text-muted, #64748b);
cursor: pointer; user-select: none;
background: none; border: none; padding: 3px 0;
white-space: nowrap; line-height: 1.2;
transition: color 0.1s ease;
}
.ab-mp-col-header:hover {
color: var(--ab-text, #1e293b);
}
.ab-mp-col-header.ab-mp-col-active {
color: var(--ab-primary, #4f46e5);
}
/* "Model" header spans the left flex-1 area */
.ab-mp-col-model {
flex: 1; min-width: 0;
}
/* "Price" header width matches .ab-mp-price */
.ab-mp-col-price {
font-variant-numeric: tabular-nums;
min-width: 90px; justify-content: flex-end;
}
/* "Context" header width matches .ab-mp-ctx (min-width 36px + padding) */
.ab-mp-col-ctx {
min-width: 48px; justify-content: center; text-align: center;
}
.ab-mp-sort-arrow {
font-size: 9px; opacity: 0.5;
transition: opacity 0.1s ease;
}
.ab-mp-col-header.ab-mp-col-active .ab-mp-sort-arrow {
opacity: 1;
}

View File

@@ -1,93 +0,0 @@
Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

Binary file not shown.

View File

@@ -1,246 +0,0 @@
/**
* PRAutoBlogger — Kanban Board Poller
*
* Live-polls the board status AJAX endpoint and updates the four columns
* (Generating | In Review | Published | Failed) in-place without a full
* page reload.
*
* Poll behaviour:
* - Polls at `prabBoard.pollInterval` ms when any article is generating.
* - Doubles the interval (backoff) when `has_active_runs` is false, capping
* at 4× the base interval — prevents needless AJAX on an idle board.
* - Resets to base interval as soon as an active run is detected again.
*
* Click-throughs (M1):
* - Generating → Activity Log
* - In Review → Review Queue
* - Published → Post edit screen
* - Failed → Activity Log
* (M2 rewires all to Article Dossier)
*
* Localised config: `prabBoard` object (ajaxUrl, nonce, pollInterval, action,
* strings) injected by PRAutoBlogger_Board_Page::on_enqueue_assets().
*
* @see includes/admin/class-board-page.php — AJAX handler + localise.
* @see assets/css/board.css — Card and column styles.
* @see templates/admin/board-page.php — Initial server-rendered HTML.
*/
( function ( $ ) {
'use strict';
var cfg = window.prabBoard || {};
var baseInterval = cfg.pollInterval || 5000;
var maxBackoff = 4;
var backoffFactor = 1;
var pollTimer = null;
var $board = null;
var $errorBanner = null;
/** Escape HTML for safe DOM insertion. */
function escHtml( str ) {
return $( '<div>' ).text( String( str ) ).html();
}
/** Format cost to 4 decimal places with a leading $. */
function formatCost( cost ) {
var n = parseFloat( cost ) || 0;
return '$' + n.toFixed( 4 );
}
/**
* Build a card HTML string from a card data object.
*
* @param {Object} card Card data from server.
* @param {string} columnKey Column identifier.
* @returns {string} HTML string.
*/
function buildCardHtml( card, columnKey ) {
var isGenerating = ( columnKey === 'generating' );
var cls = 'prab-board-card' + ( isGenerating ? ' prab-board-card--generating' : '' );
var html = '';
html += '<div class="' + escHtml( cls ) + '"';
html += ' data-run-id="' + escHtml( card.run_id || '' ) + '"';
html += ' data-post-id="' + escHtml( card.post_id || 0 ) + '">';
if ( isGenerating ) {
html += '<div class="prab-card-spinner" aria-label="' + escHtml( cfg.strings.generating ) + '"></div>';
}
html += '<div class="prab-card-title">' + escHtml( card.title || cfg.strings.empty ) + '</div>';
// v0.20.0: human-modified runs are visually distinct at run-list level.
if ( card.human_modified ) {
html += '<span class="prab-card-human-chip">' + escHtml( cfg.strings.humanModified || 'Human-modified' ) + '</span>';
}
if ( card.cost_total ) {
html += '<div class="prab-card-meta"><span class="prab-card-cost">';
html += escHtml( formatCost( card.cost_total ) );
html += '</span></div>';
}
if ( isGenerating && card.stage_current ) {
html += '<div class="prab-card-stage">';
/* translators: stage name */
html += escHtml( cfg.strings.generating + ': ' + card.stage_current );
html += '</div>';
}
if ( card.error_message ) {
var errShort = String( card.error_message ).split( ' ' ).slice( 0, 12 ).join( ' ' );
if ( card.error_message.split( ' ' ).length > 12 ) {
errShort += '…';
}
html += '<div class="prab-card-error">' + escHtml( errShort ) + '</div>';
}
// Click-through link.
var linkUrl = '';
var linkText = '';
if ( card.click_action === 'dossier' && card.dossier_url ) {
linkUrl = card.dossier_url;
linkText = cfg.strings.view;
} else if ( card.click_action === 'review' && card.review_url ) {
linkUrl = card.review_url;
linkText = cfg.strings.view;
} else if ( card.click_action === 'edit' && card.edit_url ) {
linkUrl = card.edit_url;
linkText = cfg.strings.edit;
} else if ( card.click_action === 'logs' && card.log_url ) {
linkUrl = card.log_url;
linkText = cfg.strings.viewLog;
}
if ( linkUrl ) {
html += '<div class="prab-card-actions">';
html += '<a href="' + escHtml( linkUrl ) + '" class="prab-card-link">';
html += escHtml( linkText );
html += '</a></div>';
}
html += '</div>';
return html;
}
/**
* Re-render a single column from the server snapshot.
*
* Updates the pill count and replaces card HTML. Avoids full DOM teardown
* to prevent flicker on the running spinner.
*
* @param {string} colKey Column identifier.
* @param {Array} cards Array of card objects.
* @returns {void}
*/
function renderColumn( colKey, cards ) {
var $col = $board.find( '[data-column="' + colKey + '"]' );
var $cards = $col.find( '[data-column-cards]' );
var $pill = $col.find( '.prab-col-count' );
$pill.text( cards.length );
if ( ! cards.length ) {
$cards.html( '<p class="prab-col-empty">' + escHtml( cfg.strings.empty ) + '</p>' );
return;
}
// Build new card HTML.
var newHtml = '';
for ( var i = 0; i < cards.length; i++ ) {
newHtml += buildCardHtml( cards[ i ], colKey );
}
$cards.html( newHtml );
}
/**
* Apply a server snapshot to all four columns.
*
* @param {Object} snapshot Board snapshot from AJAX.
* @returns {void}
*/
function applySnapshot( snapshot ) {
renderColumn( 'generating', snapshot.generating || [] );
renderColumn( 'in_review', snapshot.in_review || [] );
renderColumn( 'published', snapshot.published || [] );
renderColumn( 'failed', snapshot.failed || [] );
}
/**
* Compute the next poll delay based on whether there are active runs.
*
* @param {boolean} hasActiveRuns
* @returns {number} Milliseconds until next poll.
*/
function nextDelay( hasActiveRuns ) {
if ( hasActiveRuns ) {
backoffFactor = 1;
return baseInterval;
}
backoffFactor = Math.min( backoffFactor + 1, maxBackoff );
return baseInterval * backoffFactor;
}
/**
* Schedule the next poll after a given delay.
*
* @param {number} delay Milliseconds.
* @returns {void}
*/
function schedulePoll( delay ) {
clearTimeout( pollTimer );
pollTimer = setTimeout( doPoll, delay );
}
/**
* Execute one board poll: AJAX POST → apply snapshot → reschedule.
*
* @returns {void}
*/
function doPoll() {
$.ajax( {
url: cfg.ajaxUrl,
method: 'POST',
data: {
action: cfg.action,
nonce: cfg.nonce
},
success: function ( response ) {
if ( $errorBanner ) {
$errorBanner.removeClass( 'is-visible' );
}
if ( response && response.success && response.data ) {
applySnapshot( response.data );
schedulePoll( nextDelay( !! response.data.has_active_runs ) );
} else {
schedulePoll( nextDelay( false ) );
}
},
error: function () {
if ( $errorBanner ) {
$errorBanner.addClass( 'is-visible' );
}
schedulePoll( nextDelay( false ) );
}
} );
}
/** Initialise the board poller on DOM ready. */
$( function () {
$board = $( '#prab-board' );
if ( ! $board.length ) {
return;
}
// Inject the error banner after the heading.
$errorBanner = $( '<div class="prab-board-error" role="alert">' + escHtml( cfg.strings.pollError || '' ) + '</div>' );
$board.before( $errorBanner );
// Check if any generating card is present in the initial server render.
var hasActive = ( $board.find( '[data-column="generating"] .prab-board-card' ).length > 0 );
backoffFactor = hasActive ? 1 : 1; // Always start at base on first load.
schedulePoll( nextDelay( hasActive ) );
} );
}( jQuery ) );

View File

@@ -1,235 +0,0 @@
/**
* PRAutoBlogger Article Dossier — edit + re-run actions (M3, v0.20.0).
*
* Chained-cron UX contract (CPO hard constraint): clicking a re-run
* button QUEUES a background job — the UI says "queued", starts the
* stage-status poll, and renders pickup/result as the rows change.
* Nothing here implies synchronous execution.
*
* Vanilla JS, no build step. Config injected via wp_localize_script
* ('prabDossierEdit': ajaxUrl, nonce, postId, pollInterval, strings).
*
* @see admin/class-dossier-actions.php — The endpoints this calls.
* @see admin/class-dossier-page.php — Enqueue + localization.
*/
( function () {
'use strict';
var cfg = window.prabDossierEdit || null;
function post( action, fields ) {
var data = new window.FormData();
data.append( 'action', action );
data.append( 'nonce', cfg.nonce );
data.append( 'post_id', cfg.postId );
Object.keys( fields || {} ).forEach( function ( key ) {
data.append( key, fields[ key ] );
} );
return window.fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: data } )
.then( function ( res ) { return res.json(); } );
}
function feedback( panel, message, isError ) {
var el = panel.querySelector( '[data-feedback]' );
if ( el ) {
el.textContent = message || '';
el.classList.toggle( 'prab-edit-feedback--error', !! isError );
}
}
function sectionFor( el ) {
var node = el;
while ( node && ! node.classList.contains( 'prab-dossier-section--stage' ) ) {
node = node.parentElement;
}
return node;
}
// ── Stage-status polling (queued → pickup → result) ────────────────
var pollTimer = null;
var sawActivity = false;
function applyStageState( state ) {
var selector = '.prab-dossier-section--stage[data-stage="' + state.stage + '"][data-agent-role="' + state.agent_role + '"]';
var section = document.querySelector( selector );
if ( ! section ) {
return;
}
var pill = section.querySelector( '.prab-stage-status-pill' );
if ( pill ) {
pill.className = 'prab-stage-status-pill prab-stage-status-pill--' + state.status;
pill.textContent = state.status.charAt( 0 ).toUpperCase() + state.status.slice( 1 );
}
var staleChip = section.querySelector( '[data-chip="stale"]' );
if ( staleChip ) {
staleChip.hidden = ! state.stale;
}
section.classList.toggle( 'prab-stage--stale', !! state.stale );
var humanChip = section.querySelector( '[data-chip="human"]' );
if ( humanChip ) {
humanChip.hidden = ! state.human_modified;
}
}
function poll() {
post( 'prautoblogger_dossier_stage_status', {} ).then( function ( res ) {
if ( ! res || ! res.success || ! res.data ) {
return;
}
var anyRunning = false;
var anyStale = false;
var anyHuman = false;
( res.data.stages || [] ).forEach( function ( state ) {
applyStageState( state );
if ( 'running' === state.status || 'pending' === state.status ) {
anyRunning = true;
}
anyStale = anyStale || !! state.stale;
anyHuman = anyHuman || !! state.human_modified;
} );
var headerHuman = document.querySelector( '[data-header-chip="human"]' );
if ( headerHuman ) {
headerHuman.hidden = ! anyHuman;
}
var headerStale = document.querySelector( '[data-header-chip="stale"]' );
if ( headerStale ) {
headerStale.hidden = ! anyStale;
}
var terminal = -1 === [ 'running', 'pending' ].indexOf( res.data.run_status );
if ( anyRunning || ! terminal ) {
sawActivity = true;
return;
}
// Run settled after activity we watched: re-render the dossier
// fresh (server-rendered outputs, receipts, fork info).
if ( sawActivity ) {
window.clearInterval( pollTimer );
pollTimer = null;
window.location.reload();
}
} ).catch( function () { /* transient poll errors are ignored */ } );
}
function startPolling() {
sawActivity = true;
if ( ! pollTimer ) {
pollTimer = window.setInterval( poll, cfg.pollInterval * 1000 );
}
}
// ── Wiring ──────────────────────────────────────────────────────────
document.addEventListener( 'DOMContentLoaded', function () {
if ( ! cfg ) {
return;
}
// Edit panel toggles.
document.querySelectorAll( '.prab-edit-toggle' ).forEach( function ( btn ) {
btn.addEventListener( 'click', function () {
var panel = document.getElementById( btn.getAttribute( 'aria-controls' ) );
if ( ! panel ) {
return;
}
var open = btn.getAttribute( 'aria-expanded' ) === 'true';
panel.hidden = open;
btn.setAttribute( 'aria-expanded', open ? 'false' : 'true' );
} );
} );
// Save fork.
document.querySelectorAll( '.prab-edit-save' ).forEach( function ( btn ) {
btn.addEventListener( 'click', function () {
var panel = btn.closest( '.prab-edit-panel' );
var messages = [];
panel.querySelectorAll( '.prab-edit-textarea' ).forEach( function ( area ) {
messages.push( { role: area.getAttribute( 'data-role' ), content: area.value } );
} );
btn.disabled = true;
feedback( panel, cfg.strings.saving, false );
post( 'prautoblogger_dossier_save_input', {
stage: panel.getAttribute( 'data-stage' ),
agent_role: panel.getAttribute( 'data-agent-role' ),
messages: JSON.stringify( messages )
} ).then( function ( res ) {
btn.disabled = false;
if ( res && res.success ) {
feedback( panel, res.data.message, false );
var rerunBtn = panel.querySelector( '.prab-edit-rerun' );
if ( rerunBtn ) {
rerunBtn.disabled = false;
}
var info = panel.querySelector( '[data-forkinfo]' );
if ( info && res.data.version ) {
info.textContent = 'v' + res.data.version;
}
} else {
feedback( panel, ( res && res.data && res.data.message ) || cfg.strings.error, true );
}
} ).catch( function () {
btn.disabled = false;
feedback( panel, cfg.strings.error, true );
} );
} );
} );
// Replay latest fork (queued).
document.querySelectorAll( '.prab-edit-rerun' ).forEach( function ( btn ) {
btn.addEventListener( 'click', function () {
var panel = btn.closest( '.prab-edit-panel' );
if ( ! window.confirm( cfg.strings.confirmReplay ) ) {
return;
}
btn.disabled = true;
post( 'prautoblogger_dossier_rerun_stage', {
stage: panel.getAttribute( 'data-stage' ),
agent_role: panel.getAttribute( 'data-agent-role' )
} ).then( function ( res ) {
if ( res && res.success ) {
feedback( panel, res.data.message, false );
startPolling();
} else {
btn.disabled = false;
feedback( panel, ( res && res.data && res.data.message ) || cfg.strings.error, true );
}
} ).catch( function () {
btn.disabled = false;
feedback( panel, cfg.strings.error, true );
} );
} );
} );
// Re-run from here (queued rebuild).
document.querySelectorAll( '.prab-rerun-from' ).forEach( function ( btn ) {
btn.addEventListener( 'click', function () {
var section = sectionFor( btn );
if ( ! window.confirm( cfg.strings.confirmRerunFrom ) ) {
return;
}
btn.disabled = true;
btn.textContent = cfg.strings.queued;
post( 'prautoblogger_dossier_rerun_from', {
stage: btn.getAttribute( 'data-stage' ),
agent_role: section ? section.getAttribute( 'data-agent-role' ) : ''
} ).then( function ( res ) {
if ( res && res.success ) {
startPolling();
} else {
btn.disabled = false;
btn.textContent = cfg.strings.rerunFromLabel;
window.alert( ( res && res.data && res.data.message ) || cfg.strings.error );
}
} ).catch( function () {
btn.disabled = false;
btn.textContent = cfg.strings.rerunFromLabel;
window.alert( cfg.strings.error );
} );
} );
} );
// A stage already running (e.g. revisit mid-job): poll from load.
if ( document.querySelector( '.prab-stage-status-pill--running' ) ) {
startPolling();
}
} );
}() );

View File

@@ -1,41 +0,0 @@
/**
* PRAutoBlogger Article Dossier -- raw-trace toggle (M2).
*
* Toggles the hidden raw-trace <div> per stage when the "Show raw trace"
* button is clicked. Vanilla JS, no build step, no external deps.
*
* Accessible: uses aria-expanded + aria-controls; respects the hidden attribute.
*
* @see admin/class-dossier-page.php -- Enqueues this file.
* @see templates/admin/dossier-page.php -- Renders the toggle buttons.
*/
( function () {
'use strict';
document.addEventListener( 'DOMContentLoaded', function () {
var toggles = document.querySelectorAll( '.prab-trace-toggle' );
toggles.forEach( function ( btn ) {
btn.addEventListener( 'click', function () {
var targetId = btn.getAttribute( 'aria-controls' );
if ( ! targetId ) {
return;
}
var panel = document.getElementById( targetId );
if ( ! panel ) {
return;
}
var isOpen = btn.getAttribute( 'aria-expanded' ) === 'true';
if ( isOpen ) {
panel.hidden = true;
btn.setAttribute( 'aria-expanded', 'false' );
btn.textContent = btn.textContent.replace( /hide/i, 'Show' );
} else {
panel.hidden = false;
btn.setAttribute( 'aria-expanded', 'true' );
btn.textContent = btn.textContent.replace( /show/i, 'Hide' );
}
} );
} );
} );
}() );

View File

@@ -1,10 +1,9 @@
/**
* Model picker popup for PRAutoBlogger admin settings.
*
* Fetches the OpenRouter model registry via AJAX, then renders a searchable,
* sortable popup overlay when the user clicks a model-select trigger button.
* Columns: Model, Price (in / out per 1M tokens), Context window.
* Each column header is clickable to sort ascending/descending.
* Fetches the OpenRouter model registry via AJAX, then renders a searchable
* popup overlay when the user clicks a model-select trigger button. Shows
* name, provider, input/output cost, and context window per model.
*
* @see admin/class-admin-page.php — Renders model_select fields and localizes config.
* @see services/class-open-router-model-registry.php — Server-side registry source.
@@ -12,57 +11,54 @@
(function ($) {
'use strict';
var config = window.prautobloggerAdmin || {};
var cachedModels = null;
var config = window.prautobloggerAdmin || {};
var cachedModels = null;
var fetchInProgress = null;
// Persists across open/close so the user's preferred sort is remembered.
var sortState = { col: 'name', dir: 'asc' };
/**
* Fetch models from the server (cached after first call).
*
* @param {string} capability Filter capability (e.g. 'text→text').
* @return {jQuery.Deferred} Resolves with model array.
*/
function fetchModels( capability ) {
function fetchModels(capability) {
// Image models are embedded in the page config — no AJAX needed.
if ( capability === 'image_generation' ) {
if (capability === 'image_generation') {
var imgModels = config.imageModels || [];
return $.Deferred().resolve( imgModels );
return $.Deferred().resolve(imgModels);
}
if ( cachedModels ) {
return $.Deferred().resolve( filterModels( cachedModels, capability ) );
if (cachedModels) {
return $.Deferred().resolve(filterModels(cachedModels, capability));
}
if ( fetchInProgress ) {
return fetchInProgress.then( function () {
return filterModels( cachedModels, capability );
} );
if (fetchInProgress) {
return fetchInProgress.then(function () {
return filterModels(cachedModels, capability);
});
}
fetchInProgress = $.ajax( {
url: config.ajaxUrl,
fetchInProgress = $.ajax({
url: config.ajaxUrl,
method: 'POST',
data: {
action: 'prautoblogger_get_models',
nonce: config.modelsNonce
nonce: config.modelsNonce
},
timeout: 15000
} ).then( function ( response ) {
}).then(function (response) {
fetchInProgress = null;
if ( response.success && Array.isArray( response.data ) ) {
if (response.success && Array.isArray(response.data)) {
cachedModels = response.data;
return filterModels( cachedModels, capability );
return filterModels(cachedModels, capability);
}
cachedModels = [];
return [];
}, function () {
fetchInProgress = null;
cachedModels = [];
cachedModels = [];
return [];
} );
});
return fetchInProgress;
}
@@ -74,49 +70,11 @@
* @param {string} capability Capability string to match.
* @return {Array} Filtered models.
*/
function filterModels( models, capability ) {
if ( ! capability ) return models;
return models.filter( function ( m ) {
return m.capabilities && m.capabilities.indexOf( capability ) !== -1;
} );
}
/**
* Sort a model array according to the current sortState.
* Deprecated models always sink to the bottom regardless of column.
*
* @param {Array} arr Model array to sort (not mutated — returns a new array).
* @return {Array} Sorted copy.
*/
function applySort( arr ) {
var col = sortState.col;
var dir = sortState.dir;
return arr.slice().sort( function ( a, b ) {
// Deprecated always last.
if ( a.deprecated !== b.deprecated ) {
return a.deprecated ? 1 : -1;
}
var valA, valB;
if ( col === 'price' ) {
// Image models use cost_per_image; text models use input_price_per_m.
valA = ( a.cost_per_image !== undefined ) ? a.cost_per_image : ( a.input_price_per_m || 0 );
valB = ( b.cost_per_image !== undefined ) ? b.cost_per_image : ( b.input_price_per_m || 0 );
} else if ( col === 'context' ) {
valA = a.context_length || 0;
valB = b.context_length || 0;
} else {
// Default: sort by model name.
valA = ( a.name || '' ).toLowerCase();
valB = ( b.name || '' ).toLowerCase();
}
if ( valA < valB ) return dir === 'asc' ? -1 : 1;
if ( valA > valB ) return dir === 'asc' ? 1 : -1;
return 0;
} );
function filterModels(models, capability) {
if (!capability) return models;
return models.filter(function (m) {
return m.capabilities && m.capabilities.indexOf(capability) !== -1;
});
}
/**
@@ -125,11 +83,11 @@
* @param {number} price Price per 1M tokens.
* @return {string} Formatted string like "$0.25" or "Free".
*/
function formatPrice( price ) {
if ( ! price || price <= 0 ) return 'Free';
if ( price < 0.01 ) return '$' + price.toFixed( 4 );
if ( price < 1 ) return '$' + price.toFixed( 2 );
return '$' + price.toFixed( 2 );
function formatPrice(price) {
if (!price || price <= 0) return 'Free';
if (price < 0.01) return '$' + price.toFixed(4);
if (price < 1) return '$' + price.toFixed(2);
return '$' + price.toFixed(2);
}
/**
@@ -138,10 +96,10 @@
* @param {number} ctx Context length in tokens.
* @return {string} Formatted string like "128K" or "1M".
*/
function formatContext( ctx ) {
if ( ! ctx ) return '—';
if ( ctx >= 1000000 ) return ( ctx / 1000000 ).toFixed( 0 ) + 'M';
if ( ctx >= 1000 ) return Math.round( ctx / 1000 ) + 'K';
function formatContext(ctx) {
if (!ctx) return '—';
if (ctx >= 1000000) return (ctx / 1000000).toFixed(0) + 'M';
if (ctx >= 1000) return Math.round(ctx / 1000) + 'K';
return ctx.toString();
}
@@ -151,47 +109,45 @@
* @param {Object} model Normalized model record.
* @return {string} HTML string.
*/
function renderModelRow( model ) {
var deprecated = model.deprecated ? ' ab-mp-deprecated' : '';
function renderModelRow(model) {
var deprecated = model.deprecated ? ' ab-mp-deprecated' : '';
var isImageModel = model.cost_per_image !== undefined && model.cost_per_image > 0;
var priceHtml, priceTitle, metaRight;
if ( isImageModel ) {
priceHtml = '$' + model.cost_per_image.toFixed( 4 ) + '/image';
if (isImageModel) {
priceHtml = '$' + model.cost_per_image.toFixed(4) + '/image';
priceTitle = 'Cost per generated image';
metaRight = model.description
? '<span class="ab-mp-ctx" title="Details">' + escHtml( model.description ) + '</span>'
: '';
metaRight = model.description ? '<span class="ab-mp-ctx" title="Details">' + escHtml(model.description) + '</span>' : '';
} else {
priceHtml = formatPrice( model.input_price_per_m ) + ' / ' + formatPrice( model.output_price_per_m );
priceHtml = formatPrice(model.input_price_per_m) + ' / ' + formatPrice(model.output_price_per_m);
priceTitle = 'Input / Output per 1M tokens';
metaRight = '<span class="ab-mp-ctx" title="Context window">' + formatContext( model.context_length ) + '</span>';
metaRight = '<span class="ab-mp-ctx" title="Context window">' + formatContext(model.context_length) + '</span>';
}
return (
'<div class="ab-mp-row' + deprecated + '" data-model-id="' + escAttr( model.id ) + '">' +
'<div class="ab-mp-row' + deprecated + '" data-model-id="' + escAttr(model.id) + '">' +
'<div class="ab-mp-row-main">' +
'<span class="ab-mp-name">' + escHtml( model.name ) + '</span>' +
'<span class="ab-mp-provider">' + escHtml( model.provider ) + '</span>' +
( model.deprecated ? '<span class="ab-mp-dep-badge">deprecated</span>' : '' ) +
'<span class="ab-mp-name">' + escHtml(model.name) + '</span>' +
'<span class="ab-mp-provider">' + escHtml(model.provider) + '</span>' +
(model.deprecated ? '<span class="ab-mp-dep-badge">deprecated</span>' : '') +
'</div>' +
'<div class="ab-mp-row-meta">' +
metaRight +
'<span class="ab-mp-price" title="' + priceTitle + '">' + priceHtml + '</span>' +
metaRight +
'</div>' +
'</div>'
);
}
/** Minimal HTML escaping for display. */
function escHtml( str ) {
if ( ! str ) return '';
return str.replace( /&/g, '&amp;' ).replace( /</g, '&lt;' ).replace( />/g, '&gt;' );
function escHtml(str) {
if (!str) return '';
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
/** Escape a string for use in an HTML attribute. */
function escAttr( str ) {
return escHtml( str ).replace( /"/g, '&quot;' );
function escAttr(str) {
return escHtml(str).replace(/"/g, '&quot;');
}
/**
@@ -199,16 +155,16 @@
*
* @param {jQuery} $trigger The .ab-mp-trigger button that was clicked.
*/
function openPicker( $trigger ) {
var fieldId = $trigger.data( 'field-id' );
var capability = $trigger.data( 'capability' ) || '';
function openPicker($trigger) {
var fieldId = $trigger.data('field-id');
var capability = $trigger.data('capability') || '';
// Build overlay + popup structure.
var isImageCap = capability === 'image_generation';
var priceLabel = isImageCap ? 'Cost per generated image' : 'Prices per 1M tokens (in / out)';
// ── Build overlay + popup ───────────────────────────────────────
var $overlay = $( '<div class="ab-mp-overlay"></div>' );
var $popup = $(
var $overlay = $('<div class="ab-mp-overlay"></div>');
var $popup = $(
'<div class="ab-mp-popup">' +
'<div class="ab-mp-header">' +
'<span class="ab-mp-title">Select Model</span>' +
@@ -217,13 +173,6 @@
'<div class="ab-mp-search-wrap">' +
'<input type="text" class="ab-mp-search" placeholder="Search models…" autocomplete="off" />' +
'</div>' +
'<div class="ab-mp-col-headers">' +
'<button type="button" class="ab-mp-col-header ab-mp-col-model" data-col="name">Model <span class="ab-mp-sort-arrow"></span></button>' +
'<div class="ab-mp-col-headers-meta">' +
'<button type="button" class="ab-mp-col-header ab-mp-col-ctx" data-col="context">Context <span class="ab-mp-sort-arrow"></span></button>' +
'<button type="button" class="ab-mp-col-header ab-mp-col-price" data-col="price">Price (in / out) <span class="ab-mp-sort-arrow"></span></button>' +
'</div>' +
'</div>' +
'<div class="ab-mp-list"><div class="ab-mp-loading">Loading models…</div></div>' +
'<div class="ab-mp-footer">' +
'<span class="ab-mp-count"></span>' +
@@ -232,132 +181,105 @@
'</div>'
);
$overlay.append( $popup );
$( 'body' ).append( $overlay );
$overlay.append($popup);
$('body').append($overlay);
var $search = $popup.find( '.ab-mp-search' );
var $list = $popup.find( '.ab-mp-list' );
var $count = $popup.find( '.ab-mp-count' );
var $colHeaders = $popup.find( '.ab-mp-col-headers' );
var allModels = [];
var currentQuery = '';
var $search = $popup.find('.ab-mp-search');
var $list = $popup.find('.ab-mp-list');
var $count = $popup.find('.ab-mp-count');
var allModels = [];
// Focus search after render.
setTimeout( function () { $search.focus(); }, 50 );
setTimeout(function () { $search.focus(); }, 50);
// ── Sort header indicators ──────────────────────────────────────
/** Update active-column highlight and sort arrow glyphs. */
function updateSortHeaders() {
$colHeaders.find( '.ab-mp-col-header' ).each( function () {
var col = $( this ).data( 'col' );
var $arrow = $( this ).find( '.ab-mp-sort-arrow' );
if ( col === sortState.col ) {
$( this ).addClass( 'ab-mp-col-active' );
$arrow.text( sortState.dir === 'asc' ? ' ▲' : ' ▼' );
} else {
$( this ).removeClass( 'ab-mp-col-active' );
$arrow.text( ' ⇅' );
}
} );
}
// Fetch and render model list.
fetchModels(capability).then(function (models) {
allModels = models;
renderList(models, '');
});
// ── Render ──────────────────────────────────────────────────────
/** Render filtered + sorted model list. */
function renderList( models, query ) {
/** Render filtered model list. */
function renderList(models, query) {
var filtered = models;
if ( query ) {
if (query) {
var q = query.toLowerCase();
filtered = models.filter( function ( m ) {
return ( m.name && m.name.toLowerCase().indexOf( q ) !== -1 ) ||
( m.id && m.id.toLowerCase().indexOf( q ) !== -1 ) ||
( m.provider && m.provider.toLowerCase().indexOf( q ) !== -1 );
} );
filtered = models.filter(function (m) {
return (m.name && m.name.toLowerCase().indexOf(q) !== -1) ||
(m.id && m.id.toLowerCase().indexOf(q) !== -1) ||
(m.provider && m.provider.toLowerCase().indexOf(q) !== -1);
});
}
filtered = applySort( filtered );
// Sort: non-deprecated first, then by provider + name.
filtered.sort(function (a, b) {
if (a.deprecated !== b.deprecated) return a.deprecated ? 1 : -1;
var pa = (a.provider || '').toLowerCase();
var pb = (b.provider || '').toLowerCase();
if (pa !== pb) return pa < pb ? -1 : 1;
return (a.name || '').toLowerCase().localeCompare((b.name || '').toLowerCase());
});
if ( filtered.length === 0 ) {
$list.html( '<div class="ab-mp-empty">No models found.</div>' );
if (filtered.length === 0) {
$list.html('<div class="ab-mp-empty">No models found.</div>');
} else {
var html = '';
for ( var i = 0; i < filtered.length; i++ ) {
html += renderModelRow( filtered[ i ] );
for (var i = 0; i < filtered.length; i++) {
html += renderModelRow(filtered[i]);
}
$list.html( html );
$list.html(html);
}
$count.text( filtered.length + ' model' + ( filtered.length !== 1 ? 's' : '' ) );
updateSortHeaders();
$count.text(filtered.length + ' model' + (filtered.length !== 1 ? 's' : ''));
}
// Initial render after data loads.
fetchModels( capability ).then( function ( models ) {
allModels = models;
renderList( allModels, currentQuery );
} );
// ── Column header sort clicks ───────────────────────────────────
$colHeaders.on( 'click', '.ab-mp-col-header', function () {
var col = $( this ).data( 'col' );
if ( sortState.col === col ) {
sortState.dir = sortState.dir === 'asc' ? 'desc' : 'asc';
} else {
sortState.col = col;
sortState.dir = 'asc';
}
renderList( allModels, currentQuery );
} );
// ── Search (debounced) ──────────────────────────────────────────
// Search input handler (debounced).
var searchTimer = null;
$search.on( 'input', function () {
currentQuery = $( this ).val();
clearTimeout( searchTimer );
searchTimer = setTimeout( function () {
renderList( allModels, currentQuery );
}, 150 );
} );
$search.on('input', function () {
var q = $(this).val();
clearTimeout(searchTimer);
searchTimer = setTimeout(function () {
renderList(allModels, q);
}, 150);
});
// ── Select a model ──────────────────────────────────────────────
$list.on( 'click', '.ab-mp-row', function () {
var id = $( this ).data( 'model-id' );
var model = null;
for ( var i = 0; i < allModels.length; i++ ) {
if ( allModels[ i ].id === id ) { model = allModels[ i ]; break; }
}
if ( ! model ) return;
// Select a model.
$list.on('click', '.ab-mp-row', function () {
var id = $(this).data('model-id');
var model = allModels.find(function (m) { return m.id === id; });
if (!model) return;
$( '#' + fieldId ).val( model.id );
$trigger.find( '.ab-mp-display-name' ).text( model.name || model.id );
// Update hidden input + display.
$('#' + fieldId).val(model.id);
$trigger.find('.ab-mp-display-name').text(model.name || model.id);
var isImageModel = model.cost_per_image !== undefined && model.cost_per_image > 0;
var priceText = isImageModel
? '$' + model.cost_per_image.toFixed( 4 ) + '/image'
: formatPrice( model.input_price_per_m ) + ' / ' + formatPrice( model.output_price_per_m );
$trigger.find( '.ab-mp-display-price' ).text( priceText );
var priceText = isImageModel
? '$' + model.cost_per_image.toFixed(4) + '/image'
: formatPrice(model.input_price_per_m) + ' / ' + formatPrice(model.output_price_per_m);
$trigger.find('.ab-mp-display-price').text(priceText);
closePicker();
} );
});
// ── Close ───────────────────────────────────────────────────────
// Close handlers.
function closePicker() {
$overlay.remove();
}
$popup.find( '.ab-mp-close' ).on( 'click', closePicker );
$overlay.on( 'click', function ( e ) {
if ( $( e.target ).is( '.ab-mp-overlay' ) ) closePicker();
} );
$( document ).on( 'keydown.abModelPicker', function ( e ) {
if ( e.key === 'Escape' ) {
$popup.find('.ab-mp-close').on('click', closePicker);
$overlay.on('click', function (e) {
if ($(e.target).is('.ab-mp-overlay')) closePicker();
});
$(document).on('keydown.abModelPicker', function (e) {
if (e.key === 'Escape') {
closePicker();
$( document ).off( 'keydown.abModelPicker' );
$(document).off('keydown.abModelPicker');
}
} );
});
}
// Bind click on all model picker triggers.
$( document ).on( 'click', '.ab-mp-trigger', function ( e ) {
$(document).on('click', '.ab-mp-trigger', function (e) {
e.preventDefault();
openPicker( $( this ) );
} );
openPicker($(this));
});
} )( jQuery );
})(jQuery);

View File

@@ -1,142 +0,0 @@
[
{
"id": "bpc157-healing",
"topic": "BPC-157 healing protocols for tendons and gut lining",
"expected_keywords": ["BPC-157", "tendon", "gut", "healing"],
"min_words": 700,
"style": "comic"
},
{
"id": "tb500-muscle-recovery",
"topic": "TB-500 for accelerated muscle recovery and repair",
"expected_keywords": ["TB-500", "muscle", "recovery", "growth"],
"min_words": 700,
"style": "comic"
},
{
"id": "ghk-cu-skin-collagen",
"topic": "GHK-Cu peptide for skin collagen synthesis and anti-aging",
"expected_keywords": ["GHK-Cu", "collagen", "skin", "aging"],
"min_words": 700,
"style": "comic"
},
{
"id": "semaglutide-glp1-weight",
"topic": "GLP-1 receptor agonists like Semaglutide for metabolic health",
"expected_keywords": ["Semaglutide", "GLP-1", "weight", "metabolism"],
"min_words": 700,
"style": "comic"
},
{
"id": "ipamorelin-growth-hormone",
"topic": "Ipamorelin for natural growth hormone stimulation and recovery",
"expected_keywords": ["Ipamorelin", "growth hormone", "HGH", "secretagogue"],
"min_words": 700,
"style": "comic"
},
{
"id": "hexarelin-strength-gains",
"topic": "Hexarelin peptide for lean muscle and strength improvement",
"expected_keywords": ["Hexarelin", "muscle", "strength", "lean"],
"min_words": 700,
"style": "comic"
},
{
"id": "semax-cognitive-enhancement",
"topic": "Semax nootropic peptide for cognitive function and focus",
"expected_keywords": ["Semax", "cognition", "focus", "neuroprotection"],
"min_words": 700,
"style": "comic"
},
{
"id": "selank-anxiety-stress",
"topic": "Selank peptide for anxiety reduction and stress management",
"expected_keywords": ["Selank", "anxiety", "stress", "mood"],
"min_words": 700,
"style": "comic"
},
{
"id": "oxytocin-social-bonding",
"topic": "Oxytocin peptide hormone and its role in social connection",
"expected_keywords": ["Oxytocin", "social", "bonding", "neuropeptide"],
"min_words": 700,
"style": "comic"
},
{
"id": "kisspeptin-fertility-hormone",
"topic": "Kisspeptin's role in reproductive health and hormone signaling",
"expected_keywords": ["Kisspeptin", "fertility", "hormone", "reproduction"],
"min_words": 700,
"style": "comic"
},
{
"id": "melanotan-tanning-peptide",
"topic": "Melanotan peptide for pigmentation and UV protection",
"expected_keywords": ["Melanotan", "melanin", "tanning", "skin"],
"min_words": 700,
"style": "comic"
},
{
"id": "cerebrolysin-neuroprotection",
"topic": "Cerebrolysin for brain health and neuroprotection",
"expected_keywords": ["Cerebrolysin", "brain", "neuroprotection", "cognition"],
"min_words": 700,
"style": "comic"
},
{
"id": "epithalon-telomerase-aging",
"topic": "Epithalon peptide and telomerase activation for longevity",
"expected_keywords": ["Epithalon", "telomerase", "aging", "longevity"],
"min_words": 700,
"style": "comic"
},
{
"id": "thymosin-immune-function",
"topic": "Thymosin alpha-1 for immune system enhancement",
"expected_keywords": ["Thymosin", "immune", "T-cells", "immunity"],
"min_words": 700,
"style": "comic"
},
{
"id": "igf1-muscle-growth-aging",
"topic": "IGF-1 peptide for muscle growth, recovery, and anti-aging",
"expected_keywords": ["IGF-1", "muscle", "growth", "aging"],
"min_words": 700,
"style": "comic"
},
{
"id": "mechano-growth-factor",
"topic": "MGF (Mechano Growth Factor) for muscle hypertrophy",
"expected_keywords": ["MGF", "mechano", "muscle", "hypertrophy"],
"min_words": 700,
"style": "comic"
},
{
"id": "ll37-antimicrobial-peptide",
"topic": "LL-37 antimicrobial peptide for immune and skin health",
"expected_keywords": ["LL-37", "antimicrobial", "immune", "peptide"],
"min_words": 700,
"style": "comic"
},
{
"id": "lactoferrin-iron-immunity",
"topic": "Lactoferrin peptide for iron absorption and immune support",
"expected_keywords": ["Lactoferrin", "iron", "immune", "absorption"],
"min_words": 700,
"style": "comic"
},
{
"id": "collagen-peptides-joints",
"topic": "Collagen peptides for joint health and connective tissue repair",
"expected_keywords": ["Collagen", "peptides", "joints", "connective tissue"],
"min_words": 700,
"style": "comic"
},
{
"id": "ckgp-cognitive-longevity",
"topic": "Cognitive peptides and nootropic stacks for brain longevity",
"expected_keywords": ["peptide", "cognitive", "nootropic", "brain"],
"min_words": 700,
"style": "comic"
}
]

8
includes/admin/class-admin-page.php Normal file → Executable file
View File

@@ -62,7 +62,6 @@ class PRAutoBlogger_Admin_Page {
public function on_enqueue_assets( string $hook_suffix ): void {
$pages = array(
'toplevel_page_' . self::PAGE_SLUG,
'prautoblogger_page_prautoblogger-board',
'prautoblogger_page_prautoblogger-metrics',
'prautoblogger_page_prautoblogger-review-queue',
'prautoblogger_page_prautoblogger-ideas',
@@ -324,18 +323,13 @@ class PRAutoBlogger_Admin_Page {
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', 'prautoblogger_board_poll_interval', 'prautoblogger_board_published_window_days' );
$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' );
if ( in_array( $option_name, $numeric, true ) ) {
return is_numeric( $value ) ? $value : 0;
}
if ( 'prautoblogger_image_model' === $option_name ) {
return $this->sanitize_image_model( (string) $value );
}
if ( 'prautoblogger_image_style_template' === $option_name ) {
// Multi-line template: validation + textarea-safe sanitisation
// (incl. the single-token check, brief A5) lives in the filler.
return PRAutoBlogger_Image_Template_Filler::sanitize_for_save( (string) $value );
}
return sanitize_text_field( (string) $value );
}

View File

@@ -1,230 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Supplies card data for the kanban board page from existing DB tables.
*
* Orchestrates the four board columns:
* Generating | In Review | Published | Failed
*
* Generation-log queries (Generating, Failed) are delegated to
* PRAutoBlogger_Board_Gen_Log_Query. WP_Query columns (In Review, Published)
* are handled here.
*
* M2: cards now include `dossier_url` so board.js can deep-link to the
* Article Dossier instead of the old per-column destinations.
*
* No schema changes -- all data comes from tables that already exist.
*
* Triggered by: PRAutoBlogger_Board_Page::on_ajax_board_status().
* Dependencies: PRAutoBlogger_Board_Gen_Log_Query, PRAutoBlogger_Dossier_Page,
* WordPress WP_Query, get_option().
*
* @see admin/class-board-gen-log-query.php -- Raw gen_log queries (Generating/Failed).
* @see admin/class-board-page.php -- Calls get_board_snapshot().
* @see admin/class-dossier-page.php -- Provides url_for_post() for deep-links.
* @see ARCHITECTURE.md -- Database schema.
*/
class PRAutoBlogger_Board_Data_Provider {
/** @var PRAutoBlogger_Board_Gen_Log_Query Handles raw gen_log DB queries. */
private PRAutoBlogger_Board_Gen_Log_Query $gen_log_query;
/**
* @param PRAutoBlogger_Board_Gen_Log_Query|null $gen_log_query Optional injection for testing.
*/
public function __construct( ?PRAutoBlogger_Board_Gen_Log_Query $gen_log_query = null ) {
$this->gen_log_query = $gen_log_query ?? new PRAutoBlogger_Board_Gen_Log_Query();
}
/**
* Return the full board snapshot consumed by the AJAX poller.
*
* @return array{
* generating: array<int, array<string, mixed>>,
* in_review: array<int, array<string, mixed>>,
* published: array<int, array<string, mixed>>,
* failed: array<int, array<string, mixed>>,
* has_active_runs: bool,
* }
*/
public function get_board_snapshot(): array {
$generating = $this->gen_log_query->get_generating_cards();
$in_review = $this->get_in_review_cards();
$published = $this->get_published_cards();
$failed = $this->gen_log_query->get_failed_cards();
return array(
'generating' => $generating,
'in_review' => $in_review,
'published' => $published,
'failed' => $failed,
'has_active_runs' => ! empty( $generating ),
);
}
/**
* Cards for runs that are currently in-progress.
*
* @return array<int, array<string, mixed>>
*/
public function get_generating_cards(): array {
return $this->gen_log_query->get_generating_cards();
}
/**
* Cards for generation runs that ended in an error state.
*
* @return array<int, array<string, mixed>>
*/
public function get_failed_cards(): array {
return $this->gen_log_query->get_failed_cards();
}
/**
* Cards for generated draft posts awaiting human review.
* M2: cards include dossier_url for deep-linking.
*
* @return array<int, array<string, mixed>>
*/
public function get_in_review_cards(): array {
$query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'draft',
'posts_per_page' => 20,
'meta_query' => array(
array(
'key' => '_prautoblogger_generated',
'value' => '1',
),
),
'orderby' => 'date',
'order' => 'DESC',
)
);
$cards = array();
foreach ( $query->posts as $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
continue;
}
$run_id = (string) get_post_meta( $post->ID, '_prautoblogger_run_id', true );
$cost_total = (float) get_post_meta( $post->ID, '_prautoblogger_total_cost', true );
$cards[] = array(
'run_id' => $run_id,
'post_id' => $post->ID,
'title' => $post->post_title,
'cost_total' => $cost_total,
'created_at' => strtotime( $post->post_date_gmt ),
'click_action' => 'dossier',
'dossier_url' => PRAutoBlogger_Dossier_Page::url_for_post( $post->ID ),
'review_url' => admin_url( 'admin.php?page=prautoblogger-review-queue' ),
'edit_url' => get_edit_post_link( $post->ID, 'raw' ),
);
}
return $this->flag_human_modified( $cards );
}
/**
* Cards for published posts within the configured window.
* M2: cards include dossier_url for deep-linking.
*
* @return array<int, array<string, mixed>>
*/
public function get_published_cards(): array {
$window_days = max( 1, (int) get_option( 'prautoblogger_board_published_window_days', 7 ) );
$date_after = gmdate( 'Y-m-d H:i:s', time() - ( $window_days * DAY_IN_SECONDS ) );
$query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 20,
'date_query' => array(
array(
'after' => $date_after,
'inclusive' => true,
),
),
'meta_query' => array(
array(
'key' => '_prautoblogger_generated',
'value' => '1',
),
),
'orderby' => 'date',
'order' => 'DESC',
)
);
$cards = array();
foreach ( $query->posts as $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
continue;
}
$run_id = (string) get_post_meta( $post->ID, '_prautoblogger_run_id', true );
$cost_total = (float) get_post_meta( $post->ID, '_prautoblogger_total_cost', true );
$cards[] = array(
'run_id' => $run_id,
'post_id' => $post->ID,
'title' => $post->post_title,
'cost_total' => $cost_total,
'published_at' => strtotime( $post->post_date_gmt ),
'click_action' => 'dossier',
'dossier_url' => PRAutoBlogger_Dossier_Page::url_for_post( $post->ID ),
'edit_url' => get_edit_post_link( $post->ID, 'raw' ),
'post_url' => get_permalink( $post->ID ),
);
}
return $this->flag_human_modified( $cards );
}
/**
* Set 'human_modified' on each card in ONE batched query (v0.20.0 —
* CPO product AC: human-modified runs are visually distinct at the
* run-list level). No per-card queries; self-healing on a missing
* table/column (flag simply stays false).
*
* @param array<int, array<string, mixed>> $cards Column cards.
* @return array<int, array<string, mixed>> Cards with the flag set.
*/
private function flag_human_modified( array $cards ): array {
$run_ids = array();
foreach ( $cards as $i => $card ) {
$cards[ $i ]['human_modified'] = false;
if ( ! empty( $card['run_id'] ) ) {
$run_ids[] = (string) $card['run_id'];
}
}
if ( empty( $run_ids ) || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return $cards;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$placeholders = implode( ',', array_fill( 0, count( $run_ids ), '%s' ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is a fixed %s list.
$flagged = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT run_id FROM {$table} WHERE human_modified = 1 AND run_id IN ({$placeholders})",
$run_ids
)
);
if ( ! is_array( $flagged ) || empty( $flagged ) ) {
return $cards;
}
$flagged = array_flip( array_map( 'strval', $flagged ) );
foreach ( $cards as $i => $card ) {
if ( isset( $flagged[ (string) ( $card['run_id'] ?? '' ) ] ) ) {
$cards[ $i ]['human_modified'] = true;
}
}
return $cards;
}
}

View File

@@ -1,184 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Raw generation-log queries for the kanban board.
*
* Extracted from PRAutoBlogger_Board_Data_Provider to stay under the 300-line
* cap. Handles the two columns that read directly from prab_generation_log:
* Generating (in-progress runs) | Failed (error runs with no linked post)
*
* No schema changes — data comes from prab_generation_log which already exists.
*
* Triggered by: PRAutoBlogger_Board_Data_Provider::get_generating_cards()
* PRAutoBlogger_Board_Data_Provider::get_failed_cards()
* Dependencies: WordPress $wpdb, get_transient().
*
* @see admin/class-board-data-provider.php — Orchestrator that calls this class.
* @see ARCHITECTURE.md — Database schema (generation_log).
*/
class PRAutoBlogger_Board_Gen_Log_Query {
/** Seconds of gen-log inactivity after which a run is no longer "generating". */
public const GENERATING_GRACE_SECONDS = 1800;
/** Transient key written by PRAutoBlogger_Executor for the active generation run. */
public const STATUS_TRANSIENT = 'prautoblogger_generation_status';
/**
* Cards for runs that are currently in-progress.
*
* Detection strategy: check the generation status transient first (authoritative
* for the active manual-run or daily-cron run), then fall back to recent gen_log
* run_ids that have no associated published/draft post yet.
*
* @return array<int, array<string, mixed>>
*/
public function get_generating_cards(): array {
global $wpdb;
$cards = array();
// Primary: check if the executor transient signals an active run.
$status = get_transient( self::STATUS_TRANSIENT );
if ( is_array( $status ) && 'running' === ( $status['status'] ?? '' ) ) {
$cards[] = array(
'run_id' => '',
'post_id' => 0,
'title' => $status['stage'] ?? __( 'Generating…', 'prautoblogger' ),
'cost_total' => 0.0,
'stage_current' => $status['stage'] ?? '',
'stage_count' => 0,
'started_at' => $status['started'] ?? 0,
'click_action' => 'logs',
'log_url' => admin_url( 'admin.php?page=prautoblogger-logs' ),
);
}
// Secondary: runs in gen_log that are recent and have no linked post.
$table = $wpdb->prefix . 'prautoblogger_generation_log';
$since = gmdate( 'Y-m-d H:i:s', time() - self::GENERATING_GRACE_SECONDS );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$raw_runs = $wpdb->get_results(
$wpdb->prepare(
"SELECT run_id,
MIN(created_at) as started_at,
MAX(stage) as last_stage,
COUNT(*) as stage_count,
SUM(CASE WHEN response_status = 'success' THEN estimated_cost ELSE 0 END) as cost_total
FROM {$table}
WHERE created_at >= %s
AND run_id IS NOT NULL
AND post_id IS NULL
GROUP BY run_id
ORDER BY started_at DESC
LIMIT 10",
$since
),
ARRAY_A
);
if ( ! is_array( $raw_runs ) ) {
return $cards;
}
foreach ( $raw_runs as $row ) {
$run_id = (string) $row['run_id'];
if ( '' === $run_id ) {
continue;
}
// Skip if we already have a transient card (avoid duplicate).
if ( ! empty( $cards ) && '' === $cards[0]['run_id'] ) {
// Only add secondary cards if we have a real run_id.
// The transient card already covers the active run.
}
$cards[] = array(
'run_id' => $run_id,
'post_id' => 0,
'title' => sprintf(
/* translators: %s: pipeline stage name */
__( 'Generating — %s', 'prautoblogger' ),
esc_html( ucfirst( (string) $row['last_stage'] ) )
),
'cost_total' => round( (float) $row['cost_total'], 6 ),
'stage_current' => (string) $row['last_stage'],
'stage_count' => (int) $row['stage_count'],
'started_at' => strtotime( (string) $row['started_at'] ),
'click_action' => 'logs',
'log_url' => admin_url( 'admin.php?page=prautoblogger-logs' ),
);
}
return $cards;
}
/**
* Cards for generation runs that ended in an error state.
*
* Looks for recent gen_log rows with response_status='error' that have
* no corresponding published post — these are pipeline failures.
*
* @return array<int, array<string, mixed>>
*/
public function get_failed_cards(): array {
global $wpdb;
$table = $wpdb->prefix . 'prautoblogger_generation_log';
$since = gmdate( 'Y-m-d H:i:s', time() - ( 7 * DAY_IN_SECONDS ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$raw = $wpdb->get_results(
$wpdb->prepare(
"SELECT run_id,
MIN(created_at) as started_at,
MAX(error_message) as last_error,
MAX(stage) as last_stage,
COUNT(*) as call_count
FROM {$table}
WHERE created_at >= %s
AND response_status = 'error'
AND run_id IS NOT NULL
AND post_id IS NULL
GROUP BY run_id
ORDER BY started_at DESC
LIMIT 20",
$since
),
ARRAY_A
);
if ( ! is_array( $raw ) ) {
return array();
}
$cards = array();
foreach ( $raw as $row ) {
$run_id = (string) $row['run_id'];
if ( '' === $run_id ) {
continue;
}
$cards[] = array(
'run_id' => $run_id,
'post_id' => 0,
'title' => sprintf(
/* translators: %s: pipeline stage name */
__( 'Failed — %s', 'prautoblogger' ),
esc_html( ucfirst( (string) $row['last_stage'] ) )
),
'error_message' => (string) $row['last_error'],
'started_at' => strtotime( (string) $row['started_at'] ),
'click_action' => 'logs',
'log_url' => admin_url( 'admin.php?page=prautoblogger-logs' ),
);
}
return $cards;
}
}

View File

@@ -1,183 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Registers and renders the kanban board — the primary landing screen for PRAutoBlogger.
*
* Board columns: Generating | In Review | Published | Failed.
* Cards live-update via AJAX polling at a settings-backed interval (default 5s),
* backing off to 2× when no active generating run is detected.
*
* Card click-throughs (M1):
* - Generating → Activity Log filtered to run context
* - In Review → Review Queue
* - Published → Post edit screen
* - Failed → Activity Log
*
* M2 will rewire all click-throughs to the Article Dossier page.
*
* Triggered by: PRAutoBlogger::register_admin_hooks() on `admin_menu`.
* Dependencies: PRAutoBlogger_Board_Data_Provider, wp_localize_script.
*
* @see admin/class-board-data-provider.php — Supplies card data.
* @see templates/admin/board-page.php — HTML template.
* @see assets/js/board.js — Polling + DOM updates.
* @see ARCHITECTURE.md — §Board (kanban dashboard).
*/
class PRAutoBlogger_Board_Page {
private const PAGE_SLUG = 'prautoblogger-board';
/** AJAX action name for board polling. */
public const AJAX_ACTION = 'prautoblogger_board_status';
/** Nonce action string for board AJAX. */
public const NONCE_ACTION = 'prautoblogger_board';
/**
* Register the Board as the PRIMARY (first) submenu item, overriding the
* implicit Settings landing page. The trick is: WordPress auto-generates a
* submenu duplicate of the top-level page; we name it "Board" so the
* first click goes to the board, not the raw settings page.
*
* Registration order note: this method is hooked at admin_menu priority 11
* so that PRAutoBlogger_Admin_Page::on_register_menu() (priority 10) has
* already called add_menu_page(). This ensures WordPress has populated
* $admin_page_hooks['prautoblogger-settings'] before add_submenu_page()
* runs here, so get_plugin_page_hookname() resolves to the correct
* 'prautoblogger_page_prautoblogger-board' suffix rather than the fallback
* 'admin_page_prautoblogger-board'. See ARCHITECTURE.md §Board.
*
* @return void
*/
public function on_register_menu(): void {
// Override the auto-created "PRAutoBlogger" submenu entry with "Board".
add_submenu_page(
'prautoblogger-settings',
__( 'PRAutoBlogger Board', 'prautoblogger' ),
__( 'Board', 'prautoblogger' ),
'manage_options',
self::PAGE_SLUG,
array( $this, 'render_page' )
);
// Reorder submenu so Board is the FIRST entry (primary click target).
// WordPress auto-appended a duplicate of the top-level page as submenu
// index 0; our Board was appended at index 1. We swap them so the
// top-level PRAutoBlogger click lands on the Board page, not Settings.
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- intentional submenu reorder.
global $submenu;
if ( isset( $submenu['prautoblogger-settings'] ) ) {
$items = $submenu['prautoblogger-settings'];
// Find the Board entry and move it to position 0.
$board_idx = null;
foreach ( $items as $i => $item ) {
if ( isset( $item[2] ) && self::PAGE_SLUG === $item[2] ) {
$board_idx = $i;
break;
}
}
if ( null !== $board_idx && $board_idx > 0 ) {
$board_item = $items[ $board_idx ];
unset( $items[ $board_idx ] );
// Prepend board item at position 0 while preserving remaining order.
$submenu['prautoblogger-settings'] = array_merge( array( $board_item ), array_values( $items ) );
}
}
}
/**
* Render the board page.
*
* @return void
*/
public function render_page(): void {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
include PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/board-page.php';
}
/**
* Enqueue board-specific JS + CSS and localize the poller config.
*
* Called via `admin_enqueue_scripts` action, gated to this page's hook suffix.
*
* @param string $hook_suffix Current admin page hook suffix.
* @return void
*/
public function on_enqueue_assets( string $hook_suffix ): void {
$board_hook = 'prautoblogger_page_' . self::PAGE_SLUG;
if ( $hook_suffix !== $board_hook ) {
return;
}
wp_enqueue_style(
'prautoblogger-board',
PRAUTOBLOGGER_PLUGIN_URL . 'assets/css/board.css',
array( 'prautoblogger-admin' ),
PRAUTOBLOGGER_VERSION
);
wp_enqueue_script(
'prautoblogger-board',
PRAUTOBLOGGER_PLUGIN_URL . 'assets/js/board.js',
array( 'jquery' ),
PRAUTOBLOGGER_VERSION,
true
);
$poll_interval = max( 3, (int) get_option( 'prautoblogger_board_poll_interval', 5 ) );
$published_days = max( 1, (int) get_option( 'prautoblogger_board_published_window_days', 7 ) );
wp_localize_script(
'prautoblogger-board',
'prabBoard',
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( self::NONCE_ACTION ),
'pollInterval' => $poll_interval * 1000,
'publishedWindowDays' => $published_days,
'action' => self::AJAX_ACTION,
'strings' => array(
'generating' => __( 'Generating', 'prautoblogger' ),
'inReview' => __( 'In Review', 'prautoblogger' ),
'published' => __( 'Published', 'prautoblogger' ),
'failed' => __( 'Failed', 'prautoblogger' ),
'empty' => __( 'Nothing here yet.', 'prautoblogger' ),
'cost' => __( 'Cost', 'prautoblogger' ),
'view' => __( 'View', 'prautoblogger' ),
'edit' => __( 'Edit', 'prautoblogger' ),
'viewLog' => __( 'View Log', 'prautoblogger' ),
'pollError' => __( 'Board update failed — retrying.', 'prautoblogger' ),
'humanModified' => __( 'Human-modified', 'prautoblogger' ),
),
)
);
}
/**
* AJAX handler: return the current board snapshot (all four columns).
*
* Nonce: `prautoblogger_board`. Requires `manage_options` capability.
*
* Side effects: DB reads only — no writes.
*
* @return void
*/
public function on_ajax_board_status(): void {
check_ajax_referer( self::NONCE_ACTION, 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
return;
}
$provider = new PRAutoBlogger_Board_Data_Provider();
$snapshot = $provider->get_board_snapshot();
wp_send_json_success( $snapshot );
}
}

View File

@@ -1,299 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* AJAX endpoints for the dossier's edit + re-run actions (v0.20.0, M3).
*
* What: Four manage_options + nonce gated endpoints. The mutation
* endpoints follow the chained-cron contract strictly: save_input
* only INSERTs an immutable fork version; the two rerun endpoints
* only validate + queue (Rerun_Job_Support::queue) — execution and
* ALL run/stage state mutations happen in the cron handler after
* re-validation under the generation lock. Run identity (run_id /
* item_key) is always derived server-side from the post's meta —
* never trusted from the client; the client only names the stage
* row it acted on, which is validated against an existing row.
* stage_status is the read-only poll the dossier JS uses to show
* queued -> pickup -> result.
* Who triggers it: assets/js/dossier-edit.js via admin-ajax.php;
* registered in class-prautoblogger.php.
* Dependencies: Rerun_Eligibility, Stage_Input_Store, Stage_Replay
* (decode), Rerun_Job_Support/Executor, Run_Stage_State.
*
* @see assets/js/dossier-edit.js — The frontend caller.
* @see core/class-rerun-executor.php — The cron handlers jobs land in.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Dossier_Actions {
/** Nonce action shared by all four endpoints. */
public const NONCE_ACTION = 'prautoblogger_dossier_actions';
/**
* AJAX: save an edited stage input as a new immutable fork version.
*
* The fork body is the stage's base request (latest fork, else the
* recorded request_json) with ONLY the message contents substituted —
* roles, message count, model and call options are not editable, so
* a fork is always a well-formed replayable chat body. Prompt text
* is stored raw (it is LLM input, never rendered unescaped).
*
* Side effects: one stage_inputs INSERT.
*
* @return void Sends JSON.
*/
public function on_save_input(): void {
$request = $this->authorize_and_resolve();
$check = PRAutoBlogger_Rerun_Eligibility::check( $request['run_id'], $request['post_id'] );
if ( ! PRAutoBlogger_Rerun_Eligibility::is_editable_stage( $request['stage'] ) || ! $check['ok'] ) {
$reason = $check['ok'] ? __( 'This stage cannot be replayed with an edited input.', 'prautoblogger' ) : $check['reason'];
wp_send_json_error( array( 'message' => $reason ), 400 );
return;
}
$base_body = $this->resolve_base_body( $request );
if ( null === $base_body ) {
wp_send_json_error( array( 'message' => __( 'No persisted input exists for this stage.', 'prautoblogger' ) ), 400 );
return;
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- raw prompt text for the LLM; structure-validated below, stored raw, escaped at render.
$raw = isset( $_POST['messages'] ) ? wp_unslash( (string) $_POST['messages'] ) : '';
$messages = json_decode( $raw, true );
$merged = $this->merge_messages( $base_body, is_array( $messages ) ? $messages : null );
if ( null === $merged ) {
wp_send_json_error( array( 'message' => __( 'Edited messages must match the original structure (same count and roles, non-empty contents).', 'prautoblogger' ) ), 400 );
return;
}
$user = wp_get_current_user();
$version = PRAutoBlogger_Stage_Input_Store::save_fork(
$request['run_id'],
$request['stage'],
$request['agent_role'],
$request['item_key'],
(string) wp_json_encode( $merged ),
(string) $user->user_login
);
if ( null === $version ) {
wp_send_json_error( array( 'message' => __( 'The edited input could not be saved.', 'prautoblogger' ) ), 500 );
return;
}
wp_send_json_success(
array(
'version' => $version,
'message' => sprintf(
/* translators: %d: fork version number. */
__( 'Saved as version %d. The original input is preserved unchanged; re-running this stage will use your edited version and mark all downstream stages stale.', 'prautoblogger' ),
$version
),
)
);
}
/**
* AJAX: queue a single-stage replay of the latest edited fork.
*
* Validates, then ONLY schedules — chained-cron semantics. The UI
* copy never implies synchronous execution.
*
* @return void Sends JSON.
*/
public function on_rerun_stage(): void {
$request = $this->authorize_and_resolve();
$check = PRAutoBlogger_Rerun_Eligibility::check_replay(
$request['run_id'],
$request['post_id'],
$request['stage'],
$request['agent_role'],
$request['item_key']
);
if ( ! $check['ok'] ) {
wp_send_json_error( array( 'message' => $check['reason'] ), 400 );
return;
}
PRAutoBlogger_Rerun_Job_Support::queue(
PRAutoBlogger_Rerun_Executor::REPLAY_ACTION,
array( $request['run_id'], $request['post_id'], $request['stage'], $request['agent_role'], $request['item_key'] ),
sprintf(
/* translators: %s: stage display label. */
__( 'Queued: re-running %s with the edited input…', 'prautoblogger' ),
PRAutoBlogger_Stage_Display_Map::label( $request['stage'] )
)
);
wp_send_json_success(
array(
'queued' => true,
'message' => __( 'Re-run queued. The pipeline will pick it up shortly — progress appears here and on the board.', 'prautoblogger' ),
)
);
}
/**
* AJAX: queue re-run-from-here (rebuild this stage + downstream).
*
* @return void Sends JSON.
*/
public function on_rerun_from(): void {
$request = $this->authorize_and_resolve();
$check = PRAutoBlogger_Rerun_Eligibility::check_rebuild(
$request['run_id'],
$request['post_id'],
$request['stage'],
$request['item_key']
);
if ( ! $check['ok'] ) {
wp_send_json_error( array( 'message' => $check['reason'] ), 400 );
return;
}
PRAutoBlogger_Rerun_Job_Support::queue(
PRAutoBlogger_Rerun_Executor::REBUILD_ACTION,
array( $request['run_id'], $request['post_id'], $request['stage'], $request['item_key'] ),
sprintf(
/* translators: %s: stage display label. */
__( 'Queued: re-running the pipeline from %s…', 'prautoblogger' ),
PRAutoBlogger_Stage_Display_Map::label( $request['stage'] )
)
);
wp_send_json_success(
array(
'queued' => true,
'message' => __( 'Re-run from here queued. Stages will rebuild in sequence — progress appears here and on the board.', 'prautoblogger' ),
)
);
}
/**
* AJAX: read-only stage-status poll for the dossier.
*
* @return void Sends JSON: run status, per-stage state, live message.
*/
public function on_stage_status(): void {
$request = $this->authorize_and_resolve( false );
$stages = array();
foreach ( PRAutoBlogger_Run_Stage_State::stages_for_item( $request['run_id'], $request['item_key'] ) as $row ) {
$stages[] = array(
'stage' => (string) ( $row['stage'] ?? '' ),
'agent_role' => (string) ( $row['agent_role'] ?? '' ),
'status' => (string) ( $row['status'] ?? '' ),
'stale' => ! empty( $row['stale'] ),
'human_modified' => ! empty( $row['human_modified'] ),
'attempt' => (int) ( $row['attempt'] ?? 1 ),
'finished_at' => (string) ( $row['finished_at'] ?? '' ),
);
}
$live = get_transient( PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT );
wp_send_json_success(
array(
'run_status' => (string) ( PRAutoBlogger_Run_State::get_status( $request['run_id'] ) ?? '' ),
'stages' => $stages,
'live' => is_array( $live ) ? $live : null,
)
);
}
/**
* Shared gate: nonce + capability, then derive run identity from the
* POSTed post_id server-side. Sends a JSON error (and exits) on any
* failure.
*
* @param bool $require_stage Whether the request must name a stage row.
* @return array{post_id: int, run_id: string, item_key: string, stage: string, agent_role: string}
*/
private function authorize_and_resolve( bool $require_stage = true ): array {
check_ajax_referer( self::NONCE_ACTION, 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
}
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
$run_id = $post_id > 0 ? (string) get_post_meta( $post_id, '_prautoblogger_run_id', true ) : '';
if ( 0 === $post_id || '' === $run_id ) {
wp_send_json_error( array( 'message' => __( 'No generation run is recorded for this article.', 'prautoblogger' ) ), 400 );
}
$idea_hash = (string) get_post_meta( $post_id, '_prautoblogger_idea_hash', true );
$item_key = '' !== $idea_hash ? 'idea:' . $idea_hash : '';
$stage = isset( $_POST['stage'] ) ? sanitize_key( (string) wp_unslash( $_POST['stage'] ) ) : '';
$agent_role = isset( $_POST['agent_role'] ) ? sanitize_key( (string) wp_unslash( $_POST['agent_role'] ) ) : '';
if ( $require_stage && '' === $stage ) {
wp_send_json_error( array( 'message' => __( 'No stage specified.', 'prautoblogger' ) ), 400 );
}
return array(
'post_id' => $post_id,
'run_id' => $run_id,
'item_key' => $item_key,
'stage' => $stage,
'agent_role' => $agent_role,
);
}
/**
* The base body an edit forks from: latest saved fork, else the
* stage's recorded request_json.
*
* @param array<string, mixed> $request Resolved request context.
* @return array<string, mixed>|null Decoded body, or null when absent.
*/
private function resolve_base_body( array $request ): ?array {
$fork = PRAutoBlogger_Stage_Input_Store::latest_fork( $request['run_id'], $request['stage'], $request['agent_role'], $request['item_key'] );
if ( null !== $fork && ! empty( $fork['request_json'] ) ) {
return PRAutoBlogger_Stage_Replay::decode_body( (string) $fork['request_json'] );
}
$log_rows = ( new PRAutoBlogger_Dossier_Gen_Log_Query() )->get_by_run( $request['run_id'] );
$rows = $log_rows[ $request['stage'] ] ?? array();
foreach ( array_reverse( $rows ) as $row ) {
if ( ! empty( $row['request_json'] ) ) {
$body = PRAutoBlogger_Stage_Replay::decode_body( (string) $row['request_json'] );
if ( null !== $body ) {
return $body;
}
}
}
return null;
}
/**
* Substitute edited message contents into the base body. Structure
* is locked: same message count, same roles, all contents non-empty
* strings — so every fork stays a replayable chat body.
*
* @param array<string, mixed> $base Decoded base body.
* @param array<int, mixed>|null $messages Edited messages payload.
* @return array<string, mixed>|null Merged body, or null when invalid.
*/
private function merge_messages( array $base, ?array $messages ): ?array {
if ( null === $messages || count( $messages ) !== count( $base['messages'] ) ) {
return null;
}
$merged = $base;
foreach ( array_values( $messages ) as $i => $message ) {
if ( ! is_array( $message ) || ! isset( $message['role'], $message['content'] )
|| ! is_string( $message['role'] ) || ! is_string( $message['content'] ) ) {
return null;
}
if ( ( $base['messages'][ $i ]['role'] ?? null ) !== $message['role'] ) {
return null;
}
if ( '' === trim( $message['content'] ) ) {
return null;
}
$merged['messages'][ $i ]['content'] = $message['content'];
}
return $merged;
}
}

View File

@@ -1,275 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Assembles the view model for the Article Dossier page.
*
* Orchestrates 5 queries (all indexed by run_id or post_id):
* 1. wp_prautoblogger_runs -- run ledger row
* 2. wp_prautoblogger_run_stages -- all stage rows for the run
* 3. wp_prautoblogger_generation_log -- per-stage cost + raw trace
* 4. wp_prautoblogger_run_decisions -- rationale per stage
* 5. post meta (WP object cache) -- run_id + verdict + keywords
*
* Legacy posts (no run row) return ['has_run' => false] -- never notices.
* Amortized research rows (pv=null, role='') render gracefully.
*
* v0.20.0 (M3): stage rows are filtered to THIS post's item (item_key
* from the idea-hash meta; multi-article runs no longer collide) and
* gen_log rows exclude entries linked to OTHER posts; per-stage edit/
* re-run affordance data + run spend ride the view model
* (Dossier_Rerun_Panel_Data); log-only stages (image_a/image_b/
* llm_research/... -- generation_log rows with no run_stages row) and
* the post's pipeline attachments are exposed so the image sections
* render from their REAL data sources (QA M2 F3).
*
* Triggered by: PRAutoBlogger_Dossier_Page::render_page().
* Dependencies: PRAutoBlogger_Dossier_Gen_Log_Query, PRAutoBlogger_Stage_Display_Map,
* PRAutoBlogger_Run_Stage_State.
*
* @see admin/class-dossier-gen-log-query.php -- Raw generation_log queries.
* @see core/class-run-stage-state.php -- Stage I/O access.
* @see ARCHITECTURE.md -- Substrate schema.
*/
class PRAutoBlogger_Dossier_Data_Assembler {
/** @var PRAutoBlogger_Dossier_Gen_Log_Query */
private PRAutoBlogger_Dossier_Gen_Log_Query $log_query;
/**
* @param PRAutoBlogger_Dossier_Gen_Log_Query|null $log_query Injectable for tests.
*/
public function __construct( ?PRAutoBlogger_Dossier_Gen_Log_Query $log_query = null ) {
$this->log_query = $log_query ?? new PRAutoBlogger_Dossier_Gen_Log_Query();
}
/**
* Assemble the full dossier view model for a post.
*
* @param int $post_id WordPress post ID (0 = bogus/not found).
* @return array<string, mixed> View model consumed by dossier-page.php.
*/
public function assemble( int $post_id ): array {
$base = array(
'post_id' => $post_id,
'has_run' => false,
'post_title' => '',
'post_status' => '',
'verdict' => '',
'tier' => '',
'run_id' => '',
'run' => null,
'stages' => array(),
'decisions' => array(),
'gen_log_index' => array(),
'item_key' => '',
'eligibility' => array(
'ok' => false,
'reason' => '',
),
'spend' => PRAutoBlogger_Dossier_Rerun_Panel_Data::spend( null ),
'human_modified_any' => false,
'stale_any' => false,
'log_only_stages' => array(),
'images' => array(),
);
if ( $post_id <= 0 ) {
return $base;
}
$post = get_post( $post_id );
if ( ! ( $post instanceof WP_Post ) ) {
return $base;
}
$base['post_title'] = $post->post_title;
$base['post_status'] = $post->post_status;
$base['verdict'] = (string) get_post_meta( $post_id, '_prautoblogger_editor_verdict', true );
$base['tier'] = (string) get_post_meta( $post_id, '_prautoblogger_article_type', true );
$run_id = (string) get_post_meta( $post_id, '_prautoblogger_run_id', true );
if ( '' === $run_id ) {
return $base;
}
$base['run_id'] = $run_id;
$run = $this->get_run_row( $run_id );
if ( null === $run ) {
return $base;
}
$idea_hash = (string) get_post_meta( $post_id, '_prautoblogger_idea_hash', true );
$item_key = '' !== $idea_hash ? 'idea:' . $idea_hash : '';
$base['item_key'] = $item_key;
$base['has_run'] = true;
$base['run'] = $run;
$base['stages'] = $this->get_stage_rows( $run_id, $item_key );
$base['decisions'] = $this->get_decision_rows( $run_id );
$base['gen_log_index'] = $this->filter_log_for_post( $this->log_query->get_by_run( $run_id ), $post_id );
$base['eligibility'] = PRAutoBlogger_Rerun_Eligibility::check( $run_id, $post_id );
$base['spend'] = PRAutoBlogger_Dossier_Rerun_Panel_Data::spend( $run );
foreach ( $base['stages'] as $role_key => $stage_row ) {
$stage_name = (string) ( $stage_row['stage'] ?? '' );
$rerun = PRAutoBlogger_Dossier_Rerun_Panel_Data::for_stage(
$stage_row,
$base['gen_log_index'][ $stage_name ] ?? array(),
$run_id,
$base['eligibility']
);
$base['stages'][ $role_key ]['rerun'] = $rerun;
$base['human_modified_any'] = $base['human_modified_any'] || $rerun['human_modified'];
$base['stale_any'] = $base['stale_any'] || $rerun['stale'];
}
// QA M2 F3: stages that exist only in generation_log (image_a/
// image_b, llm_research, image_prompt_rewrite, ...) render from
// their real source instead of silently disappearing.
$run_stage_names = array();
foreach ( $base['stages'] as $stage_row ) {
$run_stage_names[ (string) ( $stage_row['stage'] ?? '' ) ] = true;
}
$base['log_only_stages'] = array_values( array_diff( array_keys( $base['gen_log_index'] ), array_keys( $run_stage_names ) ) );
$base['images'] = PRAutoBlogger_Dossier_Image_Data::for_post( $post_id );
return $base;
}
/**
* Fetch the run ledger row.
*
* @param string $run_id Pipeline run UUID.
* @return array<string, mixed>|null
*/
private function get_run_row( string $run_id ): ?array {
global $wpdb;
if ( null === $wpdb ) {
return null;
}
$table = $wpdb->prefix . 'prautoblogger_runs';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$row = $wpdb->get_row(
$wpdb->prepare( "SELECT * FROM {$table} WHERE run_id = %s", $run_id ),
ARRAY_A
);
return is_array( $row ) ? $row : null;
}
/**
* Fetch run_stages rows for a run, indexed by stage name — scoped to
* one item (+ run-level rows) when an item key is known.
*
* @param string $run_id Pipeline run UUID.
* @param string $item_key Item key ('' = no scoping, M2 behavior).
* @return array<string, array<string, mixed>> Stage rows keyed by stage name.
*/
private function get_stage_rows( string $run_id, string $item_key = '' ): array {
if ( ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return array();
}
global $wpdb;
if ( null === $wpdb ) {
return array();
}
$table = PRAutoBlogger_Run_Stage_State::table_name();
// v0.20.0: scope to THIS post's item + run-level rows. When the
// idea-hash meta is absent (pre-v0.18 posts) fall back to the
// unfiltered M2 behavior (single-item runs are unaffected).
if ( '' !== $item_key ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$table} WHERE run_id = %s AND item_key IN (%s, '') ORDER BY id ASC", $run_id, $item_key ),
ARRAY_A
);
} else {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$table} WHERE run_id = %s ORDER BY id ASC", $run_id ),
ARRAY_A
);
}
$index = array();
foreach ( ( $rows ?? array() ) as $row ) {
if ( ! is_array( $row ) ) {
continue;
}
$stage = (string) ( $row['stage'] ?? '' );
$role_key = $stage . ':' . ( $row['agent_role'] ?? '' );
$row['display_output'] = $this->extract_output( $row );
$index[ $role_key ] = $row;
}
return $index;
}
/**
* Drop gen_log rows linked to OTHER posts (multi-article runs share
* one run_id). Rows with no post linkage (NULL/0 — run-level work
* and pre-link entries) are kept.
*
* @param array<string, array<int, array<string, mixed>>> $log_index Rows keyed by stage.
* @param int $post_id This dossier's post.
* @return array<string, array<int, array<string, mixed>>>
*/
private function filter_log_for_post( array $log_index, int $post_id ): array {
$filtered = array();
foreach ( $log_index as $stage => $rows ) {
foreach ( $rows as $row ) {
$row_post = (int) ( $row['post_id'] ?? 0 );
if ( 0 !== $row_post && $row_post !== $post_id ) {
continue;
}
$filtered[ $stage ][] = $row;
}
}
return $filtered;
}
/**
* Extract the text output from a run_stages meta_json blob.
* Returns null when meta_json is NULL (pruned) or absent.
*
* @param array<string, mixed> $row Stage row.
* @return string|null
*/
private function extract_output( array $row ): ?string {
if ( empty( $row['meta_json'] ) ) {
return null;
}
$meta = json_decode( (string) $row['meta_json'], true );
return ( is_array( $meta ) && isset( $meta['output'] ) ) ? (string) $meta['output'] : null;
}
/**
* Fetch all run_decisions rows, indexed by stage name.
*
* @param string $run_id Pipeline run UUID.
* @return array<string, array<string, mixed>> Decision rows keyed by stage.
*/
private function get_decision_rows( string $run_id ): array {
global $wpdb;
if ( null === $wpdb ) {
return array();
}
$table = $wpdb->prefix . 'prautoblogger_run_decisions';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$table} WHERE run_id = %s ORDER BY id ASC", $run_id ),
ARRAY_A
);
$index = array();
foreach ( ( $rows ?? array() ) as $row ) {
if ( ! is_array( $row ) ) {
continue;
}
$stage = (string) ( $row['stage'] ?? 'unknown' );
$index[ $stage ] = $row;
}
return $index;
}
}

View File

@@ -1,95 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Raw generation_log queries for the Article Dossier (M2).
*
* Returns per-stage generation log data indexed by stage name: model,
* prompt_version, agent_role, token counts, estimated cost, request_json
* (raw trace), and response_status. Amortized research rows (pv=null,
* role='') are included and rendered gracefully by the template.
*
* Triggered by: PRAutoBlogger_Dossier_Data_Assembler::assemble().
* Dependencies: WordPress $wpdb.
*
* @see admin/class-dossier-data-assembler.php -- Calls get_by_run().
* @see ARCHITECTURE.md -- generation_log schema.
*/
class PRAutoBlogger_Dossier_Gen_Log_Query {
/**
* Fetch all generation_log rows for a run, indexed by stage.
*
* Multiple rows per stage (e.g. multi-step draft) are accumulated as an
* array so the template can render multiple raw-trace entries per section.
*
* SECURITY: request_json is stored without API keys (never logged per
* architecture). The template must escape this via esc_html() before render.
*
* @param string $run_id Pipeline run UUID.
* @return array<string, array<int, array<string, mixed>>> Rows keyed by stage.
*/
public function get_by_run( string $run_id ): array {
global $wpdb;
if ( null === $wpdb || '' === $run_id ) {
return array();
}
$table = $wpdb->prefix . 'prautoblogger_generation_log';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT id, stage, model, agent_role, prompt_version,
prompt_tokens, completion_tokens, estimated_cost,
request_json, response_status, error_message, created_at
FROM {$table}
WHERE run_id = %s
ORDER BY id ASC",
$run_id
),
ARRAY_A
);
$index = array();
foreach ( ( $rows ?? array() ) as $row ) {
if ( ! is_array( $row ) ) {
continue;
}
$stage = (string) ( $row['stage'] ?? 'unknown' );
if ( ! isset( $index[ $stage ] ) ) {
$index[ $stage ] = array();
}
$index[ $stage ][] = $row;
}
return $index;
}
/**
* Aggregate cost + token totals per stage for the sidebar receipt.
*
* @param array<string, array<int, array<string, mixed>>> $log_index Output of get_by_run().
* @return array<string, array{cost: float, prompt_tokens: int, completion_tokens: int, calls: int}>
*/
public function aggregate_per_stage( array $log_index ): array {
$totals = array();
foreach ( $log_index as $stage => $rows ) {
$cost = 0.0;
$prompt_tokens = 0;
$completion_tokens = 0;
foreach ( $rows as $row ) {
$cost += (float) ( $row['estimated_cost'] ?? 0 );
$prompt_tokens += (int) ( $row['prompt_tokens'] ?? 0 );
$completion_tokens += (int) ( $row['completion_tokens'] ?? 0 );
}
$totals[ $stage ] = array(
'cost' => $cost,
'prompt_tokens' => $prompt_tokens,
'completion_tokens' => $completion_tokens,
'calls' => count( $rows ),
);
}
return $totals;
}
}

View File

@@ -1,82 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Resolves a post's pipeline image attachments for the dossier (M3/F3).
*
* What: The image sections' REAL data source — the attachments the
* image pipeline produced (featured + composed og/square variants,
* discovered via the `_prautoblogger_image_role` attachment meta
* and the post thumbnail), paired in the template with the
* image_a/image_b generation_log rows. Replaces the M2 sections
* that keyed off run_stages rows the image pipeline never writes
* (QA M2 F3 — wiring the dossier to real data was the smaller,
* safer change vs. teaching the live image pipeline to write
* run_stages; the pipeline restructure is Phase 2b).
* Who triggers it: PRAutoBlogger_Dossier_Data_Assembler::assemble().
* Dependencies: get_children(), attachment meta, wp_get_attachment_image_url().
*
* @see admin/class-dossier-data-assembler.php — Caller.
* @see templates/admin/dossier-log-stage-section.php — Renders the pairs.
* @see ARCHITECTURE.md #24 — M3 design (F3 note).
*/
class PRAutoBlogger_Dossier_Image_Data {
/**
* The post's pipeline attachments (featured/og/square) via the
* `_prautoblogger_image_role` attachment meta — the image sections'
* real data source (QA M2 F3).
*
* @param int $post_id Post ID.
* @return array<int, array{id: int, role: string, url: string, is_featured: bool}>
*/
public static function for_post( int $post_id ): array {
$featured_id = (int) get_post_thumbnail_id( $post_id );
$children = get_children(
array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'numberposts' => 12,
)
);
$images = array();
$seen = array();
foreach ( (array) $children as $attachment ) {
$att_id = (int) ( $attachment->ID ?? 0 );
if ( $att_id <= 0 ) {
continue;
}
$role = (string) get_post_meta( $att_id, '_prautoblogger_image_role', true );
if ( '' === $role && $att_id !== $featured_id ) {
continue; // Not a pipeline attachment.
}
$url = (string) wp_get_attachment_image_url( $att_id, 'medium' );
if ( '' === $url ) {
continue;
}
$seen[ $att_id ] = true;
$images[] = array(
'id' => $att_id,
'role' => '' !== $role ? $role : 'featured',
'url' => $url,
'is_featured' => $att_id === $featured_id,
);
}
// Featured image attached elsewhere (not a child) still renders.
if ( $featured_id > 0 && ! isset( $seen[ $featured_id ] ) ) {
$url = (string) wp_get_attachment_image_url( $featured_id, 'medium' );
if ( '' !== $url ) {
$images[] = array(
'id' => $featured_id,
'role' => 'featured',
'url' => $url,
'is_featured' => true,
);
}
}
return $images;
}
}

View File

@@ -1,172 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Registers and renders the Article Dossier admin page (M2).
*
* The dossier is link-accessed -- it is NOT a visible submenu item. It uses
* the canonical hidden-admin-page pattern: register under parent 'options.php'
* so WordPress computes the hookname as `admin_page_prautoblogger-dossier` at
* BOTH registration time AND request time. The page is hidden from nav by
* construction (options.php is a built-in WP page with no visible submenu block)
* so no $submenu mutation is needed or permitted.
*
* Why NOT the hide-by-unset pattern (the v0.19.2 bug):
* add_submenu_page('prautoblogger-settings', ...) → hookname 'prautoblogger_page_prautoblogger-dossier'
* post-registration unset($submenu['prautoblogger-settings'][$idx])
* → at request time get_admin_page_parent() no longer finds the slug in $submenu
* → WP recomputes hookname in the 'admin_page_*' orphan namespace
* → no callback registered there → wp_die(403).
* See ARCHITECTURE.md §22b + CONVENTIONS.md §Hidden Admin Pages for the full incident
* history (board 404 v0.19.1, dossier 403 v0.19.2).
*
* Board cards and post-metabox deep-link here via
* admin.php?page=prautoblogger-dossier&post_id=X. Deep-link URLs are parent-agnostic
* (they reference only the page slug) so they are unchanged by this fix.
*
* Design contract: Proposal C "Editorial Record" -- warm editorial dossier,
* verdict pills, receipt-style cost sidebar, per-stage I/O with raw-trace toggle.
*
* Triggered by: PRAutoBlogger::register_admin_hooks() on `admin_menu` (priority 12).
* Dependencies: PRAutoBlogger_Dossier_Data_Assembler, templates/admin/dossier-page.php.
*
* @see admin/class-dossier-data-assembler.php -- Builds the view model.
* @see templates/admin/dossier-page.php -- HTML template.
* @see ARCHITECTURE.md -- §22b (hidden admin page convention).
* @see CONVENTIONS.md -- §Hidden Admin Pages.
*/
class PRAutoBlogger_Dossier_Page {
/** Admin page slug. */
public const PAGE_SLUG = 'prautoblogger-dossier';
/**
* Parent slug used at registration.
* 'options.php' is the canonical WP hidden-page parent: the hookname resolves
* to `admin_page_{slug}` at both registration time and request time, so there is
* no hookname mismatch and no need to manipulate $submenu.
*/
public const PARENT_SLUG = 'options.php';
/** Nonce action for any future stateful actions. */
public const NONCE_ACTION = 'prautoblogger_dossier';
/**
* Register the dossier as a hidden admin page.
*
* Uses the canonical options.php-parent pattern so the hookname is stable at
* both registration time and request time. No $submenu manipulation required
* or permitted (see CONVENTIONS.md §Hidden Admin Pages).
*
* @return void
*/
public function on_register_menu(): void {
add_submenu_page(
self::PARENT_SLUG,
__( 'Article Dossier', 'prautoblogger' ),
__( 'Dossier', 'prautoblogger' ),
'manage_options',
self::PAGE_SLUG,
array( $this, 'render_page' )
);
// No $submenu mutation. options.php-parent pages are hidden by construction.
}
/**
* Render the dossier page.
*
* @return void
*/
public function render_page(): void {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only dossier; no state changes.
$post_id = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0;
$assembler = new PRAutoBlogger_Dossier_Data_Assembler();
$dossier = $assembler->assemble( $post_id );
include PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/dossier-page.php';
}
/**
* Enqueue dossier-specific CSS + JS.
*
* The hook suffix for an options.php-parent page is `admin_page_{slug}`.
*
* @param string $hook_suffix Current admin page hook suffix.
* @return void
*/
public function on_enqueue_assets( string $hook_suffix ): void {
// options.php-parent pages resolve to 'admin_page_{slug}' (not 'prautoblogger_page_*').
$dossier_hook = 'admin_page_' . self::PAGE_SLUG;
if ( $hook_suffix !== $dossier_hook ) {
return;
}
wp_enqueue_style(
'prautoblogger-dossier',
PRAUTOBLOGGER_PLUGIN_URL . 'assets/css/dossier.css',
array( 'prautoblogger-admin' ),
PRAUTOBLOGGER_VERSION
);
wp_enqueue_script(
'prautoblogger-dossier',
PRAUTOBLOGGER_PLUGIN_URL . 'assets/js/dossier.js',
array(),
PRAUTOBLOGGER_VERSION,
true
);
// M3: edit + re-run layer (separate files; dossier.css is not grown).
wp_enqueue_style(
'prautoblogger-dossier-edit',
PRAUTOBLOGGER_PLUGIN_URL . 'assets/css/dossier-edit.css',
array( 'prautoblogger-dossier' ),
PRAUTOBLOGGER_VERSION
);
wp_enqueue_script(
'prautoblogger-dossier-edit',
PRAUTOBLOGGER_PLUGIN_URL . 'assets/js/dossier-edit.js',
array(),
PRAUTOBLOGGER_VERSION,
true
);
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context resolution for script config.
$post_id = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0;
wp_localize_script(
'prautoblogger-dossier-edit',
'prabDossierEdit',
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( PRAutoBlogger_Dossier_Actions::NONCE_ACTION ),
'postId' => $post_id,
// Settings read at point of use -- same poll setting as the board.
'pollInterval' => max( 3, (int) get_option( 'prautoblogger_board_poll_interval', 5 ) ),
'strings' => array(
'saving' => __( 'Saving…', 'prautoblogger' ),
'error' => __( 'Request failed — try again.', 'prautoblogger' ),
'queued' => __( 'Queued…', 'prautoblogger' ),
'rerunFromLabel' => __( 'Re-run from here', 'prautoblogger' ),
'confirmReplay' => __( 'Queue a re-run of this stage with your edited input? This makes a new LLM call billed against this run\'s ceiling, and all downstream stages will be marked stale (nothing re-runs automatically).', 'prautoblogger' ),
'confirmRerunFrom' => __( 'Queue a re-run of this stage AND every stage after it? Each re-run stage makes new LLM calls billed against this run\'s ceiling. The article draft will be refreshed; published posts are never touched.', 'prautoblogger' ),
),
)
);
}
/**
* Build the URL to the dossier for a given post.
*
* Deep-link URLs use admin.php?page=<slug> which is parent-agnostic.
* This method is unchanged from v0.19.2 -- only the registration parent changed.
*
* @param int $post_id WordPress post ID.
* @return string Admin URL to the dossier page.
*/
public static function url_for_post( int $post_id ): string {
return admin_url( 'admin.php?page=' . self::PAGE_SLUG . '&post_id=' . $post_id );
}
}

View File

@@ -1,181 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Builds the edit + re-run view-model layer for the dossier (v0.20.0, M3).
*
* What: Per-stage affordance data (editable? why not? latest fork,
* prefill messages from the fork or the stage's recorded
* request_json) plus the run-level spend strip (settled + reserved
* vs ceiling, warn fraction — guardrail 4's visible cost
* implication) and the overall eligibility verdict. Pure
* assembly: reads the rows the Dossier_Data_Assembler already
* fetched plus the stage_inputs store; performs NO mutations.
* Disabled affordances always carry an operator-readable reason —
* the UI never hides why an edit is unavailable.
* Who triggers it: PRAutoBlogger_Dossier_Data_Assembler::assemble().
* Dependencies: Rerun_Eligibility (policy), Stage_Input_Store (forks),
* Stage_Replay (body decode).
*
* @see admin/class-dossier-data-assembler.php — Caller.
* @see templates/admin/dossier-edit-panel.php — Renders this data.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Dossier_Rerun_Panel_Data {
/** Default warn threshold as a fraction of the per-run ceiling. */
private const DEFAULT_WARN_FRACTION = 0.8;
/**
* Run-level spend strip data (guardrail 4 visibility).
*
* @param array<string, mixed>|null $run Run ledger row, or null.
* @return array{settled: float, reserved: float, ceiling: float, fraction: float, warn: bool}
*/
public static function spend( ?array $run ): array {
$settled = null !== $run ? (float) ( $run['settled_usd'] ?? 0 ) : 0.0;
$reserved = null !== $run ? (float) ( $run['reserved_usd'] ?? 0 ) : 0.0;
$ceiling = null !== $run ? (float) ( $run['ceiling_usd'] ?? 0 ) : 0.0;
$fraction = $ceiling > 0 ? ( $settled + $reserved ) / $ceiling : 0.0;
/**
* Filters the spend fraction at which re-run confirms warn about
* approaching the per-run ceiling.
*
* @param float $warn_fraction Fraction of ceiling (default 0.8).
*/
$warn_fraction = (float) apply_filters( 'prautoblogger_rerun_ceiling_warn_fraction', self::DEFAULT_WARN_FRACTION );
return array(
'settled' => $settled,
'reserved' => $reserved,
'ceiling' => $ceiling,
'fraction' => $fraction,
'warn' => $ceiling > 0 && $fraction >= $warn_fraction,
);
}
/**
* Edit + re-run affordance data for one stage row.
*
* @param array<string, mixed> $stage_row run_stages row.
* @param array<int, array<string, mixed>> $log_rows generation_log rows for the stage.
* @param string $run_id Run UUID.
* @param array{ok: bool, reason: string} $eligibility Overall run eligibility.
* @return array<string, mixed> Affordance view model (see keys below).
*/
public static function for_stage( array $stage_row, array $log_rows, string $run_id, array $eligibility ): array {
$stage = (string) ( $stage_row['stage'] ?? '' );
$role = (string) ( $stage_row['agent_role'] ?? '' );
$item_key = (string) ( $stage_row['item_key'] ?? '' );
$data = array(
'stale' => ! empty( $stage_row['stale'] ),
'human_modified' => ! empty( $stage_row['human_modified'] ),
'attempt' => (int) ( $stage_row['attempt'] ?? 1 ),
'editable' => false,
'edit_reason' => '',
'fork' => null,
'prefill' => null,
'rerun_from' => $eligibility['ok'] && PRAutoBlogger_Rerun_Eligibility::is_chain_stage( $stage ),
);
if ( ! PRAutoBlogger_Rerun_Eligibility::is_editable_stage( $stage ) ) {
$data['edit_reason'] = self::policy_reason( $stage );
return $data;
}
if ( ! $eligibility['ok'] ) {
$data['edit_reason'] = $eligibility['reason'];
return $data;
}
$fork = PRAutoBlogger_Stage_Input_Store::latest_fork( $run_id, $stage, $role, $item_key );
if ( null !== $fork ) {
$data['fork'] = array(
'version' => (int) $fork['version'],
'author' => (string) $fork['author'],
'created_at' => (string) $fork['created_at'],
'has_body' => ! empty( $fork['request_json'] ),
);
}
$base_json = ( null !== $fork && ! empty( $fork['request_json'] ) )
? (string) $fork['request_json']
: self::latest_request_json( $log_rows );
if ( null === $base_json ) {
$days = (int) get_option( 'prautoblogger_request_json_retention_days', PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS );
$data['edit_reason'] = sprintf(
/* translators: %d: retention days. */
__( 'No persisted input for this stage — request bodies are recorded from v0.20.0 onward and retained for %d days.', 'prautoblogger' ),
$days
);
return $data;
}
$body = PRAutoBlogger_Stage_Replay::decode_body( $base_json );
if ( null === $body ) {
$data['edit_reason'] = __( 'The persisted input for this stage is not a replayable chat request.', 'prautoblogger' );
return $data;
}
$data['editable'] = true;
$data['prefill'] = array(
'model' => (string) $body['model'],
'messages' => $body['messages'],
);
return $data;
}
/**
* Why a non-writer stage has no edit affordance (always shown —
* the UI never silently hides the option).
*
* @param string $stage Stage name.
* @return string Operator-readable reason.
*/
private static function policy_reason( string $stage ): string {
if ( 'review' === $stage ) {
return __( 'The review input is derived entirely from the article content — edit a writing stage, then use "Re-run from here" on this one.', 'prautoblogger' );
}
if ( 'publish' === $stage ) {
return __( 'Publish is not an LLM stage — use "Re-run from here" to refresh the post from current outputs.', 'prautoblogger' );
}
if ( in_array( $stage, array( 'analysis', 'research', 'llm_research' ), true ) ) {
return __( 'Run-level stage: its output fed idea selection for the whole run and cannot be re-flowed into a single article.', 'prautoblogger' );
}
if ( 0 === strpos( $stage, 'image' ) ) {
return __( 'Image stages are not replayable yet (Phase 2b restructure).', 'prautoblogger' );
}
return __( 'This stage cannot be replayed with an edited input.', 'prautoblogger' );
}
/**
* The most recent recorded request body among a stage's log rows
* (success rows preferred, then latest id).
*
* @param array<int, array<string, mixed>> $log_rows generation_log rows.
* @return string|null
*/
private static function latest_request_json( array $log_rows ): ?string {
$best = null;
foreach ( $log_rows as $row ) {
if ( empty( $row['request_json'] ) ) {
continue;
}
if ( null === $best ) {
$best = $row;
continue;
}
$row_success = ( 'success' === ( $row['response_status'] ?? '' ) );
$best_success = ( 'success' === ( $best['response_status'] ?? '' ) );
if ( ( $row_success && ! $best_success )
|| ( $row_success === $best_success && (int) ( $row['id'] ?? 0 ) > (int) ( $best['id'] ?? 0 ) ) ) {
$best = $row;
}
}
return null !== $best ? (string) $best['request_json'] : null;
}
}

View File

@@ -6,25 +6,20 @@ declare(strict_types=1);
*
* Static registry of available image generation models.
*
* What: Returns a merged list of Runware models (from live catalog sync) and
* OpenRouter models (static list). No API discovery for OpenRouter — updated
* manually when new models are available.
* As of 2026-04-26, registry includes 15 Runware models (live) + 6 OpenRouter
* models (static), ordered cheapest-to-most-expensive within each provider.
* What: Returns a hardcoded list of image models for the admin model picker.
* No API discovery — updated manually when providers add/remove models.
* Who calls it: PRAutoBlogger_Admin_Page (model picker UI + save-time provider
* derivation) and PRAutoBlogger_Image_Pipeline (provider lookup).
* Dependencies: PRAutoBlogger_Runware_Model_Catalog (live Runware models),
* hardcoded fallback lists for resilience.
* Dependencies: None.
*
* @see admin/class-settings-fields-extended.php — Image settings reference this registry.
* @see core/class-image-pipeline.php — Derives provider from picked model.
* @see providers/class-runware-image-provider.php — Runware FLUX backend.
* @see providers/class-runware-model-catalog.php — Live model sync and caching.
*/
class PRAutoBlogger_Image_Model_Registry {
/**
* Get all available image generation models (Runware live + OpenRouter static).
* Get all available image generation models.
*
* Each entry contains:
* - id: Model identifier used in API calls.
@@ -40,10 +35,64 @@ class PRAutoBlogger_Image_Model_Registry {
* @return array<int, array<string, mixed>>
*/
public static function get_models(): array {
$catalog = new PRAutoBlogger_Runware_Model_Catalog();
$runware_models = $catalog->get_models();
$openrouter_models = self::get_openrouter_models();
return array_merge( $runware_models, $openrouter_models );
return array(
array(
'id' => 'runware:100@1',
'name' => 'FLUX.1 schnell (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0006,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Default. Fast, very cheap, comic-friendly fidelity.', 'prautoblogger' ),
),
array(
'id' => 'runware:101@1',
'name' => 'FLUX.1 dev (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.02,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Higher fidelity FLUX. ~30x schnell cost.', 'prautoblogger' ),
),
array(
'id' => 'google/gemini-2.5-flash-image',
'name' => 'Gemini 2.5 Flash Image (Nano Banana)',
'provider' => 'openrouter',
'cost_per_image' => 0.005,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Mid-tier quality, proven.', 'prautoblogger' ),
),
array(
'id' => 'google/gemini-3.1-flash-image-preview',
'name' => 'Gemini 3.1 Flash Image (Nano Banana 2)',
'provider' => 'openrouter',
'cost_per_image' => 0.008,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Latest Google. Better quality.', 'prautoblogger' ),
),
array(
'id' => 'google/gemini-3-pro-image-preview',
'name' => 'Gemini 3 Pro Image (Nano Banana Pro)',
'provider' => 'openrouter',
'cost_per_image' => 0.03,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Highest quality Google. Premium.', 'prautoblogger' ),
),
array(
'id' => 'openai/gpt-5-image-mini',
'name' => 'GPT-5 Image Mini',
'provider' => 'openrouter',
'cost_per_image' => 0.02,
'capabilities' => array( 'image_generation' ),
'description' => __( 'OpenAI budget image model.', 'prautoblogger' ),
),
array(
'id' => 'openai/gpt-5-image',
'name' => 'GPT-5 Image',
'provider' => 'openrouter',
'cost_per_image' => 0.08,
'capabilities' => array( 'image_generation' ),
'description' => __( 'OpenAI premium. Photorealistic.', 'prautoblogger' ),
),
);
}
/**
@@ -61,204 +110,4 @@ class PRAutoBlogger_Image_Model_Registry {
}
return '';
}
/**
* Hardcoded Runware model list used as fallback when the live catalog
* sync fails or API is unreachable. Kept in sync with actual Runware
* pricing page (runware.ai/pricing). This is the source of truth for
* pricing data when the Runware API doesn't expose cost information.
*
* Last verified: 2026-04-26. To update: check runware.ai/pricing for new
* text-to-image models and their costs.
*
* @return array<int, array<string, mixed>>
*/
public static function get_runware_fallback_models(): array {
return array(
array(
'id' => 'runware:100@1',
'name' => 'FLUX.1 schnell (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0006,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Default. Fast, very cheap, comic-friendly fidelity.', 'prautoblogger' ),
),
array(
'id' => 'runware:twinflow-z-image-turbo@0',
'name' => 'TwinFlow Z-Image-Turbo (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0006,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Fast text-to-image, same cost as schnell.', 'prautoblogger' ),
),
array(
'id' => 'runware:400@2',
'name' => 'FLUX.2 klein 9B (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.00078,
'capabilities' => array( 'image_generation' ),
'description' => __( 'FLUX.2 compact 9B. Stronger than schnell at similar cost.', 'prautoblogger' ),
),
array(
'id' => 'runware:400@4',
'name' => 'FLUX.2 klein 4B (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0006,
'capabilities' => array( 'image_generation' ),
'description' => __( 'FLUX.2 compact 4B. Newer architecture at schnell price.', 'prautoblogger' ),
),
array(
'id' => 'runware:5@1',
'name' => 'Stable Diffusion 3 (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0013,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Stable Diffusion 3. Sharp text, complex scenes.', 'prautoblogger' ),
),
array(
'id' => 'runware:z-image@turbo',
'name' => 'Z-Image Turbo (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0013,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Fast photorealistic generation.', 'prautoblogger' ),
),
array(
'id' => 'runware:101@1',
'name' => 'FLUX.1 dev (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.02,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Higher fidelity FLUX.1. ~30x schnell cost.', 'prautoblogger' ),
),
array(
'id' => 'runware:97@3',
'name' => 'HiDream-I1 Fast (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0038,
'capabilities' => array( 'image_generation' ),
'description' => __( 'HiDream-I1 Fast. Low latency, 17B quality.', 'prautoblogger' ),
),
array(
'id' => 'runware:97@2',
'name' => 'HiDream-I1 Dev (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0045,
'capabilities' => array( 'image_generation' ),
'description' => __( 'HiDream-I1 Dev. Strong prompt alignment.', 'prautoblogger' ),
),
array(
'id' => 'runware:z-image@0',
'name' => 'Z-Image (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0045,
'capabilities' => array( 'image_generation' ),
'description' => __( 'High-quality Z-Image foundation model.', 'prautoblogger' ),
),
array(
'id' => 'runware:400@1',
'name' => 'FLUX.2 dev (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0051,
'capabilities' => array( 'image_generation' ),
'description' => __( 'FLUX.2 dev. Controllable open text-to-image. From $0.0051.', 'prautoblogger' ),
),
array(
'id' => 'runware:108@1',
'name' => 'Qwen-Image (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0058,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Alibaba Qwen-Image. Strong text rendering in generated images.', 'prautoblogger' ),
),
array(
'id' => 'runware:97@1',
'name' => 'HiDream-I1 Full (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.009,
'capabilities' => array( 'image_generation' ),
'description' => __( 'HiDream-I1 Full. 17B high-fidelity, LoRA support.', 'prautoblogger' ),
),
array(
'id' => 'runware:107@1',
'name' => 'FLUX.1 Krea dev (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0098,
'capabilities' => array( 'image_generation' ),
'description' => __( 'FLUX.1 Krea Dev. Photorealistic open-weight generation.', 'prautoblogger' ),
),
array(
'id' => 'runware:glm-image@0',
'name' => 'GLM-Image (Runware)',
'provider' => 'runware',
'cost_per_image' => 0.0225,
'capabilities' => array( 'image_generation' ),
'description' => __( 'GLM-Image. Hybrid autoregressive+diffusion, excellent text rendering.', 'prautoblogger' ),
),
);
}
/**
* Hardcoded OpenRouter image model list. Left static for now because
* OpenRouter's catalog is large (hundreds of models) with noisy filtering.
* Future iteration will add smart filtering strategy (output_modalities,
* pricing, rate limits).
*
* Last verified: 2026-04-26. To update: check openrouter.ai/api/v1/models
* filtering to output_modalities containing 'image'.
*
* @return array<int, array<string, mixed>>
*/
private static function get_openrouter_models(): array {
return array(
array(
'id' => 'google/gemini-2.5-flash-image',
'name' => 'Gemini 2.5 Flash Image (OpenRouter)',
'provider' => 'openrouter',
'cost_per_image' => 0.005,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Mid-tier quality, proven.', 'prautoblogger' ),
),
array(
'id' => 'google/gemini-3.1-flash-image-preview',
'name' => 'Gemini 3.1 Flash Image (OpenRouter)',
'provider' => 'openrouter',
'cost_per_image' => 0.008,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Latest Google Flash image. Better quality.', 'prautoblogger' ),
),
array(
'id' => 'openai/gpt-5-image-mini',
'name' => 'GPT-5 Image Mini (OpenRouter)',
'provider' => 'openrouter',
'cost_per_image' => 0.02,
'capabilities' => array( 'image_generation' ),
'description' => __( 'OpenAI budget image model.', 'prautoblogger' ),
),
array(
'id' => 'openai/gpt-5.4-image-2',
'name' => 'GPT-5.4 Image 2 (OpenRouter)',
'provider' => 'openrouter',
'cost_per_image' => 0.02,
'capabilities' => array( 'image_generation' ),
'description' => __( 'OpenAI GPT-5.4 image generation.', 'prautoblogger' ),
),
array(
'id' => 'google/gemini-3-pro-image-preview',
'name' => 'Gemini 3 Pro Image (OpenRouter)',
'provider' => 'openrouter',
'cost_per_image' => 0.03,
'capabilities' => array( 'image_generation' ),
'description' => __( 'Highest quality Google image. Premium.', 'prautoblogger' ),
),
array(
'id' => 'openai/gpt-5-image',
'name' => 'GPT-5 Image (OpenRouter)',
'provider' => 'openrouter',
'cost_per_image' => 0.08,
'capabilities' => array( 'image_generation' ),
'description' => __( 'OpenAI premium. Photorealistic.', 'prautoblogger' ),
),
);
}
}

View File

@@ -111,15 +111,10 @@ class PRAutoBlogger_Post_List_Columns {
return;
}
echo '<style>'
. '.wp-list-table .column-title{width:22%}'
. '.column-author{width:6%}'
. '.column-categories{width:7%}'
. '.column-tags{width:9%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
. '.column-date{width:8%}'
. '.column-prab_writing_model{width:85px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
. '.column-prab_image_model{width:85px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
. '.column-prab_cost{width:50px;white-space:nowrap;overflow:visible}'
. '.column-taxonomy-peptide_topic{width:75px}'
. '.wp-list-table .column-title{width:35%;word-wrap:break-word;overflow-wrap:break-word}'
. '.column-prab_writing_model{width:100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
. '.column-prab_image_model{width:100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
. '.column-prab_cost{width:55px;white-space:nowrap;overflow:visible}'
. '.prab-cost-wrap{position:relative;display:inline-block}'
. '.prab-cost-trigger{font-size:12px;color:#2271b1;text-decoration:underline;cursor:pointer}'
. '.prab-cost-popover{display:none;position:absolute;right:0;top:100%;z-index:9999;'
@@ -187,9 +182,8 @@ class PRAutoBlogger_Post_List_Columns {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare(
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
"SELECT stage, model, prompt_tokens, completion_tokens, estimated_cost
FROM {$table} WHERE post_id = %d ORDER BY id ASC",
"SELECT stage, model, prompt_tokens, completion_tokens, estimated_cost // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
FROM {$table} WHERE post_id = %d ORDER BY id ASC",
$post_id
),
ARRAY_A

View File

@@ -4,22 +4,21 @@ declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Adds a metabox to PRAutoBlogger-generated posts.
* Adds a metabox to posts showing PRAutoBlogger generation metadata.
*
* M2: Slimmed to a "View generation dossier" link. Full generation metadata
* lives on the Article Dossier page (PRAutoBlogger_Dossier_Page).
* Only appears on posts that were generated by PRAutoBlogger (checked via
* _prautoblogger_generated post meta).
*
* Triggered by: PRAutoBlogger::register_admin_hooks() on `add_meta_boxes`.
* Dependencies: PRAutoBlogger_Dossier_Page (for URL helper).
* Dependencies: WordPress post meta API.
*
* @see class-prautoblogger.php -- Registers the hook.
* @see admin/class-dossier-page.php -- Dossier target; provides url_for_post().
* @see core/class-publisher.php -- Writes the run_id meta this class reads.
* @see class-prautoblogger.php — Registers the hook.
* @see core/class-publisher.php — Writes the metadata this class displays.
*/
class PRAutoBlogger_Post_Metabox {
/**
* Register the metabox for PRAutoBlogger-generated posts only.
* Register the metabox for the post editor.
*
* @return void
*/
@@ -36,7 +35,7 @@ class PRAutoBlogger_Post_Metabox {
add_meta_box(
'prautoblogger_generation_info',
__( 'PRAutoBlogger', 'prautoblogger' ),
__( 'PRAutoBlogger Generation Info', 'prautoblogger' ),
array( $this, 'render_metabox' ),
'post',
'side',
@@ -45,12 +44,13 @@ class PRAutoBlogger_Post_Metabox {
}
/**
* Render the dossier-link metabox.
* Render the generation metadata metabox.
*
* @param \WP_Post $post
*
* @param \WP_Post $post Current post.
* @return void
*/
public function render_metabox( \WP_Post $post ): void {
include PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/metabox-dossier-link.php';
include PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/metabox-generation-info.php';
}
}

13
includes/admin/class-review-queue.php Normal file → Executable file
View File

@@ -51,22 +51,9 @@ class PRAutoBlogger_Review_Queue {
$paged = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
$query = $this->get_pending_posts( $paged );
// v0.18.0 — runs halted by the per-run cost governor are routed
// here for human attention (they may have no draft post to list).
$halted_runs = $this->get_halted_runs();
include PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/review-queue.php';
}
/**
* Runs halted by the per-run cost governor, newest first.
*
* @return array<int, array<string, mixed>> Halted run rows (max 10).
*/
public function get_halted_runs(): array {
return PRAutoBlogger_Run_State::halted_runs( 10 );
}
/**
* Query generated draft posts awaiting review.
*

View File

@@ -8,7 +8,7 @@ declare(strict_types=1);
*
* What: Declarative field definitions for operational settings sections.
* Who calls it: PRAutoBlogger_Settings_Fields::get_fields() merges these in.
* Dependencies: PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL, PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE constants,
* Dependencies: PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL, PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX constants,
* PRAutoBlogger_Article_Typography (font choices), PRAutoBlogger_Image_Model_Registry.
*
* @see admin/class-settings-fields.php — Core fields and sections; calls get_extended_fields().
@@ -81,28 +81,6 @@ class PRAutoBlogger_Settings_Fields_Extended {
'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' ),
),
// ── Board Settings ─────────────────────────────────────────
array(
'id' => 'prautoblogger_board_poll_interval',
'label' => __( 'Board Poll Interval (seconds)', 'prautoblogger' ),
'type' => 'number',
'section' => 'prautoblogger_schedule',
'default' => 5,
'min' => 3,
'max' => 60,
'description' => __( 'How often the kanban board polls for status updates (seconds). Minimum 3s. Doubles automatically when no article is actively generating.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_board_published_window_days',
'label' => __( 'Published Column Window (days)', 'prautoblogger' ),
'type' => 'number',
'section' => 'prautoblogger_schedule',
'default' => 7,
'min' => 1,
'max' => 90,
'description' => __( 'How many days back the Published column shows articles. Increase to see older published articles on the board.', 'prautoblogger' ),
),
// ── Schedule & Budget ───────────────────────────────────────
array(
'id' => 'prautoblogger_daily_article_target',
@@ -257,12 +235,12 @@ class PRAutoBlogger_Settings_Fields_Extended {
'icon' => '🔑',
),
array(
'id' => 'prautoblogger_image_style_template',
'label' => __( 'Style Template', 'prautoblogger' ),
'id' => 'prautoblogger_image_style_suffix',
'label' => __( 'Style Suffix', 'prautoblogger' ),
'type' => 'textarea',
'section' => 'prautoblogger_images',
'default' => PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE,
'description' => __( 'The full image prompt template. Must contain exactly one {{ topic_summary }} token, which is filled with a 1-2 sentence topic/mechanism summary per article. The rest is brand-locked editorial style. Replaces the old Style Suffix (now deprecated). Changing mid-run causes visible style drift.', 'prautoblogger' ),
'default' => PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX,
'description' => __( 'Appended to every image prompt. Controls visual look. Changing mid-run causes visible style drift.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_image_prompt_instructions',
@@ -270,7 +248,7 @@ class PRAutoBlogger_Settings_Fields_Extended {
'type' => 'textarea',
'section' => 'prautoblogger_images',
'default' => PRAutoBlogger_Image_Prompt_Builder::REWRITER_SYSTEM_PROMPT,
'description' => __( 'System prompt given to the rewriter LLM that turns each article into a SCENE (a 1-2 sentence editorial topic/mechanism summary, substituted into the Style Template) plus a CAPTION (HTML text shown below the image). Changing this reshapes the look of all future images. Leave blank to use the default.', 'prautoblogger' ),
'description' => __( 'System prompt given to the rewriter LLM that turns each article into a SCENE + CAPTION for the image generator. Changing this reshapes the look of all future images. Leave blank to use the default.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_image_nsfw_retry',
@@ -280,37 +258,6 @@ class PRAutoBlogger_Settings_Fields_Extended {
'default' => '1',
'description' => __( 'When the provider rejects an image prompt as NSFW, retry once with a generic fallback scene built from the article title. Disable to fail fast if the filter gets trigger-happy.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_image_compose_enabled',
'label' => __( 'Compose Branded Variants', 'prautoblogger' ),
'type' => 'toggle',
'section' => 'prautoblogger_images',
'default' => '1',
'description' => __( 'Render branded social variants (teal band, logo, baked caption) from each generated image via the local deterministic composer. Auto-degrades to plain resizing or pass-through if the server lacks an image library — publishing is never blocked.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_image_compose_variants',
'label' => __( 'Composed Variant Set', 'prautoblogger' ),
'type' => 'text',
'section' => 'prautoblogger_images',
'default' => 'og,square',
'description' => __( 'Comma-separated variants to render for Image A. Supported: og (1200×630 social share), square (1080×1080 card). Unknown values are ignored.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_image_featured_mark_enabled',
'label' => __( 'Featured Image Corner Mark', 'prautoblogger' ),
'type' => 'toggle',
'section' => 'prautoblogger_images',
'default' => '1',
'description' => __( 'Overlay a small semi-transparent Peptide Repo mark in the bottom-right corner of featured images, so scraped or re-shared images carry attribution.', 'prautoblogger' ),
),
array(
'id' => 'prautoblogger_runware_model_catalog',
'label' => __( 'Runware Model Catalog', 'prautoblogger' ),
'type' => 'runware_catalog_sync',
'section' => 'prautoblogger_images',
'description' => __( 'Live model catalog sync status and on-demand refresh.', 'prautoblogger' ),
),
);
}
}

View File

@@ -1,72 +0,0 @@
<?php
declare(strict_types=1);
/**
* WP-CLI commands for PRAutoBlogger.
*
* Registers custom wp-cli commands exposed to the plugin.
*/
class PRAutoBlogger_WP_CLI_Commands {
/**
* Register WP-CLI commands.
*
* Called on plugins_loaded hook.
*/
public static function register(): void {
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
// Command: wp prautoblogger opik:eval
\WP_CLI::add_command(
'prautoblogger opik:eval',
array( self::class, 'opik_eval_command' ),
array(
'shortdesc' => 'Run Opik evals on the frozen dataset',
'synopsis' => array(
array(
'type' => 'assoc',
'name' => 'limit',
'description' => 'Max items to run (0 = all)',
'optional' => true,
'default' => '0',
),
array(
'type' => 'flag',
'name' => 'dry-run',
'description' => 'Skip Opik API push; score locally only',
'optional' => true,
),
),
)
);
}
/**
* Run eval on the frozen dataset.
*
* @param array $args Positional args (unused).
* @param array $assoc_args Associative args: limit, dry-run.
*
* @return void
*/
public static function opik_eval_command( array $args, array $assoc_args ): void {
// Check if Opik is enabled.
if ( empty( PRAUTOBLOGGER_OPIK_API_KEY ) || empty( PRAUTOBLOGGER_OPIK_WORKSPACE ) ) {
if ( ! isset( $assoc_args['dry-run'] ) ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_echo -- CLI output
echo "Warning: Opik is not configured. Running with --dry-run only.\n";
$assoc_args['dry-run'] = true;
}
}
$limit = absint( $assoc_args['limit'] ?? 0 );
$dry_run = isset( $assoc_args['dry-run'] );
$runner = new PRAutoBlogger_Opik_Eval_Runner();
$result = $runner->run( $limit, $dry_run );
exit( $result['items_run'] > 0 ? 0 : 1 );
}
}

17
includes/class-activator.php Normal file → Executable file
View File

@@ -31,22 +31,14 @@ class PRAutoBlogger_Activator {
self::set_default_options();
self::schedule_cron();
self::backpopulate_run_id_meta_v081();
PRAutoBlogger_Migrate_Prompt_Seed_V0180::run();
// Store the DB version so we can run migrations on future updates.
update_option( 'prautoblogger_db_version', PRAUTOBLOGGER_DB_VERSION, false );
}
/**
* Delegate to the schema installers — see those classes.
*
* `Schema_Installer` owns the v1.1.0 tables; `Pipeline_Schema_Installer`
* owns the v0.18.0 / db-1.2.0 Pipeline v2 substrate tables. Both are
* dbDelta-idempotent and safe to re-run on any version mismatch.
*/
/** Delegate to `PRAutoBlogger_Schema_Installer::install()` — see that class. */
private static function create_tables(): void {
PRAutoBlogger_Schema_Installer::install();
PRAutoBlogger_Pipeline_Schema_Installer::install();
}
/**
@@ -68,8 +60,6 @@ class PRAutoBlogger_Activator {
'prautoblogger_niche_description' => '',
'prautoblogger_target_subreddits' => '[]',
'prautoblogger_monthly_budget_usd' => 50.00,
'prautoblogger_per_run_cost_ceiling_usd' => PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD,
'prautoblogger_request_json_retention_days' => PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS,
'prautoblogger_tone' => 'informational',
'prautoblogger_min_word_count' => 800,
'prautoblogger_max_word_count' => 2000,
@@ -140,11 +130,6 @@ class PRAutoBlogger_Activator {
wp_schedule_event( $tomorrow, 'daily', 'prautoblogger_reap_orphan_research_rows' );
}
}
// v0.15.0: daily Runware model catalog sync.
if ( ! wp_next_scheduled( 'prautoblogger_sync_runware_models' ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'prautoblogger_sync_runware_models' );
}
}
/**

View File

@@ -151,53 +151,6 @@ class PRAutoBlogger_Ajax_Handlers {
wp_send_json_success( $results );
}
/**
* AJAX handler: sync Runware model catalog on demand.
*
* Nonce-protected and requires manage_options capability.
* Returns the updated cache timestamp and model count.
*
* Side effects: makes HTTP request to Runware API, writes WP options.
*/
public function on_ajax_sync_runware_models_now(): void {
check_ajax_referer( 'prautoblogger_sync_runware_models_now', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
return;
}
try {
$catalog = new PRAutoBlogger_Runware_Model_Catalog();
$success = $catalog->sync();
if ( ! $success ) {
wp_send_json_error( array( 'message' => __( 'Catalog sync failed. Check logs for details.', 'prautoblogger' ) ) );
return;
}
$models = $catalog->get_models();
$synced_at = $catalog->get_last_synced_at();
$synced_at_str = $synced_at
? wp_date( __( 'Y-m-d H:i:s', 'prautoblogger' ), $synced_at )
: __( 'Never', 'prautoblogger' );
wp_send_json_success(
array(
'message' => __( 'Runware model catalog synced successfully.', 'prautoblogger' ),
'model_count' => count( $models ),
'synced_at' => $synced_at_str,
)
);
} catch ( \Throwable $e ) {
PRAutoBlogger_Logger::instance()->error(
sprintf( 'AJAX sync Runware models failed: %s (%s)', $e->getMessage(), get_class( $e ) ),
'runware-catalog'
);
wp_send_json_error( array( 'message' => $e->getMessage() ) );
}
}
/**
* Get the shared model registry instance.
*

View File

@@ -30,7 +30,6 @@ class PRAutoBlogger_Autoloader {
'models/',
'frontend/',
'services/',
'services/opik/',
'ajax/',
);

View File

@@ -1,129 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* One-time and version-gated DB/option migrations for PRAutoBlogger.
*
* Extracted from PRAutoBlogger (class-prautoblogger.php) in v0.19.2 so the
* main orchestrator stays under the 300-line cap. All migration logic lives
* here; the orchestrator holds thin proxy methods for backward compat.
*
* Each migration is idempotent: guarded by a stored option flag so it never
* runs more than once per site.
*
* Triggered by: PRAutoBlogger::on_check_db_version() (admin_init)
* PRAutoBlogger::on_check_db_version_for_cron() (init, cron-only).
* Dependencies: PRAutoBlogger_Activator, PRAutoBlogger_Image_Model_Registry,
* PRAutoBlogger_Encryption, PRAutoBlogger_Migrate_Remove_Cloudflare_V0100.
*
* @see class-prautoblogger.php -- Orchestrator; holds proxy methods.
* @see class-activator.php -- Schema install / activate logic called here.
* @see ARCHITECTURE.md -- DB version history and migration discipline.
*/
class PRAutoBlogger_DB_Migrations {
/**
* Run all pending migrations.
*
* Called on `admin_init` (and on `init` for cron contexts). Idempotent.
*
* Side effects: may update database schema and wp_options rows.
*
* @return void
*/
public static function run(): void {
$stored_version = get_option( 'prautoblogger_db_version', '0' );
if ( version_compare( $stored_version, PRAUTOBLOGGER_DB_VERSION, '<' ) ) {
PRAutoBlogger_Activator::activate();
}
// One-time migration: switch to Gemini 2.5 Flash Lite for cost/speed.
if ( ! get_option( 'prautoblogger_migrated_gemini_flash_lite' ) ) {
update_option( 'prautoblogger_analysis_model', PRAUTOBLOGGER_DEFAULT_ANALYSIS_MODEL );
update_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL );
update_option( 'prautoblogger_editor_model', PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL );
update_option( 'prautoblogger_migrated_gemini_flash_lite', '1' );
}
// One-time migration (v0.8.0): the admin no longer has an independent
// Image Provider dropdown; provider is derived from the image model on
// save. Auto-heal any existing site where the saved provider doesn't
// match the saved model's provider. Runs once.
if ( ! get_option( 'prautoblogger_migrated_image_provider_v080' ) ) {
$saved_model = (string) get_option( 'prautoblogger_image_model', '' );
$provider = PRAutoBlogger_Image_Model_Registry::provider_for( $saved_model );
if ( '' !== $provider ) {
update_option( 'prautoblogger_image_provider', $provider );
}
update_option( 'prautoblogger_migrated_image_provider_v080', '1' );
}
// One-time migration (v0.8.2): reschedule the daily-generation cron in
// the site's configured timezone. Pre-v0.8.2 activator interpreted the
// admin "Generation Time" input as UTC; after v0.8.2 it honours the
// site timezone. Clears the stale UTC-scheduled event and re-queues
// using the timezone-aware helper. See class-activator.php.
PRAutoBlogger_Activator::reschedule_daily_in_site_timezone_v082();
// One-time migration (v3): switch to single-panel newspaper comic style.
if ( ! get_option( 'prautoblogger_migrated_style_suffix_v3' ) ) {
$known_old_prefixes = array(
'Style: a screengrab from a 1995', // v1: infomercial.
'Style: premium scientific lifestyle', // v2: photography.
);
$current = get_option( 'prautoblogger_image_style_suffix', '' );
$is_old = ( '' === $current );
foreach ( $known_old_prefixes as $prefix ) {
if ( false !== strpos( $current, $prefix ) ) {
$is_old = true;
break;
}
}
if ( $is_old ) {
update_option( 'prautoblogger_image_style_suffix', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX );
}
update_option( 'prautoblogger_migrated_style_suffix_v3', '1' );
}
// One-time migration (v4): remove caption-in-image instruction from style suffix.
if ( ! get_option( 'prautoblogger_migrated_style_suffix_v4' ) ) {
$current = get_option( 'prautoblogger_image_style_suffix', '' );
if ( false !== strpos( $current, 'caption text in a clean sans-serif font below the panel' ) ) {
update_option( 'prautoblogger_image_style_suffix', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX );
}
update_option( 'prautoblogger_migrated_style_suffix_v4', '1' );
}
// One-time migration (v0.16.0): editorial pivot -- comic Style Suffix
// replaced by editorial Style Template. Old value mirrored to a
// deprecated-keyed option for one version cycle.
if ( ! get_option( 'prautoblogger_migrated_style_template_v0160' ) ) {
$old_suffix = get_option( 'prautoblogger_image_style_suffix', '' );
if ( '' !== $old_suffix && false === get_option( 'prautoblogger_image_style_suffix_deprecated', false ) ) {
update_option( 'prautoblogger_image_style_suffix_deprecated', $old_suffix );
}
if ( '' === (string) get_option( 'prautoblogger_image_style_template', '' ) ) {
update_option( 'prautoblogger_image_style_template', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE );
}
update_option( 'prautoblogger_migrated_style_template_v0160', '1' );
}
// v0.9.0 -- Runware as default image model. v0.10.0 -- remove CF Workers AI.
PRAutoBlogger_Activator::migrate_default_image_v090();
PRAutoBlogger_Migrate_Remove_Cloudflare_V0100::run();
// One-time migration: re-wrap existing encrypted values with "enc:" prefix.
if ( ! get_option( 'prautoblogger_migrated_enc_prefix' ) ) {
$enc_options = array( 'prautoblogger_openrouter_api_key', 'prautoblogger_ga4_credentials_json', 'prautoblogger_runware_api_key' );
foreach ( $enc_options as $opt ) {
$val = get_option( $opt, '' );
if ( '' !== $val && ! PRAutoBlogger_Encryption::is_encrypted( $val ) ) {
delete_option( $opt );
}
}
update_option( 'prautoblogger_migrated_enc_prefix', '1' );
}
}
}

1
includes/class-deactivator.php Normal file → Executable file
View File

@@ -39,7 +39,6 @@ class PRAutoBlogger_Deactivator {
'prautoblogger_daily_generation',
'prautoblogger_collect_metrics',
'prautoblogger_reap_orphan_research_rows',
'prautoblogger_sync_runware_models',
);
foreach ( $hooks as $hook ) {

View File

@@ -4,26 +4,25 @@ declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Cron handlers for content generation and metrics collection.
* Cron/AJAX handlers for content generation, metrics collection, model registry.
*
* What: Daily generation, manual generation, queued-article processing,
* and metrics collection cron handlers. AJAX generation handlers
* live in PRAutoBlogger_Generation_Status_Poller (v0.18.3 split).
* Triggered by: PRAutoBlogger hook registration.
* Dependencies: Pipeline_Runner, Metrics_Collector, Generation_Lock, Logger.
*
* @see class-generation-status-poller.php — "Generate Now" AJAX + status poll.
* @see class-prautoblogger.php — Hook wiring.
* @see core/class-pipeline-runner.php — Actual generation pipeline.
* @see class-generation-lock.php — DB mutex.
* @see class-prautoblogger.php — Hook wiring.
* @see core/class-pipeline-runner.php — Actual generation pipeline.
* @see class-generation-lock.php — DB mutex.
*/
class PRAutoBlogger_Executor {
/** @var PRAutoBlogger_OpenRouter_Model_Registry|null Lazy-loaded singleton. */
private ?PRAutoBlogger_OpenRouter_Model_Registry $model_registry = null;
/** @var PRAutoBlogger_Generation_Status_Poller|null Lazy-loaded poller. */
private ?PRAutoBlogger_Generation_Status_Poller $poller = null;
/** Transient key for background generation status. */
private const STATUS_TRANSIENT = 'prautoblogger_generation_status';
/** How long to keep the result available for polling (seconds). */
private const STATUS_TTL = 600;
/**
* Handle the daily generation cron event.
@@ -54,7 +53,6 @@ class PRAutoBlogger_Executor {
sprintf( 'Daily generation %s: %s', get_class( $e ), $e->getMessage() ),
'scheduler'
);
$this->mark_current_run_failed();
PRAutoBlogger_Generation_Lock::release();
}
}
@@ -76,12 +74,79 @@ class PRAutoBlogger_Executor {
/**
* AJAX handler: kick off manual generation as a background cron job.
* Delegates to PRAutoBlogger_Generation_Status_Poller.
*
* Returns immediately so the browser never hits Hostinger's 120-second
* connection timeout. The frontend polls on_ajax_generation_status()
* every few seconds to get progress and final results.
*
* Side effects: schedules a WP-Cron event, writes a status transient.
*/
public function on_ajax_generate_now(): void {
$this->poller()->on_ajax_generate_now();
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
return;
}
$force = isset( $_POST['force'] ) && '1' === $_POST['force'];
if ( $force ) {
PRAutoBlogger_Generation_Lock::release();
delete_transient( self::STATUS_TRANSIENT );
}
// Check if a run is already in progress.
$current = get_transient( self::STATUS_TRANSIENT );
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
wp_send_json_success(
array(
'background' => true,
'message' => __( 'Generation already in progress.', 'prautoblogger' ),
)
);
return;
}
// Write initial "running" status for the frontend to poll.
set_transient(
self::STATUS_TRANSIENT,
array(
'status' => 'running',
'stage' => __( 'Starting generation...', 'prautoblogger' ),
'started' => time(),
'last_updated' => time(),
),
self::STATUS_TTL
);
// Schedule immediate one-shot cron event. WordPress will fire this
// on the next page load (or via wp-cron.php) in a separate PHP process
// that is not subject to the 120-second connection timeout.
if ( ! wp_next_scheduled( 'prautoblogger_manual_generation' ) ) {
wp_schedule_single_event( time(), 'prautoblogger_manual_generation' );
}
// Spawn the cron immediately via a non-blocking loopback request
// so we don't depend on the next visitor to trigger it.
spawn_cron();
// Direct non-blocking loopback to wp-cron.php — ensures the event
// fires even if DISABLE_WP_CRON is true or spawn_cron() no-ops.
wp_remote_post(
site_url( 'wp-cron.php?doing_wp_cron=' . sprintf( '%.22F', microtime( true ) ) ),
array(
'timeout' => 0.01,
'blocking' => false,
'sslverify' => false,
)
);
wp_send_json_success(
array(
'background' => true,
'message' => __( 'Generation started in background. Polling for status...', 'prautoblogger' ),
)
);
}
/**
@@ -99,18 +164,18 @@ class PRAutoBlogger_Executor {
if ( ! PRAutoBlogger_Generation_Lock::acquire() ) {
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
self::STATUS_TRANSIENT,
array(
'status' => 'error',
'message' => __( 'Could not acquire generation lock. Another run may be in progress.', 'prautoblogger' ),
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
self::STATUS_TTL
);
return;
}
try {
$this->poller()->update_generation_stage( __( 'Collecting sources from Reddit...', 'prautoblogger' ) );
$this->update_generation_stage( __( 'Collecting sources from Reddit...', 'prautoblogger' ) );
$runner = ( new PRAutoBlogger_Pipeline_Runner() )->set_skip_dedup( true );
$results = $runner->run();
@@ -119,7 +184,7 @@ class PRAutoBlogger_Executor {
// When articles ARE queued, the pipeline handles status + lock release.
if ( ! get_option( 'prautoblogger_article_queue' ) ) {
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
self::STATUS_TRANSIENT,
array(
'status' => 'complete',
'generated' => $results['generated'],
@@ -127,7 +192,7 @@ class PRAutoBlogger_Executor {
'rejected' => $results['rejected'],
'cost' => $results['cost'],
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
self::STATUS_TTL
);
PRAutoBlogger_Generation_Lock::release();
}
@@ -137,14 +202,13 @@ class PRAutoBlogger_Executor {
'pipeline'
);
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
self::STATUS_TRANSIENT,
array(
'status' => 'error',
'message' => $e->getMessage(),
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
self::STATUS_TTL
);
$this->mark_current_run_failed();
PRAutoBlogger_Generation_Lock::release();
}
}
@@ -167,44 +231,83 @@ class PRAutoBlogger_Executor {
delete_option( 'prautoblogger_article_queue' );
PRAutoBlogger_Generation_Lock::release();
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
self::STATUS_TRANSIENT,
array(
'status' => 'error',
'message' => $e->getMessage(),
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
self::STATUS_TTL
);
}
}
/** AJAX: return generation status for frontend polling. Delegates to poller. */
/** AJAX: return generation status for frontend polling. Recovers orphaned runs. */
public function on_ajax_generation_status(): void {
$this->poller()->on_ajax_generation_status();
}
/**
* Lazy-load the generation status poller.
*
* @return PRAutoBlogger_Generation_Status_Poller
*/
private function poller(): PRAutoBlogger_Generation_Status_Poller {
if ( null === $this->poller ) {
$this->poller = new PRAutoBlogger_Generation_Status_Poller();
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
return;
}
return $this->poller;
$status = get_transient( self::STATUS_TRANSIENT );
if ( ! is_array( $status ) ) {
wp_send_json_success( array( 'status' => 'idle' ) );
return;
}
if ( 'running' === $status['status'] ) {
$elapsed = time() - ( $status['started'] ?? 0 );
// Absolute timeout — give up after 10 minutes.
if ( $elapsed > self::STATUS_TTL ) {
$this->abort_orphaned_run( __( 'Generation timed out. Check the Activity Log.', 'prautoblogger' ) );
return;
}
// After 90s, check if a queued job died and needs re-scheduling.
if ( $elapsed > 90 && get_option( 'prautoblogger_article_queue' ) ) {
if ( ! wp_next_scheduled( PRAutoBlogger_Pipeline_Runner::CRON_ACTION ) ) {
wp_schedule_single_event( time(), PRAutoBlogger_Pipeline_Runner::CRON_ACTION );
spawn_cron();
}
}
// Stall = 5 min since last stage update (not since start).
$last_activity = $status['last_updated'] ?? $status['started'] ?? 0;
$idle_seconds = time() - $last_activity;
if ( $idle_seconds > 300 ) {
$this->abort_orphaned_run( __( 'Generation stalled. Check Activity Log.', 'prautoblogger' ) );
return;
}
}
wp_send_json_success( $status );
}
/** Clean up an orphaned generation run and report error. */
private function abort_orphaned_run( string $message ): void {
delete_transient( self::STATUS_TRANSIENT );
delete_option( 'prautoblogger_article_queue' );
PRAutoBlogger_Generation_Lock::release();
wp_send_json_success(
array(
'status' => 'error',
'message' => $message,
)
);
}
/**
* Mark this process's run failed after a fatal pipeline error
* (no-op outside a run; a governor-halted run stays halted — final
* states are sticky).
* Helper: update the generation stage for frontend polling.
*
* @return void
* @param string $stage Human-readable stage description.
*/
private function mark_current_run_failed(): void {
$run_id = PRAutoBlogger_Run_Context::current_run_id();
if ( null !== $run_id ) {
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
private function update_generation_stage( string $stage ): void {
$current = get_transient( self::STATUS_TRANSIENT );
if ( is_array( $current ) ) {
$current['stage'] = $stage;
$current['last_updated'] = time();
set_transient( self::STATUS_TRANSIENT, $current, self::STATUS_TTL );
}
}

View File

@@ -76,29 +76,6 @@ class PRAutoBlogger_Generation_Lock {
return null !== $row;
}
/**
* Get the Unix timestamp when the lock was acquired, or null if not held.
*
* Returns null when the lock is not set. The timestamp is the value written
* by acquire() — used by the status poller to detect infrastructure-timeout
* runs (lock held longer than STATUS_TTL → background PHP process died).
*
* @return int|null Unix timestamp, or null when the lock is absent.
*/
public static function get_acquired_at(): ?int {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$row = $wpdb->get_var(
$wpdb->prepare(
"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
self::LOCK_NAME
)
);
return null !== $row ? (int) $row : null;
}
/**
* Release the generation mutex.
*

View File

@@ -1,260 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* AJAX handlers for "Generate Now" + status polling.
*
* What: Two AJAX endpoints: kick-off (fire-and-forget cron spawn) and the
* status poll that drives the admin UI spinner. Extracted from
* PRAutoBlogger_Executor in v0.18.3 to keep each file under 300 lines.
*
* R2/R3 resilience (v0.18.3):
* - R2(a): on_ajax_generate_now() renews the transient with the
* full STATUS_TTL on every stage update via update_generation_stage().
* - R2(b): on_ajax_generation_status() detects lock-held-but-transient-gone
* when the lock has been held > STATUS_TTL seconds (Hostinger background-
* process death); marks the stuck run failed + surfaces a human-readable
* "infrastructure timeout" message for the Activity Log.
* - R3: on_ajax_generation_status() returns status:running (with
* started_at) when the transient is absent but the lock IS held and
* within TTL — so the button reflects reality during long runs rather
* than silently resetting to idle.
*
* Who calls it: PRAutoBlogger hook registration (wp_ajax_prautoblogger_*).
* Dependencies: PRAutoBlogger_Generation_Lock, PRAutoBlogger_Run_State,
* PRAutoBlogger_Run_Context, PRAutoBlogger_Pipeline_Runner,
* PRAutoBlogger_Logger.
*
* @see class-executor.php — Cron handlers (daily, manual, queued).
* @see class-generation-lock.php — DB mutex (acquire/release/timestamps).
* @see core/class-pipeline-status.php — Transient broadcast helpers.
* @see ARCHITECTURE.md #21 — Run lifecycle and reaper design.
*/
class PRAutoBlogger_Generation_Status_Poller {
/** Transient key for background generation status (shared with Pipeline_Status). */
public const STATUS_TRANSIENT = 'prautoblogger_generation_status';
/**
* How long (seconds) to keep the status transient readable.
* Renewed on every stage transition so a long run doesn't expire it early.
*/
public const STATUS_TTL = 600;
/**
* AJAX handler: kick off manual generation as a background cron job.
*
* Returns immediately so the browser never hits Hostinger's connection
* timeout. The frontend polls on_ajax_generation_status() every few
* seconds for progress and final results.
*
* Side effects: schedules a WP-Cron event, writes a status transient.
*/
public function on_ajax_generate_now(): void {
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
return;
}
$force = isset( $_POST['force'] ) && '1' === $_POST['force'];
if ( $force ) {
PRAutoBlogger_Generation_Lock::release();
delete_transient( self::STATUS_TRANSIENT );
}
// Check if a run is already in progress.
$current = get_transient( self::STATUS_TRANSIENT );
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
wp_send_json_success(
array(
'background' => true,
'message' => __( 'Generation already in progress.', 'prautoblogger' ),
)
);
return;
}
// Write initial "running" status for the frontend to poll.
set_transient(
self::STATUS_TRANSIENT,
array(
'status' => 'running',
'stage' => __( 'Starting generation...', 'prautoblogger' ),
'started' => time(),
'last_updated' => time(),
),
self::STATUS_TTL
);
// Schedule immediate one-shot cron event. WordPress will fire this
// on the next page load (or via wp-cron.php) in a separate PHP process
// not subject to the connection timeout.
if ( ! wp_next_scheduled( 'prautoblogger_manual_generation' ) ) {
wp_schedule_single_event( time(), 'prautoblogger_manual_generation' );
}
// Spawn the cron immediately via a non-blocking loopback request
// so we don't depend on the next visitor to trigger it.
spawn_cron();
// Direct non-blocking loopback to wp-cron.php — ensures the event
// fires even if DISABLE_WP_CRON is true or spawn_cron() no-ops.
wp_remote_post(
site_url( 'wp-cron.php?doing_wp_cron=' . sprintf( '%.22F', microtime( true ) ) ),
array(
'timeout' => 0.01,
'blocking' => false,
'sslverify' => false,
)
);
wp_send_json_success(
array(
'background' => true,
'message' => __( 'Generation started in background. Polling for status...', 'prautoblogger' ),
)
);
}
/** AJAX: return generation status for frontend polling. Recovers orphaned runs. */
public function on_ajax_generation_status(): void {
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
return;
}
$status = get_transient( self::STATUS_TRANSIENT );
// R2(b) + R3: transient is gone — check the lock before returning idle.
if ( ! is_array( $status ) ) {
$this->handle_missing_transient();
return;
}
if ( 'running' === $status['status'] ) {
$elapsed = time() - ( $status['started'] ?? 0 );
// Absolute timeout — give up after STATUS_TTL.
if ( $elapsed > self::STATUS_TTL ) {
$this->abort_orphaned_run( __( 'Generation timed out. Check the Activity Log.', 'prautoblogger' ) );
return;
}
// After 90s, check if a queued job died and needs re-scheduling.
if ( $elapsed > 90 && get_option( 'prautoblogger_article_queue' ) ) {
if ( ! wp_next_scheduled( PRAutoBlogger_Pipeline_Runner::CRON_ACTION ) ) {
wp_schedule_single_event( time(), PRAutoBlogger_Pipeline_Runner::CRON_ACTION );
spawn_cron();
}
}
// Stall = 5 min since last stage update (not since start).
$last_activity = $status['last_updated'] ?? $status['started'] ?? 0;
$idle_seconds = time() - $last_activity;
if ( $idle_seconds > 300 ) {
$this->abort_orphaned_run( __( 'Generation stalled. Check Activity Log.', 'prautoblogger' ) );
return;
}
}
wp_send_json_success( $status );
}
/**
* Handle the case where the status transient is absent.
*
* R3: if lock is HELD and within TTL → return status:running so the
* button reflects reality during long background runs.
* R2(b): if lock is held but has been held > STATUS_TTL → the background
* PHP process died without releasing it; mark the run failed and
* surface "infrastructure timeout" to the UI.
*
* @return void Sends JSON and exits.
*/
private function handle_missing_transient(): void {
$acquired_at = PRAutoBlogger_Generation_Lock::get_acquired_at();
if ( null === $acquired_at ) {
// Lock not held — genuinely idle.
wp_send_json_success( array( 'status' => 'idle' ) );
return;
}
$lock_age = time() - $acquired_at;
if ( $lock_age > self::STATUS_TTL ) {
// Lock held longer than STATUS_TTL: background process died.
// R2(b): mark the stuck run failed + surface a clear error.
PRAutoBlogger_Logger::instance()->warning(
sprintf(
'Status transient absent and lock held for %ds (> %ds TTL) — background process died; marking run failed.',
$lock_age,
self::STATUS_TTL
),
'pipeline'
);
$this->abort_orphaned_run(
__( 'Generation failed — infrastructure timeout. Check Activity Log for details.', 'prautoblogger' )
);
return;
}
// R3: lock is fresh (within TTL) but transient is gone — long run in
// progress (pipeline broadcast hasn't fired yet, or transient was
// evicted by object-cache pressure). Return running so the button
// does not silently reset to idle.
wp_send_json_success(
array(
'status' => 'running',
'stage' => __( 'Generation in progress (background). Check Activity Log for details.', 'prautoblogger' ),
'started' => $acquired_at,
'last_updated' => $acquired_at,
)
);
}
/** Clean up an orphaned generation run and report error. */
private function abort_orphaned_run( string $message ): void {
// Mark the stuck run as failed in the audit ledger.
$queue = get_option( 'prautoblogger_article_queue' );
if ( is_array( $queue ) && ! empty( $queue['run_id'] ) ) {
PRAutoBlogger_Run_State::mark_status( (string) $queue['run_id'], 'failed' );
}
// Also attempt to close the current active run from Run_Context.
$run_id = PRAutoBlogger_Run_Context::current_run_id();
if ( null !== $run_id ) {
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
}
delete_transient( self::STATUS_TRANSIENT );
delete_option( 'prautoblogger_article_queue' );
PRAutoBlogger_Generation_Lock::release();
wp_send_json_success(
array(
'status' => 'error',
'message' => $message,
)
);
}
/**
* Update the generation stage text for frontend polling.
* Renews the transient TTL at every call so a long run doesn't expire it.
*
* @param string $stage Human-readable stage description.
*/
public function update_generation_stage( string $stage ): void {
$current = get_transient( self::STATUS_TRANSIENT );
if ( is_array( $current ) ) {
$current['stage'] = $stage;
$current['last_updated'] = time();
// R2(a): renew the TTL on every stage update so the transient
// outlives any single LLM call (STATUS_TTL from last activity).
set_transient( self::STATUS_TRANSIENT, $current, self::STATUS_TTL );
}
}
}

View File

@@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* One-shot v0.18.0 migration — seed the versioned prompt registry.
*
* What: Writes the canonical hardcoded prompt texts (content, analysis,
* editor, research, illustration rewriter, image Style Template)
* into `wp_prautoblogger_prompts` as immutable version 1 and
* activates them. Idempotent twice over: gated by the
* `prautoblogger_migrated_prompt_seed_v0180` flag AND seed_v1()
* itself skips any key that already has rows. The flag is only set
* when the table was actually reachable, so a failed seed
* self-heals on the next activation / version-mismatch pass.
* Standalone class per the Migrate_Remove_Cloudflare_V0100
* precedent (keeps Activator under the 300-line cap).
* Who triggers it: PRAutoBlogger_Activator::activate() — on activation and
* on every db-version mismatch.
* Dependencies: PRAutoBlogger_Prompt_Registry(_Writer), get_option.
*
* @see class-activator.php — Sole caller.
* @see core/class-prompt-registry-writer.php — seed_v1() implementation.
* @see includes/class-migrate-remove-cloudflare-v0100.php — Pattern precedent.
*/
class PRAutoBlogger_Migrate_Prompt_Seed_V0180 {
/** Option flag marking the seed as complete. */
private const FLAG = 'prautoblogger_migrated_prompt_seed_v0180';
/**
* Run the seed once.
*
* Side effects: up to 12 INSERTs into the prompts table, one INFO log
* line, one option write.
*
* @return void
*/
public static function run(): void {
if ( get_option( self::FLAG ) ) {
return;
}
if ( ! PRAutoBlogger_Prompt_Registry::is_available() ) {
return; // Table missing — retry on the next migration pass.
}
$seeded = PRAutoBlogger_Prompt_Registry_Writer::seed_v1( 'seed:v0.18.0' );
if ( class_exists( 'PRAutoBlogger_Logger', false ) ) {
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Prompt registry seeded: %d key(s) written as v1.', $seeded ),
'activator'
);
}
update_option( self::FLAG, '1' );
}
}

View File

@@ -1,179 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Creates / updates the Pipeline v2 substrate tables via `dbDelta` (db 1.3.0).
*
* What: Owns the six pipeline substrate tables — the versioned prompt
* registry (`prompts`), the audit child tables (`run_sources`,
* `run_decisions`), and the run ledger / state machine tables
* (`runs`, `run_stages`), and the immutable stage-input version
* store (`stage_inputs`, v0.20.0 / db 1.3.0 — edit + re-run forks
* and idea seeds). Kept separate from the original
* PRAutoBlogger_Schema_Installer so both classes stay under the
* 300-line cap and the v1.1.0 schema remains byte-stable.
* Who triggers it: PRAutoBlogger_Activator::activate() — on activation and
* on every `prautoblogger_db_version` mismatch (self-healing
* auto-migration via PRAutoBlogger::on_check_db_version()).
* Dependencies: WordPress $wpdb, dbDelta() from wp-admin/includes/upgrade.php.
*
* @see class-schema-installer.php — v1.1.0 tables (source data, logs, scores).
* @see class-activator.php — Sole caller.
* @see core/class-prompt-registry.php — Reads/writes the prompts table.
* @see core/class-run-state.php — Reads/writes runs + run_stages.
* @see ARCHITECTURE.md — Database schema section documents each table.
*/
class PRAutoBlogger_Pipeline_Schema_Installer {
/**
* Create (or upgrade) the Pipeline v2 substrate tables.
*
* `dbDelta` is idempotent: it creates missing tables, adds missing
* columns and indexes, and never drops anything — matching the
* plugin's forward-only schema policy. Safe to re-run on every
* version mismatch.
*
* Side effects: up to six CREATE TABLE / ALTER TABLE statements.
*
* @return void
*/
public static function install(): void {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$prefix = $wpdb->prefix . 'prautoblogger_';
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
// Versioned prompt registry. Versions are immutable: writes create
// new (prompt_key, version) rows; exactly one row per key has
// active = 1. `prompt_key` (not `key`) because KEY is reserved SQL.
$sql_prompts = "CREATE TABLE {$prefix}prompts (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
prompt_key VARCHAR(64) NOT NULL,
version INT UNSIGNED NOT NULL DEFAULT 1,
body LONGTEXT NOT NULL,
model VARCHAR(100) DEFAULT NULL,
params_json LONGTEXT DEFAULT NULL,
author VARCHAR(100) NOT NULL DEFAULT '',
created_at DATETIME NOT NULL,
active TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY key_version (prompt_key, version),
KEY key_active (prompt_key, active)
) {$charset_collate};";
// Research-source audit rows: one row per source a run considered,
// with the keep/discard decision. Consolidates the old
// source_ids_json + _prautoblogger_research_sources scatter for
// new runs (no backfill of historical runs).
$sql_run_sources = "CREATE TABLE {$prefix}run_sources (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
run_id VARCHAR(36) NOT NULL,
agent_role VARCHAR(50) NOT NULL DEFAULT '',
source_url VARCHAR(500) DEFAULT NULL,
doi VARCHAR(255) DEFAULT NULL,
kept TINYINT(1) NOT NULL DEFAULT 0,
reason TEXT DEFAULT NULL,
quality_score FLOAT DEFAULT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY run_id (run_id)
) {$charset_collate};";
// Stage-decision audit rows: verdict + rationale per pipeline
// stage. citation_score is nullable until the Phase-2 editorial
// loop computes it.
$sql_run_decisions = "CREATE TABLE {$prefix}run_decisions (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
run_id VARCHAR(36) NOT NULL,
stage VARCHAR(50) NOT NULL,
verdict VARCHAR(50) NOT NULL,
rationale TEXT DEFAULT NULL,
citation_score FLOAT DEFAULT NULL,
human_modified TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY run_id (run_id)
) {$charset_collate};";
// Per-run ledger + lifecycle row. reserved/settled/ceiling drive the
// Cost_Governor's atomic reserve-before-call check; pinned_prompts_json
// freezes the prompt versions a run uses at start; status feeds the
// run state machine (pending|running|done|failed|halted).
$sql_runs = "CREATE TABLE {$prefix}runs (
run_id VARCHAR(36) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
ceiling_usd DECIMAL(10,6) NOT NULL DEFAULT 0,
reserved_usd DECIMAL(10,6) NOT NULL DEFAULT 0,
settled_usd DECIMAL(10,6) NOT NULL DEFAULT 0,
overage_usd DECIMAL(10,6) NOT NULL DEFAULT 0,
pinned_prompts_json LONGTEXT DEFAULT NULL,
started_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
finished_at DATETIME DEFAULT NULL,
PRIMARY KEY (run_id),
KEY status (status)
) {$charset_collate};";
// Per-run per-stage state rows. The idempotency key is
// (run_id, stage, agent_role, item_key): agent_role is the Phase-2
// fan-out dimension (quorum members), item_key scopes article-level
// stages within multi-article runs ('' for run-level stages).
// meta_json holds the stage output for resume-without-recharge.
$sql_run_stages = "CREATE TABLE {$prefix}run_stages (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
run_id VARCHAR(36) NOT NULL,
stage VARCHAR(50) NOT NULL,
agent_role VARCHAR(50) NOT NULL DEFAULT '',
item_key VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(20) NOT NULL DEFAULT 'pending',
attempt SMALLINT UNSIGNED NOT NULL DEFAULT 1,
cost_usd DECIMAL(10,6) NOT NULL DEFAULT 0,
meta_json LONGTEXT DEFAULT NULL,
human_modified TINYINT(1) NOT NULL DEFAULT 0,
stale TINYINT(1) NOT NULL DEFAULT 0,
started_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
finished_at DATETIME DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY run_stage_role_item (run_id, stage, agent_role, item_key),
KEY status_updated (status, updated_at)
) {$charset_collate};";
// Immutable stage-input version store (v0.20.0 / db 1.3.0, M3
// edit + re-run). Rows are INSERT-only: a human edit creates the
// next (scope, version) row -- the original input (the
// generation_log.request_json of the executed call) is never
// overwritten (CPO guardrail 1). source='seed' rows persist the
// Article_Idea payload at worker start so re-run-from-here can
// reconstruct the exact idea (item_key hash stability); 'human'
// rows are edit forks. Human fork bodies are retention-pruned
// like all heavy payloads; seed rows (~1KB) are structural and
// kept for the life of the run.
$sql_stage_inputs = "CREATE TABLE {$prefix}stage_inputs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
run_id VARCHAR(36) NOT NULL,
stage VARCHAR(50) NOT NULL DEFAULT '',
agent_role VARCHAR(50) NOT NULL DEFAULT '',
item_key VARCHAR(64) NOT NULL DEFAULT '',
version INT UNSIGNED NOT NULL DEFAULT 1,
source VARCHAR(20) NOT NULL DEFAULT 'human',
request_json LONGTEXT DEFAULT NULL,
author VARCHAR(100) NOT NULL DEFAULT '',
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY scope_version (run_id, stage, agent_role, item_key, version),
KEY run_id (run_id)
) {$charset_collate};";
dbDelta( $sql_prompts );
dbDelta( $sql_run_sources );
dbDelta( $sql_run_decisions );
dbDelta( $sql_runs );
dbDelta( $sql_run_stages );
dbDelta( $sql_stage_inputs );
}
}

View File

@@ -6,12 +6,20 @@ declare(strict_types=1);
*
* Main orchestrator for the PRAutoBlogger plugin.
*
* Registers all WordPress hooks and wires up dependencies.
* DB/option migrations extracted to PRAutoBlogger_DB_Migrations (v0.19.2).
* Registers all WordPress hooks (actions and filters) and wires up dependencies.
* This is the ONLY place hooks are registered — individual classes contain only
* business logic, not hook registration.
*
* @see prautoblogger.php -- Plugin bootstrap.
* @see class-db-migrations.php -- One-time DB/option migrations.
* @see ARCHITECTURE.md -- Data flow diagram.
* Triggered by: prautoblogger() singleton in prautoblogger.php, called on `plugins_loaded`.
* Dependencies: All other plugin classes (loaded via autoloader), PRAutoBlogger_Executor.
*
* @see prautoblogger.php — Plugin bootstrap that instantiates this class.
* @see class-executor.php — Cron/AJAX handlers for generation, model registry.
* @see class-ajax-handlers.php — Non-generation AJAX endpoints (images, models, test).
* @see class-generation-lock.php — DB mutex for single-writer generation.
* @see core/class-pipeline-runner.php — Executes the generation pipeline.
* @see ARCHITECTURE.md — Data flow diagram showing how classes interact.
* @see CONVENTIONS.md — Hook naming conventions.
*/
class PRAutoBlogger {
@@ -20,12 +28,14 @@ class PRAutoBlogger {
/** @var PRAutoBlogger_Executor Handles generation cron/AJAX, model registry. */
private PRAutoBlogger_Executor $executor;
/** @var PRAutoBlogger_Ajax_Handlers Handles non-generation AJAX. */
/** @var PRAutoBlogger_Ajax_Handlers Handles non-generation AJAX (images, models, test). */
private PRAutoBlogger_Ajax_Handlers $ajax_handlers;
/**
* Register all hooks and initialize the plugin.
* Called once on `plugins_loaded`. Idempotent.
*
* Side effects: registers WordPress actions and filters.
*/
public function run(): void {
if ( $this->initialized ) {
@@ -36,8 +46,6 @@ class PRAutoBlogger {
$this->ajax_handlers = new PRAutoBlogger_Ajax_Handlers( $this->executor->get_model_registry() );
add_action( 'admin_init', array( $this, 'on_check_db_version' ) );
// v0.18.0: cron requests must also self-heal the schema.
add_action( 'init', array( $this, 'on_check_db_version_for_cron' ) );
add_filter( 'cron_schedules', array( $this, 'filter_add_cron_schedules' ) );
if ( is_admin() ) {
@@ -47,36 +55,18 @@ class PRAutoBlogger {
$this->register_cron_hooks();
$this->register_frontend_hooks();
$this->register_ajax_hooks();
$this->register_cli_hooks();
/** Fires after PRAutoBlogger has finished registering all hooks. */
do_action( 'prautoblogger_loaded' );
}
/**
* Register admin-only hooks (settings, notices, metabox, board, dossier, widget).
*
* Menu-ordering rule (v0.19.1): parent menu must register at priority 10 before
* any submenu (priority 11+). WordPress resolves the submenu hookname via
* get_plugin_page_hookname() at add_submenu_page() time; if the parent slot in
* $admin_page_hooks is unset, WP falls back to admin_page_* -> 404 at request
* time. See ARCHITECTURE.md §Board for the full trace.
*/
/** Register admin-only hooks (settings, notices, metabox, dashboard widget). */
private function register_admin_hooks(): void {
$admin_page = new PRAutoBlogger_Admin_Page();
add_action( 'admin_menu', array( $admin_page, 'on_register_menu' ), 10 );
add_action( 'admin_menu', array( $admin_page, 'on_register_menu' ) );
add_action( 'admin_init', array( $admin_page, 'on_register_settings' ) );
add_action( 'admin_enqueue_scripts', array( $admin_page, 'on_enqueue_assets' ) );
$board_page = new PRAutoBlogger_Board_Page();
add_action( 'admin_menu', array( $board_page, 'on_register_menu' ), 11 );
add_action( 'admin_enqueue_scripts', array( $board_page, 'on_enqueue_assets' ) );
// Dossier: link-accessed hidden submenu, priority 12 (after board).
$dossier_page = new PRAutoBlogger_Dossier_Page();
add_action( 'admin_menu', array( $dossier_page, 'on_register_menu' ), 12 );
add_action( 'admin_enqueue_scripts', array( $dossier_page, 'on_enqueue_assets' ) );
add_action( 'admin_notices', array( new PRAutoBlogger_Admin_Notices(), 'on_display_notices' ) );
add_action( 'add_meta_boxes', array( new PRAutoBlogger_Post_Metabox(), 'on_register_metabox' ) );
add_action( 'admin_menu', array( new PRAutoBlogger_Metrics_Page(), 'on_register_menu' ) );
@@ -91,6 +81,7 @@ class PRAutoBlogger {
( new PRAutoBlogger_Post_List_Columns() )->register();
// Block false update notifications — our slug collides with another plugin.
add_filter( 'site_transient_update_plugins', array( $this, 'filter_block_false_updates' ) );
}
@@ -110,7 +101,13 @@ class PRAutoBlogger {
private function register_cron_hooks(): void {
add_action( 'prautoblogger_daily_generation', array( $this->executor, 'on_daily_generation' ) );
add_action( 'prautoblogger_collect_metrics', array( $this->executor, 'on_collect_metrics' ) );
// Manual "Generate Now" runs as a one-shot cron event to avoid
// Hostinger's 120-second web-server connection timeout.
add_action( 'prautoblogger_manual_generation', array( $this->executor, 'on_manual_generation' ) );
// Chained article generation — each queued article fires as its own
// cron event so it gets a fresh PHP process and execution time budget.
add_action(
PRAutoBlogger_Pipeline_Runner::CRON_ACTION,
array( $this->executor, 'on_process_article_queue' )
@@ -118,44 +115,53 @@ class PRAutoBlogger {
$registry = $this->executor->get_model_registry();
add_action( 'prautoblogger_refresh_model_registry', array( $registry, 'refresh' ) );
add_action( 'prautoblogger_sync_runware_models', array( new PRAutoBlogger_Runware_Model_Catalog(), 'sync' ) );
// Opik observability: async trace/span dispatch.
add_action(
'prautoblogger_opik_dispatch',
static function (): void {
if ( ! defined( 'PRAUTOBLOGGER_OPIK_API_KEY' ) || empty( PRAUTOBLOGGER_OPIK_API_KEY ) ) {
return;
}
$client = new PRAutoBlogger_Opik_Client(
$client = new PRAutoBlogger_Opik_Client(
PRAUTOBLOGGER_OPIK_API_KEY,
PRAUTOBLOGGER_OPIK_WORKSPACE,
PRAUTOBLOGGER_OPIK_URL_OVERRIDE
);
$dispatcher = new PRAutoBlogger_Opik_Dispatcher( $client, new PRAutoBlogger_Opik_Span_Queue() );
$queue = new PRAutoBlogger_Opik_Span_Queue();
$dispatcher = new PRAutoBlogger_Opik_Dispatcher( $client, $queue );
$dispatcher->dispatch();
update_option( 'prautoblogger_opik_last_dispatch', time() );
}
);
// Opik settings registration.
if ( is_admin() ) {
new PRAutoBlogger_Opik_Settings();
}
// v0.20.0 (M3): operator re-run jobs — chained-cron, never synchronous.
$rerun_executor = new PRAutoBlogger_Rerun_Executor();
add_action( PRAutoBlogger_Rerun_Executor::REPLAY_ACTION, array( $rerun_executor, 'on_replay_job' ), 10, 5 );
add_action( PRAutoBlogger_Rerun_Executor::REBUILD_ACTION, array( $rerun_executor, 'on_rebuild_job' ), 10, 4 );
// Single-idea generation from the Ideas browser page.
add_action( 'prautoblogger_generate_from_idea', array( 'PRAutoBlogger_Ideas_Browser', 'on_cron_generate_from_idea' ) );
add_action( 'prautoblogger_reap_orphan_research_rows', array( 'PRAutoBlogger_Research_Reaper', 'on_cron' ) );
add_action( 'prautoblogger_reap_orphan_research_rows', array( 'PRAutoBlogger_Run_Reaper', 'on_cron' ) );
// v0.8.1: daily reaper for orphan `llm_research` rows (when a
// pipeline dies before amortize_research_costs runs).
add_action( 'prautoblogger_reap_orphan_research_rows', array( 'PRAutoBlogger_Research_Reaper', 'on_cron' ) );
// v0.8.1: WP-CLI manual trigger for the reaper. Only registers when
// WP-CLI is present; no-op in normal HTTP requests.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
\WP_CLI::add_command(
'prautoblogger reap-research',
static function (): void {
$stats = PRAutoBlogger_Research_Reaper::reap();
\WP_CLI::success( sprintf( 'Reaped %d, deleted %d, skipped %d.', (int) $stats['reaped'], (int) $stats['deleted'], (int) $stats['skipped'] ) );
\WP_CLI::success(
sprintf(
'Reaped %d, deleted %d (stale), skipped %d.',
(int) $stats['reaped'],
(int) $stats['deleted'],
(int) $stats['skipped']
)
);
}
);
}
@@ -163,28 +169,21 @@ class PRAutoBlogger {
/** Register AJAX handlers for admin actions. */
private function register_ajax_hooks(): void {
// Generation AJAX (start + status polling) stays on executor.
add_action( 'wp_ajax_prautoblogger_generate_now', array( $this->executor, 'on_ajax_generate_now' ) );
add_action( 'wp_ajax_prautoblogger_generation_status', array( $this->executor, 'on_ajax_generation_status' ) );
// Non-generation AJAX (images, models, test) on dedicated handler.
add_action( 'wp_ajax_prautoblogger_generate_image', array( $this->ajax_handlers, 'on_ajax_generate_image' ) );
add_action( 'wp_ajax_prautoblogger_test_connection', array( $this->ajax_handlers, 'on_ajax_test_connection' ) );
add_action( 'wp_ajax_prautoblogger_get_models', array( $this->ajax_handlers, 'on_ajax_get_models' ) );
add_action( 'wp_ajax_prautoblogger_refresh_models', array( new PRAutoBlogger_Model_Registry_Refresh( $this->ajax_handlers->get_registry() ), 'handle' ) );
add_action( 'wp_ajax_prautoblogger_sync_runware_models_now', array( $this->ajax_handlers, 'on_ajax_sync_runware_models_now' ) );
$review_queue = new PRAutoBlogger_Review_Queue();
add_action( 'wp_ajax_prautoblogger_approve_post', array( $review_queue, 'on_ajax_approve_post' ) );
add_action( 'wp_ajax_prautoblogger_reject_post', array( $review_queue, 'on_ajax_reject_post' ) );
add_action( 'wp_ajax_prautoblogger_clear_logs', array( new PRAutoBlogger_Log_Viewer(), 'on_ajax_clear_logs' ) );
add_action( 'wp_ajax_' . PRAutoBlogger_Board_Page::AJAX_ACTION, array( new PRAutoBlogger_Board_Page(), 'on_ajax_board_status' ) );
// v0.20.0 (M3): dossier edit + re-run endpoints (validate + queue only).
$dossier_actions = new PRAutoBlogger_Dossier_Actions();
add_action( 'wp_ajax_prautoblogger_dossier_save_input', array( $dossier_actions, 'on_save_input' ) );
add_action( 'wp_ajax_prautoblogger_dossier_rerun_stage', array( $dossier_actions, 'on_rerun_stage' ) );
add_action( 'wp_ajax_prautoblogger_dossier_rerun_from', array( $dossier_actions, 'on_rerun_from' ) );
add_action( 'wp_ajax_prautoblogger_dossier_stage_status', array( $dossier_actions, 'on_stage_status' ) );
$ideas = new PRAutoBlogger_Ideas_Browser();
add_action( 'wp_ajax_prautoblogger_generate_from_idea', array( $ideas, 'on_ajax_generate_from_idea' ) );
@@ -192,27 +191,99 @@ class PRAutoBlogger {
}
/**
* Check if database needs migration. Delegates to PRAutoBlogger_DB_Migrations::run().
* Hooked on `admin_init`.
* Check if database needs migration after plugin update.
* Compares stored DB version with PRAUTOBLOGGER_DB_VERSION; re-runs activation if different.
*
* Side effects: may update database schema and db_version option.
*/
public function on_check_db_version(): void {
PRAutoBlogger_DB_Migrations::run();
}
$stored_version = get_option( 'prautoblogger_db_version', '0' );
if ( version_compare( $stored_version, PRAUTOBLOGGER_DB_VERSION, '<' ) ) {
PRAutoBlogger_Activator::activate();
}
/**
* Run DB migrations during cron requests (hooked on `init`).
* Only fires when wp_doing_cron() is true.
*/
public function on_check_db_version_for_cron(): void {
if ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) {
$this->on_check_db_version();
// One-time migration: switch to Gemini 2.5 Flash Lite for cost/speed.
if ( ! get_option( 'prautoblogger_migrated_gemini_flash_lite' ) ) {
update_option( 'prautoblogger_analysis_model', PRAUTOBLOGGER_DEFAULT_ANALYSIS_MODEL );
update_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL );
update_option( 'prautoblogger_editor_model', PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL );
update_option( 'prautoblogger_migrated_gemini_flash_lite', '1' );
}
// One-time migration (v0.8.0): the admin no longer has an independent
// Image Provider dropdown; provider is derived from the image model on
// save. Auto-heal any existing site where the saved provider doesn't
// match the saved model's provider (the root cause of posts 650/657
// silently missing their featured image on 2026-04-20). Runs once.
if ( ! get_option( 'prautoblogger_migrated_image_provider_v080' ) ) {
$saved_model = (string) get_option( 'prautoblogger_image_model', '' );
$provider = PRAutoBlogger_Image_Model_Registry::provider_for( $saved_model );
if ( '' !== $provider ) {
update_option( 'prautoblogger_image_provider', $provider );
}
update_option( 'prautoblogger_migrated_image_provider_v080', '1' );
}
// One-time migration (v0.8.2): reschedule the daily-generation cron in
// the site's configured timezone. Pre-v0.8.2 activator interpreted the
// admin "Generation Time" input as UTC; after v0.8.2 it honours the
// site timezone. Clears the stale UTC-scheduled event and re-queues
// using the timezone-aware helper. See class-activator.php.
PRAutoBlogger_Activator::reschedule_daily_in_site_timezone_v082();
// One-time migration (v3): switch to single-panel newspaper comic style.
// Replaces both the old infomercial pastiche and the short-lived premium
// photography style. Force-update unless the user has a truly custom value.
if ( ! get_option( 'prautoblogger_migrated_style_suffix_v3' ) ) {
$known_old_prefixes = array(
'Style: a screengrab from a 1995', // v1: infomercial.
'Style: premium scientific lifestyle', // v2: photography.
);
$current = get_option( 'prautoblogger_image_style_suffix', '' );
$is_old = ( '' === $current );
foreach ( $known_old_prefixes as $prefix ) {
if ( false !== strpos( $current, $prefix ) ) {
$is_old = true;
break;
}
}
if ( $is_old ) {
update_option( 'prautoblogger_image_style_suffix', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX );
}
update_option( 'prautoblogger_migrated_style_suffix_v3', '1' );
}
// One-time migration (v4): remove caption-in-image instruction from style suffix.
// Captions are now inserted as HTML below the image, not baked into the image.
if ( ! get_option( 'prautoblogger_migrated_style_suffix_v4' ) ) {
$current = get_option( 'prautoblogger_image_style_suffix', '' );
// Detect v3 style suffix (contains "caption text" instruction).
if ( false !== strpos( $current, 'caption text in a clean sans-serif font below the panel' ) ) {
update_option( 'prautoblogger_image_style_suffix', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX );
}
update_option( 'prautoblogger_migrated_style_suffix_v4', '1' );
}
// v0.9.0 — Runware as default image model. v0.10.0 — remove CF Workers AI.
PRAutoBlogger_Activator::migrate_default_image_v090();
PRAutoBlogger_Migrate_Remove_Cloudflare_V0100::run();
// One-time migration: re-wrap existing encrypted values with "enc:" prefix.
if ( ! get_option( 'prautoblogger_migrated_enc_prefix' ) ) {
$enc_options = array( 'prautoblogger_openrouter_api_key', 'prautoblogger_ga4_credentials_json', 'prautoblogger_runware_api_key' );
foreach ( $enc_options as $opt ) {
$val = get_option( $opt, '' );
if ( '' !== $val && ! PRAutoBlogger_Encryption::is_encrypted( $val ) ) {
delete_option( $opt );
}
}
update_option( 'prautoblogger_migrated_enc_prefix', '1' );
}
}
/**
* Add custom cron schedules (six-hourly for metrics collection).
*
* @param array<string, array{interval: int, display: string}> $schedules Existing.
* @param array<string, array{interval: int, display: string}> $schedules Existing schedules.
* @return array<string, array{interval: int, display: string}>
*/
public function filter_add_cron_schedules( array $schedules ): array {
@@ -223,13 +294,9 @@ class PRAutoBlogger {
return $schedules;
}
/** Register WP-CLI commands. */
private function register_cli_hooks(): void {
PRAutoBlogger_WP_CLI_Commands::register();
}
/**
* Block false update notifications from wordpress.org.
* Our plugin slug may collide with a different plugin in the directory.
*
* @param object $transient The update_plugins transient data.
* @return object Modified transient.
@@ -246,7 +313,7 @@ class PRAutoBlogger {
return $this->executor;
}
// -- Backward-compatible proxies --
// ── Backward-compatible proxies ──
/** @see PRAutoBlogger_Executor::on_daily_generation() */
public function on_daily_generation(): void {

View File

@@ -77,9 +77,6 @@ class PRAutoBlogger_Schema_Installer {
// Generation log — every API call with cost tracking. `run_id`
// groups all entries from a single pipeline execution so
// `link_generation_logs()` can accurately attribute costs to a post.
// v0.18.0 adds the nullable audit columns `agent_role` and
// `prompt_version` (dbDelta adds them additively on upgrade;
// historical rows stay valid with NULL).
$sql_generation_log = "CREATE TABLE {$prefix}generation_log (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
post_id BIGINT UNSIGNED DEFAULT NULL,
@@ -93,8 +90,6 @@ class PRAutoBlogger_Schema_Installer {
request_json LONGTEXT DEFAULT NULL,
response_status VARCHAR(20) NOT NULL DEFAULT 'success',
error_message TEXT DEFAULT NULL,
agent_role VARCHAR(50) DEFAULT NULL,
prompt_version VARCHAR(20) DEFAULT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY post_id (post_id),

View File

@@ -9,8 +9,7 @@ declare(strict_types=1);
* What: Builds system and user prompts for source-data analysis, including
* past-performance context for self-improvement feedback loops.
* Who calls it: PRAutoBlogger_Content_Analyzer::analyze_recent_data().
* Dependencies: PRAutoBlogger_Prompt_Registry (versioned prompt bodies),
* WordPress $wpdb (for performance lookup), no external APIs.
* Dependencies: WordPress $wpdb (for performance lookup), no external APIs.
*
* @see core/class-content-analyzer.php — Orchestrates analysis and calls these builders.
* @see ARCHITECTURE.md — Data flow step 2.
@@ -26,26 +25,54 @@ class PRAutoBlogger_Analysis_Prompts {
* @return string System prompt text.
*/
public static function build_system_prompt( string $niche, string $performance_context, int $target_count = 6 ): string {
// Blocks carry their own separators when non-empty so the rendered
// output is byte-identical to the historical concatenation.
$performance_block = '' !== $performance_context ? $performance_context . "\n\n" : '';
$prompt = 'You are a content strategist analyzing social media discussions to find article ideas for a blog';
if ( '' !== $niche ) {
$prompt .= " in the {$niche} niche";
}
$prompt .= ".\n\n";
$prompt .= "IMPORTANT: You must identify exactly {$target_count} DISTINCT article ideas. ";
$prompt .= 'Each idea must cover a substantially different topic — no two ideas should overlap ';
$prompt .= "in their main subject. Aim for diversity across these categories:\n";
$prompt .= "1. QUESTIONS: Recurring questions people ask (\"How do I...\", \"What is...\", \"Is it safe to...\")\n";
$prompt .= "2. COMPLAINTS: Pain points, frustrations, or problems people report\n";
$prompt .= "3. COMPARISONS: Product/method comparisons people discuss (\"X vs Y\", \"Which is better\")\n";
$prompt .= "4. NEWS: Recent developments, rule changes, or trends people are discussing\n";
$prompt .= "5. GUIDES: How-to topics, best practices, or educational content people need\n\n";
$prompt .= "Spread your {$target_count} ideas across multiple categories. ";
$prompt .= 'Be specific — "peptide dosing for BPC-157" is better than "peptide information". ';
$prompt .= "Each idea should be narrow enough to be a single focused blog post.\n\n";
$prompt .= "For each idea, provide:\n";
$prompt .= "- type: 'question', 'complaint', 'comparison', 'news', or 'guide'\n";
$prompt .= "- topic: A clear, specific, narrow topic description\n";
$prompt .= "- summary: 1-2 sentence summary of why this topic matters\n";
$prompt .= "- frequency: How many of the provided posts relate to this topic\n";
$prompt .= "- relevance_score: 0.0 to 1.0 indicating how relevant and article-worthy this is\n";
$prompt .= "- suggested_title: A compelling, unique blog post title\n";
$prompt .= "- key_points: Array of 3-5 key points the article should cover\n";
$prompt .= "- target_keywords: Array of SEO keywords for this topic\n\n";
if ( '' !== $performance_context ) {
$prompt .= $performance_context . "\n\n";
}
$recent_context = self::get_recent_articles_context();
$recent_block = '' !== $recent_context ? $recent_context . "\n\n" : '';
if ( '' !== $recent_context ) {
$prompt .= $recent_context . "\n\n";
}
$instructions = trim( (string) get_option( 'prautoblogger_analysis_instructions', '' ) );
$instructions_block = '' !== $instructions ? "Additional instructions:\n" . $instructions . "\n\n" : '';
// Append user-defined analysis instructions if configured.
$instructions = trim( (string) get_option( 'prautoblogger_analysis_instructions', '' ) );
if ( '' !== $instructions ) {
$prompt .= "Additional instructions:\n" . $instructions . "\n\n";
}
return PRAutoBlogger_Prompt_Registry::render(
'analysis.system',
array(
'niche_clause' => '' !== $niche ? " in the {$niche} niche" : '',
'target_count' => (string) $target_count,
'performance_block' => $performance_block,
'recent_articles_block' => $recent_block,
'instructions_block' => $instructions_block,
)
);
$prompt .= "Respond with valid JSON containing exactly {$target_count} patterns:\n";
$prompt .= '{"patterns": [{"type": "...", "topic": "...", "summary": "...", "frequency": N, "relevance_score": 0.X, "suggested_title": "...", "key_points": [...], "target_keywords": [...]}]}';
return $prompt;
}
/**
@@ -56,13 +83,9 @@ class PRAutoBlogger_Analysis_Prompts {
* @return string User prompt text.
*/
public static function build_user_prompt( string $summary, int $target_count = 6 ): string {
return PRAutoBlogger_Prompt_Registry::render(
'analysis.user',
array(
'target_count' => (string) $target_count,
'summary' => $summary,
)
);
return 'Here are the recent social media posts and comments to analyze. '
. "Find {$target_count} distinct, diverse article ideas from this data:\n\n"
. $summary;
}
/**
@@ -76,9 +99,9 @@ class PRAutoBlogger_Analysis_Prompts {
global $wpdb;
$scores_table = $wpdb->prefix . 'prautoblogger_content_scores';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$top_posts = $wpdb->get_results(
"SELECT cs.post_id, cs.composite_score, p.post_title
"SELECT cs.post_id, cs.composite_score, p.post_title // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
FROM {$scores_table} cs
JOIN {$wpdb->posts} p ON p.ID = cs.post_id
WHERE cs.composite_score > 0

View File

@@ -9,15 +9,8 @@ declare(strict_types=1);
* Extracted from Pipeline_Runner so each chained cron job has a focused,
* single-responsibility worker. One worker = one article = one PHP process.
*
* v0.18.0: per-article stage state (run_stages, item-scoped) makes resume
* idempotent — an already-published item is skipped outright, a done
* review is reused from its snapshot, and the writer reuses done LLM
* stages via Content_Generator::set_run_item(). Editorial verdicts and
* the sources that fed the article are persisted to the audit tables.
*
* Triggered by: Pipeline_Runner (directly for article 1, via cron for 2..N).
* Dependencies: Content_Generator, Chief_Editor, Publisher, Cost_Tracker,
* Run_Stage_State, Audit_Writer.
* Dependencies: Content_Generator, Chief_Editor, Publisher, Cost_Tracker.
*
* Opik instrumentation: Initializes trace context at start, creates spans
* for content generation and editorial review. Feature-flag gated (default off).
@@ -55,34 +48,6 @@ class PRAutoBlogger_Article_Worker {
* @return array{generated: int, published: int, rejected: int, cost: float}
*/
public function generate( PRAutoBlogger_Article_Idea $idea ): array {
$run_id = (string) ( $this->cost_tracker->get_run_id() ?? '' );
$item = PRAutoBlogger_Run_Stage_State::item_key_for_idea( $idea );
// v0.20.0: persist the EXACT idea payload once per item so
// re-run-from-here can reconstruct it (rebuilding from post
// fields would risk an item_key hash mismatch -> duplicate post).
if ( '' !== $run_id ) {
PRAutoBlogger_Stage_Input_Store::save_seed( $run_id, $item, (string) wp_json_encode( $idea->to_array() ) );
}
$result = array(
'generated' => 0,
'published' => 0,
'rejected' => 0,
'cost' => 0.0,
);
// Idempotent resume: this item already completed its publish stage
// in this run — re-dispatching it must not create a second post or
// charge a second cent.
if ( '' !== $run_id && PRAutoBlogger_Run_Stage_State::is_done( $run_id, 'publish', '', $item ) ) {
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Skipping "%s" — already completed in run %s (idempotent resume).', $idea->get_topic(), $run_id ),
'pipeline'
);
return $result;
}
// Initialize Opik trace context for this article generation.
$opik = $this->should_trace_with_opik();
if ( $opik ) {
@@ -91,7 +56,6 @@ class PRAutoBlogger_Article_Worker {
$llm = new PRAutoBlogger_OpenRouter_Provider();
$generator = new PRAutoBlogger_Content_Generator( $llm, $this->cost_tracker );
$generator->set_run_item( '' !== $run_id ? $run_id : null, $item );
$editor = new PRAutoBlogger_Chief_Editor( $llm, $this->cost_tracker );
$publisher = new PRAutoBlogger_Publisher();
@@ -101,16 +65,22 @@ class PRAutoBlogger_Article_Worker {
true
);
$result = array(
'generated' => 0,
'published' => 0,
'rejected' => 0,
'cost' => 0.0,
);
try {
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Generating article draft via AI…', 'prautoblogger' ) );
$this->broadcast_stage( __( 'Generating article draft via AI…', 'prautoblogger' ) );
$content = $generator->generate( $idea );
$result['generated'] = 1;
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Running editorial pass…', 'prautoblogger' ) );
$review = $this->review_with_state( $editor, $content, $idea, $run_id, $item );
$this->broadcast_stage( __( 'Running editorial pass…', 'prautoblogger' ) );
$review = $editor->review( $content, $idea );
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Saving and publishing…', 'prautoblogger' ) );
PRAutoBlogger_Run_Stage_State::start( $run_id, 'publish', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'publish' ), $item );
$this->broadcast_stage( __( 'Saving and publishing…', 'prautoblogger' ) );
$this->publish_or_draft(
$content,
$idea,
@@ -119,13 +89,7 @@ class PRAutoBlogger_Article_Worker {
$auto_publish,
$result
);
PRAutoBlogger_Run_Stage_State::done( $run_id, 'publish', '', $item );
PRAutoBlogger_Audit_Writer::record_idea_sources( $run_id, $idea );
} catch ( \Throwable $e ) {
if ( '' !== $run_id ) {
PRAutoBlogger_Run_Stage_State::fail_open_for_item( $run_id, $item );
}
PRAutoBlogger_Logger::instance()->error(
sprintf(
'Article generation %s for "%s": %s',
@@ -147,63 +111,6 @@ class PRAutoBlogger_Article_Worker {
return $result;
}
/**
* Editorial review with stage state: a done review is reused from its
* snapshot (never re-charged); a fresh review is checkpointed and its
* verdict recorded to the run_decisions audit table.
*
* Side effects: run_stages upserts, one run_decisions insert, and —
* when not resuming — one LLM call via Chief_Editor.
*
* @param PRAutoBlogger_Chief_Editor $editor Editor agent.
* @param string $content Generated HTML content.
* @param PRAutoBlogger_Article_Idea $idea The idea under review.
* @param string $run_id Run UUID ('' outside a run).
* @param string $item Stage item key for this idea.
* @return PRAutoBlogger_Editorial_Review
*/
private function review_with_state(
PRAutoBlogger_Chief_Editor $editor,
string $content,
PRAutoBlogger_Article_Idea $idea,
string $run_id,
string $item
): PRAutoBlogger_Editorial_Review {
if ( '' !== $run_id ) {
$snapshot = PRAutoBlogger_Run_Stage_State::get_output( $run_id, 'review', '', $item );
if ( null !== $snapshot ) {
$data = json_decode( $snapshot, true );
if ( is_array( $data ) && isset( $data['verdict'] ) ) {
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Reusing completed review for "%s" (idempotent resume).', $idea->get_topic() ),
'pipeline'
);
return new PRAutoBlogger_Editorial_Review( $data );
}
}
PRAutoBlogger_Run_Stage_State::start( $run_id, 'review', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'review' ), $item );
}
$review = $editor->review( $content, $idea );
if ( '' !== $run_id ) {
$snapshot = (string) wp_json_encode(
array(
'verdict' => $review->get_verdict(),
'notes' => $review->get_notes(),
'revised_content' => $review->get_revised_content(),
'quality_score' => $review->get_quality_score(),
'seo_score' => $review->get_seo_score(),
'issues' => $review->get_issues(),
)
);
PRAutoBlogger_Run_Stage_State::done( $run_id, 'review', '', $item, $snapshot );
PRAutoBlogger_Audit_Writer::record_decision( $run_id, 'review', $review->get_verdict(), $review->get_notes() );
}
return $review;
}
/**
* Publish approved content or save as draft.
*
@@ -246,6 +153,21 @@ class PRAutoBlogger_Article_Worker {
}
}
/**
* Update the generation status transient with the current stage.
*
* @param string $stage Human-readable stage description.
*/
private function broadcast_stage( string $stage ): void {
$transient_key = 'prautoblogger_generation_status';
$current = get_transient( $transient_key );
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
$current['stage'] = $stage;
$current['last_updated'] = time();
set_transient( $transient_key, $current, 600 );
}
}
/**
* Check if Opik tracing is enabled and has credentials.
*

View File

@@ -1,163 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Writes run-scoped audit rows: sources considered + stage decisions.
*
* What: Thin, self-healing insert layer over the v0.18.0 audit child
* tables. `record_decision()` persists a stage verdict (Phase 1:
* the chief editor's review verdict; Phase 2 adds curate/editorial/
* seo decisions and citation_score). `record_idea_sources()`
* consolidates which collected sources fed a generated article —
* the run_sources replacement for the historical source_ids_json /
* `_prautoblogger_research_sources` scatter — for NEW runs only (no
* backfill). Every method no-ops when the tables are missing.
* Who triggers it: Article_Worker (decision after review, sources after
* publish), Phase-2 agents.
* Dependencies: WordPress $wpdb, Run_State (availability probe pattern).
*
* @see core/class-article-worker.php — Phase-1 call sites.
* @see ARCHITECTURE.md #21 — Audit substrate design.
*/
class PRAutoBlogger_Audit_Writer {
/** @var bool|null Per-request "audit tables exist" probe result. */
private static ?bool $tables_ok = null;
/**
* Whether the audit child tables exist. Cached per request; never throws.
*
* @return bool
*/
public static function is_available(): bool {
if ( null !== self::$tables_ok ) {
return self::$tables_ok;
}
global $wpdb;
if ( null === $wpdb ) {
return false; // Not cached: $wpdb may appear later in boot.
}
$table = $wpdb->prefix . 'prautoblogger_run_decisions';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
self::$tables_ok = ( $found === $table );
return self::$tables_ok;
}
/**
* Persist a stage decision for a run.
*
* @param string $run_id Run UUID.
* @param string $stage Deciding stage (see Stage_Display_Map).
* @param string $verdict e.g. 'approved', 'revised', 'rejected'.
* @param string $rationale Why (editor notes, governor message, …).
* @param float|null $citation_score Phase-2 citation score (null in Phase 1).
* @return void
*/
public static function record_decision( string $run_id, string $stage, string $verdict, string $rationale = '', ?float $citation_score = null ): void {
if ( '' === $run_id || ! self::is_available() ) {
return;
}
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->insert(
$wpdb->prefix . 'prautoblogger_run_decisions',
array(
'run_id' => $run_id,
'stage' => $stage,
'verdict' => $verdict,
'rationale' => $rationale,
'citation_score' => $citation_score,
'created_at' => current_time( 'mysql' ),
)
);
}
/**
* Record the collected sources that fed a generated article (kept = 1;
* Phase-2 curation adds discard rows with reasons + quality scores).
*
* Resolves the idea's source_data ids to permalinks in one query.
*
* @param string $run_id Run UUID.
* @param PRAutoBlogger_Article_Idea $idea The generated idea.
* @return void
*/
public static function record_idea_sources( string $run_id, PRAutoBlogger_Article_Idea $idea ): void {
if ( '' === $run_id || ! self::is_available() ) {
return;
}
$source_ids = array_filter( array_map( 'intval', $idea->get_source_ids() ) );
if ( empty( $source_ids ) ) {
return;
}
global $wpdb;
$source_table = $wpdb->prefix . 'prautoblogger_source_data';
$placeholders = implode( ',', array_fill( 0, count( $source_ids ), '%d' ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
$rows = $wpdb->get_results(
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is a fixed %d list.
$wpdb->prepare( "SELECT id, source_type, permalink FROM {$source_table} WHERE id IN ({$placeholders})", $source_ids ),
ARRAY_A
);
if ( ! is_array( $rows ) ) {
return;
}
foreach ( $rows as $row ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->insert(
$wpdb->prefix . 'prautoblogger_run_sources',
array(
'run_id' => $run_id,
'agent_role' => 'analyst',
'source_url' => (string) ( $row['permalink'] ?? '' ),
'doi' => null,
'kept' => 1,
'reason' => sprintf( 'Cited by analyzer for "%s" (%s #%d)', $idea->get_topic(), (string) $row['source_type'], (int) $row['id'] ),
'quality_score' => null,
'created_at' => current_time( 'mysql' ),
)
);
}
}
/**
* Flag the run_decisions rows of given stages as human-modified
* (v0.20.0 / CPO guardrail 2). Used in two cases: the decision rows of
* a stage whose edited input enters execution, and decisions recorded
* during a re-run-from-here window on an item that carries a human
* edit (derived-from-edited-content). Self-healing no-op when the
* column/table is missing.
*
* @param string $run_id Run UUID.
* @param array<string> $stages Stage names to flag.
* @param string|null $since Optional MySQL datetime — only flag rows created at/after it.
* @return int Rows flagged.
*/
public static function flag_decisions_human_modified( string $run_id, array $stages, ?string $since = null ): int {
if ( '' === $run_id || empty( $stages ) || ! self::is_available() ) {
return 0;
}
global $wpdb;
$table = $wpdb->prefix . 'prautoblogger_run_decisions';
$placeholders = implode( ',', array_fill( 0, count( $stages ), '%s' ) );
$sql = "UPDATE {$table} SET human_modified = 1 WHERE run_id = %s AND stage IN ({$placeholders})";
$params = array_merge( array( $run_id ), array_values( $stages ) );
if ( null !== $since ) {
$sql .= ' AND created_at >= %s';
$params[] = $since;
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is a fixed %s list.
$updated = $wpdb->query( $wpdb->prepare( $sql, $params ) );
return is_numeric( $updated ) ? (int) $updated : 0;
}
/** Reset per-request caches (tests). */
public static function flush_cache(): void {
self::$tables_ok = null;
}
}

74
includes/core/class-chief-editor.php Normal file → Executable file
View File

@@ -9,7 +9,7 @@ declare(strict_types=1);
* Opik instrumentation: spans per review LLM call.
*
* Triggered by: PRAutoBlogger_Article_Worker.
* Dependencies: LLM_Provider_Interface, Cost_Tracker, Prompt_Registry.
* Dependencies: LLM_Provider_Interface, Cost_Tracker.
*/
class PRAutoBlogger_Chief_Editor {
@@ -64,7 +64,6 @@ class PRAutoBlogger_Chief_Editor {
'temperature' => 0.3,
'max_tokens' => 5000,
'response_format' => array( 'type' => 'json_object' ),
'stage' => 'review',
)
);
@@ -93,47 +92,54 @@ class PRAutoBlogger_Chief_Editor {
/**
* Build system prompt for editorial review.
*
* v0.18.0: renders from the versioned registry ('editor.system') with a
* byte-identical in-code fallback; the admin's extra editor
* instructions stay a setting and are injected as a token value.
*
* @param string $niche Niche description from settings.
* @return string System prompt text.
*/
private function build_system_prompt( string $niche ): string {
$instructions = trim( (string) get_option( 'prautoblogger_editor_instructions', '' ) );
$instructions_block = '' !== $instructions ? "\nAdditional instructions:\n" . $instructions . "\n" : '';
$prompt = 'You are a senior blog editor';
if ( '' !== $niche ) {
$prompt .= " specializing in {$niche} content";
}
$prompt .= ". Review article drafts before publication.\n\n";
return PRAutoBlogger_Prompt_Registry::render(
'editor.system',
array(
'niche_clause' => '' !== $niche ? " specializing in {$niche} content" : '',
'instructions_block' => $instructions_block,
)
);
$prompt .= "Evaluate on: QUALITY, ACCURACY, SEO, COMPLETENESS, READABILITY.\n";
$prompt .= "Respond with JSON: {\n";
$prompt .= ' "verdict": "approved" | "revised" | "rejected",' . "\n";
$prompt .= ' "quality_score": 0.0-1.0,' . "\n";
$prompt .= ' "seo_score": 0.0-1.0,' . "\n";
$prompt .= ' "issues": ["issue1", "issue2"],' . "\n";
$prompt .= ' "notes": "Editorial notes",' . "\n";
$prompt .= ' "revised_content": "Full revised HTML if revised, null otherwise"' . "\n";
$prompt .= "}\n\n";
$prompt .= "Rules:\n";
$prompt .= "- APPROVE if quality_score >= 0.7 and seo_score >= 0.6\n";
$prompt .= "- REVISE if fixable issues exist — provide full revised HTML\n";
$prompt .= "- REJECT if fundamentally flawed\n";
$prompt .= "- Preserve formatting, links, lists when revising\n";
$instructions = trim( (string) get_option( 'prautoblogger_editor_instructions', '' ) );
if ( '' !== $instructions ) {
$prompt .= "\nAdditional instructions:\n" . $instructions . "\n";
}
return $prompt;
}
/**
* Build user prompt for editorial review.
*
* v0.18.0: renders from the versioned registry ('editor.review').
*
* @param string $content The generated HTML content.
* @param PRAutoBlogger_Article_Idea $idea The original article idea.
* @return string User prompt text.
*/
private function build_review_prompt( string $content, PRAutoBlogger_Article_Idea $idea ): string {
return PRAutoBlogger_Prompt_Registry::render(
'editor.review',
array(
'title' => $idea->get_suggested_title(),
'topic' => $idea->get_topic(),
'article_type' => $idea->get_article_type(),
'key_points' => implode( ', ', $idea->get_key_points() ),
'keywords' => implode( ', ', $idea->get_target_keywords() ),
'content' => $content,
)
return sprintf(
"Review this article draft:\n\n" .
"BRIEF: Title: %s | Topic: %s | Type: %s\n" .
"KEY POINTS: %s\n" .
"TARGET KEYWORDS: %s\n\n" .
"CONTENT:\n%s",
$idea->get_suggested_title(),
$idea->get_topic(),
$idea->get_article_type(),
implode( ', ', $idea->get_key_points() ),
implode( ', ', $idea->get_target_keywords() ),
$content
);
}

View File

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

382
includes/core/class-content-generator.php Normal file → Executable file
View File

@@ -6,10 +6,6 @@ declare(strict_types=1);
*
* Supports: single_pass (one LLM call) or multi_step (outline → draft → polish).
* Opik instrumentation: spans per LLM call when feature-flag enabled.
* v0.18.0: prompt copy renders from the versioned prompt registry (with
* byte-identical in-code fallback); every log row carries the run-pinned
* prompt_version. The four stage methods share one execute_stage() helper —
* span lifecycle, LLM dispatch, and cost logging are identical across stages.
*
* Triggered by: PRAutoBlogger_Article_Worker.
* Dependencies: LLM_Provider_Interface, Cost_Tracker, Content_Prompts.
@@ -19,12 +15,6 @@ class PRAutoBlogger_Content_Generator {
private PRAutoBlogger_LLM_Provider_Interface $llm;
private PRAutoBlogger_Cost_Tracker $cost_tracker;
/** @var string|null Run UUID for stage-state checkpointing (null = off). */
private ?string $run_id = null;
/** @var string|null Stage item key scoping this article within the run. */
private ?string $item_key = null;
public function __construct(
PRAutoBlogger_LLM_Provider_Interface $llm,
PRAutoBlogger_Cost_Tracker $cost_tracker
@@ -33,36 +23,13 @@ class PRAutoBlogger_Content_Generator {
$this->cost_tracker = $cost_tracker;
}
/**
* Enable per-stage state checkpointing for one article item (v0.18.0).
*
* When set, every LLM stage (outline/draft/polish or the single-pass
* draft) records pending->running->done state and snapshots its output;
* a re-entered done stage returns the snapshot WITHOUT a new LLM call
* (never re-charged). When unset (default), behavior is exactly
* pre-v0.18.0 — used by callers outside a run (e.g. eval mode).
*
* @param string|null $run_id Run UUID, or null to disable.
* @param string|null $item_key Item key from Run_Stage_State::item_key_for_idea().
* @return $this
*/
public function set_run_item( ?string $run_id, ?string $item_key ): self {
$this->run_id = $run_id;
$this->item_key = $item_key;
return $this;
}
/**
* Generate a blog post from an article idea.
*
* @param PRAutoBlogger_Article_Idea $idea The scored idea to generate content for.
* @param bool $eval_mode True to suppress publish/image side effects.
* @param PRAutoBlogger_Article_Idea $idea The scored idea to generate content for.
* @return string Generated HTML content.
*/
public function generate( PRAutoBlogger_Article_Idea $idea, bool $eval_mode = false ): string {
// In eval mode, suppress publishing and image generation side effects.
define( 'PRAUTOBLOGGER_EVAL_MODE', $eval_mode );
public function generate( PRAutoBlogger_Article_Idea $idea ): string {
$mode = get_option( 'prautoblogger_writing_pipeline', 'multi_step' );
$request = new PRAutoBlogger_Content_Request(
@@ -82,132 +49,15 @@ class PRAutoBlogger_Content_Generator {
}
/**
* Single-pass: one LLM call produces complete article (Economy tier).
*
* The log row's stage stays 'draft' (historical contract: a draft row
* without an outline row marks a single-pass run) but the prompt key
* is passed explicitly — the stage map would resolve 'draft' to
* 'content.draft'.
*
* @param PRAutoBlogger_Content_Request $request Generation request.
* @return string Generated HTML content.
* Single-pass: one LLM call produces complete article.
*/
private function generate_single_pass( PRAutoBlogger_Content_Request $request ): string {
$model = get_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL );
return $this->execute_stage(
'draft',
'single_pass_generation',
PRAutoBlogger_Content_Prompts::build_single_pass( $request ),
$request,
$model,
array(
'temperature' => 0.7,
'max_tokens' => 4000,
),
'content.single_pass'
);
}
/**
* Multi-step: outline → draft → polish.
*
* @param PRAutoBlogger_Content_Request $request Generation request.
* @return string Generated HTML content.
*/
private function generate_multi_step( PRAutoBlogger_Content_Request $request ): string {
$model = get_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL );
$outline = $this->execute_stage(
'outline',
'outline_generation',
PRAutoBlogger_Content_Prompts::build_outline( $request ),
$request,
$model,
array(
'temperature' => 0.5,
'max_tokens' => 1500,
)
);
$draft = $this->execute_stage(
'draft',
'draft_generation',
PRAutoBlogger_Content_Prompts::build_draft( $request, $outline ),
$request,
$model,
array(
'temperature' => 0.7,
'max_tokens' => 4000,
)
);
return $this->execute_stage(
'polish',
'polish_generation',
PRAutoBlogger_Content_Prompts::build_polish( $draft ),
$request,
$model,
array(
'temperature' => 0.4,
'max_tokens' => 4000,
)
);
}
/**
* Run one writing stage: Opik span → LLM call → span close → cost log.
*
* Consolidates the per-stage boilerplate that was previously duplicated
* across the four stage methods (v0.18.0). The system prompt is rebuilt
* per stage exactly as before.
*
* Side effects: one OpenRouter API call, one Opik span (when tracing),
* one generation_log row.
*
* @param string $stage Log stage value ('outline'|'draft'|'polish').
* @param string $span_name Opik span name.
* @param string $user_prompt Rendered user prompt for the stage.
* @param PRAutoBlogger_Content_Request $request Generation request (system prompt input).
* @param string $model Model identifier.
* @param array<string, mixed> $options LLM options (temperature, max_tokens).
* @param string|null $prompt_key Explicit registry key for prompt_version
* stamping (null = derive from stage).
* @return string Stage output content.
*/
private function execute_stage(
string $stage,
string $span_name,
string $user_prompt,
PRAutoBlogger_Content_Request $request,
string $model,
array $options,
?string $prompt_key = null
): string {
// Idempotent resume: a done stage returns its snapshot, no LLM call.
if ( null !== $this->run_id && null !== $this->item_key ) {
$cached = PRAutoBlogger_Run_Stage_State::get_output( $this->run_id, $stage, '', $this->item_key );
if ( null !== $cached ) {
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Reusing completed %s stage output (idempotent resume).', $stage ),
'pipeline'
);
return $cached;
}
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();
$span_id = $ctx->start_span(
array(
'name' => $span_name,
'name' => 'single_pass_generation',
'type' => 'llm',
'model' => $model,
'provider' => 'openrouter',
@@ -222,28 +72,16 @@ class PRAutoBlogger_Content_Generator {
),
array(
'role' => 'user',
'content' => $user_prompt,
'content' => PRAutoBlogger_Content_Prompts::build_single_pass( $request ),
),
),
$model,
$options
array(
'temperature' => 0.7,
'max_tokens' => 4000,
)
);
// 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(
$span_id,
array(
@@ -257,38 +95,194 @@ class PRAutoBlogger_Content_Generator {
$this->cost_tracker->log_api_call(
null,
$stage,
'draft',
$this->llm->get_provider_name(),
$response['model'],
$response['prompt_tokens'],
$response['completion_tokens'],
'success',
'',
null,
$prompt_key
$response['completion_tokens']
);
if ( null !== $this->run_id && null !== $this->item_key ) {
PRAutoBlogger_Run_Stage_State::done(
$this->run_id,
$stage,
'',
$this->item_key,
(string) $response['content'],
$this->llm->estimate_cost( $response['model'], (int) $response['prompt_tokens'], (int) $response['completion_tokens'] )
);
}
return $response['content'];
}
/**
* Generate content in eval mode (no publishing, no image generation).
*
* @param PRAutoBlogger_Article_Idea $idea The scored idea to generate content for.
* @return string Generated HTML content.
* Multi-step: outline → draft → polish.
*/
public function generate_eval( PRAutoBlogger_Article_Idea $idea ): string {
return $this->generate( $idea, true );
private function generate_multi_step( PRAutoBlogger_Content_Request $request ): string {
$model = get_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL );
$outline = $this->stage_outline( $request, $model );
$draft = $this->stage_draft( $request, $outline, $model );
$polished = $this->stage_polish( $request, $draft, $model );
return $polished;
}
/**
* Stage 1: Generate article outline.
*/
private function stage_outline( PRAutoBlogger_Content_Request $request, string $model ): string {
$ctx = PRAutoBlogger_Opik_Trace_Context::current();
$span_id = $ctx->start_span(
array(
'name' => 'outline_generation',
'type' => 'llm',
'model' => $model,
'provider' => 'openrouter',
)
);
$response = $this->llm->send_chat_completion(
array(
array(
'role' => 'system',
'content' => PRAutoBlogger_Content_Prompts::build_system( $request ),
),
array(
'role' => 'user',
'content' => PRAutoBlogger_Content_Prompts::build_outline( $request ),
),
),
$model,
array(
'temperature' => 0.5,
'max_tokens' => 1500,
)
);
$ctx->end_span(
$span_id,
array(
'usage' => array(
'prompt_tokens' => $response['prompt_tokens'],
'completion_tokens' => $response['completion_tokens'],
'total_tokens' => $response['prompt_tokens'] + $response['completion_tokens'],
),
)
);
$this->cost_tracker->log_api_call(
null,
'outline',
$this->llm->get_provider_name(),
$response['model'],
$response['prompt_tokens'],
$response['completion_tokens']
);
return $response['content'];
}
/**
* Stage 2: Write full draft from outline.
*/
private function stage_draft( PRAutoBlogger_Content_Request $request, string $outline, string $model ): string {
$ctx = PRAutoBlogger_Opik_Trace_Context::current();
$span_id = $ctx->start_span(
array(
'name' => 'draft_generation',
'type' => 'llm',
'model' => $model,
'provider' => 'openrouter',
)
);
$response = $this->llm->send_chat_completion(
array(
array(
'role' => 'system',
'content' => PRAutoBlogger_Content_Prompts::build_system( $request ),
),
array(
'role' => 'user',
'content' => PRAutoBlogger_Content_Prompts::build_draft( $request, $outline ),
),
),
$model,
array(
'temperature' => 0.7,
'max_tokens' => 4000,
)
);
$ctx->end_span(
$span_id,
array(
'usage' => array(
'prompt_tokens' => $response['prompt_tokens'],
'completion_tokens' => $response['completion_tokens'],
'total_tokens' => $response['prompt_tokens'] + $response['completion_tokens'],
),
)
);
$this->cost_tracker->log_api_call(
null,
'draft',
$this->llm->get_provider_name(),
$response['model'],
$response['prompt_tokens'],
$response['completion_tokens']
);
return $response['content'];
}
/**
* Stage 3: Polish and refine draft.
*/
private function stage_polish( PRAutoBlogger_Content_Request $request, string $draft, string $model ): string {
$ctx = PRAutoBlogger_Opik_Trace_Context::current();
$span_id = $ctx->start_span(
array(
'name' => 'polish_generation',
'type' => 'llm',
'model' => $model,
'provider' => 'openrouter',
)
);
$response = $this->llm->send_chat_completion(
array(
array(
'role' => 'system',
'content' => PRAutoBlogger_Content_Prompts::build_system( $request ),
),
array(
'role' => 'user',
'content' => PRAutoBlogger_Content_Prompts::build_polish( $draft ),
),
),
$model,
array(
'temperature' => 0.4,
'max_tokens' => 4000,
)
);
$ctx->end_span(
$span_id,
array(
'usage' => array(
'prompt_tokens' => $response['prompt_tokens'],
'completion_tokens' => $response['completion_tokens'],
'total_tokens' => $response['prompt_tokens'] + $response['completion_tokens'],
),
)
);
$this->cost_tracker->log_api_call(
null,
'polish',
$this->llm->get_provider_name(),
$response['model'],
$response['prompt_tokens'],
$response['completion_tokens']
);
return $response['content'];
}
}

View File

@@ -11,8 +11,7 @@ declare(strict_types=1);
* independently of the generation orchestration.
*
* Triggered by: PRAutoBlogger_Content_Generator (called for every stage).
* Dependencies: PRAutoBlogger_Prompt_Registry (versioned prompt bodies),
* WordPress query functions (get_posts, get_the_title, get_permalink).
* Dependencies: WordPress query functions (get_posts, get_the_title, get_permalink).
*
* @see core/class-content-generator.php — Consumer of these prompts.
* @see models/class-content-request.php — Data bag passed to every builder.
@@ -25,22 +24,18 @@ class PRAutoBlogger_Content_Prompts {
* Includes niche, tone, mandatory style guide, internal link reference,
* peptide database links, and the "never fabricate URLs" rule.
*
* v0.18.0: the prompt copy renders from the versioned registry
* ('content.system', falls back to the identical in-code default);
* the style guide and linking rules are data injection and stay here.
*
* @param PRAutoBlogger_Content_Request $request Content request with settings.
* @return string Complete system prompt.
*/
public static function build_system( PRAutoBlogger_Content_Request $request ): string {
$niche = $request->get_niche_description();
$prompt = PRAutoBlogger_Prompt_Registry::render(
'content.system',
array(
'niche_clause' => '' !== $niche ? " specializing in {$niche}" : '',
'tone' => $request->get_tone(),
)
);
$prompt = 'You are an expert blog writer';
if ( '' !== $niche ) {
$prompt .= " specializing in {$niche}";
}
$prompt .= '. Write well-researched, engaging, SEO-friendly content. ';
$prompt .= "Use a {$request->get_tone()} tone. ";
$prompt .= 'Output HTML content only — no markdown, no code fences, no commentary.';
// Append user-defined writing instructions as a mandatory style guide.
$instructions = trim( $request->get_writing_instructions() );
@@ -65,17 +60,24 @@ class PRAutoBlogger_Content_Prompts {
public static function build_single_pass( PRAutoBlogger_Content_Request $request ): string {
$idea = $request->get_idea();
return PRAutoBlogger_Prompt_Registry::render(
'content.single_pass',
array(
'title' => $idea->get_suggested_title(),
'topic' => $idea->get_topic(),
'article_type' => $idea->get_article_type(),
'key_points' => implode( "\n- ", $idea->get_key_points() ),
'keywords' => implode( ', ', $idea->get_target_keywords() ),
'min_words' => (string) $request->get_min_word_count(),
'max_words' => (string) $request->get_max_word_count(),
)
return sprintf(
"Write a complete blog post in HTML format.\n\n" .
"Title: %s\nTopic: %s\nType: %s\n\nKey points:\n- %s\n\n" .
"Keywords: %s\n\n" .
"Requirements:\n" .
"- %d-%d words\n" .
"- Proper HTML (h2, h3, p, ul/li)\n" .
"- Engaging intro, strong conclusion with CTA\n" .
"- Do NOT include the title or <html>/<body> tags\n" .
"- Output HTML only, no markdown or commentary\n" .
'- Follow EVERY formatting and structural requirement from your system prompt style guide',
$idea->get_suggested_title(),
$idea->get_topic(),
$idea->get_article_type(),
implode( "\n- ", $idea->get_key_points() ),
implode( ', ', $idea->get_target_keywords() ),
$request->get_min_word_count(),
$request->get_max_word_count()
);
}
@@ -88,17 +90,21 @@ class PRAutoBlogger_Content_Prompts {
public static function build_outline( PRAutoBlogger_Content_Request $request ): string {
$idea = $request->get_idea();
return PRAutoBlogger_Prompt_Registry::render(
'content.outline',
array(
'title' => $idea->get_suggested_title(),
'topic' => $idea->get_topic(),
'article_type' => $idea->get_article_type(),
'key_points' => implode( "\n- ", $idea->get_key_points() ),
'keywords' => implode( ', ', $idea->get_target_keywords() ),
'min_words' => (string) $request->get_min_word_count(),
'max_words' => (string) $request->get_max_word_count(),
)
return sprintf(
"Create a detailed outline for a blog post titled: \"%s\"\n\n" .
"Topic: %s\nArticle type: %s\n\nKey points to cover:\n%s\n\n" .
"Target keywords: %s\n\n" .
'The outline should have 4-6 main sections with bullet points under each. ' .
'Include an introduction hook and a conclusion with a call to action. ' .
"Word count target: %d-%d words.\n\n" .
'Plan the structure to satisfy EVERY requirement in your system prompt style guide.',
$idea->get_suggested_title(),
$idea->get_topic(),
$idea->get_article_type(),
implode( "\n- ", $idea->get_key_points() ),
implode( ', ', $idea->get_target_keywords() ),
$request->get_min_word_count(),
$request->get_max_word_count()
);
}
@@ -110,15 +116,23 @@ class PRAutoBlogger_Content_Prompts {
* @return string Draft prompt.
*/
public static function build_draft( PRAutoBlogger_Content_Request $request, string $outline ): string {
return PRAutoBlogger_Prompt_Registry::render(
'content.draft',
array(
'outline' => $outline,
'tone' => $request->get_tone(),
'min_words' => (string) $request->get_min_word_count(),
'max_words' => (string) $request->get_max_word_count(),
'keywords' => implode( ', ', $request->get_idea()->get_target_keywords() ),
)
return sprintf(
"Using this outline, write the full blog post in HTML format.\n\n" .
"OUTLINE:\n%s\n\n" .
"Requirements:\n" .
"- Write in a %s tone\n" .
"- Target %d-%d words\n" .
"- Use proper HTML headings (h2, h3), paragraphs, and lists\n" .
"- Include an engaging introduction and strong conclusion\n" .
"- Naturally incorporate these keywords: %s\n" .
"- Do NOT include the title in the HTML (it will be set separately)\n" .
"- Do NOT wrap in <html>, <head>, or <body> tags — just the article content\n" .
'- Follow EVERY formatting and structural requirement from your system prompt style guide',
$outline,
$request->get_tone(),
$request->get_min_word_count(),
$request->get_max_word_count(),
implode( ', ', $request->get_idea()->get_target_keywords() )
);
}
@@ -129,10 +143,18 @@ class PRAutoBlogger_Content_Prompts {
* @return string Polish prompt.
*/
public static function build_polish( string $draft ): string {
return PRAutoBlogger_Prompt_Registry::render(
'content.polish',
array( 'draft' => $draft )
);
return "Review and polish this blog post draft. Improve:\n" .
"1. Flow and readability\n" .
"2. SEO optimization (headings, keyword placement)\n" .
"3. Engagement (hooks, transitions, call-to-action)\n" .
"4. Accuracy and clarity\n" .
"5. Remove any filler or redundant sentences\n\n" .
'IMPORTANT: Preserve all bullet points, numbered lists, hyperlinks, and ' .
'structural elements from the draft. Do NOT flatten lists into prose or ' .
'remove links. Ensure every requirement from your system prompt style ' .
"guide is satisfied in the final output.\n\n" .
"Return the polished HTML content only. Do not add commentary.\n\n" .
"DRAFT:\n" . $draft;
}
/**

View File

@@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Thrown when a reserve-before-call would push a run past its cost ceiling.
*
* What: Dedicated exception type so call paths can distinguish "this run
* was halted by the per-run cost governor" from generic API
* failures. By the time it is thrown the governor has already
* marked the run `halted`, recorded the overage on the runs row,
* and logged — catchers must NOT dispatch the call they were about
* to make, and chained jobs abort via the run-status check in
* Pipeline_Runner::process_next_queued_article().
* Who triggers it: PRAutoBlogger_Cost_Governor on a failed reservation.
* Dependencies: none (extends RuntimeException).
*
* @see core/class-cost-governor.php — Sole thrower.
* @see core/class-pipeline-runner.php — Aborts queued articles of halted runs.
*/
class PRAutoBlogger_Cost_Ceiling_Exception extends \RuntimeException {
}

View File

@@ -1,239 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Per-run cost governor — reserve-before-call against the run ledger.
*
* What: Net-new enforcement (the monthly Cost_Tracker cap only bounds the
* month; `get_current_run_cost()` was an unguarded accumulator).
* Before any governed call dispatches, its worst-case cost estimate
* is atomically added to the run's `reserved_usd` via a single
* conditional UPDATE — the same atomic-conditional-write discipline
* as PRAutoBlogger_Generation_Lock (#10) — so concurrent writers
* (curl_multi fan-outs, chained jobs) cannot slip past the ceiling
* between check and call. Batches reserve their SUMMED estimate
* before dispatch. After each response the reservation settles to
* the actual cost, so a cheap call never holds its worst case.
* Breach: the run is marked `halted` (sticky), the overage is
* recorded on the runs row, the Review Queue surfaces it, and a
* Cost_Ceiling_Exception aborts the un-dispatched call. Standalone
* calls outside any run (no run context) are not run-governed —
* exactly the historical behavior; the monthly cap and the
* Cloudflare AI Gateway path are untouched everywhere.
* Who triggers it: PRAutoBlogger_OpenRouter_Provider::send_chat_completion
* (every text-LLM call path), PRAutoBlogger_Image_Pipeline (image
* curl_multi batch).
* Dependencies: Run_Context (which run is this process in),
* Run_State (ledger row + halt), OpenRouter_Pricing (#18 chain),
* WordPress $wpdb, Logger.
*
* @see class-generation-lock.php — The atomic-write pattern this mirrors.
* @see core/class-run-state.php — The ledger row reserved against.
* @see providers/class-open-router-provider.php — Text-call integration point.
* @see core/class-image-pipeline.php — Batch reservation integration point.
* @see ARCHITECTURE.md #21 — Design rationale.
*/
class PRAutoBlogger_Cost_Governor {
/**
* Rough chars-per-token divisor for prompt-size estimation. An internal
* estimator detail (NOT a behavior setting — the enforced ceiling is
* the prautoblogger_per_run_cost_ceiling_usd SETTING).
*/
private const CHARS_PER_TOKEN = 4;
/**
* Worst-case completion tokens assumed when a caller sets no
* max_tokens. Every current call site sets one; this is belt-and-braces.
*/
private const DEFAULT_MAX_COMPLETION_TOKENS = 4096;
/**
* Reserve the worst-case cost of one chat-completion call for the
* process's current run. Call before dispatch.
*
* Returns null (call proceeds ungoverned, exactly as pre-v0.18.0) when
* this process is not inside a run, the run row/ledger is unavailable
* (half-migrated schema), or the run's ceiling is 0/disabled.
*
* @param string $model Model identifier.
* @param array<int, array{role: string, content: string}> $messages Chat messages (prompt-size estimate).
* @param array<string, mixed> $options Call options (max_tokens).
* @return array{run_id: string, amount: float}|null Open reservation, or null when ungoverned.
* @throws PRAutoBlogger_Cost_Ceiling_Exception When the reservation would breach the ceiling
* (the run is already halted when this throws).
*/
public static function open_chat_reservation( string $model, array $messages, array $options ): ?array {
return self::open_amount_reservation(
self::estimate_chat_cost( $model, $messages, $options ),
'llm:' . $model
);
}
/**
* Reserve a pre-computed worst-case amount (e.g. a curl_multi image
* batch's summed estimate) for the process's current run.
*
* @param float $amount_usd Worst-case cost estimate in USD.
* @param string $context Short label for logs ('llm:<model>', 'image_batch').
* @return array{run_id: string, amount: float}|null Open reservation, or null when ungoverned.
* @throws PRAutoBlogger_Cost_Ceiling_Exception When the reservation would breach the ceiling.
*/
public static function open_amount_reservation( float $amount_usd, string $context ): ?array {
$run_id = PRAutoBlogger_Run_Context::current_run_id();
if ( null === $run_id || '' === $run_id || $amount_usd <= 0 ) {
return null;
}
if ( ! PRAutoBlogger_Run_State::is_available() ) {
return null; // Half-migrated schema — degrade to historical behavior.
}
PRAutoBlogger_Run_State::ensure_run( $run_id );
$run = PRAutoBlogger_Run_State::get_run( $run_id );
if ( null === $run ) {
return null;
}
if ( (float) $run['ceiling_usd'] <= 0 ) {
return null; // Ceiling disabled for this run.
}
if ( self::reserve( $run_id, $amount_usd ) ) {
return array(
'run_id' => $run_id,
'amount' => $amount_usd,
);
}
self::on_breach( $run_id, $amount_usd, $context );
return null; // Unreachable — on_breach always throws.
}
/**
* Settle an open reservation to the call's actual cost: the hold is
* released and the actual amount moves to settled_usd.
*
* @param array{run_id: string, amount: float}|null $reservation Reservation from open_*(), or null (no-op).
* @param float $actual_usd Actual cost of the call.
* @return void
*/
public static function settle( ?array $reservation, float $actual_usd ): void {
if ( null === $reservation || ! PRAutoBlogger_Run_State::is_available() ) {
return;
}
global $wpdb;
$table = PRAutoBlogger_Run_State::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$table}
SET reserved_usd = GREATEST(reserved_usd - %f, 0),
settled_usd = settled_usd + %f,
updated_at = %s
WHERE run_id = %s",
$reservation['amount'],
max( $actual_usd, 0 ),
current_time( 'mysql' ),
$reservation['run_id']
)
);
}
/**
* Release an open reservation without settling cost (failed call).
*
* @param array{run_id: string, amount: float}|null $reservation Reservation from open_*(), or null (no-op).
* @return void
*/
public static function release( ?array $reservation ): void {
self::settle( $reservation, 0.0 );
}
/**
* Worst-case cost estimate for a chat call: estimated prompt tokens
* (message chars / 4) plus the call's max_tokens completion budget,
* priced via the #18 pricing chain (hardcoded table -> cached model
* registry -> conservative fallback).
*
* @param string $model Model identifier.
* @param array<int, array{role: string, content: string}> $messages Chat messages.
* @param array<string, mixed> $options Call options.
* @return float Estimated worst-case USD cost.
*/
public static function estimate_chat_cost( string $model, array $messages, array $options ): float {
$chars = 0;
foreach ( $messages as $message ) {
$chars += strlen( (string) ( $message['content'] ?? '' ) );
}
$prompt_tokens = (int) ceil( $chars / self::CHARS_PER_TOKEN );
$completion_tokens = (int) ( $options['max_tokens'] ?? self::DEFAULT_MAX_COMPLETION_TOKENS );
return ( new PRAutoBlogger_OpenRouter_Pricing() )->estimate_cost( $model, $prompt_tokens, $completion_tokens );
}
/**
* Atomic conditional reservation — the #10 discipline. One UPDATE
* whose WHERE clause enforces `settled + reserved + estimate <=
* ceiling` AND that the run is still open; affected-rows tells us who
* won. Concurrent reservers serialize on the row lock.
*
* @param string $run_id Run UUID.
* @param float $amount Estimate to reserve.
* @return bool True when the reservation was written.
*/
private static function reserve( string $run_id, float $amount ): bool {
global $wpdb;
$table = PRAutoBlogger_Run_State::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table}
SET reserved_usd = reserved_usd + %f, updated_at = %s
WHERE run_id = %s
AND status IN ('pending','running')
AND (reserved_usd + settled_usd + %f) <= ceiling_usd",
$amount,
current_time( 'mysql' ),
$run_id,
$amount
)
);
return 1 === (int) $updated;
}
/**
* Handle a failed reservation: halt the run (sticky), record the
* overage, log, throw. The Review Queue lists halted runs; chained
* queue jobs abort via the run-status check.
*
* @param string $run_id Run UUID.
* @param float $amount The estimate that failed to reserve.
* @param string $context Short label for logs.
* @return void
* @throws PRAutoBlogger_Cost_Ceiling_Exception Always.
*/
private static function on_breach( string $run_id, float $amount, string $context ): void {
$run = PRAutoBlogger_Run_State::get_run( $run_id );
$ceiling = null !== $run ? (float) $run['ceiling_usd'] : 0.0;
$held = null !== $run ? (float) $run['reserved_usd'] + (float) $run['settled_usd'] : 0.0;
$overage = max( ( $held + $amount ) - $ceiling, 0.0 );
PRAutoBlogger_Run_State::mark_status( $run_id, 'halted' );
PRAutoBlogger_Run_State::record_overage( $run_id, $overage );
$message = sprintf(
/* translators: 1: blocked amount USD, 2: call context, 3: committed USD, 4: ceiling USD, 5: run id. */
__( 'Per-run cost ceiling reached: reserving $%1$.4f for %2$s would push the run to $%3$.4f against a $%4$.2f ceiling. Run %5$s halted and routed to the Review Queue.', 'prautoblogger' ),
$amount,
$context,
$held + $amount,
$ceiling,
$run_id
);
PRAutoBlogger_Logger::instance()->error( $message, 'cost-governor' );
throw new PRAutoBlogger_Cost_Ceiling_Exception( $message );
}
}

View File

@@ -36,9 +36,8 @@ class PRAutoBlogger_Cost_Reporter {
$first_of_month = gmdate( 'Y-m-01 00:00:00' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$result = $wpdb->get_var(
$wpdb->prepare(
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
"SELECT COALESCE(SUM(estimated_cost), 0) FROM {$table} WHERE created_at >= %s AND response_status = 'success'",
$first_of_month
)
@@ -65,10 +64,9 @@ class PRAutoBlogger_Cost_Reporter {
$start_date = gmdate( 'Y-m-d', time() - ( $days * DAY_IN_SECONDS ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost
"SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
FROM {$table}
WHERE created_at >= %s AND response_status = 'success'
GROUP BY DATE(created_at)
@@ -103,13 +101,12 @@ class PRAutoBlogger_Cost_Reporter {
$table = $wpdb->prefix . 'prautoblogger_generation_log';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT stage,
SUM(estimated_cost) as total_cost,
SUM(prompt_tokens + completion_tokens) as total_tokens,
COUNT(*) as call_count
COUNT(*) as call_count // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
FROM {$table}
WHERE created_at BETWEEN %s AND %s AND response_status = 'success'
GROUP BY stage",
@@ -143,63 +140,4 @@ class PRAutoBlogger_Cost_Reporter {
}
return ( $this->get_monthly_spend() / $budget ) * 100.0;
}
/**
* Get average input/output token counts for given stages over a time period.
*
* Used by the model picker field renderer to calculate estimated costs
* per generation based on historical token usage. Maps setting IDs to their
* constituting stages (e.g., writing model controls outline + draft + polish).
* Moved here from Cost_Tracker in v0.18.0 (read-only reporting query;
* Cost_Tracker keeps a delegating wrapper for API compatibility).
*
* @param array<string> $stages Stage names ('analysis', 'outline', 'draft', 'polish', 'review').
* @param int $days Historical window (default 30 days).
*
* @return array{avg_prompt_tokens: float, avg_completion_tokens: float, sample_size: int}
* Returns empty counters if no history. Never throws.
*/
public function get_avg_tokens_for_stages( array $stages, int $days = 30 ): array {
global $wpdb;
if ( empty( $stages ) ) {
return array(
'avg_prompt_tokens' => 0.0,
'avg_completion_tokens' => 0.0,
'sample_size' => 0,
);
}
$cutoff_datetime = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );
$stage_list = implode( ',', array_map( array( $wpdb, 'prepare' ), array_fill( 0, count( $stages ), '%s' ), $stages ) );
$table_name = $wpdb->prefix . 'prautoblogger_generation_log';
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Prepared stage list via array_map + prepare
$query = $wpdb->prepare(
"SELECT AVG(prompt_tokens) as avg_prompt,
AVG(completion_tokens) as avg_completion,
COUNT(*) as sample_count
FROM $table_name
WHERE stage IN ( $stage_list )
AND created_at >= %s",
$cutoff_datetime
);
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- phpcs pragma above
$result = $wpdb->get_row( $query, ARRAY_A );
if ( ! $result || 0 === (int) ( $result['sample_count'] ?? 0 ) ) {
return array(
'avg_prompt_tokens' => 0.0,
'avg_completion_tokens' => 0.0,
'sample_size' => 0,
);
}
return array(
'avg_prompt_tokens' => (float) ( $result['avg_prompt'] ?? 0 ),
'avg_completion_tokens' => (float) ( $result['avg_completion'] ?? 0 ),
'sample_size' => (int) ( $result['sample_count'] ?? 0 ),
);
}
}

View File

@@ -47,14 +47,6 @@ class PRAutoBlogger_Cost_Tracker {
*/
public function set_run_id( string $run_id ): void {
$this->run_id = $run_id;
// v0.18.0: declaring a run id makes this PHP process part of that
// run — record the context (cost-governor guard, prompt-version
// stamping for components without a run reference), make sure the
// run ledger row exists, and pin the active prompt versions once.
// All three are self-healing no-ops on a half-migrated schema.
PRAutoBlogger_Run_Context::set_run_id( $run_id );
PRAutoBlogger_Run_State::ensure_run( $run_id );
PRAutoBlogger_Prompt_Registry::pin_for_run( $run_id );
}
/**
@@ -69,24 +61,16 @@ class PRAutoBlogger_Cost_Tracker {
/**
* Log an API call with its token usage and estimated cost.
*
* Side effects: database insert into prab_generation_log. Consumes the
* Request_Recorder stash (v0.20.0 / B1) into the row's request_json so
* every chat call's input is persisted (retention-pruned after R days).
* Side effects: database insert into prab_generation_log.
*
* @param int|null $post_id WordPress post ID (null during generation, set later).
* @param string $stage Pipeline stage (see PRAutoBlogger_Stage_Display_Map).
* @param string $provider Provider name: 'OpenRouter'.
* @param string $model Model identifier used.
* @param int $prompt_tokens Input tokens consumed.
* @param int $completion_tokens Output tokens generated.
* @param string $response_status 'success', 'error', or 'timeout'.
* @param string $error_message Error details if status is not 'success'.
* @param string|null $agent_role v0.18.0 — role that made the call; derived
* from the stage map when null.
* @param string|null $prompt_key v0.18.0 — registry key the call rendered
* with (e.g. 'content.single_pass'); derived
* from the stage map when null. Resolves the
* run-pinned prompt_version stamped on the row.
* @param int|null $post_id WordPress post ID (null during generation, set later).
* @param string $stage Pipeline stage: 'analysis', 'outline', 'draft', 'polish', 'review'.
* @param string $provider Provider name: 'OpenRouter'.
* @param string $model Model identifier used.
* @param int $prompt_tokens Input tokens consumed.
* @param int $completion_tokens Output tokens generated.
* @param string $response_status 'success', 'error', or 'timeout'.
* @param string $error_message Error details if status is not 'success'.
*
* @return void
*/
@@ -98,9 +82,7 @@ class PRAutoBlogger_Cost_Tracker {
int $prompt_tokens,
int $completion_tokens,
string $response_status = 'success',
string $error_message = '',
?string $agent_role = null,
?string $prompt_key = null
string $error_message = ''
): void {
$llm = new PRAutoBlogger_OpenRouter_Provider();
$cost = $llm->estimate_cost( $model, $prompt_tokens, $completion_tokens );
@@ -119,9 +101,6 @@ class PRAutoBlogger_Cost_Tracker {
'estimated_cost' => $cost,
'response_status' => $response_status,
'error_message' => $error_message,
'request_json' => PRAutoBlogger_Request_Recorder::consume(),
'agent_role' => $agent_role ?? PRAutoBlogger_Stage_Display_Map::default_agent_role( $stage ),
'prompt_version' => $this->resolve_prompt_version( $stage, $prompt_key ),
'created_at' => current_time( 'mysql' ),
)
);
@@ -130,19 +109,9 @@ class PRAutoBlogger_Cost_Tracker {
$table = $wpdb->prefix . 'prautoblogger_generation_log';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$inserted = $wpdb->insert( $table, $log_entry->to_db_row() );
$wpdb->insert( $table, $log_entry->to_db_row() );
// Self-healing on a half-migrated schema (e.g. cron fires after a
// deploy but before any admin_init migration pass): retry without
// the v0.18.0 audit columns rather than losing the cost row.
if ( false === $inserted ) {
$legacy_row = $log_entry->to_db_row();
unset( $legacy_row['agent_role'], $legacy_row['prompt_version'] );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$inserted = $wpdb->insert( $table, $legacy_row );
}
if ( false === $inserted || false === $wpdb->insert_id ) {
if ( false === $wpdb->insert_id ) {
PRAutoBlogger_Logger::instance()->error( 'Failed to log API call: ' . $wpdb->last_error, 'cost-tracker' );
}
}
@@ -192,55 +161,23 @@ class PRAutoBlogger_Cost_Tracker {
}
$table = $wpdb->prefix . 'prautoblogger_generation_log';
$row = array(
'post_id' => $post_id,
'run_id' => $this->run_id,
'stage' => $stage,
'provider' => 'cloudflare-workers-ai',
'model' => $model,
'prompt_tokens' => 0,
'completion_tokens' => 0,
'estimated_cost' => $cost_usd,
'response_status' => 'success',
'error_message' => '',
'agent_role' => PRAutoBlogger_Stage_Display_Map::default_agent_role( $stage ),
'prompt_version' => $this->resolve_prompt_version( $stage, null ),
'created_at' => current_time( 'mysql' ),
);
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$inserted = $wpdb->insert( $table, $row );
// Self-healing on a half-migrated schema — see log_api_call().
if ( false === $inserted ) {
unset( $row['agent_role'], $row['prompt_version'] );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->insert( $table, $row );
}
}
/**
* Resolve the pinned prompt version to stamp on a log row.
*
* Uses the explicit registry key when the call site passed one,
* otherwise the stage's primary key from the display map. The version
* comes from the run's pins; the run is this tracker's run_id or —
* for standalone trackers inside a pipeline process (e.g. the image
* prompt rewriter's) — the process-level run context. Null when there
* is no run, no pins, or no key (historical behavior preserved).
*
* @param string $stage Stage being logged.
* @param string|null $prompt_key Explicit registry key, or null to derive.
* @return string|null Pinned version as string, or null.
*/
private function resolve_prompt_version( string $stage, ?string $prompt_key ): ?string {
$key = $prompt_key ?? PRAutoBlogger_Stage_Display_Map::default_prompt_key( $stage );
if ( null === $key ) {
return null;
}
$run_id = $this->run_id ?? PRAutoBlogger_Run_Context::current_run_id();
$pins = PRAutoBlogger_Prompt_Registry::pins_for_run( $run_id );
return isset( $pins[ $key ] ) ? (string) $pins[ $key ] : null;
$wpdb->insert(
$table,
array(
'post_id' => $post_id,
'run_id' => $this->run_id,
'stage' => $stage,
'provider' => 'cloudflare-workers-ai',
'model' => $model,
'prompt_tokens' => 0,
'completion_tokens' => 0,
'estimated_cost' => $cost_usd,
'response_status' => 'success',
'error_message' => '',
'created_at' => current_time( 'mysql' ),
)
);
}
/**
@@ -277,9 +214,9 @@ class PRAutoBlogger_Cost_Tracker {
/**
* Get average input/output token counts for given stages over a time period.
*
* Thin delegate to PRAutoBlogger_Cost_Reporter (the read-only reporting
* class) — kept here for API compatibility with the model-picker field
* and existing tests. See Cost_Reporter for the query.
* Used by the model picker field renderer to calculate estimated costs
* per generation based on historical token usage. Maps setting IDs to their
* constituting stages (e.g., writing model controls outline + draft + polish).
*
* @param array<string> $stages Stage names ('analysis', 'outline', 'draft', 'polish', 'review').
* @param int $days Historical window (default 30 days).
@@ -288,6 +225,46 @@ class PRAutoBlogger_Cost_Tracker {
* Returns empty counters if no history. Never throws.
*/
public function get_avg_tokens_for_stages( array $stages, int $days = 30 ): array {
return ( new PRAutoBlogger_Cost_Reporter() )->get_avg_tokens_for_stages( $stages, $days );
global $wpdb;
if ( empty( $stages ) ) {
return array(
'avg_prompt_tokens' => 0.0,
'avg_completion_tokens' => 0.0,
'sample_size' => 0,
);
}
$cutoff_time = time() - ( $days * DAY_IN_SECONDS );
$stage_list = implode( ',', array_map( array( $wpdb, 'prepare' ), array_fill( 0, count( $stages ), '%s' ), $stages ) );
$table_name = $wpdb->prefix . 'prautoblogger_generation_log';
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Prepared stage list via array_map + prepare
$query = $wpdb->prepare(
"SELECT AVG(input_tokens) as avg_input,
AVG(output_tokens) as avg_output,
COUNT(*) as sample_count
FROM $table_name
WHERE stage IN ( $stage_list )
AND timestamp >= %d",
$cutoff_time
);
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- phpcs pragma above
$result = $wpdb->get_row( $query, ARRAY_A );
if ( ! $result || 0 === (int) ( $result['sample_count'] ?? 0 ) ) {
return array(
'avg_prompt_tokens' => 0.0,
'avg_completion_tokens' => 0.0,
'sample_size' => 0,
);
}
return array(
'avg_prompt_tokens' => (float) ( $result['avg_input'] ?? 0 ),
'avg_completion_tokens' => (float) ( $result['avg_output'] ?? 0 ),
'sample_size' => (int) ( $result['sample_count'] ?? 0 ),
);
}
}

View File

@@ -1,169 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Persists generated images and composed variants for a post.
*
* Owns the media-library side of the image pipeline: sideloading the primary
* (featured) image with cost logging, sideloading composed OG/square variants
* with role/base meta-linking (no cost-tracker entries — composition is $0
* local CPU), and prepending the editable HTML caption to the post. Extracted
* from PRAutoBlogger_Image_Pipeline in v0.17.0 for 300-line compliance.
*
* Triggered by: PRAutoBlogger_Image_Pipeline during content generation run.
* Dependencies: PRAutoBlogger_Image_Media_Sideloader, PRAutoBlogger_Cost_Tracker,
* PRAutoBlogger_Logger.
*
* @see core/class-image-pipeline.php — Sole caller.
* @see core/class-image-composer.php — Produces the variants this persists.
* @see core/class-image-media-sideloader.php — Media library import.
*/
class PRAutoBlogger_Image_Attacher {
/** Post meta key per composed variant role. */
private const ROLE_POST_META = array(
'og' => '_prautoblogger_og_image_id',
'square' => '_prautoblogger_square_image_id',
);
/** @var PRAutoBlogger_Image_Media_Sideloader Imports bytes into the media library. */
private PRAutoBlogger_Image_Media_Sideloader $sideloader;
/** @var PRAutoBlogger_Cost_Tracker Logs primary image generation spend. */
private PRAutoBlogger_Cost_Tracker $cost_tracker;
/**
* Construct with the pipeline's sideloader + cost tracker.
*
* @param PRAutoBlogger_Image_Media_Sideloader $sideloader Media importer.
* @param PRAutoBlogger_Cost_Tracker $cost_tracker Spend logger.
*/
public function __construct( PRAutoBlogger_Image_Media_Sideloader $sideloader, PRAutoBlogger_Cost_Tracker $cost_tracker ) {
$this->sideloader = $sideloader;
$this->cost_tracker = $cost_tracker;
}
/**
* Sideload a primary image into the media library and log its cost.
*
* Side effects: media import, cost-tracker row, info log.
*
* @param array $image_data Provider result with bytes, model, cost_usd.
* @param int $post_id Post ID.
* @param string $slot Cost-tracking slot ('image_a' or 'image_b').
* @param string $label Human-readable label for logs.
* @param string $alt_text Alt text — the editorial caption (v0.17.0 bug
* fix: previously the model name leaked here).
*
* @return int|\WP_Error Attachment ID on success.
*/
public function sideload_and_log( array $image_data, int $post_id, string $slot, string $label, string $alt_text = '' ) {
$attachment_id = $this->sideloader->sideload_image( $image_data, $post_id, $alt_text );
if ( is_wp_error( $attachment_id ) ) {
return $attachment_id;
}
$this->cost_tracker->log_image_generation(
$image_data['cost_usd'],
$image_data['model'] ?? 'unknown',
$post_id,
$slot
);
PRAutoBlogger_Logger::instance()->info(
sprintf( '%s for post %d (att %d, $%.4f)', $label, $post_id, $attachment_id, $image_data['cost_usd'] ),
'image_pipeline'
);
return $attachment_id;
}
/**
* Sideload composed variants and meta-link them to post + base image.
*
* Each variant attachment gets `_prautoblogger_image_role` and
* `_prautoblogger_base_attachment_id`; the post gets the role-specific
* ID meta (see ROLE_POST_META). No cost-tracker entries — composition is
* a $0 local stage. A failed variant sideload logs a WARNING and is
* skipped; it never blocks the publish.
*
* @param array $variants Composed variants (role 'og'/'square' only are persisted).
* @param int $post_id Post ID.
* @param int $base_attachment_id Featured attachment the variants derive from.
* @param string $caption Editorial caption (used as variant alt text).
* @param string $model Generation model recorded on the variant attachment.
*/
public function attach_variants( array $variants, int $post_id, int $base_attachment_id, string $caption, string $model ): void {
foreach ( $variants as $variant ) {
$role = (string) ( $variant['role'] ?? '' );
if ( ! isset( self::ROLE_POST_META[ $role ] ) ) {
continue;
}
$attachment_id = $this->sideloader->sideload_image(
array(
'bytes' => (string) ( $variant['bytes'] ?? '' ),
'mime_type' => (string) ( $variant['mime_type'] ?? 'image/png' ),
'width' => (int) ( $variant['width'] ?? 0 ),
'height' => (int) ( $variant['height'] ?? 0 ),
'model' => $model,
'cost_usd' => 0.0,
'latency_ms' => 0,
),
$post_id,
$caption,
$role
);
if ( is_wp_error( $attachment_id ) ) {
PRAutoBlogger_Logger::instance()->warning(
sprintf( 'Failed to sideload %s variant for post %d: %s', $role, $post_id, $attachment_id->get_error_message() ),
'image_composer'
);
continue;
}
update_post_meta( $attachment_id, '_prautoblogger_image_role', $role );
update_post_meta( $attachment_id, '_prautoblogger_base_attachment_id', $base_attachment_id );
update_post_meta( $post_id, self::ROLE_POST_META[ $role ], $attachment_id );
PRAutoBlogger_Logger::instance()->info(
sprintf( '%s variant for post %d (att %d, %dx%d)', $role, $post_id, $attachment_id, (int) $variant['width'], (int) $variant['height'] ),
'image_composer'
);
}
}
/**
* Prepend the editorial caption as styled text at the top of the post.
*
* Only inserts the caption — NOT the image. The theme already displays
* the featured image, so embedding it again would cause a duplicate.
*
* @param int $post_id Post ID.
* @param int $attachment_id Featured image attachment ID (unused; kept for parity with meta storage).
* @param string $caption Caption text shown below the image.
*/
public function prepend_caption_to_post( int $post_id, int $attachment_id, string $caption ): void {
$post = get_post( $post_id );
if ( ! $post ) {
return;
}
// Caption-only block — the theme handles the featured image display.
$caption_html = sprintf(
'<p class="prautoblogger-comic-caption" style="text-align:center;font-style:italic;color:#555;font-size:1.1em;margin:0 0 2em 0;">— "%s"</p>',
esc_html( $caption )
);
wp_update_post(
array(
'ID' => $post_id,
'post_content' => $caption_html . "\n\n" . $post->post_content,
)
);
}
}

View File

@@ -1,186 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Low-level Imagick canvas primitives for the deterministic image composer.
*
* Capability smoke test, base-image loading, cover-cropping, logo placement,
* and deterministic PNG encoding. No WordPress functions anywhere in this
* class — it runs unchanged inside the standalone render harness used to
* produce the PR sample images.
*
* Triggered by: PRAutoBlogger_Image_Composer_Imagick (renderer) per variant.
* Dependencies: ext-imagick (callers must gate on is_imagick_usable()).
*
* @see core/class-image-composer-imagick.php — Sole consumer.
* @see core/class-image-composer.php — Caches the capability probe result.
*/
class PRAutoBlogger_Image_Composer_Canvas {
/**
* Probe whether Imagick can do everything the renderer needs: PNG
* encode plus TTF text annotation (the smoke test draws one glyph on a
* tiny in-memory canvas). Cheap to run but callers should cache it.
*
* Side effects: none beyond a transient in-memory Imagick object.
*
* @param string $font_path Absolute path to a bundled TTF used for the smoke test.
*
* @return bool True when full compositing is available.
*/
public static function is_imagick_usable( string $font_path ): bool {
if ( ! extension_loaded( 'imagick' ) || ! class_exists( '\Imagick' ) ) {
return false;
}
try {
$formats = \Imagick::queryFormats( 'PNG' );
if ( empty( $formats ) ) {
return false;
}
if ( ! is_readable( $font_path ) ) {
return false;
}
$probe = new \Imagick();
$probe->newImage( 8, 8, new \ImagickPixel( '#ffffff' ), 'png' );
$draw = new \ImagickDraw();
$draw->setFont( $font_path );
$draw->setFontSize( 6 );
$probe->annotateImage( $draw, 1, 6, 0.0, 'P' );
$probe->clear();
return true;
} catch ( \Throwable $e ) {
return false;
}
}
/**
* Load base image bytes into an Imagick object (first frame only).
*
* @param string $bytes Raw image bytes (PNG/JPEG/WebP — any readable format).
*
* @return \Imagick Loaded image.
* @throws \RuntimeException When the bytes cannot be decoded.
*/
public static function load_base( string $bytes ): \Imagick {
$image = new \Imagick();
if ( ! $image->readImageBlob( $bytes ) ) {
throw new \RuntimeException( 'Composer could not decode base image bytes.' );
}
$image->setIteratorIndex( 0 );
$image = $image->coalesceImages()->current();
$image->setImagePage( 0, 0, 0, 0 );
return $image;
}
/**
* Center cover-crop an image to exact target dimensions without upscaling.
*
* Crops the largest centered region matching the target aspect ratio,
* then scales DOWN to the target. Refuses (returns false) when the source
* is too small to fill the target without upscaling.
*
* Side effects: mutates $image in place on success.
*
* @param \Imagick $image Source image (mutated).
* @param int $target_w Target width in px.
* @param int $target_h Target height in px.
*
* @return bool False when the crop would require upscaling.
*/
public static function cover_crop( \Imagick $image, int $target_w, int $target_h ): bool {
$width = $image->getImageWidth();
$height = $image->getImageHeight();
if ( $width < 1 || $height < 1 ) {
return false;
}
$ratio = max( $target_w / $width, $target_h / $height );
if ( $ratio > 1.0 ) {
return false;
}
$src_w = min( $width, (int) round( $target_w / $ratio ) );
$src_h = min( $height, (int) round( $target_h / $ratio ) );
$x = (int) floor( ( $width - $src_w ) / 2 );
$y = (int) floor( ( $height - $src_h ) / 2 );
$image->cropImage( $src_w, $src_h, $x, $y );
$image->setImagePage( 0, 0, 0, 0 );
$image->resizeImage( $target_w, $target_h, \Imagick::FILTER_LANCZOS, 1 );
return true;
}
/**
* Composite a brand PNG onto the canvas at a target height and opacity.
*
* @param \Imagick $canvas Destination canvas (mutated).
* @param string $asset_path Absolute path to the brand PNG.
* @param int $target_h Logo height in px (width keeps aspect).
* @param int $x Left position on the canvas.
* @param int $y Top position on the canvas.
* @param float $opacity 1.0 = opaque, 0.55 = subtle corner mark.
*
* @return int Rendered logo width in px (useful for caption x-offsets).
* @throws \RuntimeException When the asset is missing or unreadable.
*/
public static function place_logo( \Imagick $canvas, string $asset_path, int $target_h, int $x, int $y, float $opacity = 1.0 ): int {
if ( ! is_readable( $asset_path ) ) {
throw new \RuntimeException( 'Composer brand asset missing: ' . basename( $asset_path ) );
}
$logo = new \Imagick( $asset_path );
$logo->setImagePage( 0, 0, 0, 0 );
$scale = $target_h / max( 1, $logo->getImageHeight() );
$target_w = max( 1, (int) round( $logo->getImageWidth() * $scale ) );
$logo->resizeImage( $target_w, $target_h, \Imagick::FILTER_LANCZOS, 1 );
if ( $opacity < 1.0 ) {
$logo->evaluateImage( \Imagick::EVALUATE_MULTIPLY, max( 0.0, $opacity ), \Imagick::CHANNEL_ALPHA );
}
$canvas->compositeImage( $logo, \Imagick::COMPOSITE_OVER, $x, $y );
$logo->clear();
return $target_w;
}
/**
* Encode a canvas as a deterministic PNG variant payload.
*
* Strips all metadata and excludes PNG date/time chunks so identical
* inputs produce byte-identical output in the same environment.
*
* Side effects: destroys the Imagick object after encoding.
*
* @param \Imagick $image Finished canvas.
* @param string $role Variant role: 'featured', 'og', or 'square'.
*
* @return array{bytes: string, mime_type: string, width: int, height: int, role: string}
*/
public static function finalize_png( \Imagick $image, string $role ): array {
$image->setImageFormat( 'png' );
$image->setImageDepth( 8 );
$image->stripImage();
$image->setOption( 'png:exclude-chunks', 'date,time' );
$image->setOption( 'png:compression-level', '9' );
$variant = array(
'bytes' => $image->getImageBlob(),
'mime_type' => 'image/png',
'width' => $image->getImageWidth(),
'height' => $image->getImageHeight(),
'role' => $role,
);
$image->clear();
return $variant;
}
}

View File

@@ -1,114 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Resize-only composer rung backed by wp_get_image_editor() (GD path).
*
* Used when Imagick is unusable: emits unbranded, caption-free center-crops
* at each variant's exact dimensions. Variants that would require upscaling
* (e.g. a 1080×1080 square from a 1200×632 base — WP's editor never upscales
* on crop-resize) are skipped; the OG crop is always achievable from the
* standard base. Output is GD PNG, which embeds no timestamps, so this rung
* is deterministic too.
*
* Triggered by: PRAutoBlogger_Image_Composer when the capability probe says 'gd'.
* Dependencies: wp_get_image_editor(), get_temp_dir(), PRAutoBlogger_Logger.
*
* @see core/class-image-composer.php — Orchestrator + degradation ladder.
* @see core/class-image-composer-imagick.php — The full-fidelity rung this replaces.
*/
class PRAutoBlogger_Image_Composer_Editor {
/**
* Render resize-only variants for the requested roles.
*
* Side effects: temp file write/delete per variant; debug log on skips.
*
* @param string $bytes Base image bytes.
* @param string[] $roles Variant roles to attempt ('og', 'square').
* @param array<string, array<string, mixed>> $layout Layout geometry (for target dimensions).
*
* @return array<int, array{bytes: string, mime_type: string, width: int, height: int, role: string}>
* Successfully resized variants only (possibly empty).
*/
public function compose_variants( string $bytes, array $roles, array $layout ): array {
$variants = array();
foreach ( $roles as $role ) {
$target_w = (int) ( $layout[ $role ]['width'] ?? 0 );
$target_h = (int) ( $layout[ $role ]['height'] ?? 0 );
if ( $target_w < 1 || $target_h < 1 ) {
continue;
}
$resized = $this->cover_crop( $bytes, $target_w, $target_h );
if ( null === $resized ) {
PRAutoBlogger_Logger::instance()->debug(
sprintf( 'Resize-only %s variant skipped (editor failure or would upscale).', $role ),
'image_composer'
);
continue;
}
$resized['role'] = $role;
$variants[] = $resized;
}
return $variants;
}
/**
* Center-crop bytes to exact dimensions with the portable WP editor.
*
* @param string $bytes Source image bytes.
* @param int $target_w Target width in px.
* @param int $target_h Target height in px.
*
* @return array{bytes: string, mime_type: string, width: int, height: int}|null
* Null when the editor fails or cannot hit the exact size
* without upscaling.
*/
private function cover_crop( string $bytes, int $target_w, int $target_h ): ?array {
$temp = get_temp_dir() . uniqid( 'prab_compose_', true ) . '.png';
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- temp file, same pattern as the sideloader.
if ( false === file_put_contents( $temp, $bytes ) ) {
return null;
}
try {
$editor = wp_get_image_editor( $temp );
if ( is_wp_error( $editor ) ) {
return null;
}
if ( is_wp_error( $editor->resize( $target_w, $target_h, true ) ) ) {
return null;
}
$size = $editor->get_size();
if ( (int) $size['width'] !== $target_w || (int) $size['height'] !== $target_h ) {
return null; // Exact size not reachable without upscaling.
}
if ( is_wp_error( $editor->save( $temp, 'image/png' ) ) ) {
return null;
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- temp file we just wrote.
$out = file_get_contents( $temp );
return false === $out ? null : array(
'bytes' => $out,
'mime_type' => 'image/png',
'width' => $target_w,
'height' => $target_h,
);
} catch ( \Throwable $e ) {
PRAutoBlogger_Logger::instance()->debug( 'WP image editor crop threw: ' . $e->getMessage(), 'image_composer' );
return null;
} finally {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- best-effort temp cleanup.
@unlink( $temp );
}
}
}

View File

@@ -1,250 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Imagick renderer for the deterministic image composer (full-fidelity rung).
*
* Renders the three branded variants from one base image: corner-marked
* featured (1200×632), teal-band OG (1200×630), and card-layout square
* (1080×1080). No WordPress functions anywhere — layout geometry and asset
* directories arrive via the constructor, so the class runs unchanged inside
* the standalone render harness that produced the PR samples. Methods throw
* on failure; the orchestrator catches and degrades, so a renderer error can
* never fail a publish.
*
* Triggered by: PRAutoBlogger_Image_Composer when the capability probe says 'imagick'.
* Dependencies: ext-imagick, bundled brand PNGs + OFL fonts,
* PRAutoBlogger_Image_Composer_Canvas (primitives),
* PRAutoBlogger_Image_Composer_Layout (caption clamp).
*
* @see core/class-image-composer.php — Orchestrator + degradation ladder.
* @see core/class-image-composer-canvas.php — Crop/logo/PNG primitives.
* @see core/class-image-composer-layout.php — Geometry defaults + clamp.
*/
class PRAutoBlogger_Image_Composer_Imagick {
/** @var array<string, array<string, mixed>> Layout geometry keyed by role. */
private array $layout;
/** @var string Absolute path to the vendored brand PNG directory (trailing slash). */
private string $brand_dir;
/** @var string Absolute path to the bundled font directory (trailing slash). */
private string $fonts_dir;
/**
* Construct with resolved layout + asset locations.
*
* @param array<string, array<string, mixed>> $layout Filtered layout (see Layout::defaults()).
* @param string $brand_dir Brand PNG directory, trailing slash.
* @param string $fonts_dir Font directory, trailing slash.
*/
public function __construct( array $layout, string $brand_dir, string $fonts_dir ) {
$this->layout = $layout;
$this->brand_dir = $brand_dir;
$this->fonts_dir = $fonts_dir;
}
/**
* Featured variant: base image untouched except a subtle corner mark.
*
* @param string $bytes Base image bytes.
*
* @return array{bytes: string, mime_type: string, width: int, height: int, role: string}
* @throws \RuntimeException|\ImagickException On decode/asset failure.
*/
public function compose_featured( string $bytes ): array {
$conf = $this->layout['featured'];
$canvas = PRAutoBlogger_Image_Composer_Canvas::load_base( $bytes );
$mark_h = (int) $conf['mark_height'];
$inset = (int) $conf['mark_inset'];
// The mark asset is square, so rendered width equals the height.
PRAutoBlogger_Image_Composer_Canvas::place_logo(
$canvas,
$this->brand_dir . $conf['mark_asset'],
$mark_h,
$canvas->getImageWidth() - $mark_h - $inset,
$canvas->getImageHeight() - $mark_h - $inset,
(float) $conf['mark_opacity']
);
return PRAutoBlogger_Image_Composer_Canvas::finalize_png( $canvas, 'featured' );
}
/**
* OG variant (1200×630): center-cropped base, bottom teal band with the
* brand mark and the clamped caption in white.
*
* @param string $bytes Base image bytes.
* @param string $caption Editorial caption (clamped to 2 lines).
*
* @return array{bytes: string, mime_type: string, width: int, height: int, role: string}
* @throws \RuntimeException|\ImagickException On decode/crop/asset failure.
*/
public function compose_og( string $bytes, string $caption ): array {
$conf = $this->layout['og'];
$width = (int) $conf['width'];
$height = (int) $conf['height'];
$band_h = (int) $conf['band_height'];
$band_y = $height - $band_h;
$canvas = PRAutoBlogger_Image_Composer_Canvas::load_base( $bytes );
if ( ! PRAutoBlogger_Image_Composer_Canvas::cover_crop( $canvas, $width, $height ) ) {
$canvas->clear();
throw new \RuntimeException( 'OG variant would require upscaling the base image.' );
}
$this->draw_rect( $canvas, 0, $band_y, $width, $height, (string) $conf['band_color'] );
$logo_h = (int) $conf['logo_height'];
$logo_w = PRAutoBlogger_Image_Composer_Canvas::place_logo(
$canvas,
$this->brand_dir . $conf['logo_asset'],
$logo_h,
(int) $conf['logo_x'],
$band_y + (int) floor( ( $band_h - $logo_h ) / 2 )
);
$lines = PRAutoBlogger_Image_Composer_Layout::clamp_caption(
$caption,
(int) $conf['caption_chars_per_line'],
(int) $conf['caption_max_lines']
);
$this->draw_lines(
$canvas,
$lines,
array(
'font' => $this->fonts_dir . $conf['caption_font'],
'size' => (float) $conf['caption_size'],
'color' => (string) $conf['caption_color'],
'line_height' => (float) $conf['caption_line_height'],
'x' => (int) $conf['logo_x'] + $logo_w + (int) $conf['caption_gap'],
'center_y' => $band_y + (int) floor( $band_h / 2 ),
'align' => \Imagick::ALIGN_LEFT,
)
);
return PRAutoBlogger_Image_Composer_Canvas::finalize_png( $canvas, 'og' );
}
/**
* Square variant (1080×1080, card layout, no upscaling): full base
* downscaled into the top slice, cream caption panel in Poppins Bold,
* teal footer band with the horizontal reverse lockup.
*
* @param string $bytes Base image bytes.
* @param string $caption Editorial caption (clamped to 3 lines).
*
* @return array{bytes: string, mime_type: string, width: int, height: int, role: string}
* @throws \RuntimeException|\ImagickException On decode/crop/asset failure.
*/
public function compose_square( string $bytes, string $caption ): array {
$conf = $this->layout['square'];
$width = (int) $conf['width'];
$height = (int) $conf['height'];
$slice_h = (int) $conf['slice_height'];
$footer_h = (int) $conf['footer_height'];
$footer_y = $height - $footer_h;
$slice = PRAutoBlogger_Image_Composer_Canvas::load_base( $bytes );
if ( ! PRAutoBlogger_Image_Composer_Canvas::cover_crop( $slice, $width, $slice_h ) ) {
$slice->clear();
throw new \RuntimeException( 'Square variant would require upscaling the base image.' );
}
$canvas = new \Imagick();
$canvas->newImage( $width, $height, new \ImagickPixel( (string) $conf['panel_color'] ), 'png' );
$canvas->compositeImage( $slice, \Imagick::COMPOSITE_OVER, 0, 0 );
$slice->clear();
$this->draw_rect( $canvas, 0, $footer_y, $width, $height, (string) $conf['footer_color'] );
$logo_h = (int) $conf['footer_logo_height'];
$logo = new \Imagick( $this->brand_dir . $conf['footer_logo_asset'] );
$logo_w = (int) round( $logo->getImageWidth() * ( $logo_h / max( 1, $logo->getImageHeight() ) ) );
$logo->clear();
PRAutoBlogger_Image_Composer_Canvas::place_logo(
$canvas,
$this->brand_dir . $conf['footer_logo_asset'],
$logo_h,
(int) floor( ( $width - $logo_w ) / 2 ),
$footer_y + (int) floor( ( $footer_h - $logo_h ) / 2 )
);
$lines = PRAutoBlogger_Image_Composer_Layout::clamp_caption(
$caption,
(int) $conf['caption_chars_per_line'],
(int) $conf['caption_max_lines']
);
$this->draw_lines(
$canvas,
$lines,
array(
'font' => $this->fonts_dir . $conf['caption_font'],
'size' => (float) $conf['caption_size'],
'color' => (string) $conf['caption_color'],
'line_height' => (float) $conf['caption_line_height'],
'x' => (int) floor( $width / 2 ),
'center_y' => $slice_h + (int) floor( ( $footer_y - $slice_h ) / 2 ),
'align' => \Imagick::ALIGN_CENTER,
)
);
return PRAutoBlogger_Image_Composer_Canvas::finalize_png( $canvas, 'square' );
}
/**
* Fill an axis-aligned rectangle on the canvas.
*
* @param \Imagick $canvas Destination canvas (mutated).
* @param int $x1 Left.
* @param int $y1 Top.
* @param int $x2 Right.
* @param int $y2 Bottom.
* @param string $color Hex fill color.
*/
private function draw_rect( \Imagick $canvas, int $x1, int $y1, int $x2, int $y2, string $color ): void {
$draw = new \ImagickDraw();
$draw->setFillColor( new \ImagickPixel( $color ) );
$draw->rectangle( (float) $x1, (float) $y1, (float) $x2, (float) $y2 );
$canvas->drawImage( $draw );
}
/**
* Draw pre-clamped caption lines vertically centered around center_y.
*
* @param \Imagick $canvas Destination canvas (mutated).
* @param string[] $lines Already-clamped lines (may be empty — no-op).
* @param array{font: string, size: float, color: string, line_height: float, x: int, center_y: int, align: int} $opts Text options.
*
* @throws \RuntimeException When the bundled font file is missing.
*/
private function draw_lines( \Imagick $canvas, array $lines, array $opts ): void {
if ( empty( $lines ) ) {
return;
}
if ( ! is_readable( $opts['font'] ) ) {
throw new \RuntimeException( 'Composer font missing: ' . basename( $opts['font'] ) );
}
$draw = new \ImagickDraw();
$draw->setFont( $opts['font'] );
$draw->setFontSize( $opts['size'] );
$draw->setFillColor( new \ImagickPixel( $opts['color'] ) );
$draw->setTextAlignment( $opts['align'] );
$draw->setTextAntialias( true );
$metrics = $canvas->queryFontMetrics( $draw, 'Hg' );
$line_step = (int) round( $opts['size'] * $opts['line_height'] );
$block_h = ( count( $lines ) - 1 ) * $line_step + (int) round( $metrics['ascender'] - $metrics['descender'] );
$baseline = $opts['center_y'] - (int) floor( $block_h / 2 ) + (int) round( $metrics['ascender'] );
foreach ( $lines as $line ) {
$canvas->annotateImage( $draw, (float) $opts['x'], (float) $baseline, 0.0, $line );
$baseline += $line_step;
}
}
}

View File

@@ -1,175 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Geometry defaults and caption clamping for the deterministic image composer.
*
* Pure functions and constants only — no WordPress, no Imagick. This keeps
* the class unit-testable and usable from a standalone render harness. The
* orchestrator exposes defaults() through the `prautoblogger_image_compose_layout`
* filter; geometry is intentionally NOT a settings-page surface (promote to
* settings only if the CEO asks to tune it — see ARCHITECTURE.md #21).
*
* Triggered by: PRAutoBlogger_Image_Composer (orchestrator) at compose time.
* Dependencies: mbstring (bundled with WordPress via compat polyfills).
*
* @see core/class-image-composer.php — Applies the layout filter.
* @see core/class-image-composer-imagick.php — Consumes the geometry values.
* @see tests/unit/Core/ImageComposerLayoutTest.php — Clamp boundary cases.
*/
class PRAutoBlogger_Image_Composer_Layout {
/** Brand tokens (locked — see peptide-repo-brand README). */
public const COLOR_TEAL = '#1B8A92';
public const COLOR_LIME = '#7FD600';
public const COLOR_ORANGE = '#FF8A3D';
public const COLOR_INK = '#0D0D0D';
public const COLOR_CREAM = '#FAFAF7';
/** Ellipsis appended when a caption overflows its line budget. */
public const ELLIPSIS = '…';
/**
* Default geometry for every composed variant.
*
* Asset filenames resolve against assets/brand/ and assets/fonts/ in the
* plugin; sizes are px. Values were tuned against rendered samples (see
* PR #thread 2026-06-image-composer assets).
*
* Note: 'caption_margin_right' (og) and 'caption_side_padding' (square) were removed
* in v0.19.4 — the Imagick renderer enforces right-edge geometry via caption_chars_per_line
* and centered x positioning respectively, so those keys had no consumer.
*
* @return array<string, array<string, mixed>> Keyed by role: featured, og, square.
*/
public static function defaults(): array {
return array(
'featured' => array(
'mark_asset' => 'logo-mark-small-56.png',
'mark_height' => 28,
'mark_inset' => 16,
'mark_opacity' => 0.55,
),
'og' => array(
'width' => 1200,
'height' => 630,
'band_height' => 120,
'band_color' => self::COLOR_TEAL,
'logo_asset' => 'logo-mark-small-112.png',
'logo_height' => 64,
'logo_x' => 40,
'caption_font' => 'Poppins-SemiBold.ttf',
'caption_size' => 32,
'caption_color' => '#FFFFFF',
'caption_gap' => 24,
'caption_max_lines' => 2,
'caption_chars_per_line' => 52,
'caption_line_height' => 1.3,
),
'square' => array(
'width' => 1080,
'height' => 1080,
'slice_height' => 569,
'panel_color' => self::COLOR_CREAM,
'footer_height' => 96,
'footer_color' => self::COLOR_TEAL,
'footer_logo_asset' => 'logo-horizontal-reverse-128.png',
'footer_logo_height' => 48,
'caption_font' => 'Poppins-Bold.ttf',
'caption_size' => 48,
'caption_color' => self::COLOR_INK,
'caption_max_lines' => 3,
'caption_chars_per_line' => 36,
'caption_line_height' => 1.3,
),
);
}
/**
* Clamp and word-wrap a caption to a hard per-variant budget.
*
* Whitespace is collapsed, words wrap at word boundaries, words longer
* than a full line are hard-split, and overflow beyond max_lines is cut
* with a trailing ellipsis. Multibyte-safe (mb_* functions).
*
* Side effects: none (pure).
*
* @param string $caption Raw caption text (any length, any script).
* @param int $chars_per_line Hard character budget per line (min 1).
* @param int $max_lines Maximum number of lines (min 1).
*
* @return string[] Wrapped lines; empty array when the caption is blank.
*/
public static function clamp_caption( string $caption, int $chars_per_line, int $max_lines ): array {
$chars_per_line = max( 1, $chars_per_line );
$max_lines = max( 1, $max_lines );
$normalized = trim( (string) preg_replace( '/\s+/u', ' ', $caption ) );
if ( '' === $normalized ) {
return array();
}
$lines = array();
$line = '';
foreach ( explode( ' ', $normalized ) as $word ) {
// Hard-split words longer than a full line so they cannot overflow.
while ( mb_strlen( $word ) > $chars_per_line ) {
if ( '' !== $line ) {
$lines[] = $line;
$line = '';
if ( count( $lines ) >= $max_lines ) {
return self::ellipsize( $lines, $chars_per_line );
}
}
$lines[] = mb_substr( $word, 0, $chars_per_line );
$word = mb_substr( $word, $chars_per_line );
if ( count( $lines ) >= $max_lines ) {
return self::ellipsize( $lines, $chars_per_line );
}
}
$candidate = ( '' === $line ) ? $word : $line . ' ' . $word;
if ( mb_strlen( $candidate ) <= $chars_per_line ) {
$line = $candidate;
continue;
}
$lines[] = $line;
$line = $word;
if ( count( $lines ) >= $max_lines ) {
return self::ellipsize( $lines, $chars_per_line );
}
}
if ( '' !== $line ) {
$lines[] = $line;
}
return $lines;
}
/**
* Append an ellipsis to the final line, trimming first if the line is
* already at the character budget so the result never exceeds it.
*
* @param string[] $lines Lines already at the max-line count.
* @param int $chars_per_line Hard character budget per line.
*
* @return string[] Lines with a trailing ellipsis on the last one.
*/
private static function ellipsize( array $lines, int $chars_per_line ): array {
$last_index = count( $lines ) - 1;
$last = $lines[ $last_index ];
if ( mb_strlen( $last ) + 1 > $chars_per_line ) {
$last = rtrim( mb_substr( $last, 0, max( 0, $chars_per_line - 1 ) ) );
}
$lines[ $last_index ] = $last . self::ELLIPSIS;
return $lines;
}
}

View File

@@ -1,298 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Orchestrates deterministic image composition with a capability ladder.
*
* Sits between the provider's raw bytes and the media sideloader. Probes the
* environment once (cached in an option keyed by a PHP/extension fingerprint,
* so it auto-invalidates when the host changes — Hostinger extension state
* has flipped before), then renders per the ladder: (1) Imagick usable →
* full branded compositing; (2) GD via WP editor → resize-only variants, no
* branding/text, WARNING once; (3) no image library → pass-through, WARNING
* once. compose() never throws and always returns a featured-first non-empty
* list, so a composition failure can never block a publish. Local CPU only:
* $0, no provider call; duration is logged on the image_composer channel.
*
* Triggered by: PRAutoBlogger_Image_Pipeline after batch results + NSFW retry,
* before sideloading.
* Dependencies: Image_Composer_Imagick (rung 1), Image_Composer_Editor (rung 2),
* Image_Composer_Canvas (probe), Image_Composer_Layout, Logger.
*
* @see core/interface-image-composer.php — The contract.
* @see core/class-image-pipeline.php — Caller.
* @see core/class-image-attacher.php — Persists returned variants.
* @see ARCHITECTURE.md — Decision #21.
*/
class PRAutoBlogger_Image_Composer implements PRAutoBlogger_Image_Composer_Interface {
/** Option keys (prautoblogger_ prefix keeps the uninstall sweep effective). */
public const OPTION_ENABLED = 'prautoblogger_image_compose_enabled';
public const OPTION_VARIANTS = 'prautoblogger_image_compose_variants';
public const OPTION_MARK_ENABLED = 'prautoblogger_image_featured_mark_enabled';
public const OPTION_CAPABILITY = 'prautoblogger_image_compose_capability';
/** Capability rungs. */
public const CAP_IMAGICK = 'imagick';
public const CAP_GD = 'gd';
public const CAP_NONE = 'none';
/** @var PRAutoBlogger_Image_Composer_Imagick|null Lazily built; injectable for tests. */
private ?PRAutoBlogger_Image_Composer_Imagick $renderer;
/** @var bool Degradation WARNING fired this run (once per PHP process). */
private static bool $warned_this_run = false;
/**
* Construct, optionally injecting a renderer (tests).
* @param PRAutoBlogger_Image_Composer_Imagick|null $renderer Optional renderer override.
*/
public function __construct( ?PRAutoBlogger_Image_Composer_Imagick $renderer = null ) {
$this->renderer = $renderer;
}
/**
* Compose final variants for one generated image. See the interface for
* the full contract; this implementation never throws.
* Side effects: reads options, may cache the capability probe, logs.
*
* @param array $image_data Provider result (bytes, mime_type, width, height, ...).
* @param array $context {post_id, caption, title, slot}.
* @return array<int, array{bytes: string, mime_type: string, width: int, height: int, role: string}>
*/
public function compose( array $image_data, array $context ): array {
$passthrough = array( $this->passthrough_variant( $image_data ) );
if ( '' === $passthrough[0]['bytes'] || '1' !== (string) get_option( self::OPTION_ENABLED, '1' ) ) {
return $passthrough;
}
$started = microtime( true );
$bytes = $passthrough[0]['bytes'];
$capability = $this->resolve_capability();
$caption = (string) ( $context['caption'] ?? '' );
$roles = ( 'image_a' === (string) ( $context['slot'] ?? 'image_a' ) )
? $this->configured_variants()
: array();
if ( self::CAP_IMAGICK === $capability ) {
$variants = $this->compose_via_imagick( $bytes, $caption, $roles, $passthrough[0] );
} elseif ( self::CAP_GD === $capability ) {
$this->warn_once( 'Imagick unavailable — emitting resize-only variants without branding or caption.' );
$editor = new PRAutoBlogger_Image_Composer_Editor();
$variants = array_merge( $passthrough, $editor->compose_variants( $bytes, $roles, $this->layout() ) );
} else {
$this->warn_once( 'No usable image library — base image passed through unbranded.' );
$variants = $passthrough;
}
PRAutoBlogger_Logger::instance()->info(
sprintf(
'Composed %d variant(s) for post %d in %dms ($0, local, capability: %s).',
count( $variants ),
(int) ( $context['post_id'] ?? 0 ),
(int) round( ( microtime( true ) - $started ) * 1000 ),
$capability
),
'image_composer'
);
return $variants;
}
/**
* Full compositing rung. Each render is individually guarded: a featured
* failure degrades to pass-through, a variant failure skips that variant.
*
* @param string $bytes Base image bytes.
* @param string $caption Editorial caption for OG/square.
* @param array $roles Variant roles to render ('og', 'square').
* @param array $passthrough Pass-through featured variant (fallback).
* @return array<int, array<string, mixed>> Featured-first variant list.
*/
private function compose_via_imagick( string $bytes, string $caption, array $roles, array $passthrough ): array {
$variants = array();
if ( '1' === (string) get_option( self::OPTION_MARK_ENABLED, '1' ) ) {
$featured = $this->try_render( 'featured', $bytes, $caption );
$variants[] = null === $featured ? $passthrough : $featured;
} else {
$variants[] = $passthrough;
}
foreach ( $roles as $role ) {
$variant = $this->try_render( $role, $bytes, $caption );
if ( null !== $variant ) {
$variants[] = $variant;
}
}
return $variants;
}
/**
* Render one role via the Imagick renderer. Any throwable or malformed
* result (empty bytes) maps to one per-run WARNING + null (caller degrades).
* @param string $role 'featured', 'og', or 'square'.
* @param string $bytes Base image bytes.
* @param string $caption Editorial caption.
* @return array<string, mixed>|null Variant payload or null on failure.
*/
private function try_render( string $role, string $bytes, string $caption ): ?array {
try {
$renderer = $this->renderer();
if ( 'og' === $role ) {
$variant = $renderer->compose_og( $bytes, $caption );
} elseif ( 'square' === $role ) {
$variant = $renderer->compose_square( $bytes, $caption );
} else {
$variant = $renderer->compose_featured( $bytes );
}
if ( '' === (string) ( $variant['bytes'] ?? '' ) ) {
$this->warn_once( sprintf( 'Imagick render for %s variant returned no bytes — degrading.', $role ) );
return null;
}
$variant['role'] = $role;
return $variant;
} catch ( \Throwable $e ) {
$this->warn_once( sprintf( 'Imagick render failed for %s variant: %s', $role, $e->getMessage() ) );
return null;
}
}
/**
* Resolve the capability rung: cached probe + override filter. The
* same-named filter lets tests/ops force a rung (e.g. 'none').
*
* @return string One of the CAP_* constants.
*/
private function resolve_capability(): string {
$fingerprint = md5(
PHP_VERSION . '|' . ( extension_loaded( 'imagick' ) ? 'im1' : 'im0' ) . '|' . ( extension_loaded( 'gd' ) ? 'gd1' : 'gd0' )
);
$cached = get_option( self::OPTION_CAPABILITY, array() );
if ( is_array( $cached ) && ( $cached['fingerprint'] ?? '' ) === $fingerprint && isset( $cached['capability'] ) ) {
$capability = (string) $cached['capability'];
} else {
$capability = $this->probe_capability();
update_option(
self::OPTION_CAPABILITY,
array(
'fingerprint' => $fingerprint,
'capability' => $capability,
),
false
);
}
$capability = (string) apply_filters( 'prautoblogger_image_compose_capability', $capability );
return in_array( $capability, array( self::CAP_IMAGICK, self::CAP_GD, self::CAP_NONE ), true )
? $capability
: self::CAP_NONE;
}
/**
* Probe the host for the best available rung (uncached).
* @return string One of the CAP_* constants.
*/
private function probe_capability(): string {
if ( PRAutoBlogger_Image_Composer_Canvas::is_imagick_usable( $this->fonts_dir() . 'Poppins-Bold.ttf' ) ) {
return self::CAP_IMAGICK;
}
$png_crop = array(
'mime_type' => 'image/png',
'methods' => array( 'resize', 'crop' ),
);
if ( function_exists( 'wp_image_editor_supports' ) && wp_image_editor_supports( $png_crop ) ) {
return self::CAP_GD;
}
return self::CAP_NONE;
}
/**
* Lazily build the Imagick renderer with filtered layout + asset paths.
* @return PRAutoBlogger_Image_Composer_Imagick
*/
private function renderer(): PRAutoBlogger_Image_Composer_Imagick {
if ( null === $this->renderer ) {
$this->renderer = new PRAutoBlogger_Image_Composer_Imagick(
$this->layout(),
dirname( __DIR__, 2 ) . '/assets/brand/',
$this->fonts_dir()
);
}
return $this->renderer;
}
/**
* Layout geometry: pure defaults behind the documented override filter.
* @return array<string, array<string, mixed>>
*/
private function layout(): array {
return (array) apply_filters( 'prautoblogger_image_compose_layout', PRAutoBlogger_Image_Composer_Layout::defaults() );
}
/**
* Bundled font directory (path-derived, no constants — unit-test safe).
* @return string Absolute path with trailing slash.
*/
private function fonts_dir(): string {
return dirname( __DIR__, 2 ) . '/assets/fonts/';
}
/**
* Variant roles from settings, whitelisted at point of use.
* @return string[] Subset of ['og', 'square'], deduplicated, in config order.
*/
private function configured_variants(): array {
$raw = (string) get_option( self::OPTION_VARIANTS, 'og,square' );
$roles = array();
foreach ( explode( ',', $raw ) as $piece ) {
$piece = strtolower( trim( $piece ) );
if ( in_array( $piece, array( 'og', 'square' ), true ) && ! in_array( $piece, $roles, true ) ) {
$roles[] = $piece;
}
}
return $roles;
}
/**
* Build the pass-through featured variant from the provider result.
* @param array $image_data Provider result.
* @return array{bytes: string, mime_type: string, width: int, height: int, role: string}
*/
private function passthrough_variant( array $image_data ): array {
return array(
'bytes' => (string) ( $image_data['bytes'] ?? '' ),
'mime_type' => (string) ( $image_data['mime_type'] ?? 'image/png' ),
'width' => (int) ( $image_data['width'] ?? 0 ),
'height' => (int) ( $image_data['height'] ?? 0 ),
'role' => 'featured',
);
}
/**
* Log a degradation WARNING once per run (one row is enough for ops).
* @param string $message Warning text.
*/
private function warn_once( string $message ): void {
if ( self::$warned_this_run ) {
return;
}
self::$warned_this_run = true;
PRAutoBlogger_Logger::instance()->warning( $message, 'image_composer' );
}
/** Reset per-run state (unit tests only). */
public static function reset_run_state(): void {
self::$warned_this_run = false;
}
}

View File

@@ -36,13 +36,11 @@ class PRAutoBlogger_Image_Media_Sideloader {
* latency_ms: int,
* } $image_data Raw image bytes + metadata from PRAutoBlogger_Image_Provider_Interface.
* @param int $post_id Target post ID to attach the image to.
* @param string $alt_text Alt text for the image (the editorial caption).
* @param string $filename_suffix Optional role hint appended to the filename
* (e.g. 'og', 'square' for composed variants).
* @param string $alt_text Alt text for the image (from the generation prompt).
*
* @return int|\WP_Error Attachment ID on success, WP_Error on failure.
*/
public function sideload_image( array $image_data, int $post_id, string $alt_text = '', string $filename_suffix = '' ) {
public function sideload_image( array $image_data, int $post_id, string $alt_text = '' ) {
// WordPress media functions live in wp-admin/includes/ and are NOT
// loaded automatically in cron or REST contexts. Load them if missing.
// Why: WP-Cron runs as a frontend request, so admin-only files like
@@ -66,7 +64,7 @@ class PRAutoBlogger_Image_Media_Sideloader {
// Prepare file array for media_handle_sideload().
$file_array = array(
'name' => $this->generate_filename( $image_data['model'], $image_data['width'], $image_data['height'], $filename_suffix ),
'name' => $this->generate_filename( $image_data['model'], $image_data['width'], $image_data['height'] ),
'tmp_name' => $temp_file,
);
@@ -137,18 +135,16 @@ class PRAutoBlogger_Image_Media_Sideloader {
* @param string $model Model name (e.g., 'flux-1-schnell').
* @param int $width Image width.
* @param int $height Image height.
* @param string $suffix Optional role hint (e.g. 'og', 'square'); back-compat default ''.
*
* @return string Sanitized filename.
*/
private function generate_filename( string $model, int $width, int $height, string $suffix = '' ): string {
private function generate_filename( string $model, int $width, int $height ): string {
$base = sprintf(
'prautoblogger_%s_%dx%d_%s%s',
'prautoblogger_%s_%dx%d_%s',
sanitize_title( $model ),
$width,
$height,
gmdate( 'Y-m-d_H-i-s' ),
'' !== $suffix ? '_' . sanitize_title( $suffix ) : ''
gmdate( 'Y-m-d_H-i-s' )
);
return $base . '.png'; // Default to PNG — most image models output PNG.

View File

@@ -8,17 +8,13 @@ declare(strict_types=1);
*
* Generates two images per article (A/B): Image A (article-driven) as featured
* image, Image B (source-driven) in post meta. Each is independently fallible.
* Since v0.17.0 every result passes through the deterministic image composer
* (branded variants for A, corner mark for B) before sideloading; composition
* degrades gracefully and never blocks a publish.
*
* Triggered by: PRAutoBlogger_Pipeline_Runner after publisher creates the post.
* Dependencies: Image provider, Prompt builder, Composer, Attacher, Cost tracker, Logger.
* Dependencies: Image provider, Prompt builder, Sideloader, Cost tracker, Logger.
*
* @see core/class-pipeline-runner.php — Calls this after publisher.
* @see core/class-image-prompt-builder.php — Prompt generation (scene + caption).
* @see core/class-image-composer.php — Deterministic variant composition.
* @see core/class-image-attacher.php — Sideloading + variant meta-linking.
* @see core/class-image-media-sideloader.php — Media library integration.
*/
class PRAutoBlogger_Image_Pipeline {
@@ -38,36 +34,25 @@ class PRAutoBlogger_Image_Pipeline {
private PRAutoBlogger_Image_Media_Sideloader $sideloader;
/** @var PRAutoBlogger_Cost_Tracker Logs image generation spend. */
private PRAutoBlogger_Cost_Tracker $cost_tracker;
/** @var PRAutoBlogger_Image_Composer_Interface Composes branded variants pre-sideload. */
private PRAutoBlogger_Image_Composer_Interface $composer;
/** @var PRAutoBlogger_Image_Attacher Sideloads + meta-links results and variants. */
private PRAutoBlogger_Image_Attacher $attacher;
/** @var PRAutoBlogger_Opik_Trace_Context|null Optional tracing context. */
private ?PRAutoBlogger_Opik_Trace_Context $trace_context;
/**
* Construct with dependencies. When no provider is injected, the
* `prautoblogger_image_provider` setting picks the concrete class
* ('runware' or 'openrouter').
* Construct with dependencies.
*
* When no provider is injected, the constructor reads the
* `prautoblogger_image_provider` setting and instantiates the
* matching concrete class ('runware' or 'openrouter').
*
* @param PRAutoBlogger_Image_Provider_Interface|null $provider Optional provider override.
* @param PRAutoBlogger_Cost_Tracker|null $cost_tracker Optional cost tracker.
* @param PRAutoBlogger_Opik_Trace_Context|null $trace_context Optional tracing context.
* @param PRAutoBlogger_Image_Composer_Interface|null $composer Optional composer override.
*/
public function __construct(
?PRAutoBlogger_Image_Provider_Interface $provider = null,
?PRAutoBlogger_Cost_Tracker $cost_tracker = null,
?PRAutoBlogger_Opik_Trace_Context $trace_context = null,
?PRAutoBlogger_Image_Composer_Interface $composer = null
?PRAutoBlogger_Cost_Tracker $cost_tracker = null
) {
$this->provider = $provider ?? self::create_default_provider();
$this->prompt_builder = new PRAutoBlogger_Image_Prompt_Builder( $trace_context );
$this->prompt_builder = new PRAutoBlogger_Image_Prompt_Builder();
$this->sideloader = new PRAutoBlogger_Image_Media_Sideloader();
$this->cost_tracker = $cost_tracker ?? new PRAutoBlogger_Cost_Tracker();
$this->composer = $composer ?? new PRAutoBlogger_Image_Composer();
$this->attacher = new PRAutoBlogger_Image_Attacher( $this->sideloader, $this->cost_tracker );
$this->trace_context = $trace_context;
}
/**
@@ -125,16 +110,6 @@ class PRAutoBlogger_Image_Pipeline {
return $result;
}
// v0.18.0 — per-run governor: reserve the curl_multi batch's SUMMED
// worst-case estimate before dispatch (no-op outside a governed
// run). A breach halts the run and skips the whole batch.
try {
$batch_reservation = PRAutoBlogger_Cost_Governor::open_amount_reservation( $estimated_cost, 'image_batch' );
} catch ( PRAutoBlogger_Cost_Ceiling_Exception $e ) {
$result['errors'][] = $e->getMessage();
return $result;
}
// Build all prompts upfront (LLM calls happen here, sequentially).
$article_prompt = $this->prompt_builder->build_article_prompt( $article_data );
$batch_requests = array(
@@ -161,33 +136,23 @@ class PRAutoBlogger_Image_Pipeline {
try {
$batch_results = $this->provider->generate_image_batch( $batch_requests );
} catch ( \Throwable $e ) {
PRAutoBlogger_Cost_Governor::release( $batch_reservation );
PRAutoBlogger_Logger::instance()->error( 'Batch generation failed: ' . $e->getMessage(), 'image_pipeline' );
$result['errors'][] = $e->getMessage();
return $result;
}
// Settle the batch reservation to the actual per-image costs.
$actual_batch_cost = 0.0;
foreach ( $batch_results as $batch_entry ) {
$actual_batch_cost += (float) ( $batch_entry['cost_usd'] ?? 0 );
}
PRAutoBlogger_Cost_Governor::settle( $batch_reservation, $actual_batch_cost );
// Single-shot retry for any slot the provider flagged as NSFW-blocked.
if ( PRAutoBlogger_Image_NSFW_Retry::is_enabled() ) {
( new PRAutoBlogger_Image_NSFW_Retry( $this->provider, $this->prompt_builder ) )
->retry_blocked_slots( $post_id, $batch_requests, $batch_results, $captions, $article_data, $source_data );
}
$title = (string) ( $article_data['post_title'] ?? $article_data['suggested_title'] ?? '' );
// Process Image A result.
$this->process_slot( 'image_a', $post_id, $batch_results, $captions, $title, $result );
$this->process_image_a( $post_id, $batch_results, $captions, $result );
// Process Image B result (if requested).
if ( isset( $batch_results['image_b'] ) ) {
$this->process_slot( 'image_b', $post_id, $batch_results, $captions, $title, $result );
$this->process_image_b( $post_id, $batch_results, $captions, $result );
} elseif ( null === $source_data || empty( $source_data ) ) {
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Image B skipped for post %d: no source data.', $post_id ),
@@ -199,98 +164,142 @@ class PRAutoBlogger_Image_Pipeline {
}
/**
* Process one slot's batch result: compose, sideload, link to the post.
* Process Image A batch result: sideload, set featured image, insert caption.
*
* Image A becomes the featured image (role meta, caption prepend, and
* composed OG/square variants meta-linked); Image B is stored in post
* meta with a corner mark only. Alt text is the editorial caption
* (v0.17.0 fix — the model name used to leak here).
*
* @param string $slot 'image_a' or 'image_b'.
* @param int $post_id Post ID.
* @param array $batch_results Keyed results from generate_image_batch().
* @param array $captions Keyed captions from prompt builder.
* @param string $title Post title (composer context).
* @param array $result Pipeline result array (modified by reference).
* @param int $post_id Post ID.
* @param array $batch_results Keyed results from generate_image_batch().
* @param array $captions Keyed captions from prompt builder.
* @param array $result Pipeline result array (modified by reference).
*/
private function process_slot( string $slot, int $post_id, array $batch_results, array $captions, string $title, array &$result ): void {
$label = 'image_a' === $slot ? 'Image A' : 'Image B';
$image_data = $batch_results[ $slot ] ?? null;
private function process_image_a( int $post_id, array $batch_results, array $captions, array &$result ): void {
$image_data = $batch_results['image_a'] ?? null;
if ( ! $image_data || isset( $image_data['error'] ) ) {
$err_msg = $image_data['error'] ?? sprintf( '%s missing from batch results.', $label );
$err_msg = $image_data['error'] ?? 'Image A missing from batch results.';
$result['errors'][] = $err_msg;
// Log at WARNING so the path is visible even if the outer catch in the
// caller doesn't fire. See thread image-mime-bug Issue 2.
PRAutoBlogger_Logger::instance()->warning(
sprintf( '%s generation failed for post %d: %s', $label, $post_id, $err_msg ),
sprintf( 'Image A generation failed for post %d: %s', $post_id, $err_msg ),
'image_pipeline'
);
return;
}
$caption = (string) ( $captions[ $slot ] ?? '' );
$variants = $this->compose_variants( $image_data, $post_id, $caption, $title, $slot );
$featured = array_merge( $image_data, array_shift( $variants ) );
$attachment_id = $this->attacher->sideload_and_log( $featured, $post_id, $slot, $label, $caption );
$attachment_id = $this->sideload_and_log( $image_data, $post_id, 'image_a', 'Image A' );
if ( is_wp_error( $attachment_id ) ) {
$result['errors'][] = $attachment_id->get_error_message();
return;
}
$result[ $slot . '_id' ] = $attachment_id;
$result['cost_usd'] += $image_data['cost_usd'];
$result['image_a_id'] = $attachment_id;
$result['cost_usd'] += $image_data['cost_usd'];
set_post_thumbnail( $post_id, $attachment_id );
if ( '' !== $caption ) {
update_post_meta( $attachment_id, '_prautoblogger_image_caption', $caption );
}
if ( 'image_a' === $slot ) {
set_post_thumbnail( $post_id, $attachment_id );
update_post_meta( $attachment_id, '_prautoblogger_image_role', 'featured' );
if ( '' !== $caption ) {
$this->attacher->prepend_caption_to_post( $post_id, $attachment_id, $caption );
}
$this->attacher->attach_variants( $variants, $post_id, $attachment_id, $caption, (string) ( $image_data['model'] ?? 'unknown' ) );
} else {
update_post_meta( $post_id, '_prautoblogger_image_b_id', $attachment_id );
if ( '' !== ( $captions['image_a'] ?? '' ) ) {
update_post_meta( $attachment_id, '_prautoblogger_image_caption', $captions['image_a'] );
$this->prepend_caption_to_post( $post_id, $attachment_id, $captions['image_a'] );
}
}
/**
* Run the composer with a hard safety net: any failure (composer bugs
* included — its own internals already degrade) falls back to passing
* the base image through, so composition can never fail a publish.
* Process Image B batch result: sideload, store meta.
*
* @param array $image_data Provider result for one slot.
* @param int $post_id Post ID (composer context).
* @param string $caption Editorial caption (composer context).
* @param string $title Post title (composer context).
* @param string $slot 'image_a' or 'image_b'.
* @return array<int, array<string, mixed>> Featured-first variant list (never empty).
* @param int $post_id Post ID.
* @param array $batch_results Keyed results from generate_image_batch().
* @param array $captions Keyed captions from prompt builder.
* @param array $result Pipeline result array (modified by reference).
*/
private function compose_variants( array $image_data, int $post_id, string $caption, string $title, string $slot ): array {
try {
$variants = $this->composer->compose(
$image_data,
array(
'post_id' => $post_id,
'caption' => $caption,
'title' => $title,
'slot' => $slot,
)
);
if ( ! empty( $variants ) ) {
return $variants;
}
} catch ( \Throwable $e ) {
private function process_image_b( int $post_id, array $batch_results, array $captions, array &$result ): void {
$image_data = $batch_results['image_b'] ?? null;
if ( ! $image_data || isset( $image_data['error'] ) ) {
$err_msg = $image_data['error'] ?? 'Image B missing from batch results.';
$result['errors'][] = $err_msg;
// Log at WARNING so the path is visible even if the outer catch in the
// caller doesn't fire. See thread image-mime-bug Issue 2.
PRAutoBlogger_Logger::instance()->warning(
'Image composition failed, publishing original image: ' . $e->getMessage(),
'image_composer'
sprintf( 'Image B generation failed for post %d: %s', $post_id, $err_msg ),
'image_pipeline'
);
return;
}
return array( array_merge( $image_data, array( 'role' => 'featured' ) ) );
$attachment_id = $this->sideload_and_log( $image_data, $post_id, 'image_b', 'Image B' );
if ( is_wp_error( $attachment_id ) ) {
$result['errors'][] = $attachment_id->get_error_message();
return;
}
$result['image_b_id'] = $attachment_id;
$result['cost_usd'] += $image_data['cost_usd'];
update_post_meta( $post_id, '_prautoblogger_image_b_id', $attachment_id );
if ( '' !== ( $captions['image_b'] ?? '' ) ) {
update_post_meta( $attachment_id, '_prautoblogger_image_caption', $captions['image_b'] );
}
}
/**
* Sideload image bytes into the media library and log the cost.
*
* @param array $image_data Provider result with bytes, model, cost_usd.
* @param int $post_id Post ID.
* @param string $slot Cost-tracking slot ('image_a' or 'image_b').
* @param string $label Human-readable label for logs.
* @return int|\WP_Error Attachment ID on success.
*/
private function sideload_and_log( array $image_data, int $post_id, string $slot, string $label ) {
$attachment_id = $this->sideloader->sideload_image(
$image_data,
$post_id,
substr( $image_data['model'] ?? 'image', 0, 100 )
);
if ( is_wp_error( $attachment_id ) ) {
return $attachment_id;
}
$this->cost_tracker->log_image_generation(
$image_data['cost_usd'],
$image_data['model'] ?? 'unknown',
$post_id,
$slot
);
PRAutoBlogger_Logger::instance()->info(
sprintf( '%s for post %d (att %d, $%.4f)', $label, $post_id, $attachment_id, $image_data['cost_usd'] ),
'image_pipeline'
);
return $attachment_id;
}
/**
* Prepend the comic caption as styled text at the top of the post content.
*
* Only inserts the caption — NOT the image. The theme already displays the
* featured image, so embedding it again would cause a duplicate.
*
* @param int $post_id Post ID.
* @param int $attachment_id Featured image attachment ID (for meta storage only).
* @param string $caption Caption text (the comic punchline).
*/
private function prepend_caption_to_post( int $post_id, int $attachment_id, string $caption ): void {
$post = get_post( $post_id );
if ( ! $post ) {
return;
}
// Caption-only block — the theme handles the featured image display.
$caption_html = sprintf(
'<p class="prautoblogger-comic-caption" style="text-align:center;font-style:italic;color:#555;font-size:1.1em;margin:0 0 2em 0;">— "%s"</p>',
esc_html( $caption )
);
wp_update_post(
array(
'ID' => $post_id,
'post_content' => $caption_html . "\n\n" . $post->post_content,
)
);
}
}

View File

@@ -6,16 +6,13 @@ declare(strict_types=1);
*
* Builds image prompts from article content or source data.
*
* Uses a cheap LLM (via OpenRouter) to distill article content into a concise
* 1-2 sentence editorial topic/mechanism summary, then substitutes that summary
* into the admin-editable editorial style template (the {{ topic_summary }}
* slot) to produce a text-free image-gen prompt. Falls back to rule-based
* Uses a cheap LLM (via OpenRouter) to distill article content into concise
* visual scene descriptions optimised for image generation. Falls back to rule-based
* synthesis if the LLM call fails, so image generation never blocks on a
* prompt-rewriting outage.
*
* Triggered by: PRAutoBlogger_Image_Pipeline during content generation run.
* Dependencies: PRAutoBlogger_OpenRouter_Provider (LLM call),
* PRAutoBlogger_Image_Template_Filler (template substitution),
* PRAutoBlogger_Cost_Tracker (logs prompt-rewrite cost),
* PRAutoBlogger_Logger (diagnostics).
*
@@ -30,39 +27,34 @@ class PRAutoBlogger_Image_Prompt_Builder {
* prompts. Exposed as a `public const` so the admin-settings layer can
* use it as the default value for `prautoblogger_image_prompt_instructions`.
* The option, when non-empty, wins at call time (see rewrite_via_llm).
*
* Editorial pivot (v0.16.0): the model emits a concise topic/mechanism
* summary as the SCENE — concrete, single centered focal subject, no text,
* no people-as-gag, no logos — which the prompt builder substitutes into
* the editorial style template's {{ topic_summary }} slot. The CAPTION line
* is preserved unchanged for the existing HTML-caption-below-image path.
*/
public const REWRITER_SYSTEM_PROMPT = <<<'PROMPT'
You write subject descriptions for a text-free editorial science illustration about peptides, supplements, or biohacking.
You are a comedy writer and single-panel cartoon creator, like Gary Larson (The Far Side) meets science humor.
Given an article title and summary, output TWO parts separated by a blank line:
Given an article title and summary about peptides, supplements, or biohacking, create a SINGLE-PANEL COMIC concept. Output TWO parts separated by a blank line:
SCENE: A concise 1-2 sentence description of the article's core topic or mechanism, written as the SUBJECT of a single editorial illustration. Name ONE concrete, centered focal subject and the few supporting visual elements around it (e.g. a labelled-free vial and dropper, a stylised receptor on a cell membrane, a molecular chain, a dosing syringe, an organ cross-section). Favor a clear central focal point with margin around it so the image crops well. This is image-gen direction, not prose.
SCENE: One sentence describing the visual gag — a funny, absurd, or ironic situation related to the article's topic. Favor CONCRETE, HUMAN-SCALE scenes: people reacting to things, doctors and patients, scientists in a lab, gym bros with peptide vials, partners at a kitchen table, ordinary objects in ordinary rooms. Keep it simple — one clear visual joke, 1-3 characters max.
CAPTION: A short, informative caption line (under 15 words) for display as HTML text below the image. Plain and editorial, not a joke.
CAPTION: A short, punchy caption or speech bubble line (under 15 words) that delivers the punchline. The humor should be dry, nerdy, and accessible — the reader should chuckle even if they only half-understand the science.
Rules:
- The SCENE must depict the article's actual subject/mechanism, not a generic science scene.
- NO text, words, captions, speech bubbles, labels, or logos described in the SCENE — the illustration is text-free; text is rendered separately.
- NO people used as a visual gag and NO cartoon/comic framing. A human anatomical element (a cell, an organ, a hand holding a vial) is fine if it is the legitimate subject.
- Do NOT personify molecules, peptides, hormones, or proteins (no "smiling molecule"); depict them as clean stylised diagrams or structures.
- Keep the staging simple with one clear focal subject, readable at small sizes.
- The joke MUST relate to the article's actual subject matter, not generic science humor
- DO NOT personify molecules, peptides, hormones, proteins, or other chemical structures (no "anthropomorphic molecule", no "cartoon hormone"). Image models render anthropomorphized chemistry as incoherent blobs. If the article is about a substance, show a PERSON reacting to or using the substance; if the article is abstract (a mechanism, a process, a concept), fall back on a human observer reacting to its effect.
- Characters can have simple cartoon faces (round heads, dot eyes, expressive eyebrows)
- Keep the scene physically simple — few objects, clear staging, easy to read at thumbnail size
- The caption should work as a standalone joke even without the image
- No logos, watermarks, or branding
- Output ONLY the scene and caption. No preamble, no explanation.
Example output format:
A single glass peptide vial on a clean surface with a fine dropper above it, a faint stylised molecular chain arcing behind as a backdrop, centered with generous negative space.
A muscular gym bro stares, deflated, at a tiny glass vial in his hand while his friend squats a barbell effortlessly in the background.
A concentrated look at how the compound is prepared before use.
"They told me the peptide did the work, not the squats."
PROMPT;
/**
* Max tokens for the rewriter response. Enough room for the 1-2 sentence
* topic/mechanism summary plus the short editorial caption line.
* Max tokens for the rewriter response. Comic concepts need more room
* for the scene description plus the caption punchline.
*/
private const REWRITER_MAX_TOKENS = 180;
@@ -73,29 +65,12 @@ PROMPT;
*/
private ?PRAutoBlogger_OpenRouter_Provider $llm = null;
/**
* Opik trace context for instrumentation.
*
* @var PRAutoBlogger_Opik_Trace_Context|null
*/
private ?PRAutoBlogger_Opik_Trace_Context $trace_context = null;
/**
* Constructor.
*
* @param PRAutoBlogger_Opik_Trace_Context|null $trace_context Optional trace context for instrumentation.
*/
public function __construct( ?PRAutoBlogger_Opik_Trace_Context $trace_context = null ) {
$this->trace_context = $trace_context;
}
/**
* Build a visual prompt from finished article content.
*
* Tries LLM rewriting first; falls back to rule-based synthesis on
* failure. Splits scene (the topic summary, for image gen) from caption
* (HTML below the image) and substitutes the scene into the editorial
* style template's {{ topic_summary }} slot.
* failure. Splits scene (for image gen) from caption (HTML below the
* image) and appends the style suffix.
*
* @param array{post_title?: string, post_content?: string, suggested_title?: string} $article_data
* @return array{prompt: string, caption: string}
@@ -103,12 +78,14 @@ PROMPT;
public function build_article_prompt( array $article_data ): array {
$title = $article_data['post_title'] ?? $article_data['suggested_title'] ?? 'Product';
$content = $article_data['post_content'] ?? '';
$first_para = PRAutoBlogger_Image_Scene_Parser::extract_first_paragraph( $content );
$first_para = $this->extract_first_paragraph( $content );
$parsed = $this->rewrite_via_llm( $title, $first_para );
$style_suffix = $this->get_style_suffix();
return array(
'prompt' => PRAutoBlogger_Image_Template_Filler::fill( $parsed['scene'] ),
'prompt' => trim( $parsed['scene'] . ' ' . $style_suffix ),
'caption' => $parsed['caption'],
);
}
@@ -127,8 +104,10 @@ PROMPT;
$parsed = $this->rewrite_via_llm( $title, $context );
$style_suffix = $this->get_style_suffix();
return array(
'prompt' => PRAutoBlogger_Image_Template_Filler::fill( $parsed['scene'] ),
'prompt' => trim( $parsed['scene'] . ' ' . $style_suffix ),
'caption' => $parsed['caption'],
);
}
@@ -163,24 +142,7 @@ PROMPT;
$user_message .= "\n\nSummary: {$context}";
}
$span_id = null;
try {
if ( null !== $this->trace_context ) {
$span_id = $this->trace_context->start_span(
array(
'name' => 'image_prompt_rewrite',
'type' => 'llm',
'model' => get_option( 'prautoblogger_analysis_model', PRAUTOBLOGGER_DEFAULT_ANALYSIS_MODEL ),
'provider' => 'openrouter',
'input' => array(
'title' => $title,
'context' => substr( $context, 0, 200 ),
),
)
);
}
$llm = $this->get_llm_provider();
$model = get_option( 'prautoblogger_analysis_model', PRAUTOBLOGGER_DEFAULT_ANALYSIS_MODEL );
$system = $this->resolve_system_prompt();
@@ -200,7 +162,6 @@ PROMPT;
array(
'temperature' => 0.7,
'max_tokens' => self::REWRITER_MAX_TOKENS,
'stage' => 'image_prompt_rewrite',
)
);
@@ -227,24 +188,8 @@ PROMPT;
'image_prompt_builder'
);
if ( null !== $span_id && null !== $this->trace_context ) {
$this->trace_context->end_span(
$span_id,
array(
'output' => array(
'raw_response' => substr( $raw, 0, 200 ),
),
'usage' => array(
'prompt_tokens' => $result['prompt_tokens'] ?? 0,
'completion_tokens' => $result['completion_tokens'] ?? 0,
'total_tokens' => ( $result['prompt_tokens'] ?? 0 ) + ( $result['completion_tokens'] ?? 0 ),
),
)
);
}
if ( '' !== $raw ) {
return PRAutoBlogger_Image_Scene_Parser::parse_scene_and_caption( $raw );
return $this->parse_scene_and_caption( $raw );
}
} catch ( \Throwable $e ) {
// LLM failure is not fatal — fall back to rule-based synthesis.
@@ -254,7 +199,64 @@ PROMPT;
);
}
return PRAutoBlogger_Image_Scene_Parser::synthesize_visual_concepts_fallback( $title, $context );
return $this->synthesize_visual_concepts_fallback( $title, $context );
}
/**
* Parse the LLM response into separate scene and caption parts.
*
* Expected format from the LLM:
* Scene description text here.
*
* "Caption punchline here."
*
* Falls back gracefully: if no blank-line separator is found, the entire
* response becomes the scene with an empty caption.
*
* @param string $raw Raw LLM response text.
* @return array{scene: string, caption: string}
*/
private function parse_scene_and_caption( string $raw ): array {
// Split on blank line (the format the system prompt requests).
$parts = preg_split( '/\n\s*\n/', $raw, 2 );
if ( count( $parts ) >= 2 ) {
$scene = trim( $parts[0] );
$caption = trim( $parts[1] );
// Strip surrounding quotes from caption — the LLM wraps it in quotes.
$caption = trim( $caption, '"\'' );
return array(
'scene' => $scene,
'caption' => $caption,
);
}
// No blank-line separator found — treat entire response as scene.
return array(
'scene' => trim( $raw ),
'caption' => '',
);
}
/**
* Extract the first paragraph from HTML content.
*
* Removes all tags and captures the text up to the first double-newline
* or 200 characters, whichever comes first.
*
* @param string $html HTML content.
* @return string Plain text of the first paragraph.
*/
private function extract_first_paragraph( string $html ): string {
$text = wp_strip_all_tags( $html );
$paras = preg_split( '/\n\n+/', $text );
$para = isset( $paras[0] ) ? trim( $paras[0] ) : '';
if ( strlen( $para ) > 200 ) {
$para = substr( $para, 0, 200 ) . '...';
}
return $para;
}
/**
@@ -266,13 +268,36 @@ PROMPT;
* @return array{prompt: string, caption: string}
*/
public function build_fallback_prompt( string $title ): array {
$parsed = PRAutoBlogger_Image_Scene_Parser::synthesize_visual_concepts_fallback( $title, '' );
$parsed = $this->synthesize_visual_concepts_fallback( $title, '' );
$style_suffix = $this->get_style_suffix();
return array(
'prompt' => PRAutoBlogger_Image_Template_Filler::fill( $parsed['scene'] ),
'prompt' => trim( $parsed['scene'] . ' ' . $style_suffix ),
'caption' => $parsed['caption'],
);
}
/**
* Rule-based fallback when LLM rewriting is unavailable.
*
* Kept deliberately simple — this only runs if OpenRouter is down.
*
* @param string $title Main heading / topic.
* @param string $supporting_text Additional context.
* @return array{scene: string, caption: string} Scene for image gen, caption for HTML.
*/
private function synthesize_visual_concepts_fallback( string $title, string $supporting_text ): array {
// Fallback produces a simple comic concept when the LLM is unavailable.
$scene = sprintf(
'A cartoon scientist in a lab coat looking bewildered while examining something related to: %s.',
$title
);
return array(
'scene' => trim( $scene ),
'caption' => 'Science is full of surprises.',
);
}
/** Lazy-load the OpenRouter provider. */
private function get_llm_provider(): PRAutoBlogger_OpenRouter_Provider {
if ( null === $this->llm ) {
@@ -286,4 +311,20 @@ PROMPT;
$override = (string) get_option( 'prautoblogger_image_prompt_instructions', '' );
return '' !== trim( $override ) ? $override : self::REWRITER_SYSTEM_PROMPT;
}
/**
* Get image style suffix with empty-string safeguard.
*
* Treats both absent and empty string as "use default" to prevent
* silent style loss if the admin settings field is saved empty.
*
* @return string The style suffix with safe fallback.
*/
private function get_style_suffix(): string {
$style_suffix = (string) get_option( 'prautoblogger_image_style_suffix', '' );
if ( '' === trim( $style_suffix ) ) {
$style_suffix = PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX;
}
return $style_suffix;
}
}

View File

@@ -1,94 +0,0 @@
<?php
declare(strict_types=1);
/**
* Parses LLM output into scene/caption pairs and synthesises fallback prompts
* from article titles when the LLM call fails.
*
* Who calls it: PRAutoBlogger_Image_Prompt_Builder (static calls).
* Dependencies: None.
*/
class PRAutoBlogger_Image_Scene_Parser {
/**
* Parse the LLM response into separate scene and caption parts.
*
* Expected format from the LLM:
* Scene description text here.
*
* "Caption punchline here."
*
* Falls back gracefully: if no blank-line separator is found, the entire
* response becomes the scene with an empty caption.
*
* @param string $raw Raw LLM response text.
* @return array{scene: string, caption: string}
*/
public static function parse_scene_and_caption( string $raw ): array {
// Split on blank line (the format the system prompt requests).
$parts = preg_split( '/\n\s*\n/', $raw, 2 );
if ( count( $parts ) >= 2 ) {
$scene = trim( $parts[0] );
$caption = trim( $parts[1] );
// Strip surrounding quotes from caption — the LLM wraps it in quotes.
$caption = trim( $caption, '"\'' );
return array(
'scene' => $scene,
'caption' => $caption,
);
}
// No blank-line separator found — treat entire response as scene.
return array(
'scene' => trim( $raw ),
'caption' => '',
);
}
/**
* Extract the first paragraph from HTML content.
*
* Removes all tags and captures the text up to the first double-newline
* or 200 characters, whichever comes first.
*
* @param string $html HTML content.
* @return string Plain text of the first paragraph.
*/
public static function extract_first_paragraph( string $html ): string {
$text = wp_strip_all_tags( $html );
$paras = preg_split( '/\n\n+/', $text );
$para = isset( $paras[0] ) ? trim( $paras[0] ) : '';
if ( strlen( $para ) > 200 ) {
$para = substr( $para, 0, 200 ) . '...';
}
return $para;
}
/**
* Rule-based fallback when LLM rewriting is unavailable.
*
* Kept deliberately simple — this only runs if OpenRouter is down. Produces
* a text-free editorial-illustration subject (not a comic) so the prompt
* builder always has a non-empty topic summary to substitute into the
* style template, never shipping a blank prompt to the provider (brief A6).
*
* @param string $title Main heading / topic.
* @param string $supporting_text Additional context.
* @return array{scene: string, caption: string} Scene for image gen, caption for HTML.
*/
public static function synthesize_visual_concepts_fallback( string $title, string $supporting_text ): array {
// Fallback produces a simple editorial-illustration subject when the LLM is unavailable.
$scene = sprintf(
'A clean, centered editorial science illustration representing the topic of %s, with a single clear focal subject and generous negative space.',
$title
);
return array(
'scene' => trim( $scene ),
'caption' => '',
);
}
}

View File

@@ -1,185 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Fills the admin-editable editorial image-prompt template with the
* rewriter-produced topic summary, replacing the old "scene + style suffix"
* concatenation.
*
* The template (option `prautoblogger_image_style_template`, default
* PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE) contains exactly one
* `{{ topic_summary }}` token. This class:
* - resolves the active template (admin override wins; blank → default),
* - sanitises and length-clamps the topic summary (brief A5),
* - substitutes the token, and
* - degrades safely (brief A5/A6) so a blank or token-only prompt is never
* emitted to the image provider.
*
* Who calls it: PRAutoBlogger_Image_Prompt_Builder (static call from each of
* build_article_prompt / build_source_prompt / build_fallback_prompt).
* Dependencies: PRAutoBlogger_Logger (diagnostics only).
*
* @see core/class-image-prompt-builder.php — Sole caller.
* @see ARCHITECTURE.md — Image generation data flow.
*/
class PRAutoBlogger_Image_Template_Filler {
/** The single substitution token the template must contain. */
public const TOKEN = '{{ topic_summary }}';
/**
* Max characters retained from the rewriter topic summary before it is
* substituted into the template. Keeps the final provider prompt bounded
* even if the rewriter ignores its length guidance.
*/
public const MAX_SUMMARY_CHARS = 320;
/**
* Build the final image-generation prompt from a rewriter scene.
*
* @param string $scene Raw topic/mechanism summary from the rewriter (the
* "scene" half of the scene/caption contract).
* @return string Provider-ready prompt; never empty.
*/
public static function fill( string $scene ): string {
$template = self::resolve_template();
$summary = self::sanitize_summary( $scene );
// Brief A6: never ship a blank or token-only prompt. If the rewriter
// produced nothing usable, return the template with the token removed
// only as a last resort — but the caller guards this by passing a
// rule-based fallback scene, so an empty summary here is unexpected.
if ( '' === $summary ) {
PRAutoBlogger_Logger::instance()->warning(
'Editorial prompt fill received an empty topic summary; emitting style-only prompt.',
'image_template_filler'
);
return self::strip_token( $template );
}
$token_count = substr_count( $template, self::TOKEN );
if ( 1 === $token_count ) {
return trim( str_replace( self::TOKEN, $summary, $template ) );
}
// Brief A5: admin removed or duplicated the token. Fall back to
// appending the summary to the style text and log a warning rather
// than shipping a malformed prompt.
PRAutoBlogger_Logger::instance()->warning(
sprintf(
'Image style template has %d "%s" tokens (expected 1); appending summary instead of substituting.',
$token_count,
self::TOKEN
),
'image_template_filler'
);
$base = self::strip_token( $template );
return trim( $base . ' ' . $summary );
}
/**
* Sanitise and validate the admin-submitted style template on save.
*
* Multi-line, so sanitised with sanitize_textarea_field() (not
* sanitize_text_field(), which would strip newlines). Per brief A5 the
* template must contain exactly one TOKEN; otherwise the previous value is
* kept and a settings error is surfaced. A blank submission falls back to
* the editorial default so image generation can never be bricked.
*
* @param string $value Submitted template.
* @return string Sanitised, validated template.
*/
public static function sanitize_for_save( string $value ): string {
$clean = sanitize_textarea_field( $value );
if ( '' === trim( $clean ) ) {
return PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE;
}
$token_count = substr_count( $clean, self::TOKEN );
if ( 1 !== $token_count ) {
add_settings_error(
'prautoblogger_image_style_template',
'prautoblogger_image_style_template_token',
sprintf(
/* translators: 1: required token, 2: number of tokens found. */
esc_html__( 'The Style Template must contain exactly one %1$s token (found %2$d). Keeping the previous value.', 'prautoblogger' ),
esc_html( self::TOKEN ),
(int) $token_count
)
);
return (string) get_option( 'prautoblogger_image_style_template', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE );
}
return $clean;
}
/**
* Resolve the active template: admin override wins; blank → default.
*
* @return string Non-empty template string.
*/
private static function resolve_template(): string {
$override = (string) get_option( 'prautoblogger_image_style_template', '' );
if ( '' !== trim( $override ) ) {
return $override;
}
return PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE;
}
/**
* Strip control characters and clamp length of the rewriter summary
* (brief A5). Whitespace runs (including newlines) are collapsed to single
* spaces so the summary sits cleanly inside the template.
*
* @param string $scene Raw rewriter scene.
* @return string Sanitised, length-clamped summary (possibly empty).
*/
private static function sanitize_summary( string $scene ): string {
// Remove control characters (C0/C1) except via whitespace collapse below.
$clean = preg_replace( '/[\x00-\x1F\x7F]+/u', ' ', $scene );
if ( null === $clean ) {
// preg_replace can return null on bad UTF-8; degrade conservatively.
$clean = preg_replace( '/[\x00-\x1F\x7F]+/', ' ', $scene );
$clean = is_string( $clean ) ? $clean : '';
}
// Collapse whitespace runs to single spaces.
$collapsed = preg_replace( '/\s+/u', ' ', $clean );
$clean = is_string( $collapsed ) ? $collapsed : $clean;
$clean = trim( $clean );
if ( '' === $clean ) {
return '';
}
// Clamp length (multibyte-aware where available).
if ( function_exists( 'mb_strlen' ) ) {
if ( mb_strlen( $clean ) > self::MAX_SUMMARY_CHARS ) {
$clean = rtrim( mb_substr( $clean, 0, self::MAX_SUMMARY_CHARS ) ) . '...';
}
} elseif ( strlen( $clean ) > self::MAX_SUMMARY_CHARS ) {
$clean = rtrim( substr( $clean, 0, self::MAX_SUMMARY_CHARS ) ) . '...';
}
return $clean;
}
/**
* Remove every occurrence of the token from a template, tidying the
* leftover whitespace so the residual style text is still well-formed.
*
* @param string $template Template possibly containing the token.
* @return string Token-free, trimmed template.
*/
private static function strip_token( string $template ): string {
$stripped = str_replace( self::TOKEN, '', $template );
$stripped = preg_replace( '/[ \t]+/', ' ', $stripped );
$stripped = is_string( $stripped ) ? $stripped : $template;
return trim( $stripped );
}
}

98
includes/core/class-pipeline-runner.php Normal file → Executable file
View File

@@ -65,7 +65,6 @@ class PRAutoBlogger_Pipeline_Runner {
$ideas = $this->orchestrate( $cost_tracker );
if ( empty( $ideas ) ) {
PRAutoBlogger_Run_State::mark_status( (string) $cost_tracker->get_run_id(), 'done' );
return array(
'generated' => 0,
'published' => 0,
@@ -85,8 +84,7 @@ class PRAutoBlogger_Pipeline_Runner {
} else {
// Single-article run — amortize research costs now (1 article = full cost).
PRAutoBlogger_Post_Assembler::amortize_research_costs( $cost_tracker->get_run_id() );
PRAutoBlogger_Pipeline_Status::log_summary( $result );
PRAutoBlogger_Run_State::mark_status( (string) $cost_tracker->get_run_id(), 'done' );
$this->log_summary( $result );
}
return $result;
@@ -117,19 +115,6 @@ class PRAutoBlogger_Pipeline_Runner {
'Budget limit reached. Aborting remaining queued articles.',
'pipeline'
);
PRAutoBlogger_Run_State::mark_status( (string) $queue['run_id'], 'failed' );
$this->finish_queue();
return;
}
// v0.18.0 — a run halted by the per-run cost governor (or failed by
// the reaper) must not dispatch its remaining queued articles.
$run_status = PRAutoBlogger_Run_State::get_status( $queue['run_id'] );
if ( in_array( $run_status, array( 'halted', 'failed' ), true ) ) {
PRAutoBlogger_Logger::instance()->warning(
sprintf( 'Run %s is %s. Aborting remaining queued articles.', $queue['run_id'], $run_status ),
'pipeline'
);
$this->finish_queue();
return;
}
@@ -155,16 +140,15 @@ class PRAutoBlogger_Pipeline_Runner {
if ( ! empty( $queue['ideas'] ) ) {
update_option( self::QUEUE_KEY, $queue, false );
PRAutoBlogger_Pipeline_Status::update_queue_progress( $queue );
$this->update_queue_status( $queue );
$this->schedule_next();
} else {
// All articles done — amortize shared research costs across them.
PRAutoBlogger_Post_Assembler::amortize_research_costs( $queue['run_id'] );
PRAutoBlogger_Pipeline_Status::write_final( $queue['results'] );
$this->write_final_status( $queue['results'] );
delete_option( self::QUEUE_KEY );
PRAutoBlogger_Generation_Lock::release();
PRAutoBlogger_Pipeline_Status::log_summary( $queue['results'] );
PRAutoBlogger_Run_State::mark_status( (string) $queue['run_id'], 'done' );
$this->log_summary( $queue['results'] );
}
}
@@ -179,26 +163,20 @@ class PRAutoBlogger_Pipeline_Runner {
private function orchestrate( PRAutoBlogger_Cost_Tracker $cost_tracker ): array {
$target = absint( get_option( 'prautoblogger_daily_article_target', 1 ) );
$run_id = (string) $cost_tracker->get_run_id();
$enabled = json_decode( get_option( 'prautoblogger_enabled_sources', '["reddit"]' ), true );
$source_labels = is_array( $enabled ) ? implode( ', ', $enabled ) : 'reddit';
/* 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_Run_Stage_State::start( $run_id, 'research', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'research' ) );
$this->broadcast_stage( sprintf( __( 'Collecting sources from %s…', 'prautoblogger' ), $source_labels ) );
( new PRAutoBlogger_Source_Collector() )
->set_cost_tracker( $cost_tracker )
->collect_from_all_sources();
PRAutoBlogger_Run_Stage_State::done( $run_id, 'research' );
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Analyzing topics and scoring…', 'prautoblogger' ) );
PRAutoBlogger_Run_Stage_State::start( $run_id, 'analysis', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'analysis' ) );
$this->broadcast_stage( __( 'Analyzing topics and scoring…', 'prautoblogger' ) );
$llm = new PRAutoBlogger_OpenRouter_Provider();
$analyzer = new PRAutoBlogger_Content_Analyzer( $llm, $cost_tracker );
$analysis = $analyzer->analyze_recent_data( max( $target * 2, 6 ) );
PRAutoBlogger_Run_Stage_State::done( $run_id, 'analysis' );
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Selecting best topic…', 'prautoblogger' ) );
$this->broadcast_stage( __( 'Selecting best topic…', 'prautoblogger' ) );
$scorer = new PRAutoBlogger_Idea_Scorer();
$scorer->set_skip_dedup( $this->skip_dedup );
$ideas = $scorer->score_and_rank( $analysis, $target );
@@ -233,7 +211,7 @@ class PRAutoBlogger_Pipeline_Runner {
);
update_option( self::QUEUE_KEY, $queue, false );
PRAutoBlogger_Pipeline_Status::update_queue_progress( $queue );
$this->update_queue_status( $queue );
$this->schedule_next();
PRAutoBlogger_Logger::instance()->info(
@@ -258,13 +236,71 @@ class PRAutoBlogger_Pipeline_Runner {
);
}
/** Update the frontend status transient with queue progress. */
private function update_queue_status( array $queue ): void {
$done = $queue['results']['generated'] + $queue['results']['rejected'];
$total = $done + count( $queue['ideas'] );
$current = get_transient( 'prautoblogger_generation_status' );
set_transient(
'prautoblogger_generation_status',
array(
'status' => 'running',
'stage' => sprintf( __( 'Generating article %1$d of %2$d…', 'prautoblogger' ), $done + 1, $total ),
'started' => is_array( $current ) ? ( $current['started'] ?? time() ) : time(),
'last_updated' => time(),
),
600
);
}
/** Write the final "complete" status transient. */
private function write_final_status( array $r ): void {
set_transient(
'prautoblogger_generation_status',
array(
'status' => 'complete',
'generated' => $r['generated'],
'published' => $r['published'],
'rejected' => $r['rejected'],
'cost' => $r['cost'],
),
600
);
}
/** Clean up a stale or empty queue. */
private function finish_queue(): void {
$queue = get_option( self::QUEUE_KEY );
if ( is_array( $queue ) && isset( $queue['results'] ) ) {
PRAutoBlogger_Pipeline_Status::write_final( $queue['results'] );
$this->write_final_status( $queue['results'] );
}
delete_option( self::QUEUE_KEY );
PRAutoBlogger_Generation_Lock::release();
}
/** Log the pipeline summary. */
private function log_summary( array $r ): void {
PRAutoBlogger_Logger::instance()->info(
sprintf(
'Pipeline complete: %d generated, %d published, %d rejected. Cost: $%.4f',
$r['generated'],
$r['published'],
$r['rejected'],
$r['cost']
),
'pipeline'
);
}
/** Update the generation status transient with the current stage. */
private function broadcast_stage( string $stage ): void {
$key = 'prautoblogger_generation_status';
$current = get_transient( $key );
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
$current['stage'] = $stage;
$current['last_updated'] = time();
set_transient( $key, $current, 600 );
}
}
}

View File

@@ -1,106 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Frontend status-transient + summary-log helpers for pipeline runs.
*
* What: The generation-status transient plumbing (stage broadcast, queue
* progress, final result) and the pipeline summary log line,
* extracted verbatim from Pipeline_Runner / Article_Worker in
* v0.18.0 (300-line cap; the two classes carried duplicate
* broadcast helpers). Pure presentation/state — no business logic.
* Who triggers it: Pipeline_Runner, Article_Worker.
* Dependencies: WordPress transients, PRAutoBlogger_Logger.
*
* @see core/class-pipeline-runner.php — Queue progress + final status writes.
* @see core/class-article-worker.php — Per-stage broadcasts.
* @see class-executor.php — Poller that reads this transient.
*/
class PRAutoBlogger_Pipeline_Status {
/** Transient key polled by the admin frontend. */
private const KEY = 'prautoblogger_generation_status';
/** Seconds the status transient stays readable. */
private const TTL = 600;
/**
* Update the live stage text (only while a run is broadcasting).
*
* @param string $stage Human-readable stage description.
* @return void
*/
public static function broadcast( string $stage ): void {
$current = get_transient( self::KEY );
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
$current['stage'] = $stage;
$current['last_updated'] = time();
set_transient( self::KEY, $current, self::TTL );
}
}
/**
* Update queue progress ("Generating article X of Y…").
*
* @param array $queue Queue array with 'results' + 'ideas'.
* @return void
*/
public static function update_queue_progress( array $queue ): void {
$done = $queue['results']['generated'] + $queue['results']['rejected'];
$total = $done + count( $queue['ideas'] );
$current = get_transient( self::KEY );
set_transient(
self::KEY,
array(
'status' => 'running',
/* translators: 1: current article number, 2: total articles. */
'stage' => sprintf( __( 'Generating article %1$d of %2$d…', 'prautoblogger' ), $done + 1, $total ),
'started' => is_array( $current ) ? ( $current['started'] ?? time() ) : time(),
'last_updated' => time(),
),
self::TTL
);
}
/**
* Write the final "complete" status.
*
* @param array $r Result counters (generated/published/rejected/cost).
* @return void
*/
public static function write_final( array $r ): void {
set_transient(
self::KEY,
array(
'status' => 'complete',
'generated' => $r['generated'],
'published' => $r['published'],
'rejected' => $r['rejected'],
'cost' => $r['cost'],
),
self::TTL
);
}
/**
* Log the pipeline summary line.
*
* @param array $r Result counters (generated/published/rejected/cost).
* @return void
*/
public static function log_summary( array $r ): void {
PRAutoBlogger_Logger::instance()->info(
sprintf(
'Pipeline complete: %d generated, %d published, %d rejected. Cost: $%.4f',
$r['generated'],
$r['published'],
$r['rejected'],
$r['cost']
),
'pipeline'
);
}
}

View File

@@ -91,9 +91,7 @@ class PRAutoBlogger_Post_Assembler {
* are generated. Its cost is logged with the run_id but no post_id. After all
* articles finish, this method divides the research cost evenly and inserts
* one 'llm_research' row per article so the cost breakdown popover includes
* the amortized research overhead. The audit fields prompt_version and
* agent_role are carried from the original research row (v0.19.4 fix;
* prior builds left them NULL/empty — see phase-1 thread seq 49).
* the amortized research overhead.
*
* Side effects: database SELECT, INSERT, DELETE on generation_log.
*
@@ -110,8 +108,8 @@ class PRAutoBlogger_Post_Assembler {
// Find the unlinked research cost row for this run.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$research_row = $wpdb->get_row(
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
"SELECT id, estimated_cost, provider, model, prompt_tokens, completion_tokens, prompt_version, agent_role
$wpdb->prepare(
"SELECT id, estimated_cost, provider, model, prompt_tokens, completion_tokens // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
FROM {$table}
WHERE run_id = %s AND stage = 'llm_research' AND post_id IS NULL
LIMIT 1",
@@ -160,8 +158,6 @@ class PRAutoBlogger_Post_Assembler {
'estimated_cost' => $amortized_cost,
'response_status' => 'success',
'error_message' => '',
'prompt_version' => $research_row->prompt_version,
'agent_role' => $research_row->agent_role ?? '',
'created_at' => current_time( 'mysql' ),
)
);

View File

@@ -1,147 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Canonical default bodies for the editor, research, and image registry keys.
*
* What: Companion to PRAutoBlogger_Prompt_Defaults (split for the 300-line
* cap, mirroring the settings-fields/-extended split). Holds the
* chief-editor and LLM-research prompt copy extracted verbatim from
* their classes, and references the two image keys that form the
* image-composer PR seam: `image.rewriter_system` (the illustration
* rewriter prompt) and `image.style_template` (the Style Template,
* ARCHITECTURE #20). The composer PR CONSUMES these keys — it must
* not grow its own prompt storage, and the key names are frozen on
* the pipeline-v2-phase1 convo thread.
* Who triggers it: PRAutoBlogger_Prompt_Registry (render fallback + seed),
* PRAutoBlogger_Activator (seed migration).
* Dependencies: PRAutoBlogger_Image_Prompt_Builder::REWRITER_SYSTEM_PROMPT,
* PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE (referenced, not duplicated).
*
* @see core/class-prompt-defaults.php — Content + analysis keys.
* @see core/class-prompt-registry.php — Render/seed consumer.
* @see core/class-chief-editor.php — Computes the editor token values.
* @see providers/class-llm-research-provider.php — research.system consumer.
*/
class PRAutoBlogger_Prompt_Defaults_Editorial {
/**
* Chief-editor system prompt. instructions_block carries its own
* leading newline + trailing newline when non-empty ('' when absent),
* matching the historical concatenation byte-for-byte.
*/
public const EDITOR_SYSTEM = <<<'TPL'
You are a senior blog editor{{ niche_clause }}. Review article drafts before publication.
Evaluate on: QUALITY, ACCURACY, SEO, COMPLETENESS, READABILITY.
Respond with JSON: {
"verdict": "approved" | "revised" | "rejected",
"quality_score": 0.0-1.0,
"seo_score": 0.0-1.0,
"issues": ["issue1", "issue2"],
"notes": "Editorial notes",
"revised_content": "Full revised HTML if revised, null otherwise"
}
Rules:
- APPROVE if quality_score >= 0.7 and seo_score >= 0.6
- REVISE if fixable issues exist — provide full revised HTML
- REJECT if fundamentally flawed
- Preserve formatting, links, lists when revising
{{ instructions_block }}
TPL;
/** Chief-editor review user prompt. */
public const EDITOR_REVIEW = <<<'TPL'
Review this article draft:
BRIEF: Title: {{ title }} | Topic: {{ topic }} | Type: {{ article_type }}
KEY POINTS: {{ key_points }}
TARGET KEYWORDS: {{ keywords }}
CONTENT:
{{ content }}
TPL;
/**
* LLM deep-research system prompt (fully static). The user-side
* research brief stays the `prautoblogger_research_prompt` SETTING —
* it is site configuration, not pipeline copy.
*/
public const RESEARCH_SYSTEM = <<<'TPL'
You are a deep research analyst specializing in emerging trends, scientific developments, and community knowledge in niche health and biohacking domains. Your task is to identify substantive, actionable findings.
Using your training knowledge, scan across:
- Recent scientific literature and research directions
- Active community discussions, debates, and evolving consensus
- Emerging products, protocols, and methodologies gaining traction
- Common questions, misconceptions, and points of confusion
- Regulatory changes, safety concerns, and legal shifts
- Gaps between what practitioners want to know and what content exists
Your findings must be:
1. SUBSTANTIVE — 2-3 paragraphs of detailed analysis per finding, not a headline
2. ACTIONABLE — practical enough to seed a full article
3. REALISTIC — grounded in what is actually discussed or researched; do NOT invent citations
4. TIMELY — reflect current knowledge, recent shifts, or emerging questions
Respond with valid JSON only (no preamble, no markdown fences):
{"findings": [{"title": "string", "content": "string (2-3 paragraphs)", "relevance_score": 0-100, "category": "question|trend|comparison|guide|misconception|safety"}]}
Generate 8-12 findings. Prioritize depth over breadth. Avoid generic or surface-level topics.
TPL;
/**
* Registry definitions for the editor / research / image keys.
*
* The image bodies are referenced from their existing single sources
* of truth rather than duplicated. Note the image keys seed the
* registry for the composer PR; the v0.16.0 option-override chain
* (`prautoblogger_image_prompt_instructions`,
* `prautoblogger_image_style_template`) is unchanged in Phase 1.
*
* @return array<string, array{body: string, model_option: ?string, params: array<string, mixed>}>
*/
public static function defs(): array {
return array(
'editor.system' => array(
'body' => self::EDITOR_SYSTEM,
'model_option' => 'prautoblogger_editor_model',
'params' => array(
'temperature' => 0.3,
'max_tokens' => 5000,
'response_format' => array( 'type' => 'json_object' ),
),
),
'editor.review' => array(
'body' => self::EDITOR_REVIEW,
'model_option' => 'prautoblogger_editor_model',
'params' => array(),
),
'research.system' => array(
'body' => self::RESEARCH_SYSTEM,
'model_option' => 'prautoblogger_research_model',
'params' => array(
'temperature' => 0.7,
'max_tokens' => 8000,
'response_format' => array( 'type' => 'json_object' ),
),
),
'image.rewriter_system' => array(
'body' => PRAutoBlogger_Image_Prompt_Builder::REWRITER_SYSTEM_PROMPT,
'model_option' => 'prautoblogger_analysis_model',
'params' => array(
'temperature' => 0.7,
'max_tokens' => 180,
),
),
'image.style_template' => array(
'body' => PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE,
'model_option' => 'prautoblogger_image_model',
'params' => array(),
),
);
}
}

View File

@@ -1,210 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Canonical default bodies for the content + analysis prompt-registry keys.
*
* What: The v0.16.0 hardcoded prompt texts, extracted verbatim into
* `{{ token }}` templates. These constants are the single source of
* truth twice over: the v1.2.0 migration seeds them into
* `wp_prautoblogger_prompts` as version 1, AND the registry falls
* back to them whenever the table is missing/empty — so a
* half-migrated site renders byte-identical prompts and never
* fatals. Versions in the table are immutable; to change a prompt,
* create a new version (see Prompt_Registry).
* Who triggers it: PRAutoBlogger_Prompt_Registry (render fallback + seed),
* PRAutoBlogger_Activator (seed migration).
* Dependencies: none — pure constants.
*
* @see core/class-prompt-registry.php — Render/seed consumer.
* @see core/class-prompt-defaults-editorial.php — Editor/research/image keys.
* @see core/class-content-prompts.php — Computes the token values.
* @see core/class-analysis-prompts.php — Computes the token values.
*/
class PRAutoBlogger_Prompt_Defaults {
/**
* System prompt shared across all writing stages. The mandatory style
* guide block and the linking rules stay code-side (they are data
* injection, not prompt copy) and are appended after this body.
*/
public const CONTENT_SYSTEM = 'You are an expert blog writer{{ niche_clause }}. Write well-researched, engaging, SEO-friendly content. Use a {{ tone }} tone. Output HTML content only — no markdown, no code fences, no commentary.';
/** Single-pass writer prompt (Economy tier — logs stage 'draft'). */
public const CONTENT_SINGLE_PASS = <<<'TPL'
Write a complete blog post in HTML format.
Title: {{ title }}
Topic: {{ topic }}
Type: {{ article_type }}
Key points:
- {{ key_points }}
Keywords: {{ keywords }}
Requirements:
- {{ min_words }}-{{ max_words }} words
- Proper HTML (h2, h3, p, ul/li)
- Engaging intro, strong conclusion with CTA
- Do NOT include the title or <html>/<body> tags
- Output HTML only, no markdown or commentary
- Follow EVERY formatting and structural requirement from your system prompt style guide
TPL;
/** Multi-step stage 1: outline. */
public const CONTENT_OUTLINE = <<<'TPL'
Create a detailed outline for a blog post titled: "{{ title }}"
Topic: {{ topic }}
Article type: {{ article_type }}
Key points to cover:
{{ key_points }}
Target keywords: {{ keywords }}
The outline should have 4-6 main sections with bullet points under each. Include an introduction hook and a conclusion with a call to action. Word count target: {{ min_words }}-{{ max_words }} words.
Plan the structure to satisfy EVERY requirement in your system prompt style guide.
TPL;
/** Multi-step stage 2: full draft from outline. */
public const CONTENT_DRAFT = <<<'TPL'
Using this outline, write the full blog post in HTML format.
OUTLINE:
{{ outline }}
Requirements:
- Write in a {{ tone }} tone
- Target {{ min_words }}-{{ max_words }} words
- Use proper HTML headings (h2, h3), paragraphs, and lists
- Include an engaging introduction and strong conclusion
- Naturally incorporate these keywords: {{ keywords }}
- Do NOT include the title in the HTML (it will be set separately)
- Do NOT wrap in <html>, <head>, or <body> tags — just the article content
- Follow EVERY formatting and structural requirement from your system prompt style guide
TPL;
/** Multi-step stage 3: polish (canonical name — ARCHITECTURE once said 'edit'). */
public const CONTENT_POLISH = <<<'TPL'
Review and polish this blog post draft. Improve:
1. Flow and readability
2. SEO optimization (headings, keyword placement)
3. Engagement (hooks, transitions, call-to-action)
4. Accuracy and clarity
5. Remove any filler or redundant sentences
IMPORTANT: Preserve all bullet points, numbered lists, hyperlinks, and structural elements from the draft. Do NOT flatten lists into prose or remove links. Ensure every requirement from your system prompt style guide is satisfied in the final output.
Return the polished HTML content only. Do not add commentary.
DRAFT:
{{ draft }}
TPL;
/**
* Analyzer system prompt. The *_block tokens carry their own trailing
* separators when non-empty ('' when absent) so the rendered output is
* byte-identical to the historical concatenation.
*/
public const ANALYSIS_SYSTEM = <<<'TPL'
You are a content strategist analyzing social media discussions to find article ideas for a blog{{ niche_clause }}.
IMPORTANT: You must identify exactly {{ target_count }} DISTINCT article ideas. Each idea must cover a substantially different topic — no two ideas should overlap in their main subject. Aim for diversity across these categories:
1. QUESTIONS: Recurring questions people ask ("How do I...", "What is...", "Is it safe to...")
2. COMPLAINTS: Pain points, frustrations, or problems people report
3. COMPARISONS: Product/method comparisons people discuss ("X vs Y", "Which is better")
4. NEWS: Recent developments, rule changes, or trends people are discussing
5. GUIDES: How-to topics, best practices, or educational content people need
Spread your {{ target_count }} ideas across multiple categories. Be specific — "peptide dosing for BPC-157" is better than "peptide information". Each idea should be narrow enough to be a single focused blog post.
For each idea, provide:
- type: 'question', 'complaint', 'comparison', 'news', or 'guide'
- topic: A clear, specific, narrow topic description
- summary: 1-2 sentence summary of why this topic matters
- frequency: How many of the provided posts relate to this topic
- relevance_score: 0.0 to 1.0 indicating how relevant and article-worthy this is
- suggested_title: A compelling, unique blog post title
- key_points: Array of 3-5 key points the article should cover
- target_keywords: Array of SEO keywords for this topic
{{ performance_block }}{{ recent_articles_block }}{{ instructions_block }}Respond with valid JSON containing exactly {{ target_count }} patterns:
{"patterns": [{"type": "...", "topic": "...", "summary": "...", "frequency": N, "relevance_score": 0.X, "suggested_title": "...", "key_points": [...], "target_keywords": [...]}]}
TPL;
/** Analyzer user prompt wrapping the source-data summary. */
public const ANALYSIS_USER = <<<'TPL'
Here are the recent social media posts and comments to analyze. Find {{ target_count }} distinct, diverse article ideas from this data:
{{ summary }}
TPL;
/**
* Registry definitions for the content + analysis keys.
*
* Each entry: body (the v1 template), model_option (the wp_option that
* selects the model at call time — informational in Phase 1) and params
* (the call-time LLM parameters, snapshotted for audit comparability).
*
* @return array<string, array{body: string, model_option: ?string, params: array<string, mixed>}>
*/
public static function defs(): array {
return array(
'content.system' => array(
'body' => self::CONTENT_SYSTEM,
'model_option' => 'prautoblogger_writing_model',
'params' => array(),
),
'content.single_pass' => array(
'body' => self::CONTENT_SINGLE_PASS,
'model_option' => 'prautoblogger_writing_model',
'params' => array(
'temperature' => 0.7,
'max_tokens' => 4000,
),
),
'content.outline' => array(
'body' => self::CONTENT_OUTLINE,
'model_option' => 'prautoblogger_writing_model',
'params' => array(
'temperature' => 0.5,
'max_tokens' => 1500,
),
),
'content.draft' => array(
'body' => self::CONTENT_DRAFT,
'model_option' => 'prautoblogger_writing_model',
'params' => array(
'temperature' => 0.7,
'max_tokens' => 4000,
),
),
'content.polish' => array(
'body' => self::CONTENT_POLISH,
'model_option' => 'prautoblogger_writing_model',
'params' => array(
'temperature' => 0.4,
'max_tokens' => 4000,
),
),
'analysis.system' => array(
'body' => self::ANALYSIS_SYSTEM,
'model_option' => 'prautoblogger_analysis_model',
'params' => array(
'temperature' => 0.5,
'max_tokens' => 8000,
),
),
'analysis.user' => array(
'body' => self::ANALYSIS_USER,
'model_option' => 'prautoblogger_analysis_model',
'params' => array(),
),
);
}
}

View File

@@ -1,143 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Write side of the versioned prompt registry: create / activate / seed.
*
* What: Companion to PRAutoBlogger_Prompt_Registry (split for the 300-line
* cap). Owns every mutation of `wp_prautoblogger_prompts` and
* enforces the immutability rule: a stored body is NEVER updated —
* a change is a new (prompt_key, version) row, and `activate()`
* flips the single active flag per key. `seed_v1()` writes the
* canonical v0.16.0 texts as version 1 (idempotent — keys that
* already have rows keep their history). This is the API surface
* the Phase-2 in-admin Prompts editor will call; Phase 1 ships no UI.
* Who triggers it: PRAutoBlogger_Activator (seed migration on db 1.2.0),
* Phase-2 admin (create/activate), WP-CLI (future).
* Dependencies: WordPress $wpdb, PRAutoBlogger_Prompt_Registry (table name,
* availability probe, defs, cache flush).
*
* @see core/class-prompt-registry.php — Read side (render, pins, fallback).
* @see class-activator.php — Calls seed_v1() once, flag-gated.
*/
class PRAutoBlogger_Prompt_Registry_Writer {
/**
* All versions of a key, newest first (Phase-2 list/diff support).
*
* @param string $key Registry key.
* @return array<int, array<string, mixed>>
*/
public static function list_versions( string $key ): array {
if ( ! PRAutoBlogger_Prompt_Registry::is_available() ) {
return array();
}
global $wpdb;
$table = PRAutoBlogger_Prompt_Registry::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$table} WHERE prompt_key = %s ORDER BY version DESC", $key ),
ARRAY_A
);
return is_array( $rows ) ? $rows : array();
}
/**
* Create a NEW immutable version of a key and (optionally) activate it.
* Never mutates an existing row's body — that is the whole point.
*
* @param string $key Registry key.
* @param string $body Template body.
* @param string|null $model Optional model hint.
* @param array<string, mixed>|null $params Optional params snapshot.
* @param string $author Who created it (seed tag, login, agent).
* @param bool $activate Flip active to this version (default true).
* @return int New version number, or 0 on failure / table unavailable.
*/
public static function create_version( string $key, string $body, ?string $model, ?array $params, string $author, bool $activate = true ): int {
if ( ! PRAutoBlogger_Prompt_Registry::is_available() ) {
return 0;
}
global $wpdb;
$table = PRAutoBlogger_Prompt_Registry::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$max = (int) $wpdb->get_var(
$wpdb->prepare( "SELECT MAX(version) FROM {$table} WHERE prompt_key = %s", $key )
);
$next = $max + 1;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$ok = $wpdb->insert(
$table,
array(
'prompt_key' => $key,
'version' => $next,
'body' => $body,
'model' => $model,
'params_json' => null !== $params ? wp_json_encode( $params ) : null,
'author' => $author,
'created_at' => current_time( 'mysql' ),
'active' => 0,
)
);
if ( false === $ok ) {
return 0;
}
if ( $activate ) {
self::activate( $key, $next );
}
return $next;
}
/**
* Make one version the single active version of its key.
*
* @param string $key Registry key.
* @param int $version Version to activate.
* @return bool True when the version is now active.
*/
public static function activate( string $key, int $version ): bool {
if ( ! PRAutoBlogger_Prompt_Registry::is_available() ) {
return false;
}
global $wpdb;
$table = PRAutoBlogger_Prompt_Registry::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( $wpdb->prepare( "UPDATE {$table} SET active = 0 WHERE prompt_key = %s", $key ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$updated = $wpdb->query(
$wpdb->prepare( "UPDATE {$table} SET active = 1 WHERE prompt_key = %s AND version = %d", $key, $version )
);
PRAutoBlogger_Prompt_Registry::flush_cache();
return 1 === (int) $updated;
}
/**
* Seed every registry key with its canonical v1 body. Idempotent: keys
* that already have rows are left untouched (their history is theirs).
*
* Side effects: up to one INSERT + two UPDATEs per missing key.
*
* @param string $author Audit tag for the seed rows (e.g. 'seed:v0.18.0').
* @return int Number of keys seeded.
*/
public static function seed_v1( string $author = 'seed:v0.18.0' ): int {
if ( ! PRAutoBlogger_Prompt_Registry::is_available() ) {
return 0;
}
$seeded = 0;
foreach ( PRAutoBlogger_Prompt_Registry::defs() as $key => $def ) {
if ( ! empty( self::list_versions( $key ) ) ) {
continue;
}
$model = null !== $def['model_option'] ? (string) get_option( $def['model_option'], '' ) : null;
$version = self::create_version( $key, $def['body'], '' !== (string) $model ? $model : null, $def['params'], $author, true );
if ( $version > 0 ) {
++$seeded;
}
}
PRAutoBlogger_Prompt_Registry::flush_cache();
return $seeded;
}
}

View File

@@ -1,214 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Versioned prompt registry — immutable versions, one active row per key.
*
* What: Read/write API over `wp_prautoblogger_prompts`. Rendering resolves
* the ACTIVE body for a key and fills `{{ token }}` placeholders;
* when the table is missing or has no row for the key (half-migrated
* site, failed seed), it falls back to the canonical defaults the
* seed itself uses — byte-identical output, no fatals (self-healing).
* Versions are IMMUTABLE: there is no update path for a stored body;
* changes create a new (prompt_key, version) row and flip `active`
* (write side lives in PRAutoBlogger_Prompt_Registry_Writer).
* Runs pin the active version of every key at start (stored on the
* runs row) so generation_log rows can be stamped with the exact
* prompt_version they rendered with. No admin UI in Phase 1 — the
* list/activate/create API is what the Phase-2 Prompts screen needs.
* Who triggers it: Content_Prompts / Analysis_Prompts / Chief_Editor /
* LLM_Research_Provider (render), Cost_Tracker (pins_for_run),
* Activator (seed_v1), Cost_Tracker::set_run_id (pin_for_run).
* Dependencies: WordPress $wpdb, Prompt_Defaults(+Editorial), wp_json_encode.
*
* @see core/class-prompt-defaults.php — Canonical v1 bodies (seed + fallback).
* @see core/class-prompt-defaults-editorial.php — Editor/research/image bodies.
* @see core/class-run-state.php — Owns the runs row the pins live on.
* @see ARCHITECTURE.md #21 — Design rationale.
*/
class PRAutoBlogger_Prompt_Registry {
/** @var array<string, ?array<string, mixed>> Per-request active-row cache. */
private static array $active_cache = array();
/** @var array<string, array<string, int>> Per-request run-pins cache. */
private static array $pins_cache = array();
/** @var bool|null Per-request "table exists" probe result. */
private static ?bool $table_ok = null;
/** Fully-qualified prompts table name (shared with Prompt_Registry_Writer). */
public static function table_name(): string {
global $wpdb;
return $wpdb->prefix . 'prautoblogger_prompts';
}
/**
* Whether the prompts table exists and is queryable. Cached per request;
* never throws — any failure reads as "not available" and every consumer
* falls back to the in-code defaults.
*
* @return bool
*/
public static function is_available(): bool {
if ( null !== self::$table_ok ) {
return self::$table_ok;
}
global $wpdb;
if ( null === $wpdb ) {
return false; // Not cached: $wpdb may appear later in boot.
}
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
self::$table_ok = ( $found === $table );
return self::$table_ok;
}
/**
* All registry definitions (content + analysis + editor + research + image).
*
* @return array<string, array{body: string, model_option: ?string, params: array<string, mixed>}>
*/
public static function defs(): array {
return array_merge(
PRAutoBlogger_Prompt_Defaults::defs(),
PRAutoBlogger_Prompt_Defaults_Editorial::defs()
);
}
/**
* Canonical in-code default body for a key (the same text seeded as v1).
*
* @param string $key Registry key.
* @return string|null Body template, or null for unknown keys.
*/
public static function default_body( string $key ): ?string {
$defs = self::defs();
return isset( $defs[ $key ] ) ? $defs[ $key ]['body'] : null;
}
/**
* Active row for a key, or null when none / table unavailable.
*
* @param string $key Registry key.
* @return array<string, mixed>|null Row with prompt_key, version, body, model, params_json, author, created_at, active.
*/
public static function get_active( string $key ): ?array {
if ( array_key_exists( $key, self::$active_cache ) ) {
return self::$active_cache[ $key ];
}
$row = null;
if ( self::is_available() ) {
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE prompt_key = %s AND active = 1 ORDER BY version DESC LIMIT 1",
$key
),
ARRAY_A
);
$row = is_array( $row ) ? $row : null;
}
self::$active_cache[ $key ] = $row;
return $row;
}
/**
* Render a prompt: active body for the key (fallback: canonical default),
* with `{{ token }}` placeholders substituted.
*
* @param string $key Registry key (e.g. 'content.single_pass').
* @param array<string, string> $tokens Token name => replacement value.
* @return string Rendered prompt ('' only if the key is unknown AND absent).
*/
public static function render( string $key, array $tokens = array() ): string {
$active = self::get_active( $key );
$body = null !== $active ? (string) $active['body'] : (string) self::default_body( $key );
return self::fill( $body, $tokens );
}
/**
* Substitute `{{ token }}` placeholders in a template body.
*
* @param string $body Template body.
* @param array<string, string> $tokens Token name => replacement value.
* @return string
*/
public static function fill( string $body, array $tokens ): string {
foreach ( $tokens as $name => $value ) {
$body = str_replace( '{{ ' . $name . ' }}', (string) $value, $body );
}
return $body;
}
/**
* Map of prompt_key => active version for every key present in the table.
*
* @return array<string, int>
*/
public static function active_versions(): array {
if ( ! self::is_available() ) {
return array();
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results( "SELECT prompt_key, version FROM {$table} WHERE active = 1", ARRAY_A );
$map = array();
foreach ( ( is_array( $rows ) ? $rows : array() ) as $row ) {
$map[ (string) $row['prompt_key'] ] = (int) $row['version'];
}
return $map;
}
/**
* Pin the current active versions onto a run's row (once, at run start).
* No-ops when the runs row already carries pins (resume keeps the
* versions the run started with) or when tables are unavailable.
*
* @param string $run_id Pipeline run UUID.
* @return void
*/
public static function pin_for_run( string $run_id ): void {
if ( '' === $run_id || ! self::is_available() ) {
return;
}
$pins = self::active_versions();
if ( empty( $pins ) ) {
return;
}
PRAutoBlogger_Run_State::set_pins_if_absent( $run_id, $pins );
unset( self::$pins_cache[ $run_id ] );
}
/**
* The pinned prompt versions for a run (cached per request). Empty when
* the run has no pins (pre-1.2.0 rows, standalone calls, missing table).
*
* @param string|null $run_id Pipeline run UUID, or null.
* @return array<string, int>
*/
public static function pins_for_run( ?string $run_id ): array {
if ( null === $run_id || '' === $run_id ) {
return array();
}
if ( isset( self::$pins_cache[ $run_id ] ) ) {
return self::$pins_cache[ $run_id ];
}
$pins = PRAutoBlogger_Run_State::get_pins( $run_id );
self::$pins_cache[ $run_id ] = $pins;
return $pins;
}
/** Reset per-request caches (tests). */
public static function flush_cache(): void {
self::$active_cache = array();
self::$pins_cache = array();
self::$table_ok = null;
}
}

128
includes/core/class-publisher.php Normal file → Executable file
View File

@@ -82,39 +82,6 @@ class PRAutoBlogger_Publisher {
?string $run_id = null,
?PRAutoBlogger_Cost_Tracker $cost_tracker = null
): 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
// (check-before-insert) so a retried/resumed run cannot create a
// duplicate post. One run_id spans all N articles of a batch, so
// the idea hash disambiguates within the run.
$idea_hash = PRAutoBlogger_Run_Stage_State::idea_hash( $idea );
if ( null !== $run_id && '' !== $run_id ) {
$existing_id = $this->find_existing_post( $run_id, $idea_hash );
if ( $existing_id > 0 ) {
// v0.20.0: a re-run's regenerated content must land on the
// existing UNPUBLISHED post (otherwise re-runs silently
// discard their output). Published posts stay frozen
// (CPO guardrail 5) — refresh skips them untouched.
return $this->refresh_unpublished_post( $existing_id, $content, $idea, $review );
}
}
// Clean LLM artifacts, then inject peptide hyperlinks deterministically
// before the content enters WordPress. Peptide linker no-ops gracefully
// if PR Core is not active.
@@ -127,7 +94,7 @@ class PRAutoBlogger_Publisher {
'post_status' => $post_status,
'post_type' => 'post',
'post_author' => PRAutoBlogger_Post_Assembler::get_default_author_id(),
'meta_input' => $this->build_meta( $idea, $review, $run_id, $idea_hash ),
'meta_input' => $this->build_meta( $idea, $review, $run_id ),
);
/** @see class-prautoblogger.php — listeners registered in main loader. */
@@ -157,60 +124,6 @@ class PRAutoBlogger_Publisher {
return $post_id;
}
/**
* Refresh an existing post from re-run output — unpublished only.
*
* Idempotent-resume calls land here too (same content in = same
* content out, so behavior is unchanged for plain resumes). The post
* keeps its CURRENT status: a re-run never publishes an unpublished
* post — publication stays an explicit Review Queue / WP editor
* action. Published (and scheduled/private) posts are returned
* untouched: the run is frozen (CPO guardrail 5).
*
* Side effects: wp_update_post + post meta updates (unpublished only).
*
* @param int $post_id Existing post ID.
* @param string $content Regenerated HTML content.
* @param PRAutoBlogger_Article_Idea $idea The idea.
* @param PRAutoBlogger_Editorial_Review $review The fresh review.
* @return int The post ID.
*/
private function refresh_unpublished_post( int $post_id, string $content, PRAutoBlogger_Article_Idea $idea, PRAutoBlogger_Editorial_Review $review ): int {
$post = get_post( $post_id );
if ( PRAutoBlogger_Rerun_Eligibility::post_frozen( $post ) ) {
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Post %d already exists and is published — frozen, skipping content refresh.', $post_id ),
'publisher'
);
return $post_id;
}
// Same sanitize chain as create_post().
$clean_content = PRAutoBlogger_Post_Assembler::sanitize_llm_content( $content );
$linked_content = PRAutoBlogger_Peptide_Linker::inject_links( $clean_content );
wp_update_post(
array(
'ID' => $post_id,
'post_title' => sanitize_text_field( $idea->get_suggested_title() ),
'post_content' => wp_kses_post( $linked_content ),
)
);
update_post_meta( $post_id, '_prautoblogger_editor_verdict', $review->get_verdict() );
update_post_meta( $post_id, '_prautoblogger_editor_notes', $review->get_notes() );
update_post_meta( $post_id, '_prautoblogger_quality_score', $review->get_quality_score() );
update_post_meta( $post_id, '_prautoblogger_seo_score', $review->get_seo_score() );
update_post_meta( $post_id, '_prautoblogger_generated_at', gmdate( 'c' ) );
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Post %d refreshed from re-run output (status preserved: %s).', $post_id, (string) ( $post->post_status ?? '' ) ),
'publisher'
);
return $post_id;
}
/**
* Build post_meta array for generation metadata.
*
@@ -227,8 +140,7 @@ class PRAutoBlogger_Publisher {
private function build_meta(
PRAutoBlogger_Article_Idea $idea,
PRAutoBlogger_Editorial_Review $review,
?string $run_id = null,
string $idea_hash = ''
?string $run_id = null
): array {
$meta = array(
'_prautoblogger_generated' => '1',
@@ -248,42 +160,6 @@ class PRAutoBlogger_Publisher {
if ( null !== $run_id && '' !== $run_id ) {
$meta['_prautoblogger_run_id'] = $run_id;
}
if ( '' !== $idea_hash ) {
$meta['_prautoblogger_idea_hash'] = $idea_hash;
}
return $meta;
}
/**
* Find a post already created for this (run, idea) pair.
*
* Direct postmeta self-join (any post_status, including trash) — the
* idempotency check must see drafts and pending posts too.
*
* @param string $run_id Pipeline run UUID.
* @param string $idea_hash Idea hash from Run_Stage_State::idea_hash().
* @return int Existing post ID, or 0 when none.
*/
private function find_existing_post( string $run_id, string $idea_hash ): int {
global $wpdb;
if ( null === $wpdb ) {
return 0;
}
$postmeta = $wpdb->prefix . 'postmeta';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$post_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT pm_run.post_id FROM {$postmeta} pm_run
INNER JOIN {$postmeta} pm_hash
ON pm_hash.post_id = pm_run.post_id
AND pm_hash.meta_key = '_prautoblogger_idea_hash'
AND pm_hash.meta_value = %s
WHERE pm_run.meta_key = '_prautoblogger_run_id' AND pm_run.meta_value = %s
LIMIT 1",
$idea_hash,
$run_id
)
);
return null !== $post_id ? (int) $post_id : 0;
}
}

View File

@@ -1,73 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Per-PHP-process stash for the most recent outgoing LLM request body.
*
* What: A process-scoped static slot recording the JSON request body the
* OpenRouter provider is about to dispatch, so Cost_Tracker::
* log_api_call() can persist it to `generation_log.request_json`
* (v0.20.0 / B1) without threading the body through every call
* site. Mirrors the Run_Context precedent (v0.18.0).
*
* SECURITY GUARANTEE: only the request BODY is ever recorded.
* Authorization headers are built separately
* (Request_Builder::build_headers()) and can never reach this
* class; build_body() copies only whitelisted option keys.
*
* Consume-once semantics: consume() clears the slot, and record()
* overwrites it at every dispatch — so a stale body from an
* unlogged failed call can never attach to a later, unrelated
* log row.
* Who triggers it: OpenRouter_Provider::send_chat_completion() (record,
* pre-dispatch so error rows carry the request too);
* Cost_Tracker::log_api_call() (consume).
* Dependencies: none.
*
* @see providers/class-open-router-provider.php — Records before dispatch.
* @see core/class-cost-tracker.php — Consumes into the log row.
* @see core/class-run-context.php — The pattern this mirrors.
* @see ARCHITECTURE.md #24 — Edit + re-run substrate (B1).
*/
class PRAutoBlogger_Request_Recorder {
/** @var string|null JSON-encoded request body of the in-flight LLM call. */
private static ?string $request_json = null;
/**
* Record the outgoing request body for the next log row.
*
* Overwrites any previous stash (one in-flight chat call per PHP
* process). Bodies that fail JSON encoding are skipped silently —
* the log row's request_json stays NULL, never blocking the call.
*
* @param array<string, mixed> $body Request body from Request_Builder::build_body().
* @return void
*/
public static function record( array $body ): void {
$encoded = wp_json_encode( $body );
self::$request_json = is_string( $encoded ) ? $encoded : null;
}
/**
* Return the stashed request body and clear the slot (consume-once).
*
* @return string|null JSON request body, or null when nothing is stashed.
*/
public static function consume(): ?string {
$json = self::$request_json;
self::$request_json = null;
return $json;
}
/**
* Clear the stash (tests / defensive teardown).
*
* @return void
*/
public static function clear(): void {
self::$request_json = null;
}
}

View File

@@ -1,214 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Policy gates for edit + single-step re-run (v0.20.0, M3).
*
* What: Single source of truth for WHO may re-run WHAT:
* - Published posts are frozen (CPO guardrail 5): publish/future/
* private statuses lock the run; edits go through the WP editor.
* - Runs that are actively executing (status pending/running or
* the global generation lock held) cannot be re-run — "in
* progress" in the CPO sense means in the WORKFLOW (unpublished),
* not mid-execution.
* - Editable stages (input fork + replay) are the item-scoped
* writer chat stages of the CURRENT pipeline vocabulary:
* outline/draft/polish (single-pass uses draft only). review's
* input is fully derived from content (re-run it from here
* instead); analysis/research are run-level idea-selection
* stages; image stages are not chat-replayable (Phase 2b).
* - The canonical per-item chain orders downstream computation
* for stale-marking and rebuild sets.
* Who triggers it: Dossier_Actions (UI affordances + request validation),
* Rerun_Executor (re-validation under the lock before mutating).
* Dependencies: get_post(), Run_State, Generation_Lock, Stage_Input_Store.
*
* @see admin/class-dossier-actions.php — AJAX validation.
* @see core/class-rerun-executor.php — Cron-side re-validation.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Rerun_Eligibility {
/** Post statuses that freeze a run (CPO guardrail 5). */
public const FROZEN_STATUSES = array( 'publish', 'future', 'private' );
/** Stages whose input may be edited and replayed (chat writer stages). */
public const EDITABLE_STAGES = array( 'outline', 'draft', 'polish' );
/** Canonical per-item stage chain (current pipeline vocabulary). */
public const ITEM_STAGE_CHAIN = array( 'outline', 'draft', 'polish', 'review', 'publish' );
/**
* Whether a stage's input may be edited + replayed.
*
* @param string $stage Stage name.
* @return bool
*/
public static function is_editable_stage( string $stage ): bool {
return in_array( $stage, self::EDITABLE_STAGES, true );
}
/**
* Whether re-run-from-here may target this stage (any chain stage).
*
* @param string $stage Stage name.
* @return bool
*/
public static function is_chain_stage( string $stage ): bool {
return in_array( $stage, self::ITEM_STAGE_CHAIN, true );
}
/**
* Stages strictly AFTER a stage in the canonical chain — the set that
* goes stale when the stage is re-run. Stages absent from an item
* (e.g. outline/polish on single-pass runs) simply match no rows.
*
* @param string $stage Stage name.
* @return array<string> Downstream stage names ([] for non-chain stages).
*/
public static function downstream_of( string $stage ): array {
$idx = array_search( $stage, self::ITEM_STAGE_CHAIN, true );
if ( false === $idx ) {
return array();
}
return array_slice( self::ITEM_STAGE_CHAIN, $idx + 1 );
}
/**
* The demotion set for re-run-from-here: the stage itself plus all
* downstream chain stages.
*
* @param string $stage Stage name.
* @return array<string>
*/
public static function rebuild_set( string $stage ): array {
$idx = array_search( $stage, self::ITEM_STAGE_CHAIN, true );
if ( false === $idx ) {
return array();
}
return array_slice( self::ITEM_STAGE_CHAIN, $idx );
}
/**
* Whether a post is frozen for pipeline re-runs (guardrail 5).
*
* @param WP_Post|null $post The post, or null when none exists yet.
* @return bool
*/
public static function post_frozen( ?WP_Post $post ): bool {
return ( $post instanceof WP_Post )
&& in_array( (string) $post->post_status, self::FROZEN_STATUSES, true );
}
/**
* Full re-run eligibility check for a (run, post) pair.
*
* Returns ok=false with an operator-readable reason for: missing/
* frozen post, missing run row, run actively executing, or the
* global generation lock being held. Called from the AJAX layer for
* UI affordances AND re-validated by the cron handler under the lock
* (state can change between click and pickup).
*
* @param string $run_id Run UUID.
* @param int $post_id Post ID (0 = run has no post yet).
* @param bool $require_idle_lock Whether a held generation lock blocks (true for actions).
* @return array{ok: bool, reason: string} Verdict + reason ('' when ok).
*/
public static function check( string $run_id, int $post_id, bool $require_idle_lock = true ): array {
if ( '' === $run_id ) {
return self::no( __( 'This article has no recorded generation run.', 'prautoblogger' ) );
}
$post = $post_id > 0 ? get_post( $post_id ) : null;
if ( self::post_frozen( $post ) ) {
return self::no( __( 'This article is published — its run is frozen. Edit the article in the WordPress editor instead.', 'prautoblogger' ) );
}
$run = PRAutoBlogger_Run_State::get_run( $run_id );
if ( null === $run ) {
return self::no( __( 'No run ledger row exists for this article (pre-substrate run).', 'prautoblogger' ) );
}
if ( in_array( (string) $run['status'], array( 'pending', 'running' ), true ) ) {
return self::no( __( 'This run is currently executing. Wait for it to finish (or for the reaper to mark it failed).', 'prautoblogger' ) );
}
if ( $require_idle_lock && null !== PRAutoBlogger_Generation_Lock::get_acquired_at() ) {
return self::no( __( 'Another generation is in progress (lock held). Try again when it completes.', 'prautoblogger' ) );
}
return array(
'ok' => true,
'reason' => '',
);
}
/**
* Replay-specific check: base eligibility + editable stage + a saved
* input fork whose body has not been retention-pruned.
*
* @param string $run_id Run UUID.
* @param int $post_id Post ID.
* @param string $stage Stage name.
* @param string $agent_role Stage row agent role.
* @param string $item_key Stage row item key.
* @param bool $require_idle_lock False when the caller already owns the lock (cron handler).
* @return array{ok: bool, reason: string}
*/
public static function check_replay( string $run_id, int $post_id, string $stage, string $agent_role, string $item_key, bool $require_idle_lock = true ): array {
if ( ! self::is_editable_stage( $stage ) ) {
return self::no( __( 'This stage cannot be replayed with an edited input.', 'prautoblogger' ) );
}
$base = self::check( $run_id, $post_id, $require_idle_lock );
if ( ! $base['ok'] ) {
return $base;
}
$fork = PRAutoBlogger_Stage_Input_Store::latest_fork( $run_id, $stage, $agent_role, $item_key );
if ( null === $fork ) {
return self::no( __( 'Save an edited input for this stage first — re-run executes your latest saved version.', 'prautoblogger' ) );
}
if ( empty( $fork['request_json'] ) ) {
return self::no( __( 'The saved input for this stage was pruned by the retention cron and can no longer be replayed.', 'prautoblogger' ) );
}
return $base;
}
/**
* Rebuild-specific check: base eligibility + chain stage + idea seed
* available (runs started before v0.20.0 have no seed).
*
* @param string $run_id Run UUID.
* @param int $post_id Post ID.
* @param string $stage Target stage.
* @param string $item_key Item key.
* @param bool $require_idle_lock False when the caller already owns the lock (cron handler).
* @return array{ok: bool, reason: string}
*/
public static function check_rebuild( string $run_id, int $post_id, string $stage, string $item_key, bool $require_idle_lock = true ): array {
if ( ! self::is_chain_stage( $stage ) ) {
return self::no( __( 'Re-run from here is only available on article pipeline stages.', 'prautoblogger' ) );
}
$base = self::check( $run_id, $post_id, $require_idle_lock );
if ( ! $base['ok'] ) {
return $base;
}
if ( null === PRAutoBlogger_Stage_Input_Store::get_seed( $run_id, $item_key ) ) {
return self::no( __( 'No idea seed is stored for this run (recorded from v0.20.0 onward) — the pipeline cannot rebuild it safely.', 'prautoblogger' ) );
}
return $base;
}
/**
* Shorthand for a negative verdict.
*
* @param string $reason Operator-readable reason.
* @return array{ok: bool, reason: string}
*/
private static function no( string $reason ): array {
return array(
'ok' => false,
'reason' => $reason,
);
}
}

View File

@@ -1,221 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Queues and executes operator re-runs as chained cron jobs (v0.20.0, M3).
*
* What: The chained-cron seam for the dossier's two re-run actions —
* NEVER synchronous (CPO hard constraint): the AJAX layer only
* schedules; ALL state mutations happen in the cron handler after
* re-validating eligibility under the global generation lock.
* - Replay job: single-stage re-run of the latest edited input
* fork (Stage_Replay). Demotes the one stage row to running
* (human_modified=1), stale-marks downstream, executes, restores
* a terminal run status.
* - Rebuild job ("re-run from here"): demotes the target + all
* downstream chain stages to pending, then re-enters
* Article_Worker with the idea reconstructed from the stored
* seed — upstream done stages are reused (never re-charged),
* demoted stages re-run with prompts rebuilt from CURRENT
* upstream snapshots, and the publisher refreshes the
* unpublished post.
* Both jobs: monthly budget check, Run_State::reopen() (ceiling
* re-snapshotted from the current setting — a deliberate new-spend
* decision), M1 status transient for board/dossier pickup
* visibility, lock released in finally. Failures restore/record a
* terminal run status so the run-reaper's stuck-running sweep
* stays meaningful.
* Who triggers it: Dossier_Actions (queue_*), WP-Cron (on_* handlers via
* class-prautoblogger.php registration).
* Dependencies: Rerun_Job_Support (lock/budget/transient plumbing),
* Run_State, Run_Stage_Rerun_State, Stage_Input_Store,
* Stage_Replay, Article_Worker, Rerun_Eligibility.
*
* @see admin/class-dossier-actions.php — The AJAX layer (queues via Job_Support).
* @see core/class-rerun-job-support.php — Shared queue/lock/status plumbing.
* @see core/class-stage-replay.php — The governed replay call.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Rerun_Executor {
/** Cron action for single-stage replay jobs. */
public const REPLAY_ACTION = 'prautoblogger_rerun_stage_replay';
/** Cron action for re-run-from-here rebuild jobs. */
public const REBUILD_ACTION = 'prautoblogger_rerun_from_stage';
/**
* Cron handler: replay one stage from its latest edited input fork.
*
* Side effects: run_stages/runs mutations, one governed LLM call,
* generation_log row, status transient, lock acquire/release.
*
* @param string $run_id Run UUID.
* @param int $post_id Post the dossier acted on.
* @param string $stage Stage name.
* @param string $agent_role Stage row agent role.
* @param string $item_key Stage row item key.
* @return void
*/
public function on_replay_job( string $run_id, int $post_id, string $stage, string $agent_role, string $item_key ): void {
PRAutoBlogger_Rerun_Job_Support::harden_process();
if ( ! PRAutoBlogger_Rerun_Job_Support::acquire_lock_or_report() ) {
return;
}
$previous_status = null;
try {
// Re-validate under the lock — state may have changed between
// click and pickup (e.g. the post was published).
// require_idle_lock=false: THIS handler owns the lock.
$check = PRAutoBlogger_Rerun_Eligibility::check_replay( $run_id, $post_id, $stage, $agent_role, $item_key, false );
if ( ! $check['ok'] ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( $check['reason'] );
return;
}
if ( PRAutoBlogger_Rerun_Job_Support::monthly_budget_exceeded() ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'Monthly API budget exceeded. Re-run not started.', 'prautoblogger' ) );
return;
}
$fork = PRAutoBlogger_Stage_Input_Store::latest_fork( $run_id, $stage, $agent_role, $item_key );
$body = null !== $fork ? PRAutoBlogger_Stage_Replay::decode_body( (string) $fork['request_json'] ) : null;
if ( null === $body ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'The saved input could not be decoded as a replayable request.', 'prautoblogger' ) );
return;
}
$previous_status = PRAutoBlogger_Run_State::get_status( $run_id );
if ( ! PRAutoBlogger_Run_State::reopen( $run_id ) ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'The run could not be reopened for new spend.', 'prautoblogger' ) );
return;
}
if ( ! PRAutoBlogger_Run_Stage_Rerun_State::restart( $run_id, $stage, $agent_role, $item_key, true ) ) {
PRAutoBlogger_Rerun_Job_Support::restore_terminal( $run_id, $previous_status );
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'The stage row could not be demoted for replay (it may be executing).', 'prautoblogger' ) );
return;
}
// Guardrail 3: explicit, visible downstream invalidation.
PRAutoBlogger_Run_Stage_Rerun_State::mark_stale( $run_id, $item_key, PRAutoBlogger_Rerun_Eligibility::downstream_of( $stage ) );
PRAutoBlogger_Rerun_Job_Support::broadcast(
sprintf(
/* translators: %s: stage display label. */
__( 'Re-running %s with the edited input…', 'prautoblogger' ),
PRAutoBlogger_Stage_Display_Map::label( $stage )
)
);
$result = PRAutoBlogger_Stage_Replay::run( $run_id, $stage, $agent_role, $item_key, $body );
PRAutoBlogger_Run_State::mark_status( $run_id, 'done' );
PRAutoBlogger_Rerun_Job_Support::finish_complete( $result['cost'] );
} catch ( PRAutoBlogger_Cost_Ceiling_Exception $e ) {
// Governor already halted the run + recorded the overage.
PRAutoBlogger_Run_Stage_State::fail( $run_id, $stage, $agent_role, $item_key );
PRAutoBlogger_Rerun_Job_Support::finish_error( $e->getMessage() );
} catch ( \Throwable $e ) {
PRAutoBlogger_Run_Stage_State::fail( $run_id, $stage, $agent_role, $item_key );
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
PRAutoBlogger_Logger::instance()->error(
sprintf( 'Stage replay %s for run %s/%s: %s', get_class( $e ), $run_id, $stage, $e->getMessage() ),
'rerun'
);
PRAutoBlogger_Rerun_Job_Support::finish_error( $e->getMessage() );
} finally {
PRAutoBlogger_Generation_Lock::release();
}
}
/**
* Cron handler: re-run from a stage — demote it + downstream, then
* re-enter the worker so demoted stages rebuild from current
* upstream snapshots.
*
* Side effects: run_stages/runs mutations, worker LLM calls
* (governed), post refresh, status transient, lock acquire/release.
*
* @param string $run_id Run UUID.
* @param int $post_id Post the dossier acted on.
* @param string $stage Target stage (start of the rebuild set).
* @param string $item_key Item key.
* @return void
*/
public function on_rebuild_job( string $run_id, int $post_id, string $stage, string $item_key ): void {
PRAutoBlogger_Rerun_Job_Support::harden_process();
if ( ! PRAutoBlogger_Rerun_Job_Support::acquire_lock_or_report() ) {
return;
}
try {
// require_idle_lock=false: THIS handler owns the lock.
$check = PRAutoBlogger_Rerun_Eligibility::check_rebuild( $run_id, $post_id, $stage, $item_key, false );
if ( ! $check['ok'] ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( $check['reason'] );
return;
}
if ( PRAutoBlogger_Rerun_Job_Support::monthly_budget_exceeded() ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'Monthly API budget exceeded. Re-run not started.', 'prautoblogger' ) );
return;
}
$idea_json = PRAutoBlogger_Stage_Input_Store::get_seed( $run_id, $item_key );
$idea_data = null !== $idea_json ? json_decode( $idea_json, true ) : null;
if ( ! is_array( $idea_data ) ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'The stored idea seed could not be decoded.', 'prautoblogger' ) );
return;
}
$idea = new PRAutoBlogger_Article_Idea( $idea_data );
$job_start = current_time( 'mysql' );
$demoted = PRAutoBlogger_Rerun_Eligibility::rebuild_set( $stage );
if ( ! PRAutoBlogger_Run_State::reopen( $run_id ) ) {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'The run could not be reopened for new spend.', 'prautoblogger' ) );
return;
}
PRAutoBlogger_Run_Stage_Rerun_State::demote_to_pending( $run_id, $item_key, $demoted );
PRAutoBlogger_Rerun_Job_Support::broadcast(
sprintf(
/* translators: %s: stage display label. */
__( 'Re-running the pipeline from %s…', 'prautoblogger' ),
PRAutoBlogger_Stage_Display_Map::label( $stage )
)
);
$tracker = new PRAutoBlogger_Cost_Tracker();
$tracker->set_run_id( $run_id );
$result = ( new PRAutoBlogger_Article_Worker( $tracker ) )->generate( $idea );
// The worker traps its own failures (fail_open_for_item);
// publish-done is the success signal.
$succeeded = PRAutoBlogger_Run_Stage_State::is_done( $run_id, 'publish', '', $item_key );
// Decisions recorded while rebuilding a human-modified item
// derive from edited content — flag them (guardrail 2).
if ( PRAutoBlogger_Run_Stage_Rerun_State::item_has_human_modified( $run_id, $item_key ) ) {
PRAutoBlogger_Audit_Writer::flag_decisions_human_modified( $run_id, $demoted, $job_start );
}
PRAutoBlogger_Run_State::mark_status( $run_id, $succeeded ? 'done' : 'failed' );
if ( $succeeded ) {
PRAutoBlogger_Rerun_Job_Support::finish_complete( (float) $result['cost'] );
} else {
PRAutoBlogger_Rerun_Job_Support::finish_error( __( 'The re-run did not complete — check the Activity Log and the dossier stage states.', 'prautoblogger' ) );
}
} catch ( \Throwable $e ) {
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
PRAutoBlogger_Logger::instance()->error(
sprintf( 'Rebuild from %s %s for run %s: %s', $stage, get_class( $e ), $run_id, $e->getMessage() ),
'rerun'
);
PRAutoBlogger_Rerun_Job_Support::finish_error( $e->getMessage() );
} finally {
PRAutoBlogger_Generation_Lock::release();
}
}
}

View File

@@ -1,158 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Shared plumbing for re-run cron jobs (v0.20.0, M3).
*
* What: The queue/lock/budget/status-transient helpers both
* Rerun_Executor handlers share — extracted so the executor stays
* under the 300-line cap. The status transient writes use the M1
* Generation_Status_Poller shape so the kanban board (and the
* dossier's poll) show queued → pickup → result without any new
* polling infrastructure; the poller's existing R2/R3 orphan
* recovery covers a dead re-run process unchanged.
* Who triggers it: PRAutoBlogger_Rerun_Executor (handlers) and
* PRAutoBlogger_Dossier_Actions (queue()).
* Dependencies: Generation_Lock, Generation_Status_Poller (constants),
* Cost_Tracker, Run_State, Logger, WP-Cron.
*
* @see core/class-rerun-executor.php — The job handlers.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Rerun_Job_Support {
/**
* Schedule a re-run job and fire the cron spawner (non-blocking).
*
* The uniq argument keeps wp_schedule_single_event()'s identical-
* args dedup from swallowing a legitimate second click after a
* failed attempt within the 10-minute window.
*
* Side effects: one single cron event, status transient write,
* non-blocking loopback request.
*
* @param string $action Cron action name.
* @param array $args Handler args.
* @param string $queued_message Operator-facing "queued" copy.
* @return void
*/
public static function queue( string $action, array $args, string $queued_message ): void {
$args[] = (string) microtime( true ); // Uniqueness token.
wp_schedule_single_event( time(), $action, $args );
self::broadcast( $queued_message );
spawn_cron();
wp_remote_post(
site_url( 'wp-cron.php?doing_wp_cron=' . sprintf( '%.22F', microtime( true ) ) ),
array(
'timeout' => 0.01,
'blocking' => false,
'sslverify' => false,
)
);
}
/** Raise process limits for a background LLM job (cron context). */
public static function harden_process(): void {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
@ignore_user_abort( true );
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
@set_time_limit( 300 );
}
/**
* Acquire the global generation mutex or report the conflict.
*
* @return bool Whether the lock was acquired.
*/
public static function acquire_lock_or_report(): bool {
if ( PRAutoBlogger_Generation_Lock::acquire() ) {
return true;
}
self::finish_error( __( 'Could not acquire the generation lock — another run is in progress. Re-run again when it completes.', 'prautoblogger' ) );
return false;
}
/**
* Whether the monthly budget hard-stop blocks new spend.
*
* @return bool
*/
public static function monthly_budget_exceeded(): bool {
return ( new PRAutoBlogger_Cost_Tracker() )->is_budget_exceeded();
}
/**
* Restore a terminal run status after an aborted-but-reopened job.
*
* @param string $run_id Run UUID.
* @param string|null $status The pre-reopen status (done/failed/halted).
* @return void
*/
public static function restore_terminal( string $run_id, ?string $status ): void {
if ( null !== $status && in_array( $status, array( 'done', 'failed', 'halted' ), true ) ) {
PRAutoBlogger_Run_State::mark_status( $run_id, $status );
}
}
/**
* Update the live status transient (board + dossier polling).
*
* @param string $message Stage message.
* @return void
*/
public static function broadcast( string $message ): void {
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
array(
'status' => 'running',
'stage' => $message,
'started' => time(),
'last_updated' => time(),
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
);
}
/**
* Final transient: success (board-compatible shape).
*
* @param float $cost Job spend in USD.
* @return void
*/
public static function finish_complete( float $cost ): void {
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
array(
'status' => 'complete',
'generated' => 0,
'published' => 0,
'rejected' => 0,
'cost' => $cost,
'message' => __( 'Re-run complete.', 'prautoblogger' ),
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
);
}
/**
* Final transient: error (board-compatible shape) + log.
*
* @param string $message Operator-facing error.
* @return void
*/
public static function finish_error( string $message ): void {
PRAutoBlogger_Logger::instance()->warning( 'Re-run job: ' . $message, 'rerun' );
set_transient(
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
array(
'status' => 'error',
'message' => $message,
),
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
);
}
}

View File

@@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Per-PHP-process holder for the active pipeline run id.
*
* What: A process-scoped static slot recording which run this PHP request
* is executing, set whenever Cost_Tracker::set_run_id() is called
* (daily cron, manual generation, queued-article jobs, ideas
* browser). It lets components that are constructed without a run
* reference — the OpenRouter provider (cost-governor guard) and
* standalone Cost_Tracker instances (e.g. the image prompt
* rewriter's) — resolve the surrounding run for reservation and
* prompt-version stamping without threading a parameter through
* every constructor. Mirrors the Opik_Trace_Context precedent.
* Who triggers it: PRAutoBlogger_Cost_Tracker::set_run_id() (set);
* Cost_Governor + Cost_Tracker (read).
* Dependencies: none.
*
* @see core/class-cost-tracker.php — Sets the context on set_run_id().
* @see core/class-cost-governor.php — Reads it to guard LLM calls.
*/
class PRAutoBlogger_Run_Context {
/** @var string|null Active run id for this PHP process, or null. */
private static ?string $run_id = null;
/**
* Record the active run id for this process.
*
* @param string $run_id Pipeline run UUID.
* @return void
*/
public static function set_run_id( string $run_id ): void {
if ( '' !== $run_id ) {
self::$run_id = $run_id;
}
}
/**
* The active run id for this process, or null outside any run.
*
* @return string|null
*/
public static function current_run_id(): ?string {
return self::$run_id;
}
/**
* Clear the context (tests / end of run).
*
* @return void
*/
public static function clear(): void {
self::$run_id = null;
}
}

View File

@@ -1,276 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Daily sweep for stuck runs + audit-payload retention (extends #19).
*
* What: Rides the EXISTING `prautoblogger_reap_orphan_research_rows` cron
* (no new schedule) alongside the v0.8.1 Research_Reaper. Three jobs:
* 1. Stage sweep — run_stages rows stuck `running` longer than
* 2× the stage's expected wall-clock are marked `failed`
* (Hostinger kills PHP at ~120s; a stage "running" for 10+
* minutes is dead, its process gone).
* 2. Run sweep — runs rows still open (pending/running) with no
* ledger/state activity for 2× the expected run wall-clock are
* marked `failed` and their non-done stages reaped to `failed`;
* such runs render as "incomplete" via incomplete_runs().
* 3. Retention — `request_json` on generation_log, stage output
* payloads (`meta_json` on run_stages) are NULLed after R days;
* payloads, and stage_inputs human-fork bodies (v0.20.0);
* R comes from the `prautoblogger_request_json_retention_days`
* SETTING (default constant 14; 0 = keep forever) — never a
* literal at the point of use.
* Who triggers it: WP-Cron `prautoblogger_reap_orphan_research_rows`
* (daily 03:15, registered in class-prautoblogger.php).
* Dependencies: Run_State, Run_Stage_State, WordPress $wpdb, Logger.
*
* @see core/class-research-reaper.php — The #19 orphan-cost reaper (same cron).
* @see core/class-run-state.php — Run rows swept here.
* @see ARCHITECTURE.md #21 — Design rationale.
*/
class PRAutoBlogger_Run_Reaper {
/**
* Expected per-stage wall-clock seconds (sweep threshold = 2×). An
* engineering constant (like Research_Reaper::GRACE_WINDOW_SECONDS),
* overridable per stage via the
* `prautoblogger_filter_stage_expected_seconds` filter.
*/
private const EXPECTED_STAGE_SECONDS = 300;
/**
* Expected whole-run wall-clock seconds (collect + analyze + up to 10
* chained articles ≈ 30 min worst case). Sweep threshold = 2×.
* Overridable via `prautoblogger_filter_expected_run_seconds`.
*/
private const EXPECTED_RUN_SECONDS = 1800;
/**
* Cron action handler — entrypoint. Pure delegate, never throws.
*
* @return void
*/
public static function on_cron(): void {
self::reap();
}
/**
* Run all three sweeps. Returns a summary (cron path ignores it).
*
* Side effects: UPDATEs on run_stages / runs / generation_log; INFO
* log lines for swept runs.
*
* @return array{stages_failed: int, runs_failed: int, payloads_pruned: int}
*/
public static function reap(): array {
$stats = array(
'stages_failed' => 0,
'runs_failed' => 0,
'payloads_pruned' => 0,
);
try {
$stats['stages_failed'] = self::sweep_stuck_stages();
$stats['runs_failed'] = self::sweep_stuck_runs();
$stats['payloads_pruned'] = self::prune_payloads();
} catch ( \Throwable $e ) {
PRAutoBlogger_Logger::instance()->warning(
'Run reaper encountered an error: ' . $e->getMessage(),
'run-reaper'
);
}
return $stats;
}
/**
* Runs that died mid-pipeline, for audit surfaces: failed/halted runs
* that still have non-done stage rows ("incomplete").
*
* @param int $limit Max rows (default 20).
* @return array<int, array<string, mixed>>
*/
public static function incomplete_runs( int $limit = 20 ): array {
if ( ! PRAutoBlogger_Run_State::is_available() || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return array();
}
global $wpdb;
$runs = PRAutoBlogger_Run_State::table_name();
$stages = PRAutoBlogger_Run_Stage_State::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT r.* FROM {$runs} r
WHERE r.status IN ('failed','halted')
AND EXISTS (SELECT 1 FROM {$stages} s WHERE s.run_id = r.run_id AND s.status != 'done')
ORDER BY r.updated_at DESC LIMIT %d",
$limit
),
ARRAY_A
);
return is_array( $rows ) ? $rows : array();
}
/**
* Stage sweep: `running` rows older than 2× expected stage wall-clock
* become `failed`.
*
* @return int Rows swept.
*/
private static function sweep_stuck_stages(): int {
if ( ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return 0;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
/**
* Filter the expected per-stage wall-clock seconds used by the
* stuck-stage sweep (threshold is 2× this value).
*
* @param int $seconds Expected seconds (default 300).
*/
$expected = (int) apply_filters( 'prautoblogger_filter_stage_expected_seconds', self::EXPECTED_STAGE_SECONDS );
$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( 2 * $expected ) );
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$swept = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET status = 'failed', updated_at = %s, finished_at = %s
WHERE status = 'running' AND updated_at < %s",
$now,
$now,
$cutoff
)
);
return is_numeric( $swept ) ? (int) $swept : 0;
}
/**
* Run sweep: open runs with no activity for 2× expected run wall-clock
* are marked `failed`; their pending/running stages are reaped.
*
* @return int Runs swept.
*/
private static function sweep_stuck_runs(): int {
if ( ! PRAutoBlogger_Run_State::is_available() ) {
return 0;
}
global $wpdb;
$runs = PRAutoBlogger_Run_State::table_name();
/**
* Filter the expected whole-run wall-clock seconds used by the
* stuck-run sweep (threshold is 2× this value).
*
* @param int $seconds Expected seconds (default 1800).
*/
$expected = (int) apply_filters( 'prautoblogger_filter_expected_run_seconds', self::EXPECTED_RUN_SECONDS );
$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( 2 * $expected ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$stuck = $wpdb->get_col(
$wpdb->prepare(
"SELECT run_id FROM {$runs} WHERE status IN ('pending','running') AND updated_at < %s",
$cutoff
)
);
if ( ! is_array( $stuck ) || empty( $stuck ) ) {
return 0;
}
$swept = 0;
foreach ( $stuck as $run_id ) {
$run_id = (string) $run_id;
if ( ! PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' ) ) {
continue;
}
self::reap_open_stages( $run_id );
PRAutoBlogger_Logger::instance()->info(
sprintf( 'Run %s stuck past 2x expected wall-clock — marked failed (renders as incomplete).', $run_id ),
'run-reaper'
);
++$swept;
}
return $swept;
}
/**
* Mark a failed run's pending/running stage rows as failed.
*
* @param string $run_id Run UUID.
* @return void
*/
private static function reap_open_stages( string $run_id ): void {
if ( ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET status = 'failed', updated_at = %s, finished_at = %s
WHERE run_id = %s AND status IN ('pending','running')",
$now,
$now,
$run_id
)
);
}
/**
* Retention: NULL heavy payloads older than R days. R is read from the
* `prautoblogger_request_json_retention_days` setting at every call
* (default = PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS;
* 0 or negative = keep forever).
*
* @return int Rows pruned (both tables combined).
*/
private static function prune_payloads(): int {
$days = (int) get_option(
'prautoblogger_request_json_retention_days',
PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS
);
if ( $days <= 0 ) {
return 0;
}
global $wpdb;
$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );
$pruned = 0;
$gen_log = $wpdb->prefix . 'prautoblogger_generation_log';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$result = $wpdb->query(
$wpdb->prepare(
"UPDATE {$gen_log} SET request_json = NULL WHERE request_json IS NOT NULL AND created_at < %s",
$cutoff
)
);
$pruned += is_numeric( $result ) ? (int) $result : 0;
if ( PRAutoBlogger_Run_Stage_State::is_available() ) {
$stages = PRAutoBlogger_Run_Stage_State::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$result = $wpdb->query(
$wpdb->prepare(
"UPDATE {$stages} SET meta_json = NULL WHERE meta_json IS NOT NULL AND updated_at < %s",
$cutoff
)
);
$pruned += is_numeric( $result ) ? (int) $result : 0;
}
// v0.20.0: human edit-fork bodies ride the same retention (seed
// rows are kept — structural, ~1KB). A pruned fork can no longer
// be replayed; the dossier explains that state honestly.
$pruned += PRAutoBlogger_Stage_Input_Store::prune_human_bodies( $cutoff );
return $pruned;
}
}

View File

@@ -1,172 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Operator-action state mutations for edit + re-run (v0.20.0, M3).
*
* What: The ONLY paths that may demote a 'done' run_stages row — and all
* of them are deliberate operator actions dispatched from the
* dossier (never reachable from pipeline resume code):
* - restart(): done/failed/halted/pending → running for a single-
* stage replay; bumps attempt, clears stale, sets human_modified
* when the replay uses an edited input fork (CPO guardrail 2).
* - mark_stale(): flags downstream 'done' stages as stale after an
* upstream edit enters execution. Stale is a COLUMN, not a
* status: the stage stays 'done', so resume-without-recharge
* logic can never silently re-run it (CPO guardrail 3 holds by
* construction). Only Run_Stage_Writes::done() clears it.
* - demote_to_pending(): re-run-from-here demotion; the worker
* re-entry then rebuilds those stages from current upstream
* snapshots. Audit columns (attempt, human_modified) survive;
* old meta_json survives until overwritten by the fresh done().
* Every method no-ops when the run_stages table is missing.
* Who triggers it: PRAutoBlogger_Rerun_Executor (cron handlers, after
* re-validating eligibility under the generation lock).
* Dependencies: Run_Stage_State (probe/table), $wpdb.
*
* @see core/class-rerun-executor.php — Sole caller.
* @see core/class-run-stage-writes.php — Pipeline-path writes (done clears stale).
* @see core/class-rerun-eligibility.php — Policy gates before any mutation.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Run_Stage_Rerun_State {
/**
* Demote one stage row to 'running' for an operator replay.
*
* Allowed from done/failed/halted/pending — never from 'running'
* (a concurrently executing stage cannot be restarted). Bumps the
* attempt counter, clears `stale` (the row is being refreshed) and
* sets `human_modified` when the replay executes an edited fork.
* `human_modified` is never cleared by any code path — it is sticky
* audit state for the life of the run.
*
* Side effects: one UPDATE on run_stages.
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Agent role (resolved by the caller from the actual row).
* @param string $item_key Item key.
* @param bool $human_modified Whether an edited input fork drives this replay.
* @return bool Whether a row was demoted.
*/
public static function restart( string $run_id, string $stage, string $agent_role, string $item_key, bool $human_modified ): bool {
if ( '' === $run_id || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return false;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table}
SET status = 'running', attempt = attempt + 1, stale = 0,
human_modified = IF(%d = 1, 1, human_modified),
updated_at = %s, finished_at = NULL
WHERE run_id = %s AND stage = %s AND agent_role = %s AND item_key = %s
AND status IN ('done','failed','halted','pending')",
$human_modified ? 1 : 0,
$now,
$run_id,
$stage,
$agent_role,
$item_key
)
);
return 1 === (int) $updated;
}
/**
* Flag a set of 'done' stages as stale (explicit downstream
* invalidation after an upstream edit/re-run — CPO guardrail 3).
*
* Nothing is demoted and nothing auto-re-runs: the rows stay 'done'
* and visible; the operator triggers each subsequent stage (or
* re-run-from-here) deliberately.
*
* @param string $run_id Run UUID.
* @param string $item_key Item key.
* @param array<string> $stages Stage names to flag.
* @return int Rows flagged.
*/
public static function mark_stale( string $run_id, string $item_key, array $stages ): int {
if ( '' === $run_id || empty( $stages ) || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return 0;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$placeholders = implode( ',', array_fill( 0, count( $stages ), '%s' ) );
$params = array_merge( array( current_time( 'mysql' ), $run_id, $item_key ), array_values( $stages ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is a fixed %s list.
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET stale = 1, updated_at = %s
WHERE run_id = %s AND item_key = %s AND status = 'done' AND stage IN ({$placeholders})",
$params
)
);
return is_numeric( $updated ) ? (int) $updated : 0;
}
/**
* Demote a set of stages to 'pending' for re-run-from-here.
*
* The pipeline's resume machinery treats pending stages as not-done
* and re-executes them with prompts REBUILT from current upstream
* snapshots — that is how an upstream edit propagates downstream.
* Rows keep attempt/human_modified (audit) and their old meta_json
* until the fresh completion overwrites it; `stale` stays 1 until
* Run_Stage_Writes::done() clears it on fresh output. Never touches
* a 'running' row.
*
* @param string $run_id Run UUID.
* @param string $item_key Item key.
* @param array<string> $stages Stage names to demote.
* @return int Rows demoted.
*/
public static function demote_to_pending( string $run_id, string $item_key, array $stages ): int {
if ( '' === $run_id || empty( $stages ) || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return 0;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$placeholders = implode( ',', array_fill( 0, count( $stages ), '%s' ) );
$params = array_merge( array( current_time( 'mysql' ), $run_id, $item_key ), array_values( $stages ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is a fixed %s list.
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET status = 'pending', stale = 1, updated_at = %s, finished_at = NULL
WHERE run_id = %s AND item_key = %s AND status != 'running' AND stage IN ({$placeholders})",
$params
)
);
return is_numeric( $updated ) ? (int) $updated : 0;
}
/**
* Whether any stage row of this item carries the human_modified flag
* (drives derived-decision flagging during rebuilds — guardrail 2).
*
* @param string $run_id Run UUID.
* @param string $item_key Item key.
* @return bool
*/
public static function item_has_human_modified( string $run_id, string $item_key ): bool {
if ( '' === $run_id || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return false;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$found = $wpdb->get_var(
$wpdb->prepare(
"SELECT 1 FROM {$table} WHERE run_id = %s AND item_key = %s AND human_modified = 1 LIMIT 1",
$run_id,
$item_key
)
);
return null !== $found;
}
}

View File

@@ -1,271 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Per-run per-stage state machine over `wp_prautoblogger_run_stages`.
*
* One row per (run_id, stage, agent_role, item_key) holding
* pending|running|done|failed|halted plus the output snapshot (meta_json).
* Done stages are sticky and never re-charged on resume. Self-healing:
* a missing table degrades every method to a no-op/false.
*
* v0.18.2: role is resolved from Stage_Display_Map when caller passes ''
* so start/done/is_done/get_output are always symmetric. Explicit non-empty
* roles (Phase-2 fan-out) are honoured as-is. get() falls back to role=''
* on miss for mid-run-upgrade compat with v0.18.1 rows.
*
* v0.20.0: write bodies extracted to PRAutoBlogger_Run_Stage_Writes (the
* M2 split pattern — this class was at the 300-line cap); the public API
* here is unchanged and delegates. Operator-action mutations (replay
* restart, stale marking, re-run demotion) live in
* PRAutoBlogger_Run_Stage_Rerun_State only.
*
* @see core/class-run-stage-writes.php — Extracted write bodies.
* @see core/class-run-stage-rerun-state.php — M3 operator-action writes.
* @see core/class-run-state.php — Run-level lifecycle + ledger row.
* @see core/class-run-reaper.php — Sweeps stages stuck in 'running'.
* @see ARCHITECTURE.md #22 / #24 — Substrate + edit/re-run design.
*/
class PRAutoBlogger_Run_Stage_State {
/** @var bool|null Per-request "run_stages table exists" probe result. */
private static ?bool $table_ok = null;
/** @return string Fully-qualified run_stages table name. */
public static function table_name(): string {
global $wpdb;
return $wpdb->prefix . 'prautoblogger_run_stages';
}
/**
* Whether the run_stages table exists and is queryable. Cached per request.
*
* @return bool
*/
public static function is_available(): bool {
if ( null !== self::$table_ok ) {
return self::$table_ok;
}
global $wpdb;
if ( null === $wpdb ) {
return false;
}
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
self::$table_ok = ( $found === $table );
return self::$table_ok;
}
/**
* Stable 16-hex hash for one article idea within a run.
*
* @param PRAutoBlogger_Article_Idea $idea The idea.
* @return string
*/
public static function idea_hash( PRAutoBlogger_Article_Idea $idea ): string {
return substr( md5( $idea->get_suggested_title() . '|' . $idea->get_topic() ), 0, 16 );
}
/**
* Stage item_key for an article idea ('' reserved for run-level stages).
*
* @param PRAutoBlogger_Article_Idea $idea The idea.
* @return string e.g. 'idea:1a2b3c4d5e6f7a8b'.
*/
public static function item_key_for_idea( PRAutoBlogger_Article_Idea $idea ): string {
return 'idea:' . self::idea_hash( $idea );
}
/**
* Mark a stage as running. Sticky: done stages are never demoted.
* Delegates to Run_Stage_Writes (v0.20.0 split — behavior unchanged).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name (see Stage_Display_Map).
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope ('' for run-level stages).
*/
public static function start( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void {
PRAutoBlogger_Run_Stage_Writes::start( $run_id, $stage, $agent_role, $item_key );
}
/**
* Mark a stage done and persist its output for resume-without-recharge.
* Delegates to Run_Stage_Writes (v0.20.0 split; fresh completion also
* clears the `stale` flag there).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
* @param string|null $output Stage output snapshot (pruned after R days).
* @param float $cost_usd Cost attributed to this stage.
*/
public static function done( string $run_id, string $stage, string $agent_role = '', string $item_key = '', ?string $output = null, float $cost_usd = 0.0 ): void {
PRAutoBlogger_Run_Stage_Writes::done( $run_id, $stage, $agent_role, $item_key, $output, $cost_usd );
}
/**
* Mark a stage failed (does not demote a done stage). Delegates to
* Run_Stage_Writes (v0.20.0 split — behavior unchanged).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
*/
public static function fail( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void {
PRAutoBlogger_Run_Stage_Writes::fail( $run_id, $stage, $agent_role, $item_key );
}
/**
* 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 $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
* @return array<string, mixed>|null
*/
public static function get( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): ?array {
if ( '' === $run_id || ! self::is_available() ) {
return null;
}
$agent_role = PRAutoBlogger_Run_Stage_Writes::resolve_role( $stage, $agent_role );
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE run_id = %s AND stage = %s AND agent_role = %s AND item_key = %s",
$run_id,
$stage,
$agent_role,
$item_key
),
ARRAY_A
);
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;
}
/**
* Whether a stage already completed (resume entry-point check).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
* @return bool
*/
public static function is_done( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): bool {
$row = self::get( $run_id, $stage, $agent_role, $item_key );
return null !== $row && 'done' === $row['status'];
}
/**
* A done stage's stored output (null when absent, not done, or pruned).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
* @return string|null
*/
public static function get_output( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): ?string {
$row = self::get( $run_id, $stage, $agent_role, $item_key );
if ( null === $row || 'done' !== $row['status'] || empty( $row['meta_json'] ) ) {
return null;
}
$meta = json_decode( (string) $row['meta_json'], true );
return is_array( $meta ) && isset( $meta['output'] ) ? (string) $meta['output'] : null;
}
/**
* Fail every still-open stage of one item. Done stages are untouched.
* Delegates to Run_Stage_Writes (v0.20.0 split — behavior unchanged).
*
* @param string $run_id Run UUID.
* @param string $item_key Stage item key ('' = run-level stages).
*/
public static function fail_open_for_item( string $run_id, string $item_key ): void {
PRAutoBlogger_Run_Stage_Writes::fail_open_for_item( $run_id, $item_key );
}
/**
* All stage rows for one item of a run (plus run-level rows when
* $include_run_level), ordered by id. Read API for the rerun engine
* and the dossier's item-scoped assembly (v0.20.0).
*
* @param string $run_id Run UUID.
* @param string $item_key Item key ('idea:<hash>').
* @param bool $include_run_level Include item_key='' rows too.
* @return array<int, array<string, mixed>> Stage rows (ARRAY_A).
*/
public static function stages_for_item( string $run_id, string $item_key, bool $include_run_level = true ): array {
if ( '' === $run_id || ! self::is_available() ) {
return array();
}
global $wpdb;
$table = self::table_name();
$sql = $include_run_level
? "SELECT * FROM {$table} WHERE run_id = %s AND item_key IN (%s, '') ORDER BY id ASC"
: "SELECT * FROM {$table} WHERE run_id = %s AND item_key = %s ORDER BY id ASC";
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- assembled from two fixed literals above.
$rows = $wpdb->get_results( $wpdb->prepare( $sql, $run_id, $item_key ), ARRAY_A );
return is_array( $rows ) ? $rows : array();
}
/**
* Which of the given runs carry at least one stale stage (batched --
* feeds the Review Queue warning chips without N+1; CPO product AC:
* a stale flag is present at publish). Self-healing: missing table
* or column returns [].
*
* @param array<string> $run_ids Run UUIDs.
* @return array<string> Subset of $run_ids having stale stages.
*/
public static function runs_with_stale_stages( array $run_ids ): array {
$run_ids = array_values( array_filter( array_map( 'strval', $run_ids ) ) );
if ( empty( $run_ids ) || ! self::is_available() ) {
return array();
}
global $wpdb;
$table = self::table_name();
$placeholders = implode( ',', array_fill( 0, count( $run_ids ), '%s' ) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- $placeholders is a fixed %s list.
$rows = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT run_id FROM {$table} WHERE stale = 1 AND run_id IN ({$placeholders})",
$run_ids
)
);
return is_array( $rows ) ? array_map( 'strval', $rows ) : array();
}
/** Reset per-request caches (tests). */
public static function flush_cache(): void {
self::$table_ok = null;
}
}

View File

@@ -1,222 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Pipeline-path write operations over `wp_prautoblogger_run_stages`.
*
* Extracted from PRAutoBlogger_Run_Stage_State in v0.20.0 so that class
* stays under the 300-line cap (the M2 class-split pattern): start/done/
* fail/fail_open_for_item bodies moved here verbatim; Run_Stage_State
* keeps thin delegating proxies, so every existing call site is
* unchanged. One M3 behavior delta, isolated in done(): a freshly
* completed stage clears its `stale` flag (fresh output is never stale),
* with a self-healing legacy retry for half-migrated schemas that lack
* the v0.20.0 columns (same retry pattern as Cost_Tracker v0.18.0).
*
* Operator-action mutations (restart/mark_stale/demote) live in
* PRAutoBlogger_Run_Stage_Rerun_State, not here.
*
* Triggered by: PRAutoBlogger_Run_Stage_State proxies (pipeline call sites).
* Dependencies: Run_Stage_State (table probe), Stage_Display_Map (role).
*
* @see core/class-run-stage-state.php — Public API + read methods.
* @see core/class-run-stage-rerun-state.php — M3 operator-action writes.
* @see ARCHITECTURE.md #22 / #24 — Substrate + edit/re-run design.
*/
class PRAutoBlogger_Run_Stage_Writes {
/**
* Mark a stage as running. Sticky: done stages are never demoted.
*
* @param string $run_id Run UUID.
* @param string $stage Stage name (see Stage_Display_Map).
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope ('' for run-level stages).
*/
public static function start( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void {
if ( '' === $run_id || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return;
}
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"INSERT INTO {$table}
(run_id, stage, agent_role, item_key, status, attempt, started_at, updated_at)
VALUES (%s, %s, %s, %s, 'running', 1, %s, %s)
ON DUPLICATE KEY UPDATE
attempt = IF(status = 'done', attempt, attempt + 1),
status = IF(status = 'done', 'done', 'running'),
updated_at = VALUES(updated_at)",
$run_id,
$stage,
$agent_role,
$item_key,
$now,
$now
)
);
}
/**
* Mark a stage done and persist its output for resume-without-recharge.
*
* v0.20.0: a fresh completion clears the `stale` flag (and never
* touches `human_modified` — that flag is sticky run audit). When the
* site's schema predates the v0.20.0 columns (cron fired before the
* admin_init migration pass), the write self-heals by retrying the
* pre-v0.20.0 statement instead of losing the checkpoint.
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
* @param string|null $output Stage output snapshot (pruned after R days).
* @param float $cost_usd Cost attributed to this stage.
*/
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 || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return;
}
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$now = current_time( 'mysql' );
$meta = null !== $output ? wp_json_encode( array( 'output' => $output ) ) : null;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$result = $wpdb->query(
$wpdb->prepare(
"INSERT INTO {$table}
(run_id, stage, agent_role, item_key, status, attempt, cost_usd, meta_json, stale, started_at, updated_at, finished_at)
VALUES (%s, %s, %s, %s, 'done', 1, %f, %s, 0, %s, %s, %s)
ON DUPLICATE KEY UPDATE
status = 'done',
cost_usd = VALUES(cost_usd),
meta_json = VALUES(meta_json),
stale = 0,
updated_at = VALUES(updated_at),
finished_at = VALUES(finished_at)",
$run_id,
$stage,
$agent_role,
$item_key,
$cost_usd,
$meta,
$now,
$now,
$now
)
);
// Self-healing on a half-migrated schema (no `stale` column yet):
// retry with the pre-v0.20.0 statement rather than losing the
// resume checkpoint. Same pattern as Cost_Tracker (v0.18.0).
if ( false === $result ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"INSERT INTO {$table}
(run_id, stage, agent_role, item_key, status, attempt, cost_usd, meta_json, started_at, updated_at, finished_at)
VALUES (%s, %s, %s, %s, 'done', 1, %f, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
status = 'done',
cost_usd = VALUES(cost_usd),
meta_json = VALUES(meta_json),
updated_at = VALUES(updated_at),
finished_at = VALUES(finished_at)",
$run_id,
$stage,
$agent_role,
$item_key,
$cost_usd,
$meta,
$now,
$now,
$now
)
);
}
}
/**
* Mark a stage failed (does not demote a done stage).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Fan-out dimension ('' = resolve from stage map).
* @param string $item_key Article scope.
*/
public static function fail( string $run_id, string $stage, string $agent_role = '', string $item_key = '' ): void {
if ( '' === $run_id || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return;
}
$agent_role = self::resolve_role( $stage, $agent_role );
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET status = 'failed', updated_at = %s, finished_at = %s
WHERE run_id = %s AND stage = %s AND agent_role = %s AND item_key = %s AND status != 'done'",
$now,
$now,
$run_id,
$stage,
$agent_role,
$item_key
)
);
}
/**
* Fail every still-open stage of one item. Done stages are untouched.
*
* @param string $run_id Run UUID.
* @param string $item_key Stage item key ('' = run-level stages).
*/
public static function fail_open_for_item( string $run_id, string $item_key ): void {
if ( '' === $run_id || ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return;
}
global $wpdb;
$table = PRAutoBlogger_Run_Stage_State::table_name();
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET status = 'failed', updated_at = %s, finished_at = %s
WHERE run_id = %s AND item_key = %s AND status IN ('pending','running')",
$now,
$now,
$run_id,
$item_key
)
);
}
/**
* 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).
*
* Public in v0.20.0 (was private on Run_Stage_State) so the read API
* and the rerun classes share one resolution source.
*
* @param string $stage Stage name.
* @param string $agent_role Caller-supplied role ('' = auto-resolve).
* @return string Effective agent role.
*/
public 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

@@ -1,294 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Run-level state: the `wp_prautoblogger_runs` ledger + lifecycle row.
*
* What: One row per pipeline run (keyed by run_id UUID) carrying the run
* status (pending|running|done|failed|halted), the per-run cost
* ledger the Cost_Governor reserves against (ceiling / reserved /
* settled / overage), and the prompt versions pinned at run start.
* Every method is self-healing: a missing table (half-migrated
* site) degrades to no-ops/empty reads, never a fatal. Final states
* are sticky — a halted or failed run cannot be flipped back to
* running by a late writer. Per-stage state lives in
* PRAutoBlogger_Run_Stage_State (run_stages table).
* Who triggers it: Cost_Tracker::set_run_id() (ensure_run + pinning),
* Cost_Governor (ledger + halt), Run_Reaper (stuck-run sweep),
* Review Queue (halted-run surfacing), Pipeline_Runner (completion).
* Dependencies: WordPress $wpdb, get_option (ceiling setting), wp_json_encode.
*
* @see core/class-cost-governor.php — Reserves against this row atomically.
* @see core/class-prompt-registry.php — Reads/writes pins via this class.
* @see core/class-run-stage-state.php — Per-stage rows (commit 4).
* @see ARCHITECTURE.md #21 — Design rationale.
*/
class PRAutoBlogger_Run_State {
/** @var bool|null Per-request "runs table exists" probe result. */
private static ?bool $table_ok = null;
/** Fully-qualified runs table name (shared with Cost_Governor). */
public static function table_name(): string {
global $wpdb;
return $wpdb->prefix . 'prautoblogger_runs';
}
/**
* Whether the runs table exists and is queryable. Cached per request;
* never throws.
*
* @return bool
*/
public static function is_available(): bool {
if ( null !== self::$table_ok ) {
return self::$table_ok;
}
global $wpdb;
if ( null === $wpdb ) {
return false; // Not cached: $wpdb may appear later in boot.
}
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
self::$table_ok = ( $found === $table );
return self::$table_ok;
}
/**
* The per-run cost ceiling, read from the SETTING at call time
* (never a literal at the point of use). 0 disables the per-run guard.
*
* @return float Ceiling in USD.
*/
public static function ceiling_setting(): float {
return (float) get_option( 'prautoblogger_per_run_cost_ceiling_usd', PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD );
}
/**
* Create the run row if it does not exist (INSERT IGNORE — concurrent
* callers cannot double-create). Snapshots the ceiling setting at run
* start so a mid-run settings change cannot move the goalposts.
*
* Side effects: one INSERT IGNORE.
*
* @param string $run_id Pipeline run UUID.
* @return void
*/
public static function ensure_run( string $run_id ): void {
if ( '' === $run_id || ! self::is_available() ) {
return;
}
global $wpdb;
$table = self::table_name();
$now = current_time( 'mysql' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"INSERT IGNORE INTO {$table}
(run_id, status, ceiling_usd, reserved_usd, settled_usd, overage_usd, started_at, updated_at)
VALUES (%s, 'running', %f, 0, 0, 0, %s, %s)",
$run_id,
self::ceiling_setting(),
$now,
$now
)
);
}
/**
* Fetch a run row.
*
* @param string $run_id Pipeline run UUID.
* @return array<string, mixed>|null Row, or null when absent/unavailable.
*/
public static function get_run( string $run_id ): ?array {
if ( '' === $run_id || ! self::is_available() ) {
return null;
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$row = $wpdb->get_row(
$wpdb->prepare( "SELECT * FROM {$table} WHERE run_id = %s", $run_id ),
ARRAY_A
);
return is_array( $row ) ? $row : null;
}
/**
* Current run status, or null when the run has no row.
*
* @param string $run_id Pipeline run UUID.
* @return string|null pending|running|done|failed|halted, or null.
*/
public static function get_status( string $run_id ): ?string {
$run = self::get_run( $run_id );
return null !== $run ? (string) $run['status'] : null;
}
/**
* Store the pinned prompt versions — only if the run has none yet, so
* a resumed run keeps the versions it started with.
*
* @param string $run_id Pipeline run UUID.
* @param array<string, int> $pins prompt_key => version map.
* @return void
*/
public static function set_pins_if_absent( string $run_id, array $pins ): void {
if ( '' === $run_id || empty( $pins ) || ! self::is_available() ) {
return;
}
self::ensure_run( $run_id );
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET pinned_prompts_json = %s, updated_at = %s
WHERE run_id = %s AND (pinned_prompts_json IS NULL OR pinned_prompts_json = '')",
wp_json_encode( $pins ),
current_time( 'mysql' ),
$run_id
)
);
}
/**
* The pinned prompt versions for a run.
*
* @param string $run_id Pipeline run UUID.
* @return array<string, int> prompt_key => version ({} when none).
*/
public static function get_pins( string $run_id ): array {
$run = self::get_run( $run_id );
if ( null === $run || empty( $run['pinned_prompts_json'] ) ) {
return array();
}
$pins = json_decode( (string) $run['pinned_prompts_json'], true );
return is_array( $pins ) ? array_map( 'intval', $pins ) : array();
}
/**
* Move a run to a new status. Forward transitions only touch open
* (pending/running) runs; `halted` and `failed` are sticky and `done`
* cannot overwrite them.
*
* @param string $run_id Pipeline run UUID.
* @param string $status One of done|failed|halted|running.
* @return bool True when a row transitioned.
*/
public static function mark_status( string $run_id, string $status ): bool {
if ( '' === $run_id || ! self::is_available() ) {
return false;
}
if ( ! in_array( $status, array( 'running', 'done', 'failed', 'halted' ), true ) ) {
return false;
}
global $wpdb;
$table = self::table_name();
$now = current_time( 'mysql' );
$finished = in_array( $status, array( 'done', 'failed', 'halted' ), true ) ? $now : null;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET status = %s, updated_at = %s, finished_at = %s
WHERE run_id = %s AND status IN ('pending','running')",
$status,
$now,
$finished,
$run_id
)
);
return $updated >= 1;
}
/**
* Record by how much a breaching reservation exceeded the ceiling.
*
* @param string $run_id Pipeline run UUID.
* @param float $overage USD amount over the ceiling.
* @return void
*/
public static function record_overage( string $run_id, float $overage ): void {
if ( '' === $run_id || $overage <= 0 || ! self::is_available() ) {
return;
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET overage_usd = GREATEST(overage_usd, %f), updated_at = %s WHERE run_id = %s",
$overage,
current_time( 'mysql' ),
$run_id
)
);
}
/**
* Recent halted runs, for the Review Queue surface.
*
* @param int $limit Max rows (default 10).
* @return array<int, array<string, mixed>>
*/
public static function halted_runs( int $limit = 10 ): array {
if ( ! self::is_available() ) {
return array();
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE status = 'halted' ORDER BY updated_at DESC LIMIT %d",
$limit
),
ARRAY_A
);
return is_array( $rows ) ? $rows : array();
}
/**
* Reopen a terminal run for operator-deliberate new spend (M3
* re-runs). done/failed/halted -> running; finished_at cleared; the
* cost ceiling is RE-SNAPSHOTTED from the current setting — the
* deliberate re-run action adopts the operator's current per-run
* policy (can lower as well as raise), exactly as a new run would.
* Accumulated reserved/settled spend is kept: the governor treats
* re-runs as new spend on the SAME run (CPO guardrail 4).
*
* The conditional UPDATE is the atomic gate: an actively executing
* run (pending/running) can never be reopened.
*
* @param string $run_id Run UUID.
* @return bool Whether the run transitioned to running.
*/
public static function reopen( string $run_id ): bool {
if ( '' === $run_id || ! self::is_available() ) {
return false;
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table}
SET status = 'running', ceiling_usd = %f, updated_at = %s, finished_at = NULL
WHERE run_id = %s AND status IN ('done','failed','halted')",
self::ceiling_setting(),
current_time( 'mysql' ),
$run_id
)
);
return 1 === (int) $updated;
}
/** Reset per-request caches (tests). */
public static function flush_cache(): void {
self::$table_ok = null;
}
}

View File

@@ -76,33 +76,8 @@ class PRAutoBlogger_Source_Collector {
'collector'
);
} catch ( \Throwable $e ) {
// Structured failure meta: model slug, HTTP status (parsed from message),
// 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.
PRAutoBlogger_Logger::instance()->error( sprintf( 'Collection %s from %s: %s', get_class( $e ), $source_type, $e->getMessage() ), 'collector' );
// Continue with other sources — one failure shouldn't stop everything.
}
}

View File

@@ -1,172 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Display map for every generation_log / run_stages `stage` value, old and new.
*
* What: Single source of truth that renders historical stage values
* (analysis, outline, draft, polish, review, llm_research, image_a,
* image_b, image_prompt_rewrite, opik_eval_judge), the Pipeline v2
* vocabulary (research, curate, draft, editorial, seo, publish), and
* any unknown value (humanized fallback) coherently. Also maps each
* stage to its default agent role and primary prompt-registry key so
* audit stamping never hardcodes those associations at call sites.
* The `stage` column is VARCHAR — this PHP map is the vocabulary,
* there is no SQL enum.
* Who triggers it: Cost_Tracker (stamping), audit/metrics rendering, Run_State.
* Dependencies: none — pure static lookup.
*
* @see core/class-cost-tracker.php — Derives agent_role / prompt key when not passed.
* @see core/class-prompt-registry.php — Owns the prompt keys referenced here.
* @see ARCHITECTURE.md — Stage vocabulary (canonical edit-stage name: polish).
*/
class PRAutoBlogger_Stage_Display_Map {
/**
* Stage definitions: label (translated lazily), default agent role,
* and the primary prompt-registry key the stage renders with (null
* when the stage has no registry-managed prompt).
*
* @var array<string, array{label: string, role: ?string, prompt_key: ?string}>
*/
private const MAP = array(
// ── Historical vocabulary (rows that exist on prod) ─────────────
'analysis' => array(
'label' => 'Topic Analysis',
'role' => 'analyst',
'prompt_key' => 'analysis.system',
),
'outline' => array(
'label' => 'Outline',
'role' => 'writer',
'prompt_key' => 'content.outline',
),
'draft' => array(
'label' => 'Draft',
'role' => 'writer',
'prompt_key' => 'content.draft',
),
'polish' => array(
'label' => 'Polish',
'role' => 'writer',
'prompt_key' => 'content.polish',
),
'review' => array(
'label' => 'Editorial Review',
'role' => 'editor',
'prompt_key' => 'editor.system',
),
'llm_research' => array(
'label' => 'LLM Research',
'role' => 'researcher',
'prompt_key' => 'research.system',
),
'image_a' => array(
'label' => 'Image A',
'role' => 'illustrator',
'prompt_key' => 'image.style_template',
),
'image_b' => array(
'label' => 'Image B',
'role' => 'illustrator',
'prompt_key' => 'image.style_template',
),
'image_prompt_rewrite' => array(
'label' => 'Image Prompt Rewrite',
'role' => 'illustrator',
'prompt_key' => 'image.rewriter_system',
),
'opik_eval_judge' => array(
'label' => 'Opik Eval Judge',
'role' => 'judge',
'prompt_key' => null,
),
// ── Pipeline v2 vocabulary (new runs may write these) ───────────
'research' => array(
'label' => 'Research',
'role' => 'researcher',
'prompt_key' => 'research.system',
),
'curate' => array(
'label' => 'Curate',
'role' => 'curator',
'prompt_key' => null,
),
'editorial' => array(
'label' => 'Editorial Loop',
'role' => 'editor',
'prompt_key' => null,
),
'seo' => array(
'label' => 'SEO',
'role' => 'seo',
'prompt_key' => null,
),
'publish' => array(
'label' => 'Publish',
'role' => 'publisher',
'prompt_key' => null,
),
);
/**
* Human-readable label for a stage value. Unknown stages are humanized
* (underscores to spaces, words capitalized) so the audit view never
* renders blank for a value this map predates or postdates.
*
* @param string $stage Raw stage value from the database.
* @return string Translated display label.
*/
public static function label( string $stage ): string {
if ( isset( self::MAP[ $stage ] ) ) {
// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- labels are a fixed const set.
return __( self::MAP[ $stage ]['label'], 'prautoblogger' );
}
return ucwords( str_replace( array( '_', '-' ), ' ', $stage ) );
}
/**
* Default agent role recorded for a stage when the call site does not
* pass one explicitly. Null for unknown stages (column stays NULL).
*
* @param string $stage Raw stage value.
* @return string|null Agent role slug, or null when unknown.
*/
public static function default_agent_role( string $stage ): ?string {
return self::MAP[ $stage ]['role'] ?? null;
}
/**
* Primary prompt-registry key a stage renders with. Used to resolve the
* pinned prompt_version stamped on generation_log rows when the call
* site does not pass an explicit key (e.g. single-pass passes
* 'content.single_pass' for its 'draft' row).
*
* @param string $stage Raw stage value.
* @return string|null Registry key, or null when the stage has none.
*/
public static function default_prompt_key( string $stage ): ?string {
return self::MAP[ $stage ]['prompt_key'] ?? null;
}
/**
* Whether the stage value is part of the known vocabulary.
*
* @param string $stage Raw stage value.
* @return bool True when the stage is a known historical or v2 value.
*/
public static function is_known( string $stage ): bool {
return isset( self::MAP[ $stage ] );
}
/**
* The full vocabulary, for audit listings and tests.
*
* @return array<string, array{label: string, role: ?string, prompt_key: ?string}>
*/
public static function all(): array {
return self::MAP;
}
}

View File

@@ -1,269 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* INSERT-only store over `wp_prautoblogger_stage_inputs` (v0.20.0, M3).
*
* What: Immutable input-version rows for the edit + re-run feature.
* Two row kinds, discriminated by `source`:
* - 'human': an operator's edited request body for one stage. Each
* save creates the NEXT version for the (run, stage, role, item)
* scope — there is deliberately no UPDATE path in this class, so
* originals (and earlier forks) can never be overwritten (CPO
* guardrail 1; the executed original lives untouched in
* generation_log.request_json).
* - 'seed': the serialized Article_Idea persisted at worker start
* (stage='', version=1). Re-run-from-here reconstructs the EXACT
* idea from it — rebuilding the idea from post fields would risk
* an item_key hash mismatch (post_title is sanitized at insert)
* and a duplicate post.
* Self-healing: every method no-ops (null/false/empty) when the
* table is missing (half-migrated schema).
* Retention: human fork bodies are NULLed by the run-reaper after
* R days (same setting as all heavy payloads); seed rows are ~1KB
* structural state and are kept.
* Who triggers it: Dossier_Actions (save fork), Rerun_Executor (read fork
* / seed), Article_Worker (save seed), Run_Reaper (prune).
* Dependencies: WordPress $wpdb.
*
* @see admin/class-dossier-actions.php — Fork save endpoint.
* @see core/class-rerun-executor.php — Fork/seed consumption.
* @see core/class-run-reaper.php — Retention prune.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Stage_Input_Store {
/** Source discriminator: operator edit fork. */
public const SOURCE_HUMAN = 'human';
/** Source discriminator: idea seed persisted at worker start. */
public const SOURCE_SEED = 'seed';
/** @var bool|null Per-request "stage_inputs table exists" probe result. */
private static ?bool $table_ok = null;
/** @return string Fully-qualified stage_inputs table name. */
public static function table_name(): string {
global $wpdb;
return $wpdb->prefix . 'prautoblogger_stage_inputs';
}
/**
* Whether the stage_inputs table exists. Cached per request.
*
* @return bool
*/
public static function is_available(): bool {
if ( null !== self::$table_ok ) {
return self::$table_ok;
}
global $wpdb;
if ( null === $wpdb ) {
return false; // Not cached: $wpdb may appear later in boot.
}
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
self::$table_ok = ( $found === $table );
return self::$table_ok;
}
/**
* Save a human edit fork as the next version for its scope.
*
* INSERT-only by design. The version number is MAX(version)+1 for the
* scope; a concurrent-save collision on the UNIQUE key is retried
* once with a refreshed version.
*
* Side effects: one (rarely two) INSERTs into stage_inputs.
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Stage row's agent role.
* @param string $item_key Stage row's item key.
* @param string $request_json Edited request body (full JSON, no headers).
* @param string $author WP user login of the editor.
* @return int|null New version number, or null on failure/missing table.
*/
public static function save_fork( string $run_id, string $stage, string $agent_role, string $item_key, string $request_json, string $author ): ?int {
if ( '' === $run_id || '' === $stage || ! self::is_available() ) {
return null;
}
for ( $attempt = 0; $attempt < 2; $attempt++ ) {
$version = self::next_version( $run_id, $stage, $agent_role, $item_key );
$inserted = self::insert_row( $run_id, $stage, $agent_role, $item_key, $version, self::SOURCE_HUMAN, $request_json, $author );
if ( $inserted ) {
return $version;
}
}
return null;
}
/**
* Latest human fork row for a scope, or null when none exist.
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Agent role.
* @param string $item_key Item key.
* @return array<string, mixed>|null Row incl. version/request_json/author/created_at.
*/
public static function latest_fork( string $run_id, string $stage, string $agent_role, string $item_key ): ?array {
if ( '' === $run_id || ! self::is_available() ) {
return null;
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table}
WHERE run_id = %s AND stage = %s AND agent_role = %s AND item_key = %s AND source = %s
ORDER BY version DESC LIMIT 1",
$run_id,
$stage,
$agent_role,
$item_key,
self::SOURCE_HUMAN
),
ARRAY_A
);
return is_array( $row ) ? $row : null;
}
/**
* Persist the idea seed for one run item (INSERT-once; replays no-op).
*
* @param string $run_id Run UUID.
* @param string $item_key Item key from Run_Stage_State::item_key_for_idea().
* @param string $idea_json Serialized Article_Idea::to_array() payload.
* @return void
*/
public static function save_seed( string $run_id, string $item_key, string $idea_json ): void {
if ( '' === $run_id || '' === $item_key || ! self::is_available() ) {
return;
}
if ( null !== self::get_seed( $run_id, $item_key ) ) {
return; // Seed already persisted (idempotent resume).
}
self::insert_row( $run_id, '', '', $item_key, 1, self::SOURCE_SEED, $idea_json, 'pipeline' );
}
/**
* The idea seed JSON for one run item, or null when absent.
*
* @param string $run_id Run UUID.
* @param string $item_key Item key.
* @return string|null
*/
public static function get_seed( string $run_id, string $item_key ): ?string {
if ( '' === $run_id || ! self::is_available() ) {
return null;
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$json = $wpdb->get_var(
$wpdb->prepare(
"SELECT request_json FROM {$table}
WHERE run_id = %s AND stage = '' AND item_key = %s AND source = %s LIMIT 1",
$run_id,
$item_key,
self::SOURCE_SEED
)
);
return ( is_string( $json ) && '' !== $json ) ? $json : null;
}
/**
* Retention: NULL human fork bodies older than the cutoff. Seed rows
* are kept (structural, ~1KB). Version/author/flag metadata survives
* as the permanent audit trail.
*
* @param string $cutoff MySQL datetime; rows created before it are pruned.
* @return int Rows pruned.
*/
public static function prune_human_bodies( string $cutoff ): int {
if ( ! self::is_available() ) {
return 0;
}
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$result = $wpdb->query(
$wpdb->prepare(
"UPDATE {$table} SET request_json = NULL
WHERE source = %s AND request_json IS NOT NULL AND created_at < %s",
self::SOURCE_HUMAN,
$cutoff
)
);
return is_numeric( $result ) ? (int) $result : 0;
}
/** Reset per-request caches (tests). */
public static function flush_cache(): void {
self::$table_ok = null;
}
/**
* Next version number for a scope (1 when none exist).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Agent role.
* @param string $item_key Item key.
* @return int
*/
private static function next_version( string $run_id, string $stage, string $agent_role, string $item_key ): int {
global $wpdb;
$table = self::table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$max = $wpdb->get_var(
$wpdb->prepare(
"SELECT MAX(version) FROM {$table}
WHERE run_id = %s AND stage = %s AND agent_role = %s AND item_key = %s",
$run_id,
$stage,
$agent_role,
$item_key
)
);
return ( null !== $max ? (int) $max : 0 ) + 1;
}
/**
* Raw row INSERT (the only write path — INSERT-only by construction).
*
* @param string $run_id Run UUID.
* @param string $stage Stage name ('' for seeds).
* @param string $agent_role Agent role.
* @param string $item_key Item key.
* @param int $version Version number.
* @param string $source 'human' or 'seed'.
* @param string $request_json Payload JSON.
* @param string $author Author label.
* @return bool Whether the row was inserted.
*/
private static function insert_row( string $run_id, string $stage, string $agent_role, string $item_key, int $version, string $source, string $request_json, string $author ): bool {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$inserted = $wpdb->insert(
self::table_name(),
array(
'run_id' => $run_id,
'stage' => $stage,
'agent_role' => $agent_role,
'item_key' => $item_key,
'version' => $version,
'source' => $source,
'request_json' => $request_json,
'author' => $author,
'created_at' => current_time( 'mysql' ),
)
);
return false !== $inserted;
}
}

View File

@@ -1,189 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Executes one stage replay from a saved input fork (v0.20.0, M3).
*
* What: Decodes an immutable stage_inputs fork body back into the
* (messages, model, options) triple and sends it through the
* normal provider seam — so the cost governor's reserve-before-
* call (on the SAME run ledger row), the retry/backoff loop, the
* empty-completion guard, and the B1 request recorder all apply
* to replays exactly as to pipeline calls (CPO guardrail 4). The
* fresh output lands in the stage's run_stages snapshot (the same
* place downstream rebuilds read from) and a generation_log row
* is written with the replayed request body.
*
* options_from_body() is the exact inverse of Request_Builder::
* build_body() + apply_reasoning_budget(): the v0.18.1 reasoning
* headroom is subtracted back out (the builder re-adds it), and
* reasoning is pinned explicitly — enabled:false when the original
* body had none — so a later change to the global reasoning
* setting can never alter the replay's shape.
* Who triggers it: PRAutoBlogger_Rerun_Executor::on_replay_job() only
* (after eligibility re-validation, lock, reopen, restart and
* stale-marking).
* Dependencies: OpenRouter_Provider, Cost_Tracker, Run_Stage_State,
* Audit_Writer, Stage_Display_Map.
*
* @see core/class-rerun-executor.php — Orchestration around this.
* @see providers/class-open-router-request-builder.php — The forward transform.
* @see ARCHITECTURE.md #24 — Edit + re-run design.
*/
class PRAutoBlogger_Stage_Replay {
/**
* Reconstruct provider options from a stored request body.
*
* Inverse of build_body()/apply_reasoning_budget(): copies
* temperature/response_format; recovers the caller's max_tokens by
* subtracting the reasoning cap the builder added as headroom; pins
* reasoning explicitly (the stored body is the contract — global
* setting drift must not leak in). Adds the caller-metadata keys
* (stage, prompt_key) used by the guard's logging — never sent
* upstream.
*
* @param array<string, mixed> $body Decoded request body.
* @param string $stage Stage being replayed.
* @return array<string, mixed> Options for send_chat_completion().
*/
public static function options_from_body( array $body, string $stage ): array {
$options = array();
if ( isset( $body['temperature'] ) ) {
$options['temperature'] = $body['temperature'];
}
if ( isset( $body['response_format'] ) ) {
$options['response_format'] = $body['response_format'];
}
$reasoning_active = isset( $body['reasoning'] ) && false !== ( $body['reasoning']['enabled'] ?? true );
if ( $reasoning_active ) {
$options['reasoning'] = $body['reasoning'];
if ( isset( $body['max_tokens'] ) ) {
$cap = isset( $body['reasoning']['max_tokens'] ) ? (int) $body['reasoning']['max_tokens'] : 0;
// The builder raised max_tokens by the cap (completion
// headroom); hand back the caller-level value so the
// builder's re-application is not compounded.
$options['max_tokens'] = max( 1, (int) $body['max_tokens'] - $cap );
}
} else {
// Pin reasoning OFF (same per-call override shape the
// empty-completion retry uses) so a globally-enabled
// reasoning setting cannot reshape the replay.
$options['reasoning'] = array( 'enabled' => false );
if ( isset( $body['max_tokens'] ) ) {
$options['max_tokens'] = (int) $body['max_tokens'];
}
}
$options['stage'] = $stage;
$options['prompt_key'] = PRAutoBlogger_Stage_Display_Map::default_prompt_key( $stage );
return $options;
}
/**
* Decode + validate a fork body. Returns null when the JSON is not a
* replayable chat body (model string + non-empty messages list of
* role/content pairs).
*
* @param string $request_json Stored fork body.
* @return array<string, mixed>|null Decoded body, or null when invalid.
*/
public static function decode_body( string $request_json ): ?array {
$body = json_decode( $request_json, true );
if ( ! is_array( $body ) || empty( $body['model'] ) || ! is_string( $body['model'] ) ) {
return null;
}
if ( empty( $body['messages'] ) || ! is_array( $body['messages'] ) ) {
return null;
}
foreach ( $body['messages'] as $message ) {
if ( ! is_array( $message ) || ! isset( $message['role'], $message['content'] )
|| ! is_string( $message['role'] ) || ! is_string( $message['content'] ) ) {
return null;
}
}
return $body;
}
/**
* Execute the replay call and persist its results.
*
* The caller (Rerun_Executor) has already: re-validated eligibility,
* taken the generation lock, reopened the run, demoted the stage row
* to running and stale-marked downstream. This method performs the
* governed LLM call and the success-path writes.
*
* Side effects: one OpenRouter call (governor-reserved), run_stages
* done-write, one generation_log row (with the replayed request via
* the B1 recorder), run_decisions human_modified flags.
*
* @param string $run_id Run UUID.
* @param string $stage Stage name.
* @param string $agent_role Stage row agent role.
* @param string $item_key Stage row item key.
* @param array<string, mixed> $body Decoded fork body (from decode_body()).
* @return array{content: string, cost: float, model: string} Replay result.
*
* @throws \RuntimeException On provider failure or empty output.
* @throws PRAutoBlogger_Cost_Ceiling_Exception When the governor blocks the call.
*/
public static function run( string $run_id, string $stage, string $agent_role, string $item_key, array $body ): array {
$tracker = new PRAutoBlogger_Cost_Tracker();
// Joins this process to the run: Run_Context (governor guard),
// ledger row, prompt pins — replay spend reserves against the
// SAME per-run ceiling as the original calls (guardrail 4).
$tracker->set_run_id( $run_id );
$llm = new PRAutoBlogger_OpenRouter_Provider();
$options = self::options_from_body( $body, $stage );
$response = $llm->send_chat_completion( $body['messages'], (string) $body['model'], $options );
// Same belt as the writer path: an empty replay output must fail
// the stage, never overwrite a good snapshot with nothing.
if ( '' === trim( (string) $response['content'] ) ) {
throw new \RuntimeException(
sprintf(
/* translators: 1: stage name, 2: model identifier. */
__( 'Replay of stage "%1$s" produced empty content (model %2$s) — failing the replay instead of storing an empty output.', 'prautoblogger' ),
$stage,
(string) $response['model']
)
);
}
$cost = $llm->estimate_cost(
(string) $response['model'],
(int) $response['prompt_tokens'],
(int) $response['completion_tokens']
);
PRAutoBlogger_Run_Stage_State::done( $run_id, $stage, $agent_role, $item_key, (string) $response['content'], $cost );
$tracker->log_api_call(
null,
$stage,
$llm->get_provider_name(),
(string) $response['model'],
(int) $response['prompt_tokens'],
(int) $response['completion_tokens'],
'success',
'',
'' !== $agent_role ? $agent_role : null,
null
);
// Guardrail 2: decision rows for the replayed stage carry the
// human_modified flag (no-op when the stage has none).
PRAutoBlogger_Audit_Writer::flag_decisions_human_modified( $run_id, array( $stage ) );
return array(
'content' => (string) $response['content'],
'cost' => $cost,
'model' => (string) $response['model'],
);
}
}

View File

@@ -1,50 +0,0 @@
<?php
declare(strict_types=1);
/**
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
*
* Contract for image composers that turn raw provider bytes into final variants.
*
* A composer sits between the image provider (raw generated bytes) and the
* media sideloader. It receives one base image plus per-post context and
* returns one or more finished variants — the first is always the `featured`
* role (the bytes that become the post thumbnail), optionally followed by
* social variants (`og`, `square`). Implementations must NEVER throw out of
* compose(): on any internal failure they degrade to passing the base image
* through unmodified so publishing is never blocked.
*
* Triggered by: PRAutoBlogger_Image_Pipeline between batch results and sideload.
* Dependencies: none — this is the contract only.
*
* @see core/class-image-composer.php — Default implementation (capability ladder).
* @see core/class-image-pipeline.php — Caller.
* @see core/class-image-attacher.php — Persists the returned variants.
*/
interface PRAutoBlogger_Image_Composer_Interface {
/**
* Compose final image variant(s) from raw provider bytes.
*
* Side effects: implementations may read plugin options and write to the
* activity log; they must not make network calls or fail the publish.
*
* @param array{
* bytes: string,
* mime_type: string,
* width: int,
* height: int,
* } $image_data Base image bytes + metadata from the provider result.
* @param array{
* post_id: int,
* caption: string,
* title: string,
* slot: string,
* } $context Post ID, editorial caption, post title, and slot
* ('image_a' or 'image_b'); only image_a yields variants.
*
* @return array<int, array{bytes: string, mime_type: string, width: int, height: int, role: string}>
* Non-empty list; index 0 always carries role 'featured'.
*/
public function compose( array $image_data, array $context ): array;
}

10
includes/models/class-generation-log.php Normal file → Executable file
View File

@@ -26,8 +26,6 @@ class PRAutoBlogger_Generation_Log {
private ?string $request_json;
private string $response_status;
private ?string $error_message;
private ?string $agent_role;
private ?string $prompt_version;
private string $created_at;
/**
@@ -46,8 +44,6 @@ class PRAutoBlogger_Generation_Log {
$this->request_json = $data['request_json'] ?? null;
$this->response_status = $data['response_status'] ?? 'success';
$this->error_message = $data['error_message'] ?? null;
$this->agent_role = $data['agent_role'] ?? null;
$this->prompt_version = isset( $data['prompt_version'] ) ? (string) $data['prompt_version'] : null;
$this->created_at = $data['created_at'] ?? current_time( 'mysql' );
}
@@ -75,10 +71,6 @@ class PRAutoBlogger_Generation_Log {
return $this->response_status; }
public function get_error_message(): ?string {
return $this->error_message; }
public function get_agent_role(): ?string {
return $this->agent_role; }
public function get_prompt_version(): ?string {
return $this->prompt_version; }
public function get_created_at(): string {
return $this->created_at; }
@@ -98,8 +90,6 @@ class PRAutoBlogger_Generation_Log {
'request_json' => $this->request_json,
'response_status' => $this->response_status,
'error_message' => $this->error_message,
'agent_role' => $this->agent_role,
'prompt_version' => $this->prompt_version,
'created_at' => $this->created_at,
);
}

View File

@@ -70,7 +70,6 @@ class PRAutoBlogger_LLM_Research_Provider implements PRAutoBlogger_Source_Provid
'temperature' => 0.7,
'max_tokens' => 8000,
'response_format' => array( 'type' => 'json_object' ),
'stage' => 'llm_research',
)
);
@@ -124,9 +123,25 @@ class PRAutoBlogger_LLM_Research_Provider implements PRAutoBlogger_Source_Provid
* @return string
*/
private function build_system_prompt(): string {
// v0.18.0: renders from the versioned registry ('research.system')
// with a byte-identical in-code fallback.
return PRAutoBlogger_Prompt_Registry::render( 'research.system' );
return 'You are a deep research analyst specializing in emerging trends, '
. 'scientific developments, and community knowledge in niche health and '
. "biohacking domains. Your task is to identify substantive, actionable findings.\n\n"
. "Using your training knowledge, scan across:\n"
. "- Recent scientific literature and research directions\n"
. "- Active community discussions, debates, and evolving consensus\n"
. "- Emerging products, protocols, and methodologies gaining traction\n"
. "- Common questions, misconceptions, and points of confusion\n"
. "- Regulatory changes, safety concerns, and legal shifts\n"
. "- Gaps between what practitioners want to know and what content exists\n\n"
. "Your findings must be:\n"
. "1. SUBSTANTIVE — 2-3 paragraphs of detailed analysis per finding, not a headline\n"
. "2. ACTIONABLE — practical enough to seed a full article\n"
. "3. REALISTIC — grounded in what is actually discussed or researched; do NOT invent citations\n"
. "4. TIMELY — reflect current knowledge, recent shifts, or emerging questions\n\n"
. "Respond with valid JSON only (no preamble, no markdown fences):\n"
. '{"findings": [{"title": "string", "content": "string (2-3 paragraphs)", '
. '"relevance_score": 0-100, "category": "question|trend|comparison|guide|misconception|safety"}]}' . "\n\n"
. 'Generate 8-12 findings. Prioritize depth over breadth. Avoid generic or surface-level topics.';
}
/**

View File

@@ -1,168 +0,0 @@
<?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

@@ -132,9 +132,7 @@ class PRAutoBlogger_OpenRouter_Pricing {
/**
* Estimate the cost of an API call in USD.
*
* Uses hardcoded pricing first, falls back to cached model data. IDs
* carrying a date-snapshot suffix that miss both sources are retried
* once as their base ID (see resolve_pricing()).
* Uses hardcoded pricing first, falls back to cached model data.
*
* @param string $model Model identifier.
* @param int $prompt_tokens Input tokens.
@@ -148,7 +146,18 @@ class PRAutoBlogger_OpenRouter_Pricing {
return 0.0;
}
$pricing = $this->resolve_pricing( $model );
$pricing = self::MODEL_PRICING[ $model ] ?? null;
// Fall back to cached model list pricing.
if ( null === $pricing ) {
$models = $this->get_available_models();
foreach ( $models as $m ) {
if ( $m['id'] === $model && isset( $m['pricing'] ) ) {
$pricing = $m['pricing'];
break;
}
}
}
if ( null === $pricing ) {
// Unknown model — use a conservative estimate.
@@ -163,82 +172,6 @@ class PRAutoBlogger_OpenRouter_Pricing {
+ ( $completion_tokens * $pricing['completion'] / 1000000 );
}
/**
* Resolve pricing for a model ID, normalizing dated snapshot IDs.
*
* Tries the exact ID first. On a miss, strips a trailing date-snapshot
* suffix and retries once with the base ID: OpenRouter responses can
* name a dated snapshot of the requested model (e.g. request
* 'deepseek/deepseek-v4-flash', response model
* 'deepseek/deepseek-v4-flash-20260423') while pricing sources only
* list the base ID. Every cost path (governor reserve/settle and
* generation-log booking) prices through this seam, so all of them
* survive snapshot IDs instead of booking the conservative estimate.
*
* Side effects: may fetch the models list over HTTP on cache miss
* (via get_available_models()).
*
* @param string $model Model ID as requested, or as returned by the API.
*
* @return array{prompt: float, completion: float}|null Per-million USD pricing, or null when unknown.
*/
private function resolve_pricing( string $model ): ?array {
$pricing = $this->lookup_pricing( $model );
if ( null !== $pricing ) {
return $pricing;
}
$base = $this->strip_snapshot_suffix( $model );
if ( $base !== $model ) {
return $this->lookup_pricing( $base );
}
return null;
}
/**
* Look up one exact model ID: hardcoded table first, then cached model list.
*
* Side effects: may fetch the models list over HTTP on cache miss
* (via get_available_models()).
*
* @param string $model Model ID (exact match, no normalization).
*
* @return array{prompt: float, completion: float}|null Per-million USD pricing, or null on miss.
*/
private function lookup_pricing( string $model ): ?array {
$pricing = self::MODEL_PRICING[ $model ] ?? null;
if ( null !== $pricing ) {
return $pricing;
}
foreach ( $this->get_available_models() as $m ) {
if ( $m['id'] === $model && isset( $m['pricing'] ) ) {
return $m['pricing'];
}
}
return null;
}
/**
* Strip a trailing date-snapshot suffix (e.g. '-20260423') from a model ID.
*
* Only a dash followed by an 8-digit, 20-prefixed date at the very end
* is treated as a snapshot suffix. Any other trailing digit run (e.g.
* 'foo-202612345') is part of the model name and left untouched.
*
* Side effects: none — pure string transformation.
*
* @param string $model Model ID.
*
* @return string Base model ID, or the input unchanged when no snapshot suffix is present.
*/
private function strip_snapshot_suffix( string $model ): string {
$base = preg_replace( '/-20\d{6}$/', '', $model );
return is_string( $base ) ? $base : $model;
}
/**
* Get the decrypted API key from options.
*

Some files were not shown because too many files have changed in this diff Show More