Commit Graph

225 Commits

Author SHA1 Message Date
peptiderepo
7217c154bb fix: resolve pre-existing PHPCS violations (Yoda conditions + short ternaries)
Fixes non-auto-fixable PHPCS errors surfaced by the estate reusable CI:
- scripts/check-constants.php: Yoda conditions at lines 140, 201
- templates/admin/ideas-browser.php: Elvis (?:) → explicit ternary (line 75)
- templates/admin/review-queue.php: Elvis (?:) → explicit ternaries (lines 144, 161-163)
- templates/admin/metabox-generation-info.php: Elvis (?:) → explicit ternaries (7 lines)
- .github/mu-plugins/prautoblogger-deploy-receiver.php: phpcs:ignore for
  ZipArchive->numFiles (native PHP property, can't be snake_cased); Elvis (?:) fix

All violations were pre-existing; none introduced by this PR.

Agent-Session: claude/adopt-ci-20260616
2026-06-16 14:04:40 +00:00
peptiderepo
1813d419e5 style: auto-fix PHPCS violations via phpcbf 2026-06-16 14:01:59 +00:00
peptiderepo
3890485dcb ci: adopt estate reusable CI + split 300-line violations (v0.22.0)
- ci.yml → thin caller of peptide-e2e reusable CI (tests: brain-monkey)
  + keep check-constants as parallel job; workflow_call trigger enabled
- deploy.yml: retire standalone validate job; gate on ci.yml via workflow_call
- composer.json: add 'test' script (vendor/bin/phpunit --testdox)
- Version bumped to 0.22.0

300-line splits (9 files over limit → all under 300):
- class-keyword-extractor.php: shared tokeniser from Idea_Scorer + Semantic_Dedup
- class-image-aspect-ratio.php: aspect-ratio snap from OR provider + OR batch
- class-settings-sanitizer.php: option sanitization from Admin_Page
- class-settings-fields-images.php: image fields from Settings_Fields_Extended
- class-runware-image-validator.php: credential check from Runware_Image_Provider
- Runware batch: 15 phpcs:disable lines → 1 grouped suppression

Agent-Session: claude/adopt-ci-20260616
2026-06-16 14:00:48 +00:00
peptiderepo
d770e8a86a feat: M4 in-admin manual generation on chained-cron checkpoints + IA/perf pass (v0.21.0) (#166)
Final Phase 2 admin milestone. Board "New Article" runs through the M3 chained-cron checkpoint state machine (one stage/idea per tick, queue persisted before generate, lock released on every exit path) so generation survives Hostinger background-kill; retires the SSH-only do_action workaround (WP-CLI routes through the same entry). IA/perf: settings-backed board/ideas pagination + db 1.4.0 indexes. Folds guard P2s (--self-test + window doc).

QA: APPROVE-WITH-P2-NOTES @ f2a00d4 + delta APPROVE @ 0c8071f. Deferred (tracked): class-admin-page.php 353-line split + pagination Settings-UI fields.

Agent-Session: phase2-admin-m4-20260614
2026-06-15 00:48:43 +07:00
peptiderepo
326a1af900 ci: guard against undefined PRAUTOBLOGGER_* constants (#165)
Adds scripts/check-constants.php + a required ci.yml step that fails the build when any referenced PRAUTOBLOGGER_* constant is neither defined in prautoblogger.php nor defined()-guarded. Closes the v0.19.0 admin-500 incident class (seq 38). CI-only; no plugin runtime change.

QA: APPROVE-WITH-P2-NOTES (2026-06-14-923f712). P2 follow-ups folded into M4.

Agent-Session: ci-constants-guard-20260614
2026-06-14 20:03:18 +07:00
peptiderepo
6ce2cbb94c fix: restore 3 bootstrap constants dropped in v0.19.0 — admin 500 hotfix (v0.20.1) (#163)
Incident hotfix, prod already hot-patched + verified. QA: APPROVE @ 9366a01 (qa-reviews/prautoblogger/2026-06-12-9366a01.md).

Agent-Session: cto-constants-hotfix-merge-20260612
2026-06-12 22:27:34 +07:00
peptiderepo
2d641153c7 ci(review): drop multi-model panel to Haiku-only (#162)
QA A/B decision 2026-06-12 (CEO-ratified): Haiku-only. Evidence: convo/cto/threads/2026-06-qa-ab-review/. QA verdict per repo in qa-reviews/.

Agent-Session: cto-panel-merge-20260612
2026-06-12 21:53:35 +07:00
peptiderepo
ac2f20de7e feat: M3 edit + single-step re-run — input versioning, human-modified audit, staged re-run (v0.20.0) (#161)
QA: REJECT@6ed639d (CTO rebase header P1) -> APPROVE@6727e07 (qa-reviews/prautoblogger/2026-06-12-6727e07.md)
CPO guardrails 1-5 verified hard-AC. CEO conditional greenlight 2026-06-12 in chat (QA-APPROVE condition met).

Agent-Session: cto-m3-merge-20260612
2026-06-12 21:46:49 +07:00
peptiderepo
3b6a302f95 fix(maintenance): v0.19.4 — composer GD-rung tests, layout-key cleanup, carried P3s (#160)
QA: APPROVE-WITH-P2-NOTES @ c0929be (qa-reviews/prautoblogger/2026-06-12-c0929be.md)
CEO greenlight: 2026-06-12 in chat.

Agent-Session: cto-maint-v0194-merge-20260612
2026-06-12 21:21:52 +07: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
peptiderepo
49f17c3d6f v0.19.0 - Phase 2 admin M1: kanban board + live progress; cost-reporter SQL fix (#156)
M1 of the Editorial Record admin (Direction C, CEO-ratified 2026-06-12).
Kanban dashboard (Generating/In Review/Published/Failed) as primary landing,
AJAX live progress via status poller, setting-backed poll interval + published
window, cost-reporter phpcs:ignore SQL fix, board column mapping tests.

QA: REJECT-P1 (29a334b) -> remediated -> APPROVE-WITH-P2-NOTES (60aa449).
Verdicts: qa-reviews/prautoblogger/2026-06-12-29a334b.md, 2026-06-12-60aa449.md
Thread: convo/prautoblogger/threads/2026-06-pipeline-v2-phase2-admin/ seq 1-9

Agent-Session: cto-phase2-admin-m1-merge-20260612
2026-06-12 14:55:48 +07:00
peptiderepo
87020736ef ci: harden cto-review.yml severity KeyError (v0.18.3)
QA (seq 43) identified a content-triggered KeyError in the CTO-Review
postprocessor: when a model returns a concerns[] item without a 'severity'
key, line 454 crashed with KeyError instead of degrading.

  sev = c[severity].upper()        # before — hard KeyError
  sev = c.get("severity", "UNKNOWN").upper()  # after — degrades gracefully

The JSON schema marks severity as required but the postprocessor does not
enforce it — a model deviating on a large diff (91K bytes for f10e177 vs
41K for 02e9aab) triggered the crash. The fix surfaces UNKNOWN-severity
concerns rather than killing the check.

No other workflow changes.

Agent-Session: prab-v0183-20260612
2026-06-12 11:55:02 +07:00
peptiderepo
dd1c38b6cf fix: document STATUS_TTL/API_TIMEOUT/MAX_RETRIES safety invariant (v0.18.3)
Add comment at the PRAUTOBLOGGER_MAX_RETRIES + PRAUTOBLOGGER_API_TIMEOUT_SECONDS
constant definitions documenting the dependency:

  API_TIMEOUT_SECONDS × MAX_RETRIES (540s) must stay < STATUS_TTL (600s)

Current product: 180s × 3 = 540s — 60s margin. Prevents constant-drift
regression: raising either constant without checking the inequality could cause
a fully-retrying LLM call to exhaust the status-transient TTL within a single
stage, triggering a false orphan-run abort (R2b path in poller).

Agent-Session: prab-v0183-20260612
2026-06-12 11:55:02 +07:00
peptiderepo
952344ff5f docs: ARCHITECTURE.md — add poller + fetcher to file tree; rewrite fallback detection
P1-1: class-generation-status-poller.php added under includes/; executor
description updated to reflect AJAX delegation (no longer 'start + status').

P1-2: class-runware-catalog-fetcher.php added under includes/providers/;
class-runware-model-catalog.php also added (was missing from tree).

P1-3: 'Fallback detection' blurb rewritten. Old: 180s/post-meta check.
Actual: transient renewed per-stage via update_generation_stage(); lock within
STATUS_TTL → R3 (running); lock > STATUS_TTL → R2b (abort_orphaned_run,
status:error). Daily Run_Reaper remains backstop.

Agent-Session: prab-v0183-20260612
2026-06-12 11:55:02 +07:00
peptiderepo
f0dc1c4621 fix: migrate Runware catalog to modelSearch; failure cooldown (v0.18.3 R4)
Runware retired taskType:models; all 42 daily catalog 401s come from this

deprecated endpoint. Migrated to auth+modelSearch pair per Runware's

current API. Paginator fetches up to 5 pages x 100 = 500 models, filters

client-side to io:text-to-image in capabilities[]. Uses air identifier as

model id. Cache key bumped to v2 (prautoblogger_runware_model_cache_v2)

to invalidate v1 rows that used old taskType/requiresImage shape.

Failure cooldown: sync() records prautoblogger_runware_catalog_last_failure_at

on every error path. get_models() gates re-trigger via is_in_failure_cooldown()

which reads prautoblogger_runware_catalog_failure_cooldown_seconds (default

3600s). Success clears the timestamp. Caps cascade to ~24 errors/day.

300-line rule: fetching/normalization extracted to new companion class

PRAutoBlogger_Runware_Catalog_Fetcher (class-runware-catalog-fetcher.php,

205 lines). Catalog class: 261 lines. Autoloader picks up the new file.

Tests: normalize_models against real modelSearch fixture (redacted key);

cooldown behavior (failure->active->expired); sync clears timestamp; fallback

list always served when cache empty. 328/328 PHPUnit green.

Agent-Session: prab-v0183-20260612
2026-06-12 11:55:02 +07:00
peptiderepo
eae0239b0c fix(tests): add wpdb->posts and wpdb->options to mock setup
AnalysisPromptsTest: analysis-prompts.php uses $wpdb->posts in the
JOIN clause ({->posts}); mock stdClass must declare posts property.

GenerationStatusPollerTest: Generation_Lock queries {->options}
in acquire/release/get_acquired_at; mock stdClass must declare options.

Agent-Session: prab-v0183-20260612
2026-06-12 11:55:02 +07:00
peptiderepo
1afac09d0a fix(v0183): GA4 SQL fix + manual-run resilience + honest status
R1: move phpcs:ignore out of SQL string in class-analysis-prompts.php:81
    (same pattern as v0.18.2 cost-reporter fix). GA4 self-improvement loop
    has returned empty context on every pipeline run since v0.16.0 — this
    restores get_performance_context() to the LLM. Sibling occurrence also
    fixed in class-post-assembler.php:112.

R2(a): update_generation_stage() now renews STATUS_TTL on every stage call
    so the transient outlasts long LLM calls during background runs.

R2(b): on_ajax_generation_status() detects lock-held-but-transient-gone
    when lock age > STATUS_TTL (= Hostinger background-process kill).
    Marks stuck run failed, releases lock, returns status:error with
    'infrastructure timeout' message. Daily reaper remains the backstop.

R3: when transient absent but lock held within TTL, return status:running
    (with started_at from lock) instead of status:idle.

Executor split: class-executor.php was 351 lines (>300). AJAX generation
    handlers extracted to new class-generation-status-poller.php (260 lines);
    executor now 226 lines. Public hook wiring unchanged via delegation.
    Generation_Lock gains get_acquired_at() for R2b/R3 lock-age checks.

Tests: AnalysisPromptsTest (regression SQL + behavioral context shaping),
       GenerationStatusPollerTest (R2a TTL renewal, R2b abort, R3 running,
       idle path).

Closes: R1 (analysis-prompts SQL), R2 (manual-run resilience), R3 (honest status)
Version: 0.18.3
Agent-Session: prab-v0183-20260612
2026-06-12 11:55:02 +07:00
peptiderepo
5ea058d504 style: auto-fix PHPCS violations via phpcbf 2026-06-12 09:16:40 +07:00
peptiderepo
3af65bbe39 fix(stage-state): v0.18.2b — symmetric agent_role via in-class resolve_role seam
QA REJECT-P1 remediation (seq 29). start()/done()/is_done()/get_output()
were asymmetric: start() passed the mapped role but done()/is_done()/
get_output() passed '' via the default, addressing a different unique key
(run_id, stage, agent_role, item_key). On every normal run this orphaned
the start() row in 'running'; on resume is_done() always returned false
→ duplicate-post vector.

Fix: add resolve_role(stage, agent_role) private static seam in
Run_Stage_State. When the caller passes '' the role is derived from
Stage_Display_Map::default_agent_role(stage) before any DB operation.
Non-empty roles (Phase-2 fan-out) pass through unchanged. All four
write/lookup methods (start, done, fail, get) call resolve_role.
is_done() and get_output() go through get() so they benefit too.

Mid-run-upgrade compat (v0.18.1 → v0.18.2): get() falls back to a
legacy role='' row on miss so a run started under v0.18.1 (all rows
have agent_role='') can still resume under v0.18.2. One extra indexed
query, only on miss, only for known stages.

Tests: two new RunStageStateTest cases —
  test_role_tagged_start_and_done_are_symmetric: start+done with
  'editor', assert is_done('editor')=true and is_done('')=false.
  test_legacy_empty_role_row_is_found_on_fallback: resolve to 'editor',
  primary miss, legacy role='' hit → is_done=true.

ARCHITECTURE.md §22: agent_role column and #22 Phase 1 description
updated — no longer 'Phase-2 only / '' default'; now documents Phase 1
population from Stage_Display_Map.

Agent-Session: prab-v0182-maintenance-20260612
2026-06-12 09:16:40 +07:00
peptiderepo
6b1908d628 fix(maintenance): v0.18.2 — four confirmed-live fixes
1. Cost-reporter SQL: phpcs:ignore annotations were embedded inside two SQL
   string literals (get_daily_spend, get_spend_by_stage), causing MariaDB to
   reject both queries and break the Metrics & Costs admin page. Moved annotations
   above the prepare() calls. Regression tests added to CostReporterTest.

2. Collector failure observability: catch block in collect_from_all_sources() now
   logs structured meta (model slug, HTTP status parsed from exception message,
   first 200 chars of error body) so outage incidents are diagnosable post-hoc.

3. run_stages.agent_role back-write: Pipeline_Runner, Article_Worker, and
   Content_Generator were calling Run_Stage_State::start() with agent_role=''.
   All start() call sites now pass Stage_Display_Map::default_agent_role(stage).
   Role written at INSERT only; ON DUPLICATE KEY UPDATE does not include
   agent_role — idempotency-key semantics on resume are unchanged.

4. Runware float deprecation: normalize_seed() applied % to a float
   (microtime(true) * 1000), triggering PHP 8 deprecation on every image
   generation. Fixed with (int) round(...) before the modulo operator.

Refs: convo/prautoblogger/threads/2026-06-pipeline-v2-phase1/25-cto-v0182-maintenance.md
Agent-Session: prab-v0182-maintenance-20260612
2026-06-12 09:16:40 +07:00
peptiderepo
b902216497 fix(settings): sanitize reasoning token cap as numeric on save
QA F4 (P3): prautoblogger_reasoning_max_tokens was missing from the
sanitize_field() numeric allowlist, so it saved as raw text (absint at
read kept runtime safe). Saves as numeric-or-0 now, matching every other
number field. CHANGELOG 0.18.1 entry notes the server-side sanitize (no
new version — 0.18.1 is still unreleased).

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
27ef37fe15 test: split PublisherTest and OpenRouterProviderTest under the 300-line rule
QA F2 (P2): this PR pushed PublisherTest to 333 lines and
OpenRouterProviderTest to 318. Both splits are mechanical (test groups
moved verbatim to a sibling file; setUp duplicated; no test logic or
assertion changes):

- OpenRouterProviderTest (318 -> 169): wire_full_provider() + the two
  v0.18.1 retry-path integration tests move to
  OpenRouterProviderRetryTest.php (223). The remaining file is
  byte-identical to its pre-PR state on main.
- PublisherTest (333 -> 202): the five post-creation side-effect tests
  (taxonomy, tags, run_id log linking, action/filter hooks — incl. the
  two pre-existing skipped ones, moved as-is) move to
  PublisherSideEffectsTest.php (183). Guard tests stay with the
  create_post() funnel tests.

Suite count unchanged (302 tests); all four files pass locally.

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
b7ffce8d88 docs(architecture): document v0.18.1 completion guard, reasoning cap option, request-builder scope
QA F1 (REJECT-P1 on 2bdc763, qa-reviews/prautoblogger/2026-06-11-2bdc763.md):
ARCHITECTURE.md was not updated in the commit that introduced the new
class and option (Standard §7 same-commit rule).

- File tree: add class-open-router-completion-guard.php (empty-completion
  guard, v0.18.1) under includes/providers/.
- Options table: add prautoblogger_reasoning_max_tokens (v0.18.1 reasoning
  token cap; default PRAUTOBLOGGER_DEFAULT_REASONING_MAX_TOKENS = 2048;
  0 = legacy uncapped effort mode).
- File tree: refresh class-open-router-request-builder.php description —
  it now owns request body assembly + the reasoning token cap/headroom,
  not just headers.

No version bump: 0.18.1 is still unreleased on this branch.

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
da0250f3ba fix: empty-content guard + finish_reason=length handling + reasoning budget (v0.18.1)
Reasoning models at high effort could spend the entire max_tokens budget
on thinking and return zero visible content with finish_reason=length;
the empty article flowed writer -> editor (reject) -> empty draft post,
with the cost booked as success (2026-06-11 incident: prod run acf24029,
draft post 921; diagnosis: convo pipeline-v2-phase1 seq 12).

- Empty-completion guard at the provider seam (new
  OpenRouter_Completion_Guard): empty/whitespace content is a failure;
  one retry with reasoning disabled (per-call override) when
  finish_reason=length or reasoning was active, then the stage fails.
- finish_reason=length always warning-logged (model, stage, tokens).
- Failed/retried attempts booked to generation_log with
  response_status=error + real token burn; run_decisions verdict rows
  (retry_reasoning_disabled / failed_empty_completion) for v0.18.0 runs.
- Writer-path guard in Content_Generator::execute_stage and
  belt-and-braces empty check in Publisher::create_post.
- Reasoning budget sanity: reasoning.max_tokens cap + completion
  headroom via new prautoblogger_reasoning_max_tokens setting (default
  constant 2048, 0 = legacy uncapped effort mode); cap replaces effort
  when active; governor reservations use the effective ceiling.
- Body assembly moved to Request_Builder::build_body (300-line cap).
- Tests: guard verdict matrix, builder budget shaping, writer/publisher
  guards, full provider retry path.

Agent-Session: prab-empty-draft-guard-20260611
2026-06-11 21:06:46 +07:00
peptiderepo
f5658f1c97 fix(cost): resolve snapshot-suffixed model IDs to base pricing before conservative estimate
OpenRouter sometimes returns a dated snapshot ID as the response model
(request deepseek/deepseek-v4-flash -> response model
deepseek/deepseek-v4-flash-20260423). The pricing chain missed the
registry on those IDs and booked the conservative $10/$30 per-M
estimate: today's prod single-pass run logged $0.582 against a true
flash-tier cost of roughly 1-2 cents. Inflated actuals eat the
Cost_Governor per-run ceiling (default $0.50; today's run would have
halted) and the monthly $5 budget gate (~9 days to self-block).

Fix at the single pricing seam (OpenRouter_Pricing::estimate_cost):
on a lookup miss, strip a trailing 8-digit 20-prefixed -YYYYMMDD
snapshot suffix and retry the hardcoded table + cached models list
once with the base ID. The conservative fallback is unchanged when
the base ID is also unknown. Governor reserve/settle and
generation-log booking all price through this seam, so every path
survives snapshot IDs.

Tests: snapshot ID resolves to the base price when only the base ID
is registered; an unknown ID without a suffix still gets the
conservative estimate; a non-date trailing digit run (foo-202612345)
is never stripped.

Agent-Session: pipeline-v2-phase1-pricing-fix-20260611
2026-06-11 16:42:56 +07:00
peptiderepo
c5e2a73e42 fix(schema): self-heal generation_log writes on half-migrated state
A cron-triggered generation can run right after a deploy, before any
admin_init migration pass — inserts carrying the new agent_role /
prompt_version columns would fail silently on the old schema and lose
the cost row. Two-sided heal: (1) log_api_call/log_image_generation
retry the insert without the v0.18.0 columns when it fails; (2) the
db-version check now also runs on cron requests (init + wp_doing_cron),
so the schema migrates on the first cron hit, not the first admin visit.

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
50da840553 feat(runs): state machine, idempotent resume, reaper extension, retention
Pipeline v2 Phase 1, commit 4/4. Run_Stage_State persists per-run
per-stage state keyed run_id + stage + agent_role + item_key (item_key
scopes articles because one run_id spans a whole batch; agent_role is
the Phase-2 quorum dimension, schema-only). Done stages snapshot output
and are reused on re-entry — writer stages via
Content_Generator::set_run_item, the review via its stored verdict, a
published item skipped outright — never re-run, never re-charged. Post
creation is keyed by _prautoblogger_run_id + new _prautoblogger_idea_hash
(check-before-insert in Publisher) so retries cannot duplicate posts.
Run-level research/analysis checkpoints + done/failed lifecycle marks
ride Pipeline_Runner/Executor (incl. orphan-abort + budget-abort paths).

Run_Reaper rides the EXISTING #19 daily cron: stages stuck running >2x
expected stage wall-clock and runs silent >2x expected run wall-clock ->
failed (filterable), open stages reaped, queryable as 'incomplete'.
Retention: request_json + stage output payloads NULLed after R days, R
from the new Audit Payload Retention setting (default constant 14,
0 = keep forever, no literal at point of use). Audit_Writer records
editorial verdicts (run_decisions) and per-article kept sources
(run_sources) for new runs.

Under-300: status-transient/summary helpers extracted verbatim to
Pipeline_Status (Pipeline_Runner 271; removed the worker's duplicate).

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
c6d051c87a feat(cost): per-run cost governor — reserve-before-call enforcement
Pipeline v2 Phase 1, commit 3/4. Cost_Governor reserves each call's
worst-case estimate (prompt chars/4 + max_tokens via the #18 pricing
chain) against the run ledger row with one atomic conditional UPDATE
(the #10 lock discipline) BEFORE dispatch, then settles to actuals after
each response; failed calls release their hold. Integrated inside
OpenRouter_Provider::send_chat_completion so EVERY text-LLM call path is
guarded with zero call-site changes; the image curl_multi batch reserves
its summed estimate in Image_Pipeline before generate_image_batch.

Breach: run halted (sticky), overage recorded, Cost_Ceiling_Exception
aborts the un-dispatched call, process_next_queued_article aborts the
remaining queued articles of halted/failed runs, and the Review Queue
shows a 'Halted runs' notice (runs halted pre-post have no draft to
list). Ceiling = prautoblogger_per_run_cost_ceiling_usd setting (default
constant $0.50, snapshotted at run start, 0 = disabled). Standalone
no-run calls, the monthly cap, and the AI Gateway path are unchanged.

Under-300: provider API-key fetch+validation moved verbatim to
OpenRouter_Request_Builder::resolve_api_key().

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
c723af927b feat(prompts): versioned prompt registry, v1 seed, pinning + stamping
Pipeline v2 Phase 1, commit 2/4. Prompt_Registry (read) +
Prompt_Registry_Writer (immutable create/activate/seed) over the new
prompts table; canonical v1 bodies extracted verbatim into
Prompt_Defaults(+Editorial) — single source for BOTH the seed migration
(Migrate_Prompt_Seed_V0180, flag-gated, self-healing) and the in-code
fallback, so a missing table renders byte-identical prompts and never
fatals. Call sites swapped: Content_Prompts, Analysis_Prompts,
Chief_Editor, LLM_Research_Provider. Includes the image-composer seam
keys image.rewriter_system + image.style_template (composer PR consumes,
must not add its own prompt storage).

Pinning: Cost_Tracker::set_run_id() registers the process run context,
ensures the runs ledger row, and pins active versions once per run;
log_api_call/log_image_generation stamp prompt_version (run pins) +
agent_role (stage map) on every generation_log row. Single-pass keeps
stage 'draft' and stamps content.single_pass explicitly.

Under-300 refactors: Content_Generator's four duplicated span/log blocks
consolidated into execute_stage() (301 -> 224 lines, behavior
identical); get_avg_tokens_for_stages body moved to Cost_Reporter with a
delegating wrapper kept for API compatibility.

Tests: byte-identical fallback renders (single_pass/outline/polish/
editor.system), token filling, key coverage incl. stage-map integrity.

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
1704d7f3a6 feat(schema): v1.2.0 substrate schema + stage display map (v0.18.0)
Pipeline v2 Phase 1, commit 1/4. Five new dbDelta-idempotent tables
(prompts, run_sources, run_decisions, runs, run_stages), additive
nullable agent_role + prompt_version columns on generation_log,
PRAUTOBLOGGER_DB_VERSION 1.1.0 -> 1.2.0 (existing on_check_db_version
auto-migration re-runs the installers on mismatch), Stage_Display_Map
covering historical + image + v2 stage vocabulary with humanizing
fallback, uninstall coverage for all new tables + full cron hook list,
ARCHITECTURE edit->polish canonicalization + schema docs + decision #22.

No behavior change: nothing reads the new tables yet.

Agent-Session: pipeline-v2-phase1-engineer-20260612
2026-06-11 16:42:56 +07:00
peptiderepo
6de8cf2031 feat: deterministic image composer - OG + square variants, branding, baked caption (v0.17.0) (#152)
Composer slots between provider bytes and sideload: corner-marked featured,
branded 1200x630 OG + 1080x1080 square with baked clamped caption, capability
ladder (Imagick -> resize-only -> pass-through, never blocks publish).
Alt-text bug fix (caption, not model name). Vendored brand PNGs + OFL Poppins.

QA: APPROVE-WITH-P2-NOTES @ 6f76df1 (qa-reviews/prautoblogger/2026-06-11-6f76df1.md)
CEO greenlight: 2026-06-11 in chat.

Agent-Session: cto-image-composer-merge-20260611
2026-06-11 15:27:48 +07:00
peptiderepo
d559fc58ab ci: adopt shared reusable deploy workflow (#150)
Replaces the per-repo staging/smoke/production jobs with one call to
peptiderepo/peptide-e2e/.github/workflows/deploy-app.yml (target_path=wp-content/plugins/prautoblogger).
Validated end-to-end on the calculator pilot.

Agent-Session: cto rollout-reusable-deploy
2026-06-09 19:15:45 +07:00
peptiderepo
a18aa9f316 ci(audit): retry PR-association check (#149)
listPullRequestsAssociatedWithCommit is eventually-consistent after a squash
merge; the single immediate call intermittently flagged legit merges as
'direct push to main'. Now polls up to 5x/10s before opening an issue.

Agent-Session: cto audit-race-fix
2026-06-09 13:39:08 +07:00
peptiderepo
d00e746727 Commit 1: editorial image prompt + style-template setting (#146)
* Commit 1: editorial image prompt + style-template setting

Pivot the image pipeline from the single-panel comic style to a text-free
editorial scientific illustration, and replace the Style Suffix setting with
an editable Style Template setting. Commit 1 of the in-plugin editorial image
pipeline (no composer yet; pipeline otherwise unchanged).

- New constant PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_TEMPLATE (brief §7 editorial
  template with the single {{ topic_summary }} token).
- New setting prautoblogger_image_style_template (textarea) replaces the
  Style Suffix field; single-token validation on save (brief A5); old
  prautoblogger_image_style_suffix mirrored to _deprecated for one cycle and
  not deleted (one-time migration prautoblogger_migrated_style_template_v0160).
- REWRITER_SYSTEM_PROMPT now emits a 1-2 sentence editorial topic/mechanism
  summary as the SCENE (no comic gag), keeping the CAPTION line for the
  unchanged HTML-caption-below-image path; scene/caption parsing contract
  preserved.
- New PRAutoBlogger_Image_Template_Filler substitutes the scene into the
  template's {{ topic_summary }} slot across all three entry points; strips
  control chars + clamps length (A5); degrades safely on missing token or
  empty summary so a blank/token-only prompt is never sent to the provider
  (A5/A6).
- Version bump 0.15.1 -> 0.16.0 + CHANGELOG + ARCHITECTURE.md updates.

Agent-Session: image-editorial-commit1

* style: auto-fix PHPCS violations via phpcbf

---------

Co-authored-by: peptiderepo <peptiderepo@users.noreply.github.com>
2026-06-09 13:18:38 +07:00
peptiderepo
a4f3b1832e ci: fix cto-review ARG_MAX (#110) + restore deploy pipeline (#147)
- cto-review.yml: pass the PR diff to the review step via a file
  (/tmp/cto-review-diff.txt) instead of a step output/env var. A ~400KB diff
  in the process env exceeds the runner ARG_MAX and failed the 'Call 4 models'
  step with 'Argument list too long' (#110).
- deploy.yml: remove invalid 'continue-on-error: true' from the smoke job
  (a reusable-workflow 'uses:' call). Actions does not support this property
  on 'uses:' jobs; it produced a 0-job workflow failure that has been failing
  every deploy. Matches the fix already in prcore/theme.

Closes #110.

Agent-Session: cto fix-cto-review-and-deploy

Co-authored-by: peptiderepo <peptiderepo@users.noreply.github.com>
2026-06-09 13:18:36 +07:00
peptiderepo
ac60c3d3a6 ci: make smoke gate informational (#144)
Smoke runs but does not block prod promotion until triage completes.

Agent-Session: cto retry-merge-smoke-informational
2026-05-14 21:34:06 +07:00
peptiderepo
1955f92859 Fix cost-tracker SELECT against canonical schema (v0.15.1) (#142)
Author: Engineer PRAutoBlogger
QA: 0bac52d clean (0 P0/P1/P2, 3 P3 nits)
Fixes WP DB error notice in AI Models settings tab present since v0.11.0.

Agent-Session: cto merge-cost-tracker-fix
2026-05-14 16:15:00 +07:00
peptiderepo
96f0248d81 ci: add smoke gate + deploy summary 2026-04-26 11:55:52 +07:00
peptiderepo
19849a5eaf ci: standardize PHP matrix to 8.1/8.2/8.3 2026-04-26 11:55:51 +07:00
peptiderepo
d9317ff567 fix: correct happy-path sync test — taskType, WP response helpers, shared store
Three bugs in test_sync_success_caches_and_returns_models:
1. Mock data lacked taskType=imageInference so normalize_models() filtered
   everything out → sync() returned false (empty result).
2. wp_remote_retrieve_response_code and wp_remote_retrieve_body not mocked
   → Brain\Monkey MissingFunctionExpectations.
3. is_wp_error not mocked.
4. get_option/update_option used separate static stores so update_option
   write was invisible to the subsequent get_option in get_models().
2026-04-26 04:50:02 +00:00
peptiderepo
30282035b5 fix: add patchwork.json to allow time() mocking in catalog tests
RunwareModelCatalogTest mocks time() via Patchwork/Brain\Monkey. Without
declaring it in redefinable-internals, Patchwork throws NotUserDefined
on every test in that suite (18 failures).
2026-04-26 04:47:46 +00:00
peptiderepo
6db6ffd7f5 fix: stub get_option/update_option in ImageModelRegistryTest for catalog delegation
get_models() now delegates to PRAutoBlogger_Runware_Model_Catalog which
calls get_option() to check WP cache. Brain\Monkey threw MissingFunction
Expectations on all registry tests. Added setUp() stub: get_option returns
false (no cache) so catalog falls back to hardcoded list; update_option
stubbed to prevent side-effect errors.
2026-04-26 04:45:59 +00:00
peptiderepo
1cdb41224b fix: add PRAUTOBLOGGER_DEFAULT_IMAGE_PROVIDER to test bootstrap
Catalog class references this constant; test suite was throwing
"Undefined constant" on all image pipeline tests (18 errors).
2026-04-26 04:43:36 +00:00
peptiderepo
b2bc4be9c2 fix: correct array nesting in settings-fields-extended (CI lint failure)
Orphaned array entry for runware_catalog_sync field was placed after the
closing ); of the fields array instead of inside it. PHP parse error on
line 268. Moved entry to correct position inside the array.
2026-04-26 04:41:25 +00:00
peptiderepo
73ac6d12b4 feat: live Runware model sync with 24h cache and Sync Now button (v0.15.0)
Replace hardcoded model registry with live-sync system.

New PRAutoBlogger_Runware_Model_Catalog class fetches the Runware model
catalog daily, caches in WP options (24h TTL), and falls back to the
hardcoded 15-model list if the API is unavailable. Sync Now button
in PRAdmin for on-demand refresh. Eliminates the drift that caused
silent model fallback bugs (v0.13.8, v0.14.0).
2026-04-26 11:38:59 +07:00
peptiderepo
61975d4551 fix: expand Runware pricing whitelist to all 15 registry models (v0.14.0)
All Runware model selections except schnell and dev were silently falling
back to runware:100@1 because COST_PER_IMAGE only had 2 entries while the
image model registry was expanded to 15 models in v0.13.8.

Fix: add all 15 model IDs to COST_PER_IMAGE and DEFAULT_STEPS.
2026-04-26 11:14:28 +07:00
peptiderepo
ca82e395f4 fix: model picker price sort broken for image models (v0.13.9)
applySort() always read input_price_per_m for price sorting, but image
models carry cost_per_image instead — input_price_per_m is undefined on
them, so every image model got an effective price of 0 and the sort was a
no-op.

Fix: detect image models via cost_per_image !== undefined and use that
field when present; fall back to input_price_per_m for text models.

Files changed:
- assets/js/model-picker.js — applySort price branch
- prautoblogger.php        — version bump 0.13.8 → 0.13.9
- CHANGELOG.md             — release notes
2026-04-26 02:36:56 +00:00
peptiderepo
3f60ecd0ff feat: expand image model registry to 21 models (v0.13.8)
Adds 13 new Runware text-to-image models and openai/gpt-5.4-image-2 via OpenRouter.
All models live-verified 2026-04-26.
2026-04-26 03:49:25 +07:00