diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 4da3c07..a948217 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -724,7 +724,7 @@ Stored on every PRAutoBlogger-generated post: | `_prautoblogger_analysis_id` | FK to ab_analysis_results.id | | `_prautoblogger_source_ids` | JSON array of source data IDs used | | `_prautoblogger_model_used` | Model that generated the content | -| `_prautoblogger_pipeline_mode` | 'single_pass' or 'multi_step' | +| `_prautoblogger_pipeline_mode` | 'single_pass', 'multi_step', or 'authority' | | `_prautoblogger_total_cost` | Total USD cost for this post | | `_prautoblogger_total_tokens` | Total tokens consumed for this post | | `_prautoblogger_editor_verdict` | 'approved', 'revised', 'rejected' | diff --git a/CHANGELOG.md b/CHANGELOG.md index f352d58..55ef72c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,38 @@ All notable changes to PRAutoBlogger will be documented in this file. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project uses [Semantic Versioning](https://semver.org/). +## [0.32.2] - 2026-06-24 + +### Fixed +- **P1 (canary) — quorum-miss HOLD no longer crashes as `failed`** (`class-authority-pipeline-stages.php`). + `hold_as_draft()` now branches on whether draft content is present: + - **No content** (quorum miss, pre-draft failure): records the hold decision to `run_decisions` + only — Publisher is never called. Eliminates the `RuntimeException("Refusing to create draft + post")` thrown by the v0.18.1 empty-content guard, which was causing the run to land as + `failed` instead of `held`. No post is created; HOLD decision row is written; operator sees + the run in the Review Queue (status `held-quorum`). + - **With content** (editorial escalation, citation gate, cost ceiling after draft): saves draft + post + suppresses imagery — behaviour unchanged from pre-fix. +- **P2 — Authority posts now carry `_prautoblogger_pipeline_mode = 'authority'`** (`class-publisher.php`, + `class-authority-pipeline.php`, `class-authority-pipeline-stages.php`). `Publisher::save_as_draft()` + and `publish()` accept an optional `string $pipeline_mode = ''` parameter. When '' the value falls + back to `get_option('prautoblogger_writing_pipeline', ...)` (Economy/single-pass unchanged). The + Authority pipeline passes `'authority'` explicitly on every post creation call. Economy path is + unaffected — callers that omit the param still read the option. + +### Tests (PHPUnit — 556 tests, 0 failures) +- `AuthorityPipelineTest::test_quorum_miss_hold_records_decision_no_post_created` — no post, HOLD + decision row written, status=held-quorum. +- `AuthorityPipelineTest::test_quorum_miss_does_not_throw` — run() must not throw on quorum miss. +- `AuthorityPipelineTest::test_editorial_escalation_hold_saves_draft_with_content` — content-present + path unchanged: draft post created, imagery suppressed. +- `AuthorityPipelineTest::test_authority_published_post_gets_authority_pipeline_mode` — meta value is + `authority`, not `single_pass`. +- `PublisherTest::test_publish_pipeline_mode_defaults_to_option_value` — Economy omits param; option + value (`single_pass`) written to meta. +- `PublisherTest::test_publish_explicit_pipeline_mode_overrides_option` — Authority passes `'authority'`; + meta = `authority` regardless of option. + ## [0.32.1] - 2026-06-24 ### Fixed diff --git a/CONTEXT.md b/CONTEXT.md index a07027b..f47a27c 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -171,7 +171,7 @@ into the live Economy path until P2b.4). | **Research_Fanout** | `PRAutoBlogger_Research_Fanout` — the orchestrator class that implements the fan-out pattern. Reserves the SUMMED worst-case cost of all N agents from the cost governor before dispatch, applies quorum enforcement after, and returns per-agent result arrays to the caller. Not live until P2b.4 wires it into the tier router. | | **curate stage** | The pipeline stage (`stage = 'curate'`) that follows fan-out. Implemented by `PRAutoBlogger_Research_Judge`. Deduplicates sources from all agents, scores each by `quality_score`, and writes the top-12 results to `run_sources`. Already present in `Stage_Display_Map` since v0.18.0. | | **Research_Judge** | `PRAutoBlogger_Research_Judge` — the class that executes the curate stage. Dedup chain: URL-canonical → semantic cosine (OpenRouter embeddings) → keyword-overlap fallback. Scores via `Research_Source_Scorer`. Writes `kept=1` / `kept=0` rows to `run_sources` with `quality_score` and `reason`. | -| **quorum** | Minimum number of research agents that must return usable results for the fan-out to proceed. Formula: ⌈N/2⌉+1 (one strict majority). Example: N=3 → quorum=3; N=5 → quorum=4. If fewer than quorum agents return valid results, `Research_Fanout::dispatch()` returns an empty array and the caller **must hold the run** rather than proceeding on thin research. | +| **quorum** | Minimum number of research agents that must return usable results for the fan-out to proceed. Formula: ⌈N/2⌉+1 (one strict majority). Example: N=3 → quorum=3; N=5 → quorum=4. If fewer than quorum agents return valid results, `Research_Fanout::dispatch()` returns an empty array and the pipeline holds the run (status `held-quorum`). v0.32.2: quorum-miss hold no longer calls Publisher — only a `run_decisions` row is written (no draft post created; Publisher would throw on empty content). | | **specialist role** | One of `{mechanisms, clinical, safety, comparison, practical}`. Each agent in the fan-out is assigned a distinct role and receives a role-specific user prompt. The first N roles in priority order are used (N = `prautoblogger_research_agent_count`). Written to `run_stages` as `agent_role = 'researcher:'`. | | **quality_score** | A composite score for a source: `relevance × authority_weight`. `relevance` comes from the agent's self-reported score (0.0–1.0). `authority_weight` is the source-type multiplier from `Research_Source_Scorer`. Higher scores sort the source closer to the top-12 kept set. Stored in `run_sources.quality_score`. | | **authority weight** | A source-type multiplier applied by `PRAutoBlogger_Research_Source_Scorer` to produce `quality_score`. Values: DOI/PubMed/NCBI peer-reviewed → 1.0; .gov/.edu/WHO/FDA institutional → 0.85; preprint → 0.70; HTTPS → 0.60; HTTP → 0.40. Reflects the editorial preference for peer-reviewed sources in Authority-tier articles. | diff --git a/convo/prautoblogger/threads/2026-06-phase2b-authority/28-engineer-holdfix.md b/convo/prautoblogger/threads/2026-06-phase2b-authority/28-engineer-holdfix.md new file mode 100644 index 0000000..9d22e71 --- /dev/null +++ b/convo/prautoblogger/threads/2026-06-phase2b-authority/28-engineer-holdfix.md @@ -0,0 +1,83 @@ +--- +seq: 28 +from: engineer-prautoblogger +to: cto+qa +date: 2026-06-24 +thread: phase2b-authority +status: awaiting-qa +in-reply-to: null +superseded-by: null +--- + +# Hold-path bugfix + pipeline_mode label — v0.32.2 ready for QA + +Branch `claude/prab-phase2b-holdfix-20260624` off `origin/main` (v0.32.1). +PR opened; not merged. VPS verified: PHPCS clean (exit 0), PHPUnit 556/556 OK. + +--- + +## P1 fix — quorum-miss HOLD no longer crashes as `failed` + +**Root cause:** `Authority_Pipeline_Stages::hold_as_draft()` called +`Publisher::save_as_draft('')` unconditionally, even when no draft content +existed yet (quorum miss / pre-draft failure). Publisher's v0.18.1 empty-content +guard threw `RuntimeException("Refusing to create draft post")`, which propagated +up and caused Article_Worker to mark the run `failed`. + +**Fix:** `hold_as_draft()` now branches on content: + +- **No content** (empty after `wp_strip_all_tags`): writes a `run_decisions` + HOLD row only. No post created, no exception thrown. Run lands `held-quorum`. +- **With content** (editorial escalation, citation gate, cost ceiling after draft): + saves draft + suppresses imagery — behaviour unchanged. + +The branch is a single `if` at the top of `hold_as_draft()`: +```php +if ( '' === trim( wp_strip_all_tags( $content ) ) ) { + PRAutoBlogger_Audit_Writer::record_decision( $run_id, 'publish-gate', $verdict, $hold_reason ); + return; +} +``` + +## P2 fix — Authority posts get `pipeline_mode = authority` + +**Root cause:** `Publisher::build_meta()` read `get_option('prautoblogger_writing_pipeline')` +unconditionally, which returns `'single_pass'` for Authority runs (the setting value, +not the actual pipeline used). + +**Fix:** `save_as_draft()` and `publish()` accept a new optional `string $pipeline_mode = ''` +parameter. When non-empty it overrides the option. All Authority pipeline call sites pass +`'authority'`. Economy callers pass nothing (option fallback unchanged). + +Files changed: +- `includes/core/class-authority-pipeline-stages.php` — branch in `hold_as_draft()`; pass + `'authority'` to `save_as_draft()` for content-present holds. +- `includes/core/class-publisher.php` — `$pipeline_mode` param on `publish()`, + `save_as_draft()`, `create_post()`, `build_meta()`. 299 lines (within 300-line rule). +- `includes/core/class-authority-pipeline.php` — pass `'authority'` to `save_as_draft()` + in stage 3b (draft for SEO stage). +- `ARCHITECTURE.md` — `_prautoblogger_pipeline_mode` values updated to include `'authority'`. +- `CONTEXT.md` — quorum entry updated with v0.32.2 no-post hold note. + +## Tests added (all pass) + +`AuthorityPipelineTest`: +- `test_quorum_miss_hold_records_decision_no_post_created` — wp_insert_post never called; + HOLD decision row written; status = held-quorum. +- `test_quorum_miss_does_not_throw` — run() must not throw Throwable on quorum miss. +- `test_editorial_escalation_hold_saves_draft_with_content` — content-present path + unchanged: draft created, imagery suppressed. +- `test_authority_published_post_gets_authority_pipeline_mode` — meta = `authority`. + +`PublisherTest`: +- `test_publish_pipeline_mode_defaults_to_option_value` — Economy: option value written. +- `test_publish_explicit_pipeline_mode_overrides_option` — Authority: `'authority'` in meta. + +## VPS CI results + +``` +vendor/bin/phpcs --standard=phpcs.xml (3 modified files): exit 0 +vendor/bin/phpunit --testsuite unit: Tests: 556, Assertions: 2046, Skipped: 5. OK +``` + +— engineer-prautoblogger diff --git a/includes/core/class-authority-pipeline-stages.php b/includes/core/class-authority-pipeline-stages.php index f8878bb..5d139a8 100644 --- a/includes/core/class-authority-pipeline-stages.php +++ b/includes/core/class-authority-pipeline-stages.php @@ -12,21 +12,21 @@ declare(strict_types=1); * beyond what the individual stage classes already require. * * Who triggers it: PRAutoBlogger_Authority_Pipeline (P2b.4). - * Dependencies: All P2b.1–P2b.3 stage classes + Content_Generator, + * Dependencies: All P2b.1-P2b.3 stage classes + Content_Generator, * Publisher, Image_Pipeline, Run_Stage_State, Audit_Writer. * - * @see core/class-authority-pipeline.php — Orchestrator that calls these helpers. - * @see ARCHITECTURE.md — Phase 2b data flow. + * @see core/class-authority-pipeline.php -- Orchestrator that calls these helpers. + * @see ARCHITECTURE.md -- Phase 2b data flow. */ class PRAutoBlogger_Authority_Pipeline_Stages { /** * Run the research fan-out stage. * - * @param string $run_id Pipeline run UUID. - * @param string $item_key Article-scoped item key. - * @param PRAutoBlogger_Article_Idea $idea The idea being researched. - * @param PRAutoBlogger_Cost_Tracker $cost_tracker Pipeline cost tracker. + * @param string $run_id Pipeline run UUID. + * @param string $item_key Article-scoped item key. + * @param PRAutoBlogger_Article_Idea $idea The idea being researched. + * @param PRAutoBlogger_Cost_Tracker $cost_tracker Pipeline cost tracker. * @param PRAutoBlogger_Research_Fanout $fanout Fan-out instance. * @return array Per-agent results, or empty on quorum miss. */ @@ -37,7 +37,7 @@ class PRAutoBlogger_Authority_Pipeline_Stages { PRAutoBlogger_Cost_Tracker $cost_tracker, PRAutoBlogger_Research_Fanout $fanout ): array { - PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: running specialist research fan-out…', 'prautoblogger' ) ); + PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: running specialist research fan-out...', 'prautoblogger' ) ); PRAutoBlogger_Run_Stage_State::start( $run_id, 'research', 'researcher', $item_key ); $results = $fanout->dispatch( $run_id, $item_key, $idea, $cost_tracker ); if ( ! empty( $results ) ) { @@ -51,10 +51,10 @@ class PRAutoBlogger_Authority_Pipeline_Stages { /** * Run the curate (Research_Judge) stage. * - * @param string $run_id Pipeline run UUID. - * @param string $item_key Article-scoped item key. - * @param array $fanout_results Results from research stage. - * @param PRAutoBlogger_Research_Judge $judge Judge instance. + * @param string $run_id Pipeline run UUID. + * @param string $item_key Article-scoped item key. + * @param array $fanout_results Results from research stage. + * @param PRAutoBlogger_Research_Judge $judge Judge instance. * @return array Kept sources. */ public static function run_curate( @@ -63,18 +63,18 @@ class PRAutoBlogger_Authority_Pipeline_Stages { array $fanout_results, PRAutoBlogger_Research_Judge $judge ): array { - PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: curating research sources…', 'prautoblogger' ) ); + PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: curating research sources...', 'prautoblogger' ) ); return $judge->curate( $run_id, $item_key, $fanout_results ); } /** * Run the draft (Content_Generator) stage. * - * @param string $run_id Pipeline run UUID. - * @param string $item_key Article-scoped item key. - * @param PRAutoBlogger_Article_Idea $idea The idea to draft. - * @param PRAutoBlogger_Cost_Tracker $cost_tracker Pipeline cost tracker. - * @param PRAutoBlogger_Content_Generator|null $generator Optional override (tests). + * @param string $run_id Pipeline run UUID. + * @param string $item_key Article-scoped item key. + * @param PRAutoBlogger_Article_Idea $idea The idea to draft. + * @param PRAutoBlogger_Cost_Tracker $cost_tracker Pipeline cost tracker. + * @param PRAutoBlogger_Content_Generator|null $generator Optional override (tests). * @return string Draft HTML content. */ public static function run_draft( @@ -84,7 +84,7 @@ class PRAutoBlogger_Authority_Pipeline_Stages { PRAutoBlogger_Cost_Tracker $cost_tracker, ?PRAutoBlogger_Content_Generator $generator = null ): string { - PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: generating article draft…', 'prautoblogger' ) ); + PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: generating article draft...', 'prautoblogger' ) ); if ( null === $generator ) { $llm = new PRAutoBlogger_OpenRouter_Provider(); $generator = new PRAutoBlogger_Content_Generator( $llm, $cost_tracker ); @@ -96,12 +96,12 @@ class PRAutoBlogger_Authority_Pipeline_Stages { /** * Run the editorial loop stage. * - * @param string $run_id Pipeline run UUID. - * @param string $item_key Article-scoped item key. - * @param string $content Draft HTML. - * @param PRAutoBlogger_Article_Idea $idea The idea under review. - * @param PRAutoBlogger_Cost_Tracker $cost_tracker Pipeline cost tracker. - * @param PRAutoBlogger_Editorial_Loop $editorial Editorial loop instance. + * @param string $run_id Pipeline run UUID. + * @param string $item_key Article-scoped item key. + * @param string $content Draft HTML. + * @param PRAutoBlogger_Article_Idea $idea The idea under review. + * @param PRAutoBlogger_Cost_Tracker $cost_tracker Pipeline cost tracker. + * @param PRAutoBlogger_Editorial_Loop $editorial Editorial loop instance. * @return array{content: string, escalated: bool} Result: content and escalation flag. */ public static function run_editorial( @@ -112,7 +112,7 @@ class PRAutoBlogger_Authority_Pipeline_Stages { PRAutoBlogger_Cost_Tracker $cost_tracker, PRAutoBlogger_Editorial_Loop $editorial ): array { - PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: running editorial loop…', 'prautoblogger' ) ); + PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: running editorial loop...', 'prautoblogger' ) ); $reviewed = $editorial->run( $run_id, $item_key, $content, $idea, $cost_tracker ); return array( 'content' => '' === $reviewed ? $content : $reviewed, @@ -123,9 +123,9 @@ class PRAutoBlogger_Authority_Pipeline_Stages { /** * Run the SEO stage. * - * @param string $run_id Pipeline run UUID. - * @param string $item_key Article-scoped item key. - * @param int $post_id Published/draft post ID. + * @param string $run_id Pipeline run UUID. + * @param string $item_key Article-scoped item key. + * @param int $post_id Published/draft post ID. * @param array $kept_sources Kept research sources from curate stage. * @param array $peptide_ids Related peptide post IDs. * @return float The computed citation_score. @@ -137,25 +137,36 @@ class PRAutoBlogger_Authority_Pipeline_Stages { array $kept_sources, array $peptide_ids ): float { - PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: writing SEO meta…', 'prautoblogger' ) ); + PRAutoBlogger_Pipeline_Status::broadcast( __( 'Authority: writing SEO meta...', 'prautoblogger' ) ); $seo_stage = new PRAutoBlogger_Seo_Stage(); return $seo_stage->run( $run_id, $item_key, $post_id, $kept_sources, $peptide_ids ); } /** - * Hold an article as draft (citation gate, escalation, or cost ceiling). + * Hold an article (citation gate, escalation, or cost ceiling). * - * Creates the draft post and suppresses image generation on it. Writes - * a run_decisions row for the hold reason. Returns the decision verdict - * string suitable for the result 'status' key. + * Behaviour depends on whether draft content is available: * - * @param string $run_id Pipeline run UUID. - * @param string $item_key Article-scoped item key. - * @param string $content Draft HTML content. - * @param PRAutoBlogger_Article_Idea $idea The article idea. - * @param string $hold_reason Short human-readable hold reason. - * @param string $verdict Decision verdict for audit row. - * @param string $run_id_for_publisher Run ID passed to Publisher. + * - NO content (empty after tag-strip): quorum miss or other pre-draft + * failure. No post is created. The hold is recorded as a run_decisions + * row and logged. This path never calls Publisher (avoids the + * empty-content RuntimeException introduced in v0.18.1). + * + * - WITH content (editorial escalation, citation gate, or cost ceiling + * after draft stage): saves a draft post, suppresses imagery, and + * records the decision row. Behaviour unchanged from pre-v0.32.2. + * + * Side effects (no-content path): Logger info + Audit_Writer decision row. + * Side effects (content path): Logger info + Publisher draft + post-meta + * (_prautoblogger_imagery_suppressed) + Audit_Writer decision row. + * + * @param string $run_id Pipeline run UUID. + * @param string $item_key Article-scoped item key. + * @param string $content Draft HTML ('' = pre-draft hold). + * @param PRAutoBlogger_Article_Idea $idea The article idea. + * @param string $hold_reason Short human-readable hold reason. + * @param string $verdict Decision verdict for audit row. + * @param string $run_id_for_publisher Run ID passed to Publisher (content path). * @return void */ public static function hold_as_draft( @@ -172,7 +183,17 @@ class PRAutoBlogger_Authority_Pipeline_Stages { 'authority-pipeline' ); - // Save as draft with a neutral editorial review stub. + // v0.32.2: when there is no draft content yet (quorum miss or other + // pre-draft failure), skip Publisher entirely -- Publisher::save_as_draft() + // throws RuntimeException on empty content (v0.18.1 guard). Record the + // hold decision only; the run state is returned as 'held' by the caller. + if ( '' === trim( wp_strip_all_tags( $content ) ) ) { + PRAutoBlogger_Audit_Writer::record_decision( $run_id, 'publish-gate', $verdict, $hold_reason ); + return; + } + + // Content is present: save as draft and suppress imagery (editorial + // escalation, citation gate, or cost ceiling after the draft stage). $publisher = new PRAutoBlogger_Publisher(); $review = new PRAutoBlogger_Editorial_Review( array( @@ -184,7 +205,7 @@ class PRAutoBlogger_Authority_Pipeline_Stages { 'issues' => array(), ) ); - $post_id = $publisher->save_as_draft( $content, $idea, $review, $run_id_for_publisher, null ); + $post_id = $publisher->save_as_draft( $content, $idea, $review, $run_id_for_publisher, null, 'authority' ); // Imagery gate: suppress image generation on held articles. if ( $post_id > 0 ) { diff --git a/includes/core/class-authority-pipeline.php b/includes/core/class-authority-pipeline.php index 249017b..7c70d36 100644 --- a/includes/core/class-authority-pipeline.php +++ b/includes/core/class-authority-pipeline.php @@ -222,7 +222,7 @@ class PRAutoBlogger_Authority_Pipeline implements PRAutoBlogger_Authority_Pipeli ) ); $auto_publish = in_array( get_option( 'prautoblogger_auto_publish', '0' ), array( '1', 'yes' ), true ); - $post_id = $publisher->save_as_draft( $final_content, $idea, $stub_review, $run_id, null ); + $post_id = $publisher->save_as_draft( $final_content, $idea, $stub_review, $run_id, null, 'authority' ); PRAutoBlogger_Run_Stage_State::start( $run_id, 'publish', (string) PRAutoBlogger_Stage_Display_Map::default_agent_role( 'publish' ), $item_key ); // Stage 5: SEO. diff --git a/includes/core/class-publisher.php b/includes/core/class-publisher.php index 598a141..098b290 100644 --- a/includes/core/class-publisher.php +++ b/includes/core/class-publisher.php @@ -13,22 +13,23 @@ declare(strict_types=1); * Dependencies: PRAutoBlogger_Post_Assembler (taxonomy, images, sanitization), * WordPress wp_insert_post(), post meta API. * - * @see core/class-post-assembler.php — Post-creation helpers (taxonomy, images, logs). - * @see core/class-peptide-linker.php — Injects peptide database hyperlinks into content. - * @see core/class-chief-editor.php — Produces the editorial review we consume. - * @see core/class-content-generator.php — Produces the content we publish. - * @see ARCHITECTURE.md — Data flow step 6. + * @see core/class-post-assembler.php -- Post-creation helpers (taxonomy, images, logs). + * @see core/class-peptide-linker.php -- Injects peptide database hyperlinks into content. + * @see core/class-chief-editor.php -- Produces the editorial review we consume. + * @see core/class-content-generator.php -- Produces the content we publish. + * @see ARCHITECTURE.md -- Data flow step 6. */ class PRAutoBlogger_Publisher { /** * Publish an editor-approved article. * - * @param string $content The final HTML content. - * @param PRAutoBlogger_Article_Idea $idea The original article idea. - * @param PRAutoBlogger_Editorial_Review $review The editor's review. - * @param string|null $run_id Pipeline run ID for log linking. - * @param ?PRAutoBlogger_Cost_Tracker $cost_tracker Optional cost tracker for image generation cost logging. + * @param string $content The final HTML content. + * @param PRAutoBlogger_Article_Idea $idea The original article idea. + * @param PRAutoBlogger_Editorial_Review $review The editor's review. + * @param string|null $run_id Pipeline run ID for log linking. + * @param PRAutoBlogger_Cost_Tracker|null $cost_tracker Optional cost tracker for imagery. + * @param string $pipeline_mode Override pipeline_mode meta ('' = option). * @return int The created post ID. * @throws \RuntimeException If post creation fails. */ @@ -37,19 +38,21 @@ class PRAutoBlogger_Publisher { PRAutoBlogger_Article_Idea $idea, PRAutoBlogger_Editorial_Review $review, ?string $run_id = null, - ?PRAutoBlogger_Cost_Tracker $cost_tracker = null + ?PRAutoBlogger_Cost_Tracker $cost_tracker = null, + string $pipeline_mode = '' ): int { - return $this->create_post( $content, $idea, $review, 'publish', $run_id, $cost_tracker ); + return $this->create_post( $content, $idea, $review, 'publish', $run_id, $cost_tracker, $pipeline_mode ); } /** * Save an editor-rejected article as a draft for human review. * - * @param string $content The generated HTML content (pre-revision). - * @param PRAutoBlogger_Article_Idea $idea The original article idea. - * @param PRAutoBlogger_Editorial_Review $review The editor's review with rejection notes. - * @param string|null $run_id Pipeline run ID for log linking. - * @param ?PRAutoBlogger_Cost_Tracker $cost_tracker Optional cost tracker for image generation cost logging. + * @param string $content The generated HTML content (pre-revision). + * @param PRAutoBlogger_Article_Idea $idea The original article idea. + * @param PRAutoBlogger_Editorial_Review $review The editor's review with rejection notes. + * @param string|null $run_id Pipeline run ID for log linking. + * @param PRAutoBlogger_Cost_Tracker|null $cost_tracker Optional cost tracker for imagery. + * @param string $pipeline_mode Override pipeline_mode meta ('' = option). * @return int The created post ID. * @throws \RuntimeException If post creation fails. */ @@ -58,21 +61,24 @@ class PRAutoBlogger_Publisher { PRAutoBlogger_Article_Idea $idea, PRAutoBlogger_Editorial_Review $review, ?string $run_id = null, - ?PRAutoBlogger_Cost_Tracker $cost_tracker = null + ?PRAutoBlogger_Cost_Tracker $cost_tracker = null, + string $pipeline_mode = '' ): int { - return $this->create_post( $content, $idea, $review, 'draft', $run_id, $cost_tracker ); + return $this->create_post( $content, $idea, $review, 'draft', $run_id, $cost_tracker, $pipeline_mode ); } /** * Create a WordPress post with generation metadata. * - * @param string $content HTML content. - * @param PRAutoBlogger_Article_Idea $idea Article idea. - * @param PRAutoBlogger_Editorial_Review $review Editorial review. - * @param string $post_status 'publish' or 'draft'. - * @param string|null $run_id Pipeline run ID for log linking. + * @param string $content HTML content. + * @param PRAutoBlogger_Article_Idea $idea Article idea. + * @param PRAutoBlogger_Editorial_Review $review Editorial review. + * @param string $post_status 'publish' or 'draft'. + * @param string|null $run_id Pipeline run ID. + * @param PRAutoBlogger_Cost_Tracker|null $cost_tracker Cost tracker for imagery. + * @param string $pipeline_mode Override pipeline_mode meta ('' = option). * @return int Post ID. - * @throws \RuntimeException If wp_insert_post fails. + * @throws \RuntimeException On wp_insert_post failure or empty content (v0.18.1 guard). */ private function create_post( string $content, @@ -80,10 +86,11 @@ class PRAutoBlogger_Publisher { PRAutoBlogger_Editorial_Review $review, string $post_status, ?string $run_id = null, - ?PRAutoBlogger_Cost_Tracker $cost_tracker = null + ?PRAutoBlogger_Cost_Tracker $cost_tracker = null, + string $pipeline_mode = '' ): int { // v0.18.1 belt-and-braces: never create a post whose content is - // empty once tags and whitespace are stripped — an empty "draft + // empty once tags and whitespace are stripped -- an empty "draft // for human review" (2026-06-11 incident, post 921) reviews // nothing and hides the underlying generation failure. The // provider/writer guards make this unreachable on OpenRouter @@ -110,7 +117,7 @@ class PRAutoBlogger_Publisher { // v0.20.0: a re-run's regenerated content must land on the // existing UNPUBLISHED post (otherwise re-runs silently // discard their output). Published posts stay frozen - // (CPO guardrail 5) — refresh skips them untouched. + // (CPO guardrail 5) -- refresh skips them untouched. return $this->refresh_unpublished_post( $existing_id, $content, $idea, $review ); } } @@ -127,10 +134,10 @@ class PRAutoBlogger_Publisher { 'post_status' => $post_status, 'post_type' => 'post', 'post_author' => PRAutoBlogger_Post_Assembler::get_default_author_id(), - 'meta_input' => $this->build_meta( $idea, $review, $run_id, $idea_hash ), + 'meta_input' => $this->build_meta( $idea, $review, $run_id, $idea_hash, $pipeline_mode ), ); - /** @see class-prautoblogger.php — listeners registered in main loader. */ + /** @see class-prautoblogger.php -- listeners registered in main loader. */ $post_data = apply_filters( 'prautoblogger_filter_post_data', $post_data, $idea, $review ); $post_id = wp_insert_post( $post_data, true ); @@ -158,15 +165,11 @@ class PRAutoBlogger_Publisher { } /** - * Refresh an existing post from re-run output — unpublished only. - * - * Idempotent-resume calls land here too (same content in = same - * content out, so behavior is unchanged for plain resumes). The post - * keeps its CURRENT status: a re-run never publishes an unpublished - * post — publication stays an explicit Review Queue / WP editor - * action. Published (and scheduled/private) posts are returned - * untouched: the run is frozen (CPO guardrail 5). + * Refresh an existing post from re-run output -- unpublished only. * + * Idempotent-resume: same content in = same content out. The post keeps + * its CURRENT status -- a re-run never publishes an unpublished post. + * Published/scheduled/private posts are returned untouched (CPO guardrail 5). * Side effects: wp_update_post + post meta updates (unpublished only). * * @param int $post_id Existing post ID. @@ -179,7 +182,7 @@ class PRAutoBlogger_Publisher { $post = get_post( $post_id ); if ( PRAutoBlogger_Rerun_Eligibility::post_frozen( $post ) ) { PRAutoBlogger_Logger::instance()->info( - sprintf( 'Post %d already exists and is published — frozen, skipping content refresh.', $post_id ), + sprintf( 'Post %d already exists and is published -- frozen, skipping content refresh.', $post_id ), 'publisher' ); return $post_id; @@ -214,28 +217,35 @@ class PRAutoBlogger_Publisher { /** * Build post_meta array for generation metadata. * - * The `_prautoblogger_run_id` key (added v0.8.1) lets the orphan-research - * reaper attribute an orphan `llm_research` row back to its sibling - * articles without re-walking the gen_log table. See - * core/class-research-reaper.php. + * `_prautoblogger_run_id` lets the orphan-research reaper attribute an orphan + * `llm_research` row back to its article without re-walking gen_log. + * `_prautoblogger_pipeline_mode`: Authority passes 'authority'; Economy passes + * '' (falls back to the option). See core/class-research-reaper.php. * - * @param PRAutoBlogger_Article_Idea $idea - * @param PRAutoBlogger_Editorial_Review $review - * @param string|null $run_id Pipeline run UUID, or null in legacy paths. + * @param PRAutoBlogger_Article_Idea $idea Article idea. + * @param PRAutoBlogger_Editorial_Review $review Editorial review. + * @param string|null $run_id Pipeline run UUID, or null in legacy paths. + * @param string $idea_hash Idea hash ('' when not yet computed). + * @param string $pipeline_mode Explicit pipeline mode ('' = read option). * @return array */ private function build_meta( PRAutoBlogger_Article_Idea $idea, PRAutoBlogger_Editorial_Review $review, ?string $run_id = null, - string $idea_hash = '' + string $idea_hash = '', + string $pipeline_mode = '' ): array { + $mode = '' !== $pipeline_mode + ? $pipeline_mode + : get_option( 'prautoblogger_writing_pipeline', 'multi_step' ); + $meta = array( '_prautoblogger_generated' => '1', '_prautoblogger_analysis_id' => $idea->get_analysis_id(), '_prautoblogger_source_ids' => wp_json_encode( $idea->get_source_ids() ), '_prautoblogger_model_used' => get_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL ), - '_prautoblogger_pipeline_mode' => get_option( 'prautoblogger_writing_pipeline', 'multi_step' ), + '_prautoblogger_pipeline_mode' => $mode, '_prautoblogger_editor_verdict' => $review->get_verdict(), '_prautoblogger_editor_notes' => $review->get_notes(), '_prautoblogger_quality_score' => $review->get_quality_score(), @@ -257,7 +267,7 @@ class PRAutoBlogger_Publisher { /** * Find a post already created for this (run, idea) pair. * - * Direct postmeta self-join (any post_status, including trash) — the + * Direct postmeta self-join (any post_status, including trash) -- the * idempotency check must see drafts and pending posts too. * * @param string $run_id Pipeline run UUID. diff --git a/prautoblogger.php b/prautoblogger.php index 15c7891..8bf4d45 100644 --- a/prautoblogger.php +++ b/prautoblogger.php @@ -9,7 +9,7 @@ * Plugin Name: 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. - * Version: 0.32.1 + * Version: 0.32.2 * Requires at least: 6.0 * Requires PHP: 7.4 * Author: PeptideRepo @@ -35,7 +35,7 @@ if ( ! defined( 'ABSPATH' ) ) { | Defined here so every file in the plugin can reference paths, versions, | and limits without magic strings. */ -define( 'PRAUTOBLOGGER_VERSION', '0.32.1' ); +define( 'PRAUTOBLOGGER_VERSION', '0.32.2' ); define( 'PRAUTOBLOGGER_DB_VERSION', '1.4.0' ); // No schema change in v0.32.0 (P2b.5 admin controls are additive only). define( 'PRAUTOBLOGGER_DEFAULT_RUN_CEILING_USD', 0.50 ); define( 'PRAUTOBLOGGER_DEFAULT_REQUEST_JSON_RETENTION_DAYS', 14 ); diff --git a/tests/unit/Core/AuthorityPipelineTest.php b/tests/unit/Core/AuthorityPipelineTest.php index d7be343..8b7a23a 100644 --- a/tests/unit/Core/AuthorityPipelineTest.php +++ b/tests/unit/Core/AuthorityPipelineTest.php @@ -323,6 +323,138 @@ class AuthorityPipelineTest extends BaseTestCase { $this->assertArrayHasKey( "status", $result ); } + + // -- P1: Quorum-miss hold (no content) -------------------------------- + + /** + * When fanout returns empty (quorum miss), the pipeline must record a + * HOLD decision row and return status='held-quorum'. No post must be + * created (wp_insert_post must NOT be called), and no exception must + * be thrown. + * + * Regression: before v0.32.2, hold_as_draft('') called Publisher which + * threw RuntimeException, causing the run to land as 'failed' instead. + */ + public function test_quorum_miss_hold_records_decision_no_post_created(): void { + // Fanout returns empty -- quorum miss. + $fanout = $this->make_fanout_stub( array() ); + $tracker = $this->make_cost_tracker_stub(); + $pipeline = new \PRAutoBlogger_Authority_Pipeline( $tracker, $fanout ); + + // wp_insert_post must never be called on a quorum-miss hold. + Functions\expect( "wp_insert_post" )->never(); + + $result = $pipeline->run( "run-quorum", $this->make_idea(), $tracker ); + + $this->assertSame( "held-quorum", $result["status"] ); + $this->assertSame( 0, $result["published"] ); + $this->assertEmpty( $this->published_posts ); + + // A run_decisions row must be written for the hold. + $hold_decisions = array_filter( + $this->decision_rows, + static fn( $row ) => "quorum-miss" === $row["verdict"] + ); + $this->assertNotEmpty( $hold_decisions, "Expected a quorum-miss decision row in run_decisions" ); + } + + /** + * When fanout returns empty (quorum miss), the run state must be + * 'held-quorum', not 'failed'. The P1 bug caused an uncaught + * RuntimeException which Article_Worker caught and marked 'failed'. + */ + public function test_quorum_miss_does_not_throw(): void { + $fanout = $this->make_fanout_stub( array() ); + $tracker = $this->make_cost_tracker_stub(); + $pipeline = new \PRAutoBlogger_Authority_Pipeline( $tracker, $fanout ); + + // No exception must propagate out of run(). + $exception_thrown = false; + try { + $result = $pipeline->run( "run-nothrow", $this->make_idea(), $tracker ); + } catch ( \Throwable $e ) { + $exception_thrown = true; + } + + $this->assertFalse( $exception_thrown, "run() must not throw on quorum miss (was RuntimeException before v0.32.2)" ); + } + + // -- P1: Hold WITH content (editorial escalation) --------------------- + + /** + * When the editorial loop escalates with content present, hold_as_draft + * must save a draft post (wp_insert_post called once) and suppress + * imagery. Verifies the content-present path is unchanged by the fix. + */ + public function test_editorial_escalation_hold_saves_draft_with_content(): void { + $sources = array( array( "url" => "https://a.com", "title" => "A", "quality_score" => 0.9 ) ); + $fanout = $this->make_fanout_stub( $this->make_fanout_results( $sources ) ); + $judge = $this->make_judge_stub( $sources ); + $loop = $this->make_editorial_loop_stub( "

escalated draft content

", true ); + $generator = $this->make_generator_stub( "

draft content

" ); + $tracker = $this->make_cost_tracker_stub(); + $pipeline = new \PRAutoBlogger_Authority_Pipeline( $tracker, $fanout, $judge, $loop, $generator ); + + $posts_inserted = 0; + $original_when = null; + Functions\when( "wp_insert_post" )->alias( + function ( $args ) use ( &$posts_inserted ) { + ++$posts_inserted; + return 55; + } + ); + + $result = $pipeline->run( "run-escalated", $this->make_idea(), $tracker ); + + $this->assertSame( "held-escalated", $result["status"] ); + $this->assertGreaterThanOrEqual( 1, $posts_inserted, "wp_insert_post must be called for escalated hold with content" ); + $this->assertArrayHasKey( "_prautoblogger_imagery_suppressed", $this->meta_written ); + $this->assertSame( "1", $this->meta_written["_prautoblogger_imagery_suppressed"] ); + } + + // -- P2: pipeline_mode label ------------------------------------------ + + /** + * Authority published posts must carry _prautoblogger_pipeline_mode='authority'. + * The Economy single-pass label is validated separately in PublisherTest. + */ + public function test_authority_published_post_gets_authority_pipeline_mode(): void { + $this->stub_get_option( array( + "prautoblogger_log_level" => "error", + "prautoblogger_auto_publish" => "0", + "prautoblogger_citation_score_threshold" => 0.0, + "prautoblogger_writing_pipeline" => "single_pass", + "prautoblogger_writing_model" => "openai/gpt-4o-mini", + "prautoblogger_default_author" => 1, + ) ); + + $sources = array( array( "url" => "https://a.com", "title" => "A", "quality_score" => 0.8 ) ); + $fanout = $this->make_fanout_stub( $this->make_fanout_results( $sources ) ); + $judge = $this->make_judge_stub( $sources ); + $loop = $this->make_editorial_loop_stub( "

approved content

", false ); + $generator = $this->make_generator_stub( "

draft content

" ); + $tracker = $this->make_cost_tracker_stub(); + $pipeline = new \PRAutoBlogger_Authority_Pipeline( $tracker, $fanout, $judge, $loop, $generator ); + + $captured_meta = null; + Functions\when( "wp_insert_post" )->alias( + function ( $args ) use ( &$captured_meta ) { + $captured_meta = $args["meta_input"] ?? array(); + return 66; + } + ); + + $result = $pipeline->run( "run-pmode", $this->make_idea(), $tracker ); + + $this->assertNotNull( $captured_meta, "wp_insert_post must have been called" ); + $this->assertArrayHasKey( "_prautoblogger_pipeline_mode", $captured_meta ); + $this->assertSame( + "authority", + $captured_meta["_prautoblogger_pipeline_mode"], + "Authority pipeline posts must carry pipeline_mode=authority, not single_pass" + ); + } + // -- Helpers ---------------------------------------------------------- private function make_idea(): \PRAutoBlogger_Article_Idea { diff --git a/tests/unit/Core/PublisherTest.php b/tests/unit/Core/PublisherTest.php index 64f6b30..ea71455 100644 --- a/tests/unit/Core/PublisherTest.php +++ b/tests/unit/Core/PublisherTest.php @@ -203,4 +203,65 @@ class PublisherTest extends BaseTestCase { $publisher->publish( "

\n\t

", $this->idea, $this->review ); } -} + /** + * P2 fix (v0.32.2): Publisher::publish() called without an explicit + * pipeline_mode must record the option value (Economy / single-pass + * path). Verifies the fallback behaviour is unchanged. + */ + public function test_publish_pipeline_mode_defaults_to_option_value(): void { + $this->stub_get_option( [ + 'prautoblogger_writing_pipeline' => 'single_pass', + 'prautoblogger_writing_model' => 'openai/gpt-4o-mini', + 'prautoblogger_default_author' => 1, + ] ); + + $captured_meta = null; + Functions\when( 'wp_insert_post' )->alias( function ( $args ) use ( &$captured_meta ) { + $captured_meta = $args['meta_input'] ?? []; + return 99; + } ); + + $wpdb = $this->create_mock_wpdb(); + $wpdb->method( 'query' )->willReturn( 0 ); + $wpdb->method( 'prepare' )->willReturn( '' ); + $GLOBALS['wpdb'] = $wpdb; + + $publisher = new \PRAutoBlogger_Publisher(); + $publisher->publish( '

Content

', $this->idea, $this->review, 'run-economy' ); + + $this->assertArrayHasKey( '_prautoblogger_pipeline_mode', $captured_meta ); + $this->assertSame( 'single_pass', $captured_meta['_prautoblogger_pipeline_mode'], + 'Economy path (no explicit pipeline_mode) must use the option value' ); + } + + /** + * P2 fix (v0.32.2): when an explicit pipeline_mode is passed (Authority + * path), it overrides the option value and is stored as post meta. + */ + public function test_publish_explicit_pipeline_mode_overrides_option(): void { + $this->stub_get_option( [ + 'prautoblogger_writing_pipeline' => 'single_pass', + 'prautoblogger_writing_model' => 'openai/gpt-4o-mini', + 'prautoblogger_default_author' => 1, + ] ); + + $captured_meta = null; + Functions\when( 'wp_insert_post' )->alias( function ( $args ) use ( &$captured_meta ) { + $captured_meta = $args['meta_input'] ?? []; + return 100; + } ); + + $wpdb = $this->create_mock_wpdb(); + $wpdb->method( 'query' )->willReturn( 0 ); + $wpdb->method( 'prepare' )->willReturn( '' ); + $GLOBALS['wpdb'] = $wpdb; + + $publisher = new \PRAutoBlogger_Publisher(); + $publisher->publish( '

Content

', $this->idea, $this->review, 'run-authority', null, 'authority' ); + + $this->assertArrayHasKey( '_prautoblogger_pipeline_mode', $captured_meta ); + $this->assertSame( 'authority', $captured_meta['_prautoblogger_pipeline_mode'], + 'Explicit pipeline_mode must override the option (Authority path)' ); + } + +} \ No newline at end of file