@adsim/wordpress-mcp-server 3.1.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +543 -176
  2. package/dxt/manifest.json +86 -9
  3. package/index.js +3156 -36
  4. package/package.json +1 -1
  5. package/src/confirmationToken.js +64 -0
  6. package/src/contentAnalyzer.js +476 -0
  7. package/src/htmlParser.js +80 -0
  8. package/src/linkUtils.js +158 -0
  9. package/src/utils/contentCompressor.js +116 -0
  10. package/src/woocommerceClient.js +88 -0
  11. package/tests/unit/contentAnalyzer.test.js +397 -0
  12. package/tests/unit/tools/analyzeEeatSignals.test.js +192 -0
  13. package/tests/unit/tools/approval.test.js +251 -0
  14. package/tests/unit/tools/auditCanonicals.test.js +149 -0
  15. package/tests/unit/tools/auditHeadingStructure.test.js +150 -0
  16. package/tests/unit/tools/auditMediaSeo.test.js +123 -0
  17. package/tests/unit/tools/auditOutboundLinks.test.js +175 -0
  18. package/tests/unit/tools/auditTaxonomies.test.js +173 -0
  19. package/tests/unit/tools/contentCompressor.test.js +320 -0
  20. package/tests/unit/tools/contentIntelligence.test.js +2168 -0
  21. package/tests/unit/tools/destructive.test.js +246 -0
  22. package/tests/unit/tools/findBrokenInternalLinks.test.js +222 -0
  23. package/tests/unit/tools/findKeywordCannibalization.test.js +183 -0
  24. package/tests/unit/tools/findOrphanPages.test.js +145 -0
  25. package/tests/unit/tools/findThinContent.test.js +145 -0
  26. package/tests/unit/tools/internalLinks.test.js +283 -0
  27. package/tests/unit/tools/perTargetControls.test.js +228 -0
  28. package/tests/unit/tools/site.test.js +6 -1
  29. package/tests/unit/tools/woocommerce.test.js +344 -0
  30. package/tests/unit/tools/woocommerceIntelligence.test.js +341 -0
  31. package/tests/unit/tools/woocommerceWrite.test.js +323 -0
package/index.js CHANGED
@@ -22,12 +22,18 @@ import fetch from 'node-fetch';
22
22
  import { readFileSync, existsSync } from 'fs';
23
23
  import { resolve } from 'path';
24
24
  import { HttpTransportManager } from './src/transport/http.js';
25
+ import { generateToken, validateToken } from './src/confirmationToken.js';
26
+ import { extractInternalLinks, extractExternalLinks, checkLinkStatus, extractFocusKeyword, calculateRelevanceScore, suggestAnchorText } from './src/linkUtils.js';
27
+ import { wcApiCall, getWcCredentials } from './src/woocommerceClient.js';
28
+ import { parseImagesFromHtml, extractHeadings, extractInternalLinks as extractInternalLinksHtml, countWords } from './src/htmlParser.js';
29
+ import { summarizePost, applyContentFormat } from './src/utils/contentCompressor.js';
30
+ import { calculateReadabilityScore, extractHeadingsOutline, detectContentSections, extractTransitionWords, countPassiveSentences, buildTFIDFVectors, computeCosineSimilarity, findDuplicatePairs, extractEntities, computeTextDiff } from './src/contentAnalyzer.js';
25
31
 
26
32
  // ============================================================
27
33
  // CONFIGURATION
28
34
  // ============================================================
29
35
 
30
- const VERSION = '2.2.0';
36
+ const VERSION = '3.2.0';
31
37
  const VERBOSE = process.env.WP_MCP_VERBOSE === 'true' || process.argv.includes('--verbose');
32
38
  const MAX_RETRIES = parseInt(process.env.WP_MCP_MAX_RETRIES || '3', 10);
33
39
  const TIMEOUT_MS = parseInt(process.env.WP_MCP_TIMEOUT || '30000', 10);
@@ -41,6 +47,8 @@ const READ_ONLY = process.env.WP_READ_ONLY === 'true';
41
47
  const DRAFT_ONLY = process.env.WP_DRAFT_ONLY === 'true';
42
48
  const DISABLE_DELETE = process.env.WP_DISABLE_DELETE === 'true';
43
49
  const DISABLE_PLUGIN_MANAGEMENT = process.env.WP_DISABLE_PLUGIN_MANAGEMENT === 'true';
50
+ const REQUIRE_APPROVAL = process.env.WP_REQUIRE_APPROVAL === 'true';
51
+ const CONFIRM_DESTRUCTIVE = process.env.WP_CONFIRM_DESTRUCTIVE === 'true';
44
52
  const MAX_CALLS_PER_MINUTE = parseInt(process.env.WP_MAX_CALLS_PER_MINUTE || '0', 10); // 0 = unlimited
45
53
  const ALLOWED_TYPES = process.env.WP_ALLOWED_TYPES ? process.env.WP_ALLOWED_TYPES.split(',').map(s => s.trim()) : null; // null = all
46
54
  const ALLOWED_STATUSES = process.env.WP_ALLOWED_STATUSES ? process.env.WP_ALLOWED_STATUSES.split(',').map(s => s.trim()) : null;
@@ -50,38 +58,39 @@ const AUDIT_LOG = process.env.WP_AUDIT_LOG !== 'off'; // on by default
50
58
  const rateLimiter = { calls: [], windowMs: 60000 };
51
59
 
52
60
  function checkRateLimit() {
53
- if (MAX_CALLS_PER_MINUTE <= 0) return;
61
+ const maxCpm = getActiveControls().max_calls_per_minute;
62
+ if (maxCpm <= 0) return;
54
63
  const now = Date.now();
55
64
  rateLimiter.calls = rateLimiter.calls.filter(t => now - t < rateLimiter.windowMs);
56
- if (rateLimiter.calls.length >= MAX_CALLS_PER_MINUTE) {
57
- throw new Error(`Rate limit exceeded: ${MAX_CALLS_PER_MINUTE} calls/minute. Try again in a few seconds.`);
65
+ if (rateLimiter.calls.length >= maxCpm) {
66
+ throw new Error(`Rate limit exceeded: ${maxCpm} calls/minute. Try again in a few seconds.`);
58
67
  }
59
68
  rateLimiter.calls.push(now);
60
69
  }
61
70
 
62
71
  function enforceReadOnly(toolName) {
63
- const writeTools = ['wp_create_post', 'wp_update_post', 'wp_delete_post', 'wp_create_page', 'wp_update_page', 'wp_upload_media', 'wp_create_comment', 'wp_create_taxonomy_term', 'wp_update_seo_meta', 'wp_activate_plugin', 'wp_deactivate_plugin', 'wp_restore_revision', 'wp_delete_revision'];
64
- if (process.env.WP_READ_ONLY === 'true' && writeTools.includes(toolName)) {
72
+ const writeTools = ['wp_create_post', 'wp_update_post', 'wp_delete_post', 'wp_create_page', 'wp_update_page', 'wp_upload_media', 'wp_create_comment', 'wp_create_taxonomy_term', 'wp_update_seo_meta', 'wp_activate_plugin', 'wp_deactivate_plugin', 'wp_restore_revision', 'wp_delete_revision', 'wp_submit_for_review', 'wp_approve_post', 'wp_reject_post', 'wc_list_products', 'wc_get_product', 'wc_list_orders', 'wc_get_order', 'wc_list_customers', 'wc_inventory_alert', 'wc_order_intelligence', 'wc_seo_product_audit', 'wc_suggest_product_links', 'wc_update_product', 'wc_update_stock', 'wc_update_order_status'];
73
+ if (getActiveControls().read_only && writeTools.includes(toolName)) {
65
74
  throw new Error(`Blocked: Server is in READ-ONLY mode (WP_READ_ONLY=true). Tool "${toolName}" is not allowed.`);
66
75
  }
67
76
  }
68
77
 
69
78
  function enforceDeleteDisabled(toolName) {
70
79
  const deleteTools = ['wp_delete_post', 'wp_delete_revision'];
71
- if (process.env.WP_DISABLE_DELETE === 'true' && deleteTools.includes(toolName)) {
80
+ if (getActiveControls().disable_delete && deleteTools.includes(toolName)) {
72
81
  throw new Error(`Blocked: Destructive actions are disabled (WP_DISABLE_DELETE=true). Tool "${toolName}" is not allowed.`);
73
82
  }
74
83
  }
75
84
 
76
85
  function enforcePluginManagement(toolName) {
77
86
  const pluginWriteTools = ['wp_activate_plugin', 'wp_deactivate_plugin'];
78
- if (process.env.WP_DISABLE_PLUGIN_MANAGEMENT === 'true' && pluginWriteTools.includes(toolName)) {
87
+ if (getActiveControls().disable_plugin_management && pluginWriteTools.includes(toolName)) {
79
88
  throw new Error(`Blocked: Plugin management is disabled (WP_DISABLE_PLUGIN_MANAGEMENT=true). Tool "${toolName}" is not allowed.`);
80
89
  }
81
90
  }
82
91
 
83
92
  function enforceDraftOnly(status) {
84
- if (process.env.WP_DRAFT_ONLY === 'true' && status && status !== 'draft' && status !== 'pending') {
93
+ if (getActiveControls().draft_only && status && status !== 'draft' && status !== 'pending') {
85
94
  throw new Error(`Blocked: Server is in DRAFT-ONLY mode (WP_DRAFT_ONLY=true). Only "draft" and "pending" statuses are allowed, got "${status}".`);
86
95
  }
87
96
  }
@@ -98,6 +107,55 @@ function enforceAllowedStatuses(status) {
98
107
  }
99
108
  }
100
109
 
110
+ // ── Per-target controls merge (OR strict) ──
111
+
112
+ function getActiveControls() {
113
+ const tc = currentTarget?.controls || {};
114
+ const globalMaxCpm = parseInt(process.env.WP_MAX_CALLS_PER_MINUTE || '0', 10);
115
+ const targetMaxCpm = tc.max_calls_per_minute || 0;
116
+ let effectiveMaxCpm;
117
+ if (globalMaxCpm > 0 && targetMaxCpm > 0) effectiveMaxCpm = Math.min(globalMaxCpm, targetMaxCpm);
118
+ else if (globalMaxCpm > 0) effectiveMaxCpm = globalMaxCpm;
119
+ else if (targetMaxCpm > 0) effectiveMaxCpm = targetMaxCpm;
120
+ else effectiveMaxCpm = 0;
121
+
122
+ return {
123
+ read_only: process.env.WP_READ_ONLY === 'true' || tc.read_only === true,
124
+ draft_only: process.env.WP_DRAFT_ONLY === 'true' || tc.draft_only === true,
125
+ disable_delete: process.env.WP_DISABLE_DELETE === 'true' || tc.disable_delete === true,
126
+ disable_plugin_management: process.env.WP_DISABLE_PLUGIN_MANAGEMENT === 'true' || tc.disable_plugin_management === true,
127
+ require_approval: process.env.WP_REQUIRE_APPROVAL === 'true' || tc.require_approval === true,
128
+ confirm_destructive: process.env.WP_CONFIRM_DESTRUCTIVE === 'true' || tc.confirm_destructive === true,
129
+ max_calls_per_minute: effectiveMaxCpm,
130
+ };
131
+ }
132
+
133
+ function getControlSources() {
134
+ const tc = currentTarget?.controls || {};
135
+ const src = (g, t) => (g && t) ? 'both' : g ? 'global' : t ? 'target' : 'none';
136
+ const globalMaxCpm = parseInt(process.env.WP_MAX_CALLS_PER_MINUTE || '0', 10);
137
+ const targetMaxCpm = tc.max_calls_per_minute || 0;
138
+ return {
139
+ read_only_source: src(process.env.WP_READ_ONLY === 'true', tc.read_only === true),
140
+ draft_only_source: src(process.env.WP_DRAFT_ONLY === 'true', tc.draft_only === true),
141
+ disable_delete_source: src(process.env.WP_DISABLE_DELETE === 'true', tc.disable_delete === true),
142
+ disable_plugin_management_source: src(process.env.WP_DISABLE_PLUGIN_MANAGEMENT === 'true', tc.disable_plugin_management === true),
143
+ require_approval_source: src(process.env.WP_REQUIRE_APPROVAL === 'true', tc.require_approval === true),
144
+ confirm_destructive_source: src(process.env.WP_CONFIRM_DESTRUCTIVE === 'true', tc.confirm_destructive === true),
145
+ max_calls_per_minute_source: (globalMaxCpm > 0 && targetMaxCpm > 0) ? 'both' : (globalMaxCpm > 0 ? 'global' : (targetMaxCpm > 0 ? 'target' : 'none')),
146
+ };
147
+ }
148
+
149
+ // Test helper — not part of public API
150
+ function _testSetTarget(name, config) {
151
+ if (name && config) {
152
+ targets[name] = config;
153
+ currentTarget = { name, ...config };
154
+ } else {
155
+ currentTarget = null;
156
+ }
157
+ }
158
+
101
159
  // ============================================================
102
160
  // LOGGER & AUDIT
103
161
  // ============================================================
@@ -121,7 +179,8 @@ function auditLog(entry) {
121
179
  latency_ms: entry.latency_ms,
122
180
  site: entry.site || currentTarget?.name || 'default',
123
181
  params: entry.params || {},
124
- error: entry.error || null
182
+ error: entry.error || null,
183
+ ...(entry.effective_controls ? { effective_controls: entry.effective_controls } : {})
125
184
  };
126
185
  console.error(`[AUDIT] ${JSON.stringify(record)}`);
127
186
  }
@@ -376,24 +435,32 @@ const ORDERBY = ['date', 'relevance', 'id', 'title', 'slug', 'modified', 'author
376
435
  const ORDERS = ['asc', 'desc'];
377
436
  const MEDIA_TYPES = ['image', 'video', 'audio', 'application'];
378
437
  const COMMENT_STATUSES = ['approved', 'hold', 'spam', 'trash'];
379
- const TOOLS_COUNT = 35;
438
+ const TOOLS_COUNT = 79;
380
439
 
381
440
  function json(data) { return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }; }
382
441
  function strip(html) { return (html || '').replace(/<[^>]*>/g, '').trim(); }
383
442
 
384
443
  // ============================================================
385
- // TOOL DEFINITIONS (35 tools)
444
+ // TOOL DEFINITIONS (56 tools)
386
445
  // ============================================================
387
446
 
388
447
  const TOOLS_DEFINITIONS = [
389
448
  // ── POSTS (6) ──
390
- { name: 'wp_list_posts', description: 'List posts with filtering and search.', inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 10 }, page: { type: 'number', default: 1 }, status: { type: 'string', default: 'publish' }, orderby: { type: 'string', default: 'date' }, order: { type: 'string', default: 'desc' }, categories: { type: 'string' }, tags: { type: 'string' }, search: { type: 'string' }, author: { type: 'number' } }}},
391
- { name: 'wp_get_post', description: 'Get post by ID with full content and meta.', inputSchema: { type: 'object', properties: { id: { type: 'number' } }, required: ['id'] }},
449
+ { name: 'wp_list_posts', description: 'List posts with filtering and search. Default "full" mode returns all fields including excerpts — use mode:"summary" for listing/inventory workflows (id, title, slug, date, status, link only), mode:"ids_only" when you only need IDs for a subsequent batch operation (e.g. then calling wp_get_post per ID). Use mode:"full" only when you need excerpts or category/tag details.', inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 10 }, page: { type: 'number', default: 1 }, status: { type: 'string', default: 'publish' }, orderby: { type: 'string', default: 'date' }, order: { type: 'string', default: 'desc' }, categories: { type: 'string' }, tags: { type: 'string' }, search: { type: 'string' }, author: { type: 'number' }, mode: { type: 'string', default: 'full', description: 'full=all fields, summary=id/title/slug/date/status/link only, ids_only=flat ID array' } }}},
450
+ { name: 'wp_get_post', description: 'Get post by ID. WARNING: default returns full HTML content (50,000-187,000 chars on Elementor/page-builder sites) — always specify content_format to avoid context overflow. Use content_format:"links_only" for internal linking workflows (~800 chars instead of 187,000). Use content_format:"text" for content audit/rewrite workflows (plain text truncated to 15,000 chars). Use content_format:"html" only when you need raw HTML for structure analysis. Combine with fields:["id","title","content"] for rewrite tasks or fields:["id","title","meta"] for SEO-only tasks. Prefer wp_get_seo_meta over wp_get_post when you only need SEO metadata.', inputSchema: { type: 'object', properties: { id: { type: 'number' }, fields: { type: 'array', items: { type: 'string' }, description: 'Return only specified fields (id,title,content,excerpt,slug,status,date,modified,categories,tags,author,featured_media,meta,link). Omit for all.' }, content_format: { type: 'string', default: 'html', description: 'html=raw HTML (truncated at WP_MAX_CONTENT_CHARS), text=plain text, links_only=extract internal links only' } }, required: ['id'] }},
392
451
  { name: 'wp_create_post', description: 'Create a post (default: draft).', inputSchema: { type: 'object', properties: { title: { type: 'string' }, content: { type: 'string' }, status: { type: 'string', default: 'draft' }, excerpt: { type: 'string' }, categories: { type: 'array', items: { type: 'number' } }, tags: { type: 'array', items: { type: 'number' } }, slug: { type: 'string' }, featured_media: { type: 'number' }, meta: { type: 'object' }, author: { type: 'number' } }, required: ['title', 'content'] }},
393
452
  { name: 'wp_update_post', description: 'Update a post.', inputSchema: { type: 'object', properties: { id: { type: 'number' }, title: { type: 'string' }, content: { type: 'string' }, status: { type: 'string' }, excerpt: { type: 'string' }, categories: { type: 'array', items: { type: 'number' } }, tags: { type: 'array', items: { type: 'number' } }, slug: { type: 'string' }, featured_media: { type: 'number' }, meta: { type: 'object' }, author: { type: 'number' } }, required: ['id'] }},
394
- { name: 'wp_delete_post', description: 'Delete a post (trash or permanent).', inputSchema: { type: 'object', properties: { id: { type: 'number' }, force: { type: 'boolean', default: false } }, required: ['id'] }},
453
+ { name: 'wp_delete_post', description: 'Delete a post (trash or permanent). When WP_CONFIRM_DESTRUCTIVE=true, requires a confirmation_token (call once without to get token, then again with token).', inputSchema: { type: 'object', properties: { id: { type: 'number' }, force: { type: 'boolean', default: false }, confirmation_token: { type: 'string', description: 'Confirmation token returned by the first call when WP_CONFIRM_DESTRUCTIVE=true' } }, required: ['id'] }},
395
454
  { name: 'wp_search', description: 'Full-text search across all content.', inputSchema: { type: 'object', properties: { search: { type: 'string' }, per_page: { type: 'number', default: 10 }, type: { type: 'string', default: '' } }, required: ['search'] }},
396
455
 
456
+ // ── APPROVAL WORKFLOW (3) ──
457
+ { name: 'wp_submit_for_review', description: 'Submit a draft post for editorial review (draft → pending). Blocked by WP_READ_ONLY.',
458
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post ID' }, note: { type: 'string', description: 'Optional review note (stored as post meta _mcp_review_note)' } }, required: ['id'] }},
459
+ { name: 'wp_approve_post', description: 'Approve a pending post for publication (pending → publish). Blocked by WP_READ_ONLY and WP_DRAFT_ONLY.',
460
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post ID' } }, required: ['id'] }},
461
+ { name: 'wp_reject_post', description: 'Reject a pending post back to draft with a reason (pending → draft). Stores rejection reason and increments rejection count. Blocked by WP_READ_ONLY.',
462
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post ID' }, reason: { type: 'string', description: 'Reason for rejection (stored as post meta _mcp_rejection_reason)' } }, required: ['id', 'reason'] }},
463
+
397
464
  // ── PAGES (4) ──
398
465
  { name: 'wp_list_pages', description: 'List pages with hierarchy.', inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 10 }, page: { type: 'number', default: 1 }, status: { type: 'string', default: 'publish' }, parent: { type: 'number' }, orderby: { type: 'string', default: 'menu_order' }, order: { type: 'string', default: 'asc' }, search: { type: 'string' } }}},
399
466
  { name: 'wp_get_page', description: 'Get page by ID with content and template.', inputSchema: { type: 'object', properties: { id: { type: 'number' } }, required: ['id'] }},
@@ -430,11 +497,11 @@ const TOOLS_DEFINITIONS = [
430
497
  inputSchema: { type: 'object', properties: {} }},
431
498
 
432
499
  // ── SEO METADATA (3) ──
