seomd-cli 1.4.0 → 2.0.1

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 (39) 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 +79 -31
  5. package/package.json +11 -7
  6. package/src/commands/analyze.js +90 -90
  7. package/src/commands/check.js +301 -0
  8. package/src/commands/doctor.js +109 -0
  9. package/src/commands/generate.js +215 -0
  10. package/src/commands/init.js +170 -66
  11. package/src/commands/status.js +92 -76
  12. package/src/commands/sync.js +84 -70
  13. package/src/commands/validate.js +52 -25
  14. package/src/generators/directory.js +46 -114
  15. package/src/generators/reverse.js +46 -56
  16. package/src/generators/seomd.js +226 -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/migrate.js +99 -0
  23. package/src/utils/parser.js +114 -25
  24. package/src/utils/placeholders.js +31 -0
  25. package/src/utils/repo-scanner.js +207 -0
  26. package/src/utils/writeback.js +171 -82
  27. package/src/validators/seomd.js +263 -93
  28. package/scripts/release-contributors.js +0 -196
  29. package/scripts/release-notes.js +0 -194
  30. package/src/templates/blog/SEO.REVERSE.md +0 -176
  31. package/src/templates/blog/SEO.md +0 -233
  32. package/src/templates/ecommerce/SEO.REVERSE.md +0 -199
  33. package/src/templates/ecommerce/SEO.md +0 -239
  34. package/src/templates/local/SEO.REVERSE.md +0 -222
  35. package/src/templates/local/SEO.md +0 -245
  36. package/src/templates/marketplace/SEO.REVERSE.md +0 -222
  37. package/src/templates/marketplace/SEO.md +0 -245
  38. package/src/templates/saas/SEO.REVERSE.md +0 -268
  39. package/src/templates/saas/SEO.md +0 -257
