seomd-cli 1.4.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 +90 -90
  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 +123 -62
  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 +43 -110
  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 +171 -82
  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 -233
  30. package/src/templates/ecommerce/SEO.REVERSE.md +0 -199
  31. package/src/templates/ecommerce/SEO.md +0 -239
  32. package/src/templates/local/SEO.REVERSE.md +0 -222
  33. package/src/templates/local/SEO.md +0 -245
  34. package/src/templates/marketplace/SEO.REVERSE.md +0 -222
  35. package/src/templates/marketplace/SEO.md +0 -245
  36. package/src/templates/saas/SEO.REVERSE.md +0 -268
  37. package/src/templates/saas/SEO.md +0 -257
@@ -2,45 +2,134 @@ import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import YAML from 'yaml';
4
4
 
5
+ const FRONTMATTER_REGEX = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/;
6
+
5
7
  /**
6
- * Parses the SEO.md file in the specified directory.
7
- * Returns both the plain JavaScript object and the YAML Document (for comment preservation).
8
- *
9
- * @param {string} [cwd=process.cwd()] - Current working directory
10
- * @returns {Promise<{doc: YAML.Document, data: any}>} Parsed SEO.md representation
8
+ * Parses SEO.md in the specified directory.
9
+ * Supports both:
10
+ * - v2: Markdown with YAML frontmatter (`--- ... ---`)
11
+ * - v1 (legacy): Raw YAML document with `#` comment headings
12
+ *
13
+ * @param {string} [cwd=process.cwd()] - Directory containing SEO.md
14
+ * @returns {Promise<{format: 'v2'|'v1', doc: YAML.Document, data: any, body: string, raw: string, filePath: string}>}
11
15
  */
