Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,34 @@ curl -X POST https://your-site.com/wp-json/citecue/v1/content \
-d "$BODY"
```

Responses: `201` created / `200` updated (`{created, updated, post_id, status, permalink, edit_link}`), `400` product push without WooCommerce, `401` bad signature or stale timestamp, `403` ingest disabled, `409` edited locally / SKU exists without `force` / type conflict, `410` push was trashed in WordPress, `429` rate-limited (120/hour, filterable).
Responses: `201` created / `200` updated (`{created, updated, post_id, status, permalink, seq, edit_link}`; `seq` is the post's status-report counter, see below), `400` product push without WooCommerce, `401` bad signature or stale timestamp, `403` ingest disabled, `409` edited locally / SKU exists without `force` / type conflict, `410` push was trashed in WordPress, `429` rate-limited (120/hour, filterable).

There is also a public handshake endpoint: `GET /wp-json/citecue/v1/health` → `{plugin, version, delivery, ingest, woocommerce}`.

## Status reports (CiteCue posts only)

The plugin tells CiteCue when a post or page it pushed changes in WordPress: published, unpublished (draft, pending, private, scheduled or any custom status), trashed, restored, permanently deleted, given a new address, or edited while live. CiteCue applies it so its own record follows the site.

```
hook (transition_post_status / before_delete_post / post_updated + wp_after_insert_post)
└─ mark the post: _citecue_report_pending = now, bump _citecue_report_gen
(a permanent delete builds its whole report now and stores it in the
non-autoloaded option citecue_deleted_report_<id>)
└─ schedule citecue_report_drain at "now" (pulling a later one forward) and spawn_cron()

