seomd-cli 1.3.0 → 2.0.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 (37) hide show
  1. package/PROVIDER_SPEC.md +125 -0
  2. package/README.md +54 -190
  3. package/SKILL.md +44 -0
  4. package/bin/seomd.js +78 -31
  5. package/package.json +11 -7
  6. package/src/commands/analyze.js +92 -92
  7. package/src/commands/check.js +301 -0
  8. package/src/commands/doctor.js +109 -0
  9. package/src/commands/generate.js +202 -0
  10. package/src/commands/init.js +127 -79
  11. package/src/commands/status.js +107 -79
  12. package/src/commands/sync.js +86 -72
  13. package/src/commands/validate.js +52 -25
  14. package/src/generators/directory.js +44 -143
  15. package/src/generators/reverse.js +46 -56
  16. package/src/generators/seomd.js +197 -44
  17. package/src/providers/http.js +67 -0
  18. package/src/providers/index.js +194 -0
  19. package/src/utils/agent-wiring.js +97 -0
  20. package/src/utils/api-client.js +14 -56
  21. package/src/utils/constants.js +110 -12
  22. package/src/utils/parser.js +114 -25
  23. package/src/utils/repo-scanner.js +207 -0
  24. package/src/utils/writeback.js +181 -100
  25. package/src/validators/seomd.js +255 -93
  26. package/scripts/release-contributors.js +0 -196
  27. package/scripts/release-notes.js +0 -194
  28. package/src/templates/blog/SEO.REVERSE.md +0 -176
  29. package/src/templates/blog/SEO.md +0 -348
  30. package/src/templates/ecommerce/SEO.REVERSE.md +0 -199
  31. package/src/templates/ecommerce/SEO.md +0 -354
  32. package/src/templates/local/SEO.REVERSE.md +0 -222
  33. package/src/templates/local/SEO.md +0 -360
  34. package/src/templates/marketplace/SEO.REVERSE.md +0 -222
  35. package/src/templates/marketplace/SEO.md +0 -360
  36. package/src/templates/saas/SEO.REVERSE.md +0 -268
  37. package/src/templates/saas/SEO.md +0 -372
@@ -1,46 +1,35 @@
1
1
  import chalk from 'chalk';
2
2
  import ora from 'ora';
3
- import fs from 'fs-extra';
4
- import dotenv from 'dotenv';
5
- import { parseSeoMd } from '../utils/parser.js';
6
- import { client } from '../utils/api-client.js';
3
+ import { parseSeoMd, getBrand, getPages, getIntentQueries } from '../utils/parser.js';
4
+ import { resolveProvider } from '../providers/index.js';
7
5
  import { writeAnalysisToSeoMd, writeReverseMd, writePageAnalysis } from '../utils/writeback.js';
6
+ import { INTENT_CATEGORIES } from '../utils/constants.js';
8
7
 
9
- dotenv.config();
8
+ function escapeRegexSegment(str) {
9
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
10
+ }
10
11
 
11
- function matchRoute(pattern, url) {
12
- const cleanPattern = pattern.replace(/\/$/, '');
13
- const cleanUrl = url.replace(/\/$/, '');
12
+ export function matchRoute(pattern, url) {
13
+ const cleanPattern = String(pattern || '').replace(/\/$/, '') || '/';
14
+ const cleanUrl = String(url || '').replace(/\/$/, '') || '/';
14
15
 
15
16
  if (cleanPattern.toLowerCase() === cleanUrl.toLowerCase()) {
16
17
  return true;
17
18
  }
18
19
 
19
- // Replace "/[param]" with optional group "(?:/([^/]+))?"
20
- const regexPattern = cleanPattern
21
- .replace(/\/\[[^\]]+\]/g, '(?:\\/([^/]+))?')
22
- .replace(/\//g, '\\/');
20
+ // Replace dynamic segments like [competitor] with a required single path segment [^/]+
21
+ const parts = cleanPattern.split('/').map((seg) => {
22
+ if (/^\[[^\]]+\]$/.test(seg)) {
23
+ return '[^/]+';
24
+ }
25
+ return escapeRegexSegment(seg);
26
+ });
23
27
 
24
- const regex = new RegExp('^' + regexPattern + '\\/?$', 'i');
25
- return regex.test(url);
28
+ const regex = new RegExp(`^${parts.join('\\/')}\\/?$`, 'i');
29
+ return regex.test(cleanUrl);
26
30
  }