@@ -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
+ }
@@ -0,0 +1,215 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { parseSeoMd, getBrand, getPages } from '../utils/parser.js';
5
+ import { AI_BOTS, SCHEMA_TYPES } from '../utils/constants.js';
6
+ import { getFact, findPlaceholders } from '../utils/placeholders.js';
7
+
8
+ const VALID_TARGETS = ['robots', 'llms', 'schema'];
9
+
10
+ export function buildRobotsTxt(data) {
11
+ const domain = data.site?.domain || 'example.com';
12
+ const canonical = (data.site?.canonical || `https://${domain}`).replace(/\/$/, '');
13
+ const crawl = data.crawl || {};
14
+ const allowAi = crawl.allow_ai_bots !== false;
15
+ const disallow = Array.isArray(crawl.disallow) ? crawl.disallow : ['/admin', '/api/*'];
16
+ const sitemap = crawl.sitemap || '/sitemap.xml';
17
+
18
+ const lines = [
19
+ `# robots.txt generated from SEO.md — https://seomd.dev`,
20
+ '',
21
+ 'User-agent: *',
22
+ 'Allow: /',
23
+ ...disallow.map((d) => `Disallow: ${d}`),
24
+ '',
25
+ ];
26
+
27
+ if (allowAi) {
28
+ lines.push('# AI Search & Citation Crawlers');
29
+ for (const bot of AI_BOTS) {
30
+ lines.push(`User-agent: ${bot.userAgent}`);
31
+ lines.push(`Allow: ${bot.allow}`);
32
+ lines.push('');
33
+ }
34
+ }
35
+
36
+ lines.push(`Sitemap: ${sitemap.startsWith('http') ? sitemap : `${canonical}${sitemap}`}`);
37
+ lines.push('');
38
+
39
+ return lines.join('\n');
40
+ }
41
+
42
+ export function buildLlmsTxt(data, body = '') {
43
+ const brand = getBrand(data);
44
+ const domain = data.site?.domain || 'example.com';
45
+ const canonical = (data.site?.canonical || `https://${domain}`).replace(/\/$/, '');
46
+ const primaryKeyword = data.keywords?.primary || '';
47
+ const pages = getPages(data);
48
+
49
+ // Use the founder's one-liner from the Markdown body, unless it is still init's template text
50
+ const summary = getFact(body, 'One-liner')
51
+ || `${brand} (${domain}) — ${primaryKeyword || 'official documentation and product pages'}.`;
52
+
53
+ const lines = [
54
+ `# ${brand}`,
55
+ '',
56
+ `> ${summary}`,
57
+ '',
58
+ '## Key Pages',
59
+ '',
60
+ ];
61
+
62
+ const concretePages = pages.filter((p) => p.url && !p.url.includes('['));
63
+ if (concretePages.length > 0) {
64
+ for (const page of concretePages) {
65
+ const fullUrl = `${canonical}${page.url === '/' ? '' : page.url}`;
66
+ const label = page.primary_keyword ? `${page.id} — ${page.primary_keyword}` : page.id;
67
+ lines.push(`- [${label}](${fullUrl})`);
68
+ }
69
+ } else {
70
+ lines.push(`- [Homepage](${canonical})`);
71
+ }
72
+
73
+ const secondary = Array.isArray(data.keywords?.secondary) ? data.keywords.secondary : [];
74
+ if (primaryKeyword || secondary.length > 0) {
75
+ lines.push('');
76
+ lines.push('## Topics');
77
+ lines.push('');
78
+ if (primaryKeyword) lines.push(`- ${primaryKeyword}`);
79
+ for (const kw of secondary) {
80
+ lines.push(`- ${kw}`);
81
+ }
82
+ }
83
+
84
+ lines.push('');
85
+ return lines.join('\n');
86
+ }
87
+
88
+ export function buildSchemaJsonLd(data, body = '') {
89
+ const brand = getBrand(data);
90
+ const domain = data.site?.domain || 'example.com';
91
+ const canonical = (data.site?.canonical || `https://${domain}`).replace(/\/$/, '');
92
+ const siteType = data.site?.type || 'saas';
93
+ const types = Array.isArray(data.schema?.types) && data.schema.types.length > 0
94
+ ? data.schema.types
95
+ : (SCHEMA_TYPES[siteType] || SCHEMA_TYPES.saas);
96
+
97
+ const graph = [];
98
+
99
+ if (types.includes('Organization')) {
100
+ graph.push({
101
+ '@type': 'Organization',
102
+ name: brand,
103
+ url: canonical,
104
+ });
105
+ }
106
+
107
+ if (types.includes('SoftwareApplication')) {
108
+ graph.push({
109
+ '@type': 'SoftwareApplication',
110
+ name: brand,
111
+ applicationCategory: 'BusinessApplication',
112
+ url: canonical,
113
+ });
114
+ }
115
+
116
+ if (types.includes('LocalBusiness')) {
117
+ graph.push({
118
+ '@type': 'LocalBusiness',
119
+ name: brand,
120
+ url: canonical,
121
+ });
122
+ }
123
+
124
+ if (types.includes('WebSite')) {
125
+ graph.push({
126
+ '@type': 'WebSite',
127
+ name: brand,
128
+ url: canonical,
129
+ });
130
+ }
131
+
132
+ // Only emit an FAQ answer the founder actually wrote; never publish template text as a fact
133
+ const oneLiner = getFact(body, 'One-liner');
134
+ if (types.includes('FAQPage') && oneLiner) {
135
+ graph.push({
136
+ '@type': 'FAQPage',
137
+ mainEntity: [
138
+ {
139
+ '@type': 'Question',
140
+ name: `What is ${brand}?`,
141
+ acceptedAnswer: {
142
+ '@type': 'Answer',
143
+ text: oneLiner,
144
+ },
145
+ },
146
+ ],
147
+ });
148
+ }
149
+
150
+ if (graph.length === 0) {
151
+ graph.push({
152
+ '@type': 'WebPage',
153
+ name: brand,
154
+ url: canonical,
155
+ });
156
+ }
157
+
158
+ return JSON.stringify(
159
+ {
160
+ '@context': 'https://schema.org',
161
+ '@graph': graph,
162
+ },
163
+ null,
164
+ 2
165
+ ) + '\n';
166
+ }
167
+
168
+ export async function generateCommand(target, options = {}) {
169
+ const normalizedTarget = String(target || '').trim().toLowerCase();
170
+
171
+ if (!VALID_TARGETS.includes(normalizedTarget)) {
172
+ console.log(chalk.red(`✗ Unknown generate target '${target}'. Valid targets: ${VALID_TARGETS.join(', ')}`));
173
+ process.exitCode = 1;
174
+ return;
175
+ }
176
+
177
+ try {
178
+ const cwd = process.cwd();
179
+ const { data, body } = await parseSeoMd(cwd);
180
+
181
+ // llms.txt and JSON-LD draw on the Canonical Product Facts; flag any still left as template text
182
+ const placeholders = normalizedTarget === 'robots' ? [] : findPlaceholders(body);
183
+ if (placeholders.length > 0) {
184
+ const list = placeholders.join(', ');
185
+ if (options.strict) {
186
+ console.error(chalk.red(`✗ SEO.md still has template text in: ${list}. Fill in Canonical Product Facts, then re-run.`));
187
+ process.exitCode = 1;
188
+ return;
189
+ }
190
+ console.error(chalk.yellow(`⚠ SEO.md still has template text in: ${list}. Those facts were left out of the ${normalizedTarget} output.`));
191
+ }
192
+
193
+ let output = '';
194
+ if (normalizedTarget === 'robots') {
195
+ output = buildRobotsTxt(data);
196
+ } else if (normalizedTarget === 'llms') {
197
+ output = buildLlmsTxt(data, body);
198
+ } else if (normalizedTarget === 'schema') {
199
+ output = buildSchemaJsonLd(data, body);
200
+ }
201
+
202
+ if (options.out) {
203
+ const outPath = path.resolve(cwd, options.out);
204
+ await fs.ensureDir(path.dirname(outPath));
205
+ await fs.writeFile(outPath, output, 'utf8');
206
+ console.log(chalk.green(`✓ Generated ${normalizedTarget} -> ${path.relative(cwd, outPath) || outPath}`));
207
+ } else {
208
+ process.stdout.write(output);
209
+ }
210
+ process.exitCode = 0;
211
+ } catch (err) {
212
+ console.log(chalk.red(`✗ Generate failed: ${err.message}`));
213
+ process.exitCode = 1;
214
+ }
215
+ }
@@ -1,102 +1,178 @@
1
1
  import chalk from 'chalk';
