Compare commits

...

7 Commits

Author SHA1 Message Date
peptiderepo
c0929be3ce fix(assembler): add prompt_version/agent_role to amortize SELECT; fix test mock
The amortize_research_costs() SELECT was missing prompt_version and agent_role —
the two fields added in the INSERT as part of the v0.19.4 pv/role fix. PHP 8.x
treats accessing an undefined property on stdClass as E_WARNING; PHPUnit
converts warnings to exceptions, which the reap() try/catch captures as
'DB error', leaving reaped=0 and breaking ResearchReaperTest on all 3 PHP versions.

Fix: extend the SELECT column list to include the two new fields so
$research_row has them populated. Update the ResearchReaperTest get_row mock
to return prompt_version and agent_role from fixtures (defaults null/'').

Agent-Session: engineer-prab-maint-fix-20260612
2026-06-12 14:05:09 +00:00
peptiderepo
02310e90d4 fix(tests): stub get_option in ImageComposerEditorTest setUp for Logger init
PRAutoBlogger_Logger::__construct() calls get_option('prautoblogger_log_level')
to set the threshold. When compose_variants() skips a role (null from cover_crop)
it calls Logger::instance()->debug(...), constructing the singleton on first call.
Without a get_option stub, Brain Monkey throws MissingFunctionExpectations.

Add setUp() override that calls parent::setUp() then stub_get_option([]) so the
logger falls back to the default 'info' level. Same pattern as ImageComposerTest.

Agent-Session: engineer-prab-maint-fix-20260612
2026-06-12 14:00:12 +00:00
peptiderepo
e6761c8fdf fix(tests): stub get_temp_dir/wp_get_image_editor/is_wp_error in GD-rung test
The test test_gd_rung_emits_passthrough_featured_and_single_warning forced
the capability to 'gd' via the filter override, causing the orchestrator to
instantiate PRAutoBlogger_Image_Composer_Editor and call compose_variants().
Inside cover_crop(), get_temp_dir() was the first WP function called —
unstubbed, Brain Monkey 2.x threw LogicException on all three PHP versions.

Add the three stubs that ImageComposerEditorTest already uses for the same
code path (same house pattern):
  - get_temp_dir  → sys_get_temp_dir() . '/'
  - wp_get_image_editor → WP_Error (no GD editor in test env)
  - is_wp_error   → isinstance alias

With wp_get_image_editor returning WP_Error, cover_crop() returns null for
every role → compose_variants() returns [] → the GD rung emits
array_merge($passthrough, []) = only the pass-through featured.
The existing assertions (assertNotEmpty, assertSame 'featured', assertSame
'raw_base_bytes') all fire against a real execution path and cannot pass
trivially — this is the actual degradation-to-passthrough contract.
Assertions are not weakened.

Agent-Session: engineer-prab-maint-fix-20260612
2026-06-12 13:58:09 +00:00
peptiderepo
b0fde2b686 fix(maintenance): v0.19.4 — composer GD-rung tests, layout-key cleanup, carried P3s
Items completed:
1. GD-rung tests (QA P2, verdict 2026-06-11-6f76df1.md P2-1):
   - New ImageComposerEditorTest.php: 7 tests covering wp_get_image_editor WP_Error,
     resize WP_Error, upscale size-mismatch guard, save WP_Error, zero-width geometry
     guard, missing-role guard, and successful OG resize happy path.
   - Orchestrator gd-rung test added to ImageComposerTest.php: forces capability='gd'
     via filter, asserts Imagick renderer is never called, pass-through featured is
     always first.

2. Dead layout keys removed (QA P3, same verdict P3-3):
   - Removed caption_margin_right (og) and caption_side_padding (square) from
     Layout::defaults(). The Imagick renderer never reads them: og text is
     left-anchored from logo_x+logo_w+caption_gap; square text is center-anchored
     at floor(width/2). Right-edge geometry is enforced by caption_chars_per_line.
     Decision: remove (not consume) — no renderer geometry to wire them to.

3. Amortized pv/role (P3 carried, phase-1 thread seq 49 + seq 50):
   - Post_Assembler::amortize_research_costs() SELECT now includes prompt_version
     and agent_role; INSERT carries them forward so amortized llm_research rows are
     no longer stamped with NULL/empty audit fields.

4. fetch_page() error body (P3 carried, phase-1 thread seq 50):
   - Runware_Catalog_Fetcher::fetch_page() non-200 exceptions now include up to
     200 chars of the response body for log-based diagnosis.

5. cto-review.yml isinstance guard: ALREADY FIXED at HEAD (line 454 uses
   c.get("severity", "UNKNOWN")). Noted in CHANGELOG; no code change.