12
16
  export async function parseSeoMd(cwd = process.cwd()) {
13
- const seomdPath = path.join(cwd, 'SEO.md');
14
-
15
- if (!(await fs.pathExists(seomdPath))) {
16
- throw new Error(`SEO.md not found at ${seomdPath}. Run 'seomd init' first.`);
17
+ const filePath = path.join(cwd, 'SEO.md');
18
+
19
+ if (!(await fs.pathExists(filePath))) {
20
+ throw new Error(`SEO.md not found at ${filePath}. Run 'npx seomd-cli init' first.`);
17
21
  }
18
-
19
- const content = await fs.readFile(seomdPath, 'utf8');
20
-
22
+
23
+ const raw = await fs.readFile(filePath, 'utf8');
24
+ const match = raw.match(FRONTMATTER_REGEX);
25
+
21
26
  try {
22
- const doc = YAML.parseDocument(content);
27
+ if (match) {
28
+ const frontmatterText = match[1];
29
+ const body = (match[2] || '').trim();
30
+ const doc = YAML.parseDocument(frontmatterText);
31
+ if (doc.errors && doc.errors.length > 0) {
32
+ throw new Error(doc.errors[0].message);
33
+ }
34
+ const data = doc.toJS();
35
+ if (!data || typeof data !== 'object') {
36
+ throw new Error('SEO.md frontmatter is empty or not a valid YAML object');
37
+ }
38
+ return { format: 'v2', doc, data, body, raw, filePath };
39
+ }
40
+
41
+ // Legacy v1 raw YAML
42
+ const doc = YAML.parseDocument(raw);
43
+ if (doc.errors && doc.errors.length > 0) {
44
+ throw new Error(doc.errors[0].message);
45
+ }
23
46
  const data = doc.toJS();
24
-
25
47
  if (!data || typeof data !== 'object') {
26
48
  throw new Error('SEO.md is empty or invalid YAML structure');
27
49
  }
28
-
29
- return { doc, data };
50
+ return { format: 'v1', doc, data, body: '', raw, filePath };
30
51
  } catch (err) {
31
52
  throw new Error(`Failed to parse SEO.md: ${err.message}`);
32
53
  }
33
54
  }
34
55
 
35
56
  /**
36
- * Writes the YAML Document back to SEO.md in the specified directory.
37
- *
38
- * @param {YAML.Document} doc - The YAML Document to write
39
- * @param {string} [cwd=process.cwd()] - Current working directory
40
- * @returns {Promise<void>}
57
+ * Extracts normalized brand name from v1 or v2 SEO.md data.
58
+ */
59
+ export function getBrand(data) {
60
+ return data?.site?.brand || data?.identity?.brand || 'My Brand';
61
+ }
62
+
63
+ /**
64
+ * Extracts normalized page list from v2 (`pages: [...]`) or v1 (`pages.required` + `pages.optional`).
65
+ */
66
+ export function getPages(data) {
67
+ if (!data?.pages) return [];
68
+
69
+ let rawPages = [];
70
+ if (Array.isArray(data.pages)) {
71
+ rawPages = data.pages;
72
+ } else {
73
+ if (Array.isArray(data.pages.required)) {
74
+ rawPages = rawPages.concat(data.pages.required);
75
+ }
76
+ if (Array.isArray(data.pages.optional)) {
77
+ rawPages = rawPages.concat(data.pages.optional);
78
+ }
79
+ }
80
+
81
+ return rawPages
82
+ .filter((p) => p && typeof p === 'object')
83
+ .map((p) => ({
84
+ ...p,
85
+ primary_keyword: p.primary_keyword || p.keyword || null,
86
+ status: p.status || 'planned',
87
+ priority: p.priority ?? 0,
88
+ }));
89
+ }
90
+
91
+ /**
92
+ * Extracts normalized intent queries map from v1 or v2 SEO.md data.
93
+ */
94
+ export function getIntentQueries(data, filterCategory = null) {
95
+ const queries = {};
96
+ if (!data?.intent || typeof data.intent !== 'object') return queries;
97
+
98
+ const filterLower = filterCategory ? String(filterCategory).trim().toLowerCase() : null;
99
+
100
+ for (const [intentType, obj] of Object.entries(data.intent)) {
101
+ if (intentType === '_analysis') continue;
102
+ if (filterLower && intentType.toLowerCase() !== filterLower) continue;
103
+
104
+ if (Array.isArray(obj)) {
105
+ queries[intentType] = obj;
106
+ } else if (obj && Array.isArray(obj.queries)) {
107
+ queries[intentType] = obj.queries;
108
+ }
109
+ }
110
+
111
+ return queries;
112
+ }
113
+
114
+ /**
115
+ * Extracts normalized competitor domains from v1 or v2 SEO.md data.
116
+ */
117
+ export function getCompetitors(data) {
118
+ const raw = data?.competitors ?? data?.aeo?.competitors_to_monitor ?? [];
119
+ if (!Array.isArray(raw)) return [];
120
+ return raw
121
+ .map((c) => (typeof c === 'string' ? c : c?.domain))
122
+ .filter(Boolean);
123
+ }
124
+
125
+ /**
126
+ * Extracts provider configuration from v2 (`provider`) or v1 (`platform`).
41
127
  */
42
- export async function writeSeoMd(doc, cwd = process.cwd()) {
43
- const seomdPath = path.join(cwd, 'SEO.md');
44
- const content = doc.toString();
45
- await fs.writeFile(seomdPath, content, 'utf8');
128
+ export function getProviderConfig(data) {
129
+ const p = data?.provider || data?.platform || {};
130
+ return {
131
+ name: p.name || p.provider || null,
132
+ endpoint: p.endpoint || p.url || null,
133
+ project_id: p.project_id || null,
134
+ };
46
135
  }
@@ -0,0 +1,207 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+
4
+ const IGNORED_DIRS = new Set([
5
+ 'node_modules',
6
+ '.git',
7
+ '.next',
8
+ '.nuxt',
9
+ '.svelte-kit',
10
+ '.seo',
11
+ 'dist',
12
+ 'build',
13
+ 'out',
14
+ 'coverage',
15
+ 'api',
16
+ ]);
17
+
18
+ /**
19
+ * Inspects a project directory to discover framework, existing public routes,
20
+ * and crawl files (robots.txt, sitemap.xml, llms.txt).
21
+ *
22
+ * @param {string} cwd - Directory to inspect
23
+ * @returns {Promise<{
24
+ * framework: string|null,
25
+ * packageName: string|null,
26
+ * homepage: string|null,
27
+ * routes: string[],
28
+ * hasRobotsTxt: boolean,
29
+ * hasSitemap: boolean,
30
+ * hasLlmsTxt: boolean
31
+ * }>}
32
+ */
33
+ export async function scanRepo(cwd) {
34
+ const result = {
35
+ framework: null,
36
+ packageName: null,
37
+ homepage: null,
38
+ routes: [],
39
+ hasRobotsTxt: false,
40
+ hasSitemap: false,
41
+ hasLlmsTxt: false,
42
+ };
43
+
44
+ // 1. Read package.json if present
45
+ const pkgPath = path.join(cwd, 'package.json');
46
+ if (await fs.pathExists(pkgPath)) {
47
+ try {
48
+ const pkg = await fs.readJson(pkgPath);
49
+ result.packageName = typeof pkg.name === 'string' ? pkg.name : null;
50
+ result.homepage = typeof pkg.homepage === 'string' ? pkg.homepage : null;
51
+
52
+ const deps = {
53
+ ...(pkg.dependencies || {}),
54
+ ...(pkg.devDependencies || {}),
55
+ };
56
+ if (deps.next) result.framework = 'nextjs';
57
+ else if (deps.astro) result.framework = 'astro';
58
+ else if (deps['@sveltejs/kit']) result.framework = 'sveltekit';
59
+ else if (deps['@remix-run/react'] || deps['react-router']) result.framework = 'remix';
60
+ else if (deps.nuxt) result.framework = 'nuxt';
61
+ else if (deps.vite) result.framework = 'vite';
62
+ } catch {
63
+ // Ignore malformed package.json
64
+ }
65
+ }
66
+
67
+ // 2. Check crawl artifacts in public/ or root
68
+ const publicDirs = [path.join(cwd, 'public'), path.join(cwd, 'static'), cwd];
69
+ for (const dir of publicDirs) {
70
+ if (!result.hasRobotsTxt && (await fs.pathExists(path.join(dir, 'robots.txt')))) {
71
+ result.hasRobotsTxt = true;
72
+ }
73
+ if (!result.hasSitemap && (await fs.pathExists(path.join(dir, 'sitemap.xml')))) {
74
+ result.hasSitemap = true;
75
+ }
76
+ if (!result.hasLlmsTxt && (await fs.pathExists(path.join(dir, 'llms.txt')))) {
77
+ result.hasLlmsTxt = true;
78
+ }
79
+ }
80
+
81
+ // Also check Next.js App Router dynamic robots/sitemap conventions
82
+ for (const appBase of [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')]) {
83
+ if (await fs.pathExists(appBase)) {
84
+ for (const ext of ['ts', 'js', 'tsx', 'jsx']) {
85
+ if (!result.hasRobotsTxt && (await fs.pathExists(path.join(appBase, `robots.${ext}`)))) {
86
+ result.hasRobotsTxt = true;
87
+ }
88
+ if (!result.hasSitemap && (await fs.pathExists(path.join(appBase, `sitemap.${ext}`)))) {
89
+ result.hasSitemap = true;
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ // 3. Discover routes based on common conventions
96
+ const routes = new Set();
97
+
98
+ // Next.js App Router: app/**/page.{tsx,jsx,ts,js,mdx}
99
+ for (const appDir of [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')]) {
100
+ if (await fs.pathExists(appDir)) {
101
+ if (!result.framework) result.framework = 'nextjs';
102
+ await walkAppRouter(appDir, '', routes);
103
+ }
104
+ }
105
+
106
+ // Next.js / Astro / Nuxt Pages Router: pages/**/*.{tsx,jsx,ts,js,astro,md,mdx,vue}
107
+ for (const pagesDir of [path.join(cwd, 'pages'), path.join(cwd, 'src', 'pages')]) {
108
+ if (await fs.pathExists(pagesDir)) {
109
+ await walkPagesRouter(pagesDir, '', routes);
110
+ }
111
+ }
112
+
113
+ // SvelteKit: src/routes/**/+page.svelte
114
+ const svelteRoutes = path.join(cwd, 'src', 'routes');
115
+ if (await fs.pathExists(svelteRoutes)) {
116
+ await walkSvelteRoutes(svelteRoutes, '', routes);
117
+ }
118
+
119
+ result.routes = Array.from(routes).sort((a, b) => {
120
+ if (a === '/') return -1;
121
+ if (b === '/') return 1;
122
+ return a.localeCompare(b);
123
+ });
124
+
125
+ return result;
126
+ }
127
+
128
+ async function walkAppRouter(dir, prefix, routes, depth = 0) {
129
+ if (depth > 5) return;
130
+ let entries;
131
+ try {
132
+ entries = await fs.readdir(dir, { withFileTypes: true });
133
+ } catch {
134
+ return;
135
+ }
136
+
137
+ for (const entry of entries) {
138
+ if (entry.isDirectory()) {
139
+ if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('_') || entry.name.startsWith('@')) {
140
+ continue;
141
+ }
142
+ // Route groups like (marketing) do not add a URL segment
143
+ const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');
144
+ const nextPrefix = isGroup ? prefix : `${prefix}/${entry.name}`;
145
+ await walkAppRouter(path.join(dir, entry.name), nextPrefix, routes, depth + 1);
146
+ } else if (/^page\.(tsx|jsx|ts|js|mdx|md)$/.test(entry.name)) {
147
+ routes.add(prefix || '/');
148
+ }
149
+ }
150
+ }
151
+
152
+ async function walkPagesRouter(dir, prefix, routes, depth = 0) {
153
+ if (depth > 5) return;
154
+ let entries;
155
+ try {
156
+ entries = await fs.readdir(dir, { withFileTypes: true });
157
+ } catch {
158
+ return;
159
+ }
160
+
161
+ for (const entry of entries) {
162
+ if (entry.isDirectory()) {
163
+ if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('_')) continue;
164
+ await walkPagesRouter(path.join(dir, entry.name), `${prefix}/${entry.name}`, routes, depth + 1);
165
+ } else if (/\.(tsx|jsx|ts|js|astro|mdx|md|vue)$/.test(entry.name)) {
166
+ const base = entry.name.replace(/\.(tsx|jsx|ts|js|astro|mdx|md|vue)$/, '');
167
+ if (base.startsWith('_') || base === '404' || base === '500') continue;
168
+ const route = base === 'index' ? (prefix || '/') : `${prefix}/${base}`;
169
+ routes.add(route);
170
+ }
171
+ }
172
+ }
173
+
174
+ async function walkSvelteRoutes(dir, prefix, routes, depth = 0) {
175
+ if (depth > 5) return;
176
+ let entries;
177
+ try {
178
+ entries = await fs.readdir(dir, { withFileTypes: true });
179
+ } catch {
180
+ return;
181
+ }
182
+
183
+ for (const entry of entries) {
184
+ if (entry.isDirectory()) {
185
+ if (IGNORED_DIRS.has(entry.name)) continue;
186
+ const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');
187
+ const nextPrefix = isGroup ? prefix : `${prefix}/${entry.name}`;
188
+ await walkSvelteRoutes(path.join(dir, entry.name), nextPrefix, routes, depth + 1);
189
+ } else if (entry.name === '+page.svelte') {
190
+ routes.add(prefix || '/');
191
+ }
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Converts a URL route like `/vs/[competitor]` into a clean page ID slug.
197
+ */
198
+ export function routeToPageId(url) {
199
+ if (!url || url === '/') return 'homepage';
200
+ return url
201
+ .replace(/^\//, '')
202
+ .replace(/\/$/, '')
203
+ .replace(/\[([^\]]+)\]/g, '$1')
204
+ .replace(/[^a-zA-Z0-9]+/g, '-')
205
+ .replace(/^-+|-+$/g, '')
206
+ .toLowerCase() || 'page';
207
+ }
@@ -1,121 +1,210 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import YAML from 'yaml';
4
+ import { INTENT_CATEGORIES } from './constants.js';
4
5
 
5
6
  /**
6
- * Writes platform analysis blocks into the .seo/STATUS.yml file.
7
- *
8
- * @param {YAML.Document} doc - The YAML Document of SEO.md (deprecated, but kept for signature compatibility)
9
- * @param {any} response - The API response from analyze/sync
10
- * @param {string} cwd - Current working directory
7
+ * Sanitizes a page ID so it can never escape `.seo/pages/`.
11
8
  */
12
- export async function writeAnalysisToSeoMd(doc, response, cwd) {
13
- const lastAnalyzed = response.aeo_analysis.last_analyzed;
14
- const nextAnalysis = response.aeo_analysis.next_analysis;
9
+ export function sanitizePageId(id) {
10
+ const cleaned = String(id || 'page')
11
+ .replace(/[^a-zA-Z0-9_-]/g, '-')
12
+ .replace(/-+/g, '-')
13
+ .replace(/^-+|-+$/g, '');
14
+ return cleaned || 'page';
15
+ }
16
+
17
+ function mergePagesById(existingPages = [], incomingPages = []) {
18
+ const map = new Map();
19
+ for (const p of existingPages) {
20
+ if (p && p.id) map.set(p.id, p);
21
+ }
22
+ for (const p of incomingPages) {
23
+ if (p && p.id) map.set(p.id, p);
24
+ }
25
+ return Array.from(map.values());
26
+ }
27
+
28
+ /**
29
+ * Writes (and merges) platform analysis metrics into `.seo/STATUS.yml`.
30
+ *
31
+ * @param {any} _doc - Deprecated parameter kept for backwards signature compatibility
32
+ * @param {any} response - API response from analyze/sync
33
+ * @param {string} cwd - Project root directory
34
+ * @param {{ provider?: string }} [options]
35
+ */
36
+ export async function writeAnalysisToSeoMd(_doc, response, cwd, options = {}) {
37
+ const seomdDir = path.join(cwd, '.seo');
38
+ await fs.ensureDir(seomdDir);
39
+ const statusPath = path.join(seomdDir, 'STATUS.yml');
40
+
41
+ let existing = {};
42
+ if (await fs.pathExists(statusPath)) {
43
+ try {
44
+ existing = YAML.parse(await fs.readFile(statusPath, 'utf8')) || {};
45
+ } catch {
46
+ existing = {};
47
+ }
48
+ }
49
+
50
+ const aeo = response?.aeo_analysis || {};
51
+ const incomingPages = Array.isArray(response?.page_analysis)
52
+ ? response.page_analysis.map((p) => ({
53
+ id: p.id,
54
+ url: p.url,
55
+ citation_rate: p.citation_rate ?? null,
56
+ gap_score: p.gap_score ?? null,
57
+ top_cited_competitor: p.top_cited_competitor ?? null,
58
+ }))
59
+ : [];
60
+
61
+ const existingPages = Array.isArray(existing?.pages?.pages) ? existing.pages.pages : [];
62
+ const mergedPages = mergePagesById(existingPages, incomingPages);
63
+
64
+ const mergedIntent = { ...(existing.intent || {}) };
65
+ if (response?.intent_analysis && typeof response.intent_analysis === 'object') {
66
+ for (const cat of INTENT_CATEGORIES) {
67
+ if (response.intent_analysis[cat]) {
68
+ mergedIntent[cat] = {
69
+ citation_rate: response.intent_analysis[cat].citation_rate ?? null,
70
+ top_cited_competitor: response.intent_analysis[cat].top_cited_competitor ?? null,
71
+ gap_score: response.intent_analysis[cat].gap_score ?? null,
72
+ trend: response.intent_analysis[cat].trend || 'stable',
73
+ };
74
+ }
75
+ }
76
+ }
77
+
78
+ const source = response?.provider || options.provider || existing.source || 'custom';
15
79
 
16
80
  const statusData = {
17
- source: 'foxcite',
18
- last_analyzed: lastAnalyzed,
19
- next_analysis: nextAnalysis,
81
+ source,
82
+ last_analyzed: aeo.last_analyzed ?? existing.last_analyzed ?? null,
83
+ next_analysis: aeo.next_analysis ?? existing.next_analysis ?? null,
20
84
  aeo: {
21
- overall_citation_rate: response.aeo_analysis.overall_citation_rate,
22
- overall_gap_score: response.aeo_analysis.overall_gap_score,
23
- engines_tracked: response.aeo_analysis.engines_tracked,
85
+ overall_citation_rate: aeo.overall_citation_rate ?? existing.aeo?.overall_citation_rate ?? null,
86
+ overall_gap_score: aeo.overall_gap_score ?? existing.aeo?.overall_gap_score ?? null,
87
+ engines_tracked: aeo.engines_tracked ?? existing.aeo?.engines_tracked ?? [],
24
88
  },
25
- intent: {},
89
+ intent: mergedIntent,
26
90
  pages: {
27
- pages: response.page_analysis.map(p => ({
28
- id: p.id,
29
- url: p.url,
30
- citation_rate: p.citation_rate,
31
- gap_score: p.gap_score,
32
- top_cited_competitor: p.top_cited_competitor
33
- })),
34
- missing_pages: [],
35
- build_order_recommendation: []
91
+ pages: mergedPages,
92
+ missing_pages: existing.pages?.missing_pages || [],
93
+ build_order_recommendation: existing.pages?.build_order_recommendation || [],
36
94
  },
37
- keywords: {}
95
+ keywords: existing.keywords || {},
38
96
  };
39
97
 
40
- const categories = ['informational', 'comparison', 'transactional', 'reputational', 'category'];
41
- for (const cat of categories) {
42
- if (response.intent_analysis && response.intent_analysis[cat]) {
43
- statusData.intent[cat] = {
44
- citation_rate: response.intent_analysis[cat].citation_rate,
45
- top_cited_competitor: response.intent_analysis[cat].top_cited_competitor,
46
- gap_score: response.intent_analysis[cat].gap_score,
47
- trend: response.intent_analysis[cat].trend || 'stable'
48
- };
49
- }
50
- }
98
+ const header = [
99
+ '# .seo/STATUS.yml',
100
+ '#',
101
+ '# Auto-generated by your connected SEO.md provider.',
102
+ '# Do not edit manually — run `npx seomd-cli analyze` or `npx seomd-cli sync` to update.',
103
+ '',
104
+ ].join('\n');
51
105
 
52
- const seomdDir = path.join(cwd, '.seo');
53
- await fs.ensureDir(seomdDir);
54
- const statusPath = path.join(seomdDir, 'STATUS.yml');
55
-
56
- const header = `# .seo/STATUS.yml\n#\n# This file is auto-generated by your connected SEO.md platform.\n# Do not edit manually — run \`npx seomd analyze\` to update.\n# Run \`npx seomd sync\` to pull latest intelligence.\n\n`;
57
- await fs.writeFile(statusPath, header + YAML.stringify(statusData), 'utf8');
106
+ await fs.writeFile(statusPath, `${header}\n${YAML.stringify(statusData)}`, 'utf8');
58
107
  }
59
108
 
109
+ export const writeStatusYml = writeAnalysisToSeoMd;
110
+
60
111
  /**
61
- * Generates and writes the .seo/REVERSE.md file.
62
- *
63
- * @param {string} cwd - Current working directory
64
- * @param {any} response - The API response from analyze/sync
112
+ * Generates and merges `.seo/REVERSE.md`.
113
+ *
114
+ * @param {string} cwd - Project root directory
115
+ * @param {any} response - API response from analyze/sync
116
+ * @param {string} [defaultDomain='example.com']
117
+ * @param {string} [defaultBrand='My Brand']
118
+ * @param {{ provider?: string }} [options]
65
119
  */
66
- export async function writeReverseMd(cwd, response, defaultDomain = 'example.com', defaultBrand = 'My Brand') {
120
+ export async function writeReverseMd(
121
+ cwd,
122
+ response,
123
+ defaultDomain = 'example.com',
124
+ defaultBrand = 'My Brand',
125
+ options = {}
126
+ ) {
67
127
  const seomdDir = path.join(cwd, '.seo');
68
128
  await fs.ensureDir(seomdDir);
69
129
  const reversePath = path.join(seomdDir, 'REVERSE.md');
70
130
 
71
- const reversePages = response.page_analysis.map(p => ({
72
- id: p.id,
73
- url: p.url,
74
- status: p.status || 'planned',
75
- citation_rate: p.citation_rate,
76
- gap_score: p.gap_score,
77
- top_cited_competitor: p.top_cited_competitor,
78
- why_page_won: p.why_page_won || [],
79
- citation_hooks: p.citation_hooks || [],
80
- gaps_for_my_brand: p.gaps_for_brand || [],
81
- remediation_playbook: p.remediation_playbook || [],
82
- fastest_win: p.fastest_win || { action: null, estimated_gap_score_improvement: null, effort: null },
83
- suggested_content_outline: p.suggested_content_outline || []
84
- }));
85
-
86
- const primaryCompetitor = response.intent_analysis?.comparison?.top_cited_competitor || 'None';
131
+ let existing = {};
132
+ if (await fs.pathExists(reversePath)) {
133
+ try {
134
+ existing = YAML.parse(await fs.readFile(reversePath, 'utf8')) || {};
135
+ } catch {
136
+ existing = {};
137
+ }
138
+ }
139
+
140
+ const incomingPages = Array.isArray(response?.page_analysis)
141
+ ? response.page_analysis.map((p) => ({
142
+ id: p.id,
143
+ url: p.url,
144
+ status: p.status || 'planned',
145
+ citation_rate: p.citation_rate ?? null,
146
+ gap_score: p.gap_score ?? null,
147
+ top_cited_competitor: p.top_cited_competitor ?? null,
148
+ why_page_won: p.why_page_won || [],
149
+ citation_hooks: p.citation_hooks || [],
150
+ gaps_for_brand: p.gaps_for_brand || p.gaps_for_my_brand || [],
151
+ remediation_playbook: p.remediation_playbook || [],
152
+ fastest_win: p.fastest_win || { action: null, estimated_gap_score_improvement: null, effort: null },
153
+ suggested_content_outline: p.suggested_content_outline || [],
154
+ }))
155
+ : [];
156
+
157
+ const existingPages = Array.isArray(existing.pages) ? existing.pages : [];
158
+ const mergedPages = mergePagesById(existingPages, incomingPages);
159
+
160
+ const aeo = response?.aeo_analysis || {};
161
+ const primaryCompetitor =
162
+ response?.intent_analysis?.comparison?.top_cited_competitor ||
163
+ existing.primary_competitor ||
164
+ null;
165
+
166
+ const source = response?.provider || options.provider || existing.source || 'custom';
87
167
 
88
168
  const reverseDoc = {
89
- domain: response.domain || defaultDomain,
90
- brand: response.brand_name || defaultBrand,
169
+ domain: response?.domain || existing.domain || defaultDomain,
170
+ brand: response?.brand_name || existing.brand || defaultBrand,
91
171
  primary_competitor: primaryCompetitor,
92
- last_analyzed: response.aeo_analysis.last_analyzed,
93
- next_analysis: response.aeo_analysis.next_analysis,
94
- source: 'foxcite',
95
- pages: reversePages
172
+ last_analyzed: aeo.last_analyzed ?? existing.last_analyzed ?? null,
173
+ next_analysis: aeo.next_analysis ?? existing.next_analysis ?? null,
174
+ source,
175
+ pages: mergedPages,
176
+ ...(Array.isArray(existing.competitors) ? { competitors: existing.competitors } : {}),
96
177
  };
97
178
 
98
- const header = `# .seo/REVERSE.md\n#\n# This file is auto-generated by your connected SEO.md platform.\n# Do not edit manually — run \`npx seomd analyze\` to update.\n# Run \`npx seomd sync\` to pull latest intelligence.\n\n`;
179
+ const header = [
180
+ '# .seo/REVERSE.md',
181
+ '#',
182
+ '# Auto-generated by your connected SEO.md provider.',
183
+ '# Do not edit manually — run `npx seomd-cli analyze` or `npx seomd-cli sync` to update.',
184
+ '',
185
+ ].join('\n');
99
186
 
100
- const yamlContent = YAML.stringify(reverseDoc);
101
- await fs.writeFile(reversePath, header + yamlContent, 'utf8');
187
+ await fs.writeFile(reversePath, `${header}\n${YAML.stringify(reverseDoc)}`, 'utf8');
102
188
  }
103
189
 
104
190
  /**
105
- * Writes individual page playbooks into .seo/pages/{id}.md files.
106
- *
107
- * @param {string} cwd - Current working directory
108
- * @param {any} response - The API response from analyze/sync
191
+ * Writes individual page playbooks into `.seo/pages/{sanitized-id}.md`.
192
+ *
193
+ * @param {string} cwd - Project root directory
194
+ * @param {any} response - API response from analyze/sync
109
195
  */
110
196
  export async function writePageAnalysis(cwd, response) {
111
- const seomdDir = path.join(cwd, '.seo');
112
- const pagesDir = path.join(seomdDir, 'pages');
113
-
197
+ const pagesDir = path.resolve(cwd, '.seo', 'pages');
114
198
  await fs.ensureDir(pagesDir);
115
199
 
116
- for (const page of response.page_analysis) {
117
- if (page.markdown_content) {
118
- const filePath = path.join(pagesDir, `${page.id}.md`);
200
+ const pages = Array.isArray(response?.page_analysis) ? response.page_analysis : [];
201
+ for (const page of pages) {
202
+ if (page && page.markdown_content) {
203
+ const safeId = sanitizePageId(page.id);
204
+ const filePath = path.resolve(pagesDir, `${safeId}.md`);
205
+ if (!filePath.startsWith(pagesDir + path.sep)) {
206
+ continue;
207
+ }
119
208
  await fs.writeFile(filePath, page.markdown_content, 'utf8');
120
209
  }
121
210
  }