2
2
  import enquirer from 'enquirer';
3
- const { prompt } = enquirer;
4
3
  import ora from 'ora';
5
4
  import fs from 'fs-extra';
6
5
  import path from 'path';
7
- import { generateSeoMd } from '../generators/seomd.js';
6
+ import { readFileSync } from 'fs';
7
+ import { fileURLToPath } from 'url';
8
+ import { generateSeoMd, normalizeDomain } from '../generators/seomd.js';
8
9
  import { generateReverseMd } from '../generators/reverse.js';
9
10
  import { createSeomdDir } from '../generators/directory.js';
10
- import { SITE_TYPES } from '../utils/constants.js';
11
+ import { scanRepo } from '../utils/repo-scanner.js';
12
+ import { wireAgentFiles } from '../utils/agent-wiring.js';
13
+ import { parseSeoMd } from '../utils/parser.js';
14
+ import { seedFromExisting, backupSeoMd } from '../utils/migrate.js';
15
+ import { SITE_TYPES, VALID_SITE_TYPES, SITE_TYPE_PROFILES } from '../utils/constants.js';
16
+
17
+ const { prompt } = enquirer;
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+ const pkg = JSON.parse(readFileSync(path.join(__dirname, '../../package.json'), 'utf8'));
11
20
 
12
- export async function initCommand(options) {
21
+ export async function initCommand(options = {}) {
13
22
  console.log('');
14
- console.log(chalk.bold('SEO.md') + chalk.dim(' v0.1.0 — https://seomd.dev'));
23
+ console.log(chalk.bold('SEO.md') + chalk.dim(` v${pkg.version} — https://seomd.dev`));
15
24
  console.log('');
16
- console.log(chalk.dim('The open standard for AI-era SEO configuration.'));
25
+ console.log(chalk.dim('The open standard for AI-era search & citation configuration.'));
17
26
  console.log('');
18
27
 
28
+ // Validate --type upfront before touching the filesystem
29
+ if (options.type && !VALID_SITE_TYPES.includes(options.type)) {
30
+ console.log(
31
+ chalk.red(`Invalid --type '${options.type}'. Must be one of: ${VALID_SITE_TYPES.join(', ')}`)
32
+ );
33
+ process.exitCode = 1;
34
+ return;
35
+ }
36
+
19
37
  // Determine target directory
20
38
  let workingDir = process.cwd();
21
39
  if (options.output) {
22
40
  const resolved = path.resolve(options.output);
23
- if (await fs.pathExists(resolved) && (await fs.readdir(resolved)).length > 0) {
41
+ if ((await fs.pathExists(resolved)) && (await fs.readdir(resolved)).length > 0) {
24
42
  console.log(chalk.red(`Output directory must be empty or non-existent: ${resolved}`));
25
- process.exit(1);
43
+ process.exitCode = 1;
44
+ return;
26
45
  }
27
46
  await fs.ensureDir(resolved);
28
47
  workingDir = resolved;
29
48
  }
30
49
 
50
+ // Non-interactive if -y OR any config flag provided
51
+ const hasConfigFlags =
52
+ options.brand !== undefined ||
53
+ options.domain !== undefined ||
54
+ options.primaryKeyword !== undefined ||
55
+ options.competitors !== undefined;
56
+ const isNonInteractive = Boolean(options.yes || hasConfigFlags);
57
+
58
+ // An existing SEO.md is never replaced silently:
59
+ // - v1 (legacy) files are upgraded in place, keeping their values
60
+ // - v2 / unreadable files need --force (or an interactive yes)
61
+ // and the previous file is always backed up first.
31
62
  const seomdPath = path.join(workingDir, 'SEO.md');
63
+ let existing = null;
32
64
  if (await fs.pathExists(seomdPath)) {
33
- console.log(chalk.yellow('⚠ SEO.md already exists in this directory.'));
34
- const { overwrite } = await prompt({
35
- type: 'confirm',
36
- name: 'overwrite',
37
- message: 'Overwrite existing SEO.md?',
38
- initial: false,
39
- });
40
- if (!overwrite) {
41
- console.log(chalk.dim('Aborted.'));
42
- process.exit(0);
65
+ let parsed = null;
66
+ try {
67
+ parsed = await parseSeoMd(workingDir);
68
+ } catch {
69
+ parsed = null;
43
70
  }
71
+ const isLegacy = parsed?.format === 'v1';
72
+
73
+ if (!options.force) {
74
+ if (isNonInteractive && !isLegacy) {
75
+ console.log(chalk.red('✗ SEO.md already exists in this directory. Nothing was changed.'));
76
+ console.log(chalk.dim(' Re-run with --force to regenerate it (the current file is backed up to SEO.md.bak).'));
77
+ process.exitCode = 1;
78
+ return;
79
+ }
80
+ if (!isNonInteractive) {
81
+ console.log(chalk.yellow(isLegacy
82
+ ? '⚠ Found a v1 SEO.md. init can upgrade it to v2, keeping your brand, keywords, intent queries, and pages.'
83
+ : '⚠ SEO.md already exists in this directory.'));
84
+ const { overwrite } = await prompt({
85
+ type: 'confirm',
86
+ name: 'overwrite',
87
+ message: isLegacy
88
+ ? 'Upgrade SEO.md to v2? (current file is backed up to SEO.md.bak)'
89
+ : 'Overwrite existing SEO.md? (current file is backed up to SEO.md.bak)',
90
+ initial: isLegacy,
91
+ });
92
+ if (!overwrite) {
93
+ console.log(chalk.dim('Aborted.'));
94
+ process.exitCode = 0;
95
+ return;
96
+ }
97
+ }
98
+ }
99
+ existing = { parsed, isLegacy };
44
100
  }
101
+ const seed = seedFromExisting(existing?.parsed?.data);
45
102
 
46
- let answers;
103
+ // Inspect repository for framework, existing routes, and crawl files
104
+ const repoInfo = await scanRepo(workingDir);
105
+ if (repoInfo.framework || repoInfo.routes.length > 0) {
106
+ const fwLabel = repoInfo.framework ? ` (${repoInfo.framework})` : '';
107
+ console.log(
108
+ chalk.dim(
109
+ `Detected project${fwLabel}: ${repoInfo.routes.length} route(s) discovered`
110
+ )
111
+ );
112
+ console.log('');
113
+ }
47
114
 
48
- // Mode 5: non-interactive if -y OR any config field provided
49
- const hasConfigFlags =
50
- options.brand !== undefined ||
51
- options.domain !== undefined ||
52
- options.primaryKeyword !== undefined ||
53
- options.competitors !== undefined;
115
+ const inferredBrand = seed.answers.brand || (repoInfo.packageName
116
+ ? repoInfo.packageName.replace(/^@[^/]+\//, '').replace(/[-_]+/g, ' ')
117
+ : 'My Brand');
118
+ const inferredDomain = seed.answers.domain || (repoInfo.homepage
119
+ ? normalizeDomain(repoInfo.homepage)
120
+ : 'example.com');
54
121
 
55
- if (options.yes || hasConfigFlags) {
122
+ let answers;
123
+ if (isNonInteractive) {
124
+ const siteType = options.type || seed.answers.site_type || 'saas';
125
+ const profile = SITE_TYPE_PROFILES[siteType];
56
126
  answers = {
57
- site_type: options.type || 'saas',
58
- domain: options.domain || 'example.com',
59
- brand: options.brand || 'My Brand',
60
- primary_keyword: options.primaryKeyword || '',
127
+ site_type: siteType,
128
+ domain: normalizeDomain(options.domain || inferredDomain),
129
+ brand: (options.brand || inferredBrand).trim(),
130
+ primary_keyword: (options.primaryKeyword || seed.answers.primary_keyword || profile.defaultKeyword).trim(),
61
131
  competitors: options.competitors
62
132
  ? options.competitors
63
133
  .split(',')
64
- .map((c) => c.trim())
134
+ .map((c) => normalizeDomain(c))
65
135
  .filter(Boolean)
66
- .slice(0, 3)
67
- : [],
136
+ .slice(0, 5)
137
+ : (seed.answers.competitors || []).map((c) => normalizeDomain(c)).filter(Boolean),
138
+ provider: options.provider || seed.answers.provider || null,
68
139
  };
69
140
  } else {
70
- // The 5-question init flow
141
+ const typeForPrompt = options.type || seed.answers.site_type;
142
+ const initialTypeIdx = typeForPrompt
143
+ ? Math.max(0, SITE_TYPES.findIndex((t) => t.value === typeForPrompt))
144
+ : 0;
145
+
71
146
  answers = await prompt([
72
147
  {
73
148
  type: 'select',
74
149
  name: 'site_type',
75
150
  message: 'Site type:',
76
- choices: SITE_TYPES.map(t => ({ name: t.value, message: t.name })),
77
- initial: options.type ? SITE_TYPES.findIndex(t => t.value === options.type) : 0,
151
+ choices: SITE_TYPES.map((t) => ({ name: t.value, message: t.name })),
152
+ initial: initialTypeIdx,
78
153
  },
79
154
  {
80
155
  type: 'input',
81
156
  name: 'domain',
82
157
  message: 'Primary domain:',
158
+ initial: inferredDomain !== 'example.com' ? inferredDomain : undefined,
83
159
  hint: 'e.g. myapp.com',
84
160
  validate(value) {
85
- if (!value) return 'Domain is required';
86
- // Strip protocol if provided
161
+ if (!value || !value.trim()) return 'Domain is required';
87
162
  return true;
88
163
  },
89
164
  result(value) {
90
- return value.replace(/^https?:\/\//, '').replace(/\/$/, '');
165
+ return normalizeDomain(value);
91
166
  },
92
167
  },
93
168
  {
94
169
  type: 'input',
95
170
  name: 'brand',
96
171
  message: 'Brand name:',
172
+ initial: inferredBrand !== 'My Brand' ? inferredBrand : undefined,
97
173
  hint: 'e.g. MyApp',
98
174
  validate(value) {
99
- if (!value) return 'Brand name is required';
175
+ if (!value || !value.trim()) return 'Brand name is required';
100
176
  return true;
101
177
  },
102
178
  },
@@ -104,66 +180,94 @@ export async function initCommand(options) {
104
180
  type: 'input',
105
181
  name: 'primary_keyword',
106
182
  message: 'Primary keyword:',
183
+ initial: seed.answers.primary_keyword,
107
184
  hint: 'e.g. project management software',
108
185
  validate(value) {
109
- if (!value) return 'Primary keyword is required';
186
+ if (!value || !value.trim()) return 'Primary keyword is required';
110
187
  return true;
111
188
  },
112
189
  },
113
190
  {
114
191
  type: 'input',
115
192
  name: 'competitors',
116
- message: 'Top 3 competitors (comma separated):',
193
+ message: 'Top competitors (comma separated, optional):',
194
+ initial: seed.answers.competitors ? seed.answers.competitors.join(', ') : undefined,
117
195
  hint: 'e.g. asana.com, monday.com, notion.so',
118
196
  result(value) {
119
- return value
197
+ return String(value || '')
120
198
  .split(',')
121
- .map(c => c.trim())
199
+ .map((c) => normalizeDomain(c))
122
200
  .filter(Boolean)
123
- .slice(0, 3);
201
+ .slice(0, 5);
124
202
  },
125
203
  },
126
204
  ]);
205
+ answers.provider = options.provider || seed.answers.provider || null;
127
206
  }
207
+ answers.carry = seed.carry;
128
208
 
129
209
  console.log('');
130
- const spinner = ora('Scaffolding your SEO.md files...').start();
210
+ const spinner = ora('Scaffolding your SEO.md workspace...').start();
131
211
 
132
212
  try {
133
- // 1. Generate SEO.md
134
- const seomdContent = generateSeoMd(answers);
213
+ // 1. Generate v2 SEO.md (YAML frontmatter + Markdown body), backing up any existing file
214
+ const seomdContent = generateSeoMd(answers, repoInfo);
215
+ if (existing) {
216
+ const backupName = await backupSeoMd(workingDir);
217
+ spinner.succeed(chalk.green(`Previous SEO.md backed up to ${backupName}`));
218
+ }
135
219
  await fs.writeFile(path.join(workingDir, 'SEO.md'), seomdContent, 'utf8');
136
- spinner.succeed(chalk.green('SEO.md created'));
220
+ spinner.succeed(chalk.green(existing?.isLegacy
221
+ ? 'SEO.md upgraded from v1 to spec v2.0.0 (values carried over)'
222
+ : 'SEO.md created (spec v2.0.0)'));
137
223
 
138
- // 2. Create .seo/ directory structure
224
+ // 2. Create .seo/ workspace directory (keeps an existing .seo/README.md)
139
225
  await createSeomdDir(workingDir, answers);
140
- spinner.succeed(chalk.green('.seo/ directory created'));
141
-
142
- // 3. Generate .seo/REVERSE.md
143
- const reverseContent = generateReverseMd(answers);
144
- await fs.writeFile(path.join(workingDir, '.seo', 'REVERSE.md'), reverseContent, 'utf8');
145
- spinner.succeed(chalk.green('.seo/REVERSE.md initialized'));
226
+ spinner.succeed(chalk.green('.seo/ workspace ready'));
146
227
 
228
+ // 3. Initialize .seo/REVERSE.md: provider-generated intelligence, never overwritten
229
+ const reversePath = path.join(workingDir, '.seo', 'REVERSE.md');
230
+ if (await fs.pathExists(reversePath)) {
231
+ spinner.succeed(chalk.green('.seo/REVERSE.md kept (existing provider intelligence)'));
232
+ } else {
233
+ await fs.writeFile(reversePath, generateReverseMd(answers), 'utf8');
234
+ spinner.succeed(chalk.green('.seo/REVERSE.md initialized'));
235
+ }
147
236
 
237
+ // 4. Wire AGENTS.md / CLAUDE.md unless opted out via --no-wire-agents
238
+ let agentResult = { updated: [], created: [] };
239
+ if (options.wireAgents !== false) {
240
+ agentResult = await wireAgentFiles(workingDir);
241
+ const wiredList = [...agentResult.created, ...agentResult.updated];
242
+ if (wiredList.length > 0) {
243
+ spinner.succeed(chalk.green(`Agent instructions wired into ${wiredList.join(', ')}`));
244
+ }
245
+ }
148
246
 
149
247
  console.log('');
150
248
  console.log(chalk.bold.green('✓ SEO.md initialized successfully'));
151
249
  console.log('');
152
- console.log(chalk.dim('Files created:'));
153
- console.log(' ' + chalk.cyan('SEO.md') + chalk.dim(' — your living SEO config'));
154
- console.log(' ' + chalk.cyan('.seo/REVERSE.md') + chalk.dim(' — reverse engineer output (platform generated)'));
155
- console.log(' ' + chalk.cyan('.seo/') + chalk.dim(' — intelligence directory'));
250
+ console.log(chalk.dim('Files created / updated:'));
251
+ console.log(' ' + chalk.cyan('SEO.md') + chalk.dim(' — your Markdown + frontmatter SEO/AEO spec'));
252
+ console.log(' ' + chalk.cyan('.seo/REVERSE.md') + chalk.dim(' — competitor intelligence scaffold'));
253
+ console.log(' ' + chalk.cyan('.seo/') + chalk.dim(' — provider intelligence workspace'));
254
+ for (const f of [...agentResult.created, ...agentResult.updated]) {
255
+ console.log(' ' + chalk.cyan(f.padEnd(18)) + chalk.dim(' — wired so coding agents auto-read SEO.md'));
256
+ }
156
257
  console.log('');
157
- console.log(chalk.dim('Next steps:'));
158
- console.log(' ' + chalk.white('npx seomd analyze') + chalk.dim(' — run your first citation analysis'));
159
- console.log(' ' + chalk.white('npx seomd status') + chalk.dim(' — view current gap scores'));
258
+ console.log(chalk.dim('Next steps (works locally with zero API key):'));
259
+ console.log(' ' + chalk.white('npx seomd-cli validate') + chalk.dim(' — validate SEO.md'));
260
+ console.log(' ' + chalk.white('npx seomd-cli check ./public') + chalk.dim(' — audit local files / localhost against SEO.md'));
261
+ console.log(' ' + chalk.white('npx seomd-cli generate robots') + chalk.dim(' — generate AI-bot-friendly robots.txt or llms.txt'));
262
+ console.log(' ' + chalk.white('npx seomd-cli doctor') + chalk.dim(' — inspect repo & provider readiness'));
160
263
  console.log('');
161
- console.log(chalk.dim('Connect your platform at ') + chalk.cyan('https://seomd.dev/connect'));
264
+ console.log(chalk.dim('Optional live AI citation scans (any compatible provider — see PROVIDER_SPEC.md):'));
265
+ console.log(' ' + chalk.white('npx seomd-cli analyze') + chalk.dim(' — run live multi-LLM citation analysis'));
162
266
  console.log('');
163
-
267
+ process.exitCode = 0;
164
268
  } catch (err) {
165
269
  spinner.fail(chalk.red('Failed to scaffold SEO.md'));
166
270
  console.error(chalk.dim(err.message));
167
- process.exit(1);
271
+ process.exitCode = 1;
168
272
  }
169
273
  }