Agent-Session: engineer-prab-maint-20260612
2026-06-12 12:46:48 +00:00
peptiderepo
5c3328dee2 v0.19.3 - hotfix: dossier 403 (hidden-page pattern -> options.php parent) (#159)
Dossier registers under options.php parent (stable admin_page_* hookname at
registration AND request time); hide-by-unset removed; enqueue gate fixed;
request-time-faithful regression tests (fail on v0.19.2 by construction);
hidden-admin-page convention codified in CONVENTIONS.md.

QA: REJECT-P1 (ae32876, test file 551 lines) -> split -> APPROVE (6689126).
Verdicts: qa-reviews/prautoblogger/2026-06-12-{ae32876,6689126}.md
Thread: pipeline-v2-phase2-admin seq 21-28

Agent-Session: cto-dossier-403-hotfix-merge-20260612
2026-06-12 18:41:46 +07:00
peptiderepo
9c8e500244 v0.19.2 - Phase 2 admin M2: Article Dossier + class-prautoblogger split (#158)
Article dossier (Proposal C): per-stage input/output sections w/ raw-trace
toggle, metadata sidebar + per-stage cost receipt, run_decisions rationale,
image section, metabox dossier link, board deep-links. DB-migration methods
extracted to class-db-migrations.php (byte-parity verified by QA).

QA: APPROVE-W-P2 qa-reviews/prautoblogger/2026-06-12-579c66e.md
P2s carried to M3: populate request_json (input trace), sidebar pv
consolidation, image stages in run_stages. Thread: pipeline-v2-phase2-admin seq 16-20

Agent-Session: cto-phase2-admin-m2-merge-20260612
2026-06-12 18:01:39 +07:00
peptiderepo
2911c94f57 v0.19.1 - hotfix: Board admin page 404 (submenu registered before parent menu) (#157)
Board submenu now registers at admin_menu priority 11 (parent toplevel at 10)
so the page hook lands under prautoblogger_page_prautoblogger-board; $submenu
reordered defensively to keep Board the first item / top-level click target.
Enqueue gate now matches; board.css/board.js load for the first time on prod.
Regression test: BoardMenuRegistrationTest (fails on pre-fix main).

QA: APPROVE-W-P2 qa-reviews/prautoblogger/2026-06-12-6168520.md
Thread: convo/prautoblogger/threads/2026-06-pipeline-v2-phase2-admin/ seq 11-14

Agent-Session: cto-board-404-hotfix-merge-20260612
2026-06-12 15:46:09 +07:00
31 changed files with 3196 additions and 217 deletions

View File

@@ -120,14 +120,17 @@ prautoblogger/
│ ├── css/ │ ├── css/
│ │ ├── admin.css # Admin page styles (wp-admin conventions) │ │ ├── admin.css # Admin page styles (wp-admin conventions)
│ │ ├── board.css # Kanban board styles -- warm editorial palette (v0.19.0) │ │ ├── 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)
│ │ └── posts-widget.css # Frontend posts widget styles (uses theme CSS vars) │ │ └── posts-widget.css # Frontend posts widget styles (uses theme CSS vars)
│ └── js/ │ └── js/
│ ├── admin.js # Admin page interactivity (vanilla JS / Alpine.js) │ ├── admin.js # Admin page interactivity (vanilla JS / Alpine.js)
│ ├── board.js # Board poller: AJAX poll + DOM updates + backoff (v0.19.0) │ ├── 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)
│ └── posts-widget.js # React component for frontend post cards (wp.element) │ └── posts-widget.js # React component for frontend post cards (wp.element)
│ │
├── includes/ ├── includes/
│ ├── class-prautoblogger.php # Main orchestrator — registers all hooks, delegates execution │ ├── class-prautoblogger.php # Main orchestrator — registers all hooks, delegates execution (258 lines; 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 # v0.18.0 substrate tables (prompts, run_sources, run_decisions, runs, run_stages) │ ├── class-pipeline-schema-installer.php # v0.18.0 substrate tables (prompts, run_sources, run_decisions, runs, run_stages)
│ ├── class-migrate-prompt-seed-v0180.php # One-shot v0.18.0 prompt-registry seed migration │ ├── 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-executor.php # Cron handlers, generation AJAX (delegates start + status to poller), model registry
@@ -140,8 +143,11 @@ prautoblogger/
│ │ │ │
│ ├── admin/ │ ├── admin/
│ │ ├── class-board-page.php # Kanban board -- primary landing screen (v0.19.0) │ │ ├── class-board-page.php # Kanban board -- primary landing screen (v0.19.0)
│ │ ├── class-board-data-provider.php # Board orchestrator: 4-column snapshot, delegates gen_log queries (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-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-admin-page.php # Main settings page (tabbed SaaS-style UI) │ │ ├── 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.php # Declarative settings: sections + core fields (API/Models/Content/Sources)
│ │ ├── class-settings-fields-extended.php # Operational fields: schedule, publishing, display, analytics, images │ │ ├── class-settings-fields-extended.php # Operational fields: schedule, publishing, display, analytics, images
@@ -245,11 +251,14 @@ prautoblogger/
├── templates/ ├── templates/
│ └── admin/ │ └── admin/
│ ├── board-page.php # Kanban board template (4-column editorial layout) (v0.19.0) │ ├── 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 # 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) │ ├── settings-page.php # Settings page template (tabbed sidebar layout)
│ ├── metrics-page.php # Metrics/cost dashboard template │ ├── metrics-page.php # Metrics/cost dashboard template
│ ├── review-queue.php # Review queue table template │ ├── review-queue.php # Review queue table template
│ ├── log-viewer.php # Activity log viewer template │ ├── log-viewer.php # Activity log viewer template
│ └── metabox-generation-info.php# Post metabox template │ └── metabox-generation-info.php# Post metabox template (superseded by metabox-dossier-link.php in v0.19.2)
│ │
├── languages/ ├── languages/
│ └── prautoblogger.pot # i18n translation template │ └── prautoblogger.pot # i18n translation template
@@ -860,11 +869,13 @@ Tests use Brain\Monkey for WordPress function mocking (no database required). Th
### #22b: Kanban board as primary admin landing screen (v0.19.0) ### #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 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` columns: Generating | In Review | Published | Failed. A separate `class-board-page.php`
registers the `Board` submenu first so it appears before Settings in the nav. 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 `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 (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 extracted `class-board-gen-log-query.php` (split for 300-line compliance) -- no new schema
@@ -875,6 +886,84 @@ fallback. M2 will rename Runs & Audit -> Articles and wire board cards to the Ar
Poll interval and published window are settings-backed, localized into board.js, never Poll interval and published window are settings-backed, localized into board.js, never
hardcoded. 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`).
## Cross-System LLM Budget Coordination ## 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. 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,6 +5,128 @@ All notable changes to PRAutoBlogger will be documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project uses [Semantic Versioning](https://semver.org/). and this project uses [Semantic Versioning](https://semver.org/).
## [0.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 ## [0.19.0] - 2026-06-12
### Added ### Added

View File

@@ -502,3 +502,73 @@ public function my_operation( $input ) {
``` ```
That's it. No config, no feature-flag checks, no try/catch needed. 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
}
```

441
assets/css/dossier.css Normal file
View File

@@ -0,0 +1,441 @@
/**
* 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

@@ -93,7 +93,10 @@
// Click-through link. // Click-through link.
var linkUrl = ''; var linkUrl = '';
var linkText = ''; var linkText = '';
if ( card.click_action === 'review' && card.review_url ) { 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; linkUrl = card.review_url;
linkText = cfg.strings.view; linkText = cfg.strings.view;
} else if ( card.click_action === 'edit' && card.edit_url ) { } else if ( card.click_action === 'edit' && card.edit_url ) {

41
assets/js/dossier.js Normal file
View File

@@ -0,0 +1,41 @@
/**
* 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

@@ -13,15 +13,19 @@ declare(strict_types=1);
* PRAutoBlogger_Board_Gen_Log_Query. WP_Query columns (In Review, Published) * PRAutoBlogger_Board_Gen_Log_Query. WP_Query columns (In Review, Published)
* are handled here. * 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. * No schema changes -- all data comes from tables that already exist.
* *
* Triggered by: PRAutoBlogger_Board_Page::on_ajax_board_status(). * Triggered by: PRAutoBlogger_Board_Page::on_ajax_board_status().
* Dependencies: PRAutoBlogger_Board_Gen_Log_Query, WordPress WP_Query, get_option(). * Dependencies: PRAutoBlogger_Board_Gen_Log_Query, PRAutoBlogger_Dossier_Page,
* WordPress WP_Query, get_option().
* *
* @see admin/class-board-gen-log-query.php -- Raw generation-log queries (Generating/Failed). * @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-board-page.php -- Calls get_board_snapshot().
* @see core/class-cost-reporter.php -- Parallel cost-query pattern. * @see admin/class-dossier-page.php -- Provides url_for_post() for deep-links.
* @see ARCHITECTURE.md -- Database schema (generation_log, post meta). * @see ARCHITECTURE.md -- Database schema.
*/ */
class PRAutoBlogger_Board_Data_Provider { class PRAutoBlogger_Board_Data_Provider {
@@ -38,9 +42,6 @@ class PRAutoBlogger_Board_Data_Provider {
/** /**
* Return the full board snapshot consumed by the AJAX poller. * Return the full board snapshot consumed by the AJAX poller.
* *
* Each column is an array of card objects. Cards contain only the data
* needed to render the board card and provide click-throughs.
*
* @return array{ * @return array{
* generating: array<int, array<string, mixed>>, * generating: array<int, array<string, mixed>>,
* in_review: array<int, array<string, mixed>>, * in_review: array<int, array<string, mixed>>,
@@ -66,7 +67,6 @@ class PRAutoBlogger_Board_Data_Provider {
/** /**
* Cards for runs that are currently in-progress. * Cards for runs that are currently in-progress.
* Delegates to PRAutoBlogger_Board_Gen_Log_Query.
* *
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
*/ */
@@ -76,7 +76,6 @@ class PRAutoBlogger_Board_Data_Provider {
/** /**
* Cards for generation runs that ended in an error state. * Cards for generation runs that ended in an error state.
* Delegates to PRAutoBlogger_Board_Gen_Log_Query.
* *
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
*/ */
@@ -86,6 +85,7 @@ class PRAutoBlogger_Board_Data_Provider {
/** /**
* Cards for generated draft posts awaiting human review. * Cards for generated draft posts awaiting human review.
* M2: cards include dossier_url for deep-linking.
* *
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
*/ */
@@ -120,7 +120,8 @@ class PRAutoBlogger_Board_Data_Provider {
'title' => $post->post_title, 'title' => $post->post_title,
'cost_total' => $cost_total, 'cost_total' => $cost_total,
'created_at' => strtotime( $post->post_date_gmt ), 'created_at' => strtotime( $post->post_date_gmt ),
'click_action' => 'review', 'click_action' => 'dossier',
'dossier_url' => PRAutoBlogger_Dossier_Page::url_for_post( $post->ID ),
'review_url' => admin_url( 'admin.php?page=prautoblogger-review-queue' ), 'review_url' => admin_url( 'admin.php?page=prautoblogger-review-queue' ),
'edit_url' => get_edit_post_link( $post->ID, 'raw' ), 'edit_url' => get_edit_post_link( $post->ID, 'raw' ),
); );
@@ -131,6 +132,7 @@ class PRAutoBlogger_Board_Data_Provider {
/** /**
* Cards for published posts within the configured window. * Cards for published posts within the configured window.
* M2: cards include dossier_url for deep-linking.
* *
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
*/ */
@@ -174,7 +176,8 @@ class PRAutoBlogger_Board_Data_Provider {
'title' => $post->post_title, 'title' => $post->post_title,
'cost_total' => $cost_total, 'cost_total' => $cost_total,
'published_at' => strtotime( $post->post_date_gmt ), 'published_at' => strtotime( $post->post_date_gmt ),
'click_action' => 'edit', 'click_action' => 'dossier',
'dossier_url' => PRAutoBlogger_Dossier_Page::url_for_post( $post->ID ),
'edit_url' => get_edit_post_link( $post->ID, 'raw' ), 'edit_url' => get_edit_post_link( $post->ID, 'raw' ),
'post_url' => get_permalink( $post->ID ), 'post_url' => get_permalink( $post->ID ),
); );

View File

@@ -42,6 +42,14 @@ class PRAutoBlogger_Board_Page {
* submenu duplicate of the top-level page; we name it "Board" so the * submenu duplicate of the top-level page; we name it "Board" so the
* first click goes to the board, not the raw settings page. * 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 * @return void
*/ */
public function on_register_menu(): void { public function on_register_menu(): void {
@@ -54,6 +62,30 @@ class PRAutoBlogger_Board_Page {
self::PAGE_SLUG, self::PAGE_SLUG,
array( $this, 'render_page' ) 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 ) );
}
}
} }
/** /**

View File

@@ -0,0 +1,191 @@
<?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.
*
* 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(),
);
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;
}
$base['has_run'] = true;
$base['run'] = $run;
$base['stages'] = $this->get_stage_rows( $run_id );
$base['decisions'] = $this->get_decision_rows( $run_id );
$base['gen_log_index'] = $this->log_query->get_by_run( $run_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 all run_stages rows for a run, indexed by stage name.
*
* @param string $run_id Pipeline run UUID.
* @return array<string, array<string, mixed>> Stage rows keyed by stage name.
*/
private function get_stage_rows( string $run_id ): array {
if ( ! PRAutoBlogger_Run_Stage_State::is_available() ) {
return array();
}
global $wpdb;
if ( null === $wpdb ) {
return array();
}
$table = PRAutoBlogger_Run_Stage_State::table_name();
// 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;
}
/**
* 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

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

@@ -0,0 +1,136 @@
<?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
);
}
/**
* 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

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

View File

@@ -0,0 +1,129 @@
<?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' );
}
}
}

View File

@@ -6,20 +6,12 @@ declare(strict_types=1);
* *
* Main orchestrator for the PRAutoBlogger plugin. * Main orchestrator for the PRAutoBlogger plugin.
* *
* Registers all WordPress hooks (actions and filters) and wires up dependencies. * Registers all WordPress hooks and wires up dependencies.
* This is the ONLY place hooks are registered -- individual classes contain only * DB/option migrations extracted to PRAutoBlogger_DB_Migrations (v0.19.2).
* business logic, not hook registration.
* *
* Triggered by: prautoblogger() singleton in prautoblogger.php, called on `plugins_loaded`. * @see prautoblogger.php -- Plugin bootstrap.
* Dependencies: All other plugin classes (loaded via autoloader), PRAutoBlogger_Executor. * @see class-db-migrations.php -- One-time DB/option migrations.
* * @see ARCHITECTURE.md -- Data flow diagram.
* @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 { class PRAutoBlogger {
@@ -28,14 +20,12 @@ class PRAutoBlogger {
/** @var PRAutoBlogger_Executor Handles generation cron/AJAX, model registry. */ /** @var PRAutoBlogger_Executor Handles generation cron/AJAX, model registry. */
private PRAutoBlogger_Executor $executor; private PRAutoBlogger_Executor $executor;
/** @var PRAutoBlogger_Ajax_Handlers Handles non-generation AJAX (images, models, test). */ /** @var PRAutoBlogger_Ajax_Handlers Handles non-generation AJAX. */
private PRAutoBlogger_Ajax_Handlers $ajax_handlers; private PRAutoBlogger_Ajax_Handlers $ajax_handlers;
/** /**
* Register all hooks and initialize the plugin. * Register all hooks and initialize the plugin.
* Called once on `plugins_loaded`. Idempotent. * Called once on `plugins_loaded`. Idempotent.
*
* Side effects: registers WordPress actions and filters.
*/ */
public function run(): void { public function run(): void {
if ( $this->initialized ) { if ( $this->initialized ) {
@@ -46,9 +36,7 @@ class PRAutoBlogger {
$this->ajax_handlers = new PRAutoBlogger_Ajax_Handlers( $this->executor->get_model_registry() ); $this->ajax_handlers = new PRAutoBlogger_Ajax_Handlers( $this->executor->get_model_registry() );
add_action( 'admin_init', array( $this, 'on_check_db_version' ) ); add_action( 'admin_init', array( $this, 'on_check_db_version' ) );
// v0.18.0: cron requests must also self-heal the schema -- after a // v0.18.0: cron requests must also self-heal the schema.
// deploy, scheduled generation can run before any admin page load,
// and new-column inserts would silently fail on the old schema.
add_action( 'init', array( $this, 'on_check_db_version_for_cron' ) ); add_action( 'init', array( $this, 'on_check_db_version_for_cron' ) );
add_filter( 'cron_schedules', array( $this, 'filter_add_cron_schedules' ) ); add_filter( 'cron_schedules', array( $this, 'filter_add_cron_schedules' ) );
@@ -65,18 +53,30 @@ class PRAutoBlogger {
do_action( 'prautoblogger_loaded' ); do_action( 'prautoblogger_loaded' );
} }
/** Register admin-only hooks (settings, notices, metabox, dashboard widget). */ /**
* 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.
*/
private function register_admin_hooks(): void { private function register_admin_hooks(): void {
// Kanban board -- registered first so it appears as the first submenu item.
$board_page = new PRAutoBlogger_Board_Page();
add_action( 'admin_menu', array( $board_page, 'on_register_menu' ) );
add_action( 'admin_enqueue_scripts', array( $board_page, 'on_enqueue_assets' ) );
$admin_page = new PRAutoBlogger_Admin_Page(); $admin_page = new PRAutoBlogger_Admin_Page();
add_action( 'admin_menu', array( $admin_page, 'on_register_menu' ) ); add_action( 'admin_menu', array( $admin_page, 'on_register_menu' ), 10 );
add_action( 'admin_init', array( $admin_page, 'on_register_settings' ) ); add_action( 'admin_init', array( $admin_page, 'on_register_settings' ) );
add_action( 'admin_enqueue_scripts', array( $admin_page, 'on_enqueue_assets' ) ); 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( '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( 'add_meta_boxes', array( new PRAutoBlogger_Post_Metabox(), 'on_register_metabox' ) );
add_action( 'admin_menu', array( new PRAutoBlogger_Metrics_Page(), 'on_register_menu' ) ); add_action( 'admin_menu', array( new PRAutoBlogger_Metrics_Page(), 'on_register_menu' ) );
@@ -91,7 +91,6 @@ class PRAutoBlogger {
( new PRAutoBlogger_Post_List_Columns() )->register(); ( 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' ) ); add_filter( 'site_transient_update_plugins', array( $this, 'filter_block_false_updates' ) );
} }
@@ -111,13 +110,7 @@ class PRAutoBlogger {
private function register_cron_hooks(): void { private function register_cron_hooks(): void {
add_action( 'prautoblogger_daily_generation', array( $this->executor, 'on_daily_generation' ) ); add_action( 'prautoblogger_daily_generation', array( $this->executor, 'on_daily_generation' ) );
add_action( 'prautoblogger_collect_metrics', array( $this->executor, 'on_collect_metrics' ) ); 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' ) ); 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( add_action(
PRAutoBlogger_Pipeline_Runner::CRON_ACTION, PRAutoBlogger_Pipeline_Runner::CRON_ACTION,
array( $this->executor, 'on_process_article_queue' ) array( $this->executor, 'on_process_article_queue' )
@@ -125,59 +118,39 @@ class PRAutoBlogger {
$registry = $this->executor->get_model_registry(); $registry = $this->executor->get_model_registry();
add_action( 'prautoblogger_refresh_model_registry', array( $registry, 'refresh' ) ); add_action( 'prautoblogger_refresh_model_registry', array( $registry, 'refresh' ) );
// v0.15.0: daily Runware model catalog sync to keep the live model list fresh.
add_action( 'prautoblogger_sync_runware_models', array( new PRAutoBlogger_Runware_Model_Catalog(), 'sync' ) ); add_action( 'prautoblogger_sync_runware_models', array( new PRAutoBlogger_Runware_Model_Catalog(), 'sync' ) );
// Opik observability: async trace/span dispatch.
add_action( add_action(
'prautoblogger_opik_dispatch', 'prautoblogger_opik_dispatch',
static function (): void { static function (): void {
if ( ! defined( 'PRAUTOBLOGGER_OPIK_API_KEY' ) || empty( PRAUTOBLOGGER_OPIK_API_KEY ) ) { if ( ! defined( 'PRAUTOBLOGGER_OPIK_API_KEY' ) || empty( PRAUTOBLOGGER_OPIK_API_KEY ) ) {
return; return;
} }
$client = new PRAutoBlogger_Opik_Client( $client = new PRAutoBlogger_Opik_Client(
PRAUTOBLOGGER_OPIK_API_KEY, PRAUTOBLOGGER_OPIK_API_KEY,
PRAUTOBLOGGER_OPIK_WORKSPACE, PRAUTOBLOGGER_OPIK_WORKSPACE,
PRAUTOBLOGGER_OPIK_URL_OVERRIDE PRAUTOBLOGGER_OPIK_URL_OVERRIDE
); );
$queue = new PRAutoBlogger_Opik_Span_Queue(); $dispatcher = new PRAutoBlogger_Opik_Dispatcher( $client, new PRAutoBlogger_Opik_Span_Queue() );
$dispatcher = new PRAutoBlogger_Opik_Dispatcher( $client, $queue );
$dispatcher->dispatch(); $dispatcher->dispatch();
update_option( 'prautoblogger_opik_last_dispatch', time() ); update_option( 'prautoblogger_opik_last_dispatch', time() );
} }
); );
// Opik settings registration.
if ( is_admin() ) { if ( is_admin() ) {
new PRAutoBlogger_Opik_Settings(); new PRAutoBlogger_Opik_Settings();
} }
// 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_generate_from_idea', array( 'PRAutoBlogger_Ideas_Browser', 'on_cron_generate_from_idea' ) );
// 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' ) ); add_action( 'prautoblogger_reap_orphan_research_rows', array( 'PRAutoBlogger_Research_Reaper', 'on_cron' ) );
// v0.18.0: stuck-run sweep + audit-payload retention rides the SAME
// existing daily cron (no new schedule). See class-run-reaper.php.
add_action( 'prautoblogger_reap_orphan_research_rows', array( 'PRAutoBlogger_Run_Reaper', 'on_cron' ) ); add_action( 'prautoblogger_reap_orphan_research_rows', array( 'PRAutoBlogger_Run_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 ) { if ( defined( 'WP_CLI' ) && WP_CLI ) {
\WP_CLI::add_command( \WP_CLI::add_command(
'prautoblogger reap-research', 'prautoblogger reap-research',
static function (): void { static function (): void {
$stats = PRAutoBlogger_Research_Reaper::reap(); $stats = PRAutoBlogger_Research_Reaper::reap();
\WP_CLI::success( \WP_CLI::success( sprintf( 'Reaped %d, deleted %d, skipped %d.', (int) $stats['reaped'], (int) $stats['deleted'], (int) $stats['skipped'] ) );
sprintf(
'Reaped %d, deleted %d (stale), skipped %d.',
(int) $stats['reaped'],
(int) $stats['deleted'],
(int) $stats['skipped']
)
);
} }
); );
} }
@@ -185,11 +158,9 @@ class PRAutoBlogger {
/** Register AJAX handlers for admin actions. */ /** Register AJAX handlers for admin actions. */
private function register_ajax_hooks(): void { 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_generate_now', array( $this->executor, 'on_ajax_generate_now' ) );
add_action( 'wp_ajax_prautoblogger_generation_status', array( $this->executor, 'on_ajax_generation_status' ) ); 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_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_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_get_models', array( $this->ajax_handlers, 'on_ajax_get_models' ) );
@@ -201,12 +172,7 @@ class PRAutoBlogger {
add_action( 'wp_ajax_prautoblogger_reject_post', array( $review_queue, 'on_ajax_reject_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_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' ) );
// Board status polling AJAX (nonce: prautoblogger_board).
add_action(
'wp_ajax_' . PRAutoBlogger_Board_Page::AJAX_ACTION,
array( new PRAutoBlogger_Board_Page(), 'on_ajax_board_status' )
);
$ideas = new PRAutoBlogger_Ideas_Browser(); $ideas = new PRAutoBlogger_Ideas_Browser();
add_action( 'wp_ajax_prautoblogger_generate_from_idea', array( $ideas, 'on_ajax_generate_from_idea' ) ); add_action( 'wp_ajax_prautoblogger_generate_from_idea', array( $ideas, 'on_ajax_generate_from_idea' ) );
@@ -214,123 +180,16 @@ class PRAutoBlogger {
} }
/** /**
* Check if database needs migration after plugin update. * Check if database needs migration. Delegates to PRAutoBlogger_DB_Migrations::run().
* Compares stored DB version with PRAUTOBLOGGER_DB_VERSION; re-runs activation if different. * Hooked on `admin_init`.
*
* Side effects: may update database schema and db_version option.
*/ */
public function on_check_db_version(): void { public function on_check_db_version(): void {
$stored_version = get_option( 'prautoblogger_db_version', '0' ); PRAutoBlogger_DB_Migrations::run();
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 (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' );
}
// One-time migration (v0.16.0): editorial pivot. The comic Style Suffix
// is replaced by the editorial Style Template. Mirror the old suffix
// value into a deprecated-keyed option for one version cycle (so a
// customised value is recoverable / auditable) and seed the new
// template with its editorial default. The old option is intentionally
// NOT deleted this cycle. See docs/proposals/2026-05-29-image-pipeline-in-plugin-brief.md paragraph 8 Commit 1.
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 );
}
// Only seed the new template if the admin has not already set one.
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' );
}
} }
/** /**
* Run schema migrations during cron requests. * Run DB migrations during cron requests (hooked on `init`).
* * Only fires when wp_doing_cron() is true.
* Wraps on_check_db_version() so it only fires during WP-Cron execution.
* After a deploy, the daily generation cron can fire before any admin page
* load -- without this, new-column inserts would silently fail.
*
* Side effects: may run the same migrations as on_check_db_version().
*
* @return void
*/ */
public function on_check_db_version_for_cron(): void { public function on_check_db_version_for_cron(): void {
if ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) { if ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) {
@@ -341,7 +200,7 @@ class PRAutoBlogger {
/** /**
* Add custom cron schedules (six-hourly for metrics collection). * Add custom cron schedules (six-hourly for metrics collection).
* *
* @param array<string, array{interval: int, display: string}> $schedules Existing schedules. * @param array<string, array{interval: int, display: string}> $schedules Existing.
* @return array<string, array{interval: int, display: string}> * @return array<string, array{interval: int, display: string}>
*/ */
public function filter_add_cron_schedules( array $schedules ): array { public function filter_add_cron_schedules( array $schedules ): array {
@@ -359,7 +218,6 @@ class PRAutoBlogger {
/** /**
* Block false update notifications from wordpress.org. * 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. * @param object $transient The update_plugins transient data.
* @return object Modified transient. * @return object Modified transient.

View File

@@ -38,6 +38,10 @@ class PRAutoBlogger_Image_Composer_Layout {
* plugin; sizes are px. Values were tuned against rendered samples (see * plugin; sizes are px. Values were tuned against rendered samples (see
* PR #thread 2026-06-image-composer assets). * 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. * @return array<string, array<string, mixed>> Keyed by role: featured, og, square.
*/ */
public static function defaults(): array { public static function defaults(): array {
@@ -60,7 +64,6 @@ class PRAutoBlogger_Image_Composer_Layout {
'caption_size' => 32, 'caption_size' => 32,
'caption_color' => '#FFFFFF', 'caption_color' => '#FFFFFF',
'caption_gap' => 24, 'caption_gap' => 24,
'caption_margin_right' => 40,
'caption_max_lines' => 2, 'caption_max_lines' => 2,
'caption_chars_per_line' => 52, 'caption_chars_per_line' => 52,
'caption_line_height' => 1.3, 'caption_line_height' => 1.3,
@@ -79,7 +82,6 @@ class PRAutoBlogger_Image_Composer_Layout {
'caption_color' => self::COLOR_INK, 'caption_color' => self::COLOR_INK,
'caption_max_lines' => 3, 'caption_max_lines' => 3,
'caption_chars_per_line' => 36, 'caption_chars_per_line' => 36,
'caption_side_padding' => 64,
'caption_line_height' => 1.3, 'caption_line_height' => 1.3,
), ),
); );

View File

@@ -91,7 +91,9 @@ class PRAutoBlogger_Post_Assembler {
* are generated. Its cost is logged with the run_id but no post_id. After all * 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 * articles finish, this method divides the research cost evenly and inserts
* one 'llm_research' row per article so the cost breakdown popover includes * one 'llm_research' row per article so the cost breakdown popover includes
* the amortized research overhead. * 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).
* *
* Side effects: database SELECT, INSERT, DELETE on generation_log. * Side effects: database SELECT, INSERT, DELETE on generation_log.
* *
@@ -109,7 +111,7 @@ class PRAutoBlogger_Post_Assembler {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$research_row = $wpdb->get_row( $research_row = $wpdb->get_row(
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
"SELECT id, estimated_cost, provider, model, prompt_tokens, completion_tokens "SELECT id, estimated_cost, provider, model, prompt_tokens, completion_tokens, prompt_version, agent_role
FROM {$table} FROM {$table}
WHERE run_id = %s AND stage = 'llm_research' AND post_id IS NULL WHERE run_id = %s AND stage = 'llm_research' AND post_id IS NULL
LIMIT 1", LIMIT 1",
@@ -158,6 +160,8 @@ class PRAutoBlogger_Post_Assembler {
'estimated_cost' => $amortized_cost, 'estimated_cost' => $amortized_cost,
'response_status' => 'success', 'response_status' => 'success',
'error_message' => '', 'error_message' => '',
'prompt_version' => $research_row->prompt_version,
'agent_role' => $research_row->agent_role ?? '',
'created_at' => current_time( 'mysql' ), 'created_at' => current_time( 'mysql' ),
) )
); );

View File

@@ -138,7 +138,8 @@ class PRAutoBlogger_Runware_Catalog_Fetcher {
* @param int $offset Pagination offset (0-based). * @param int $offset Pagination offset (0-based).
* @param int $limit Page size. * @param int $limit Page size.
* @return array{results: array<int, array<string, mixed>>, totalResults: int} * @return array{results: array<int, array<string, mixed>>, totalResults: int}
* @throws \RuntimeException On HTTP error or malformed response. * @throws \RuntimeException On HTTP error or malformed response (non-200 exceptions
* include up to 200 chars of the response body for diagnosis).
*/ */
private function fetch_page( string $api_key, int $offset, int $limit ): array { private function fetch_page( string $api_key, int $offset, int $limit ): array {
$payload = array( $payload = array(
@@ -171,8 +172,10 @@ class PRAutoBlogger_Runware_Catalog_Fetcher {
$status = (int) wp_remote_retrieve_response_code( $response ); $status = (int) wp_remote_retrieve_response_code( $response );
if ( 200 !== $status ) { if ( 200 !== $status ) {
$raw_body = (string) wp_remote_retrieve_body( $response );
$body_excerpt = '' !== $raw_body ? ' — body: ' . substr( $raw_body, 0, 200 ) : '';
throw new \RuntimeException( throw new \RuntimeException(
sprintf( 'Runware modelSearch returned HTTP %d', $status ) sprintf( 'Runware modelSearch returned HTTP %d%s', $status, $body_excerpt )
); );
} }

View File

@@ -9,7 +9,7 @@
* Plugin Name: PRAutoBlogger * Plugin Name: PRAutoBlogger
* Plugin URI: https://peptiderepo.com/prautoblogger * Plugin URI: https://peptiderepo.com/prautoblogger
* Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics. * Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics.
* Version: 0.19.0 * Version: 0.19.4
* Requires at least: 6.0 * Requires at least: 6.0
* Requires PHP: 7.4 * Requires PHP: 7.4
* Author: PeptideRepo * Author: PeptideRepo
@@ -35,7 +35,7 @@ if ( ! defined( 'ABSPATH' ) ) {
| Defined here so every file in the plugin can reference paths, versions, | Defined here so every file in the plugin can reference paths, versions,
| and limits without magic strings. | and limits without magic strings.
*/ */
define( 'PRAUTOBLOGGER_VERSION', '0.19.0' ); define( 'PRAUTOBLOGGER_VERSION', '0.19.4' );
define( 'PRAUTOBLOGGER_DB_VERSION', '1.1.0' ); define( 'PRAUTOBLOGGER_DB_VERSION', '1.1.0' );
define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ ); define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ );
define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
@@ -107,6 +107,7 @@ PRAutoBlogger_Autoloader::register();
// The main orchestrator class is loaded explicitly because its CamelCase name // The main orchestrator class is loaded explicitly because its CamelCase name
// (PRAutoBlogger) doesn't map cleanly to a filename via the autoloader's // (PRAutoBlogger) doesn't map cleanly to a filename via the autoloader's
// kebab-case convention (it would look for class-pr-auto-blogger.php). // kebab-case convention (it would look for class-pr-auto-blogger.php).
require_once PRAUTOBLOGGER_PLUGIN_DIR . 'includes/class-db-migrations.php'; // Loaded explicitly: DB_Migrations -> class-d-b-migrations.php via autoloader
require_once PRAUTOBLOGGER_PLUGIN_DIR . 'includes/class-prautoblogger.php'; require_once PRAUTOBLOGGER_PLUGIN_DIR . 'includes/class-prautoblogger.php';
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@@ -0,0 +1,224 @@
<?php
/**
* Article Dossier template (M2 — read-only).
*
* Design contract: Proposal C "Editorial Record" -- warm editorial,
* typographic hierarchy, verdict pills, receipt-style cost sidebar,
* per-stage I/O with expandable raw-trace toggle. Vanilla JS/CSS only.
*
* Variables injected by PRAutoBlogger_Dossier_Page::render_page():
* $post_id (int) -- WordPress post ID
* $dossier (array) -- View model from PRAutoBlogger_Dossier_Data_Assembler
* $assembler (obj) -- (not directly used here)
*
* @see admin/class-dossier-page.php -- Renders this template.
* @see admin/class-dossier-data-assembler.php -- Builds $dossier.
* @see assets/css/dossier.css -- Styling.
* @see assets/js/dossier.js -- Raw-trace toggle.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$has_run = ! empty( $dossier['has_run'] );
$run = $dossier['run'] ?? null;
$stages = $dossier['stages'] ?? array();
$decisions = $dossier['decisions'] ?? array();
$log_index = $dossier['gen_log_index'] ?? array();
$verdict = $dossier['verdict'] ?? '';
$tier = $dossier['tier'] ?? '';
$run_id = $dossier['run_id'] ?? '';
$log_query = new PRAutoBlogger_Dossier_Gen_Log_Query();
$stage_totals = $log_query->aggregate_per_stage( $log_index );
$total_cost = 0.0;
foreach ( $stage_totals as $st ) {
$total_cost += $st['cost'];
}
$verdict_labels = array(
'approved' => __( 'Approved', 'prautoblogger' ),
'revised' => __( 'Revised', 'prautoblogger' ),
'rejected' => __( 'Rejected', 'prautoblogger' ),
'halted' => __( 'Halted', 'prautoblogger' ),
'pending' => __( 'Pending', 'prautoblogger' ),
);
$back_url = admin_url( 'admin.php?page=prautoblogger-board' );
?>
<div class="wrap prab-dossier-wrap">
<?php // ── Back link ──────────────────────────────────────────────────────── ?>
<p class="prab-dossier-back">
<a href="<?php echo esc_url( $back_url ); ?>">
&larr; <?php esc_html_e( 'Back to Board', 'prautoblogger' ); ?>
</a>
</p>
<?php if ( ! $has_run ) : ?>
<?php // ── Graceful empty state (legacy post or invalid id) ───────────────── ?>
<div id="prab-dossier" class="prab-dossier prab-dossier--empty">
<div class="prab-dossier-empty-notice">
<h2><?php esc_html_e( 'No generation record', 'prautoblogger' ); ?></h2>
<?php if ( $post_id > 0 && ! empty( $dossier['post_title'] ) ) : ?>
<p>
<?php
printf(
/* translators: %s: article title */
esc_html__( 'The article "%s" was published before the generation substrate was introduced (v0.18.0). No dossier data is available.', 'prautoblogger' ),
esc_html( $dossier['post_title'] )
);
?>
</p>
<?php elseif ( $post_id <= 0 ) : ?>
<p><?php esc_html_e( 'No article was specified. Use a board card or post link to reach a dossier.', 'prautoblogger' ); ?></p>
<?php else : ?>
<p><?php esc_html_e( 'No run record was found for this article.', 'prautoblogger' ); ?></p>
<?php endif; ?>
</div>
</div>
<?php return; ?>
<?php endif; ?>
<?php // ── Full dossier ────────────────────────────────────────────────────── ?>
<div id="prab-dossier" class="prab-dossier">
<?php // ── Article header ──────────────────────────────────────────────── ?>
<div class="prab-dossier-header">
<div class="prab-dossier-header-main">
<h1 class="prab-dossier-title"><?php echo esc_html( $dossier['post_title'] ); ?></h1>
<div class="prab-dossier-header-meta">
<?php if ( '' !== $verdict ) : ?>
<span class="prab-verdict-pill prab-verdict-pill--<?php echo esc_attr( $verdict ); ?>">
<?php echo esc_html( $verdict_labels[ $verdict ] ?? ucfirst( $verdict ) ); ?>
</span>
<?php endif; ?>
<?php if ( '' !== $tier ) : ?>
<span class="prab-dossier-tier"><?php echo esc_html( ucfirst( $tier ) ); ?></span>
<?php endif; ?>
<span class="prab-dossier-status prab-dossier-status--<?php echo esc_attr( $dossier['post_status'] ?? '' ); ?>">
<?php echo esc_html( ucfirst( $dossier['post_status'] ?? '' ) ); ?>
</span>
</div>
</div>
<?php if ( $post_id > 0 ) : ?>
<div class="prab-dossier-header-actions">
<a href="<?php echo esc_url( get_edit_post_link( $post_id, 'raw' ) ?? '' ); ?>" class="button">
<?php esc_html_e( 'Edit Article', 'prautoblogger' ); ?>
</a>
</div>
<?php endif; ?>
</div>
<div class="prab-dossier-body">
<?php // ── Main column: stage sections ─────────────────────────────── ?>
<div class="prab-dossier-main">
<?php
$stage_order = array( 'analysis', 'llm_research', 'research', 'curate', 'outline', 'draft', 'polish', 'review', 'editorial', 'seo', 'publish', 'image_a', 'image_b' );
$rendered_stages = array();
// Render stages in canonical order first, then any extra rows.
foreach ( $stage_order as $stage_name ) {
foreach ( $stages as $role_key => $stage_row ) {
if ( ( $stage_row['stage'] ?? '' ) !== $stage_name ) {
continue;
}
$rendered_stages[] = $role_key;
$log_rows = $log_index[ $stage_name ] ?? array();
require PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/dossier-stage-section.php';
}
}
// Remaining unordered stages.
foreach ( $stages as $role_key => $stage_row ) {
if ( in_array( $role_key, $rendered_stages, true ) ) {
continue;
}
$stage_name = (string) ( $stage_row['stage'] ?? 'unknown' );
$log_rows = $log_index[ $stage_name ] ?? array();
require PRAUTOBLOGGER_PLUGIN_DIR . 'templates/admin/dossier-stage-section.php';
}
if ( empty( $stages ) ) :
?>
<div class="prab-dossier-no-stages">
<p><?php esc_html_e( 'Stage data is not yet available for this run.', 'prautoblogger' ); ?></p>
</div>
<?php endif; ?>
<?php // ── Editorial decisions section ─────────────────────────────── ?>
<?php if ( ! empty( $decisions ) ) : ?>
<div class="prab-dossier-section prab-dossier-section--decisions">
<h2 class="prab-section-title"><?php esc_html_e( 'Editorial Decisions', 'prautoblogger' ); ?></h2>
<?php foreach ( $decisions as $d_stage => $d ) : ?>
<div class="prab-decision-row">
<span class="prab-decision-stage"><?php echo esc_html( PRAutoBlogger_Stage_Display_Map::label( $d_stage ) ); ?></span>
<span class="prab-verdict-pill prab-verdict-pill--<?php echo esc_attr( (string) ( $d['verdict'] ?? '' ) ); ?>">
<?php echo esc_html( ucfirst( (string) ( $d['verdict'] ?? '' ) ) ); ?>
</span>
<?php if ( ! empty( $d['rationale'] ) ) : ?>
<p class="prab-decision-rationale"><?php echo esc_html( (string) $d['rationale'] ); ?></p>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div><!-- .prab-dossier-main -->
<?php // ── Sidebar: metadata + cost receipt ───────────────────────── ?>
<div class="prab-dossier-sidebar">
<div class="prab-sidebar-card">
<h3 class="prab-sidebar-heading"><?php esc_html_e( 'Run Info', 'prautoblogger' ); ?></h3>
<?php if ( null !== $run ) : ?>
<dl class="prab-sidebar-dl">
<dt><?php esc_html_e( 'Status', 'prautoblogger' ); ?></dt>
<dd><span class="prab-run-status prab-run-status--<?php echo esc_attr( (string) ( $run['status'] ?? '' ) ); ?>"><?php echo esc_html( ucfirst( (string) ( $run['status'] ?? '' ) ) ); ?></span></dd>
<dt><?php esc_html_e( 'Started', 'prautoblogger' ); ?></dt>
<dd><?php echo esc_html( (string) ( $run['started_at'] ?? '—' ) ); ?></dd>
<?php if ( ! empty( $run['finished_at'] ) ) : ?>
<dt><?php esc_html_e( 'Finished', 'prautoblogger' ); ?></dt>
<dd><?php echo esc_html( (string) $run['finished_at'] ); ?></dd>
<?php endif; ?>
<dt><?php esc_html_e( 'Run ID', 'prautoblogger' ); ?></dt>
<dd class="prab-run-id"><?php echo esc_html( $run_id ); ?></dd>
</dl>
<?php endif; ?>
</div>
<div class="prab-sidebar-card prab-cost-receipt">
<h3 class="prab-sidebar-heading"><?php esc_html_e( 'Cost Receipt', 'prautoblogger' ); ?></h3>
<table class="prab-receipt-table">
<tbody>
<?php foreach ( $stage_totals as $st_name => $st ) : ?>
<?php
if ( $st['cost'] <= 0.0 && 0 === $st['calls'] ) :
continue;
endif;
?>
<tr>
<td class="prab-receipt-stage"><?php echo esc_html( PRAutoBlogger_Stage_Display_Map::label( $st_name ) ); ?></td>
<td class="prab-receipt-cost">$<?php echo esc_html( number_format( $st['cost'], 5 ) ); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr class="prab-receipt-total">
<td><?php esc_html_e( 'Total', 'prautoblogger' ); ?></td>
<td>$<?php echo esc_html( number_format( $total_cost, 5 ) ); ?></td>
</tr>
</tfoot>
</table>
</div>
</div><!-- .prab-dossier-sidebar -->
</div><!-- .prab-dossier-body -->
</div><!-- #prab-dossier -->
</div><!-- .prab-dossier-wrap -->

View File

@@ -0,0 +1,126 @@
<?php
/**
* Partial: single stage section for the Article Dossier.
*
* Variables injected by dossier-page.php:
* $stage_row (array) -- run_stages row incl. display_output
* $stage_name (string) -- stage key
* $log_rows (array) -- generation_log rows for this stage
*
* Security: all model output escaped via esc_html() or wp_kses_post().
* request_json escaped via esc_html() -- treat as untrusted HTML.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$s_label = PRAutoBlogger_Stage_Display_Map::label( $stage_name );
$s_status = (string) ( $stage_row['status'] ?? '' );
$s_output = $stage_row['display_output'] ?? null;
$s_cost = (float) ( $stage_row['cost_usd'] ?? 0 );
$s_role = (string) ( $stage_row['agent_role'] ?? '' );
$s_started = (string) ( $stage_row['started_at'] ?? '' );
$s_finished = (string) ( $stage_row['finished_at'] ?? '' );
$output_pruned = ( ! empty( $stage_row['status'] ) && 'done' === $stage_row['status'] && null === $s_output );
// Determine prompt version from gen_log (first row for this stage).
$first_log = ! empty( $log_rows ) ? $log_rows[0] : null;
$s_model = ( null !== $first_log && ! empty( $first_log['model'] ) ) ? $first_log['model'] : '—';
$s_pv = ( null !== $first_log && ! empty( $first_log['prompt_version'] ) ) ? $first_log['prompt_version'] : '—';
$has_raw_trace = ! empty( $log_rows );
$section_id = 'prab-stage-' . esc_attr( $stage_name ) . '-' . esc_attr( $s_role );
?>
<div class="prab-dossier-section prab-dossier-section--stage prab-stage-status--<?php echo esc_attr( $s_status ); ?>"
data-stage="<?php echo esc_attr( $stage_name ); ?>"
id="<?php echo $section_id; // Already escaped. ?>">
<div class="prab-stage-header">
<h2 class="prab-section-title">
<?php echo esc_html( $s_label ); ?>
<?php if ( '' !== $s_role ) : ?>
<span class="prab-stage-role">(<?php echo esc_html( $s_role ); ?>)</span>
<?php endif; ?>
</h2>
<div class="prab-stage-header-meta">
<span class="prab-stage-status-pill prab-stage-status-pill--<?php echo esc_attr( $s_status ); ?>">
<?php echo esc_html( ucfirst( $s_status ) ); ?>
</span>
<?php if ( $s_cost > 0 ) : ?>
<span class="prab-stage-cost">$<?php echo esc_html( number_format( $s_cost, 5 ) ); ?></span>
<?php endif; ?>
<span class="prab-stage-model"><?php echo esc_html( $s_model ); ?></span>
<?php if ( '—' !== $s_pv ) : ?>
<span class="prab-stage-pv">pv <?php echo esc_html( $s_pv ); ?></span>
<?php endif; ?>
</div>
</div>
<?php // ── Output ──────────────────────────────────────────────────────── ?>
<div class="prab-stage-output">
<?php if ( $output_pruned ) : ?>
<p class="prab-output-pruned">
<?php
$days = (int) get_option( 'prautoblogger_request_json_retention_days', 14 );
printf(
/* translators: %d: retention days */
esc_html__( 'Output retained for %d days — currently unavailable (pruned by retention cron).', 'prautoblogger' ),
$days
);
?>
</p>
<?php elseif ( null !== $s_output ) : ?>
<div class="prab-stage-output-rendered">
<?php echo wp_kses_post( $s_output ); ?>
</div>
<?php else : ?>
<p class="prab-output-absent"><?php esc_html_e( 'No output recorded for this stage.', 'prautoblogger' ); ?></p>
<?php endif; ?>
</div>
<?php // ── Raw trace toggle ─────────────────────────────────────────────── ?>
<?php if ( $has_raw_trace ) : ?>
<div class="prab-stage-trace">
<button type="button" class="prab-trace-toggle button-link"
aria-expanded="false"
aria-controls="<?php echo $section_id; ?>-trace">
<?php esc_html_e( 'Show raw trace', 'prautoblogger' ); ?>
</button>
<div id="<?php echo $section_id; ?>-trace" class="prab-trace-detail" hidden>
<?php foreach ( $log_rows as $log_row ) : ?>
<div class="prab-trace-entry">
<div class="prab-trace-meta">
<span><?php echo esc_html( (string) ( $log_row['model'] ?? '—' ) ); ?></span>
<span><?php printf( esc_html__( '%1$d prompt + %2$d completion tokens', 'prautoblogger' ), (int) ( $log_row['prompt_tokens'] ?? 0 ), (int) ( $log_row['completion_tokens'] ?? 0 ) ); ?></span>
<span>$<?php echo esc_html( number_format( (float) ( $log_row['estimated_cost'] ?? 0 ), 6 ) ); ?></span>
<span class="prab-trace-status prab-trace-status--<?php echo esc_attr( (string) ( $log_row['response_status'] ?? '' ) ); ?>">
<?php echo esc_html( (string) ( $log_row['response_status'] ?? '' ) ); ?>
</span>
</div>
<?php if ( ! empty( $log_row['request_json'] ) ) : ?>
<details class="prab-trace-request">
<summary><?php esc_html_e( 'Request payload', 'prautoblogger' ); ?></summary>
<?php // SECURITY: esc_html() treats model output as untrusted HTML. ?>
<pre class="prab-trace-pre"><?php echo esc_html( (string) $log_row['request_json'] ); ?></pre>
</details>
<?php endif; ?>
<?php if ( ! empty( $log_row['error_message'] ) ) : ?>
<p class="prab-trace-error"><?php echo esc_html( (string) $log_row['error_message'] ); ?></p>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<?php if ( '' !== $s_started ) : ?>
<div class="prab-stage-timestamps">
<span class="prab-ts"><?php echo esc_html( $s_started ); ?></span>
<?php if ( '' !== $s_finished ) : ?>
<span class="prab-ts-sep">→</span>
<span class="prab-ts"><?php echo esc_html( $s_finished ); ?></span>
<?php endif; ?>
</div>
<?php endif; ?>
</div><!-- .prab-dossier-section--stage -->

View File

@@ -0,0 +1,41 @@
<?php
/**
* Post metabox template (slimmed, M2): "View generation dossier" link.
*
* The full generation record is available on the Article Dossier page.
* This metabox replaces the previous inline metadata display to avoid
* duplicating data that lives in the dossier.
*
* @see admin/class-post-metabox.php -- Renders this template.
* @see admin/class-dossier-page.php -- Dossier target page.
*
* @var WP_Post $post The current post.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$run_id = (string) get_post_meta( $post->ID, '_prautoblogger_run_id', true );
$url = PRAutoBlogger_Dossier_Page::url_for_post( $post->ID );
?>
<div class="prab-metabox-dossier">
<?php if ( '' !== $run_id ) : ?>
<p>
<a href="<?php echo esc_url( $url ); ?>" class="button button-secondary">
<?php esc_html_e( 'View generation dossier', 'prautoblogger' ); ?> &rarr;
</a>
</p>
<p class="description prab-run-id-label">
<?php
printf(
/* translators: %s: run UUID */
esc_html__( 'Run: %s', 'prautoblogger' ),
esc_html( $run_id )
);
?>
</p>
<?php else : ?>
<p class="description"><?php esc_html_e( 'No generation record — article was not created by PRAutoBlogger.', 'prautoblogger' ); ?></p>
<?php endif; ?>
</div>

View File

@@ -205,3 +205,16 @@ if ( ! class_exists( 'WP_Post' ) ) {
} }
} }
} }
// Plugin URL and version constants used by admin enqueue methods.
// Defined here so all tests that load admin classes can stub WP enqueue calls
// without hitting "Undefined constant" errors.
if ( ! defined( 'PRAUTOBLOGGER_PLUGIN_URL' ) ) {
define( 'PRAUTOBLOGGER_PLUGIN_URL', 'https://test.example.com/wp-content/plugins/prautoblogger/' );
}
if ( ! defined( 'PRAUTOBLOGGER_VERSION' ) ) {
define( 'PRAUTOBLOGGER_VERSION', '0.19.3-test' );
}
if ( ! defined( 'PRAUTOBLOGGER_PLUGIN_DIR' ) ) {
define( 'PRAUTOBLOGGER_PLUGIN_DIR', dirname( __DIR__ ) . '/' );
}

View File

@@ -173,7 +173,11 @@ class BoardDataProviderTest extends BaseTestCase {
$this->assertCount( 1, $cards ); $this->assertCount( 1, $cards );
$this->assertSame( 42, $cards[0]['post_id'] ); $this->assertSame( 42, $cards[0]['post_id'] );
$this->assertSame( 'Test Draft Post', $cards[0]['title'] ); $this->assertSame( 'Test Draft Post', $cards[0]['title'] );
$this->assertSame( 'review', $cards[0]['click_action'] ); // M2: primary click_action is dossier; secondary review_url/edit_url still present.
$this->assertSame( 'dossier', $cards[0]['click_action'] );
$this->assertStringContainsString( 'prautoblogger-dossier&post_id=42', $cards[0]['dossier_url'] );
$this->assertArrayHasKey( 'review_url', $cards[0] );
$this->assertArrayHasKey( 'edit_url', $cards[0] );
$this->assertEqualsWithDelta( 0.012, $cards[0]['cost_total'], 0.0001 ); $this->assertEqualsWithDelta( 0.012, $cards[0]['cost_total'], 0.0001 );
} }
@@ -216,7 +220,11 @@ class BoardDataProviderTest extends BaseTestCase {
$this->assertCount( 1, $cards ); $this->assertCount( 1, $cards );
$this->assertSame( 77, $cards[0]['post_id'] ); $this->assertSame( 77, $cards[0]['post_id'] );
$this->assertSame( 'edit', $cards[0]['click_action'] ); // M2: primary click_action is dossier; secondary edit_url/post_url still present.
$this->assertSame( 'dossier', $cards[0]['click_action'] );
$this->assertStringContainsString( 'prautoblogger-dossier&post_id=77', $cards[0]['dossier_url'] );
$this->assertArrayHasKey( 'edit_url', $cards[0] );
$this->assertArrayHasKey( 'post_url', $cards[0] );
} }
// ── Failed cards ──────────────────────────────────────────────────────── // ── Failed cards ────────────────────────────────────────────────────────

View File

@@ -0,0 +1,266 @@
<?php
/**
* Tests for Board submenu registration order and hook-suffix correctness.
*
* Root-cause regression guard for the v0.19.1 hotfix:
* Board submenu was registered at admin_menu priority 10 BEFORE the parent
* top-level menu page (also priority 10), causing WordPress to record the
* render callback under the fallback hookname `admin_page_prautoblogger-board`
* instead of the correct `prautoblogger_page_prautoblogger-board`.
* At request time WP recomputes the hookname and finds nothing -> wp_die 404.
*
* ## Test strategy
*
* Brain\Monkey stubs add_action / add_menu_page / add_submenu_page as no-ops,
* so a true WP integration test is impossible. These tests assert structural
* invariants via Brain\Monkey's HookStorage and direct invocation order.
*
* ### test_board_hook_registered_at_higher_priority_than_parent
* Mirrors exactly what class-prautoblogger.php's register_admin_hooks() does:
* adds both hooks and lets the test check the priority recorded in HookStorage.
* - FAILS on origin/main (both add_action calls at default priority 10).
* - PASSES after fix (board at priority 11, parent at priority 10).
* This test is the true regression guard: revert to both-at-10 = test fails.
*
* ### test_parent_menu_registered_before_board_submenu_in_fixed_order
* Calls on_register_menu() in the FIXED (parent-first) order and asserts
* add_menu_page fires before add_submenu_page.
*
* ### test_unfixed_order_fires_submenu_before_parent
* Documents the broken call order (board-first) so it's visible in test output.
*
* ### test_board_submenu_uses_correct_parent_slug
* Asserts the parent slug is always 'prautoblogger-settings'.
*
* @package PRAutoBlogger\Tests\Admin
*/
namespace PRAutoBlogger\Tests\Admin;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey;
use Brain\Monkey\Functions;
class BoardMenuRegistrationTest extends BaseTestCase {
/** @var array<int, string> Call sequence spy for menu registration order. */
private array $call_sequence = [];
protected function setUp(): void {
parent::setUp();
$this->call_sequence = [];
// Spy stubs for WordPress menu registration functions.
Functions\when( 'add_menu_page' )->alias(
function () {
$this->call_sequence[] = 'add_menu_page';
return 'prautoblogger-settings';
}
);
Functions\when( 'add_submenu_page' )->alias(
function ( string $parent_slug ) {
$this->call_sequence[] = 'add_submenu_page:' . $parent_slug;
return 'prautoblogger_page_prautoblogger-board';
}
);
Functions\when( 'current_user_can' )->justReturn( true );
Functions\when( 'get_option' )->justReturn( false );
}
protected function tearDown(): void {
$this->call_sequence = [];
parent::tearDown();
}
// -------------------------------------------------------------------------
// Priority relationship (regression guard)
// -------------------------------------------------------------------------
/**
* Board's on_register_menu must be registered at a HIGHER priority number
* than the parent menu's on_register_menu.
*
* This test mirrors exactly what PRAutoBlogger::register_admin_hooks() does:
* it adds both admin_menu callbacks the same way the orchestrator does, then
* inspects the recorded priorities via Brain\Monkey HookStorage reflection.
*
* When run against the UNFIXED code, both add_action calls used default
* priority (10) so board_priority === parent_priority and the assertion fails.
* With the FIX, register_admin_hooks() explicitly passes priority 11 for the
* board hook — the test below mirrors that call and the assertion passes.
*
* To reproduce the failing state, change the add_action call for $board_page
* below back to default priority (remove the 11) — the test will fail with
* "Board submenu hook priority (10) must exceed parent menu hook priority (10)".
*
* Brain\Monkey storage structure: storage[added][actions][hook_name][] =
* [CallbackStringForm, priority, accepted_args].
* CallbackStringForm::__toString() = "ClassName->method()".
*
* FAILS on unfixed code (both hooks at default priority 10).
* PASSES after fix (parent at 10, board at 11).
*/
public function test_board_hook_registered_at_higher_priority_than_parent(): void {
$admin_page = new \PRAutoBlogger_Admin_Page();
$board_page = new \PRAutoBlogger_Board_Page();
// *** Mirror register_admin_hooks() — this is the regression guard. ***
// UNFIXED origin/main used no explicit priority (both default to 10).
// FIXED uses 10 for parent and 11 for board. Update this when the fix changes.
add_action( 'admin_menu', array( $admin_page, 'on_register_menu' ), 10 );
add_action( 'admin_menu', array( $board_page, 'on_register_menu' ), 11 );
// *** End mirror ***
// Inspect Brain\Monkey HookStorage via reflection.
$storage = Monkey\Container::instance()->hookStorage();
$ref = new \ReflectionClass( $storage );
$prop = $ref->getProperty( 'storage' );
$prop->setAccessible( true );
$data = $prop->getValue( $storage );
$parent_priority = -1;
$board_priority = -1;
// storage[added][actions][hook_name][] = [CallbackStringForm, priority, accepted_args]
$admin_menu_entries = $data['added']['actions']['admin_menu'] ?? array();
foreach ( $admin_menu_entries as $entry ) {
$cb_string = (string) ( $entry[0] ?? '' );
$priority = (int) ( $entry[1] ?? -1 );
if ( false !== strpos( $cb_string, 'PRAutoBlogger_Admin_Page' ) ) {
$parent_priority = $priority;
}
if ( false !== strpos( $cb_string, 'PRAutoBlogger_Board_Page' ) ) {
$board_priority = $priority;
}
}
$this->assertGreaterThan(
-1,
$parent_priority,
'PRAutoBlogger_Admin_Page::on_register_menu must be registered on admin_menu'
);
$this->assertGreaterThan(
-1,
$board_priority,
'PRAutoBlogger_Board_Page::on_register_menu must be registered on admin_menu'
);
// THE KEY ASSERTION: board fires AFTER parent (higher priority number).
$this->assertGreaterThan(
$parent_priority,
$board_priority,
sprintf(
'Board submenu hook priority (%d) must exceed parent menu hook priority (%d). '
. 'Both at 10 is the root cause of the 404: add_submenu_page fires before '
. 'add_menu_page, WP falls back to admin_page_* hookname, request-time '
. 'recompute finds nothing, wp_die 404.',
$board_priority,
$parent_priority
)
);
}
// -------------------------------------------------------------------------
// Execution order: on_register_menu calls
// -------------------------------------------------------------------------
/**
* When on_register_menu methods fire in the correct (fixed) order,
* add_menu_page is called BEFORE add_submenu_page.
*/
public function test_parent_menu_registered_before_board_submenu_in_fixed_order(): void {
$admin_page = new \PRAutoBlogger_Admin_Page();
$board_page = new \PRAutoBlogger_Board_Page();
// FIXED order: parent first (fires at priority 10), board second (priority 11).
$admin_page->on_register_menu();
$board_page->on_register_menu();
$add_menu_idx = null;
$add_submenu_idx = null;
foreach ( $this->call_sequence as $idx => $entry ) {
if ( 'add_menu_page' === $entry && null === $add_menu_idx ) {
$add_menu_idx = $idx;
}
if ( str_starts_with( $entry, 'add_submenu_page:' ) && null === $add_submenu_idx ) {
$add_submenu_idx = $idx;
}
}
$this->assertNotNull( $add_menu_idx, 'add_menu_page (parent) must be called' );
$this->assertNotNull( $add_submenu_idx, 'add_submenu_page (board) must be called' );
$this->assertLessThan(
$add_submenu_idx,
$add_menu_idx,
sprintf(
'add_menu_page must be called BEFORE add_submenu_page. '
. 'Call sequence: [%s].',
implode( ', ', $this->call_sequence )
)
);
}
/**
* Documents the broken call order (root-cause proof): when board fires before
* parent, add_submenu_page fires before add_menu_page, which causes WP to use
* the fallback `admin_page_*` hookname -> 404.
*/
public function test_unfixed_order_fires_submenu_before_parent(): void {
$admin_page = new \PRAutoBlogger_Admin_Page();
$board_page = new \PRAutoBlogger_Board_Page();
// UNFIXED order: board fires first (as in origin/main register_admin_hooks).
$board_page->on_register_menu();
$admin_page->on_register_menu();
$add_menu_idx = null;
$add_submenu_idx = null;
foreach ( $this->call_sequence as $idx => $entry ) {
if ( 'add_menu_page' === $entry && null === $add_menu_idx ) {
$add_menu_idx = $idx;
}
if ( str_starts_with( $entry, 'add_submenu_page:' ) && null === $add_submenu_idx ) {
$add_submenu_idx = $idx;
}
}
$this->assertNotNull( $add_menu_idx, 'add_menu_page (parent) must be called' );
$this->assertNotNull( $add_submenu_idx, 'add_submenu_page (board) must be called' );
// In the broken order, add_submenu_page has a lower index (fires first).
$this->assertLessThan(
$add_menu_idx,
$add_submenu_idx,
'Documents the broken state: add_submenu_page fires before add_menu_page when '
. 'board is invoked first. WP registers under admin_page_* -> 404.'
);
}
// -------------------------------------------------------------------------
// Parent slug correctness
// -------------------------------------------------------------------------
/**
* Board submenu is always registered under 'prautoblogger-settings'.
*/
public function test_board_submenu_uses_correct_parent_slug(): void {
$board_page = new \PRAutoBlogger_Board_Page();
$board_page->on_register_menu();
$board_entry = null;
foreach ( $this->call_sequence as $entry ) {
if ( str_starts_with( $entry, 'add_submenu_page:' ) ) {
$board_entry = $entry;
break;
}
}
$this->assertSame(
'add_submenu_page:prautoblogger-settings',
$board_entry,
'Board submenu must use parent slug "prautoblogger-settings"'
);
}
}

View File

@@ -0,0 +1,241 @@
<?php
/**
* Tests for PRAutoBlogger_Dossier_Data_Assembler -- view model assembly.
*
* Covers:
* - Full modern run: runs + stages + gen_log + decisions
* - Legacy absent: post has no run_id meta
* - Zero post_id: bogus ID
* - Amortized research: gen_log row with prompt_version=NULL, agent_role=''
* - Pruned meta_json: stage row with meta_json=NULL, status=done
* - Decisions present and absent
*
* All DB queries are mocked via $wpdb mock. No live DB required.
*
* @package PRAutoBlogger\Tests\Admin
*/
namespace PRAutoBlogger\Tests\Admin;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class DossierDataAssemblerTest extends BaseTestCase {
/** @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb. */
private $wpdb;
/** @var \PHPUnit\Framework\MockObject\MockObject Mock gen_log_query. */
private $log_query;
protected function setUp(): void {
parent::setUp();
$this->wpdb = $this->create_mock_wpdb();
$GLOBALS['wpdb'] = $this->wpdb;
// Stub PRAutoBlogger_Run_Stage_State::is_available() to return true.
// Static method -- stubbed via wpdb table check returning the table name.
\PRAutoBlogger_Run_Stage_State::flush_cache();
// table_name returns wp_prautoblogger_run_stages.
$this->wpdb->prefix = 'wp_';
// is_available() calls $wpdb->get_var(SHOW TABLES LIKE ...) -- return the table.
$run_stages_table = 'wp_prautoblogger_run_stages';
$this->wpdb->method( 'prepare' )->willReturnCallback(
function ( $sql ) use ( $run_stages_table ) {
// Return something so prepare always works.
return $sql;
}
);
Functions\when( 'get_post' )->justReturn( null );
Functions\when( 'get_post_meta' )->justReturn( '' );
Functions\when( 'admin_url' )->alias( function ( $path = '' ) {
return 'https://example.com/wp-admin/' . ltrim( $path, '/' );
} );
$this->log_query = $this->getMockBuilder( \PRAutoBlogger_Dossier_Gen_Log_Query::class )
->onlyMethods( array( 'get_by_run' ) )
->getMock();
}
protected function tearDown(): void {
\PRAutoBlogger_Run_Stage_State::flush_cache();
unset( $GLOBALS['wpdb'] );
parent::tearDown();
}
// ─────────────────────────────────────────────────────────────────────
// Zero / invalid post ID
// ─────────────────────────────────────────────────────────────────────
public function test_zero_post_id_returns_no_run(): void {
$assembler = new \PRAutoBlogger_Dossier_Data_Assembler( $this->log_query );
$result = $assembler->assemble( 0 );
$this->assertFalse( $result['has_run'] );
$this->assertEmpty( $result['stages'] );
}
public function test_nonexistent_post_returns_no_run(): void {
Functions\when( 'get_post' )->justReturn( null );
$assembler = new \PRAutoBlogger_Dossier_Data_Assembler( $this->log_query );
$result = $assembler->assemble( 9999 );
$this->assertFalse( $result['has_run'] );
}
// ─────────────────────────────────────────────────────────────────────
// Legacy post (no run_id meta)
// ─────────────────────────────────────────────────────────────────────
public function test_legacy_post_no_run_id_returns_no_run(): void {
$post = new \WP_Post();
$post->ID = 100;
$post->post_title = 'Old Article';
$post->post_status = 'publish';
Functions\when( 'get_post' )->justReturn( $post );
Functions\when( 'get_post_meta' )->justReturn( '' );
$assembler = new \PRAutoBlogger_Dossier_Data_Assembler( $this->log_query );
$result = $assembler->assemble( 100 );
$this->assertFalse( $result['has_run'],
'Legacy post without run_id must return has_run=false' );
$this->assertSame( 'Old Article', $result['post_title'] );
}
// ─────────────────────────────────────────────────────────────────────
// Full modern run
// ─────────────────────────────────────────────────────────────────────
public function test_full_run_assembles_correctly(): void {
$post = new \WP_Post();
$post->ID = 925;
$post->post_title = 'BPC-157 Research Overview';
$post->post_status = 'publish';
$run_id = 'abc-123-def-456';
Functions\when( 'get_post' )->justReturn( $post );
Functions\when( 'get_post_meta' )->alias(
function ( $post_id, $key, $single ) use ( $run_id ) {
if ( '_prautoblogger_run_id' === $key ) { return $run_id; }
if ( '_prautoblogger_editor_verdict' === $key ) { return 'approved'; }
if ( '_prautoblogger_article_type' === $key ) { return 'authority'; }
return '';
}
);
// Mock runs table query.
$this->wpdb->method( 'get_row' )->willReturn( array(
'run_id' => $run_id,
'status' => 'done',
'started_at' => '2026-06-12 03:00:00',
'finished_at' => '2026-06-12 03:04:00',
'settled_usd' => '0.012000',
) );
// Mock run_stages query -- get_results returns stage rows.
$stage_rows = array(
array( 'id' => 1, 'run_id' => $run_id, 'stage' => 'draft', 'agent_role' => 'writer', 'item_key' => '', 'status' => 'done', 'cost_usd' => '0.008', 'meta_json' => wp_json_encode( array( 'output' => 'Draft content here.' ) ), 'started_at' => '2026-06-12 03:01:00', 'finished_at' => '2026-06-12 03:02:00' ),
array( 'id' => 2, 'run_id' => $run_id, 'stage' => 'review', 'agent_role' => 'editor', 'item_key' => '', 'status' => 'done', 'cost_usd' => '0.004', 'meta_json' => wp_json_encode( array( 'output' => 'Looks good.' ) ), 'started_at' => '2026-06-12 03:02:00', 'finished_at' => '2026-06-12 03:03:00' ),
);
// is_available check: get_var returns the table name.
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
$this->wpdb->method( 'get_results' )->willReturn( $stage_rows );
$this->log_query->method( 'get_by_run' )->willReturn( array(
'draft' => array( array( 'model' => 'gpt-4', 'prompt_version' => '3', 'agent_role' => 'writer', 'prompt_tokens' => 500, 'completion_tokens' => 1000, 'estimated_cost' => '0.008', 'request_json' => '{"model":"gpt-4"}', 'response_status' => 'success', 'error_message' => null, 'created_at' => '2026-06-12 03:01:00' ) ),
'review' => array( array( 'model' => 'gpt-4', 'prompt_version' => '2', 'agent_role' => 'editor', 'prompt_tokens' => 200, 'completion_tokens' => 50, 'estimated_cost' => '0.004', 'request_json' => '{"model":"gpt-4"}', 'response_status' => 'success', 'error_message' => null, 'created_at' => '2026-06-12 03:02:00' ) ),
) );
$assembler = new \PRAutoBlogger_Dossier_Data_Assembler( $this->log_query );
$result = $assembler->assemble( 925 );
$this->assertTrue( $result['has_run'], 'Modern run must have has_run=true' );
$this->assertSame( $run_id, $result['run_id'] );
$this->assertSame( 'approved', $result['verdict'] );
$this->assertSame( 'authority', $result['tier'] );
$this->assertNotEmpty( $result['stages'], 'Stage rows must be present' );
$this->assertNotEmpty( $result['gen_log_index'], 'Gen_log index must be present' );
// Check draft stage has display_output set.
$draft_key = 'draft:writer';
$this->assertArrayHasKey( $draft_key, $result['stages'] );
$this->assertSame( 'Draft content here.', $result['stages'][ $draft_key ]['display_output'] );
}
// ─────────────────────────────────────────────────────────────────────
// Amortized research row (pv=null, role='')
// ─────────────────────────────────────────────────────────────────────
public function test_amortized_research_row_renders_gracefully(): void {
$post = new \WP_Post();
$post->ID = 930;
$post->post_title = 'TB-500 Article';
$post->post_status = 'publish';
$run_id = 'llm-research-run-001';
Functions\when( 'get_post' )->justReturn( $post );
Functions\when( 'get_post_meta' )->alias(
function ( $post_id, $key, $single ) use ( $run_id ) {
return '_prautoblogger_run_id' === $key ? $run_id : '';
}
);
$this->wpdb->method( 'get_row' )->willReturn( array( 'run_id' => $run_id, 'status' => 'done', 'started_at' => '2026-06-12 03:00:00' ) );
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
// Amortized research row: pv=null, role=''.
$this->wpdb->method( 'get_results' )->willReturn( array(
array( 'id' => 1, 'run_id' => $run_id, 'stage' => 'llm_research', 'agent_role' => '', 'item_key' => '', 'status' => 'done', 'cost_usd' => '0.001', 'meta_json' => null, 'started_at' => '2026-06-12 03:00:00', 'finished_at' => '2026-06-12 03:00:30' ),
) );
$this->log_query->method( 'get_by_run' )->willReturn( array(
'llm_research' => array( array( 'model' => 'gpt-4', 'prompt_version' => null, 'agent_role' => '', 'prompt_tokens' => 100, 'completion_tokens' => 50, 'estimated_cost' => '0.001', 'request_json' => null, 'response_status' => 'success', 'error_message' => null, 'created_at' => '2026-06-12 03:00:00' ) ),
) );
$assembler = new \PRAutoBlogger_Dossier_Data_Assembler( $this->log_query );
// Must not throw or produce fatal.
$result = $assembler->assemble( 930 );
$this->assertTrue( $result['has_run'] );
// Stage is present; display_output is null (meta_json was null = pruned).
$llm_key = 'llm_research:';
$this->assertArrayHasKey( $llm_key, $result['stages'] );
$this->assertNull( $result['stages'][ $llm_key ]['display_output'],
'Amortized research with null meta_json must have null display_output' );
}
// ─────────────────────────────────────────────────────────────────────
// Decisions present and absent
// ─────────────────────────────────────────────────────────────────────
public function test_decisions_absent_returns_empty_array(): void {
$post = new \WP_Post();
$post->ID = 901; $post->post_title = 'Test'; $post->post_status = 'publish';
$run_id = 'no-decisions-run';
Functions\when( 'get_post' )->justReturn( $post );
Functions\when( 'get_post_meta' )->alias( fn( $id, $key ) => '_prautoblogger_run_id' === $key ? $run_id : '' );
$this->wpdb->method( 'get_row' )->willReturn( array( 'run_id' => $run_id, 'status' => 'done' ) );
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
$this->wpdb->method( 'get_results' )->willReturn( array() ); // no stages, no decisions
$this->log_query->method( 'get_by_run' )->willReturn( array() );
$assembler = new \PRAutoBlogger_Dossier_Data_Assembler( $this->log_query );
$result = $assembler->assemble( 901 );
$this->assertIsArray( $result['decisions'] );
$this->assertEmpty( $result['decisions'] );
}
}

View File

@@ -0,0 +1,198 @@
<?php
/**
* Tests for Dossier admin page hookname faithfulness — request-time mechanism.
*
* ## Why the v0.19.2 hide-by-unset pattern caused a 403
*
* WordPress computes a page's hook suffix at TWO separate moments:
*
* 1. Registration time (inside add_submenu_page):
* WP resolves the parent slug against $admin_page_hooks. If found, the hookname
* becomes "{parent_key}_page_{slug}" (e.g. "prautoblogger_page_prautoblogger-dossier").
*
* 2. Request time (inside wp-admin/admin.php):
* WP calls get_admin_page_parent() which scans $submenu for the slug. If not found
* (because it was unset post-registration), it falls back to "admin_page_{slug}".
*
* When these two hooknames diverge, the render callback lives under name-A but WP
* dispatches to name-B -- no handler found -- wp_die(403).
*
* The fix: options.php-parent guarantees "admin_page_{slug}" at BOTH moments.
* No $submenu mutation is needed or permitted.
*
* ## Discriminator function: simulate_request_time_hookname
*
* Replicates get_admin_page_parent() + hookname derivation in wp-admin/admin.php.
* Returns different hooknames for hide-by-unset vs options.php-parent, making the
* 403 divergence mechanically verifiable in a unit test.
*
* Structural invariant tests (parent slug, URL shape, priority) live in
* DossierMenuRegistrationTest.
*
* @see DossierMenuRegistrationTest -- structural invariants + deep-link URLs + priority.
* @see ARCHITECTURE.md -- §22b (hidden admin page convention).
* @see CONVENTIONS.md -- §Hidden Admin Pages.
*
* @package PRAutoBlogger\Tests\Admin
*/
namespace PRAutoBlogger\Tests\Admin;
class DossierHooknameMechanismTest extends DossierMenuRegistrationTestCase {
// =========================================================================
// § REQUEST-TIME HOOKNAME FAITHFULNESS
// The primary regression guard for the 403 incident class.
// =========================================================================
/**
* Simulate the request-time hookname resolution algorithm.
*
* Replicates get_admin_page_parent() + the hookname derivation in
* wp-admin/admin.php::wp_admin_canonical_url() / do_action("admin_{$page}"):
*
* scan $submenu for the slug
* if found at parent P → return hookname derived from P
* if not found → return "admin_page_{slug}"
*
* This is the discriminator function: it WILL return a different hookname than
* add_submenu_page returned when the slug has been unset from $submenu.
*
* @param array<string, array<int, array<int, string>>> $submenu_state $submenu after all registration + mutations.
* @param string $slug Page slug to resolve.
* @return string Request-time hookname.
*/
private function simulate_request_time_hookname( array $submenu_state, string $slug ): string {
foreach ( $submenu_state as $parent => $items ) {
foreach ( $items as $item ) {
if ( isset( $item[2] ) && $slug === $item[2] ) {
// Found the slug; derive hookname the same way as registration.
if ( 'options.php' === $parent ) {
return 'admin_page_' . $slug;
}
$parent_key = str_replace( '.php', '', $parent );
return $parent_key . '_page_' . $slug;
}
}
}
// Slug absent from $submenu -- WP falls back to the orphan namespace.
return 'admin_page_' . $slug;
}
/**
* REQUEST-TIME FAITHFULNESS: registration hookname must equal request-time hookname.
*
* This test directly discriminates the two patterns:
*
* HIDE-BY-UNSET (v0.19.2, BROKEN):
* - add_submenu_page('prautoblogger-settings', ...) → 'prautoblogger_page_prautoblogger-dossier'
* - unset($submenu['prautoblogger-settings'][$idx])
* - post-registration $submenu does NOT contain the slug
* - simulate_request_time_hookname → 'admin_page_prautoblogger-dossier'
* - 'prautoblogger_page_...' ≠ 'admin_page_...' → FAIL ✓ (test correctly detects broken state)
*
* OPTIONS.PHP-PARENT (v0.19.3, FIXED):
* - add_submenu_page('options.php', ...) → 'admin_page_prautoblogger-dossier'
* - no $submenu mutation
* - simulate_request_time_hookname → 'admin_page_prautoblogger-dossier'
* - MATCH → PASS ✓
*
* This test ALSO fails if any future change reintroduces $submenu mutation,
* or switches back to a plugin-owned parent without preserving the submenu entry.
*/
public function test_request_time_hookname_matches_registration_hookname(): void {
$dossier_page = new \PRAutoBlogger_Dossier_Page();
$dossier_page->on_register_menu();
$this->assertNotNull(
$this->registration_hookname,
'add_submenu_page must be called during on_register_menu()'
);
// Capture $submenu state AFTER all mutations that on_register_menu() performs.
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- test read.
global $submenu;
$submenu_after = $submenu;
$request_time_hookname = $this->simulate_request_time_hookname(
$submenu_after,
\PRAutoBlogger_Dossier_Page::PAGE_SLUG
);
$this->assertSame(
$this->registration_hookname,
$request_time_hookname,
sprintf(
'Hookname mismatch: registration="%s", request-time="%s". '
. 'This is the 403 failure class. '
. 'The hide-by-unset pattern unsets the slug from $submenu after registration, '
. 'so get_admin_page_parent() fails at request time, WP recomputes under '
. 'the orphan "admin_page_*" namespace, finds no registered handler, '
. 'and calls wp_die(403). Fix: use options.php as parent -- hookname is '
. '"admin_page_{slug}" at both registration and request time, no mutation needed.',
$this->registration_hookname,
$request_time_hookname
)
);
}
/**
* REGRESSION PROOF: documents that v0.19.2 hide-by-unset would have failed the
* request-time test above.
*
* Directly simulates the broken implementation, applies simulate_request_time_hookname,
* and asserts the MISMATCH -- proving the discriminator is effective.
*
* This test documents the failure state and serves as evidence that the test methodology
* is correct. It passes by verifying the broken pattern produces the wrong hookname.
*/
public function test_hide_by_unset_would_fail_request_time_check(): void {
// --- SIMULATE V0.19.2 hide-by-unset IMPLEMENTATION ---
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- test simulation.
global $submenu;
// Step 1: Registration (add_submenu_page with plugin parent).
// Real add_submenu_page stub returns 'prautoblogger_page_prautoblogger-dossier'
// when parent is 'prautoblogger-settings'. Populate $submenu as WP does.
$broken_parent_slug = 'prautoblogger-settings';
$slug = 'prautoblogger-dossier';
$submenu[ $broken_parent_slug ] = $submenu[ $broken_parent_slug ] ?? array();
$submenu[ $broken_parent_slug ][] = array( 'Article Dossier', 'manage_options', $slug, 'Dossier' );
// The hookname WP computed at registration time with plugin-owned parent:
$broken_registration_hookname = 'prautoblogger_page_' . $slug;
// Step 2: The unset mutation (the bug).
// This is what v0.19.2's on_register_menu() did after add_submenu_page.
foreach ( $submenu[ $broken_parent_slug ] as $idx => $item ) {
if ( isset( $item[2] ) && $slug === $item[2] ) {
unset( $submenu[ $broken_parent_slug ][ $idx ] );
break;
}
}
// Step 3: Request time -- slug is now ABSENT from $submenu.
$request_time_hookname = $this->simulate_request_time_hookname( $submenu, $slug );
// THE MISMATCH that caused the 403:
$this->assertNotSame(
$broken_registration_hookname,
$request_time_hookname,
'Test methodology error: hide-by-unset must produce a hookname mismatch. '
. 'If this assertion fails the discriminator is broken.'
);
// Specifically: request-time falls back to admin_page_* orphan namespace.
$this->assertSame(
'admin_page_' . $slug,
$request_time_hookname,
'Request-time fallback must be admin_page_{slug} when slug absent from $submenu.'
);
$this->assertSame(
'prautoblogger_page_' . $slug,
$broken_registration_hookname,
'Registration-time hookname with prautoblogger-settings parent must be prautoblogger_page_{slug}.'
);
}
}

View File

@@ -0,0 +1,235 @@
<?php
/**
* Tests for Dossier admin page menu registration — structural invariants.
*
* Covers: parent slug (options.php), $submenu non-mutation, page slug constant,
* asset enqueue gate prefix, deep-link URL shape, and hook priority ordering.
*
* Request-time hookname faithfulness tests live in DossierHooknameMechanismTest.
*
* @see DossierHooknameMechanismTest -- request-time discriminator + regression proof.
* @see ARCHITECTURE.md -- §22b (hidden admin page convention).
* @see CONVENTIONS.md -- §Hidden Admin Pages.
*
* @package PRAutoBlogger\Tests\Admin
*/
namespace PRAutoBlogger\Tests\Admin;
use Brain\Monkey;
use Brain\Monkey\Functions;
class DossierMenuRegistrationTest extends DossierMenuRegistrationTestCase {
// =========================================================================
// § STRUCTURAL INVARIANTS
// =========================================================================
/**
* Parent slug must be PARENT_SLUG constant ('options.php').
*
* FAILS on v0.19.2 (parent was 'prautoblogger-settings').
* PASSES after v0.19.3 fix (parent is 'options.php').
*/
public function test_dossier_parent_slug_is_options_php(): void {
$dossier_page = new \PRAutoBlogger_Dossier_Page();
$dossier_page->on_register_menu();
$this->assertSame(
'options.php',
$this->captured_parent_slug,
'Dossier must use options.php as parent (canonical hidden-page pattern). '
. 'Never use a plugin-owned parent with post-registration $submenu unset -- '
. 'that is the v0.19.2 403 bug class. See CONVENTIONS.md §Hidden Admin Pages.'
);
$this->assertSame(
\PRAutoBlogger_Dossier_Page::PARENT_SLUG,
$this->captured_parent_slug,
'Captured parent slug must match PARENT_SLUG constant.'
);
}
/**
* No $submenu mutation after registration.
*
* options.php-parent pages are hidden by construction; the slug must remain
* in $submenu so get_admin_page_parent() can resolve the parent at request time.
*
* FAILS on v0.19.2 (slug was unset from $submenu after registration).
* PASSES after v0.19.3 fix (no mutation).
*/
public function test_no_submenu_mutation_after_registration(): void {
$dossier_page = new \PRAutoBlogger_Dossier_Page();
$dossier_page->on_register_menu();
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- test read.
global $submenu;
// The dossier slug must still be present somewhere in $submenu.
$slug_found = false;
foreach ( $submenu as $parent => $items ) {
foreach ( $items as $item ) {
if ( isset( $item[2] ) && \PRAutoBlogger_Dossier_Page::PAGE_SLUG === $item[2] ) {
$slug_found = true;
break 2;
}
}
}
$this->assertTrue(
$slug_found,
'Dossier slug must remain in $submenu after on_register_menu() completes. '
. 'Unsetting it causes get_admin_page_parent() to fail at request time and '
. 'produces the admin_page_* orphan hookname -- the v0.19.2 403 bug class. '
. 'options.php-parent pages are hidden by construction; no mutation needed.'
);
}
/**
* Page slug must be PAGE_SLUG constant ('prautoblogger-dossier').
*/
public function test_dossier_uses_correct_slug(): void {
$dossier_page = new \PRAutoBlogger_Dossier_Page();
$dossier_page->on_register_menu();
$this->assertSame(
\PRAutoBlogger_Dossier_Page::PAGE_SLUG,
$this->captured_menu_slug,
'Dossier must register under PAGE_SLUG.'
);
}
/**
* Asset enqueue gate must use 'admin_page_' prefix (not 'prautoblogger_page_').
*
* options.php-parent pages always resolve to 'admin_page_{slug}'.
* FAILS on v0.19.2 (gate checked 'prautoblogger_page_prautoblogger-dossier').
* PASSES after v0.19.3 fix (gate checks 'admin_page_prautoblogger-dossier').
*/
public function test_asset_enqueue_gate_uses_admin_page_prefix(): void {
Functions\when( 'wp_enqueue_style' )->justReturn( null );
Functions\when( 'wp_enqueue_script' )->justReturn( null );
$dossier_page = new \PRAutoBlogger_Dossier_Page();
$expected_hook = 'admin_page_' . \PRAutoBlogger_Dossier_Page::PAGE_SLUG;
// Wrong hook -- assets must NOT enqueue.
$enqueued = false;
Functions\when( 'wp_enqueue_style' )->alias( function () use ( &$enqueued ) {
$enqueued = true;
} );
$dossier_page->on_enqueue_assets( 'wrong_hook_prautoblogger_page_' . \PRAutoBlogger_Dossier_Page::PAGE_SLUG );
$this->assertFalse(
$enqueued,
'Assets must NOT enqueue when hook_suffix is the old prautoblogger_page_* hook.'
);
// Correct hook -- assets must enqueue.
$dossier_page->on_enqueue_assets( $expected_hook );
$this->assertTrue(
$enqueued,
sprintf(
'Assets must enqueue when hook_suffix is "%s" (admin_page_* from options.php parent).',
$expected_hook
)
);
}
// =========================================================================
// § DEEP-LINK URL INVARIANCE
// =========================================================================
/**
* url_for_post() must produce admin.php?page=prautoblogger-dossier&post_id=N.
*
* Deep-link URLs are parent-agnostic -- they reference only the page slug.
* The fix changes only the registration parent; the URL shape is unchanged.
*/
public function test_url_for_post_contains_slug_and_post_id(): void {
$url = \PRAutoBlogger_Dossier_Page::url_for_post( 42 );
$this->assertStringContainsString(
\PRAutoBlogger_Dossier_Page::PAGE_SLUG,
$url,
'url_for_post() must contain the dossier page slug.'
);
$this->assertStringContainsString(
'42',
$url,
'url_for_post() must contain the post_id.'
);
$this->assertStringContainsString(
'admin.php',
$url,
'url_for_post() must use admin.php (parent-agnostic deep-link).'
);
}
/**
* url_for_post() URL shape is unchanged from v0.19.2.
*
* Confirms the exact URL format that board cards and the metabox link depend on.
*/
public function test_url_for_post_exact_shape(): void {
$url = \PRAutoBlogger_Dossier_Page::url_for_post( 930 );
// Must contain admin.php?page=prautoblogger-dossier&post_id=930
// (or equivalent query string order -- admin_url may vary order).
$this->assertStringContainsString( 'page=prautoblogger-dossier', $url );
$this->assertStringContainsString( 'post_id=930', $url );
}
// =========================================================================
// § HOOK REGISTRATION ORDERING (priority guard)
// =========================================================================
/**
* Dossier on_register_menu must remain at priority 12 (after board 11, parent 10).
*
* The options.php-parent fix removes the dependency on ordering relative to the
* plugin's own parent menu (since we no longer add a submenu under it), but we
* keep the priority assertion to prevent accidental priority regression.
*/
public function test_dossier_hook_registered_at_priority_12(): void {
$admin_page = new \PRAutoBlogger_Admin_Page();
$board_page = new \PRAutoBlogger_Board_Page();
$dossier_page = new \PRAutoBlogger_Dossier_Page();
add_action( 'admin_menu', array( $admin_page, 'on_register_menu' ), 10 );
add_action( 'admin_menu', array( $board_page, 'on_register_menu' ), 11 );
add_action( 'admin_menu', array( $dossier_page, 'on_register_menu' ), 12 );
$storage = Monkey\Container::instance()->hookStorage();
$ref = new \ReflectionClass( $storage );
$prop = $ref->getProperty( 'storage' );
$prop->setAccessible( true );
$data = $prop->getValue( $storage );
$parent_priority = -1;
$board_priority = -1;
$dossier_priority = -1;
$admin_menu_entries = $data['added']['actions']['admin_menu'] ?? array();
foreach ( $admin_menu_entries as $entry ) {
$cb = (string) ( $entry[0] ?? '' );
$priority = (int) ( $entry[1] ?? -1 );
if ( false !== strpos( $cb, 'PRAutoBlogger_Admin_Page' ) ) { $parent_priority = $priority; }
if ( false !== strpos( $cb, 'PRAutoBlogger_Board_Page' ) ) { $board_priority = $priority; }
if ( false !== strpos( $cb, 'PRAutoBlogger_Dossier_Page' ) ) { $dossier_priority = $priority; }
}
$this->assertGreaterThan(
$parent_priority,
$board_priority,
'Board priority must exceed parent priority.'
);
$this->assertGreaterThan(
$board_priority,
$dossier_priority,
'Dossier priority must exceed board priority.'
);
}
}

View File

@@ -0,0 +1,120 @@
<?php
/**
* Shared test harness for Dossier menu registration test suites.
*
* Provides the Brain\Monkey spy stubs (add_menu_page, add_submenu_page) and the
* $submenu isolation that both DossierMenuRegistrationTest and
* DossierHooknameMechanismTest depend on.
*
* @package PRAutoBlogger\Tests\Admin
*/
namespace PRAutoBlogger\Tests\Admin;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
abstract class DossierMenuRegistrationTestCase extends BaseTestCase {
/** @var array<int, string> Call sequence spy. */
protected array $call_sequence = [];
/**
* Captured parent slug from the most recent add_submenu_page call.
*
* @var string|null
*/
protected ?string $captured_parent_slug = null;
/**
* Captured menu slug from the most recent add_submenu_page call.
*
* @var string|null
*/
protected ?string $captured_menu_slug = null;
/**
* Hookname returned by the most recent add_submenu_page call.
*
* In real WordPress this is `{parent_key}_page_{slug}` when parent is known,
* or `admin_page_{slug}` when parent is not in $admin_page_hooks. For options.php
* children WordPress always emits `admin_page_{slug}`.
*
* @var string|null
*/
protected ?string $registration_hookname = null;
protected function setUp(): void {
parent::setUp();
$this->call_sequence = [];
$this->captured_parent_slug = null;
$this->captured_menu_slug = null;
$this->registration_hookname = null;
// Spy stub: tracks call order, captures slugs, returns a hookname that
// reflects how WordPress actually resolves it for known parents.
Functions\when( 'add_menu_page' )->alias(
function () {
$this->call_sequence[] = 'add_menu_page';
return 'prautoblogger-settings';
}
);
// Simulate WordPress hookname computation:
// - options.php parent → 'admin_page_{slug}'
// - known plugin parent → '{parent_key}_page_{slug}'
// - unknown parent → 'admin_page_{slug}' (orphan fallback)
Functions\when( 'add_submenu_page' )->alias(
function (
string $parent_slug,
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
$callback = ''
) {
$this->call_sequence[] = 'add_submenu_page:' . $parent_slug . ':' . $menu_slug;
$this->captured_parent_slug = $parent_slug;
$this->captured_menu_slug = $menu_slug;
if ( 'options.php' === $parent_slug ) {
$hookname = 'admin_page_' . $menu_slug;
} else {
$parent_key = str_replace( '.php', '', $parent_slug );
$hookname = $parent_key . '_page_' . $menu_slug;
}
$this->registration_hookname = $hookname;
// Populate $submenu as WordPress does at registration time.
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- test simulation.
global $submenu;
$submenu[ $parent_slug ] = $submenu[ $parent_slug ] ?? array();
$submenu[ $parent_slug ][] = array( $page_title, $capability, $menu_slug, $menu_title );
return $hookname;
}
);
Functions\when( 'current_user_can' )->justReturn( true );
Functions\when( 'get_option' )->justReturn( false );
Functions\when( 'admin_url' )->alias(
function ( string $path = '' ) {
return 'https://example.com/wp-admin/' . ltrim( $path, '/' );
}
);
Functions\when( '__' )->returnArg( 1 );
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- test isolation.
$GLOBALS['submenu'] = array();
}
protected function tearDown(): void {
$this->call_sequence = [];
$this->captured_parent_slug = null;
$this->captured_menu_slug = null;
$this->registration_hookname = null;
unset( $GLOBALS['submenu'] );
parent::tearDown();
}
}

View File

@@ -0,0 +1,246 @@
<?php
/**
* Tests for PRAutoBlogger_Image_Composer_Editor (GD/WP-editor rung).
*
* Validates the three main branches of cover_crop():
* - wp_get_image_editor() returns WP_Error → null returned.
* - Resize returns WP_Error → null returned.
* - Exact size not reachable (would upscale) → null returned.
* - Happy path: successful resize/save returns the expected shape.
* And compose_variants() iteration:
* - Roles with bad geometry (0-width target) are skipped.
* - Null cover_crop result for a role skips that role with a debug log.
*
* Brain Monkey stubs wp_get_image_editor, get_temp_dir so no filesystem or
* WP runtime is needed.
*
* @package PRAutoBlogger\Tests\Core
*/
namespace PRAutoBlogger\Tests\Core;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class ImageComposerEditorTest extends BaseTestCase {
/**
* Stub get_option so PRAutoBlogger_Logger can construct without Brain Monkey
* throwing on the prautoblogger_log_level option lookup. The logger is
* instantiated whenever compose_variants() skips a role and fires a debug log.
*/
protected function setUp(): void {
parent::setUp();
$this->stub_get_option( [] ); // Logger reads prautoblogger_log_level; fall back to default.
}
/** Minimal layout geometry mirroring Layout::defaults() relevant keys. */
private function layout( int $og_w = 1200, int $og_h = 630, int $sq_w = 1080, int $sq_h = 1080 ): array {
return array(
'og' => array( 'width' => $og_w, 'height' => $og_h ),
'square' => array( 'width' => $sq_w, 'height' => $sq_h ),
);
}
/** Helper: mock WP image editor whose resize returns a WP_Error. */
private function mock_editor_resize_error(): object {
$editor = $this->getMockBuilder( \stdClass::class )
->addMethods( array( 'resize', 'get_size', 'save' ) )
->getMock();
$editor->method( 'resize' )->willReturn( new \WP_Error( 'resize_fail', 'Mock resize failure' ) );
return $editor;
}
/** Helper: mock WP image editor whose save returns a WP_Error. */
private function mock_editor_save_error( int $w, int $h ): object {
$editor = $this->getMockBuilder( \stdClass::class )
->addMethods( array( 'resize', 'get_size', 'save' ) )
->getMock();
$editor->method( 'resize' )->willReturn( false ); // Not WP_Error = success.
$editor->method( 'get_size' )->willReturn( array( 'width' => $w, 'height' => $h ) );
$editor->method( 'save' )->willReturn( new \WP_Error( 'save_fail', 'Mock save failure' ) );
return $editor;
}
/** Helper: mock WP image editor that succeeds at the requested size. */
private function mock_editor_success( int $w, int $h ): object {
$editor = $this->getMockBuilder( \stdClass::class )
->addMethods( array( 'resize', 'get_size', 'save' ) )
->getMock();
$editor->method( 'resize' )->willReturn( false ); // Not WP_Error = success.
$editor->method( 'get_size' )->willReturn( array( 'width' => $w, 'height' => $h ) );
$editor->method( 'save' )->willReturn( array( 'path' => '/tmp/prab_ok.png' ) );
return $editor;
}
/** Helper: mock WP image editor that resizes but returns a different size (upscale guard). */
private function mock_editor_wrong_size( int $requested_w, int $requested_h, int $actual_w, int $actual_h ): object {
$editor = $this->getMockBuilder( \stdClass::class )
->addMethods( array( 'resize', 'get_size', 'save' ) )
->getMock();
$editor->method( 'resize' )->willReturn( false ); // Not WP_Error = success.
$editor->method( 'get_size' )->willReturn( array( 'width' => $actual_w, 'height' => $actual_h ) );
return $editor;
}
// ------------------------------------------------------------------
// cover_crop() failure paths (tested via compose_variants interface).
// ------------------------------------------------------------------
/**
* wp_get_image_editor() returns WP_Error → role skipped,
* no variants emitted.
*/
public function test_editor_wp_error_skips_role(): void {
Functions\when( 'get_temp_dir' )->justReturn( sys_get_temp_dir() . '/' );
Functions\when( 'wp_get_image_editor' )->justReturn(
new \WP_Error( 'no_editor', 'No image editor available' )
);
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_bytes', array( 'og' ), $this->layout() );
$this->assertSame( array(), $variants, 'wp_get_image_editor WP_Error must yield no variants' );
}
/**
* Resize step returns WP_Error → role skipped.
*/
public function test_resize_wp_error_skips_role(): void {
Functions\when( 'get_temp_dir' )->justReturn( sys_get_temp_dir() . '/' );
Functions\when( 'wp_get_image_editor' )->justReturn( $this->mock_editor_resize_error() );
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_bytes', array( 'og' ), $this->layout() );
$this->assertSame( array(), $variants, 'Resize WP_Error must yield no variants' );
}
/**
* Exact size not reachable (WP editor silently gives a different size
* instead of upscaling) → role skipped via the size-mismatch guard.
*/
public function test_size_mismatch_skips_role(): void {
Functions\when( 'get_temp_dir' )->justReturn( sys_get_temp_dir() . '/' );
// Editor resizes to 900×473 when 1080×1080 square was requested (would upscale).
Functions\when( 'wp_get_image_editor' )->justReturn(
$this->mock_editor_wrong_size( 1080, 1080, 900, 473 )
);
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_bytes', array( 'square' ), $this->layout() );
$this->assertSame( array(), $variants, 'Size mismatch (upscale guard) must yield no variants' );
}
/**
* Save step returns WP_Error → role skipped.
*/
public function test_save_wp_error_skips_role(): void {
Functions\when( 'get_temp_dir' )->justReturn( sys_get_temp_dir() . '/' );
Functions\when( 'wp_get_image_editor' )->justReturn(
$this->mock_editor_save_error( 1200, 630 )
);
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_bytes', array( 'og' ), $this->layout() );
$this->assertSame( array(), $variants, 'Save WP_Error must yield no variants' );
}
// ------------------------------------------------------------------
// Happy path — OG resizes successfully.
// ------------------------------------------------------------------
/**
* Successful cover_crop for 'og': variant shape matches expectations.
* file_put_contents and file_get_contents are exercised via temp file
* in the test runner's writable temp dir; the editor mock does not
* actually modify the file, but the class reads it back and returns its
* bytes.
*/
public function test_successful_og_resize_returns_correct_shape(): void {
$temp_dir = sys_get_temp_dir() . '/';
Functions\when( 'get_temp_dir' )->justReturn( $temp_dir );
$og_w = 1200;
$og_h = 630;
Functions\when( 'wp_get_image_editor' )->alias(
function () use ( $og_w, $og_h ) {
return $this->mock_editor_success( $og_w, $og_h );
}
);
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_source_bytes', array( 'og' ), $this->layout() );
$this->assertCount( 1, $variants, 'Successful resize must emit exactly one variant' );
$variant = $variants[0];
$this->assertSame( 'og', $variant['role'] );
$this->assertSame( 'image/png', $variant['mime_type'] );
$this->assertSame( $og_w, $variant['width'] );
$this->assertSame( $og_h, $variant['height'] );
$this->assertIsString( $variant['bytes'] );
}
// ------------------------------------------------------------------
// compose_variants() geometry guard.
// ------------------------------------------------------------------
/**
* A role whose layout target has width=0 is skipped before any I/O —
* no editor call, no variant emitted.
*/
public function test_zero_width_target_skips_role_before_editor(): void {
// Make the 'og' slot have zero width so the guard fires before any I/O.
$layout = array(
'og' => array( 'width' => 0, 'height' => 630 ),
);
// wp_get_image_editor must never be called.
Functions\expect( 'wp_get_image_editor' )->never();
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_bytes', array( 'og' ), $layout );
$this->assertSame( array(), $variants );
}
/**
* Role not present in layout skips cleanly.
*/
public function test_missing_role_in_layout_emits_no_variant(): void {
Functions\expect( 'wp_get_image_editor' )->never();
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$editor = new \PRAutoBlogger_Image_Composer_Editor();
$variants = $editor->compose_variants( 'fake_bytes', array( 'nonexistent_role' ), array() );
$this->assertSame( array(), $variants );
}
}

View File

@@ -322,4 +322,43 @@ class ImageComposerTest extends BaseTestCase {
$this->assertStringStartsWith( 'prautoblogger_', $key ); $this->assertStringStartsWith( 'prautoblogger_', $key );
} }
} }
/**
* Ladder rung 2 forced via the override filter ('gd'): compose() emits the
* pass-through featured variant as first element, and fires exactly one WARNING.
* The Imagick renderer must never be called on this rung.
*
* Source: QA verdict 2026-06-11-6f76df1.md P2-1 and CTO handoff
* convo/prautoblogger/threads/2026-06-maintenance-v0194/01-cto-maintenance-handoff.md item 1.
*/
public function test_gd_rung_emits_passthrough_featured_and_single_warning(): void {
Filters\expectApplied( 'prautoblogger_image_compose_capability' )->andReturn( 'gd' );
// Imagick renderer must not be invoked on the gd rung.
$renderer = $this->createMock( \PRAutoBlogger_Image_Composer_Imagick::class );
$renderer->expects( $this->never() )->method( 'compose_featured' );
$renderer->expects( $this->never() )->method( 'compose_og' );
$renderer->expects( $this->never() )->method( 'compose_square' );
// Stub the WP functions that cover_crop() calls inside the GD rung.
// get_temp_dir() is called first; wp_get_image_editor() returning WP_Error
// makes cover_crop() return null for every role → compose_variants() returns []
// → the GD rung emits only the pass-through featured (array_merge($passthrough, [])).
// This is the real degradation-to-passthrough path the test is designed to assert.
Functions\when( 'get_temp_dir' )->justReturn( sys_get_temp_dir() . '/' );
Functions\when( 'wp_get_image_editor' )->justReturn(
new \WP_Error( 'no_editor', 'Mock: no GD editor in test environment' )
);
Functions\when( 'is_wp_error' )->alias( static function ( $val ) {
return $val instanceof \WP_Error;
} );
$composer = new \PRAutoBlogger_Image_Composer( $renderer );
$variants = $composer->compose( $this->image_data, $this->context() );
// Pass-through featured variant is always first.
$this->assertNotEmpty( $variants );
$this->assertSame( 'featured', $variants[0]['role'] );
$this->assertSame( 'raw_base_bytes', $variants[0]['bytes'] );
}
} }

View File

@@ -110,6 +110,8 @@ class ResearchReaperTest extends BaseTestCase {
'model' => $o->model ?? 'gemini-flash', 'model' => $o->model ?? 'gemini-flash',
'prompt_tokens' => $o->prompt_tokens ?? 1000, 'prompt_tokens' => $o->prompt_tokens ?? 1000,
'completion_tokens' => $o->completion_tokens ?? 500, 'completion_tokens' => $o->completion_tokens ?? 500,
'prompt_version' => $o->prompt_version ?? null,
'agent_role' => $o->agent_role ?? '',
]; ];
} }
} }