433
- { name: 'wp_get_seo_meta', description: 'Get SEO metadata (title, description, focus keyword, robots, canonical, og) for a post or page. Auto-detects Yoast SEO, RankMath, SEOPress, or All in One SEO.',
500
+ { name: 'wp_get_seo_meta', description: 'Get SEO metadata (title, description, focus keyword, robots, canonical, og) for a post or page. Auto-detects Yoast SEO, RankMath, SEOPress, or All in One SEO. Preferred over wp_get_post for SEO-only workflows — no HTML content loaded.',
434
501
  inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post or page ID' }, post_type: { type: 'string', default: 'post', description: 'post or page' } }, required: ['id'] }},
435
502
  { name: 'wp_update_seo_meta', description: 'Update SEO metadata (title, description, focus keyword) for a post or page. Auto-detects installed SEO plugin.',
436
503
  inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post or page ID' }, post_type: { type: 'string', default: 'post', description: 'post or page' }, title: { type: 'string', description: 'SEO title' }, description: { type: 'string', description: 'Meta description' }, focus_keyword: { type: 'string', description: 'Focus keyword' }, canonical_url: { type: 'string', description: 'Canonical URL' }, robots_noindex: { type: 'boolean', description: 'Set noindex' }, robots_nofollow: { type: 'boolean', description: 'Set nofollow' } }, required: ['id'] }},
437
- { name: 'wp_audit_seo', description: 'Audit SEO metadata across multiple posts/pages. Returns missing titles, descriptions, keywords, and quality scores.',
504
+ { name: 'wp_audit_seo', description: 'Audit SEO metadata across multiple posts/pages. Returns scores and issue flags only — never loads post content, safe for bulk operations.',
438
505
  inputSchema: { type: 'object', properties: { post_type: { type: 'string', default: 'post', description: 'post or page' }, per_page: { type: 'number', default: 20, description: 'Number of posts to audit (max 100)' }, status: { type: 'string', default: 'publish' }, orderby: { type: 'string', default: 'date' }, order: { type: 'string', default: 'desc' } }}},
439
506
 
440
507
  // ── PLUGINS (3) ──
@@ -458,8 +525,114 @@ const TOOLS_DEFINITIONS = [
458
525
  inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post or page ID' }, revision_id: { type: 'number', description: 'Revision ID' }, post_type: { type: 'string', enum: ['post', 'page'], default: 'post', description: 'Post type' } }, required: ['post_id', 'revision_id'] }},
459
526
  { name: 'wp_restore_revision', description: 'Restore a post or page to a previous revision. Copies revision content back to the post. Blocked by WP_READ_ONLY.',
460
527
  inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post or page ID' }, revision_id: { type: 'number', description: 'Revision ID to restore' }, post_type: { type: 'string', enum: ['post', 'page'], default: 'post', description: 'Post type' } }, required: ['post_id', 'revision_id'] }},
461
- { name: 'wp_delete_revision', description: 'Permanently delete a revision. This action cannot be undone. Blocked by WP_READ_ONLY and WP_DISABLE_DELETE.',
462
- inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post or page ID' }, revision_id: { type: 'number', description: 'Revision ID to delete' }, post_type: { type: 'string', enum: ['post', 'page'], default: 'post', description: 'Post type' } }, required: ['post_id', 'revision_id'] }}
528
+ { name: 'wp_delete_revision', description: 'Permanently delete a revision. This action cannot be undone. Blocked by WP_READ_ONLY and WP_DISABLE_DELETE. When WP_CONFIRM_DESTRUCTIVE=true, requires a confirmation_token.',
529
+ inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post or page ID' }, revision_id: { type: 'number', description: 'Revision ID to delete' }, post_type: { type: 'string', enum: ['post', 'page'], default: 'post', description: 'Post type' }, confirmation_token: { type: 'string', description: 'Confirmation token returned by the first call when WP_CONFIRM_DESTRUCTIVE=true' } }, required: ['post_id', 'revision_id'] }},
530
+
531
+ // ── LINK ANALYSIS (2) ──
532
+ { name: 'wp_analyze_links', description: 'Analyze internal and external links in a post. Optionally checks for broken internal links via HEAD requests (read-only).',
533
+ inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post ID to analyze' }, check_broken: { type: 'boolean', default: true, description: 'Check broken internal links via HEAD request' }, timeout_ms: { type: 'number', default: 5000, description: 'Timeout per HEAD request in ms' } }, required: ['post_id'] }},
534
+ { name: 'wp_suggest_internal_links', description: 'Suggest internal links for a post based on keyword relevance, shared categories, and content freshness (read-only). Use before wp_get_post with content_format:"links_only" to map existing links first.',
535
+ inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post ID to get suggestions for' }, max_suggestions: { type: 'number', default: 5, description: 'Number of suggestions (1-10)' }, focus_keywords: { type: 'array', items: { type: 'string' }, description: 'Additional keywords to match against' }, exclude_already_linked: { type: 'boolean', default: true, description: 'Exclude posts already linked from the current post' } }, required: ['post_id'] }},
536
+
537
+ // ── WOOCOMMERCE (6) ──
538
+ { name: 'wc_list_products', description: 'List WooCommerce products with filtering and search. Requires WC_CONSUMER_KEY and WC_CONSUMER_SECRET. Blocked by WP_READ_ONLY.',
539
+ inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 10 }, page: { type: 'number', default: 1 }, status: { type: 'string', default: 'any', description: 'any, draft, pending, private, publish' }, search: { type: 'string' }, category: { type: 'number', description: 'Category ID' }, orderby: { type: 'string', default: 'date', description: 'date, id, title, price, popularity' }, order: { type: 'string', default: 'desc', description: 'asc or desc' } }}},
540
+ { name: 'wc_get_product', description: 'Get a WooCommerce product by ID with full details. Includes variations summary for variable products. Blocked by WP_READ_ONLY.',
541
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Product ID' } }, required: ['id'] }},
542
+ { name: 'wc_list_orders', description: 'List WooCommerce orders with filtering. Blocked by WP_READ_ONLY.',
543
+ inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 10 }, page: { type: 'number', default: 1 }, status: { type: 'string', default: 'any', description: 'any, pending, processing, on-hold, completed, cancelled, refunded, failed' }, customer: { type: 'number', description: 'Customer ID' }, orderby: { type: 'string', default: 'date' }, order: { type: 'string', default: 'desc' } }}},
544
+ { name: 'wc_get_order', description: 'Get a WooCommerce order by ID with full details including line items, shipping, billing, and payment info. Blocked by WP_READ_ONLY.',
545
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Order ID' } }, required: ['id'] }},
546
+ { name: 'wc_list_customers', description: 'List WooCommerce customers with search and filtering. Blocked by WP_READ_ONLY.',
547
+ inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 10 }, page: { type: 'number', default: 1 }, search: { type: 'string' }, orderby: { type: 'string', default: 'date_created' }, order: { type: 'string', default: 'desc' }, role: { type: 'string', default: 'customer' } }}},
548
+ { name: 'wc_price_guardrail', description: 'Analyze a product price change without modifying anything. Returns safe/unsafe assessment based on threshold percentage. Always allowed even in WP_READ_ONLY mode.',
549
+ inputSchema: { type: 'object', properties: { product_id: { type: 'number', description: 'Product ID' }, new_price: { type: 'number', description: 'Proposed new price' }, threshold_percent: { type: 'number', default: 20, description: 'Maximum allowed change percentage (default 20)' } }, required: ['product_id', 'new_price'] }},
550
+
551
+ // ── WOOCOMMERCE INTELLIGENCE (4) ──
552
+ { name: 'wc_inventory_alert', description: 'Identify low-stock and out-of-stock products below a threshold, sorted by urgency. Blocked by WP_READ_ONLY.',
553
+ inputSchema: { type: 'object', properties: { threshold: { type: 'number', default: 5, description: 'Stock quantity threshold (default 5)' }, per_page: { type: 'number', default: 50, description: 'Products to scan (max 100)' }, include_out_of_stock: { type: 'boolean', default: true, description: 'Include out-of-stock products' } }}},
554
+ { name: 'wc_order_intelligence', description: 'Analyze customer purchase history: lifetime value, average order, favourite products, order frequency, status breakdown. Blocked by WP_READ_ONLY.',
555
+ inputSchema: { type: 'object', properties: { customer_id: { type: 'number', description: 'Customer ID' } }, required: ['customer_id'] }},
556
+ { name: 'wc_seo_product_audit', description: 'Audit WooCommerce product listings for SEO issues (missing descriptions, images, alt text, generic slugs, missing price). Returns per-product scores. Blocked by WP_READ_ONLY.',
557
+ inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 20, description: 'Products to audit (max 100)' }, page: { type: 'number', default: 1 } }}},
558
+ { name: 'wc_suggest_product_links', description: 'Suggest WooCommerce products to link from a WordPress blog post based on SEO keyword relevance. Blocked by WP_READ_ONLY.',
559
+ inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'WordPress post ID' }, max_suggestions: { type: 'number', default: 3, description: 'Maximum suggestions (1-5)' } }, required: ['post_id'] }},
560
+
561
+ // ── WOOCOMMERCE WRITE (3) ──
562
+ { name: 'wc_update_product', description: 'Update a WooCommerce product. Includes automatic price guardrail: price changes >20% require price_guardrail_confirmed=true. Blocked by WP_READ_ONLY.',
563
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Product ID' }, name: { type: 'string' }, description: { type: 'string' }, short_description: { type: 'string' }, regular_price: { type: 'string', description: 'Format "19.99"' }, sale_price: { type: 'string' }, status: { type: 'string', description: 'publish, draft, or private' }, price_guardrail_confirmed: { type: 'boolean', default: false, description: 'Set true to bypass price guardrail after calling wc_price_guardrail' } }, required: ['id'] }},
564
+ { name: 'wc_update_stock', description: 'Update stock quantity of a WooCommerce product or variation. Blocked by WP_READ_ONLY.',
565
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Product ID' }, stock_quantity: { type: 'number', description: 'New stock quantity (>= 0)' }, variation_id: { type: 'number', description: 'Variation ID (for variable products)' } }, required: ['id', 'stock_quantity'] }},
566
+ { name: 'wc_update_order_status', description: 'Update WooCommerce order status with transition validation. Blocked by WP_READ_ONLY.',
567
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Order ID' }, status: { type: 'string', description: 'New status (processing, completed, cancelled, refunded, on-hold, failed)' }, note: { type: 'string', description: 'Optional internal note added to the order' } }, required: ['id', 'status'] }},
568
+
569
+ // ── SEO ADVANCED (3) ──
570
+ { name: 'wp_audit_media_seo', description: 'Audit media library images for SEO issues (missing alt text, filename-as-alt, alt too short). Optionally scans post content for inline images. Read-only.',
571
+ inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 50, description: 'Media items to audit (max 100)' }, page: { type: 'number', default: 1 }, post_id: { type: 'number', description: 'Optional: also scan inline images from this post' } }}},
572
+ { name: 'wp_find_orphan_pages', description: 'Find published pages with no internal links pointing to them from other pages. Read-only.',
573
+ inputSchema: { type: 'object', properties: { per_page: { type: 'number', default: 100, description: 'Pages to scan (max 100)' }, exclude_ids: { type: 'array', items: { type: 'number' }, description: 'Page IDs to exclude from orphan check' }, min_words: { type: 'number', default: 0, description: 'Minimum word count to include in results' } }}},
574
+ { name: 'wp_audit_heading_structure', description: 'Audit heading hierarchy (H1-H6) of a post or page for SEO issues: H1 in content, level skips, empty headings, keyword stuffing. Read-only.',
575
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post or page ID' }, post_type: { type: 'string', default: 'post', description: 'post or page' }, focus_keyword: { type: 'string', description: 'Optional keyword to check in H2 headings' } }, required: ['id'] }},
576
+
577
+ // ── SEO ADVANCED v4.1 (3) ──
578
+ { name: 'wp_find_thin_content', description: 'Find thin/low-quality published posts: too short, outdated, uncategorized. Classifies severity and suggests actions. Read-only.',
579
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', default: 100, description: 'Max posts to scan (1-500)' }, min_words: { type: 'number', default: 300, description: 'Threshold for "too short"' }, critical_words: { type: 'number', default: 150, description: 'Threshold for "very short"' }, max_age_days: { type: 'number', default: 730, description: 'Days since update to flag as outdated' }, include_uncategorized: { type: 'boolean', default: true, description: 'Flag uncategorized posts' }, post_type: { type: 'string', default: 'post', description: 'post or page' } }}},
580
+ { name: 'wp_audit_canonicals', description: 'Audit canonical URLs for SEO issues: missing, HTTP on HTTPS site, staging URLs, wrong domain, trailing slash mismatch. Auto-detects SEO plugin. Read-only.',
581
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', default: 50, description: 'Max posts to audit (1-200)' }, post_type: { type: 'string', default: 'post', description: 'post, page, or both' }, check_staging_patterns: { type: 'boolean', default: true, description: 'Detect staging/dev URLs' } }}},
582
+ { name: 'wp_analyze_eeat_signals', description: 'Analyze E-E-A-T (Experience, Expertise, Authoritativeness, Trustworthiness) signals for posts. Scores 0-100 with actionable priority fixes. Read-only.',
583
+ inputSchema: { type: 'object', properties: { post_ids: { type: 'array', items: { type: 'number' }, description: 'Specific post IDs to analyze (if empty, audits latest N)' }, limit: { type: 'number', default: 10, description: 'Number of latest posts to audit (1-50)' }, post_type: { type: 'string', default: 'post', description: 'post or page' }, authoritative_domains: { type: 'array', items: { type: 'string' }, default: ['wikipedia.org', 'gov', 'edu', 'who.int', 'pubmed'], description: 'Domains considered authoritative' } }}},
584
+
585
+ // ── SEO ADVANCED v4.2 (4) ──
586
+ { name: 'wp_find_broken_internal_links', description: 'Scan published posts, extract all internal links and verify accessibility via HEAD requests. Detects 404s, 301/302 redirects, timeouts and network errors. Configurable batching to avoid overloading WordPress. Read-only.',
587
+ inputSchema: { type: 'object', properties: { limit_posts: { type: 'number', default: 20, description: 'Max posts to scan (1-100)' }, batch_size: { type: 'number', default: 5, description: 'Links per batch (1-10)' }, timeout_ms: { type: 'number', default: 5000, description: 'Timeout per HEAD request (1000-30000)' }, delay_ms: { type: 'number', default: 200, description: 'Delay between batches (0-2000)' }, post_type: { type: 'string', default: 'post', description: 'post, page, or both' }, include_redirects: { type: 'boolean', default: true, description: 'Include 301/302 redirects in results' } }}},
588
+ { name: 'wp_find_keyword_cannibalization', description: 'Detect articles targeting the same SEO focus keywords, creating internal competition that dilutes authority. Returns cannibalization groups with recommended actions. Read-only.',
589
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', default: 200, description: 'Max posts to analyze (1-500)' }, post_type: { type: 'string', default: 'post', description: 'post, page, or both' }, similarity_mode: { type: 'string', default: 'normalized', description: 'exact or normalized keyword matching' }, min_group_size: { type: 'number', default: 2, description: 'Minimum articles per group (min 2)' } }}},
590
+ { name: 'wp_audit_taxonomies', description: 'Audit categories and tags for taxonomy bloat: empty tags, single-post tags, near-duplicate terms, categories without SEO description. These archive pages create crawl waste for Googlebot. Read-only.',
591
+ inputSchema: { type: 'object', properties: { check_tags: { type: 'boolean', default: true, description: 'Audit tags' }, check_categories: { type: 'boolean', default: true, description: 'Audit categories' }, min_posts_threshold: { type: 'number', default: 2, description: 'Minimum posts per term' }, detect_duplicates: { type: 'boolean', default: true, description: 'Detect near-duplicate terms via Levenshtein' } }}},
592
+ { name: 'wp_audit_outbound_links', description: 'Analyze outbound (external) links in published posts. Detects posts without external sources, posts with too many outbound links (dilution), and identifies most-cited domains. Good outbound link profile improves E-E-A-T credibility. Read-only.',
593
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', default: 30, description: 'Max posts to audit (1-100)' }, post_type: { type: 'string', default: 'post', description: 'post or page' }, min_outbound: { type: 'number', default: 1, description: 'Minimum outbound links threshold' }, max_outbound: { type: 'number', default: 15, description: 'Maximum outbound links before dilution warning' }, authoritative_domains: { type: 'array', items: { type: 'string' }, default: ['wikipedia.org', 'gov', 'edu', 'who.int', 'pubmed.ncbi'], description: 'Domains considered authoritative' } }}},
594
+
595
+ // ── CONTENT INTELLIGENCE v4.4 (2) ──
596
+ { name: 'wp_get_content_brief', description: 'Aggregate a complete editorial/SEO brief for a single post or page in one call: word count, readability score, heading structure, internal/external links, SEO metadata, content sections (intro, conclusion, FAQ, lists, tables, images), categories and tags resolved to names. Read-only.',
597
+ inputSchema: { type: 'object', properties: { id: { type: 'number', description: 'Post or page ID' }, post_type: { type: 'string', default: 'post', description: 'post or page' } }, required: ['id'] }},
598
+ { name: 'wp_extract_post_outline', description: 'Extract heading structure (H1-H4) from N posts in a category to build a reference outline. Returns per-post outlines with word counts, aggregated stats, and common H2 patterns ranked by frequency. Read-only.',
599
+ inputSchema: { type: 'object', properties: { category_id: { type: 'number', description: 'Category ID to analyze' }, post_type: { type: 'string', default: 'post', description: 'post or page' }, limit: { type: 'number', default: 10, description: 'Max posts to analyze (1-50)' } }, required: ['category_id'] }},
600
+
601
+ // ── CONTENT INTELLIGENCE v4.4 Week 2 (3) ──
602
+ { name: 'wp_audit_readability', description: 'Audit Flesch-Kincaid FR readability in bulk across N published posts. Returns per-post scores, transition word density, passive voice ratio, issues flagged, and aggregated distribution. Sorted worst-first. Read-only.',
603
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page'], description: 'post or page (default post)' }, category_id: { type: 'number', description: 'Optional: filter by category ID' }, min_words: { type: 'number', description: 'Minimum word count to include (default 100)' } }}},
604
+ { name: 'wp_audit_update_frequency', description: 'Find posts not modified in X days, cross-referenced with SEO metadata quality to prioritize content refreshes. Sorted by priority (age x SEO gap). Read-only.',
605
+ inputSchema: { type: 'object', properties: { days_threshold: { type: 'number', description: 'Flag posts not modified in X days (default 180)' }, limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page'], description: 'post or page (default post)' }, include_seo_score: { type: 'boolean', description: 'Cross-reference with SEO metadata quality (default true)' } }}},
606
+ { name: 'wp_build_link_map', description: 'Build a complete internal linking matrix with simplified PageRank scoring. Identifies orphan posts, inbound/outbound counts, and generates a sparse adjacency matrix. Read-only.',
607
+ inputSchema: { type: 'object', properties: { post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' }, limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, category_id: { type: 'number', description: 'Optional: filter by category ID' } }}},
608
+
609
+ // ── CONTENT INTELLIGENCE v4.4 Week 3 (3) ──
610
+ { name: 'wp_audit_anchor_texts', description: 'Audit internal link anchor text diversity and relevance across N posts. Detects generic anchors, over-optimized anchors, image links without text. Sorted by diversity score ASC. Read-only.',
611
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' } }}},
612
+ { name: 'wp_audit_schema_markup', description: 'Detect and validate JSON-LD schema.org blocks in post HTML. Checks Article, FAQPage, HowTo, LocalBusiness, BreadcrumbList types for required fields. Read-only.',
613
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' } }}},
614
+ { name: 'wp_audit_content_structure', description: 'Analyze editorial structure: intro/conclusion/FAQ presence, heading density, lists, tables, images, paragraphs. Scores 0-100. Sorted by structure score ASC. Read-only.',
615
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' }, category_id: { type: 'number', description: 'Optional: filter by category ID' } }}},
616
+
617
+ // ── CONTENT INTELLIGENCE v4.4 Batch 4A (4) ──
618
+ { name: 'wp_find_duplicate_content', description: 'Detect near-duplicate content via TF-IDF cosine similarity. Returns duplicate pairs with severity and clusters. Read-only.',
619
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-100, default 50)' }, post_type: { type: 'string', enum: ['post', 'page'], description: 'post or page (default post)' }, category_id: { type: 'number', description: 'Optional: filter by category ID' }, similarity_threshold: { type: 'number', description: 'Minimum similarity to flag (0.0-1.0, default 0.7)' } }}},
620
+ { name: 'wp_find_content_gaps', description: 'Identify taxonomy terms (categories/tags) with too few posts — content creation opportunities. Read-only.',
621
+ inputSchema: { type: 'object', properties: { min_posts: { type: 'number', description: 'Minimum posts per term to NOT be flagged (default 3)' }, taxonomy: { type: 'string', enum: ['category', 'post_tag', 'both'], description: 'Taxonomy to analyze (default both)' }, exclude_empty: { type: 'boolean', description: 'Exclude terms with 0 posts (default false)' } }}},
622
+ { name: 'wp_extract_faq_blocks', description: 'Inventory all FAQ blocks: JSON-LD FAQPage, Gutenberg Yoast/RankMath blocks, HTML Q&A patterns. Read-only.',
623
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to scan (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' } }}},
624
+ { name: 'wp_audit_cta_presence', description: 'Detect CTA presence per post: contact links, forms, buttons, phone links, quote requests, signup links. Scores 0-100. Read-only.',
625
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-200, default 50)' }, post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' }, category_id: { type: 'number', description: 'Optional: filter by category ID' } }}},
626
+
627
+ // ── CONTENT INTELLIGENCE v4.4 Batch 4B (4) ──
628
+ { name: 'wp_extract_entities', description: 'Extract named entities (brands, locations, persons, organizations) from posts using regex heuristics. Read-only.',
629
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-100, default 20)' }, post_type: { type: 'string', enum: ['post', 'page'], description: 'post or page (default post)' }, min_occurrences: { type: 'number', description: 'Minimum total occurrences across corpus (default 2)' } }}},
630
+ { name: 'wp_get_publishing_velocity', description: 'Analyze publishing cadence by author and category over configurable periods. Read-only.',
631
+ inputSchema: { type: 'object', properties: { periods: { type: 'string', description: "Comma-separated day periods (default '30,90,180')" }, post_type: { type: 'string', enum: ['post', 'page'], description: 'post or page (default post)' }, limit: { type: 'number', description: 'Max posts to fetch (1-500, default 200)' } }}},
632
+ { name: 'wp_compare_revisions_diff', description: 'Diff between two post revisions: lines/words added/removed, headings diff, amplitude score. Read-only.',
633
+ inputSchema: { type: 'object', properties: { post_id: { type: 'number', description: 'Post or page ID' }, revision_id_from: { type: 'number', description: 'Older revision ID (baseline)' }, revision_id_to: { type: 'number', description: 'Newer revision ID (omit for current post)' }, post_type: { type: 'string', enum: ['post', 'page'], description: 'post or page (default post)' } }, required: ['post_id', 'revision_id_from'] }},
634
+ { name: 'wp_list_posts_by_word_count', description: 'List posts sorted by word count with automatic length segmentation and distribution stats. Read-only.',
635
+ inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Max posts to analyze (1-500, default 100)' }, post_type: { type: 'string', enum: ['post', 'page', 'both'], description: 'post, page, or both (default post)' }, order: { type: 'string', enum: ['asc', 'desc'], description: 'Sort order by word count (default desc)' }, category_id: { type: 'number', description: 'Optional: filter by category ID' } }}}
463
636
  ];
464
637
 
465
638
  function registerHandlers(s) {
@@ -498,21 +671,34 @@ export async function handleToolCall(request) {
498
671
  // ── POSTS ──
499
672
 
500
673
  case 'wp_list_posts': {
501
- validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 }, status: { type: 'string', enum: STATUSES }, orderby: { type: 'string', enum: ORDERBY }, order: { type: 'string', enum: ORDERS } });
502
- const { per_page = 10, page = 1, status = 'publish', orderby = 'date', order = 'desc', categories, tags, search, author } = args;
674
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 }, status: { type: 'string', enum: STATUSES }, orderby: { type: 'string', enum: ORDERBY }, order: { type: 'string', enum: ORDERS }, mode: { type: 'string', enum: ['full', 'summary', 'ids_only'] } });
675
+ const { per_page = 10, page = 1, status = 'publish', orderby = 'date', order = 'desc', categories, tags, search, author, mode = 'full' } = args;
503
676
  let ep = `/posts?per_page=${per_page}&page=${page}&status=${status}&orderby=${orderby}&order=${order}`;
504
677
  if (categories) ep += `&categories=${categories}`; if (tags) ep += `&tags=${tags}`;
505
678
  if (search) ep += `&search=${encodeURIComponent(search)}`; if (author) ep += `&author=${author}`;
506
679
  const posts = await wpApiCall(ep);
507
- result = json({ total: posts.length, page, posts: posts.map(p => ({ id: p.id, title: p.title.rendered, status: p.status, date: p.date, modified: p.modified, link: p.link, author: p.author, categories: p.categories, tags: p.tags, excerpt: strip(p.excerpt.rendered).substring(0, 200) })) });
680
+ let listResult;
681
+ if (mode === 'ids_only') {
682
+ listResult = { total: posts.length, page, mode: 'ids_only', ids: posts.map(p => p.id) };
683
+ } else if (mode === 'summary') {
684
+ listResult = { total: posts.length, page, mode: 'summary', posts: posts.map(p => ({ id: p.id, title: p.title.rendered, slug: p.slug, date: p.date, status: p.status, link: p.link })) };
685
+ } else {
686
+ listResult = { total: posts.length, page, posts: posts.map(p => ({ id: p.id, title: p.title.rendered, status: p.status, date: p.date, modified: p.modified, link: p.link, author: p.author, categories: p.categories, tags: p.tags, excerpt: strip(p.excerpt.rendered).substring(0, 200) })) };
687
+ }
688
+ result = json(listResult);
508
689
  auditLog({ tool: name, action: 'list', status: 'success', latency_ms: Date.now() - t0, params: sanitizeParams(args) });
509
690
  break;
510
691
  }
511
692
 
512
693
  case 'wp_get_post': {
513
- validateInput(args, { id: { type: 'number', required: true, min: 1 } });
694
+ validateInput(args, { id: { type: 'number', required: true, min: 1 }, fields: { type: 'array' }, content_format: { type: 'string', enum: ['html', 'text', 'links_only'] } });
695
+ const { content_format = 'html', fields: requestedFields } = args;
514
696
  const p = await wpApiCall(`/posts/${args.id}`);
515
- result = json({ id: p.id, title: p.title.rendered, content: p.content.rendered, excerpt: p.excerpt.rendered, status: p.status, date: p.date, modified: p.modified, link: p.link, slug: p.slug, categories: p.categories, tags: p.tags, author: p.author, featured_media: p.featured_media, comment_status: p.comment_status, meta: p.meta || {} });
697
+ let postData = { id: p.id, title: p.title.rendered, content: p.content.rendered, excerpt: p.excerpt.rendered, status: p.status, date: p.date, modified: p.modified, link: p.link, slug: p.slug, categories: p.categories, tags: p.tags, author: p.author, featured_media: p.featured_media, comment_status: p.comment_status, meta: p.meta || {} };
698
+ const { url: siteUrl } = getActiveAuth();
699
+ postData = applyContentFormat(postData, content_format, siteUrl);
700
+ if (requestedFields && requestedFields.length > 0) postData = summarizePost(postData, requestedFields);
701
+ result = json(postData);
516
702
  auditLog({ tool: name, target: args.id, target_type: 'post', action: 'read', status: 'success', latency_ms: Date.now() - t0 });
517
703
  break;
518
704
  }
@@ -520,6 +706,10 @@ export async function handleToolCall(request) {
520
706
  case 'wp_create_post': {
521
707
  validateInput(args, { title: { type: 'string', required: true }, content: { type: 'string', required: true }, status: { type: 'string', enum: STATUSES.filter(s => s !== 'trash') } });
522
708
  enforceDraftOnly(args.status); enforceAllowedStatuses(args.status); enforceAllowedTypes('post');
709
+ if (getActiveControls().require_approval && args.status === 'publish') {
710
+ auditLog({ tool: name, target: null, target_type: 'post', action: 'create', status: 'blocked', latency_ms: Date.now() - t0, params: sanitizeParams(args), error: 'APPROVAL REQUIRED: Use wp_submit_for_review then wp_approve_post' });
711
+ return { content: [{ type: 'text', text: 'Error: APPROVAL REQUIRED: Use wp_submit_for_review then wp_approve_post' }], isError: true };
712
+ }
523
713
  const { title, content, status = 'draft', excerpt, categories, tags, slug, featured_media, meta, author } = args;
524
714
  const data = { title, content, status };
525
715
  if (excerpt) data.excerpt = excerpt; if (categories) data.categories = categories; if (tags) data.tags = tags;
@@ -533,6 +723,10 @@ export async function handleToolCall(request) {
533
723
  case 'wp_update_post': {
534
724
  validateInput(args, { id: { type: 'number', required: true, min: 1 }, status: { type: 'string', enum: STATUSES } });
535
725
  if (args.status) { enforceDraftOnly(args.status); enforceAllowedStatuses(args.status); }
726
+ if (getActiveControls().require_approval && args.status === 'publish') {
727
+ auditLog({ tool: name, target: args.id, target_type: 'post', action: 'update', status: 'blocked', latency_ms: Date.now() - t0, params: sanitizeParams(args), error: 'APPROVAL REQUIRED: Use wp_submit_for_review then wp_approve_post' });
728
+ return { content: [{ type: 'text', text: 'Error: APPROVAL REQUIRED: Use wp_submit_for_review then wp_approve_post' }], isError: true };
729
+ }
536
730
  const { id, ...upd } = args;
537
731
  const up = await wpApiCall(`/posts/${id}`, { method: 'POST', body: JSON.stringify(upd) });
538
732
  result = json({ success: true, message: `Post ${id} updated`, post: { id: up.id, title: up.title.rendered, status: up.status, link: up.link, modified: up.modified } });
@@ -542,10 +736,31 @@ export async function handleToolCall(request) {
542
736
 
543
737
  case 'wp_delete_post': {
544
738
  validateInput(args, { id: { type: 'number', required: true, min: 1 } });
545
- const { id, force = false } = args;
739
+ const { id, force = false, confirmation_token } = args;
740
+ const deleteAction = force ? 'permanent_delete' : 'trash';
741
+
742
+ // Two-step confirmation when WP_CONFIRM_DESTRUCTIVE=true
743
+ if (getActiveControls().confirm_destructive) {
744
+ if (!confirmation_token) {
745
+ // Step 1: return confirmation_required with token
746
+ const p = await wpApiCall(`/posts/${id}`);
747
+ const token = generateToken(id, deleteAction);
748
+ const verb = force ? 'permanently deleted' : 'trashed';
749
+ result = json({ status: 'confirmation_required', post_id: id, post_title: p.title?.rendered || `Post #${id}`, action: deleteAction, confirmation_token: token, expires_in: 60, message: `Post #${id} '${p.title?.rendered || ''}' will be ${verb}. Call again with confirmation_token to confirm.` });
750
+ auditLog({ tool: name, target: id, target_type: 'post', action: 'delete_requested', status: 'pending', latency_ms: Date.now() - t0, params: { id, force } });
751
+ break;
752
+ }
753
+ // Step 2: validate token then execute
754
+ const validation = validateToken(confirmation_token, id, deleteAction);
755
+ if (!validation.valid) {
756
+ auditLog({ tool: name, target: id, target_type: 'post', action: deleteAction, status: 'error', latency_ms: Date.now() - t0, params: { id, force }, error: 'Invalid or expired confirmation token' });
757
+ return { content: [{ type: 'text', text: 'Error: Invalid or expired confirmation token' }], isError: true };
758
+ }
759
+ }
760
+
546
761
  const dp = await wpApiCall(`/posts/${id}${force ? '?force=true' : ''}`, { method: 'DELETE' });
547
762
  result = json({ success: true, message: force ? `Post ${id} permanently deleted` : `Post ${id} trashed`, post: { id: dp.id, title: dp.title?.rendered || dp.previous?.title?.rendered, status: force ? 'deleted' : 'trash' } });
548
- auditLog({ tool: name, target: id, target_type: 'post', action: force ? 'permanent_delete' : 'trash', status: 'success', latency_ms: Date.now() - t0 });
763
+ auditLog({ tool: name, target: id, target_type: 'post', action: deleteAction, status: 'success', latency_ms: Date.now() - t0 });
549
764
  break;
550
765
  }
551
766
 
@@ -751,8 +966,9 @@ export async function handleToolCall(request) {
751
966
  const prev = currentTarget?.name || 'default';
752
967
  currentTarget = { name: site, ...targets[site] };
753
968
  log.info(`Target switched: ${prev} → ${site} (${currentTarget.url})`);
754
- result = json({ success: true, message: `Active site: ${site}`, previous: prev, current: { name: site, url: currentTarget.url } });
755
- auditLog({ tool: name, action: 'switch_target', status: 'success', latency_ms: Date.now() - t0, params: { from: prev, to: site } });
969
+ const effectiveControls = getActiveControls();
970
+ result = json({ success: true, message: `Active site: ${site}`, previous: prev, current: { name: site, url: currentTarget.url }, effective_controls: effectiveControls });
971
+ auditLog({ tool: name, action: 'switch_target', status: 'success', latency_ms: Date.now() - t0, params: { from: prev, to: site }, effective_controls: effectiveControls });
756
972
  break;
757
973
  }
758
974
 
@@ -774,12 +990,17 @@ export async function handleToolCall(request) {
774
990
  site: { name: si.name, description: si.description, url: si.url || baseUrl, gmt_offset: si.gmt_offset, timezone_string: si.timezone_string },
775
991
  current_user: u ? { id: u.id, name: u.name, slug: u.slug, roles: u.roles } : null,
776
992
  post_types: postTypes,
777
- enterprise_controls: {
778
- read_only: process.env.WP_READ_ONLY === 'true', draft_only: process.env.WP_DRAFT_ONLY === 'true', delete_disabled: process.env.WP_DISABLE_DELETE === 'true', plugin_management_disabled: process.env.WP_DISABLE_PLUGIN_MANAGEMENT === 'true',
779
- rate_limit: MAX_CALLS_PER_MINUTE > 0 ? `${MAX_CALLS_PER_MINUTE}/min` : 'unlimited',
780
- allowed_types: ALLOWED_TYPES || 'all', allowed_statuses: ALLOWED_STATUSES || 'all',
781
- audit_log: AUDIT_LOG
782
- },
993
+ enterprise_controls: (() => {
994
+ const c = getActiveControls();
995
+ const s = getControlSources();
996
+ return {
997
+ read_only: c.read_only, draft_only: c.draft_only, delete_disabled: c.disable_delete, plugin_management_disabled: c.disable_plugin_management, require_approval: c.require_approval, confirm_destructive: c.confirm_destructive,
998
+ rate_limit: c.max_calls_per_minute > 0 ? `${c.max_calls_per_minute}/min` : 'unlimited',
999
+ allowed_types: ALLOWED_TYPES || 'all', allowed_statuses: ALLOWED_STATUSES || 'all',
1000
+ audit_log: AUDIT_LOG,
1001
+ ...s
1002
+ };
1003
+ })(),
783
1004
  multi_target: {
784
1005
  enabled: isMultiTarget, active_site: currentTarget?.name || 'default',
785
1006
  available_sites: Object.keys(targets)
@@ -1282,8 +1503,24 @@ export async function handleToolCall(request) {
1282
1503
  revision_id: { type: 'number', required: true, min: 1 },
1283
1504
  post_type: { type: 'string', enum: ['post', 'page'] }
1284
1505
  });
1285
- const { post_id, revision_id, post_type = 'post' } = args;
1506
+ const { post_id, revision_id, post_type = 'post', confirmation_token } = args;
1286
1507
  const base = post_type === 'page' ? 'pages' : 'posts';
1508
+
1509
+ // Two-step confirmation when WP_CONFIRM_DESTRUCTIVE=true
1510
+ if (getActiveControls().confirm_destructive) {
1511
+ if (!confirmation_token) {
1512
+ const token = generateToken(revision_id, 'delete_revision');
1513
+ result = json({ status: 'confirmation_required', revision_id, post_id, action: 'delete_revision', confirmation_token: token, expires_in: 60, message: `Revision #${revision_id} of post #${post_id} will be permanently deleted. Call again with confirmation_token to confirm.` });
1514
+ auditLog({ tool: name, target: revision_id, target_type: 'revision', action: 'delete_requested', status: 'pending', latency_ms: Date.now() - t0, params: { post_id, revision_id } });
1515
+ break;
1516
+ }
1517
+ const validation = validateToken(confirmation_token, revision_id, 'delete_revision');
1518
+ if (!validation.valid) {
1519
+ auditLog({ tool: name, target: revision_id, target_type: 'revision', action: 'delete_revision', status: 'error', latency_ms: Date.now() - t0, params: { post_id, revision_id }, error: 'Invalid or expired confirmation token' });
1520
+ return { content: [{ type: 'text', text: 'Error: Invalid or expired confirmation token' }], isError: true };
1521
+ }
1522
+ }
1523
+
1287
1524
  try {
1288
1525
  await wpApiCall(`/${base}/${post_id}/revisions/${revision_id}?force=true`, { method: 'DELETE' });
1289
1526
  result = json({ deleted: true, revision_id, post_id, post_type });
@@ -1299,6 +1536,2889 @@ export async function handleToolCall(request) {
1299
1536
  break;
1300
1537
  }
1301
1538
 
1539
+ // ── APPROVAL WORKFLOW ──
1540
+
1541
+ case 'wp_submit_for_review': {
1542
+ validateInput(args, { id: { type: 'number', required: true, min: 1 } });
1543
+ const { id, note } = args;
1544
+ const p = await wpApiCall(`/posts/${id}`);
1545
+ if (p.status !== 'draft' && p.status !== 'auto-draft') {
1546
+ throw new Error(`Post ${id} is in "${p.status}" status. Only "draft" or "auto-draft" posts can be submitted for review.`);
1547
+ }
1548
+ const data = { status: 'pending' };
1549
+ if (note) data.meta = { _mcp_review_note: note };
1550
+ const up = await wpApiCall(`/posts/${id}`, { method: 'POST', body: JSON.stringify(data) });
1551
+ result = json({ success: true, message: `Post ${id} submitted for review`, post: { id: up.id, title: up.title.rendered, status: up.status, link: up.link } });
1552
+ auditLog({ tool: name, target: id, target_type: 'post', action: 'submit_for_review', status: 'success', latency_ms: Date.now() - t0, params: { id } });
1553
+ break;
1554
+ }
1555
+
1556
+ case 'wp_approve_post': {
1557
+ validateInput(args, { id: { type: 'number', required: true, min: 1 } });
1558
+ const { id } = args;
1559
+ if (getActiveControls().draft_only) {
1560
+ auditLog({ tool: name, target: id, target_type: 'post', action: 'approve', status: 'blocked', latency_ms: Date.now() - t0, params: { id }, error: 'Blocked: Server is in DRAFT-ONLY mode (WP_DRAFT_ONLY=true). Publishing is not allowed.' });
1561
+ return { content: [{ type: 'text', text: 'Error: Blocked: Server is in DRAFT-ONLY mode (WP_DRAFT_ONLY=true). Publishing is not allowed.' }], isError: true };
1562
+ }
1563
+ const p = await wpApiCall(`/posts/${id}`);
1564
+ if (p.status !== 'pending') {
1565
+ throw new Error(`Post ${id} is in "${p.status}" status. Only "pending" posts can be approved.`);
1566
+ }
1567
+ const up = await wpApiCall(`/posts/${id}`, { method: 'POST', body: JSON.stringify({ status: 'publish' }) });
1568
+ result = json({ success: true, message: `Post ${id} approved and published`, post: { id: up.id, title: up.title.rendered, status: up.status, link: up.link } });
1569
+ auditLog({ tool: name, target: id, target_type: 'post', action: 'approve', status: 'success', latency_ms: Date.now() - t0, params: { id } });
1570
+ break;
1571
+ }
1572
+
1573
+ case 'wp_reject_post': {
1574
+ validateInput(args, { id: { type: 'number', required: true, min: 1 }, reason: { type: 'string', required: true } });
1575
+ const { id, reason } = args;
1576
+ const p = await wpApiCall(`/posts/${id}`);
1577
+ if (p.status !== 'pending') {
1578
+ throw new Error(`Post ${id} is in "${p.status}" status. Only "pending" posts can be rejected.`);
1579
+ }
1580
+ const currentCount = parseInt(p.meta?._mcp_rejection_count || '0', 10);
1581
+ const up = await wpApiCall(`/posts/${id}`, { method: 'POST', body: JSON.stringify({ status: 'draft', meta: { _mcp_rejection_reason: reason, _mcp_rejection_count: currentCount + 1 } }) });
1582
+ result = json({ success: true, message: `Post ${id} rejected and moved to draft`, post: { id: up.id, title: up.title.rendered, status: up.status }, rejection: { reason, count: currentCount + 1 } });
1583
+ auditLog({ tool: name, target: id, target_type: 'post', action: 'reject', status: 'success', latency_ms: Date.now() - t0, params: { id } });
1584
+ break;
1585
+ }
1586
+
1587
+ // ── LINK ANALYSIS ──
1588
+
1589
+ case 'wp_analyze_links': {
1590
+ validateInput(args, { post_id: { type: 'number', required: true, min: 1 }, timeout_ms: { type: 'number', min: 100 } });
1591
+ const { post_id, check_broken = true, timeout_ms = 5000 } = args;
1592
+ const p = await wpApiCall(`/posts/${post_id}`);
1593
+ const content = p.content?.rendered || '';
1594
+ const postTitle = strip(p.title?.rendered || '');
1595
+ const { url: siteUrl } = getActiveAuth();
1596
+ const internal_links = extractInternalLinks(content, siteUrl);
1597
+ const external_links = extractExternalLinks(content, siteUrl);
1598
+ let broken_count = 0, warning_count = 0, unknown_count = 0;
1599
+ if (check_broken) {
1600
+ const toCheck = internal_links.slice(0, 20);
1601
+ for (const link of toCheck) {
1602
+ const fullUrl = link.url.startsWith('/') ? `${siteUrl}${link.url}` : link.url;
1603
+ const { status, http_code } = await checkLinkStatus(fullUrl, timeout_ms);
1604
+ link.status = status;
1605
+ link.http_code = http_code;
1606
+ if (status === 'broken') broken_count++;
1607
+ else if (status === 'warning') warning_count++;
1608
+ else if (status === 'unknown') unknown_count++;
1609
+ }
1610
+ for (let i = 20; i < internal_links.length; i++) {
1611
+ internal_links[i].status = 'unchecked';
1612
+ internal_links[i].http_code = null;
1613
+ }
1614
+ } else {
1615
+ for (const link of internal_links) { link.status = 'unchecked'; link.http_code = null; }
1616
+ }
1617
+ result = json({
1618
+ post_id, post_title: postTitle, internal_links, external_links,
1619
+ summary: { total_internal: internal_links.length, total_external: external_links.length, broken_count, warning_count, unknown_count }
1620
+ });
1621
+ auditLog({ tool: name, target: post_id, target_type: 'post', action: 'analyze_links', status: 'success', latency_ms: Date.now() - t0 });
1622
+ break;
1623
+ }
1624
+
1625
+ case 'wp_suggest_internal_links': {
1626
+ validateInput(args, { post_id: { type: 'number', required: true, min: 1 }, max_suggestions: { type: 'number', min: 1, max: 10 } });
1627
+ const { post_id, max_suggestions = 5, focus_keywords = [], exclude_already_linked = true } = args;
1628
+ const p = await wpApiCall(`/posts/${post_id}`);
1629
+ const content = p.content?.rendered || '';
1630
+ const postTitle = strip(p.title?.rendered || '');
1631
+ const postMeta = p.meta || {};
1632
+ const postCategories = p.categories || [];
1633
+ const { url: siteUrl } = getActiveAuth();
1634
+
1635
+ // Step 1 — Collect keywords
1636
+ const seoKeyword = extractFocusKeyword(postMeta);
1637
+ let keywords = [...(Array.isArray(focus_keywords) ? focus_keywords : [])];
1638
+ if (seoKeyword) keywords.unshift(seoKeyword);
1639
+ keywords = [...new Set(keywords.map(k => k.toLowerCase()))];
1640
+ if (keywords.length === 0) {
1641
+ keywords = postTitle.split(/\s+/).slice(0, 5).filter(w => w.length > 2).map(w => w.toLowerCase());
1642
+ }
1643
+
1644
+ // Already-linked URLs
1645
+ const linkedUrls = siteUrl ? extractInternalLinks(content, siteUrl).map(l => l.url) : [];
1646
+
1647
+ // Step 2 — Search for candidates (max 3 keyword searches)
1648
+ const candidateMap = new Map();
1649
+ for (const kw of keywords.slice(0, 3)) {
1650
+ try {
1651
+ const results = await wpApiCall(`/posts?search=${encodeURIComponent(kw)}&per_page=10&status=publish`);
1652
+ if (Array.isArray(results)) {
1653
+ for (const r of results) {
1654
+ if (r.id !== post_id && !candidateMap.has(r.id)) candidateMap.set(r.id, r);
1655
+ }
1656
+ }
1657
+ } catch { /* search failed */ }
1658
+ }
1659
+
1660
+ // Step 3 — Score each candidate
1661
+ const currentPostData = { id: post_id, categories: postCategories, linkedUrls: exclude_already_linked ? linkedUrls : [] };
1662
+ const scored = [];
1663
+ let excluded_count = 0;
1664
+
1665
+ for (const [, cand] of candidateMap) {
1666
+ const candTitle = typeof cand.title === 'string' ? cand.title : (cand.title?.rendered || '');
1667
+ const { total, breakdown } = calculateRelevanceScore(
1668
+ { id: cand.id, title: candTitle, date: cand.date, categories: cand.categories || [], meta: cand.meta || {}, link: cand.link || '' },
1669
+ currentPostData, keywords
1670
+ );
1671
+ if (total === -999) { excluded_count++; continue; }
1672
+ scored.push({
1673
+ target_post_id: cand.id, target_title: strip(candTitle), target_url: cand.link || '',
1674
+ anchor_text: suggestAnchorText({ meta: cand.meta || {}, title: candTitle }),
1675
+ relevance_score: total, score_breakdown: breakdown,
1676
+ already_linked: linkedUrls.some(u => u === cand.link)
1677
+ });
1678
+ }
1679
+
1680
+ scored.sort((a, b) => b.relevance_score - a.relevance_score);
1681
+ const suggestions = scored.slice(0, Math.min(max_suggestions, 10));
1682
+ result = json({ post_id, post_title: postTitle, keywords_used: keywords, suggestions, excluded_already_linked: excluded_count });
1683
+ auditLog({ tool: name, target: post_id, target_type: 'post', action: 'suggest_links', status: 'success', latency_ms: Date.now() - t0 });
1684
+ break;
1685
+ }
1686
+
1687
+ // ── WOOCOMMERCE ──
1688
+
1689
+ case 'wc_list_products': {
1690
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 } });
1691
+ const { per_page = 10, page = 1, status = 'any', search, category, orderby = 'date', order = 'desc' } = args;
1692
+ const { url: baseUrl } = getActiveAuth();
1693
+ let ep = `/products?per_page=${per_page}&page=${page}&orderby=${orderby}&order=${order}`;
1694
+ if (status && status !== 'any') ep += `&status=${status}`;
1695
+ if (search) ep += `&search=${encodeURIComponent(search)}`;
1696
+ if (category) ep += `&category=${category}`;
1697
+ const products = await wcApiCall(ep, {}, baseUrl);
1698
+ result = json({ total: products.length, page, products: products.map(p => ({ id: p.id, name: p.name, slug: p.slug, status: p.status, price: p.price, regular_price: p.regular_price, sale_price: p.sale_price, stock_status: p.stock_status, stock_quantity: p.stock_quantity, categories: (p.categories || []).map(c => ({ id: c.id, name: c.name })), image: p.images?.[0]?.src || null, permalink: p.permalink })) });
1699
+ auditLog({ tool: name, action: 'list', target_type: 'product', status: 'success', latency_ms: Date.now() - t0, params: sanitizeParams(args) });
1700
+ break;
1701
+ }
1702
+
1703
+ case 'wc_get_product': {
1704
+ validateInput(args, { id: { type: 'number', required: true, min: 1 } });
1705
+ const { url: baseUrl } = getActiveAuth();
1706
+ const p = await wcApiCall(`/products/${args.id}`, {}, baseUrl);
1707
+ const productData = { ...p };
1708
+ if (p.type === 'variable' && p.variations && p.variations.length > 0) {
1709
+ try {
1710
+ const vars = await wcApiCall(`/products/${args.id}/variations?per_page=100`, {}, baseUrl);
1711
+ productData.variations_detail = vars.map(v => ({ id: v.id, sku: v.sku, price: v.price, regular_price: v.regular_price, sale_price: v.sale_price, stock_status: v.stock_status, stock_quantity: v.stock_quantity, attributes: v.attributes }));
1712
+ } catch { productData.variations_detail = []; }
1713
+ }
1714
+ result = json(productData);
1715
+ auditLog({ tool: name, target: args.id, target_type: 'product', action: 'read', status: 'success', latency_ms: Date.now() - t0 });
1716
+ break;
1717
+ }
1718
+
1719
+ case 'wc_list_orders': {
1720
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 } });
1721
+ const { per_page = 10, page = 1, status = 'any', customer, orderby = 'date', order = 'desc' } = args;
1722
+ const { url: baseUrl } = getActiveAuth();
1723
+ let ep = `/orders?per_page=${per_page}&page=${page}&orderby=${orderby}&order=${order}`;
1724
+ if (status && status !== 'any') ep += `&status=${status}`;
1725
+ if (customer) ep += `&customer=${customer}`;
1726
+ const orders = await wcApiCall(ep, {}, baseUrl);
1727
+ result = json({ total: orders.length, page, orders: orders.map(o => ({ id: o.id, number: o.number, status: o.status, date_created: o.date_created, customer_id: o.customer_id, billing_name: `${o.billing?.first_name || ''} ${o.billing?.last_name || ''}`.trim(), billing_email: o.billing?.email || '', total: o.total, currency: o.currency, line_items: (o.line_items || []).map(li => ({ name: li.name, quantity: li.quantity, total: li.total })) })) });
1728
+ auditLog({ tool: name, action: 'list', target_type: 'order', status: 'success', latency_ms: Date.now() - t0, params: sanitizeParams(args) });
1729
+ break;
1730
+ }
1731
+
1732
+ case 'wc_get_order': {
1733
+ validateInput(args, { id: { type: 'number', required: true, min: 1 } });
1734
+ const { url: baseUrl } = getActiveAuth();
1735
+ const o = await wcApiCall(`/orders/${args.id}`, {}, baseUrl);
1736
+ result = json(o);
1737
+ auditLog({ tool: name, target: args.id, target_type: 'order', action: 'read', status: 'success', latency_ms: Date.now() - t0 });
1738
+ break;
1739
+ }
1740
+
1741
+ case 'wc_list_customers': {
1742
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 } });
1743
+ const { per_page = 10, page = 1, search, orderby = 'date_created', order = 'desc', role = 'customer' } = args;
1744
+ const { url: baseUrl } = getActiveAuth();
1745
+ let ep = `/customers?per_page=${per_page}&page=${page}&orderby=${orderby}&order=${order}&role=${role}`;
1746
+ if (search) ep += `&search=${encodeURIComponent(search)}`;
1747
+ const customers = await wcApiCall(ep, {}, baseUrl);
1748
+ result = json({ total: customers.length, page, customers: customers.map(c => ({ id: c.id, first_name: c.first_name, last_name: c.last_name, email: c.email, date_created: c.date_created, orders_count: c.orders_count, total_spent: c.total_spent, username: c.username })) });
1749
+ auditLog({ tool: name, action: 'list', target_type: 'customer', status: 'success', latency_ms: Date.now() - t0, params: sanitizeParams(args) });
1750
+ break;
1751
+ }
1752
+
1753
+ case 'wc_price_guardrail': {
1754
+ validateInput(args, { product_id: { type: 'number', required: true, min: 1 }, new_price: { type: 'number', required: true }, threshold_percent: { type: 'number', min: 0 } });
1755
+ const { product_id, new_price, threshold_percent = 20 } = args;
1756
+ const { url: baseUrl } = getActiveAuth();
1757
+ const p = await wcApiCall(`/products/${product_id}`, {}, baseUrl);
1758
+ const current_price = parseFloat(p.price);
1759
+ if (isNaN(current_price) || current_price <= 0) {
1760
+ result = json({ safe: false, product_id, product_name: p.name, current_price: p.price, new_price, change_percent: null, message: 'Cannot evaluate: current price is zero or invalid' });
1761
+ auditLog({ tool: name, target: product_id, target_type: 'product', action: 'price_check', status: 'success', latency_ms: Date.now() - t0, params: { new_price, threshold_percent } });
1762
+ break;
1763
+ }
1764
+ const change_percent = Math.round(Math.abs(new_price - current_price) / current_price * 10000) / 100;
1765
+ const safe = change_percent <= threshold_percent;
1766
+ result = json({
1767
+ safe, product_id, product_name: p.name, current_price, new_price, change_percent,
1768
+ ...(safe
1769
+ ? { message: 'Price change within threshold' }
1770
+ : { requires_confirmation: true, message: `Price change of ${change_percent}% exceeds threshold of ${threshold_percent}%. Use wp_update_product with confirm=true to proceed.` })
1771
+ });
1772
+ auditLog({ tool: name, target: product_id, target_type: 'product', action: 'price_check', status: 'success', latency_ms: Date.now() - t0, params: { current_price, new_price, change_percent, threshold_percent, safe } });
1773
+ break;
1774
+ }
1775
+
1776
+ // ── WOOCOMMERCE INTELLIGENCE ──
1777
+
1778
+ case 'wc_inventory_alert': {
1779
+ validateInput(args, { threshold: { type: 'number', min: 0 }, per_page: { type: 'number', min: 1, max: 100 } });
1780
+ const { threshold = 5, per_page = 50, include_out_of_stock = true } = args;
1781
+ const { url: baseUrl } = getActiveAuth();
1782
+ const fetchSize = Math.min(per_page * 2, 100);
1783
+ let allProducts = [];
1784
+ const instock = await wcApiCall(`/products?stock_status=instock&per_page=${fetchSize}`, {}, baseUrl);
1785
+ allProducts.push(...instock);
1786
+ if (include_out_of_stock) {
1787
+ const oos = await wcApiCall(`/products?stock_status=outofstock&per_page=${fetchSize}`, {}, baseUrl);
1788
+ allProducts.push(...oos);
1789
+ }
1790
+ const alerts = allProducts.filter(p => {
1791
+ if (p.stock_status === 'outofstock') return true;
1792
+ if (p.stock_quantity !== null && p.stock_quantity !== undefined && p.stock_quantity <= threshold) return true;
1793
+ return false;
1794
+ });
1795
+ alerts.sort((a, b) => (a.stock_quantity ?? -1) - (b.stock_quantity ?? -1));
1796
+ const out_of_stock_count = alerts.filter(p => p.stock_status === 'outofstock').length;
1797
+ const low_stock_count = alerts.length - out_of_stock_count;
1798
+ result = json({
1799
+ products: alerts.map(p => ({ id: p.id, name: p.name, sku: p.sku || '', stock_quantity: p.stock_quantity, stock_status: p.stock_status, price: p.price, permalink: p.permalink })),
1800
+ summary: { total_alerts: alerts.length, out_of_stock_count, low_stock_count, threshold_used: threshold }
1801
+ });
1802
+ auditLog({ tool: name, action: 'inventory_alert', target_type: 'product', status: 'success', latency_ms: Date.now() - t0, params: { threshold, include_out_of_stock } });
1803
+ break;
1804
+ }
1805
+
1806
+ case 'wc_order_intelligence': {
1807
+ validateInput(args, { customer_id: { type: 'number', required: true, min: 1 } });
1808
+ const { customer_id } = args;
1809
+ const { url: baseUrl } = getActiveAuth();
1810
+ const orders = await wcApiCall(`/orders?customer=${customer_id}&per_page=100&orderby=date&order=desc`, {}, baseUrl);
1811
+ const total_orders = orders.length;
1812
+ if (total_orders === 0) {
1813
+ result = json({ customer_id, total_orders: 0, total_spent: 0, average_order_value: 0, first_order_date: null, last_order_date: null, order_frequency_days: null, favourite_products: [], statuses_breakdown: {}, recent_orders: [] });
1814
+ auditLog({ tool: name, target: customer_id, target_type: 'customer', action: 'order_intelligence', status: 'success', latency_ms: Date.now() - t0 });
1815
+ break;
1816
+ }
1817
+ const total_spent = Math.round(orders.reduce((sum, o) => sum + parseFloat(o.total || '0'), 0) * 100) / 100;
1818
+ const average_order_value = Math.round(total_spent / total_orders * 100) / 100;
1819
+ const last_order_date = orders[0].date_created;
1820
+ const first_order_date = orders[orders.length - 1].date_created;
1821
+ let order_frequency_days = null;
1822
+ if (total_orders > 1) {
1823
+ const firstMs = new Date(first_order_date).getTime();
1824
+ const lastMs = new Date(last_order_date).getTime();
1825
+ order_frequency_days = Math.round((lastMs - firstMs) / (1000 * 60 * 60 * 24) / total_orders);
1826
+ }
1827
+ const productFreq = {};
1828
+ for (const o of orders) {
1829
+ for (const li of (o.line_items || [])) {
1830
+ productFreq[li.name] = (productFreq[li.name] || 0) + li.quantity;
1831
+ }
1832
+ }
1833
+ const favourite_products = Object.entries(productFreq).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([pname, quantity]) => ({ name: pname, quantity }));
1834
+ const statuses_breakdown = {};
1835
+ for (const o of orders) { statuses_breakdown[o.status] = (statuses_breakdown[o.status] || 0) + 1; }
1836
+ const recent_orders = orders.slice(0, 5).map(o => ({ id: o.id, date: o.date_created, total: o.total, status: o.status }));
1837
+ result = json({ customer_id, total_orders, total_spent, average_order_value, first_order_date, last_order_date, order_frequency_days, favourite_products, statuses_breakdown, recent_orders });
1838
+ auditLog({ tool: name, target: customer_id, target_type: 'customer', action: 'order_intelligence', status: 'success', latency_ms: Date.now() - t0 });
1839
+ break;
1840
+ }
1841
+
1842
+ case 'wc_seo_product_audit': {
1843
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 } });
1844
+ const { per_page = 20, page = 1 } = args;
1845
+ const { url: baseUrl } = getActiveAuth();
1846
+ const products = await wcApiCall(`/products?per_page=${per_page}&page=${page}&status=publish`, {}, baseUrl);
1847
+ let totalScore = 0;
1848
+ const audited = products.map(p => {
1849
+ const issues = [];
1850
+ const descText = strip(p.description || '');
1851
+ if (descText.length === 0) issues.push('missing_description');
1852
+ else if (descText.length < 50) issues.push('description_too_short');
1853
+ if (!p.short_description || strip(p.short_description).length === 0) issues.push('missing_short_description');
1854
+ if (p.slug && p.slug.includes('product-')) issues.push('generic_slug');
1855
+ if (!p.images || p.images.length === 0 || !p.images[0]?.src) issues.push('missing_image');
1856
+ else if (!p.images[0]?.alt || p.images[0].alt.trim() === '') issues.push('missing_image_alt');
1857
+ if (!p.price || p.price === '') issues.push('missing_price');
1858
+ const score = Math.max(0, 100 - issues.length * 15);
1859
+ totalScore += score;
1860
+ return { id: p.id, name: p.name, score, issues, permalink: p.permalink };
1861
+ });
1862
+ const average_score = audited.length > 0 ? Math.round(totalScore / audited.length) : 0;
1863
+ result = json({
1864
+ average_score, total_audited: audited.length, products: audited,
1865
+ summary: { perfect_score_count: audited.filter(p => p.score === 100).length, needs_attention_count: audited.filter(p => p.score < 70).length }
1866
+ });
1867
+ auditLog({ tool: name, action: 'seo_product_audit', target_type: 'product', status: 'success', latency_ms: Date.now() - t0, params: { per_page, page, avg_score: average_score } });
1868
+ break;
1869
+ }
1870
+
1871
+ case 'wc_suggest_product_links': {
1872
+ validateInput(args, { post_id: { type: 'number', required: true, min: 1 }, max_suggestions: { type: 'number', min: 1, max: 5 } });
1873
+ const { post_id, max_suggestions = 3 } = args;
1874
+ const { url: baseUrl } = getActiveAuth();
1875
+ const post = await wpApiCall(`/posts/${post_id}`);
1876
+ const postTitle = strip(post.title?.rendered || '');
1877
+ const postMeta = post.meta || {};
1878
+ const focusKw = extractFocusKeyword(postMeta);
1879
+ const keywords = [];
1880
+ if (focusKw) keywords.push(focusKw);
1881
+ const titleWords = postTitle.split(/\s+/).filter(w => w.length > 3).slice(0, 3);
1882
+ for (const w of titleWords) {
1883
+ if (!keywords.some(k => k.toLowerCase() === w.toLowerCase())) keywords.push(w);
1884
+ }
1885
+ const candidateMap = new Map();
1886
+ for (const kw of keywords.slice(0, 2)) {
1887
+ try {
1888
+ const prods = await wcApiCall(`/products?search=${encodeURIComponent(kw)}&per_page=10&status=publish`, {}, baseUrl);
1889
+ if (Array.isArray(prods)) {
1890
+ for (const p of prods) { if (!candidateMap.has(p.id)) candidateMap.set(p.id, p); }
1891
+ }
1892
+ } catch { /* search failed */ }
1893
+ }
1894
+ const scored = [];
1895
+ for (const [, p] of candidateMap) {
1896
+ let relevance_score = 0;
1897
+ const nameLower = (p.name || '').toLowerCase();
1898
+ const descLower = strip(p.description || '').toLowerCase();
1899
+ for (const kw of keywords) {
1900
+ const kwLower = kw.toLowerCase();
1901
+ if (nameLower.includes(kwLower)) relevance_score += 3;
1902
+ if (descLower.includes(kwLower)) relevance_score += 2;
1903
+ }
1904
+ if (p.stock_status === 'instock') relevance_score += 1;
1905
+ if (p.images && p.images.length > 0 && p.images[0]?.src) relevance_score += 1;
1906
+ scored.push({ product_id: p.id, product_name: p.name, product_url: p.permalink, anchor_text: (p.name || '').substring(0, 50), price: p.price, relevance_score, in_stock: p.stock_status === 'instock' });
1907
+ }
1908
+ scored.sort((a, b) => b.relevance_score - a.relevance_score);
1909
+ const suggestions = scored.slice(0, max_suggestions);
1910
+ result = json({ post_id, post_title: postTitle, keywords_used: keywords, suggestions });
1911
+ auditLog({ tool: name, target: post_id, target_type: 'post', action: 'suggest_product_links', status: 'success', latency_ms: Date.now() - t0, params: { post_id, suggestion_count: suggestions.length } });
1912
+ break;
1913
+ }
1914
+
1915
+ // ── WOOCOMMERCE WRITE ──
1916
+
1917
+ case 'wc_update_product': {
1918
+ validateInput(args, { id: { type: 'number', required: true, min: 1 }, status: { type: 'string', enum: ['publish', 'draft', 'private'] } });
1919
+ const { id, name: prodName, description, short_description, regular_price, sale_price, status: prodStatus, price_guardrail_confirmed = false } = args;
1920
+ const { url: baseUrl } = getActiveAuth();
1921
+
1922
+ // Price guardrail check
1923
+ if (regular_price !== undefined || sale_price !== undefined) {
1924
+ const current = await wcApiCall(`/products/${id}`, {}, baseUrl);
1925
+ const checks = [];
1926
+ if (regular_price !== undefined) checks.push({ label: 'regular_price', current: parseFloat(current.regular_price), proposed: parseFloat(regular_price) });
1927
+ if (sale_price !== undefined && sale_price !== '') checks.push({ label: 'sale_price', current: parseFloat(current.sale_price || '0'), proposed: parseFloat(sale_price) });
1928
+
1929
+ for (const chk of checks) {
1930
+ if (!isNaN(chk.current) && chk.current > 0) {
1931
+ const changePct = Math.round(Math.abs(chk.proposed - chk.current) / chk.current * 10000) / 100;
1932
+ if (changePct > 20 && !price_guardrail_confirmed) {
1933
+ auditLog({ tool: name, target: id, target_type: 'product', action: 'update_product', status: 'blocked', latency_ms: Date.now() - t0, params: sanitizeParams(args), error: 'PRICE_GUARDRAIL_TRIGGERED' });
1934
+ return { content: [{ type: 'text', text: JSON.stringify({ error: 'PRICE_GUARDRAIL_TRIGGERED', message: `Price change of ${changePct}% exceeds 20% threshold. Call wc_price_guardrail first, then retry with price_guardrail_confirmed: true`, current_price: chk.current, new_price: chk.proposed, change_percent: changePct }, null, 2) }], isError: true };
1935
+ }
1936
+ }
1937
+ }
1938
+ }
1939
+
1940
+ const updateData = {};
1941
+ if (prodName !== undefined) updateData.name = prodName;
1942
+ if (description !== undefined) updateData.description = description;
1943
+ if (short_description !== undefined) updateData.short_description = short_description;
1944
+ if (regular_price !== undefined) updateData.regular_price = regular_price;
1945
+ if (sale_price !== undefined) updateData.sale_price = sale_price;
1946
+ if (prodStatus !== undefined) updateData.status = prodStatus;
1947
+
1948
+ const updated = await wcApiCall(`/products/${id}`, { method: 'PUT', body: JSON.stringify(updateData) }, baseUrl);
1949
+ const auditParams = { id, ...updateData };
1950
+ if (regular_price !== undefined || sale_price !== undefined) auditParams.price_change = true;
1951
+ result = json({ success: true, message: `Product ${id} updated`, product: { id: updated.id, name: updated.name, status: updated.status, regular_price: updated.regular_price, sale_price: updated.sale_price, permalink: updated.permalink } });
1952
+ auditLog({ tool: name, target: id, target_type: 'product', action: 'update_product', status: 'success', latency_ms: Date.now() - t0, params: sanitizeParams(auditParams) });
1953
+ break;
1954
+ }
1955
+
1956
+ case 'wc_update_stock': {
1957
+ validateInput(args, { id: { type: 'number', required: true, min: 1 }, stock_quantity: { type: 'number', required: true, min: 0 }, variation_id: { type: 'number', min: 1 } });
1958
+ const { id, stock_quantity, variation_id } = args;
1959
+ const { url: baseUrl } = getActiveAuth();
1960
+
1961
+ // Fetch current product/variation for audit
1962
+ let previousStock;
1963
+ if (variation_id) {
1964
+ const currentVar = await wcApiCall(`/products/${id}/variations/${variation_id}`, {}, baseUrl);
1965
+ previousStock = currentVar.stock_quantity;
1966
+ await wcApiCall(`/products/${id}/variations/${variation_id}`, { method: 'PUT', body: JSON.stringify({ stock_quantity, manage_stock: true }) }, baseUrl);
1967
+ } else {
1968
+ const currentProd = await wcApiCall(`/products/${id}`, {}, baseUrl);
1969
+ previousStock = currentProd.stock_quantity;
1970
+ await wcApiCall(`/products/${id}`, { method: 'PUT', body: JSON.stringify({ stock_quantity, manage_stock: true }) }, baseUrl);
1971
+ }
1972
+
1973
+ result = json({ success: true, message: variation_id ? `Variation ${variation_id} stock updated` : `Product ${id} stock updated`, product_id: id, variation_id: variation_id || null, previous_stock: previousStock, new_stock: stock_quantity });
1974
+ auditLog({ tool: name, target: id, target_type: 'product', action: 'update_stock', status: 'success', latency_ms: Date.now() - t0, params: { id, variation_id: variation_id || null, previous_stock: previousStock, new_stock: stock_quantity } });
1975
+ break;
1976
+ }
1977
+
1978
+ case 'wc_update_order_status': {
1979
+ validateInput(args, { id: { type: 'number', required: true, min: 1 }, status: { type: 'string', required: true } });
1980
+ const { id, status: newStatus, note } = args;
1981
+ const { url: baseUrl } = getActiveAuth();
1982
+
1983
+ const VALID_TRANSITIONS = {
1984
+ 'pending': ['processing', 'cancelled', 'on-hold'],
1985
+ 'processing': ['completed', 'cancelled', 'refunded', 'on-hold'],
1986
+ 'on-hold': ['processing', 'cancelled'],
1987
+ 'completed': ['refunded'],
1988
+ 'cancelled': [],
1989
+ 'refunded': [],
1990
+ 'failed': ['processing', 'cancelled']
1991
+ };
1992
+
1993
+ const order = await wcApiCall(`/orders/${id}`, {}, baseUrl);
1994
+ const currentStatus = order.status;
1995
+ const validNext = VALID_TRANSITIONS[currentStatus];
1996
+
1997
+ if (validNext === undefined) {
1998
+ auditLog({ tool: name, target: id, target_type: 'order', action: 'update_order_status', status: 'error', latency_ms: Date.now() - t0, params: { current_status: currentStatus, requested_status: newStatus }, error: 'UNKNOWN_STATUS' });
1999
+ return { content: [{ type: 'text', text: JSON.stringify({ error: 'UNKNOWN_STATUS', current_status: currentStatus, requested_status: newStatus, message: `Unknown current status "${currentStatus}"` }, null, 2) }], isError: true };
2000
+ }
2001
+
2002
+ if (!validNext.includes(newStatus)) {
2003
+ auditLog({ tool: name, target: id, target_type: 'order', action: 'update_order_status', status: 'error', latency_ms: Date.now() - t0, params: { current_status: currentStatus, requested_status: newStatus }, error: 'INVALID_TRANSITION' });
2004
+ return { content: [{ type: 'text', text: JSON.stringify({ error: 'INVALID_TRANSITION', current_status: currentStatus, requested_status: newStatus, valid_transitions: validNext, message: validNext.length === 0 ? `Order status "${currentStatus}" is terminal — no transitions allowed` : `Cannot transition from "${currentStatus}" to "${newStatus}". Valid: ${validNext.join(', ')}` }, null, 2) }], isError: true };
2005
+ }
2006
+
2007
+ await wcApiCall(`/orders/${id}`, { method: 'PUT', body: JSON.stringify({ status: newStatus }) }, baseUrl);
2008
+
2009
+ let noteAdded = false;
2010
+ if (note) {
2011
+ await wcApiCall(`/orders/${id}/notes`, { method: 'POST', body: JSON.stringify({ note, customer_note: false }) }, baseUrl);
2012
+ noteAdded = true;
2013
+ }
2014
+
2015
+ result = json({ success: true, message: `Order ${id} status updated: ${currentStatus} → ${newStatus}`, order_id: id, previous_status: currentStatus, new_status: newStatus, note_added: noteAdded });
2016
+ auditLog({ tool: name, target: id, target_type: 'order', action: 'update_order_status', status: 'success', latency_ms: Date.now() - t0, params: { previous_status: currentStatus, new_status: newStatus, note_added: noteAdded } });
2017
+ break;
2018
+ }
2019
+
2020
+ // ── SEO ADVANCED ──
2021
+
2022
+ case 'wp_audit_media_seo': {
2023
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, page: { type: 'number', min: 1 }, post_id: { type: 'number', min: 1 } });
2024
+ const { per_page = 50, page = 1, post_id } = args;
2025
+ const mediaItems = await wpApiCall(`/media?per_page=${Math.min(per_page, 100)}&page=${page}&media_type=image`);
2026
+
2027
+ const audit = [];
2028
+ let totalScore = 0;
2029
+ for (const m of mediaItems) {
2030
+ const item = { id: m.id, title: m.title?.rendered || '', source_url: m.source_url || '', alt_text: m.alt_text || '', issues: [], score: 100 };
2031
+ if (!item.alt_text) {
2032
+ item.issues.push('missing_alt'); item.score -= 40;
2033
+ } else {
2034
+ const filename = (m.source_url || '').split('/').pop()?.split('.')[0]?.replace(/[-_]/g, ' ') || '';
2035
+ if (filename && item.alt_text.toLowerCase().replace(/[-_]/g, ' ') === filename.toLowerCase()) {
2036
+ item.issues.push('filename_as_alt'); item.score -= 20;
2037
+ }
2038
+ if (item.alt_text.length < 5) { item.issues.push('alt_too_short'); item.score -= 15; }
2039
+ }
2040
+ if (item.score < 0) item.score = 0;
2041
+ totalScore += item.score;
2042
+ audit.push(item);
2043
+ }
2044
+
2045
+ let inlineImages = [];
2046
+ if (post_id) {
2047
+ const p = await wpApiCall(`/posts/${post_id}`);
2048
+ inlineImages = parseImagesFromHtml(p.content?.rendered || '');
2049
+ }
2050
+
2051
+ const avgScore = audit.length > 0 ? Math.round(totalScore / audit.length) : 0;
2052
+ result = json({
2053
+ summary: {
2054
+ total_audited: audit.length, average_score: avgScore,
2055
+ issues_breakdown: {
2056
+ missing_alt: audit.filter(a => a.issues.includes('missing_alt')).length,
2057
+ filename_as_alt: audit.filter(a => a.issues.includes('filename_as_alt')).length,
2058
+ alt_too_short: audit.filter(a => a.issues.includes('alt_too_short')).length,
2059
+ }
2060
+ },
2061
+ media: audit,
2062
+ inline_images: inlineImages
2063
+ });
2064
+ auditLog({ tool: name, action: 'audit_media_seo', status: 'success', latency_ms: Date.now() - t0, params: { count: audit.length, avg_score: avgScore } });
2065
+ break;
2066
+ }
2067
+
2068
+ case 'wp_find_orphan_pages': {
2069
+ validateInput(args, { per_page: { type: 'number', min: 1, max: 100 }, min_words: { type: 'number', min: 0 } });
2070
+ const { per_page = 100, exclude_ids = [], min_words = 0 } = args;
2071
+ const allPages = await wpApiCall(`/pages?per_page=${Math.min(per_page, 100)}&status=publish`);
2072
+ const { url: siteUrl } = getActiveAuth();
2073
+
2074
+ // Build set of linked page permalinks
2075
+ const linkedPermalinks = new Set();
2076
+ for (const pg of allPages) {
2077
+ const content = pg.content?.rendered || '';
2078
+ const links = extractInternalLinksHtml(content, siteUrl);
2079
+ for (const link of links) {
2080
+ // Normalise trailing slash for comparison
2081
+ linkedPermalinks.add(link.replace(/\/+$/, ''));
2082
+ }
2083
+ }
2084
+
2085
+ // Find orphans: pages whose permalink is NOT in linkedPermalinks
2086
+ const excludeSet = new Set(Array.isArray(exclude_ids) ? exclude_ids : []);
2087
+ const orphans = allPages.filter(pg => {
2088
+ if (excludeSet.has(pg.id)) return false;
2089
+ const normLink = (pg.link || '').replace(/\/+$/, '');
2090
+ if (linkedPermalinks.has(normLink)) return false;
2091
+ const wc = countWords(pg.content?.rendered || '');
2092
+ if (wc < min_words) return false;
2093
+ return true;
2094
+ });
2095
+
2096
+ // Sort by word count descending
2097
+ orphans.sort((a, b) => countWords(b.content?.rendered || '') - countWords(a.content?.rendered || ''));
2098
+
2099
+ result = json({
2100
+ total_pages: allPages.length, total_orphans: orphans.length,
2101
+ orphans: orphans.map(pg => ({
2102
+ id: pg.id, title: strip(pg.title?.rendered || ''), slug: pg.slug, link: pg.link,
2103
+ word_count: countWords(pg.content?.rendered || ''), status: pg.status
2104
+ }))
2105
+ });
2106
+ auditLog({ tool: name, action: 'find_orphan_pages', status: 'success', latency_ms: Date.now() - t0, params: { total: allPages.length, orphans: orphans.length } });
2107
+ break;
2108
+ }
2109
+
2110
+ case 'wp_audit_heading_structure': {
2111
+ validateInput(args, { id: { type: 'number', required: true, min: 1 } });
2112
+ const { id, post_type = 'post', focus_keyword } = args;
2113
+ const ep = post_type === 'page' ? `/pages/${id}` : `/posts/${id}`;
2114
+ const p = await wpApiCall(ep);
2115
+ const content = p.content?.rendered || '';
2116
+ const postTitle = strip(p.title?.rendered || '');
2117
+
2118
+ const headings = extractHeadings(content);
2119
+ const issues = [];
2120
+ let score = 100;
2121
+
2122
+ // H1 in content
2123
+ const h1s = headings.filter(h => h.level === 1);
2124
+ if (h1s.length > 0) {
2125
+ issues.push({ type: 'h1_in_content', count: h1s.length, message: 'H1 tag found in content — the post title already provides the H1' });
2126
+ score -= 20;
2127
+ }
2128
+
2129
+ // Heading level skips
2130
+ for (let i = 1; i < headings.length; i++) {
2131
+ if (headings[i].level > headings[i - 1].level + 1) {
2132
+ issues.push({ type: 'heading_skip', from: `H${headings[i - 1].level}`, to: `H${headings[i].level}`, message: `Heading level skip: H${headings[i - 1].level} → H${headings[i].level}` });
2133
+ score -= 10;
2134
+ }
2135
+ }
2136
+
2137
+ // Empty headings
2138
+ const emptyHeadings = headings.filter(h => !h.text);
2139
+ if (emptyHeadings.length > 0) {
2140
+ issues.push({ type: 'empty_heading', count: emptyHeadings.length, message: `${emptyHeadings.length} empty heading(s) found` });
2141
+ score -= 10 * emptyHeadings.length;
2142
+ }
2143
+
2144
+ // No H2
2145
+ const h2s = headings.filter(h => h.level === 2);
2146
+ if (h2s.length === 0 && headings.length > 0) {
2147
+ issues.push({ type: 'no_h2', message: 'No H2 headings found — content should use H2 for main sections' });
2148
+ score -= 15;
2149
+ }
2150
+
2151
+ // Keyword checks
2152
+ if (focus_keyword && h2s.length > 0) {
2153
+ const kwLower = focus_keyword.toLowerCase();
2154
+ const h2WithKw = h2s.filter(h => h.text.toLowerCase().includes(kwLower));
2155
+ if (h2WithKw.length === 0) {
2156
+ issues.push({ type: 'keyword_absent_h2', message: `Focus keyword "${focus_keyword}" not found in any H2 heading` });
2157
+ score -= 10;
2158
+ }
2159
+ if (h2s.length >= 3 && h2WithKw.length / h2s.length > 0.5) {
2160
+ issues.push({ type: 'keyword_stuffing', count: h2WithKw.length, total_h2: h2s.length, message: `Keyword "${focus_keyword}" appears in ${h2WithKw.length}/${h2s.length} H2 headings (>50%)` });
2161
+ score -= 15;
2162
+ }
2163
+ }
2164
+
2165
+ if (score < 0) score = 0;
2166
+
2167
+ result = json({
2168
+ post_id: id, post_title: postTitle, headings, issues, score,
2169
+ summary: {
2170
+ total_headings: headings.length,
2171
+ h1_count: h1s.length, h2_count: h2s.length,
2172
+ h3_count: headings.filter(h => h.level === 3).length,
2173
+ h4_count: headings.filter(h => h.level === 4).length,
2174
+ h5_count: headings.filter(h => h.level === 5).length,
2175
+ h6_count: headings.filter(h => h.level === 6).length,
2176
+ }
2177
+ });
2178
+ auditLog({ tool: name, target: id, target_type: post_type, action: 'audit_heading_structure', status: 'success', latency_ms: Date.now() - t0, params: { headings_count: headings.length, issues_count: issues.length, score } });
2179
+ break;
2180
+ }
2181
+
2182
+ // ── SEO ADVANCED v4.1 ──
2183
+
2184
+ case 'wp_find_thin_content': {
2185
+ validateInput(args, {
2186
+ limit: { type: 'number', min: 1, max: 500 },
2187
+ min_words: { type: 'number', min: 1 },
2188
+ critical_words: { type: 'number', min: 1 },
2189
+ max_age_days: { type: 'number', min: 1 },
2190
+ include_uncategorized: { type: 'string' },
2191
+ post_type: { type: 'string', enum: ['post', 'page'] }
2192
+ });
2193
+ const { limit = 100, min_words = 300, critical_words = 150, max_age_days = 730, include_uncategorized = true, post_type = 'post' } = args;
2194
+ const endpoint = post_type === 'page' ? '/pages' : '/posts';
2195
+ const items = await wpApiCall(`${endpoint}?per_page=${Math.min(limit, 100)}&status=publish&_fields=id,title,link,content,modified,date,categories`);
2196
+
2197
+ const now = new Date();
2198
+ const articles = [];
2199
+ for (const item of items) {
2200
+ const wc = countWords(item.content?.rendered || '');
2201
+ const modified = new Date(item.modified);
2202
+ const daysSinceUpdate = Math.floor((now - modified) / (1000 * 60 * 60 * 24));
2203
+
2204
+ const signals = [];
2205
+ if (wc < critical_words) signals.push('very_short');
2206
+ else if (wc < min_words) signals.push('too_short');
2207
+ if (daysSinceUpdate > max_age_days) signals.push('outdated');
2208
+ if (include_uncategorized) {
2209
+ const cats = item.categories || [];
2210
+ if (cats.length === 0 || (cats.length === 1 && cats[0] === 1)) signals.push('uncategorized');
2211
+ }
2212
+
2213
+ if (signals.length === 0) continue;
2214
+
2215
+ let severity = 'medium';
2216
+ if (signals.length >= 3) severity = 'critical';
2217
+ else if (signals.length >= 2) severity = 'high';
2218
+
2219
+ let suggested_action = 'review';
2220
+ if (signals.includes('very_short') && signals.includes('outdated')) suggested_action = 'delete';
2221
+ else if (signals.includes('too_short') || signals.includes('very_short')) suggested_action = 'expand';
2222
+ else if (signals.includes('outdated') && !signals.includes('too_short') && !signals.includes('very_short')) suggested_action = 'update_or_merge';
2223
+
2224
+ articles.push({
2225
+ id: item.id, title: strip(item.title?.rendered || ''), link: item.link || '',
2226
+ word_count: wc, days_since_update: daysSinceUpdate,
2227
+ signals, severity, suggested_action
2228
+ });
2229
+ }
2230
+
2231
+ // Sort: severity DESC (critical > high > medium), then word_count ASC
2232
+ const sevOrder = { critical: 0, high: 1, medium: 2 };
2233
+ articles.sort((a, b) => (sevOrder[a.severity] - sevOrder[b.severity]) || (a.word_count - b.word_count));
2234
+
2235
+ const bySev = { critical: 0, high: 0, medium: 0 };
2236
+ for (const a of articles) bySev[a.severity]++;
2237
+
2238
+ result = json({ total_analyzed: items.length, total_thin: articles.length, by_severity: bySev, articles });
2239
+ auditLog({ tool: name, action: 'audit_seo', target_type: post_type, status: 'success', latency_ms: Date.now() - t0, params: { total_analyzed: items.length, total_thin: articles.length } });
2240
+ break;
2241
+ }
2242
+
2243
+ case 'wp_audit_canonicals': {
2244
+ validateInput(args, {
2245
+ limit: { type: 'number', min: 1, max: 200 },
2246
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] },
2247
+ check_staging_patterns: { type: 'string' }
2248
+ });
2249
+ const { limit = 50, post_type = 'post', check_staging_patterns = true } = args;
2250
+
2251
+ // Fetch posts (and/or pages)
2252
+ let allPosts = [];
2253
+ const fieldsList = 'id,title,link,meta';
2254
+ if (post_type === 'both' || post_type === 'post') {
2255
+ const posts = await wpApiCall(`/posts?per_page=${Math.min(limit, 100)}&status=publish&_fields=${fieldsList}`);
2256
+ allPosts = allPosts.concat(posts);
2257
+ }
2258
+ if (post_type === 'both' || post_type === 'page') {
2259
+ const pages = await wpApiCall(`/pages?per_page=${Math.min(limit, 100)}&status=publish&_fields=${fieldsList}`);
2260
+ allPosts = allPosts.concat(pages);
2261
+ }
2262
+
2263
+ // Detect site URL from auth
2264
+ const { url: siteUrl } = getActiveAuth();
2265
+ let siteHost = '';
2266
+ let siteProtocol = 'https:';
2267
+ try {
2268
+ const parsed = new URL(siteUrl);
2269
+ siteHost = parsed.host;
2270
+ siteProtocol = parsed.protocol;
2271
+ } catch { /* fallback */ }
2272
+
2273
+ // Detect SEO plugin from meta keys
2274
+ let seoPluginDetected = 'none';
2275
+ const seoCanonicalKeys = {
2276
+ rank_math_canonical_url: 'RankMath',
2277
+ _yoast_wpseo_canonical: 'Yoast',
2278
+ _seopress_robots_canonical: 'SEOPress',
2279
+ _aioseo_og_title: 'AIOSEO'
2280
+ };
2281
+
2282
+ for (const p of allPosts) {
2283
+ const meta = p.meta || {};
2284
+ for (const [key, plugin] of Object.entries(seoCanonicalKeys)) {
2285
+ if (meta[key] !== undefined && meta[key] !== '' && meta[key] !== null) {
2286
+ seoPluginDetected = plugin;
2287
+ break;
2288
+ }
2289
+ }
2290
+ if (seoPluginDetected !== 'none') break;
2291
+ }
2292
+
2293
+ // Get canonical field name
2294
+ const canonicalKey = Object.keys(seoCanonicalKeys).find(k => {
2295
+ return allPosts.some(p => p.meta && p.meta[k] !== undefined);
2296
+ }) || '';
2297
+
2298
+ const stagingPatterns = ['staging', 'dev', 'local', 'preprod', 'test', 'localhost'];
2299
+ const audits = [];
2300
+ const issuesByType = { missing_canonical: 0, http_on_https_site: 0, staging_url: 0, wrong_domain: 0, trailing_slash_mismatch: 0 };
2301
+
2302
+ for (const p of allPosts) {
2303
+ const meta = p.meta || {};
2304
+ const postUrl = p.link || '';
2305
+ const canonical = (canonicalKey && meta[canonicalKey]) ? String(meta[canonicalKey]) : '';
2306
+ const postIssues = [];
2307
+
2308
+ if (!canonical) {
2309
+ postIssues.push('missing_canonical');
2310
+ issuesByType.missing_canonical++;
2311
+ } else {
2312
+ // HTTP on HTTPS site
2313
+ if (siteProtocol === 'https:' && canonical.startsWith('http://')) {
2314
+ postIssues.push('http_on_https_site');
2315
+ issuesByType.http_on_https_site++;
2316
+ }
2317
+ // Staging URL
2318
+ if (check_staging_patterns) {
2319
+ let canonHostLower = '';
2320
+ try { canonHostLower = new URL(canonical).hostname.toLowerCase(); } catch { /* skip */ }
2321
+ if (canonHostLower && stagingPatterns.some(pat => canonHostLower.includes(pat))) {
2322
+ postIssues.push('staging_url');
2323
+ issuesByType.staging_url++;
2324
+ }
2325
+ }
2326
+ // Wrong domain
2327
+ try {
2328
+ const canonHost = new URL(canonical).host;
2329
+ if (siteHost && canonHost !== siteHost) {
2330
+ postIssues.push('wrong_domain');
2331
+ issuesByType.wrong_domain++;
2332
+ }
2333
+ } catch { /* skip invalid canonical URL */ }
2334
+ // Trailing slash mismatch
2335
+ if (postUrl && canonical) {
2336
+ const postTrailing = postUrl.endsWith('/');
2337
+ const canonTrailing = canonical.endsWith('/');
2338
+ if (postTrailing !== canonTrailing) {
2339
+ postIssues.push('trailing_slash_mismatch');
2340
+ issuesByType.trailing_slash_mismatch++;
2341
+ }
2342
+ }
2343
+ }
2344
+
2345
+ audits.push({
2346
+ id: p.id, title: strip(p.title?.rendered || ''), url: postUrl,
2347
+ canonical: canonical || null, issues: postIssues
2348
+ });
2349
+ }
2350
+
2351
+ const totalIssues = audits.filter(a => a.issues.length > 0).length;
2352
+ result = json({ total_audited: audits.length, total_issues: totalIssues, seo_plugin_detected: seoPluginDetected, issues_by_type: issuesByType, audits });
2353
+ auditLog({ tool: name, action: 'audit_seo', target_type: post_type, status: 'success', latency_ms: Date.now() - t0, params: { total_audited: audits.length, total_issues: totalIssues, seo_plugin: seoPluginDetected } });
2354
+ break;
2355
+ }
2356
+
2357
+ case 'wp_analyze_eeat_signals': {
2358
+ validateInput(args, {
2359
+ post_ids: { type: 'array' },
2360
+ limit: { type: 'number', min: 1, max: 50 },
2361
+ post_type: { type: 'string', enum: ['post', 'page'] },
2362
+ authoritative_domains: { type: 'array' }
2363
+ });
2364
+ const { post_ids, limit = 10, post_type = 'post', authoritative_domains = ['wikipedia.org', 'gov', 'edu', 'who.int', 'pubmed'] } = args;
2365
+
2366
+ // Fetch posts
2367
+ let posts;
2368
+ if (post_ids && post_ids.length > 0) {
2369
+ posts = await wpApiCall(`/${post_type === 'page' ? 'pages' : 'posts'}?include=${post_ids.join(',')}&_fields=id,title,link,content,author,date,modified,meta`);
2370
+ } else {
2371
+ posts = await wpApiCall(`/${post_type === 'page' ? 'pages' : 'posts'}?per_page=${Math.min(limit, 50)}&status=publish&orderby=date&order=desc&_fields=id,title,link,content,author,date,modified,meta`);
2372
+ }
2373
+
2374
+ // Cache authors
2375
+ const authorCache = {};
2376
+ const eeatResults = [];
2377
+
2378
+ for (const p of posts) {
2379
+ const content = p.content?.rendered || '';
2380
+ const wc = countWords(content);
2381
+ const nowDate = new Date();
2382
+ const modified = new Date(p.modified);
2383
+ const daysSinceUpdate = Math.floor((nowDate - modified) / (1000 * 60 * 60 * 24));
2384
+
2385
+ // Fetch author
2386
+ const authorId = p.author;
2387
+ if (authorId && !authorCache[authorId]) {
2388
+ try {
2389
+ authorCache[authorId] = await wpApiCall(`/users/${authorId}`);
2390
+ } catch { authorCache[authorId] = {}; }
2391
+ }
2392
+ const author = authorCache[authorId] || {};
2393
+
2394
+ const signalsPresent = [];
2395
+ const signalsMissing = [];
2396
+
2397
+ // EXPERIENCE (score /25)
2398
+ let experienceScore = 0;
2399
+ const hasBio = !!(author.description && author.description.trim());
2400
+ if (hasBio) { experienceScore += 10; signalsPresent.push('author_has_bio'); } else { signalsMissing.push({ signal: 'author_has_bio', impact: 10, category: 'experience' }); }
2401
+ const hasFirstPerson = /\b(je|nous|notre|mon|ma|j'ai|j'|I|we|my|our|I've)\b/i.test(content);
2402
+ if (hasFirstPerson) { experienceScore += 8; signalsPresent.push('content_has_first_person'); } else { signalsMissing.push({ signal: 'content_has_first_person', impact: 8, category: 'experience' }); }
2403
+ const hasPersonalExp = /\b(expérience|témoignage|cas|exemple|client|projet|experience|testimony|case study|example|project)\b/i.test(content);
2404
+ if (hasPersonalExp) { experienceScore += 7; signalsPresent.push('content_has_personal_experience'); } else { signalsMissing.push({ signal: 'content_has_personal_experience', impact: 7, category: 'experience' }); }
2405
+
2406
+ // EXPERTISE (score /25)
2407
+ let expertiseScore = 0;
2408
+ const hasData = /\d+\s*(%|€|\$|£|kg|km|ml|mg|px|ms|gb|mb|tb)/i.test(content);
2409
+ if (hasData) { expertiseScore += 8; signalsPresent.push('content_has_data'); } else { signalsMissing.push({ signal: 'content_has_data', impact: 8, category: 'expertise' }); }
2410
+ const hasEntities = /[.>]\s+\w+\s+[A-Z][a-z]{2,}/.test(content.replace(/<[^>]*>/g, ''));
2411
+ if (hasEntities) { expertiseScore += 7; signalsPresent.push('content_has_entities'); } else { signalsMissing.push({ signal: 'content_has_entities', impact: 7, category: 'expertise' }); }
2412
+ if (wc > 800) { expertiseScore += 10; signalsPresent.push('content_word_count_expert'); } else { signalsMissing.push({ signal: 'content_word_count_expert', impact: 10, category: 'expertise' }); }
2413
+
2414
+ // AUTHORITATIVENESS (score /25)
2415
+ let authScore = 0;
2416
+ const extLinkRegex = /<a\s[^>]*?href=["'](https?:\/\/[^"']+)["'][^>]*?>/gi;
2417
+ const externalLinks = [];
2418
+ let extMatch;
2419
+ const { url: sUrl } = getActiveAuth();
2420
+ let sHost = '';
2421
+ try { sHost = new URL(sUrl).host; } catch { /* */ }
2422
+ while ((extMatch = extLinkRegex.exec(content)) !== null) {
2423
+ try {
2424
+ const linkHost = new URL(extMatch[1]).host;
2425
+ if (linkHost !== sHost) externalLinks.push(extMatch[1]);
2426
+ } catch { /* skip */ }
2427
+ }
2428
+ if (externalLinks.length >= 2) { authScore += 8; signalsPresent.push('has_outbound_links'); } else { signalsMissing.push({ signal: 'has_outbound_links', impact: 8, category: 'authoritativeness' }); }
2429
+ const hasAuthSources = externalLinks.some(link => {
2430
+ const lowerLink = link.toLowerCase();
2431
+ return authoritative_domains.some(d => lowerLink.includes(d));
2432
+ });
2433
+ if (hasAuthSources) { authScore += 10; signalsPresent.push('has_authoritative_sources'); } else { signalsMissing.push({ signal: 'has_authoritative_sources', impact: 10, category: 'authoritativeness' }); }
2434
+ const hasCitations = /\b(selon|d'après|source|étude|rapport|according to|study|report|research)\b/i.test(content);
2435
+ if (hasCitations) { authScore += 7; signalsPresent.push('content_has_citations'); } else { signalsMissing.push({ signal: 'content_has_citations', impact: 7, category: 'authoritativeness' }); }
2436
+
2437
+ // TRUSTWORTHINESS (score /25)
2438
+ let trustScore = 0;
2439
+ if (daysSinceUpdate <= 365) { trustScore += 10; signalsPresent.push('has_update_date'); } else { signalsMissing.push({ signal: 'has_update_date', impact: 10, category: 'trustworthiness' }); }
2440
+ const hasAvatar = !!(author.avatar_urls && Object.keys(author.avatar_urls).length > 0);
2441
+ if (hasBio && hasAvatar) { trustScore += 8; signalsPresent.push('author_linked'); } else { signalsMissing.push({ signal: 'author_linked', impact: 8, category: 'trustworthiness' }); }
2442
+ const hasStructuredData = content.includes('application/ld+json');
2443
+ if (hasStructuredData) { trustScore += 7; signalsPresent.push('has_structured_data'); } else { signalsMissing.push({ signal: 'has_structured_data', impact: 7, category: 'trustworthiness' }); }
2444
+
2445
+ const total = experienceScore + expertiseScore + authScore + trustScore;
2446
+
2447
+ // Priority fixes: top 3 missing signals by impact
2448
+ const priorityFixes = signalsMissing
2449
+ .sort((a, b) => b.impact - a.impact)
2450
+ .slice(0, 3)
2451
+ .map(s => ({ signal: s.signal, category: s.category, potential_points: s.impact }));
2452
+
2453
+ eeatResults.push({
2454
+ id: p.id, title: strip(p.title?.rendered || ''),
2455
+ scores: { experience: experienceScore, expertise: expertiseScore, authoritativeness: authScore, trustworthiness: trustScore, total },
2456
+ signals_present: signalsPresent,
2457
+ signals_missing: signalsMissing.map(s => s.signal),
2458
+ priority_fixes: priorityFixes
2459
+ });
2460
+ }
2461
+
2462
+ result = json({ total_analyzed: posts.length, analyses: eeatResults });
2463
+ auditLog({ tool: name, action: 'audit_seo', target_type: post_type, status: 'success', latency_ms: Date.now() - t0, params: { total_analyzed: posts.length } });
2464
+ break;
2465
+ }
2466
+
2467
+ // ── SEO ADVANCED v4.2 ──
2468
+
2469
+ case 'wp_find_broken_internal_links': {
2470
+ validateInput(args, {
2471
+ limit_posts: { type: 'number', min: 1, max: 100 },
2472
+ batch_size: { type: 'number', min: 1, max: 10 },
2473
+ timeout_ms: { type: 'number', min: 1000, max: 30000 },
2474
+ delay_ms: { type: 'number', min: 0, max: 2000 },
2475
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] }
2476
+ });
2477
+ const { limit_posts = 20, batch_size = 5, timeout_ms = 5000, delay_ms = 200, post_type = 'post', include_redirects = true } = args;
2478
+ const scanStart = Date.now();
2479
+
2480
+ // Fetch posts
2481
+ const endpoints = post_type === 'both' ? ['/posts', '/pages'] : [post_type === 'page' ? '/pages' : '/posts'];
2482
+ let allPosts = [];
2483
+ for (const ep of endpoints) {
2484
+ const items = await wpApiCall(`${ep}?per_page=${Math.min(limit_posts, 100)}&status=publish&_fields=id,title,link,content`);
2485
+ allPosts = allPosts.concat(items);
2486
+ }
2487
+ allPosts = allPosts.slice(0, limit_posts);
2488
+
2489
+ // Extract internal links per post and deduplicate globally
2490
+ const linkToSources = new Map(); // url → [{post_id, post_title, post_url, html}]
2491
+ for (const p of allPosts) {
2492
+ const html = p.content?.rendered || '';
2493
+ const siteUrl = p.link ? p.link.replace(/\/[^/]*\/?$/, '') : '';
2494
+ const internalUrls = extractInternalLinksHtml(html, siteUrl);
2495
+ const uniqueUrls = [...new Set(internalUrls)];
2496
+ for (const url of uniqueUrls) {
2497
+ if (!linkToSources.has(url)) linkToSources.set(url, []);
2498
+ linkToSources.get(url).push({ post_id: p.id, post_title: strip(p.title?.rendered || ''), post_url: p.link, html });
2499
+ }
2500
+ }
2501
+
2502
+ // Check links in batches
2503
+ const allUrls = [...linkToSources.keys()];
2504
+ const linkResults = new Map(); // url → {status, ok, isTimeout}
2505
+
2506
+ async function checkSingleLink(url, tms) {
2507
+ const controller = new AbortController();
2508
+ const timer = setTimeout(() => controller.abort(), tms);
2509
+ try {
2510
+ const response = await fetch(url, { method: 'HEAD', signal: controller.signal, redirect: 'manual' });
2511
+ clearTimeout(timer);
2512
+ return { url, status: response.status, ok: response.status < 400 };
2513
+ } catch (error) {
2514
+ clearTimeout(timer);
2515
+ return { url, status: null, ok: false, isTimeout: error.name === 'AbortError' };
2516
+ }
2517
+ }
2518
+
2519
+ for (let i = 0; i < allUrls.length; i += batch_size) {
2520
+ const batch = allUrls.slice(i, i + batch_size);
2521
+ const results = await Promise.allSettled(batch.map(u => checkSingleLink(u, timeout_ms)));
2522
+ for (const r of results) {
2523
+ const val = r.status === 'fulfilled' ? r.value : { url: batch[0], status: null, ok: false, isTimeout: false };
2524
+ linkResults.set(val.url, val);
2525
+ }
2526
+ if (i + batch_size < allUrls.length && delay_ms > 0) {
2527
+ await new Promise(r => setTimeout(r, delay_ms));
2528
+ }
2529
+ }
2530
+
2531
+ // Extract anchor text helper
2532
+ function getAnchorText(html, href) {
2533
+ const escaped = href.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2534
+ const m = html.match(new RegExp(`<a\\s[^>]*?href=["']${escaped}["'][^>]*?>(.*?)<\\/a>`, 'i'));
2535
+ return m ? m[1].replace(/<[^>]*>/g, '').trim() : '';
2536
+ }
2537
+
2538
+ // Build results
2539
+ const brokenLinks = [];
2540
+ let totalRedirects = 0;
2541
+ let totalTimeouts = 0;
2542
+ let totalBroken = 0;
2543
+
2544
+ for (const [url, lr] of linkResults) {
2545
+ let issueType = null;
2546
+ if (lr.status === 404) issueType = 'not_found';
2547
+ else if (lr.status === 301 || lr.status === 302) issueType = 'redirect';
2548
+ else if (lr.isTimeout) issueType = 'timeout';
2549
+ else if (!lr.ok && lr.status !== 301 && lr.status !== 302) issueType = 'network_error';
2550
+
2551
+ if (!issueType) continue;
2552
+ if (issueType === 'redirect') { totalRedirects++; if (!include_redirects) continue; }
2553
+ if (issueType === 'timeout') totalTimeouts++;
2554
+ if (issueType === 'not_found' || issueType === 'network_error') totalBroken++;
2555
+
2556
+ const sources = linkToSources.get(url) || [];
2557
+ for (const src of sources) {
2558
+ brokenLinks.push({
2559
+ source_post_id: src.post_id, source_post_title: src.post_title, source_post_url: src.post_url,
2560
+ broken_url: url, anchor_text: getAnchorText(src.html, url),
2561
+ status_code: lr.status, issue_type: issueType
2562
+ });
2563
+ }
2564
+ }
2565
+
2566
+ // Sort: not_found first, then redirect, then timeout, then network_error
2567
+ const typeOrder = { not_found: 0, redirect: 1, timeout: 2, network_error: 3 };
2568
+ brokenLinks.sort((a, b) => (typeOrder[a.issue_type] ?? 9) - (typeOrder[b.issue_type] ?? 9));
2569
+
2570
+ result = json({
2571
+ total_posts_scanned: allPosts.length,
2572
+ total_links_checked: allUrls.length,
2573
+ total_broken: totalBroken,
2574
+ total_redirects: totalRedirects,
2575
+ total_timeouts: totalTimeouts,
2576
+ broken_links: brokenLinks,
2577
+ scan_duration_ms: Date.now() - scanStart
2578
+ });
2579
+ auditLog({ tool: name, action: 'audit_seo', target_type: 'post', status: 'success', latency_ms: Date.now() - t0, params: { limit_posts, total_links_checked: allUrls.length } });
2580
+ break;
2581
+ }
2582
+
2583
+ case 'wp_find_keyword_cannibalization': {
2584
+ validateInput(args, {
2585
+ limit: { type: 'number', min: 1, max: 500 },
2586
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] },
2587
+ similarity_mode: { type: 'string', enum: ['exact', 'normalized'] },
2588
+ min_group_size: { type: 'number', min: 2 }
2589
+ });
2590
+ const { limit = 200, post_type = 'post', similarity_mode = 'normalized', min_group_size = 2 } = args;
2591
+
2592
+ const endpoints = post_type === 'both' ? ['/posts', '/pages'] : [post_type === 'page' ? '/pages' : '/posts'];
2593
+ let allPosts = [];
2594
+ for (const ep of endpoints) {
2595
+ const items = await wpApiCall(`${ep}?per_page=${Math.min(limit, 100)}&status=publish&_fields=id,title,link,date,meta`);
2596
+ allPosts = allPosts.concat(items);
2597
+ }
2598
+ allPosts = allPosts.slice(0, limit);
2599
+
2600
+ // Extract focus keyword
2601
+ function getFocusKeyword(meta) {
2602
+ if (!meta) return null;
2603
+ return meta.rank_math_focus_keyword || meta._yoast_wpseo_focuskw || meta._seopress_analysis_target_kw || meta._aioseo_keywords || null;
2604
+ }
2605
+
2606
+ // Normalize keyword
2607
+ function normalizeKeyword(kw) {
2608
+ return kw
2609
+ .toLowerCase()
2610
+ .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
2611
+ .replace(/\b(le|la|les|un|une|des|de|du|en|et|ou|the|a|an|of|for|in|on|at)\b/g, '')
2612
+ .replace(/[^a-z0-9\s]/g, ' ')
2613
+ .replace(/\s+/g, ' ')
2614
+ .trim();
2615
+ }
2616
+
2617
+ // Group by keyword
2618
+ const kwMap = new Map(); // normalizedKw → [{id, title, url, date, original_keyword}]
2619
+ let postsWithKw = 0;
2620
+ let postsWithoutKw = 0;
2621
+
2622
+ for (const p of allPosts) {
2623
+ const raw = getFocusKeyword(p.meta);
2624
+ if (!raw || !raw.trim()) { postsWithoutKw++; continue; }
2625
+ postsWithKw++;
2626
+ const key = similarity_mode === 'exact' ? raw.trim() : normalizeKeyword(raw);
2627
+ if (!kwMap.has(key)) kwMap.set(key, []);
2628
+ kwMap.get(key).push({
2629
+ id: p.id, title: strip(p.title?.rendered || ''), url: p.link, date: p.date, original_keyword: raw.trim()
2630
+ });
2631
+ }
2632
+
2633
+ // Filter groups by min_group_size
2634
+ const groups = [];
2635
+ for (const [keyword, articles] of kwMap) {
2636
+ if (articles.length < min_group_size) continue;
2637
+ // Recommended action
2638
+ let recommended_action = 'differentiate';
2639
+ if (articles.length >= 3) {
2640
+ recommended_action = 'merge';
2641
+ } else if (articles.length === 2) {
2642
+ const d1 = new Date(articles[0].date);
2643
+ const d2 = new Date(articles[1].date);
2644
+ const diffDays = Math.abs(d1 - d2) / (1000 * 60 * 60 * 24);
2645
+ if (diffDays > 365) recommended_action = 'consolidate_301';
2646
+ else recommended_action = 'differentiate';
2647
+ }
2648
+ groups.push({
2649
+ keyword,
2650
+ variants: [...new Set(articles.map(a => a.original_keyword))],
2651
+ articles_count: articles.length,
2652
+ articles,
2653
+ recommended_action
2654
+ });
2655
+ }
2656
+
2657
+ let articlesAffected = 0;
2658
+ for (const g of groups) articlesAffected += g.articles_count;
2659
+
2660
+ result = json({
2661
+ total_posts_analyzed: allPosts.length,
2662
+ posts_with_keyword: postsWithKw,
2663
+ posts_without_keyword: postsWithoutKw,
2664
+ total_groups: groups.length,
2665
+ articles_affected: articlesAffected,
2666
+ cannibalization_groups: groups
2667
+ });
2668
+ auditLog({ tool: name, action: 'audit_seo', target_type: 'post', status: 'success', latency_ms: Date.now() - t0, params: { total_posts_analyzed: allPosts.length, total_groups: groups.length } });
2669
+ break;
2670
+ }
2671
+
2672
+ case 'wp_audit_taxonomies': {
2673
+ validateInput(args, {
2674
+ min_posts_threshold: { type: 'number', min: 1 }
2675
+ });
2676
+ const { check_tags = true, check_categories = true, min_posts_threshold = 2, detect_duplicates = true } = args;
2677
+
2678
+ // Levenshtein distance
2679
+ function levenshtein(a, b) {
2680
+ const m = a.length, n = b.length;
2681
+ const dp = Array.from({ length: m + 1 }, (_, i) =>
2682
+ Array.from({ length: n + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0)
2683
+ );
2684
+ for (let i = 1; i <= m; i++)
2685
+ for (let j = 1; j <= n; j++)
2686
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1]
2687
+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
2688
+ return dp[m][n];
2689
+ }
2690
+
2691
+ function normalizeTermName(name) {
2692
+ return name.toLowerCase()
2693
+ .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
2694
+ .replace(/[^a-z0-9]/g, '');
2695
+ }
2696
+
2697
+ function auditTerms(terms, isCat) {
2698
+ const empty = [];
2699
+ const singlePost = [];
2700
+ const missingDesc = [];
2701
+ for (const t of terms) {
2702
+ const item = { id: t.id, name: t.name, slug: t.slug, count: t.count };
2703
+ if (t.count === 0) { empty.push({ ...item, issue_type: 'empty' }); }
2704
+ else if (t.count < min_posts_threshold) { singlePost.push({ ...item, issue_type: 'single_post' }); }
2705
+ if (isCat && (!t.description || t.description.trim() === '')) {
2706
+ missingDesc.push({ ...item, issue_type: 'missing_description' });
2707
+ }
2708
+ }
2709
+
2710
+ // Duplicate detection
2711
+ const duplicateGroups = [];
2712
+ if (detect_duplicates && terms.length > 1) {
2713
+ const normalized = terms.map(t => ({ ...t, norm: normalizeTermName(t.name) }));
2714
+ const used = new Set();
2715
+ for (let i = 0; i < normalized.length; i++) {
2716
+ if (used.has(i)) continue;
2717
+ const group = [normalized[i]];
2718
+ for (let j = i + 1; j < normalized.length; j++) {
2719
+ if (used.has(j)) continue;
2720
+ const isExact = normalized[i].norm === normalized[j].norm;
2721
+ const isNear = !isExact && normalized[i].norm.length >= 4 && normalized[j].norm.length >= 4 && levenshtein(normalized[i].norm, normalized[j].norm) <= 2;
2722
+ if (isExact || isNear) {
2723
+ group.push(normalized[j]);
2724
+ used.add(j);
2725
+ }
2726
+ }
2727
+ if (group.length >= 2) {
2728
+ used.add(i);
2729
+ const similarity = group.every(g => g.norm === group[0].norm) ? 'exact' : 'near';
2730
+ duplicateGroups.push({
2731
+ terms: group.map(g => ({ id: g.id, name: g.name, slug: g.slug, count: g.count, issue_type: 'duplicate' })),
2732
+ similarity
2733
+ });
2734
+ }
2735
+ }
2736
+ }
2737
+
2738
+ const issues = { empty, single_post: singlePost, duplicate_groups: duplicateGroups };
2739
+ if (isCat) issues.missing_description = missingDesc;
2740
+ return issues;
2741
+ }
2742
+
2743
+ let tagsResult = null;
2744
+ let catsResult = null;
2745
+ let totalIssues = 0;
2746
+ let totalTerms = 0;
2747
+
2748
+ if (check_tags) {
2749
+ const tags = await wpApiCall('/tags?per_page=100');
2750
+ const issues = auditTerms(tags, false);
2751
+ const tagIssueCount = issues.empty.length + issues.single_post.length + issues.duplicate_groups.reduce((s, g) => s + g.terms.length, 0);
2752
+ totalIssues += tagIssueCount;
2753
+ totalTerms += tags.length;
2754
+ tagsResult = { total: tags.length, issues };
2755
+ }
2756
+
2757
+ if (check_categories) {
2758
+ const cats = await wpApiCall('/categories?per_page=100');
2759
+ const issues = auditTerms(cats, true);
2760
+ const catIssueCount = issues.empty.length + issues.single_post.length + (issues.missing_description || []).length + issues.duplicate_groups.reduce((s, g) => s + g.terms.length, 0);
2761
+ totalIssues += catIssueCount;
2762
+ totalTerms += cats.length;
2763
+ catsResult = { total: cats.length, issues };
2764
+ }
2765
+
2766
+ const crawlWasteScore = totalTerms > 0 ? Math.min(100, Math.round((totalIssues / totalTerms) * 100)) : 0;
2767
+
2768
+ const output = { total_issues: totalIssues, crawl_waste_score: crawlWasteScore };
2769
+ if (tagsResult) output.tags = tagsResult;
2770
+ if (catsResult) output.categories = catsResult;
2771
+
2772
+ result = json(output);
2773
+ auditLog({ tool: name, action: 'audit_seo', target_type: 'taxonomy', status: 'success', latency_ms: Date.now() - t0, params: { total_issues: totalIssues, crawl_waste_score: crawlWasteScore } });
2774
+ break;
2775
+ }
2776
+
2777
+ case 'wp_audit_outbound_links': {
2778
+ validateInput(args, {
2779
+ limit: { type: 'number', min: 1, max: 100 },
2780
+ post_type: { type: 'string', enum: ['post', 'page'] },
2781
+ min_outbound: { type: 'number', min: 0 },
2782
+ max_outbound: { type: 'number', min: 1 },
2783
+ authoritative_domains: { type: 'array' }
2784
+ });
2785
+ const { limit = 30, post_type = 'post', min_outbound = 1, max_outbound = 15, authoritative_domains = ['wikipedia.org', 'gov', 'edu', 'who.int', 'pubmed.ncbi'] } = args;
2786
+ const endpoint = post_type === 'page' ? '/pages' : '/posts';
2787
+ const posts = await wpApiCall(`${endpoint}?per_page=${Math.min(limit, 100)}&status=publish&_fields=id,title,link,content`);
2788
+
2789
+ function extractDomain(url) {
2790
+ try { return new URL(url).hostname.replace(/^www\./, ''); }
2791
+ catch { return null; }
2792
+ }
2793
+
2794
+ function isAuthoritative(domain) {
2795
+ return authoritative_domains.some(ad => domain === ad || domain.endsWith('.' + ad));
2796
+ }
2797
+
2798
+ const domainCounts = new Map();
2799
+ const articles = [];
2800
+ let totalAuthoritative = 0;
2801
+
2802
+ for (const p of posts) {
2803
+ const html = p.content?.rendered || '';
2804
+ const wc = countWords(html);
2805
+ const siteHost = p.link ? extractDomain(p.link) : '';
2806
+
2807
+ // Extract all links
2808
+ const allLinks = [];
2809
+ const linkRegex = /<a\s[^>]*?href=["']([^"']+)["'][^>]*?>/gi;
2810
+ let m;
2811
+ while ((m = linkRegex.exec(html)) !== null) {
2812
+ try {
2813
+ const href = m[1];
2814
+ if (href.startsWith('http')) allLinks.push(href);
2815
+ } catch { /* skip */ }
2816
+ }
2817
+
2818
+ // Separate external links
2819
+ const externalLinks = [];
2820
+ const externalDomains = new Set();
2821
+ for (const link of allLinks) {
2822
+ const dom = extractDomain(link);
2823
+ if (!dom || dom === siteHost) continue;
2824
+ externalLinks.push(link);
2825
+ externalDomains.add(dom);
2826
+ domainCounts.set(dom, (domainCounts.get(dom) || 0) + 1);
2827
+ }
2828
+
2829
+ const outboundCount = externalLinks.length;
2830
+ let authCount = 0;
2831
+ for (const dom of externalDomains) {
2832
+ if (isAuthoritative(dom)) authCount++;
2833
+ }
2834
+ if (authCount > 0) totalAuthoritative++;
2835
+
2836
+ let status;
2837
+ if (outboundCount === 0) status = 'no_outbound';
2838
+ else if (outboundCount < min_outbound) status = 'insufficient';
2839
+ else if (outboundCount > max_outbound) status = 'excessive';
2840
+ else status = 'good';
2841
+
2842
+ articles.push({
2843
+ id: p.id, title: strip(p.title?.rendered || ''), url: p.link, word_count: wc,
2844
+ outbound_count: outboundCount,
2845
+ authoritative_count: authCount,
2846
+ outbound_ratio: wc > 0 ? Math.round((outboundCount / (wc / 100)) * 100) / 100 : 0,
2847
+ status,
2848
+ external_domains: [...externalDomains]
2849
+ });
2850
+ }
2851
+
2852
+ // Top cited domains
2853
+ const topDomains = [...domainCounts.entries()]
2854
+ .sort((a, b) => b[1] - a[1])
2855
+ .slice(0, 10)
2856
+ .map(([domain, count]) => ({ domain, count, is_authoritative: isAuthoritative(domain) }));
2857
+
2858
+ const byStatus = { no_outbound: 0, insufficient: 0, good: 0, excessive: 0 };
2859
+ for (const a of articles) byStatus[a.status]++;
2860
+
2861
+ const avgOutbound = articles.length > 0 ? Math.round((articles.reduce((s, a) => s + a.outbound_count, 0) / articles.length) * 100) / 100 : 0;
2862
+
2863
+ result = json({
2864
+ total_analyzed: posts.length,
2865
+ by_status: byStatus,
2866
+ top_cited_domains: topDomains,
2867
+ articles,
2868
+ average_outbound_per_post: avgOutbound,
2869
+ posts_with_authoritative_sources: totalAuthoritative
2870
+ });
2871
+ auditLog({ tool: name, action: 'audit_seo', target_type: 'post', status: 'success', latency_ms: Date.now() - t0, params: { total_analyzed: posts.length } });
2872
+ break;
2873
+ }
2874
+
2875
+ // ── CONTENT INTELLIGENCE v4.4 ──
2876
+
2877
+ case 'wp_get_content_brief': {
2878
+ validateInput(args, {
2879
+ id: { type: 'number', required: true, min: 1 },
2880
+ post_type: { type: 'string', enum: ['post', 'page'] }
2881
+ });
2882
+ const { id, post_type: briefPostType = 'post' } = args;
2883
+ const briefEndpoint = briefPostType === 'page' ? '/pages' : '/posts';
2884
+ const briefPost = await wpApiCall(`${briefEndpoint}/${id}?_fields=id,title,content,excerpt,slug,status,date,modified,link,categories,tags,author,featured_media,meta`);
2885
+
2886
+ const briefContent = briefPost.content?.rendered || '';
2887
+ const { url: briefSiteUrl } = getActiveAuth();
2888
+
2889
+ // Word count & readability
2890
+ const briefWordCount = countWords(briefContent);
2891
+ const readability = calculateReadabilityScore(briefContent);
2892
+
2893
+ // Structure
2894
+ const briefHeadings = extractHeadingsOutline(briefContent);
2895
+ const structure = detectContentSections(briefContent);
2896
+
2897
+ // Links
2898
+ const briefInternalLinks = extractInternalLinks(briefContent, briefSiteUrl);
2899
+ const briefExternalLinks = extractExternalLinks(briefContent, briefSiteUrl);
2900
+
2901
+ // SEO meta
2902
+ const briefMeta = briefPost.meta || {};
2903
+ const briefFocusKw = extractFocusKeyword(briefMeta);
2904
+ const seoTitle = briefMeta._yoast_wpseo_title || briefMeta.rank_math_title || briefMeta._seopress_titles_title || null;
2905
+ const seoDescription = briefMeta._yoast_wpseo_metadesc || briefMeta.rank_math_description || briefMeta._seopress_titles_desc || null;
2906
+ const seoCanonical = briefMeta._yoast_wpseo_canonical || briefMeta.rank_math_canonical_url || briefMeta._seopress_robots_canonical || null;
2907
+
2908
+ // Resolve categories to names
2909
+ const briefCatIds = briefPost.categories || [];
2910
+ let briefCategories = [];
2911
+ if (briefCatIds.length > 0) {
2912
+ try {
2913
+ const cats = await wpApiCall(`/categories?include=${briefCatIds.join(',')}&_fields=id,name`);
2914
+ briefCategories = cats.map(c => ({ id: c.id, name: c.name }));
2915
+ } catch { briefCategories = briefCatIds.map(cid => ({ id: cid, name: null })); }
2916
+ }
2917
+
2918
+ // Resolve tags to names
2919
+ const briefTagIds = briefPost.tags || [];
2920
+ let briefTags = [];
2921
+ if (briefTagIds.length > 0) {
2922
+ try {
2923
+ const tags = await wpApiCall(`/tags?include=${briefTagIds.join(',')}&_fields=id,name`);
2924
+ briefTags = tags.map(t => ({ id: t.id, name: t.name }));
2925
+ } catch { briefTags = briefTagIds.map(tid => ({ id: tid, name: null })); }
2926
+ }
2927
+
2928
+ result = json({
2929
+ id: briefPost.id,
2930
+ title: strip(briefPost.title?.rendered || ''),
2931
+ slug: briefPost.slug,
2932
+ status: briefPost.status,
2933
+ date: briefPost.date,
2934
+ modified: briefPost.modified,
2935
+ link: briefPost.link,
2936
+ author: briefPost.author,
2937
+ word_count: briefWordCount,
2938
+ readability: { score: readability.score, level: readability.level, avg_words_per_sentence: readability.avg_words_per_sentence },
2939
+ seo: {
2940
+ title: seoTitle,
2941
+ description: seoDescription,
2942
+ focus_keyword: briefFocusKw,
2943
+ canonical: seoCanonical
2944
+ },
2945
+ structure: {
2946
+ headings: briefHeadings,
2947
+ has_intro: structure.has_intro,
2948
+ has_conclusion: structure.has_conclusion,
2949
+ has_faq: structure.has_faq,
2950
+ lists_count: structure.lists_count,
2951
+ tables_count: structure.tables_count,
2952
+ images_count: structure.images_count
2953
+ },
2954
+ categories: briefCategories,
2955
+ tags: briefTags,
2956
+ internal_links: { count: briefInternalLinks.length, links: briefInternalLinks },
2957
+ external_links: { count: briefExternalLinks.length, links: briefExternalLinks },
2958
+ featured_media: briefPost.featured_media || null
2959
+ });
2960
+ auditLog({ tool: name, target: id, target_type: briefPostType, action: 'content_brief', status: 'success', latency_ms: Date.now() - t0, params: { id, post_type: briefPostType } });
2961
+ break;
2962
+ }
2963
+
2964
+ case 'wp_extract_post_outline': {
2965
+ validateInput(args, {
2966
+ category_id: { type: 'number', required: true, min: 1 },
2967
+ post_type: { type: 'string', enum: ['post', 'page'] },
2968
+ limit: { type: 'number', min: 1, max: 50 }
2969
+ });
2970
+ const { category_id, post_type: outlinePostType = 'post', limit: outlineLimit = 10 } = args;
2971
+ const outlineEndpoint = outlinePostType === 'page' ? '/pages' : '/posts';
2972
+ let outlineUrl = `${outlineEndpoint}?per_page=${Math.min(outlineLimit, 50)}&status=publish&_fields=id,title,content,slug,link,meta`;
2973
+ if (outlinePostType !== 'page') outlineUrl += `&categories=${category_id}`;
2974
+ const outlinePosts = await wpApiCall(outlineUrl);
2975
+
2976
+ const outlines = [];
2977
+ const h2Counter = new Map();
2978
+
2979
+ for (const p of outlinePosts) {
2980
+ const html = p.content?.rendered || '';
2981
+ const headings = extractHeadingsOutline(html);
2982
+ const wc = countWords(html);
2983
+
2984
+ // Count H2 patterns
2985
+ for (const h of headings) {
2986
+ if (h.level === 2) {
2987
+ const normalized = h.text.toLowerCase().trim();
2988
+ if (normalized) h2Counter.set(normalized, (h2Counter.get(normalized) || 0) + 1);
2989
+ }
2990
+ }
2991
+
2992
+ outlines.push({
2993
+ id: p.id,
2994
+ title: strip(p.title?.rendered || ''),
2995
+ slug: p.slug,
2996
+ link: p.link,
2997
+ word_count: wc,
2998
+ headings_count: headings.length,
2999
+ headings
3000
+ });
3001
+ }
3002
+
3003
+ // Aggregated stats
3004
+ const totalWords = outlines.reduce((s, o) => s + o.word_count, 0);
3005
+ const totalHeadings = outlines.reduce((s, o) => s + o.headings_count, 0);
3006
+ const avgWordCount = outlines.length > 0 ? Math.round(totalWords / outlines.length) : 0;
3007
+ const avgHeadingsCount = outlines.length > 0 ? Math.round(totalHeadings / outlines.length) : 0;
3008
+
3009
+ // Common H2 patterns (top 10)
3010
+ const commonH2 = [...h2Counter.entries()]
3011
+ .sort((a, b) => b[1] - a[1])
3012
+ .slice(0, 10)
3013
+ .map(([text, frequency]) => ({ text, frequency }));
3014
+
3015
+ result = json({
3016
+ category_id,
3017
+ posts_analyzed: outlines.length,
3018
+ avg_word_count: avgWordCount,
3019
+ avg_headings_count: avgHeadingsCount,
3020
+ common_h2_patterns: commonH2,
3021
+ outlines
3022
+ });
3023
+ auditLog({ tool: name, action: 'extract_outline', status: 'success', latency_ms: Date.now() - t0, params: { category_id, post_type: outlinePostType, limit: outlineLimit } });
3024
+ break;
3025
+ }
3026
+
3027
+ // ── wp_audit_readability ──
3028
+ case 'wp_audit_readability': {
3029
+ validateInput(args, {
3030
+ limit: { type: 'number', min: 1, max: 200 },
3031
+ post_type: { type: 'string', enum: ['post', 'page'] },
3032
+ category_id: { type: 'number' },
3033
+ min_words: { type: 'number', min: 0 }
3034
+ });
3035
+ const { limit: arLimit = 50, post_type: arPostType = 'post', category_id: arCatId, min_words: arMinWords = 100 } = args;
3036
+ const arEndpoint = arPostType === 'page' ? '/pages' : '/posts';
3037
+ let arUrl = `${arEndpoint}?per_page=${Math.min(arLimit, 200)}&status=publish&_fields=id,title,content,slug,link,categories,meta`;
3038
+ if (arCatId && arPostType !== 'page') arUrl += `&categories=${arCatId}`;
3039
+ const arPosts = await wpApiCall(arUrl);
3040
+
3041
+ const arResults = [];
3042
+ for (const p of arPosts) {
3043
+ const html = p.content?.rendered || '';
3044
+ const wc = countWords(html);
3045
+ if (wc < arMinWords) continue;
3046
+ const plainText = strip(html);
3047
+ const readabilityResult = calculateReadabilityScore(html);
3048
+ const transitionResult = extractTransitionWords(plainText);
3049
+ const passiveResult = countPassiveSentences(plainText);
3050
+
3051
+ const issues = [];
3052
+ if (readabilityResult.score < 20) issues.push('very_low_readability');
3053
+ else if (readabilityResult.score < 40) issues.push('low_readability');
3054
+ if (transitionResult.count === 0) issues.push('no_transition_words');
3055
+ else if (transitionResult.density < 0.1) issues.push('low_transition_density');
3056
+ if (passiveResult.ratio > 0.3) issues.push('high_passive_ratio');
3057
+
3058
+ arResults.push({
3059
+ id: p.id,
3060
+ title: strip(p.title?.rendered || ''),
3061
+ slug: p.slug,
3062
+ link: p.link,
3063
+ word_count: wc,
3064
+ readability: {
3065
+ score: readabilityResult.score,
3066
+ level: readabilityResult.level,
3067
+ avg_words_per_sentence: readabilityResult.avg_words_per_sentence,
3068
+ avg_syllables_per_word: readabilityResult.avg_syllables_per_word
3069
+ },
3070
+ transition_density: transitionResult.density,
3071
+ passive_ratio: passiveResult.ratio,
3072
+ issues
3073
+ });
3074
+ }
3075
+
3076
+ // Sort by score ASC (worst first)
3077
+ arResults.sort((a, b) => a.readability.score - b.readability.score);
3078
+
3079
+ // Aggregation
3080
+ const arTotal = arResults.length;
3081
+ const arAvgScore = arTotal > 0 ? Math.round(arResults.reduce((s, r) => s + r.readability.score, 0) / arTotal * 10) / 10 : 0;
3082
+ const arAvgTD = arTotal > 0 ? Math.round(arResults.reduce((s, r) => s + r.transition_density, 0) / arTotal * 1000) / 1000 : 0;
3083
+ const arAvgPR = arTotal > 0 ? Math.round(arResults.reduce((s, r) => s + r.passive_ratio, 0) / arTotal * 1000) / 1000 : 0;
3084
+ const distribution = { 'très facile': 0, 'facile': 0, 'standard': 0, 'difficile': 0, 'très difficile': 0 };
3085
+ for (const r of arResults) { distribution[r.readability.level] = (distribution[r.readability.level] || 0) + 1; }
3086
+
3087
+ result = json({
3088
+ total_analyzed: arTotal,
3089
+ avg_readability_score: arAvgScore,
3090
+ distribution,
3091
+ avg_transition_density: arAvgTD,
3092
+ avg_passive_ratio: arAvgPR,
3093
+ posts: arResults
3094
+ });
3095
+ auditLog({ tool: name, action: 'audit_readability', status: 'success', latency_ms: Date.now() - t0, params: { limit: arLimit, post_type: arPostType, category_id: arCatId, min_words: arMinWords } });
3096
+ break;
3097
+ }
3098
+
3099
+ // ── wp_audit_update_frequency ──
3100
+ case 'wp_audit_update_frequency': {
3101
+ validateInput(args, {
3102
+ days_threshold: { type: 'number', min: 1 },
3103
+ limit: { type: 'number', min: 1, max: 200 },
3104
+ post_type: { type: 'string', enum: ['post', 'page'] },
3105
+ include_seo_score: { type: 'boolean' }
3106
+ });
3107
+ const { days_threshold: aufDays = 180, limit: aufLimit = 50, post_type: aufPostType = 'post', include_seo_score: aufIncludeSeo = true } = args;
3108
+ const aufEndpoint = aufPostType === 'page' ? '/pages' : '/posts';
3109
+ const aufUrl = `${aufEndpoint}?per_page=${Math.min(aufLimit, 200)}&status=publish&_fields=id,title,slug,link,date,modified,content,meta,categories`;
3110
+ const aufAllPosts = await wpApiCall(aufUrl);
3111
+
3112
+ const aufNow = Date.now();
3113
+ const aufFiltered = [];
3114
+
3115
+ for (const p of aufAllPosts) {
3116
+ const daysSince = Math.floor((aufNow - new Date(p.modified).getTime()) / 86400000);
3117
+ if (daysSince < aufDays) continue;
3118
+
3119
+ const meta = p.meta || {};
3120
+ const html = p.content?.rendered || '';
3121
+ const wc = countWords(html);
3122
+
3123
+ let seoScore = null;
3124
+ const issues = ['outdated_180d'];
3125
+ if (daysSince >= 365) issues.push('outdated_365d');
3126
+ if (wc < 300) issues.push('thin_content');
3127
+
3128
+ if (aufIncludeSeo) {
3129
+ const seoTitle = meta.rank_math_title || meta._yoast_wpseo_title || meta._seopress_titles_title || meta._aioseo_title || null;
3130
+ const seoDesc = meta.rank_math_description || meta._yoast_wpseo_metadesc || meta._seopress_titles_desc || meta._aioseo_description || null;
3131
+ const focusKw = extractFocusKeyword(meta);
3132
+ seoScore = 100;
3133
+ if (!seoTitle) { seoScore -= 30; issues.push('missing_seo_title'); }
3134
+ if (!seoDesc) { seoScore -= 30; issues.push('missing_meta_description'); }
3135
+ if (!focusKw) seoScore -= 20;
3136
+ if (seoTitle && focusKw && !seoTitle.toLowerCase().includes(focusKw.toLowerCase())) seoScore -= 10;
3137
+ if (seoScore < 70) issues.push('low_seo_score');
3138
+ }
3139
+
3140
+ const priority = daysSince * (aufIncludeSeo && seoScore !== null ? (100 - seoScore) / 100 : 1) * (wc < 300 ? 1.5 : 1);
3141
+
3142
+ aufFiltered.push({
3143
+ id: p.id,
3144
+ title: strip(p.title?.rendered || ''),
3145
+ slug: p.slug,
3146
+ link: p.link,
3147
+ date: p.date,
3148
+ modified: p.modified,
3149
+ days_since_modified: daysSince,
3150
+ word_count: wc,
3151
+ seo_score: seoScore,
3152
+ priority_score: Math.round(priority * 10) / 10,
3153
+ issues
3154
+ });
3155
+ }
3156
+
3157
+ aufFiltered.sort((a, b) => b.priority_score - a.priority_score);
3158
+
3159
+ result = json({
3160
+ days_threshold: aufDays,
3161
+ total_published: aufAllPosts.length,
3162
+ outdated_count: aufFiltered.length,
3163
+ outdated_ratio: aufAllPosts.length > 0 ? Math.round(aufFiltered.length / aufAllPosts.length * 100) / 100 : 0,
3164
+ posts: aufFiltered
3165
+ });
3166
+ auditLog({ tool: name, action: 'audit_update_frequency', status: 'success', latency_ms: Date.now() - t0, params: { days_threshold: aufDays, limit: aufLimit, post_type: aufPostType, include_seo_score: aufIncludeSeo } });
3167
+ break;
3168
+ }
3169
+
3170
+ // ── wp_build_link_map ──
3171
+ case 'wp_build_link_map': {
3172
+ validateInput(args, {
3173
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] },
3174
+ limit: { type: 'number', min: 1, max: 200 },
3175
+ category_id: { type: 'number' }
3176
+ });
3177
+ const { post_type: lmPostType = 'post', limit: lmLimit = 50, category_id: lmCatId } = args;
3178
+ const { url: lmSiteUrl } = getActiveAuth();
3179
+ const perPage = Math.min(lmLimit, 200);
3180
+ const fields = '_fields=id,title,slug,link,content,categories';
3181
+
3182
+ let lmPosts = [];
3183
+ if (lmPostType === 'both') {
3184
+ let postsUrl = `/posts?per_page=${perPage}&status=publish&${fields}`;
3185
+ if (lmCatId) postsUrl += `&categories=${lmCatId}`;
3186
+ const [posts, pages] = await Promise.all([
3187
+ wpApiCall(postsUrl),
3188
+ wpApiCall(`/pages?per_page=${perPage}&status=publish&${fields}`)
3189
+ ]);
3190
+ lmPosts = [...posts, ...pages];
3191
+ } else {
3192
+ const ep = lmPostType === 'page' ? '/pages' : '/posts';
3193
+ let postsUrl = `${ep}?per_page=${perPage}&status=publish&${fields}`;
3194
+ if (lmCatId && lmPostType !== 'page') postsUrl += `&categories=${lmCatId}`;
3195
+ lmPosts = await wpApiCall(postsUrl);
3196
+ }
3197
+
3198
+ // Build lookup maps
3199
+ const postMap = new Map();
3200
+ const slugToId = new Map();
3201
+ for (const p of lmPosts) {
3202
+ postMap.set(p.id, {
3203
+ id: p.id,
3204
+ title: strip(p.title?.rendered || ''),
3205
+ slug: p.slug,
3206
+ link: p.link,
3207
+ outbound_links: [],
3208
+ inbound_count: 0,
3209
+ unresolved_links: 0
3210
+ });
3211
+ slugToId.set(p.slug, p.id);
3212
+ if (p.link) {
3213
+ try { slugToId.set(new URL(p.link).pathname.replace(/\/+$/, ''), p.id); } catch { /* skip */ }
3214
+ }
3215
+ }
3216
+
3217
+ // Extract links and resolve targets
3218
+ let totalLinks = 0;
3219
+ const linkMatrix = {};
3220
+
3221
+ for (const p of lmPosts) {
3222
+ const html = p.content?.rendered || '';
3223
+ const internalLinks = extractInternalLinks(html, lmSiteUrl);
3224
+ const resolvedTargets = [];
3225
+ let unresolvedCount = 0;
3226
+
3227
+ for (const link of internalLinks) {
3228
+ let targetId = null;
3229
+ // Try to match by URL path
3230
+ try {
3231
+ const linkPath = new URL(link.url || link).pathname.replace(/\/+$/, '');
3232
+ targetId = slugToId.get(linkPath) || null;
3233
+ if (!targetId) {
3234
+ // Try matching just the last segment as slug
3235
+ const lastSeg = linkPath.split('/').filter(Boolean).pop();
3236
+ if (lastSeg) targetId = slugToId.get(lastSeg) || null;
3237
+ }
3238
+ } catch { /* skip */ }
3239
+
3240
+ if (targetId && targetId !== p.id && postMap.has(targetId)) {
3241
+ const target = postMap.get(targetId);
3242
+ resolvedTargets.push({
3243
+ target_id: targetId,
3244
+ target_title: target.title,
3245
+ anchor_text: link.anchor_text || link.text || ''
3246
+ });
3247
+ target.inbound_count++;
3248
+ totalLinks++;
3249
+ } else {
3250
+ unresolvedCount++;
3251
+ }
3252
+ }
3253
+
3254
+ const entry = postMap.get(p.id);
3255
+ entry.outbound_links = resolvedTargets;
3256
+ entry.unresolved_links = unresolvedCount;
3257
+ if (resolvedTargets.length > 0) {
3258
+ linkMatrix[p.id] = resolvedTargets.map(l => l.target_id);
3259
+ }
3260
+ }
3261
+
3262
+ // Simplified PageRank (10 iterations, damping 0.85)
3263
+ const N = lmPosts.length;
3264
+ const damping = 0.85;
3265
+ let scores = new Map();
3266
+ for (const p of lmPosts) scores.set(p.id, 1 / N);
3267
+
3268
+ for (let iter = 0; iter < 10; iter++) {
3269
+ const newScores = new Map();
3270
+ for (const p of lmPosts) newScores.set(p.id, (1 - damping) / N);
3271
+ for (const p of lmPosts) {
3272
+ const entry = postMap.get(p.id);
3273
+ const outCount = entry.outbound_links.length;
3274
+ if (outCount > 0) {
3275
+ const share = (damping * scores.get(p.id)) / outCount;
3276
+ for (const link of entry.outbound_links) {
3277
+ newScores.set(link.target_id, (newScores.get(link.target_id) || 0) + share);
3278
+ }
3279
+ }
3280
+ }
3281
+ scores = newScores;
3282
+ }
3283
+
3284
+ // Normalize to 0-100
3285
+ let maxScore = 0;
3286
+ for (const s of scores.values()) { if (s > maxScore) maxScore = s; }
3287
+ const normalizedScores = new Map();
3288
+ for (const [id, s] of scores) {
3289
+ normalizedScores.set(id, maxScore > 0 ? Math.round((s / maxScore) * 100 * 10) / 10 : 0);
3290
+ }
3291
+
3292
+ // Build result array
3293
+ const lmResults = [];
3294
+ for (const [id, entry] of postMap) {
3295
+ lmResults.push({
3296
+ id,
3297
+ title: entry.title,
3298
+ slug: entry.slug,
3299
+ link: entry.link,
3300
+ outbound_count: entry.outbound_links.length,
3301
+ inbound_count: entry.inbound_count,
3302
+ pagerank_score: normalizedScores.get(id) || 0,
3303
+ is_orphan: entry.inbound_count === 0,
3304
+ outbound_links: entry.outbound_links,
3305
+ unresolved_links: entry.unresolved_links
3306
+ });
3307
+ }
3308
+
3309
+ lmResults.sort((a, b) => b.pagerank_score - a.pagerank_score);
3310
+
3311
+ const orphanCount = lmResults.filter(r => r.is_orphan).length;
3312
+ result = json({
3313
+ total_analyzed: lmPosts.length,
3314
+ total_internal_links: totalLinks,
3315
+ avg_outbound_per_post: lmPosts.length > 0 ? Math.round(totalLinks / lmPosts.length * 10) / 10 : 0,
3316
+ orphan_posts: orphanCount,
3317
+ posts: lmResults,
3318
+ link_matrix: linkMatrix
3319
+ });
3320
+ auditLog({ tool: name, action: 'build_link_map', status: 'success', latency_ms: Date.now() - t0, params: { post_type: lmPostType, limit: lmLimit, category_id: lmCatId } });
3321
+ break;
3322
+ }
3323
+
3324
+ // ── wp_audit_anchor_texts ──
3325
+ case 'wp_audit_anchor_texts': {
3326
+ validateInput(args, {
3327
+ limit: { type: 'number', min: 1, max: 200 },
3328
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] }
3329
+ });
3330
+ const { limit: aatLimit = 50, post_type: aatPostType = 'post' } = args;
3331
+ const { url: aatSiteUrl } = getActiveAuth();
3332
+ const aatPerPage = Math.min(aatLimit, 200);
3333
+ const aatFields = '_fields=id,title,slug,link,content';
3334
+
3335
+ let aatPosts = [];
3336
+ if (aatPostType === 'both') {
3337
+ const [posts, pages] = await Promise.all([
3338
+ wpApiCall(`/posts?per_page=${aatPerPage}&status=publish&${aatFields}`),
3339
+ wpApiCall(`/pages?per_page=${aatPerPage}&status=publish&${aatFields}`)
3340
+ ]);
3341
+ aatPosts = [...posts, ...pages];
3342
+ } else {
3343
+ const ep = aatPostType === 'page' ? '/pages' : '/posts';
3344
+ aatPosts = await wpApiCall(`${ep}?per_page=${aatPerPage}&status=publish&${aatFields}`);
3345
+ }
3346
+
3347
+ const GENERIC_ANCHORS = ['cliquez ici', 'click here', 'lire la suite', 'read more', 'en savoir plus', 'learn more', 'ici', 'here', 'lien', 'link', 'voir', 'see', 'plus', 'more', 'article', 'page', 'ce lien', 'this link', 'cet article', 'this article'];
3348
+
3349
+ // Corpus-wide anchor map: anchor_text_lower → { count, posts: Set, targets: Set }
3350
+ const anchorMap = new Map();
3351
+ const postAnchors = new Map(); // postId → { anchors: [{text,type}], total, unique }
3352
+
3353
+ let totalInternalLinks = 0;
3354
+
3355
+ for (const p of aatPosts) {
3356
+ const html = p.content?.rendered || '';
3357
+ const links = extractInternalLinks(html, aatSiteUrl);
3358
+ const postAnchorList = [];
3359
+
3360
+ for (const link of links) {
3361
+ const text = (link.anchor_text || '').trim();
3362
+ const lower = text.toLowerCase();
3363
+ totalInternalLinks++;
3364
+
3365
+ postAnchorList.push({ text, lower, href: link.url });
3366
+
3367
+ if (!anchorMap.has(lower)) {
3368
+ anchorMap.set(lower, { count: 0, posts: new Set(), targets: new Set() });
3369
+ }
3370
+ const entry = anchorMap.get(lower);
3371
+ entry.count++;
3372
+ entry.posts.add(p.id);
3373
+ entry.targets.add(link.url);
3374
+ }
3375
+
3376
+ postAnchors.set(p.id, postAnchorList);
3377
+ }
3378
+
3379
+ // Classify each anchor
3380
+ const anchorHealth = { healthy: 0, generic: 0, over_optimized: 0, image_link: 0 };
3381
+ const genericAnchorsMap = new Map(); // text → { count, post_ids }
3382
+ const overOptimized = [];
3383
+
3384
+ for (const [lower, entry] of anchorMap) {
3385
+ if (lower === '' || /^\s*$/.test(lower)) {
3386
+ anchorHealth.image_link += entry.count;
3387
+ } else if (GENERIC_ANCHORS.includes(lower)) {
3388
+ anchorHealth.generic += entry.count;
3389
+ genericAnchorsMap.set(lower, { text: lower, count: entry.count, post_ids: [...entry.posts] });
3390
+ } else if (entry.count > 3 && entry.targets.size > 1) {
3391
+ anchorHealth.over_optimized += entry.count;
3392
+ overOptimized.push({ text: lower, count: entry.count, target_count: entry.targets.size, post_ids: [...entry.posts] });
3393
+ } else {
3394
+ anchorHealth.healthy += entry.count;
3395
+ }
3396
+ }
3397
+
3398
+ // Top 10 generic anchors sorted by count DESC
3399
+ const genericAnchors = [...genericAnchorsMap.values()].sort((a, b) => b.count - a.count).slice(0, 10);
3400
+
3401
+ // Per-post results
3402
+ const aatResults = [];
3403
+ for (const p of aatPosts) {
3404
+ const anchors = postAnchors.get(p.id) || [];
3405
+ const total = anchors.length;
3406
+ const uniqueTexts = new Set(anchors.map(a => a.lower));
3407
+ const unique = uniqueTexts.size;
3408
+ const ds = total > 0 ? unique / total : 1;
3409
+
3410
+ const issues = [];
3411
+ const hasGeneric = anchors.some(a => GENERIC_ANCHORS.includes(a.lower));
3412
+ const hasOverOpt = anchors.some(a => {
3413
+ const e = anchorMap.get(a.lower);
3414
+ return e && e.count > 3 && e.targets.size > 1 && a.lower !== '' && !GENERIC_ANCHORS.includes(a.lower);
3415
+ });
3416
+ const hasImageLink = anchors.some(a => a.lower === '' || /^\s*$/.test(a.lower));
3417
+ if (hasGeneric) issues.push('has_generic_anchors');
3418
+ if (hasOverOpt) issues.push('has_over_optimized_anchors');
3419
+ if (hasImageLink) issues.push('has_image_links');
3420
+ if (total > 0 && ds < 0.5) issues.push('low_anchor_diversity');
3421
+
3422
+ aatResults.push({
3423
+ id: p.id,
3424
+ title: strip(p.title?.rendered || ''),
3425
+ slug: p.slug,
3426
+ internal_links_count: total,
3427
+ unique_anchors_count: unique,
3428
+ diversity_score: Math.round(ds * 100) / 100,
3429
+ issues
3430
+ });
3431
+ }
3432
+
3433
+ aatResults.sort((a, b) => a.diversity_score - b.diversity_score);
3434
+
3435
+ result = json({
3436
+ total_analyzed: aatPosts.length,
3437
+ total_internal_links: totalInternalLinks,
3438
+ total_unique_anchors: anchorMap.size,
3439
+ anchor_health: anchorHealth,
3440
+ generic_anchors: genericAnchors,
3441
+ over_optimized_anchors: overOptimized,
3442
+ posts: aatResults
3443
+ });
3444
+ auditLog({ tool: name, action: 'audit_anchor_texts', status: 'success', latency_ms: Date.now() - t0, params: { limit: aatLimit, post_type: aatPostType } });
3445
+ break;
3446
+ }
3447
+
3448
+ // ── wp_audit_schema_markup ──
3449
+ case 'wp_audit_schema_markup': {
3450
+ validateInput(args, {
3451
+ limit: { type: 'number', min: 1, max: 200 },
3452
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] }
3453
+ });
3454
+ const { limit: asmLimit = 50, post_type: asmPostType = 'post' } = args;
3455
+ const asmPerPage = Math.min(asmLimit, 200);
3456
+ const asmFields = '_fields=id,title,slug,link,content';
3457
+
3458
+ let asmPosts = [];
3459
+ if (asmPostType === 'both') {
3460
+ const [posts, pages] = await Promise.all([
3461
+ wpApiCall(`/posts?per_page=${asmPerPage}&status=publish&${asmFields}`),
3462
+ wpApiCall(`/pages?per_page=${asmPerPage}&status=publish&${asmFields}`)
3463
+ ]);
3464
+ asmPosts = [...posts, ...pages];
3465
+ } else {
3466
+ const ep = asmPostType === 'page' ? '/pages' : '/posts';
3467
+ asmPosts = await wpApiCall(`${ep}?per_page=${asmPerPage}&status=publish&${asmFields}`);
3468
+ }
3469
+
3470
+ const SCHEMA_REQUIRED_FIELDS = {
3471
+ 'Article': ['headline', 'datePublished', 'author'],
3472
+ 'NewsArticle': ['headline', 'datePublished', 'author'],
3473
+ 'BlogPosting': ['headline', 'datePublished', 'author'],
3474
+ 'FAQPage': ['mainEntity'],
3475
+ 'HowTo': ['name', 'step'],
3476
+ 'LocalBusiness': ['name', 'address'],
3477
+ 'BreadcrumbList': ['itemListElement'],
3478
+ 'Organization': ['name'],
3479
+ 'WebPage': ['name']
3480
+ };
3481
+ const ARTICLE_TYPES = ['Article', 'NewsArticle', 'BlogPosting'];
3482
+
3483
+ const typeDist = {};
3484
+ let totalSchemas = 0;
3485
+ let validCount = 0;
3486
+ let invalidCount = 0;
3487
+ let postsWithSchema = 0;
3488
+ let postsWithout = 0;
3489
+
3490
+ const ldJsonRegex = /<script\s+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi;
3491
+
3492
+ const asmResults = [];
3493
+ for (const p of asmPosts) {
3494
+ const html = p.content?.rendered || '';
3495
+ const schemas = [];
3496
+ const issues = [];
3497
+ let hasInvalidJson = false;
3498
+ let hasArticleSchema = false;
3499
+
3500
+ let ldMatch;
3501
+ ldJsonRegex.lastIndex = 0;
3502
+ while ((ldMatch = ldJsonRegex.exec(html)) !== null) {
3503
+ const raw = ldMatch[1].trim();
3504
+ let parsed;
3505
+ try {
3506
+ parsed = JSON.parse(raw);
3507
+ } catch {
3508
+ schemas.push({ type: 'unknown', valid: false, missing_fields: [], raw_type: 'parse_error' });
3509
+ hasInvalidJson = true;
3510
+ invalidCount++;
3511
+ totalSchemas++;
3512
+ continue;
3513
+ }
3514
+
3515
+ const types = Array.isArray(parsed['@type']) ? parsed['@type'] : [parsed['@type'] || 'unknown'];
3516
+ for (const t of types) {
3517
+ const required = SCHEMA_REQUIRED_FIELDS[t];
3518
+ if (ARTICLE_TYPES.includes(t)) hasArticleSchema = true;
3519
+
3520
+ if (required) {
3521
+ const missing = required.filter(f => {
3522
+ const val = parsed[f];
3523
+ if (val === undefined || val === null) return true;
3524
+ if (Array.isArray(val) && val.length === 0) return true;
3525
+ return false;
3526
+ });
3527
+ const isValid = missing.length === 0;
3528
+ schemas.push({ type: t, valid: isValid, missing_fields: missing, raw_type: t });
3529
+ if (isValid) validCount++; else invalidCount++;
3530
+ if (!isValid) issues.push('missing_required_fields');
3531
+ typeDist[t] = (typeDist[t] || 0) + 1;
3532
+ } else {
3533
+ schemas.push({ type: t, valid: true, missing_fields: [], raw_type: t });
3534
+ validCount++;
3535
+ typeDist['other'] = (typeDist['other'] || 0) + 1;
3536
+ }
3537
+ totalSchemas++;
3538
+ }
3539
+ }
3540
+
3541
+ if (schemas.length === 0) {
3542
+ issues.push('no_schema');
3543
+ postsWithout++;
3544
+ } else {
3545
+ postsWithSchema++;
3546
+ }
3547
+ if (hasInvalidJson) issues.push('invalid_json');
3548
+ if (!hasArticleSchema && schemas.length > 0) issues.push('no_article_schema');
3549
+
3550
+ asmResults.push({
3551
+ id: p.id,
3552
+ title: strip(p.title?.rendered || ''),
3553
+ slug: p.slug,
3554
+ link: p.link,
3555
+ schemas_found: schemas.length,
3556
+ schemas,
3557
+ issues
3558
+ });
3559
+ }
3560
+
3561
+ // Sort: posts with issues first, by issue count DESC
3562
+ asmResults.sort((a, b) => b.issues.length - a.issues.length);
3563
+
3564
+ result = json({
3565
+ total_analyzed: asmPosts.length,
3566
+ posts_with_schema: postsWithSchema,
3567
+ posts_without_schema: postsWithout,
3568
+ schema_type_distribution: typeDist,
3569
+ total_schemas_found: totalSchemas,
3570
+ total_valid: validCount,
3571
+ total_invalid: invalidCount,
3572
+ posts: asmResults
3573
+ });
3574
+ auditLog({ tool: name, action: 'audit_schema_markup', status: 'success', latency_ms: Date.now() - t0, params: { limit: asmLimit, post_type: asmPostType } });
3575
+ break;
3576
+ }
3577
+
3578
+ // ── wp_audit_content_structure ──
3579
+ case 'wp_audit_content_structure': {
3580
+ validateInput(args, {
3581
+ limit: { type: 'number', min: 1, max: 200 },
3582
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] },
3583
+ category_id: { type: 'number' }
3584
+ });
3585
+ const { limit: acsLimit = 50, post_type: acsPostType = 'post', category_id: acsCatId } = args;
3586
+ const acsPerPage = Math.min(acsLimit, 200);
3587
+ const acsFields = '_fields=id,title,slug,link,content,categories';
3588
+
3589
+ let acsPosts = [];
3590
+ if (acsPostType === 'both') {
3591
+ let postsUrl = `/posts?per_page=${acsPerPage}&status=publish&${acsFields}`;
3592
+ if (acsCatId) postsUrl += `&categories=${acsCatId}`;
3593
+ const [posts, pages] = await Promise.all([
3594
+ wpApiCall(postsUrl),
3595
+ wpApiCall(`/pages?per_page=${acsPerPage}&status=publish&${acsFields}`)
3596
+ ]);
3597
+ acsPosts = [...posts, ...pages];
3598
+ } else {
3599
+ const ep = acsPostType === 'page' ? '/pages' : '/posts';
3600
+ let postsUrl = `${ep}?per_page=${acsPerPage}&status=publish&${acsFields}`;
3601
+ if (acsCatId && acsPostType !== 'page') postsUrl += `&categories=${acsCatId}`;
3602
+ acsPosts = await wpApiCall(postsUrl);
3603
+ }
3604
+
3605
+ let totalScore = 0;
3606
+ const distribution = { excellent: 0, good: 0, average: 0, poor: 0 };
3607
+ const featureCounts = { intro: 0, conclusion: 0, faq: 0, toc: 0, lists: 0, tables: 0, images: 0, blockquotes: 0 };
3608
+
3609
+ const acsResults = [];
3610
+ for (const p of acsPosts) {
3611
+ const html = p.content?.rendered || '';
3612
+ const sections = detectContentSections(html);
3613
+ const wc = countWords(html);
3614
+
3615
+ // Paragraphs count (non-empty <p>)
3616
+ const pMatches = html.match(/<p[^>]*>(?!\s*<\/p>)/gi) || [];
3617
+ const paragraphsCount = pMatches.length || 1;
3618
+ const avgParagraphLength = Math.round(wc / paragraphsCount);
3619
+
3620
+ // TOC detection
3621
+ const hasToc = /<[^>]+(?:id|class)=["'][^"']*(?:toc|table-of-contents|table-des-matieres)[^"']*["'][^>]*>/i.test(html);
3622
+
3623
+ // Blockquotes and code blocks
3624
+ const blockquotesCount = (html.match(/<blockquote\b/gi) || []).length;
3625
+ const codeBlocksCount = (html.match(/<(?:pre|code)\b/gi) || []).length;
3626
+
3627
+ // Heading density: headings per 300 words
3628
+ const headingDensity = wc > 0 ? sections.headings_count / (wc / 300) : 0;
3629
+
3630
+ // Structure score (0-100)
3631
+ let score = 0;
3632
+ if (sections.has_intro) score += 15;
3633
+ if (sections.has_conclusion) score += 10;
3634
+ if (sections.headings_count >= 3) score += 15;
3635
+ if (headingDensity >= 0.5 && headingDensity <= 2.0) score += 10;
3636
+ if (sections.lists_count >= 1) score += 10;
3637
+ if (sections.images_count >= 1) score += 10;
3638
+ if (sections.has_faq) score += 10;
3639
+ if (sections.tables_count >= 1) score += 5;
3640
+ if (hasToc) score += 5;
3641
+ if (blockquotesCount > 0 || codeBlocksCount > 0) score += 5;
3642
+ if (avgParagraphLength < 100) score += 5;
3643
+
3644
+ totalScore += score;
3645
+
3646
+ if (score >= 80) distribution.excellent++;
3647
+ else if (score >= 60) distribution.good++;
3648
+ else if (score >= 40) distribution.average++;
3649
+ else distribution.poor++;
3650
+
3651
+ // Feature coverage tracking
3652
+ if (sections.has_intro) featureCounts.intro++;
3653
+ if (sections.has_conclusion) featureCounts.conclusion++;
3654
+ if (sections.has_faq) featureCounts.faq++;
3655
+ if (hasToc) featureCounts.toc++;
3656
+ if (sections.lists_count >= 1) featureCounts.lists++;
3657
+ if (sections.tables_count >= 1) featureCounts.tables++;
3658
+ if (sections.images_count >= 1) featureCounts.images++;
3659
+ if (blockquotesCount > 0) featureCounts.blockquotes++;
3660
+
3661
+ // Issues
3662
+ const issues = [];
3663
+ if (!sections.has_intro) issues.push('no_intro');
3664
+ if (!sections.has_conclusion) issues.push('no_conclusion');
3665
+ if (sections.headings_count === 0) issues.push('no_headings');
3666
+ if (headingDensity < 0.3 && wc > 100) issues.push('low_heading_density');
3667
+ if (headingDensity > 3.0) issues.push('high_heading_density');
3668
+ if (sections.images_count === 0) issues.push('no_images');
3669
+ if (sections.lists_count === 0) issues.push('no_lists');
3670
+ if (avgParagraphLength > 150) issues.push('long_paragraphs');
3671
+ if (score < 40) issues.push('poor_structure');
3672
+
3673
+ acsResults.push({
3674
+ id: p.id,
3675
+ title: strip(p.title?.rendered || ''),
3676
+ slug: p.slug,
3677
+ link: p.link,
3678
+ word_count: wc,
3679
+ structure_score: score,
3680
+ features: {
3681
+ has_intro: sections.has_intro,
3682
+ has_conclusion: sections.has_conclusion,
3683
+ has_faq: sections.has_faq,
3684
+ has_toc: hasToc,
3685
+ headings_count: sections.headings_count,
3686
+ lists_count: sections.lists_count,
3687
+ tables_count: sections.tables_count,
3688
+ images_count: sections.images_count,
3689
+ paragraphs_count: paragraphsCount,
3690
+ avg_paragraph_length: avgParagraphLength,
3691
+ blockquotes_count: blockquotesCount,
3692
+ code_blocks_count: codeBlocksCount,
3693
+ heading_density: Math.round(headingDensity * 100) / 100
3694
+ },
3695
+ issues
3696
+ });
3697
+ }
3698
+
3699
+ acsResults.sort((a, b) => a.structure_score - b.structure_score);
3700
+
3701
+ const acsTotal = acsPosts.length;
3702
+ const featureCoverage = {};
3703
+ for (const [key, count] of Object.entries(featureCounts)) {
3704
+ featureCoverage[key] = acsTotal > 0 ? Math.round(count / acsTotal * 100) : 0;
3705
+ }
3706
+
3707
+ result = json({
3708
+ total_analyzed: acsTotal,
3709
+ avg_structure_score: acsTotal > 0 ? Math.round(totalScore / acsTotal * 10) / 10 : 0,
3710
+ distribution,
3711
+ feature_coverage: featureCoverage,
3712
+ posts: acsResults
3713
+ });
3714
+ auditLog({ tool: name, action: 'audit_content_structure', status: 'success', latency_ms: Date.now() - t0, params: { limit: acsLimit, post_type: acsPostType, category_id: acsCatId } });
3715
+ break;
3716
+ }
3717
+
3718
+ // ── wp_find_duplicate_content ──
3719
+ case 'wp_find_duplicate_content': {
3720
+ validateInput(args, {
3721
+ limit: { type: 'number', min: 1, max: 100 },
3722
+ post_type: { type: 'string', enum: ['post', 'page'] },
3723
+ category_id: { type: 'number' },
3724
+ similarity_threshold: { type: 'number', min: 0, max: 1 }
3725
+ });
3726
+ const { limit: fdcLimit = 50, post_type: fdcPostType = 'post', category_id: fdcCatId, similarity_threshold: fdcThreshold = 0.7 } = args;
3727
+ const fdcPerPage = Math.min(fdcLimit, 100);
3728
+ const fdcFields = '_fields=id,title,content,slug,link';
3729
+
3730
+ const fdcEp = fdcPostType === 'page' ? '/pages' : '/posts';
3731
+ let fdcUrl = `${fdcEp}?per_page=${fdcPerPage}&status=publish&${fdcFields}`;
3732
+ if (fdcCatId && fdcPostType !== 'page') fdcUrl += `&categories=${fdcCatId}`;
3733
+
3734
+ const fdcPosts = await wpApiCall(fdcUrl);
3735
+
3736
+ const fdcDocs = [];
3737
+ const fdcPostMap = new Map();
3738
+ for (const p of fdcPosts) {
3739
+ const text = strip(p.content?.rendered || '');
3740
+ const wc = countWords(p.content?.rendered || '');
3741
+ fdcPostMap.set(p.id, { id: p.id, title: strip(p.title?.rendered || ''), slug: p.slug, word_count: wc });
3742
+ if (wc >= 50) {
3743
+ fdcDocs.push({ id: p.id, title: strip(p.title?.rendered || ''), text });
3744
+ }
3745
+ }
3746
+
3747
+ const fdcPairs = findDuplicatePairs(fdcDocs, fdcThreshold);
3748
+
3749
+ const formattedPairs = fdcPairs
3750
+ .sort((a, b) => b.similarity - a.similarity)
3751
+ .map(pair => {
3752
+ const p1 = fdcPostMap.get(pair.doc1_id);
3753
+ const p2 = fdcPostMap.get(pair.doc2_id);
3754
+ const sim = Math.round(pair.similarity * 1000) / 1000;
3755
+ return {
3756
+ post1: { id: p1.id, title: p1.title, slug: p1.slug, word_count: p1.word_count },
3757
+ post2: { id: p2.id, title: p2.title, slug: p2.slug, word_count: p2.word_count },
3758
+ similarity: sim,
3759
+ severity: sim >= 0.9 ? 'critical' : sim >= 0.8 ? 'high' : 'medium'
3760
+ };
3761
+ });
3762
+
3763
+ // Union-find clustering
3764
+ const ufParent = new Map();
3765
+ const ufFind = (x) => {
3766
+ if (!ufParent.has(x)) ufParent.set(x, x);
3767
+ if (ufParent.get(x) !== x) ufParent.set(x, ufFind(ufParent.get(x)));
3768
+ return ufParent.get(x);
3769
+ };
3770
+ const ufUnion = (a, b) => { ufParent.set(ufFind(a), ufFind(b)); };
3771
+
3772
+ for (const pair of fdcPairs) ufUnion(pair.doc1_id, pair.doc2_id);
3773
+
3774
+ const clusterMap = new Map();
3775
+ const idsInPairs = new Set();
3776
+ for (const pair of fdcPairs) { idsInPairs.add(pair.doc1_id); idsInPairs.add(pair.doc2_id); }
3777
+ for (const id of idsInPairs) {
3778
+ const root = ufFind(id);
3779
+ if (!clusterMap.has(root)) clusterMap.set(root, { posts: [], maxSim: 0 });
3780
+ const info = fdcPostMap.get(id);
3781
+ clusterMap.get(root).posts.push({ id: info.id, title: info.title, slug: info.slug });
3782
+ }
3783
+ for (const pair of fdcPairs) {
3784
+ const root = ufFind(pair.doc1_id);
3785
+ const cluster = clusterMap.get(root);
3786
+ if (pair.similarity > cluster.maxSim) cluster.maxSim = pair.similarity;
3787
+ }
3788
+
3789
+ let fdcClusterId = 0;
3790
+ const clusters = [...clusterMap.values()].map(c => ({
3791
+ cluster_id: ++fdcClusterId,
3792
+ posts: c.posts,
3793
+ max_similarity: Math.round(c.maxSim * 1000) / 1000
3794
+ }));
3795
+
3796
+ result = json({
3797
+ total_analyzed: fdcPosts.length,
3798
+ similarity_threshold: fdcThreshold,
3799
+ duplicate_pairs_found: formattedPairs.length,
3800
+ duplicate_clusters: clusters.length,
3801
+ pairs: formattedPairs,
3802
+ clusters
3803
+ });
3804
+ auditLog({ tool: name, action: 'find_duplicate_content', status: 'success', latency_ms: Date.now() - t0, params: { limit: fdcLimit, post_type: fdcPostType, category_id: fdcCatId, similarity_threshold: fdcThreshold } });
3805
+ break;
3806
+ }
3807
+
3808
+ // ── wp_find_content_gaps ──
3809
+ case 'wp_find_content_gaps': {
3810
+ validateInput(args, {
3811
+ min_posts: { type: 'number', min: 1, max: 50 },
3812
+ taxonomy: { type: 'string', enum: ['category', 'post_tag', 'both'] },
3813
+ exclude_empty: { type: 'boolean' }
3814
+ });
3815
+ const { min_posts: fcgMinPosts = 3, taxonomy: fcgTaxonomy = 'both', exclude_empty: fcgExcludeEmpty = false } = args;
3816
+
3817
+ let fcgCategories = [];
3818
+ let fcgTags = [];
3819
+
3820
+ if (fcgTaxonomy === 'category' || fcgTaxonomy === 'both') {
3821
+ fcgCategories = await wpApiCall('/categories?per_page=100&_fields=id,name,slug,count,description,parent');
3822
+ }
3823
+ if (fcgTaxonomy === 'post_tag' || fcgTaxonomy === 'both') {
3824
+ fcgTags = await wpApiCall('/tags?per_page=100&_fields=id,name,slug,count');
3825
+ }
3826
+
3827
+ const catMap = new Map();
3828
+ for (const c of fcgCategories) catMap.set(c.id, c);
3829
+
3830
+ const fcgGaps = [];
3831
+ const fcgWellCovered = [];
3832
+
3833
+ for (const c of fcgCategories) {
3834
+ if (fcgExcludeEmpty && c.count === 0) continue;
3835
+ if (c.count < fcgMinPosts) {
3836
+ const parentInfo = c.parent ? catMap.get(c.parent) : null;
3837
+ fcgGaps.push({
3838
+ taxonomy: 'category', id: c.id, name: c.name, slug: c.slug,
3839
+ current_count: c.count, deficit: fcgMinPosts - c.count,
3840
+ parent_name: parentInfo ? parentInfo.name : null,
3841
+ parent_count: parentInfo ? parentInfo.count : null,
3842
+ severity: c.count === 0 ? 'empty' : 'underrepresented',
3843
+ suggestion: c.count === 0
3844
+ ? `Create ${fcgMinPosts} posts for "${c.name}"`
3845
+ : `Add ${fcgMinPosts - c.count} more posts for "${c.name}"`
3846
+ });
3847
+ } else {
3848
+ fcgWellCovered.push({ taxonomy: 'category', id: c.id, name: c.name, count: c.count });
3849
+ }
3850
+ }
3851
+
3852
+ for (const t of fcgTags) {
3853
+ if (fcgExcludeEmpty && t.count === 0) continue;
3854
+ if (t.count < fcgMinPosts) {
3855
+ fcgGaps.push({
3856
+ taxonomy: 'post_tag', id: t.id, name: t.name, slug: t.slug,
3857
+ current_count: t.count, deficit: fcgMinPosts - t.count,
3858
+ parent_name: null, parent_count: null,
3859
+ severity: t.count === 0 ? 'empty' : 'underrepresented',
3860
+ suggestion: t.count === 0
3861
+ ? `Create ${fcgMinPosts} posts for "${t.name}"`
3862
+ : `Add ${fcgMinPosts - t.count} more posts for "${t.name}"`
3863
+ });
3864
+ } else {
3865
+ fcgWellCovered.push({ taxonomy: 'post_tag', id: t.id, name: t.name, count: t.count });
3866
+ }
3867
+ }
3868
+
3869
+ fcgGaps.sort((a, b) => b.deficit - a.deficit || a.current_count - b.current_count);
3870
+ fcgWellCovered.sort((a, b) => b.count - a.count);
3871
+
3872
+ const catGaps = fcgGaps.filter(g => g.taxonomy === 'category');
3873
+ const tagGaps = fcgGaps.filter(g => g.taxonomy === 'post_tag');
3874
+
3875
+ result = json({
3876
+ min_posts_threshold: fcgMinPosts,
3877
+ total_terms_analyzed: fcgCategories.length + fcgTags.length,
3878
+ gaps_found: fcgGaps.length,
3879
+ gaps_by_taxonomy: { categories: catGaps.length, tags: tagGaps.length },
3880
+ gaps: fcgGaps,
3881
+ well_covered: fcgWellCovered.slice(0, 10)
3882
+ });
3883
+ auditLog({ tool: name, action: 'find_content_gaps', status: 'success', latency_ms: Date.now() - t0, params: { min_posts: fcgMinPosts, taxonomy: fcgTaxonomy, exclude_empty: fcgExcludeEmpty } });
3884
+ break;
3885
+ }
3886
+
3887
+ // ── wp_extract_faq_blocks ──
3888
+ case 'wp_extract_faq_blocks': {
3889
+ validateInput(args, {
3890
+ limit: { type: 'number', min: 1, max: 200 },
3891
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] }
3892
+ });
3893
+ const { limit: efbLimit = 50, post_type: efbPostType = 'post' } = args;
3894
+ const efbPerPage = Math.min(efbLimit, 200);
3895
+ const efbFields = '_fields=id,title,slug,link,content';
3896
+
3897
+ let efbPosts = [];
3898
+ if (efbPostType === 'both') {
3899
+ const [posts, pages] = await Promise.all([
3900
+ wpApiCall(`/posts?per_page=${efbPerPage}&status=publish&${efbFields}`),
3901
+ wpApiCall(`/pages?per_page=${efbPerPage}&status=publish&${efbFields}`)
3902
+ ]);
3903
+ efbPosts = [...posts, ...pages];
3904
+ } else {
3905
+ const ep = efbPostType === 'page' ? '/pages' : '/posts';
3906
+ efbPosts = await wpApiCall(`${ep}?per_page=${efbPerPage}&status=publish&${efbFields}`);
3907
+ }
3908
+
3909
+ const efbLdRegex = /<script\s+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi;
3910
+ const efbYoastRegex = /<!-- wp:yoast\/faq-block -->([\s\S]*?)<!-- \/wp:yoast\/faq-block -->/gi;
3911
+ const efbRankMathRegex = /<!-- wp:rank-math\/faq-block -->([\s\S]*?)<!-- \/wp:rank-math\/faq-block -->/gi;
3912
+ const efbFaqHeadingRegex = /<h[2-4][^>]*>[^<]*(?:FAQ|Questions fréquentes|Questions courantes|Foire aux questions)[^<]*<\/h[2-4]>/gi;
3913
+
3914
+ let efbTotalQ = 0;
3915
+ let efbPostsWithFaq = 0;
3916
+ const efbBySource = { 'json-ld': 0, 'gutenberg-block': 0, 'html-pattern': 0 };
3917
+
3918
+ const efbResults = [];
3919
+ for (const p of efbPosts) {
3920
+ const html = p.content?.rendered || '';
3921
+ const faqBlocks = [];
3922
+
3923
+ // Type A: JSON-LD FAQPage
3924
+ efbLdRegex.lastIndex = 0;
3925
+ let ldMatch;
3926
+ while ((ldMatch = efbLdRegex.exec(html)) !== null) {
3927
+ try {
3928
+ const parsed = JSON.parse(ldMatch[1].trim());
3929
+ const pType = Array.isArray(parsed['@type']) ? parsed['@type'] : [parsed['@type']];
3930
+ if (pType.includes('FAQPage') && Array.isArray(parsed.mainEntity)) {
3931
+ const questions = parsed.mainEntity
3932
+ .filter(q => q['@type'] === 'Question' && q.name)
3933
+ .map(q => ({ question: q.name, answer: (q.acceptedAnswer?.text || '').slice(0, 200) }));
3934
+ if (questions.length > 0) {
3935
+ faqBlocks.push({ source: 'json-ld', plugin: null, questions_count: questions.length, questions });
3936
+ efbBySource['json-ld'] += questions.length;
3937
+ efbTotalQ += questions.length;
3938
+ }
3939
+ }
3940
+ } catch { /* invalid JSON */ }
3941
+ }
3942
+
3943
+ // Type B: Gutenberg FAQ blocks
3944
+ const processGutenberg = (regex, plugin) => {
3945
+ regex.lastIndex = 0;
3946
+ let gMatch;
3947
+ while ((gMatch = regex.exec(html)) !== null) {
3948
+ const blockHtml = gMatch[1];
3949
+ const questions = [];
3950
+ const qRegex = /<(?:strong|h3)[^>]*class=["'][^"']*faq-question[^"']*["'][^>]*>([\s\S]*?)<\/(?:strong|h3)>/gi;
3951
+ const aRegex = /<(?:p|div)[^>]*class=["'][^"']*faq-answer[^"']*["'][^>]*>([\s\S]*?)<\/(?:p|div)>/gi;
3952
+ const qs = [];
3953
+ const as = [];
3954
+ let qm;
3955
+ while ((qm = qRegex.exec(blockHtml)) !== null) qs.push(strip(qm[1]));
3956
+ let am;
3957
+ while ((am = aRegex.exec(blockHtml)) !== null) as.push(strip(am[1]).slice(0, 200));
3958
+ for (let i = 0; i < qs.length; i++) {
3959
+ questions.push({ question: qs[i], answer: as[i] || '' });
3960
+ }
3961
+ if (questions.length > 0) {
3962
+ faqBlocks.push({ source: 'gutenberg-block', plugin, questions_count: questions.length, questions });
3963
+ efbBySource['gutenberg-block'] += questions.length;
3964
+ efbTotalQ += questions.length;
3965
+ }
3966
+ }
3967
+ };
3968
+ processGutenberg(efbYoastRegex, 'yoast');
3969
+ processGutenberg(efbRankMathRegex, 'rankmath');
3970
+
3971
+ // Type C: HTML pattern FAQ
3972
+ efbFaqHeadingRegex.lastIndex = 0;
3973
+ if (efbFaqHeadingRegex.test(html)) {
3974
+ const questions = [];
3975
+ const h3pRegex = /<h3[^>]*>([\s\S]*?)<\/h3>\s*<p[^>]*>([\s\S]*?)<\/p>/gi;
3976
+ const dtddRegex = /<dt[^>]*>([\s\S]*?)<\/dt>\s*<dd[^>]*>([\s\S]*?)<\/dd>/gi;
3977
+ let hm;
3978
+ while ((hm = h3pRegex.exec(html)) !== null) {
3979
+ const q = strip(hm[1]);
3980
+ if (q) questions.push({ question: q, answer: strip(hm[2]).slice(0, 200) });
3981
+ }
3982
+ if (questions.length === 0) {
3983
+ while ((hm = dtddRegex.exec(html)) !== null) {
3984
+ const q = strip(hm[1]);
3985
+ if (q) questions.push({ question: q, answer: strip(hm[2]).slice(0, 200) });
3986
+ }
3987
+ }
3988
+ if (questions.length > 0) {
3989
+ faqBlocks.push({ source: 'html-pattern', plugin: null, questions_count: questions.length, questions });
3990
+ efbBySource['html-pattern'] += questions.length;
3991
+ efbTotalQ += questions.length;
3992
+ }
3993
+ }
3994
+
3995
+ const hasFaq = faqBlocks.length > 0;
3996
+ if (hasFaq) efbPostsWithFaq++;
3997
+
3998
+ efbResults.push({
3999
+ id: p.id, title: strip(p.title?.rendered || ''), slug: p.slug, link: p.link,
4000
+ has_faq: hasFaq, faq_blocks: faqBlocks
4001
+ });
4002
+ }
4003
+
4004
+ let efbFiltered = efbPosts.length <= 10
4005
+ ? efbResults
4006
+ : efbResults.filter(r => r.has_faq);
4007
+
4008
+ efbFiltered.sort((a, b) => {
4009
+ const qA = a.faq_blocks.reduce((s, f) => s + f.questions_count, 0);
4010
+ const qB = b.faq_blocks.reduce((s, f) => s + f.questions_count, 0);
4011
+ return qB - qA;
4012
+ });
4013
+
4014
+ result = json({
4015
+ total_analyzed: efbPosts.length,
4016
+ posts_with_faq: efbPostsWithFaq,
4017
+ total_questions: efbTotalQ,
4018
+ faq_by_source: efbBySource,
4019
+ posts: efbFiltered
4020
+ });
4021
+ auditLog({ tool: name, action: 'extract_faq_blocks', status: 'success', latency_ms: Date.now() - t0, params: { limit: efbLimit, post_type: efbPostType } });
4022
+ break;
4023
+ }
4024
+
4025
+ // ── wp_audit_cta_presence ──
4026
+ case 'wp_audit_cta_presence': {
4027
+ validateInput(args, {
4028
+ limit: { type: 'number', min: 1, max: 200 },
4029
+ post_type: { type: 'string', enum: ['post', 'page', 'both'] },
4030
+ category_id: { type: 'number' }
4031
+ });
4032
+ const { limit: acpLimit = 50, post_type: acpPostType = 'post', category_id: acpCatId } = args;
4033
+ const acpPerPage = Math.min(acpLimit, 200);
4034
+ const acpFields = '_fields=id,title,slug,link,content,categories';
4035
+
4036
+ let acpPosts = [];
4037
+ if (acpPostType === 'both') {
4038
+ let postsUrl = `/posts?per_page=${acpPerPage}&status=publish&${acpFields}`;
4039
+ if (acpCatId) postsUrl += `&categories=${acpCatId}`;
4040
+ const [posts, pages] = await Promise.all([
4041
+ wpApiCall(postsUrl),
4042
+ wpApiCall(`/pages?per_page=${acpPerPage}&status=publish&${acpFields}`)
4043
+ ]);
4044
+ acpPosts = [...posts, ...pages];
4045
+ } else {
4046
+ const ep = acpPostType === 'page' ? '/pages' : '/posts';
4047
+ let postsUrl = `${ep}?per_page=${acpPerPage}&status=publish&${acpFields}`;
4048
+ if (acpCatId && acpPostType !== 'page') postsUrl += `&categories=${acpCatId}`;
4049
+ acpPosts = await wpApiCall(postsUrl);
4050
+ }
4051
+
4052
+ const CTA_CONTACT_HREFS = ['/contact', '/nous-contacter', '/contactez-nous', 'mailto:'];
4053
+ const CTA_CONTACT_ANCHORS = ['contactez', 'contact', 'nous contacter'];
4054
+ const CTA_FORM_PATTERNS = ['wpforms', 'cf7', 'gravity', 'elementor-form', 'formulaire', 'form'];
4055
+ const CTA_BUTTON_TEXTS = ['devis', 'essai', 'commencer', 'inscription', "s'inscrire", 'acheter', 'commander', 'réserver', 'télécharger', 'download', 'get started', 'sign up', 'buy', 'order', 'book', 'subscribe'];
4056
+ const CTA_QUOTE_TEXTS = ['devis', 'demande de devis', 'quote', 'request a quote', 'estimation'];
4057
+ const CTA_SIGNUP_HREFS = ['/inscription', '/register', '/signup', '/trial', '/essai'];
4058
+
4059
+ let acpWithCta = 0;
4060
+ let acpWithoutCta = 0;
4061
+ const ctaTypeDist = { contact_link: 0, form: 0, button_cta: 0, phone_link: 0, quote_request: 0, signup_link: 0 };
4062
+
4063
+ const acpResults = [];
4064
+ for (const p of acpPosts) {
4065
+ const html = p.content?.rendered || '';
4066
+ const lower = html.toLowerCase();
4067
+ const ctas = [];
4068
+ const ctaTypesFound = new Set();
4069
+
4070
+ // Scan all links
4071
+ const linkRegex = /<a\b[^>]*href=["']([^"']*)["'][^>]*>([\s\S]*?)<\/a>/gi;
4072
+ let lm;
4073
+ while ((lm = linkRegex.exec(html)) !== null) {
4074
+ const href = lm[1].toLowerCase();
4075
+ const anchor = strip(lm[2]).toLowerCase();
4076
+
4077
+ if (CTA_CONTACT_HREFS.some(pat => href.includes(pat)) || CTA_CONTACT_ANCHORS.some(txt => anchor.includes(txt))) {
4078
+ ctas.push({ type: 'contact_link', text: strip(lm[2]), href: lm[1] });
4079
+ ctaTypesFound.add('contact_link');
4080
+ }
4081
+ if (href.startsWith('tel:')) {
4082
+ ctas.push({ type: 'phone_link', text: strip(lm[2]), href: lm[1] });
4083
+ ctaTypesFound.add('phone_link');
4084
+ }
4085
+ if (CTA_SIGNUP_HREFS.some(pat => href.includes(pat))) {
4086
+ ctas.push({ type: 'signup_link', text: strip(lm[2]), href: lm[1] });
4087
+ ctaTypesFound.add('signup_link');
4088
+ }
4089
+ if (CTA_QUOTE_TEXTS.some(txt => anchor.includes(txt))) {
4090
+ ctas.push({ type: 'quote_request', text: strip(lm[2]), href: lm[1] });
4091
+ ctaTypesFound.add('quote_request');
4092
+ }
4093
+ }
4094
+
4095
+ // Forms
4096
+ if (/<form\b/i.test(html) || CTA_FORM_PATTERNS.some(pat => lower.includes(pat))) {
4097
+ const formElement = CTA_FORM_PATTERNS.find(pat => lower.includes(pat)) || 'form';
4098
+ ctas.push({ type: 'form', element: formElement });
4099
+ ctaTypesFound.add('form');
4100
+ }
4101
+
4102
+ // Button CTAs (by class)
4103
+ const btnClassRegex = /<(?:button|a)\b[^>]*class=["'][^"']*(?:cta|btn-cta|call-to-action|bouton-action)[^"']*["'][^>]*>([\s\S]*?)<\/(?:button|a)>/gi;
4104
+ let bm;
4105
+ while ((bm = btnClassRegex.exec(html)) !== null) {
4106
+ ctas.push({ type: 'button_cta', text: strip(bm[1]) });
4107
+ ctaTypesFound.add('button_cta');
4108
+ }
4109
+ // Button CTAs (by text)
4110
+ if (!ctaTypesFound.has('button_cta')) {
4111
+ const btnTextRegex = /<button\b[^>]*>([\s\S]*?)<\/button>/gi;
4112
+ let btm;
4113
+ while ((btm = btnTextRegex.exec(html)) !== null) {
4114
+ const btnText = strip(btm[1]).toLowerCase();
4115
+ if (CTA_BUTTON_TEXTS.some(txt => btnText.includes(txt))) {
4116
+ ctas.push({ type: 'button_cta', text: strip(btm[1]) });
4117
+ ctaTypesFound.add('button_cta');
4118
+ break;
4119
+ }
4120
+ }
4121
+ }
4122
+
4123
+ const uniqueTypes = ctaTypesFound.size;
4124
+ let ctaScore = 0;
4125
+ if (uniqueTypes >= 3) ctaScore = 100;
4126
+ else if (uniqueTypes === 2) ctaScore = 70;
4127
+ else if (uniqueTypes === 1) ctaScore = 40;
4128
+
4129
+ const issues = [];
4130
+ if (uniqueTypes === 0) { issues.push('no_cta'); acpWithoutCta++; }
4131
+ else { acpWithCta++; }
4132
+ if (uniqueTypes === 1) issues.push('single_cta_type');
4133
+
4134
+ for (const ct of ctaTypesFound) ctaTypeDist[ct]++;
4135
+
4136
+ acpResults.push({
4137
+ id: p.id, title: strip(p.title?.rendered || ''), slug: p.slug, link: p.link,
4138
+ cta_score: ctaScore, cta_count: ctas.length, cta_types: [...ctaTypesFound],
4139
+ ctas, issues
4140
+ });
4141
+ }
4142
+
4143
+ acpResults.sort((a, b) => a.cta_score - b.cta_score);
4144
+
4145
+ const acpTotal = acpPosts.length;
4146
+ result = json({
4147
+ total_analyzed: acpTotal,
4148
+ posts_with_cta: acpWithCta,
4149
+ posts_without_cta: acpWithoutCta,
4150
+ cta_coverage: acpTotal > 0 ? Math.round(acpWithCta / acpTotal * 100) : 0,
4151
+ cta_type_distribution: ctaTypeDist,
4152
+ posts: acpResults
4153
+ });
4154
+ auditLog({ tool: name, action: 'audit_cta_presence', status: 'success', latency_ms: Date.now() - t0, params: { limit: acpLimit, post_type: acpPostType, category_id: acpCatId } });
4155
+ break;
4156
+ }
4157
+
4158
+ // ── CONTENT INTELLIGENCE v4.4 Batch 4B ──
4159
+
4160
+ case 'wp_extract_entities': {
4161
+ validateInput(args, { limit: { type: 'number', min: 1, max: 100 }, post_type: { type: 'string', enum: ['post', 'page'] }, min_occurrences: { type: 'number', min: 1 } });
4162
+ const eeLimit = args.limit || 20;
4163
+ const eePostType = args.post_type || 'post';
4164
+ const eeMinOcc = args.min_occurrences || 2;
4165
+
4166
+ const eePosts = await wpApiCall(`/${eePostType}s?per_page=${eeLimit}&status=publish&_fields=id,title,content,slug`);
4167
+
4168
+ const globalEntities = new Map(); // name -> { type, count, post_ids, contexts }
4169
+ const postResults = [];
4170
+
4171
+ for (const p of eePosts) {
4172
+ const text = strip(p.content?.rendered || '');
4173
+ const entities = extractEntities(text);
4174
+ const localEntities = [];
4175
+
4176
+ for (const ent of entities) {
4177
+ localEntities.push({ name: ent.name, type: ent.type, count: ent.count });
4178
+ if (!globalEntities.has(ent.name)) {
4179
+ globalEntities.set(ent.name, { type: ent.type, count: 0, post_ids: new Set(), contexts: [] });
4180
+ }
4181
+ const g = globalEntities.get(ent.name);
4182
+ g.count += ent.count;
4183
+ g.post_ids.add(p.id);
4184
+ for (const ctx of ent.contexts) {
4185
+ if (g.contexts.length < 2) g.contexts.push(ctx);
4186
+ }
4187
+ }
4188
+
4189
+ postResults.push({
4190
+ id: p.id, title: strip(p.title?.rendered || ''), slug: p.slug,
4191
+ entities_count: localEntities.length,
4192
+ entities: localEntities
4193
+ });
4194
+ }
4195
+
4196
+ // Filter by min_occurrences and build aggregated results
4197
+ const filteredEntities = [...globalEntities.entries()]
4198
+ .filter(([, v]) => v.count >= eeMinOcc)
4199
+ .sort((a, b) => b[1].count - a[1].count);
4200
+
4201
+ const byType = { brand: 0, location: 0, person: 0, organization: 0, unknown: 0 };
4202
+ for (const [, v] of filteredEntities) {
4203
+ if (byType[v.type] !== undefined) byType[v.type]++;
4204
+ }
4205
+
4206
+ result = json({
4207
+ total_analyzed: eePosts.length,
4208
+ total_entities_found: filteredEntities.length,
4209
+ entities_by_type: byType,
4210
+ top_entities: filteredEntities.slice(0, 20).map(([name, v]) => ({
4211
+ name, type: v.type, total_count: v.count, post_ids: [...v.post_ids], contexts: v.contexts
4212
+ })),
4213
+ posts: postResults
4214
+ });
4215
+ auditLog({ tool: name, action: 'extract_entities', status: 'success', latency_ms: Date.now() - t0, params: { limit: eeLimit, post_type: eePostType, min_occurrences: eeMinOcc } });
4216
+ break;
4217
+ }
4218
+
4219
+ case 'wp_get_publishing_velocity': {
4220
+ validateInput(args, { periods: { type: 'string' }, post_type: { type: 'string', enum: ['post', 'page'] }, limit: { type: 'number', min: 1, max: 500 } });
4221
+ const pvPeriodsStr = args.periods || '30,90,180';
4222
+ const pvPostType = args.post_type || 'post';
4223
+ const pvLimit = args.limit || 200;
4224
+
4225
+ const periodDays = pvPeriodsStr.split(',').map(s => parseInt(s.trim(), 10)).filter(n => n > 0);
4226
+ if (periodDays.length === 0) throw new Error('Invalid periods: must be comma-separated positive integers');
4227
+
4228
+ const pvPosts = await wpApiCall(`/${pvPostType}s?per_page=${pvLimit}&status=publish&orderby=date&order=desc&_fields=id,title,date,author,categories`);
4229
+ const pvAuthors = await wpApiCall('/users?per_page=100&_fields=id,name');
4230
+ const pvCategories = await wpApiCall('/categories?per_page=100&_fields=id,name');
4231
+
4232
+ const authorMap = new Map(pvAuthors.map(a => [a.id, a.name]));
4233
+ const catMap = new Map(pvCategories.map(c => [c.id, c.name]));
4234
+ const now = Date.now();
4235
+
4236
+ const periodsResult = periodDays.map(p => {
4237
+ const cutoff = now - p * 86400000;
4238
+ const inPeriod = pvPosts.filter(post => new Date(post.date).getTime() >= cutoff);
4239
+ const velocity = Math.round(inPeriod.length / (p / 30) * 10) / 10;
4240
+
4241
+ // By author
4242
+ const authorCounts = new Map();
4243
+ for (const post of inPeriod) {
4244
+ authorCounts.set(post.author, (authorCounts.get(post.author) || 0) + 1);
4245
+ }
4246
+ const byAuthor = [...authorCounts.entries()]
4247
+ .map(([id, count]) => ({ id, name: authorMap.get(id) || `Author ${id}`, posts_count: count, velocity_per_month: Math.round(count / (p / 30) * 10) / 10 }))
4248
+ .sort((a, b) => b.velocity_per_month - a.velocity_per_month);
4249
+
4250
+ // By category
4251
+ const catCounts = new Map();
4252
+ for (const post of inPeriod) {
4253
+ for (const catId of (post.categories || [])) {
4254
+ catCounts.set(catId, (catCounts.get(catId) || 0) + 1);
4255
+ }
4256
+ }
4257
+ const byCategory = [...catCounts.entries()]
4258
+ .map(([id, count]) => ({ id, name: catMap.get(id) || `Category ${id}`, posts_count: count, velocity_per_month: Math.round(count / (p / 30) * 10) / 10 }))
4259
+ .sort((a, b) => b.velocity_per_month - a.velocity_per_month);
4260
+
4261
+ return { days: p, posts_count: inPeriod.length, velocity_per_month: velocity, by_author: byAuthor, by_category: byCategory };
4262
+ });
4263
+
4264
+ // Trend calculation
4265
+ const sortedPeriods = [...periodsResult].sort((a, b) => a.days - b.days);
4266
+ const shortV = sortedPeriods[0].velocity_per_month;
4267
+ const longV = sortedPeriods[sortedPeriods.length - 1].velocity_per_month;
4268
+ const changePct = longV > 0 ? Math.round(((shortV - longV) / longV) * 100) : 0;
4269
+ let direction = 'stable';
4270
+ if (changePct > 20) direction = 'accelerating';
4271
+ else if (changePct < -20) direction = 'decelerating';
4272
+
4273
+ // Top authors/categories from shortest period
4274
+ const shortPeriod = sortedPeriods[0];
4275
+
4276
+ result = json({
4277
+ total_posts_fetched: pvPosts.length,
4278
+ post_type: pvPostType,
4279
+ periods: periodsResult,
4280
+ trend: { direction, short_period_velocity: shortV, long_period_velocity: longV, change_percent: changePct },
4281
+ top_authors: shortPeriod.by_author.slice(0, 10),
4282
+ top_categories: shortPeriod.by_category.slice(0, 10)
4283
+ });
4284
+ auditLog({ tool: name, action: 'publishing_velocity', status: 'success', latency_ms: Date.now() - t0, params: { periods: periodDays, post_type: pvPostType, limit: pvLimit } });
4285
+ break;
4286
+ }
4287
+
4288
+ case 'wp_compare_revisions_diff': {
4289
+ validateInput(args, { post_id: { type: 'number', required: true }, revision_id_from: { type: 'number', required: true }, revision_id_to: { type: 'number' }, post_type: { type: 'string', enum: ['post', 'page'] } });
4290
+ const crdPostId = args.post_id;
4291
+ const crdRevFrom = args.revision_id_from;
4292
+ const crdRevTo = args.revision_id_to;
4293
+ const crdPostType = args.post_type || 'post';
4294
+
4295
+ const revFrom = await wpApiCall(`/${crdPostType}s/${crdPostId}/revisions/${crdRevFrom}?_fields=id,date,content,title`);
4296
+ let revTo;
4297
+ let revToId;
4298
+ if (crdRevTo) {
4299
+ revTo = await wpApiCall(`/${crdPostType}s/${crdPostId}/revisions/${crdRevTo}?_fields=id,date,content,title`);
4300
+ revToId = crdRevTo;
4301
+ } else {
4302
+ revTo = await wpApiCall(`/${crdPostType}s/${crdPostId}?_fields=id,content,title,modified`);
4303
+ revToId = 'current';
4304
+ }
4305
+
4306
+ const textFrom = strip(revFrom.content?.rendered || revFrom.content || '');
4307
+ const textTo = strip(revTo.content?.rendered || revTo.content || '');
4308
+ const diff = computeTextDiff(textFrom, textTo);
4309
+
4310
+ const wcFrom = countWords(revFrom.content?.rendered || revFrom.content || '');
4311
+ const wcTo = countWords(revTo.content?.rendered || revTo.content || '');
4312
+
4313
+ const headingsFrom = extractHeadingsOutline(revFrom.content?.rendered || revFrom.content || '');
4314
+ const headingsTo = extractHeadingsOutline(revTo.content?.rendered || revTo.content || '');
4315
+ const headingsFromSet = new Set(headingsFrom.map(h => `${h.level}:${h.text}`));
4316
+ const headingsToSet = new Set(headingsTo.map(h => `${h.level}:${h.text}`));
4317
+ const headingsAdded = headingsTo.filter(h => !headingsFromSet.has(`${h.level}:${h.text}`));
4318
+ const headingsRemoved = headingsFrom.filter(h => !headingsToSet.has(`${h.level}:${h.text}`));
4319
+
4320
+ const amplitude = diff.change_ratio >= 0.5 ? 'major' : diff.change_ratio >= 0.2 ? 'moderate' : 'minor';
4321
+
4322
+ result = json({
4323
+ post_id: crdPostId,
4324
+ from: {
4325
+ revision_id: crdRevFrom,
4326
+ date: revFrom.date,
4327
+ title: strip(revFrom.title?.rendered || revFrom.title || ''),
4328
+ word_count: wcFrom
4329
+ },
4330
+ to: {
4331
+ revision_id: revToId,
4332
+ date: revTo.date || revTo.modified,
4333
+ title: strip(revTo.title?.rendered || revTo.title || ''),
4334
+ word_count: wcTo
4335
+ },
4336
+ diff: {
4337
+ lines_added: diff.lines_added,
4338
+ lines_removed: diff.lines_removed,
4339
+ lines_unchanged: diff.lines_unchanged,
4340
+ words_added: diff.words_added,
4341
+ words_removed: diff.words_removed,
4342
+ word_count_change: wcTo - wcFrom,
4343
+ change_ratio: Math.round(diff.change_ratio * 1000) / 1000,
4344
+ amplitude
4345
+ },
4346
+ headings_diff: { added: headingsAdded, removed: headingsRemoved },
4347
+ sample_changes: {
4348
+ added: diff.added_lines.slice(0, 10),
4349
+ removed: diff.removed_lines.slice(0, 10)
4350
+ }
4351
+ });
4352
+ auditLog({ tool: name, action: 'compare_revisions_diff', status: 'success', latency_ms: Date.now() - t0, params: { post_id: crdPostId, revision_id_from: crdRevFrom, revision_id_to: crdRevTo } });
4353
+ break;
4354
+ }
4355
+
4356
+ case 'wp_list_posts_by_word_count': {
4357
+ validateInput(args, { limit: { type: 'number', min: 1, max: 500 }, post_type: { type: 'string', enum: ['post', 'page', 'both'] }, order: { type: 'string', enum: ['asc', 'desc'] }, category_id: { type: 'number' } });
4358
+ const wclLimit = args.limit || 100;
4359
+ const wclPostType = args.post_type || 'post';
4360
+ const wclOrder = args.order || 'desc';
4361
+ const wclCatId = args.category_id;
4362
+
4363
+ let wclPosts;
4364
+ if (wclPostType === 'both') {
4365
+ const catParam = wclCatId ? `&categories=${wclCatId}` : '';
4366
+ const [postsArr, pagesArr] = await Promise.all([
4367
+ wpApiCall(`/posts?per_page=${wclLimit}&status=publish&_fields=id,title,slug,link,content,date,modified,categories${catParam}`),
4368
+ wpApiCall(`/pages?per_page=${wclLimit}&status=publish&_fields=id,title,slug,link,content,date,modified,categories`)
4369
+ ]);
4370
+ wclPosts = [...postsArr, ...pagesArr];
4371
+ } else {
4372
+ const catParam = wclCatId ? `&categories=${wclCatId}` : '';
4373
+ wclPosts = await wpApiCall(`/${wclPostType}s?per_page=${wclLimit}&status=publish&_fields=id,title,slug,link,content,date,modified,categories${catParam}`);
4374
+ }
4375
+
4376
+ const postsWithWc = wclPosts.map(p => {
4377
+ const wc = countWords(p.content?.rendered || '');
4378
+ let segment;
4379
+ if (wc < 300) segment = 'very_short';
4380
+ else if (wc < 600) segment = 'short';
4381
+ else if (wc < 1000) segment = 'medium';
4382
+ else if (wc < 2000) segment = 'standard';
4383
+ else if (wc < 3000) segment = 'long';
4384
+ else segment = 'very_long';
4385
+
4386
+ return {
4387
+ id: p.id, title: strip(p.title?.rendered || ''), slug: p.slug, link: p.link,
4388
+ word_count: wc, segment,
4389
+ date: p.date, modified: p.modified,
4390
+ categories: p.categories || []
4391
+ };
4392
+ });
4393
+
4394
+ postsWithWc.sort((a, b) => wclOrder === 'asc' ? a.word_count - b.word_count : b.word_count - a.word_count);
4395
+
4396
+ const counts = postsWithWc.map(p => p.word_count);
4397
+ const total = counts.length || 1;
4398
+ const avg = counts.reduce((s, c) => s + c, 0) / total;
4399
+ const sorted = [...counts].sort((a, b) => a - b);
4400
+ const median = sorted.length % 2 === 0 ? (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2 : sorted[Math.floor(sorted.length / 2)];
4401
+
4402
+ const dist = { very_short: 0, short: 0, medium: 0, standard: 0, long: 0, very_long: 0 };
4403
+ for (const p of postsWithWc) dist[p.segment]++;
4404
+ const distribution = {};
4405
+ for (const [seg, count] of Object.entries(dist)) {
4406
+ distribution[seg] = { count, percent: Math.round(count / total * 100) };
4407
+ }
4408
+
4409
+ result = json({
4410
+ total_analyzed: postsWithWc.length,
4411
+ avg_word_count: Math.round(avg),
4412
+ median_word_count: median,
4413
+ min_word_count: sorted[0] || 0,
4414
+ max_word_count: sorted[sorted.length - 1] || 0,
4415
+ distribution,
4416
+ posts: postsWithWc
4417
+ });
4418
+ auditLog({ tool: name, action: 'list_by_word_count', status: 'success', latency_ms: Date.now() - t0, params: { limit: wclLimit, post_type: wclPostType, order: wclOrder, category_id: wclCatId } });
4419
+ break;
4420
+ }
4421
+
1302
4422
  default:
1303
4423
  throw new Error(`Unknown tool: "${name}".`);
1304
4424
  }
@@ -1364,4 +4484,4 @@ if (process.env.NODE_ENV !== 'test') {
1364
4484
  main().catch((error) => { log.error(`Fatal: ${error.message}`); process.exit(1); });
1365
4485
  }
1366
4486
 
1367
- export { server };
4487
+ export { server, getActiveControls, getControlSources, _testSetTarget };