WP-Cron: citecue_report_drain
up to 20 due entries, oldest first, one request at a time, 30 s budget
POST {app}/api/delivery/v2/content-status Bearer ck_live_… X-Citecue-Channel: wordpress
```

- **Never in the editor's request.** Nothing waits on CiteCue; a slow or unreachable CiteCue cannot slow or break saving. Each report is built from the post as it is when the run happens, not when it was marked.
- **Which posts.** A `post` or `page` carrying both `_citecue_external_id` and `_citecue_source`, on a site with an API key that accepts content pushes and whose `home_url()` is https (the plugin already refuses pushes on plain http, and CiteCue would answer 400). Nothing is marked otherwise. The plugin's own `/content` handling is suspended around its insert/update, and after a successful push it clears the post's pending mark and resets what was last reported.
- **Body.** `external_id`, `source`, `site_url` (`home_url( '/' )`), `post_id`, `status` (`publish` for any publicly viewable status, `trash`, `deleted`, otherwise `draft`), `permalink` (publish only), `edited` (the content no longer hashes to `_citecue_content_hash`; the same test as `edited_locally()`, omitted for `deleted`), `seq` and `observed_at`.
- **Order.** `seq` is a per-post counter (`_citecue_report_seq`), allocated atomically in SQL before the post is read again from the database, so a report never carries an older state than a push its number is above; the `/content` response returns the current value so each push resets CiteCue's baseline. A report CiteCue answers with `ignored` / `out_of_order` and a higher `recorded_seq` makes the plugin raise its counter and send the current state once more.
- **Concurrency.** Every mark bumps a per-post generation. A run captures it and only clears or backs off the entry if it is unchanged, so a change made while a report is in flight is never lost.
- **Outcomes.** 2xx clears the entry (and, unless `ignored`, records the `edited` value and permalink sent); 400 and 404 clear it; 401, 403, 408, 429, any 5xx, a timeout or a network error keep it and retry after 1, 5, 15, then 30 minutes (up to 30% jitter, `Retry-After` as a floor, 1 hour cap). After the fourth retry the report is dropped and counted in `citecue_report_given_up`, which Settings → CiteCue shows beside the connection status. A run stops on 401, 403, 408, 429, other 5xx and transport errors; `503 busy` defers only that post.
- **Housekeeping.** Disconnecting clears pending marks and stored delete reports; deactivating clears the cron event; uninstalling removes the options and the `_citecue_report_*` / `_citecue_reported_*` meta. On multisite, uninstalling removes the reporter's bookkeeping (options and post meta) only for the site the uninstall runs on, because those live in each site's own tables; the per-user dismissal records are cleared for every site.

## WooCommerce

With WooCommerce active:
Expand All @@ -207,6 +231,7 @@ With WooCommerce active:
| `GET /api/delivery/v2/page?k&u&b` | `Bearer ck_live_…` + `X-Citecue-Channel: wordpress` | Optimized page for a crawler request (ETag/304; 404 = pass through; hit recorded server-side) |
| `GET /api/delivery/v2/seo-head?k&u` | `Bearer ck_live_…` + `X-Citecue-Channel: wordpress` | Enriched head block for one URL, injected into live pages (204 = nothing to inject; 404 = not optimized; fetched on cron, never on a render) |
| `GET /api/delivery/v2/llms.txt?k` | `Bearer ck_live_…` | llms.txt body (ETag/304) |
| `POST /api/delivery/v2/content-status` | `Bearer ck_live_…` + `X-Citecue-Channel: wordpress` | Status report for one CiteCue post (see "Status reports"); sent from WP-Cron, never from a visitor's or editor's request |
| `GET /api/delivery/v1/crawlers` | none (public) | Daily AI-crawler UA token refresh |

## Hooks
Expand Down Expand Up @@ -313,3 +338,5 @@ The second URL must be one CiteCue holds an optimized version of; anything else
`Citecue_Proxy` and `Citecue_Llms_Txt` each split into a `decide()` that returns what should happen and a `serve()` that emits headers and calls `exit`. All the branching lives in `decide()`, which is what the tests drive; `serve()` stays deliberately trivial because nothing can assert against a request that has already ended.

`Citecue_Seo_Head` follows the same split for the same reason, in three pieces rather than two: `decide()` answers "what should this page get" from cache alone, `refresh()` is the only part that talks to the network (on cron, never on a render), and `merge()` is a pure function from (what the rest of `wp_head` printed, CiteCue's block) to the tags that may be added. `merge()` is the whole conflict-avoidance contract with every other SEO plugin on the site, and being pure is what lets it be tested against a real Yoast head dump without a request in sight.

`Citecue_Status_Reporter` takes an injectable clock and cron spawner (`set_clock()`, `set_spawner()`), so its tests spend the 30 s run budget and walk the retry schedule without waiting and without a loopback request; the CiteCue endpoint is the mock's `content_status` queue.
5 changes: 3 additions & 2 deletions citecue.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Plugin Name: CiteCue AI Auto-Fix
* Plugin URI: https://github.com/citecue/wordpress-plugin
* Description: Serves CiteCue-optimized versions of your pages to AI bots and crawlers, adds CiteCue's enriched SEO metadata to your live pages, and lets CiteCue push brand-building draft content into WordPress.
* Version: 1.3.0
* Version: 1.5.0
* Requires at least: 5.8
* Requires PHP: 7.4
* Author: CiteCue
Expand Down Expand Up @@ -138,7 +138,7 @@
return;
}

define( 'CITECUE_VERSION', '1.3.0' );
define( 'CITECUE_VERSION', '1.5.0' );
define( 'CITECUE_PLUGIN_FILE', __FILE__ );
define( 'CITECUE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

Expand All @@ -151,6 +151,7 @@
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-proxy.php';
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-seo-head.php';
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-llms-txt.php';
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-status-reporter.php';
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-ingest.php';
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-admin.php';
require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-plugin.php';
Expand Down
17 changes: 17 additions & 0 deletions includes/class-citecue-admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,23 @@ private function render_status_card() {
<?php endif; ?>
</td>
</tr>
<?php $given_up = Citecue_Status_Reporter::given_up(); ?>
<?php if ( $given_up['count'] > 0 ) : ?>
<tr>
<td><?php esc_html_e( 'Status reports', 'citecue-ai-auto-fix' ); ?></td>
<td>
<span style="color:#996800;">&#8212;</span>
<?php
printf(
/* translators: 1: number of status changes, 2: date of the most recent one. */
esc_html( _n( '%1$d status change could not be delivered to CiteCue (last on %2$s).', '%1$d status changes could not be delivered to CiteCue (last on %2$s).', $given_up['count'], 'citecue-ai-auto-fix' ) ),
(int) $given_up['count'],
esc_html( wp_date( get_option( 'date_format' ), $given_up['last'] ) )
);
?>
</td>
</tr>
<?php endif; ?>
<tr>
<td><?php esc_html_e( 'Last check', 'citecue-ai-auto-fix' ); ?></td>
<td>
Expand Down
43 changes: 43 additions & 0 deletions includes/class-citecue-api-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* GET /api/delivery/v2/page — optimized page for an AI crawler (ETag/304)
* GET /api/delivery/v2/seo-head — enriched head block for one URL (humans)
* GET /api/delivery/v2/llms.txt — llms.txt body (ETag/304)
* POST /api/delivery/v2/content-status — a status change of a CiteCue post
* the public keyless registry feed:
* GET /api/delivery/v1/crawlers — AI crawler UA token registry
* and the code-gated pairing exchange:
Expand All @@ -28,6 +29,12 @@
*/
class Citecue_Api_Client {

/**
* Request timeout of a status report, in seconds. The reporter budgets its
* run around it.
*/
const STATUS_TIMEOUT = 5;

/**
* Settings.
*
Expand Down Expand Up @@ -195,6 +202,42 @@ public function claim_connect_code( $code, array $site ) {
return $connection;
}

/**
* POST /api/delivery/v2/content-status — reports one CiteCue post's status.
*
* Sent from WP-Cron, never from a visitor's or an editor's request. No
* redirects (the key rides on it) and a 5 second timeout. The reply is
* passed up as it came, because the reporter's retry rules depend on the
* exact status and on Retry-After.
*
* @param array $body The report.
* @return array|WP_Error {status:int, data:array|null, retry_after:string}
*/
public function post_content_status( array $body ) {
$response = wp_remote_post(
$this->settings->api_base() . '/api/delivery/v2/content-status',
array(
'timeout' => self::STATUS_TIMEOUT,
'redirection' => 0,
'user-agent' => 'CiteCue-WordPress/' . CITECUE_VERSION . ' (+' . home_url( '/' ) . ')',
'headers' => array_merge( $this->auth_headers(), array( 'Content-Type' => 'application/json' ) ),
'body' => wp_json_encode( $body ),
)
);

if ( is_wp_error( $response ) ) {
return $response;
}

$data = json_decode( (string) wp_remote_retrieve_body( $response ), true );

return array(
'status' => (int) wp_remote_retrieve_response_code( $response ),
'data' => is_array( $data ) ? $data : null,
'retry_after' => (string) wp_remote_retrieve_header( $response, 'retry-after' ),
);
}

/**
* GET /api/delivery/v2/config — the API key's org projects.
*
Expand Down
3 changes: 3 additions & 0 deletions includes/class-citecue-connect.php
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ public function disconnect() {
delete_option( 'citecue_auth_failed' );
delete_option( self::VERIFY_OPTION );
$this->plugin->cache->flush();
// A reconnect may pair a different project, so reports meant for this
// one must not follow it there.
$this->plugin->reporter->clear_pending();
}

/**
Expand Down
130 changes: 74 additions & 56 deletions includes/class-citecue-ingest.php
Original file line number Diff line number Diff line change
Expand Up @@ -282,44 +282,52 @@ public function handle_content( WP_REST_Request $request ) {
);
}

if ( 'product' === $post_type ) {
$post_id = $this->upsert_product( $existing_id, $params, $title, $content, $status );
if ( is_wp_error( $post_id ) ) {
return $post_id;
}
} else {
$postarr = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => $status,
'post_type' => $post_type,
'post_author' => $this->resolve_author(),
);
if ( isset( $params['excerpt'] ) ) {
$postarr['post_excerpt'] = sanitize_textarea_field( (string) $params['excerpt'] );
}
if ( isset( $params['slug'] ) && '' !== (string) $params['slug'] ) {
$postarr['post_name'] = sanitize_title( (string) $params['slug'] );
}
if ( $existing_id ) {
$postarr['ID'] = $existing_id;
}
// CiteCue knows what it is writing, so the status reporter must not send
// it back as a change made in WordPress. Resumed in `finally`: every
// error return below, and an exception from a filter, still lets go.
$this->plugin->reporter->suspend();
try {
if ( 'product' === $post_type ) {
$post_id = $this->upsert_product( $existing_id, $params, $title, $content, $status );
if ( is_wp_error( $post_id ) ) {
return $post_id;
}
} else {
$postarr = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => $status,
'post_type' => $post_type,
'post_author' => $this->resolve_author(),
);
if ( isset( $params['excerpt'] ) ) {
$postarr['post_excerpt'] = sanitize_textarea_field( (string) $params['excerpt'] );
}
if ( isset( $params['slug'] ) && '' !== (string) $params['slug'] ) {
$postarr['post_name'] = sanitize_title( (string) $params['slug'] );
}
if ( $existing_id ) {
$postarr['ID'] = $existing_id;
}

/**
* Filters the post array before a CiteCue push is inserted/updated.
* Posts and pages only — products go through WooCommerce's CRUD.
*
* @param array $postarr wp_insert_post() arguments.
* @param array $params Raw (unsanitized) request payload.
*/
$postarr = apply_filters( 'citecue_ingest_postarr', $postarr, $params );

$result = $existing_id ? wp_update_post( $postarr, true ) : wp_insert_post( $postarr, true );
if ( is_wp_error( $result ) ) {
$result->add_data( array( 'status' => 500 ) );
return $result;
/**
* Filters the post array before a CiteCue push is inserted/updated.
* Posts and pages only — products go through WooCommerce's CRUD.
*
* @param array $postarr wp_insert_post() arguments.
* @param array $params Raw (unsanitized) request payload.
*/
$postarr = apply_filters( 'citecue_ingest_postarr', $postarr, $params );

$result = $existing_id ? wp_update_post( $postarr, true ) : wp_insert_post( $postarr, true );
if ( is_wp_error( $result ) ) {
$result->add_data( array( 'status' => 500 ) );
return $result;
}
$post_id = (int) $result;
}
$post_id = (int) $result;
} finally {
$this->plugin->reporter->resume();
}

if ( 'post' === $post_type || 'product' === $post_type ) {
Expand Down Expand Up @@ -347,22 +355,35 @@ public function handle_content( WP_REST_Request $request ) {
$stored = get_post( $post_id );
update_post_meta( $post_id, '_citecue_content_hash', md5( $stored ? $stored->post_content : '' ) );

$response = rest_ensure_response(
array(
'created' => ! $existing_id,
'updated' => (bool) $existing_id,
'post_id' => $post_id,
'status' => get_post_status( $post_id ),
'permalink' => get_permalink( $post_id ),
'edit_link' => add_query_arg(
array(
'post' => $post_id,
'action' => 'edit',
),
admin_url( 'post.php' )
// The push replaced the text and the status: nothing is waiting to be
// reported any more, and what was last reported is what was just pushed.
// Posts and pages only: the reporter never tracks a product.
$reported = in_array( $post_type, array( 'post', 'page' ), true );
if ( $reported ) {
$this->plugin->reporter->after_push( $post_id );
}

$data = array(
'created' => ! $existing_id,
'updated' => (bool) $existing_id,
'post_id' => $post_id,
'status' => get_post_status( $post_id ),
'permalink' => get_permalink( $post_id ),
'edit_link' => add_query_arg(
array(
'post' => $post_id,
'action' => 'edit',
),
)
admin_url( 'post.php' )
),
);
if ( $reported ) {
// Where this post's status-report counter stands. CiteCue records
// it as its baseline, so a report built before this push and
// delivered after it is recognised as out of date.
$data['seq'] = $this->plugin->reporter->current_seq( $post_id );
}
$response = rest_ensure_response( $data );
$response->set_status( $existing_id ? 200 : 201 );
return $response;
}
Expand Down Expand Up @@ -523,12 +544,9 @@ private function find_by_external_id( $external_id ) {
* @return bool
*/
private function edited_locally( $post_id ) {
$last_hash = (string) get_post_meta( $post_id, '_citecue_content_hash', true );
if ( '' === $last_hash ) {
return false;
}
$post = get_post( $post_id );
return $post && md5( $post->post_content ) !== $last_hash;
// One test, shared with the status reporter, so "edited" means the same
// thing when CiteCue refuses a push and when it is told about an edit.
return Citecue_Status_Reporter::content_edited( get_post( $post_id ) );
}

/**
Expand Down
19 changes: 19 additions & 0 deletions includes/class-citecue-plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ final class Citecue_Plugin {
*/
public $connect;

/**
* Status reporter: tells CiteCue when a CiteCue post changes in WordPress.
*
* @var Citecue_Status_Reporter
*/
public $reporter;

/**
* Returns (and boots) the singleton.
*
Expand All @@ -88,6 +95,8 @@ private function __construct() {
$this->activity = new Citecue_Activity_Log();
$this->api = new Citecue_Api_Client( $this->settings );
$this->connect = new Citecue_Connect( $this );
$this->reporter = new Citecue_Status_Reporter( $this );
$this->reporter->register();

( new Citecue_Llms_Txt( $this ) )->register();
( new Citecue_Proxy( $this ) )->register();
Expand Down Expand Up @@ -188,6 +197,10 @@ public function on_init() {
* @return void
*/
public function daily_sync() {
// Local only, and before the connection check: marks can outlive a drain
// event whatever state the site is in.
$this->reporter->ensure_drain_scheduled();

if ( ! $this->settings->is_connected() ) {
return;
}
Expand All @@ -212,6 +225,9 @@ public static function activate() {

$settings = new Citecue_Settings();
$settings->ensure_ingest_secret();

// Marks left from before a deactivation get their drain back.
self::instance()->reporter->ensure_drain_scheduled();
}

/**
Expand All @@ -221,6 +237,9 @@ public static function activate() {
*/
public static function deactivate() {
wp_clear_scheduled_hook( self::CRON_HOOK );
// Pending status reports stay marked on their posts; activate() and the
// daily sync schedule the drain again, and they are sent then.
wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK );
// Queued metadata refreshes, one per URL. wp_unschedule_hook(), not
// wp_clear_scheduled_hook(): the latter only clears events whose
// arguments match the ones passed, and every one of these carries its
Expand Down
Loading
Loading