27
31
 
28
- export async function analyzeCommand(options) {
29
- const apiKey = process.env.SEOMD_API_KEY;
30
- const paymentToken = process.env.SEOMD_PAYMENT_TOKEN;
31
-
32
- if (!apiKey && !paymentToken) {
33
- console.log('');
34
- console.log(chalk.yellow('⚠ No API key or payment token found.'));
35
- console.log('');
36
- console.log('Add your API key to .env:');
37
- console.log(chalk.cyan(' SEOMD_API_KEY=your_key_here'));
38
- console.log('');
39
- console.log('Get your API key at ' + chalk.cyan('https://seomd.dev/connect'));
40
- console.log('');
41
- process.exit(1);
42
- }
43
-
32
+ export async function analyzeCommand(options = {}) {
44
33
  const cwd = process.cwd();
45
34
  let doc, data;
46
35
 
@@ -49,45 +38,56 @@ export async function analyzeCommand(options) {
49
38
  doc = parsed.doc;
50
39
  data = parsed.data;
51
40
  } catch (err) {
52
- console.log(chalk.red(`\n❌ Error: ${err.message}`));
53
- process.exit(1);
41
+ console.log(chalk.red(`\n✗ Error: ${err.message}`));
42
+ process.exitCode = 1;
43
+ return;
44
+ }
45
+
46
+ const provider = resolveProvider(data);
47
+ if (!provider) {
48
+ console.log('');
49
+ console.log(chalk.yellow('⚠ No intelligence provider configured.'));
50
+ console.log('');
51
+ console.log('Local commands (`validate`, `check`, `generate`, `doctor`) work offline without a provider.');
52
+ console.log('To run live AI citation analysis, configure any SEO.md-compatible provider in `.env`:');
53
+ console.log(chalk.cyan(' SEOMD_PROVIDER=foxcite # or custom | semrush | ahrefs | profound | peec'));
54
+ console.log(chalk.cyan(' SEOMD_API_KEY=your_key_here'));
55
+ console.log(chalk.cyan(' # SEOMD_API_URL=https://api.your-provider.com (for custom endpoints)'));
56
+ console.log('');
57
+ console.log('Provider protocol & compatible platforms: ' + chalk.cyan('https://seomd.dev/providers'));
58
+ console.log('');
59
+ process.exitCode = 1;
60
+ return;
54
61
  }
55
62
 
56
63
  const domain = data.site?.domain;
57
64
  if (!domain) {
58
- console.log(chalk.red('\n❌ Error: "site.domain" is required in SEO.md.'));
59
- process.exit(1);
65
+ console.log(chalk.red('\n✗ Error: "site.domain" is required in SEO.md.'));
66
+ process.exitCode = 1;
67
+ return;
60
68
  }
61
69
 
62
- const niche = data.site?.type || 'saas';
63
-
64
- // Extract intent queries
65
- const queries = {};
66
- if (data.intent) {
67
- for (const [intentType, obj] of Object.entries(data.intent)) {
68
- if (intentType !== '_analysis' && obj && Array.isArray(obj.queries)) {
69
- queries[intentType] = obj.queries;
70
- }
71
- }
70
+ // Validate --intent option if provided
71
+ if (options.intent && !INTENT_CATEGORIES.includes(String(options.intent).toLowerCase())) {
72
+ console.log(
73
+ chalk.red(
74
+ `\n✗ Error: Invalid --intent '${options.intent}'. Must be one of: ${INTENT_CATEGORIES.join(', ')}`
75
+ )
76
+ );
77
+ process.exitCode = 1;
78
+ return;
72
79
  }
73
80
 
74
- // Extract pages
75
- let pagesList = [];
76
- if (data.pages) {
77
- if (Array.isArray(data.pages.required)) {
78
- pagesList = pagesList.concat(data.pages.required);
79
- }
80
- if (Array.isArray(data.pages.optional)) {
81
- pagesList = pagesList.concat(data.pages.optional);
82
- }
83
- }
81
+ const niche = data.site?.type || 'saas';
82
+ const queries = getIntentQueries(data, options.intent || null);
84
83
 
85
- // Filter by options.page if specified
84
+ // Extract & filter pages
85
+ let pagesList = getPages(data);
86
86
  if (options.page) {
87
- pagesList = pagesList.filter(p => matchRoute(p.url, options.page));
87
+ pagesList = pagesList.filter((p) => matchRoute(p.url, options.page));
88
88
  }
89
89
 
90
- // Default fallback if no page matches or list is empty
90
+ // Fallback when --page does not match any declared route or pages list is empty
91
91
  if (pagesList.length === 0) {
92
92
  let fallbackId = 'homepage';
93
93
  if (options.page && options.page !== '/') {
@@ -100,80 +100,80 @@ export async function analyzeCommand(options) {
100
100
  id: fallbackId,
101
101
  url: options.page || '/',
102
102
  primary_keyword: data.keywords?.primary || `best ${niche}`,
103
- status: 'planned'
103
+ status: 'planned',
104
104
  });
105
105
  }
106
106
 
107
- // Extract engines
108
- let engines = data.aeo?._analysis?.engines_tracked || ['ChatGPT'];
107
+ let engines = ['ChatGPT', 'Perplexity', 'Claude'];
109
108
  if (options.engines) {
110
- engines = options.engines.split(',').map(e => e.trim());
109
+ engines = options.engines
110
+ .split(',')
111
+ .map((e) => e.trim())
112
+ .filter(Boolean);
111
113
  }
112
114
 
113
- console.log(chalk.bold.cyan(`\n📊 Foxcite: Running AI Search Audit for ${chalk.white(domain)}`));
115
+ console.log(chalk.bold.cyan(`\n📊 ${provider.displayName}: Running AI Search Audit for ${chalk.white(domain)}`));
114
116
  console.log(chalk.dim(`Engines: ${engines.join(', ')}`));
117
+ if (options.intent) {
118
+ console.log(chalk.dim(`Intent filter: ${options.intent}`));
119
+ }
115
120
  console.log(chalk.dim(`Pages to scan: ${pagesList.length}`));
116
121
  console.log('');
117
122
 
118
123
  const spinner = ora('Initializing scan sessions...').start();
119
124
 
120
125
  try {
121
- const brand = data.identity?.brand || 'My Brand';
126
+ const brand = getBrand(data);
122
127
  const payload = {
123
128
  domain,
124
129
  niche,
125
130
  brand,
126
131
  queries,
127
132
  engines,
128
- pages: pagesList.map(p => ({
133
+ pages: pagesList.map((p) => ({
129
134
  id: p.id,
130
- url: options.page || p.url, // Use the specific page requested if provided
135
+ url: options.page && pagesList.length === 1 ? options.page : p.url,
131
136
  primary_keyword: p.primary_keyword || data.keywords?.primary || `best ${niche}`,
132
- status: p.status
133
- }))
137
+ status: p.status,
138
+ })),
134
139
  };
135
140
 
136
141
  spinner.text = 'Scanning AI search engines and compiling citations (this may take up to a minute)...';
137
142
 
138
- const response = await client.post('/cli/analyze', payload);
139
- const results = response.data;
140
-
141
- spinner.text = 'Writing analysis blocks back to repository files...';
143
+ const results = await provider.analyze(payload);
142
144
 
143
- // Writeback to SEO.md
144
- await writeAnalysisToSeoMd(doc, results, cwd);
145
+ spinner.text = 'Writing analysis results back to .seo/ workspace...';
145
146
 
146
- // Writeback to SEO.REVERSE.md
147
- const brandName = data.identity?.brand || 'My Brand';
148
- await writeReverseMd(cwd, results, domain, brandName);
149
-
150
- // Writeback to .seo/pages/*.md
147
+ await writeAnalysisToSeoMd(doc, results, cwd, { provider: provider.name });
148
+ await writeReverseMd(cwd, results, domain, brand, { provider: provider.name });
151
149
  await writePageAnalysis(cwd, results);
152
150
 
153
151
  spinner.succeed(chalk.green('Analysis completed successfully!'));
154
152
  console.log('');
155
153
 
156
- // Display results summary
157
- const aeo = results.aeo_analysis;
154
+ const aeo = results?.aeo_analysis || {};
158
155
  console.log(chalk.bold('--- Results Summary ---'));
159
- console.log(`Overall Citation Rate : ${chalk.bold.green((aeo.overall_citation_rate * 100).toFixed(0) + '%')}`);
160
- console.log(`Overall Gap Score : ${chalk.bold.red(aeo.overall_gap_score)}`);
161
-
162
- if (results.credits_remaining !== null) {
156
+ if (typeof aeo.overall_citation_rate === 'number') {
157
+ console.log(`Overall Citation Rate : ${chalk.bold.green((aeo.overall_citation_rate * 100).toFixed(0) + '%')}`);
158
+ }
159
+ if (aeo.overall_gap_score !== undefined && aeo.overall_gap_score !== null) {
160
+ console.log(`Overall Gap Score : ${chalk.bold.red(aeo.overall_gap_score)}`);
161
+ }
162
+ if (results?.credits_remaining !== null && results?.credits_remaining !== undefined) {
163
163
  console.log(`Credits Remaining : ${chalk.cyan(results.credits_remaining)}`);
164
164
  }
165
- console.log(`Last Analyzed : ${chalk.dim(aeo.last_analyzed)}`);
166
- console.log(`Next Analysis Target : ${chalk.dim(aeo.next_analysis)}`);
165
+ console.log(`Last Analyzed : ${chalk.dim(aeo.last_analyzed || 'N/A')}`);
166
+ console.log(`Next Analysis Target : ${chalk.dim(aeo.next_analysis || 'N/A')}`);
167
167
  console.log('-----------------------');
168
168
  console.log('');
169
- console.log(chalk.green('✔ SEO.md updated.'));
170
- console.log(chalk.green('✔ SEO.REVERSE.md updated.'));
171
- console.log(chalk.green('✔ .seo/pages/ playbooks generated.'));
169
+ console.log(chalk.green('✔ .seo/STATUS.yml updated.'));
170
+ console.log(chalk.green('✔ .seo/REVERSE.md updated.'));
171
+ console.log(chalk.green('✔ .seo/pages/ playbooks updated.'));
172
172
  console.log('');
173
-
173
+ process.exitCode = 0;
174
174
  } catch (err) {
175
175
  spinner.fail(chalk.red('Analysis failed'));
176
176
  console.error(chalk.bold.red(`\nError: ${err.message}`));
177
- process.exit(1);
177
+ process.exitCode = 1;
178
178
  }
179
- }
179
+ }
@@ -0,0 +1,301 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { parseSeoMd, getPages } from '../utils/parser.js';
5
+
6
+ const KEY_AI_BOTS = ['GPTBot', 'ClaudeBot', 'PerplexityBot'];
7
+
8
+ /**
9
+ * Inspects HTML content for core SEO/AEO signals.
10
+ */
11
+ export function auditHtmlContent(html, urlLabel, negativeKeywords = []) {
12
+ const errors = [];
13
+ const warnings = [];
14
+
15
+ const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
16
+ const title = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim() : '';
17
+ if (!title) {
18
+ errors.push({ target: urlLabel, rule: 'title', message: 'Missing <title> tag' });
19
+ } else if (title.length > 70) {
20
+ warnings.push({ target: urlLabel, rule: 'title', message: `<title> is ${title.length} chars (recommended <= 70)` });
21
+ }
22
+
23
+ const metaDescMatch =
24
+ html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']*)["'][^>]*>/i) ||
25
+ html.match(/<meta[^>]+content=["']([^"']*)["'][^>]+name=["']description["'][^>]*>/i);
26
+ const metaDesc = metaDescMatch ? metaDescMatch[1].trim() : '';
27
+ if (!metaDesc) {
28
+ warnings.push({ target: urlLabel, rule: 'meta-description', message: 'Missing <meta name="description">' });
29
+ } else if (metaDesc.length < 50 || metaDesc.length > 165) {
30
+ warnings.push({
31
+ target: urlLabel,
32
+ rule: 'meta-description',
33
+ message: `Meta description is ${metaDesc.length} chars (recommended 50-160)`,
34
+ });
35
+ }
36
+
37
+ const h1Matches = html.match(/<h1\b[^>]*>[\s\S]*?<\/h1>/gi) || [];
38
+ if (h1Matches.length === 0) {
39
+ errors.push({ target: urlLabel, rule: 'h1', message: 'Missing <h1> heading' });
40
+ } else if (h1Matches.length > 1) {
41
+ warnings.push({ target: urlLabel, rule: 'h1', message: `Found ${h1Matches.length} <h1> tags (recommended 1)` });
42
+ }
43
+
44
+ const hasCanonical = /<link[^>]+rel=["']canonical["'][^>]*>/i.test(html);
45
+ if (!hasCanonical) {
46
+ warnings.push({ target: urlLabel, rule: 'canonical', message: 'Missing <link rel="canonical">' });
47
+ }
48
+
49
+ const jsonLdMatches = [...html.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)];
50
+ if (jsonLdMatches.length === 0) {
51
+ warnings.push({ target: urlLabel, rule: 'json-ld', message: 'No JSON-LD structured data (<script type="application/ld+json">) found' });
52
+ } else {
53
+ for (const m of jsonLdMatches) {
54
+ try {
55
+ JSON.parse(m[1].trim());
56
+ } catch {
57
+ errors.push({ target: urlLabel, rule: 'json-ld', message: 'Invalid JSON inside <script type="application/ld+json">' });
58
+ }
59
+ }
60
+ }
61
+
62
+ // Check negative keywords in title/H1 (high-signal dilution check)
63
+ if (Array.isArray(negativeKeywords) && negativeKeywords.length > 0) {
64
+ const headingText = `${title} ${h1Matches.join(' ')}`.toLowerCase();
65
+ for (const neg of negativeKeywords) {
66
+ const term = String(neg || '').trim().toLowerCase();
67
+ if (term && headingText.includes(term)) {
68
+ warnings.push({
69
+ target: urlLabel,
70
+ rule: 'negative-keyword',
71
+ message: `Title/H1 contains negative keyword '${neg}' declared in SEO.md`,
72
+ });
73
+ }
74
+ }
75
+ }
76
+
77
+ return { errors, warnings };
78
+ }
79
+
80
+ /**
81
+ * Checks robots.txt content for blocked AI crawlers when allow_ai_bots is true.
82
+ */
83
+ export function auditRobotsTxt(robotsContent, allowAiBots = true) {
84
+ const errors = [];
85
+ const warnings = [];
86
+ if (!allowAiBots) return { errors, warnings };
87
+
88
+ const blocks = robotsContent.split(/\r?\n\s*\r?\n/);
89
+ for (const block of blocks) {
90
+ const lines = block
91
+ .split(/\r?\n/)
92
+ .map((l) => l.replace(/#.*$/, '').trim())
93
+ .filter(Boolean);
94
+ const agents = lines
95
+ .filter((l) => /^user-agent:/i.test(l))
96
+ .map((l) => l.split(':')[1]?.trim().toLowerCase());
97
+ const disallowsRoot = lines.some((l) => /^disallow:\s*\/\s*$/i.test(l));
98
+
99
+ if (!disallowsRoot) continue;
100
+ for (const bot of KEY_AI_BOTS) {
101
+ if (agents.includes(bot.toLowerCase())) {
102
+ errors.push({
103
+ target: 'robots.txt',
104
+ rule: 'ai-bots',
105
+ message: `${bot} is blocked (Disallow: /) in robots.txt, conflicting with crawl.allow_ai_bots: true`,
106
+ });
107
+ }
108
+ }
109
+ }
110
+
111
+ return { errors, warnings };
112
+ }
113
+
114
+ async function collectHtmlFiles(dir, baseDir, out = [], depth = 0) {
115
+ if (depth > 4 || out.length >= 50) return out;
116
+ let entries;
117
+ try {
118
+ entries = await fs.readdir(dir, { withFileTypes: true });
119
+ } catch {
120
+ return out;
121
+ }
122
+
123
+ for (const entry of entries) {
124
+ if (entry.isDirectory()) {
125
+ if (['node_modules', '.git', '.seo', '.next'].includes(entry.name)) continue;
126
+ await collectHtmlFiles(path.join(dir, entry.name), baseDir, out, depth + 1);
127
+ } else if (entry.name.endsWith('.html')) {
128
+ const fullPath = path.join(dir, entry.name);
129
+ out.push({
130
+ fullPath,
131
+ relPath: path.relative(baseDir, fullPath) || entry.name,
132
+ });
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+
138
+ export async function checkCommand(target, options = {}) {
139
+ try {
140
+ const cwd = process.cwd();
141
+ const { data } = await parseSeoMd(cwd);
142
+ const negativeKeywords = Array.isArray(data.keywords?.negative) ? data.keywords.negative : [];
143
+ const allowAiBots = data.crawl?.allow_ai_bots !== false;
144
+
145
+ const errors = [];
146
+ const warnings = [];
147
+ let checkedPages = 0;
148
+
149
+ const isUrl = typeof target === 'string' && /^https?:\/\//i.test(target);
150
+
151
+ if (isUrl) {
152
+ const baseUrl = target.replace(/\/$/, '');
153
+
154
+ // Check robots.txt
155
+ try {
156
+ const res = await fetch(`${baseUrl}/robots.txt`);
157
+ if (res.ok) {
158
+ const text = await res.text();
159
+ const r = auditRobotsTxt(text, allowAiBots);
160
+ errors.push(...r.errors);
161
+ warnings.push(...r.warnings);
162
+ } else {
163
+ warnings.push({ target: `${baseUrl}/robots.txt`, rule: 'robots', message: `robots.txt returned HTTP ${res.status}` });
164
+ }
165
+ } catch (err) {
166
+ warnings.push({ target: `${baseUrl}/robots.txt`, rule: 'robots', message: `Could not fetch robots.txt: ${err.message}` });
167
+ }
168
+
169
+ // Check llms.txt if declared
170
+ if (data.crawl?.llms_txt) {
171
+ try {
172
+ const res = await fetch(`${baseUrl}${data.crawl.llms_txt}`);
173
+ if (!res.ok) {
174
+ warnings.push({ target: `${baseUrl}${data.crawl.llms_txt}`, rule: 'llms-txt', message: `llms.txt returned HTTP ${res.status}` });
175
+ }
176
+ } catch {
177
+ warnings.push({ target: `${baseUrl}${data.crawl.llms_txt}`, rule: 'llms-txt', message: 'Could not fetch llms.txt' });
178
+ }
179
+ }
180
+
181
+ // Audit concrete pages from SEO.md (or homepage fallback)
182
+ const pages = getPages(data).filter((p) => p.url && !p.url.includes('[') && p.status !== 'planned');
183
+ const toFetch = pages.length > 0 ? pages : [{ id: 'homepage', url: '/' }];
184
+
185
+ for (const page of toFetch) {
186
+ const pageUrl = `${baseUrl}${page.url === '/' ? '' : page.url}`;
187
+ try {
188
+ const res = await fetch(pageUrl);
189
+ if (!res.ok) {
190
+ errors.push({ target: page.url, rule: 'http-status', message: `Page returned HTTP ${res.status}` });
191
+ continue;
192
+ }
193
+ const html = await res.text();
194
+ const r = auditHtmlContent(html, page.url, negativeKeywords);
195
+ errors.push(...r.errors);
196
+ warnings.push(...r.warnings);
197
+ checkedPages += 1;
198
+ } catch (err) {
199
+ errors.push({ target: page.url, rule: 'network', message: `Failed to fetch ${pageUrl}: ${err.message}` });
200
+ }
201
+ }
202
+ } else {
203
+ // Local directory audit
204
+ const targetDir = target ? path.resolve(cwd, target) : cwd;
205
+ if (!(await fs.pathExists(targetDir))) {
206
+ throw new Error(`Target directory not found: ${targetDir}`);
207
+ }
208
+
209
+ // Locate robots.txt & llms.txt in targetDir or public/
210
+ const candidateDirs = [targetDir, path.join(targetDir, 'public'), path.join(cwd, 'public')];
211
+ let foundRobots = false;
212
+ let foundLlms = false;
213
+
214
+ for (const dir of candidateDirs) {
215
+ const robotsPath = path.join(dir, 'robots.txt');
216
+ if (!foundRobots && (await fs.pathExists(robotsPath))) {
217
+ foundRobots = true;
218
+ const robotsContent = await fs.readFile(robotsPath, 'utf8');
219
+ const r = auditRobotsTxt(robotsContent, allowAiBots);
220
+ errors.push(...r.errors);
221
+ warnings.push(...r.warnings);
222
+ }
223
+ const llmsPath = path.join(dir, 'llms.txt');
224
+ if (!foundLlms && (await fs.pathExists(llmsPath))) {
225
+ foundLlms = true;
226
+ }
227
+ }
228
+
229
+ if (!foundRobots) {
230
+ warnings.push({ target: 'robots.txt', rule: 'robots', message: 'robots.txt not found (run `npx seomd-cli generate robots --out public/robots.txt`)' });
231
+ }
232
+ if (data.crawl?.llms_txt && !foundLlms) {
233
+ warnings.push({ target: 'llms.txt', rule: 'llms-txt', message: 'llms.txt not found (run `npx seomd-cli generate llms --out public/llms.txt`)' });
234
+ }
235
+
236
+ // Audit any HTML files under targetDir
237
+ const htmlFiles = await collectHtmlFiles(targetDir, targetDir);
238
+ for (const file of htmlFiles) {
239
+ const html = await fs.readFile(file.fullPath, 'utf8');
240
+ const r = auditHtmlContent(html, file.relPath, negativeKeywords);
241
+ errors.push(...r.errors);
242
+ warnings.push(...r.warnings);
243
+ checkedPages += 1;
244
+ }
245
+ }
246
+
247
+ const failed = errors.length > 0 || (Boolean(options.strict) && warnings.length > 0);
248
+
249
+ if (options.json) {
250
+ console.log(
251
+ JSON.stringify(
252
+ {
253
+ passed: !failed,
254
+ checked_pages: checkedPages,
255
+ errors,
256
+ warnings,
257
+ },
258
+ null,
259
+ 2
260
+ )
261
+ );
262
+ process.exitCode = failed ? 1 : 0;
263
+ return;
264
+ }
265
+
266
+ console.log('');
267
+ console.log(chalk.bold('SEO.md Local Check') + chalk.dim(` (${checkedPages} HTML page(s) inspected)`));
268
+ console.log('');
269
+
270
+ if (errors.length > 0) {
271
+ console.log(chalk.red.bold(` Errors (${errors.length}):`));
272
+ for (const err of errors) {
273
+ console.log(` ${chalk.red('✗')} ${err.message} ${chalk.dim(`[${err.target}]`)}`);
274
+ }
275
+ console.log('');
276
+ }
277
+
278
+ if (warnings.length > 0) {
279
+ console.log(chalk.yellow.bold(` Warnings (${warnings.length}):`));
280
+ for (const warn of warnings) {
281
+ console.log(` ${chalk.yellow('⚠')} ${warn.message} ${chalk.dim(`[${warn.target}]`)}`);
282
+ }
283
+ console.log('');
284
+ }
285
+
286
+ if (!failed) {
287
+ console.log(chalk.green.bold(`✓ Check passed (${errors.length} error(s), ${warnings.length} warning(s)).`));
288
+ } else {
289
+ console.log(chalk.red.bold(`✗ Check failed (${errors.length} error(s), ${warnings.length} warning(s)).`));
290
+ }
291
+ console.log('');
292
+ process.exitCode = failed ? 1 : 0;
293
+ } catch (err) {
294
+ if (options.json) {
295
+ console.log(JSON.stringify({ passed: false, error: err.message }, null, 2));
296
+ } else {
297
+ console.log(chalk.red(`✗ Check failed: ${err.message}`));
298
+ }
299
+ process.exitCode = 1;
300
+ }
301
+ }
@@ -0,0 +1,109 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { parseSeoMd } from '../utils/parser.js';
5
+ import { validateSeoMd } from '../validators/seomd.js';
6
+ import { inspectAgentWiring } from '../utils/agent-wiring.js';
7
+ import { scanRepo } from '../utils/repo-scanner.js';
8
+ import { resolveProvider } from '../providers/index.js';
9
+
10
+ export async function doctorCommand(options = {}) {
11
+ const cwd = process.cwd();
12
+ const report = {
13
+ seomd: { exists: false, format: null, valid: false, errors: 0, warnings: 0 },
14
+ agents: { filesFound: [], wiredFiles: [] },
15
+ repo: { framework: null, routesDiscovered: 0, hasRobotsTxt: false, hasSitemap: false, hasLlmsTxt: false },
16
+ workspace: { hasStatus: false, hasReverse: false },
17
+ provider: { configured: false, name: null, endpoint: null, hasAuth: false },
18
+ };
19
+
20
+ let parsedData = null;
21
+ try {
22
+ const { format, data, body } = await parseSeoMd(cwd);
23
+ parsedData = data;
24
+ const { errors, warnings } = validateSeoMd(data, { format, body });
25
+ report.seomd = {
26
+ exists: true,
27
+ format,
28
+ valid: errors.length === 0,
29
+ errors: errors.length,
30
+ warnings: warnings.length,
31
+ };
32
+ } catch (err) {
33
+ report.seomd.error = err.message;
34
+ }
35
+
36
+ report.agents = await inspectAgentWiring(cwd);
37
+
38
+ const repoInfo = await scanRepo(cwd);
39
+ report.repo = {
40
+ framework: repoInfo.framework,
41
+ routesDiscovered: repoInfo.routes.length,
42
+ hasRobotsTxt: repoInfo.hasRobotsTxt,
43
+ hasSitemap: repoInfo.hasSitemap,
44
+ hasLlmsTxt: repoInfo.hasLlmsTxt,
45
+ };
46
+
47
+ report.workspace.hasStatus = await fs.pathExists(path.join(cwd, '.seo', 'STATUS.yml'));
48
+ report.workspace.hasReverse = await fs.pathExists(path.join(cwd, '.seo', 'REVERSE.md'));
49
+
50
+ const provider = resolveProvider(parsedData);
51
+ if (provider) {
52
+ report.provider = {
53
+ configured: true,
54
+ name: provider.name,
55
+ endpoint: provider.endpoint,
56
+ hasAuth: provider.hasAuth,
57
+ capabilities: provider.capabilities,
58
+ };
59
+ }
60
+
61
+ if (options.json) {
62
+ console.log(JSON.stringify(report, null, 2));
63
+ process.exitCode = report.seomd.valid ? 0 : 1;
64
+ return;
65
+ }
66
+
67
+ console.log('');
68
+ console.log(chalk.bold('SEO.md Doctor'));
69
+ console.log(chalk.dim('─'.repeat(50)));
70
+
71
+ // SEO.md
72
+ if (report.seomd.exists && report.seomd.valid) {
73
+ console.log(`${chalk.green('✓')} SEO.md found (${report.seomd.format}) — valid (${report.seomd.warnings} warning(s))`);
74
+ } else if (report.seomd.exists) {
75
+ console.log(`${chalk.red('✗')} SEO.md found (${report.seomd.format}) — ${report.seomd.errors} error(s)`);
76
+ } else {
77
+ console.log(`${chalk.red('✗')} SEO.md not found — run ${chalk.cyan('npx seomd-cli init')}`);
78
+ }
79
+
80
+ // Agent wiring
81
+ if (report.agents.wiredFiles.length > 0) {
82
+ console.log(`${chalk.green('✓')} Agent wiring active in: ${report.agents.wiredFiles.join(', ')}`);
83
+ } else {
84
+ console.log(`${chalk.yellow('⚠')} AGENTS.md / CLAUDE.md not wired to SEO.md yet`);
85
+ }
86
+
87
+ // Crawl files
88
+ console.log(
89
+ `${report.repo.hasRobotsTxt ? chalk.green('✓') : chalk.yellow('⚠')} robots.txt ${report.repo.hasRobotsTxt ? 'detected' : 'missing'}`
90
+ );
91
+ console.log(
92
+ `${report.repo.hasLlmsTxt ? chalk.green('✓') : chalk.yellow('⚠')} llms.txt ${report.repo.hasLlmsTxt ? 'detected' : 'missing'}`
93
+ );
94
+ console.log(
95
+ `${report.repo.hasSitemap ? chalk.green('✓') : chalk.yellow('⚠')} sitemap.xml ${report.repo.hasSitemap ? 'detected' : 'missing'}`
96
+ );
97
+
98
+ // Provider
99
+ if (report.provider.configured) {
100
+ const authTag = report.provider.hasAuth ? chalk.green('credentials set') : chalk.yellow('missing SEOMD_API_KEY');
101
+ const endpointTag = report.provider.endpoint ? chalk.dim(report.provider.endpoint) : chalk.yellow('no endpoint');
102
+ console.log(`${chalk.green('✓')} Provider: ${chalk.bold(report.provider.name)} (${authTag}, ${endpointTag})`);
103
+ } else {
104
+ console.log(`${chalk.dim('•')} Provider: local-only mode (optional — set SEOMD_PROVIDER / SEOMD_API_KEY for live citation scans)`);
105
+ }
106
+
107
+ console.log('');
108
+ process.exitCode = report.seomd.valid ? 0 : 1;
109
+ }