@businesskit/agent 1.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 (84) hide show
  1. package/.agents/skills/agents.md +56 -0
  2. package/.agents/skills/analytics.md +47 -0
  3. package/.agents/skills/brand.md +87 -0
  4. package/.agents/skills/schema.md +45 -0
  5. package/.agents/skills/store.md +46 -0
  6. package/.claude/commands/analytics.md +7 -0
  7. package/.claude/commands/blog-writer.md +9 -0
  8. package/.claude/commands/cbo.md +7 -0
  9. package/.claude/commands/ceo.md +10 -0
  10. package/.claude/commands/cmo.md +7 -0
  11. package/.claude/commands/compress.md +73 -0
  12. package/.claude/commands/coo.md +11 -0
  13. package/.claude/commands/copywriter.md +15 -0
  14. package/.claude/commands/course-creator.md +9 -0
  15. package/.claude/commands/crm.md +82 -0
  16. package/.claude/commands/deep.md +50 -0
  17. package/.claude/commands/docs-writer.md +8 -0
  18. package/.claude/commands/forms-builder.md +10 -0
  19. package/.claude/commands/jobs-manager.md +8 -0
  20. package/.claude/commands/kb.md +107 -0
  21. package/.claude/commands/newsletter-writer.md +9 -0
  22. package/.claude/commands/preserve.md +64 -0
  23. package/.claude/commands/resume.md +67 -0
  24. package/.claude/commands/scheduler.md +8 -0
  25. package/.claude/commands/seo.md +60 -0
  26. package/.claude/commands/social.md +51 -0
  27. package/.claude/commands/store-manager.md +11 -0
  28. package/.claude/skills/README.md +33 -0
  29. package/.claude/skills/agents.md +56 -0
  30. package/.claude/skills/analytics.md +7 -0
  31. package/.claude/skills/blog-writing.md +452 -0
  32. package/.claude/skills/brand.md +44 -0
  33. package/.claude/skills/content-seo.md +0 -0
  34. package/.claude/skills/humanizer.md +474 -0
  35. package/.claude/skills/schema.md +45 -0
  36. package/.claude/skills/social-content.md +278 -0
  37. package/.claude/skills/store-copywriting.md +519 -0
  38. package/.claude/skills/store.md +62 -0
  39. package/.claude-plugin/plugin.json +33 -0
  40. package/.cursorrules +0 -0
  41. package/.env.example +2 -0
  42. package/.mcp.json +3 -0
  43. package/AGENTS.md +63 -0
  44. package/CLAUDE.md +221 -0
  45. package/GEMINI.md +37 -0
  46. package/LICENSE +21 -0
  47. package/PLAN.md +253 -0
  48. package/PRD-Agent-Harness.md +316 -0
  49. package/README.md +237 -0
  50. package/SYSTEM.md +49 -0
  51. package/agents/_base.ts +63 -0
  52. package/agents/creators/blog-writer.ts +347 -0
  53. package/agents/creators/copywriter.ts +89 -0
  54. package/agents/creators/course-creator.ts +106 -0
  55. package/agents/creators/crm-agent.ts +479 -0
  56. package/agents/creators/docs-writer.ts +77 -0
  57. package/agents/creators/forms-builder.ts +90 -0
  58. package/agents/creators/jobs-manager.ts +82 -0
  59. package/agents/creators/newsletter-writer.ts +91 -0
  60. package/agents/creators/store-manager.ts +138 -0
  61. package/agents/csuite/cbo.ts +109 -0
  62. package/agents/csuite/ceo.ts +121 -0
  63. package/agents/csuite/cmo.ts +109 -0
  64. package/agents/csuite/coo.ts +115 -0
  65. package/agents/growth/analytics-agent.ts +52 -0
  66. package/agents/growth/scheduler.ts +68 -0
  67. package/agents/growth/seo-agent.ts +282 -0
  68. package/agents/growth/social-agent.ts +346 -0
  69. package/bin/businesskit.js +17 -0
  70. package/cli.ts +125 -0
  71. package/context/brand.md +80 -0
  72. package/context/business.md +66 -0
  73. package/lib/analytics.ts +81 -0
  74. package/lib/db.adapter.ts +30 -0
  75. package/lib/db.ts +16 -0
  76. package/lib/id.ts +15 -0
  77. package/lib/kb.ts +337 -0
  78. package/lib/memory.ts +219 -0
  79. package/lib/pattern-detector.ts +169 -0
  80. package/lib/profile.ts +119 -0
  81. package/lib/slug.ts +30 -0
  82. package/package.json +50 -0
  83. package/setup.ts +127 -0
  84. package/tsconfig.json +13 -0
@@ -0,0 +1,115 @@
1
+ /**
2
+ * OTTO — Chief Operating Officer
3
+ * "Pipelines don't run themselves. I make sure they do."
4
+ * Manages: publish queue, draft pipeline, scheduling
5
+ * Phase 3: becomes the CF Durable Object that runs everything autonomously
6
+ */
7
+
8
+ import { BaseAgent, db, now, iso } from '../_base.ts'
9
+
10
+ interface ScheduledItem {
11
+ table: string; id: string; title: string; scheduled_for: string | number
12
+ }
13
+
14
+ export class COO extends BaseAgent {
15
+ readonly name = 'OTTO'
16
+ readonly title = 'Chief Operating Officer'
17
+
18
+ /** All drafts across every content type */
19
+ async draftPipeline() {
20
+ await this.init()
21
+ const tables = [
22
+ { table: 'posts', label: 'Blog Posts', dateCol: 'date' },
23
+ { table: 'products', label: 'Products', dateCol: null },
24
+ { table: 'pages', label: 'Pages', dateCol: null },
25
+ { table: 'job_listings', label: 'Jobs', dateCol: null },
26
+ { table: 'forms', label: 'Forms', dateCol: null },
27
+ ]
28
+
29
+ const results = await Promise.all(tables.map(async ({ table, label, dateCol }) => {
30
+ const { rows } = await db.execute({
31
+ sql: `SELECT id, title, ${dateCol ?? 'created_at'} AS scheduled_for
32
+ FROM ${table} WHERE profile_id=? AND published=0 AND hidden=0
33
+ ORDER BY created_at DESC`,
34
+ args: [this.profileId],
35
+ })
36
+ return { label, table, drafts: rows }
37
+ }))
38
+
39
+ return results.filter(r => r.drafts.length > 0)
40
+ }
41
+
42
+ /** Content due for publish right now */
43
+ async publishQueue(): Promise<ScheduledItem[]> {
44
+ await this.init()
45
+ const nowUnix = now()
46
+ const nowISO = iso()
47
+ const queue: ScheduledItem[] = []
48
+
49
+ // ISO date tables: posts, job_listings
50
+ for (const table of ['posts', 'job_listings']) {
51
+ const { rows } = await db.execute({
52
+ sql: `SELECT id, title, date AS scheduled_for FROM ${table}
53
+ WHERE profile_id=? AND published=0 AND hidden=0
54
+ AND date IS NOT NULL AND date <= ? ORDER BY date ASC`,
55
+ args: [this.profileId, nowISO],
56
+ })
57
+ rows.forEach(r => queue.push({ table, id: r.id as string, title: r.title as string, scheduled_for: r.scheduled_for as string }))
58
+ }
59
+
60
+ // Unix timestamp tables: products
61
+ const { rows: products } = await db.execute({
62
+ sql: `SELECT id, title, published_at AS scheduled_for FROM products
63
+ WHERE profile_id=? AND published=0 AND hidden=0
64
+ AND published_at IS NOT NULL AND published_at <= ? ORDER BY published_at ASC`,
65
+ args: [this.profileId, nowUnix],
66
+ })
67
+ products.forEach(r => queue.push({ table: 'products', id: r.id as string, title: r.title as string, scheduled_for: r.scheduled_for as number }))
68
+
69
+ return queue
70
+ }
71
+
72
+ /**
73
+ * Run the publish queue — flips published=1 on all due items.
74
+ * Phase 1: call manually. Phase 3: called by CF Durable Object on cron.
75
+ */
76
+ async runPublishQueue(): Promise<ScheduledItem[]> {
77
+ await this.init()
78
+ const { n8n_webhook_url } = this.ctx.credentials
79
+ const queue = await this.publishQueue()
80
+ if (!queue.length) return []
81
+
82
+ const isoTables = new Set(['posts', 'job_listings'])
83
+ const statements = queue.map(item => ({
84
+ sql: `UPDATE ${item.table} SET published=1, updated_at=? WHERE id=?`,
85
+ args: [isoTables.has(item.table) ? iso() : now(), item.id],
86
+ }))
87
+ await db.batch(statements)
88
+
89
+ // Notify n8n once with the full batch
90
+ if (n8n_webhook_url) {
91
+ fetch(n8n_webhook_url, {
92
+ method: 'POST',
93
+ headers: { 'Content-Type': 'application/json' },
94
+ body: JSON.stringify({ event: 'content_published', business: this.ctx.profile.title, items: queue }),
95
+ }).catch(() => { /* non-blocking */ })
96
+ }
97
+
98
+ return queue
99
+ }
100
+
101
+ /** Schedule any content for future publish */
102
+ async schedule(table: 'posts' | 'products' | 'job_listings', id: string, at: Date) {
103
+ const isISO = table !== 'products'
104
+ const dateCol = table === 'products' ? 'published_at' : 'date'
105
+ const val = isISO ? at.toISOString().slice(0, 19) + 'Z' : Math.floor(at.getTime() / 1000)
106
+ const updCol = isISO ? `updated_at='${iso()}'` : `updated_at=${now()}`
107
+
108
+ await db.execute({
109
+ sql: `UPDATE ${table} SET published=0, ${dateCol}=?, ${updCol} WHERE id=?`,
110
+ args: [val, id],
111
+ })
112
+ }
113
+ }
114
+
115
+ export const coo = new COO()
@@ -0,0 +1,52 @@
1
+ /**
2
+ * ATLAS — Analytics Agent
3
+ * "I see everything. I tell you what it means."
4
+ *
5
+ * Read-only. Never writes. Used by ARIA, REX, NOVA for intelligence.
6
+ */
7
+
8
+ import { BaseAgent } from '../_base.ts'
9
+ import { profileSummary, productSummary, linkSummary, formSummary } from '../../lib/analytics.ts'
10
+
11
+ export class AnalyticsAgent extends BaseAgent {
12
+ readonly name = 'ATLAS'
13
+ readonly title = 'Analytics Agent'
14
+
15
+ async snapshot() {
16
+ await this.init()
17
+ const [profile, products, links, forms] = await Promise.all([
18
+ profileSummary(this.profileId),
19
+ productSummary(this.profileId),
20
+ linkSummary(this.profileId),
21
+ formSummary(this.profileId),
22
+ ])
23
+ return { profile, products, links, forms }
24
+ }
25
+
26
+ async revenueReport() {
27
+ await this.init()
28
+ const products = await productSummary(this.profileId)
29
+ const profile = await profileSummary(this.profileId)
30
+ return {
31
+ total_revenue: profile?.total_revenue ?? 0,
32
+ revenue_trend: profile?.revenue_trend ?? 'no data',
33
+ last_30d_revenue: profile?.revenue_30d.reduce((a, b) => a + b, 0) ?? 0,
34
+ top_products: products.slice(0, 5),
35
+ }
36
+ }
37
+
38
+ async trafficReport() {
39
+ await this.init()
40
+ const profile = await profileSummary(this.profileId)
41
+ const links = await linkSummary(this.profileId)
42
+ return {
43
+ total_clicks: profile?.total_clicks ?? 0,
44
+ clicks_30d: profile?.clicks_30d ?? [],
45
+ top_countries: profile?.top_countries ?? [],
46
+ top_referrers: profile?.top_referrers ?? [],
47
+ top_links: links,
48
+ }
49
+ }
50
+ }
51
+
52
+ export const analyticsAgent = new AnalyticsAgent()
@@ -0,0 +1,68 @@
1
+ /**
2
+ * CRON — Scheduler
3
+ * "I wake up so you don't have to."
4
+ *
5
+ * Phase 1: run manually via `npx tsx agents/growth/cron.ts`
6
+ * Phase 3: export as CF Durable Object, called by wrangler cron trigger
7
+ *
8
+ * Design: thin orchestrator — delegates to OTTO (publish queue),
9
+ * ARIA (weekly briefing), NOVA (content calendar drafts), PEARL (newsletter).
10
+ */
11
+
12
+ import { coo } from '../csuite/coo.ts'
13
+ import { ceo } from '../csuite/ceo.ts'
14
+
15
+ export class Scheduler {
16
+ readonly name = 'CRON'
17
+ readonly title = 'Scheduler'
18
+
19
+ /**
20
+ * Hourly job — publish any content scheduled for now
21
+ * CF Workflow cron: "0 * * * *"
22
+ */
23
+ async hourly() {
24
+ const published = await coo.runPublishQueue()
25
+ return { published_count: published.length, published }
26
+ }
27
+
28
+ /**
29
+ * Daily job — lightweight ops check
30
+ * CF Workflow cron: "0 9 * * *"
31
+ */
32
+ async daily() {
33
+ const pipeline = await coo.draftPipeline()
34
+ const totalDrafts = pipeline.reduce((a, p) => a + p.drafts.length, 0)
35
+ return { draft_count: totalDrafts, pipeline_summary: pipeline.map(p => `${p.label}: ${p.drafts.length} drafts`) }
36
+ }
37
+
38
+ /**
39
+ * Weekly job — full briefing sent to n8n
40
+ * CF Workflow cron: "0 8 * * 1" (Monday 8am)
41
+ */
42
+ async weekly() {
43
+ const result = await ceo.sendBriefing()
44
+ return { briefing_sent: result.ok, ...result }
45
+ }
46
+ }
47
+
48
+ export const scheduler = new Scheduler()
49
+
50
+ // ─── CF Durable Object export (Phase 3) ──────────────────────────────────────
51
+ // Uncomment when deploying as a Durable Object on Cloudflare Workers:
52
+ //
53
+ // import { DurableObject } from 'cloudflare:workers'
54
+ // export class CronAgent extends DurableObject {
55
+ // async fetch(req: Request) {
56
+ // const { pathname } = new URL(req.url)
57
+ // if (pathname === '/hourly') return Response.json(await cron.hourly())
58
+ // if (pathname === '/daily') return Response.json(await cron.daily())
59
+ // if (pathname === '/weekly') return Response.json(await cron.weekly())
60
+ // return new Response('Not found', { status: 404 })
61
+ // }
62
+ // }
63
+
64
+ // ─── CLI runner (Phase 1) ─────────────────────────────────────────────────────
65
+ if (process.argv[2]) {
66
+ const job = process.argv[2] as 'hourly' | 'daily' | 'weekly'
67
+ scheduler[job]?.().then(r => console.log(JSON.stringify(r, null, 2))).catch(console.error)
68
+ }
@@ -0,0 +1,282 @@
1
+ /**
2
+ * SEO Agent
3
+ *
4
+ * Google SEO + LLM Visibility (Arvow insight).
5
+ * Tracks brand mentions in ChatGPT, Claude, Gemini, Perplexity.
6
+ * Audits all content tables for SEO issues and fixes them.
7
+ *
8
+ * Tables read: posts, compare, alternative, prompt, guides, collections
9
+ * Tables written: posts (seo_title, seo_description, seo_keywords)
10
+ * profiles (llm_visibility)
11
+ * collections (seo_title, seo_description)
12
+ */
13
+
14
+ import { BaseAgent, db, iso } from '../_base.ts'
15
+ import { logMemory } from '../../lib/memory.ts'
16
+
17
+ export interface SEOIssue {
18
+ table: string
19
+ id: string
20
+ title: string
21
+ slug: string
22
+ problems: string[]
23
+ }
24
+
25
+ export interface LLMVisibility {
26
+ chatgpt: number // mention count or 0
27
+ claude: number
28
+ gemini: number
29
+ perplexity: number
30
+ last_checked: string
31
+ }
32
+
33
+ export class SEOAgent extends BaseAgent {
34
+ readonly name = 'SEO Agent'
35
+ readonly title = 'SEO Agent'
36
+
37
+ // ── Full audit across all content tables ─────────────────────────────────
38
+
39
+ async audit(): Promise<{ issues: SEOIssue[]; score: number; summary: string }> {
40
+ await this.init()
41
+
42
+ const tables = ['posts', 'compare', 'alternative', 'guides'] as const
43
+ const allIssues: SEOIssue[] = []
44
+
45
+ for (const table of tables) {
46
+ try {
47
+ const { rows } = await db.execute({
48
+ sql: `SELECT id,title,slug,excerpt,seo_title,seo_description,word_count
49
+ FROM ${table} WHERE profile_id=? AND published=1 AND hidden=0`,
50
+ args: [this.profileId],
51
+ })
52
+
53
+ for (const r of rows) {
54
+ const problems: string[] = []
55
+ if (!r.excerpt) problems.push('missing excerpt')
56
+ if (!r.seo_title) problems.push('missing seo_title')
57
+ if (!r.seo_description) problems.push('missing seo_description')
58
+ if (r.seo_title && String(r.seo_title).length > 60) problems.push('seo_title >60 chars')
59
+ if (r.seo_description && String(r.seo_description).length > 160) problems.push('seo_description >160 chars')
60
+ if (Number(r.word_count ?? 0) < 300) problems.push('thin content <300 words')
61
+ if (!r.slug || String(r.slug).includes(' ')) problems.push('slug has spaces')
62
+ if (String(r.slug ?? '').length > 80) problems.push('slug too long >80 chars')
63
+
64
+ if (problems.length) {
65
+ allIssues.push({ table, id: r.id as string, title: r.title as string, slug: r.slug as string, problems })
66
+ }
67
+ }
68
+ } catch { /* table may not exist on older DBs */ }
69
+ }
70
+
71
+ const score = allIssues.length === 0 ? 100 : Math.max(0, 100 - allIssues.length * 5)
72
+ const summary = allIssues.length === 0
73
+ ? 'All content passes SEO checks.'
74
+ : `${allIssues.length} issues found across ${tables.join(', ')}.`
75
+
76
+ await logMemory('seo', `SEO audit: score ${score}/100, ${allIssues.length} issues`, { issues: allIssues.length, score })
77
+
78
+ return { issues: allIssues, score, summary }
79
+ }
80
+
81
+ // ── Fix a specific post's SEO fields ─────────────────────────────────────
82
+
83
+ async fixPost(id: string, fixes: {
84
+ seo_title?: string
85
+ seo_description?: string
86
+ seo_keywords?: string[]
87
+ excerpt?: string
88
+ slug?: string
89
+ }, table = 'posts') {
90
+ const sets: string[] = ['updated_at=?']
91
+ const args: unknown[] = [iso()]
92
+
93
+ if (fixes.seo_title) { sets.push('seo_title=?'); args.push(fixes.seo_title.slice(0, 60)) }
94
+ if (fixes.seo_description) { sets.push('seo_description=?'); args.push(fixes.seo_description.slice(0, 160)) }
95
+ if (fixes.seo_keywords) { sets.push('seo_keywords=?'); args.push(JSON.stringify(fixes.seo_keywords)) }
96
+ if (fixes.excerpt) { sets.push('excerpt=?'); args.push(fixes.excerpt) }
97
+ if (fixes.slug) { sets.push('slug=?'); args.push(this.toSlug(fixes.slug)) }
98
+
99
+ args.push(id)
100
+ await db.execute({
101
+ sql: `UPDATE ${table} SET ${sets.join(',')} WHERE id=? AND profile_id=?`,
102
+ args: [...args, this.profileId],
103
+ })
104
+ }
105
+
106
+ // ── Collection SEO ────────────────────────────────────────────────────────
107
+
108
+ async setCollectionSEO(categorySlug: string, opts: {
109
+ seo_title: string
110
+ seo_description: string
111
+ seo_robots?: string
112
+ }) {
113
+ await this.init()
114
+ await db.execute({
115
+ sql: `UPDATE collections SET
116
+ seo_title=?,seo_description=?,seo_robots=?,updated_at=?
117
+ WHERE profile_id=? AND category_slug=?`,
118
+ args: [
119
+ opts.seo_title.slice(0, 60),
120
+ opts.seo_description.slice(0, 160),
121
+ opts.seo_robots ?? 'index,follow',
122
+ iso(), this.profileId, categorySlug,
123
+ ],
124
+ })
125
+ }
126
+
127
+ // ── Slug suggestions ──────────────────────────────────────────────────────
128
+
129
+ suggestSlug(title: string, keyword?: string): string {
130
+ const base = (keyword ?? title)
131
+ .toLowerCase()
132
+ .replace(/[^a-z0-9\s-]/g, '')
133
+ .replace(/\s+/g, '-')
134
+ .replace(/-+/g, '-')
135
+ .replace(/^-|-$/g, '')
136
+ return base.slice(0, 80)
137
+ }
138
+
139
+ // ── LLM Visibility (Arvow-inspired) ──────────────────────────────────────
140
+ //
141
+ // Tracks whether ChatGPT, Claude, Gemini, Perplexity mention your brand.
142
+ // This is the "AI SEO" layer on top of Google SEO.
143
+ // Strategy: write content that gets cited by LLMs (detailed, factual, well-structured).
144
+
145
+ async checkLLMVisibility(): Promise<LLMVisibility> {
146
+ await this.init()
147
+ const { rows: [r] } = await db.execute({
148
+ sql: `SELECT llm_visibility FROM profiles WHERE id=? LIMIT 1`,
149
+ args: [this.profileId],
150
+ })
151
+
152
+ const current: LLMVisibility = safeJSON(r?.llm_visibility, {
153
+ chatgpt: 0, claude: 0, gemini: 0, perplexity: 0, last_checked: '',
154
+ })
155
+
156
+ return current
157
+ }
158
+
159
+ async updateLLMVisibility(counts: Partial<Omit<LLMVisibility, 'last_checked'>>) {
160
+ await this.init()
161
+ const current = await this.checkLLMVisibility()
162
+ const updated: LLMVisibility = {
163
+ ...current,
164
+ ...counts,
165
+ last_checked: iso(),
166
+ }
167
+ await db.execute({
168
+ sql: `UPDATE profiles SET llm_visibility=? WHERE id=?`,
169
+ args: [JSON.stringify(updated), this.profileId],
170
+ })
171
+ await logMemory('seo', 'Updated LLM visibility', updated)
172
+ return updated
173
+ }
174
+
175
+ llmVisibilityAdvice(visibility: LLMVisibility): string[] {
176
+ const advice: string[] = []
177
+ const allZero = !visibility.chatgpt && !visibility.claude && !visibility.gemini && !visibility.perplexity
178
+
179
+ if (allZero) {
180
+ advice.push('No LLM mentions detected yet. Publish more detailed, factual, well-structured content.')
181
+ advice.push('Write ultimate guides and how-to articles — LLMs prefer citing comprehensive sources.')
182
+ advice.push('Include data, statistics, and clear definitions — these get cited more often.')
183
+ advice.push('Use your brand name consistently in titles, headings, and the first paragraph.')
184
+ } else {
185
+ if (!visibility.perplexity) advice.push('Not visible in Perplexity. Add more cited sources and data to your content.')
186
+ if (!visibility.chatgpt) advice.push('Not visible in ChatGPT. Publish FAQ-style content around your core topic.')
187
+ if (visibility.chatgpt > 0) advice.push(`ChatGPT mentions: ${visibility.chatgpt} — keep publishing in this area.`)
188
+ }
189
+
190
+ return advice
191
+ }
192
+
193
+ // ── Content gap analysis ──────────────────────────────────────────────────
194
+
195
+ async contentGaps(): Promise<{
196
+ missing_types: string[]
197
+ thin_posts: number
198
+ no_compare: boolean
199
+ no_alternative: boolean
200
+ advice: string[]
201
+ }> {
202
+ await this.init()
203
+ const [
204
+ { rows: typeCounts },
205
+ { rows: [compareCount] },
206
+ { rows: [altCount] },
207
+ ] = await Promise.all([
208
+ db.execute({
209
+ sql: `SELECT content_type, COUNT(*) as cnt FROM posts
210
+ WHERE profile_id=? AND published=1 AND hidden=0
211
+ GROUP BY content_type`,
212
+ args: [this.profileId],
213
+ }),
214
+ db.execute({
215
+ sql: `SELECT COUNT(*) cnt FROM compare WHERE profile_id=? AND published=1`,
216
+ args: [this.profileId],
217
+ }),
218
+ db.execute({
219
+ sql: `SELECT COUNT(*) cnt FROM alternative WHERE profile_id=? AND published=1`,
220
+ args: [this.profileId],
221
+ }),
222
+ ])
223
+
224
+ const publishedTypes = new Set(typeCounts.map(r => r.content_type as string))
225
+ const highValueTypes = ['listicle', 'how-to', 'ultimate-guide', 'qa']
226
+ const missingTypes = highValueTypes.filter(t => !publishedTypes.has(t))
227
+
228
+ const { rows: [thin] } = await db.execute({
229
+ sql: `SELECT COUNT(*) cnt FROM posts WHERE profile_id=? AND published=1 AND word_count < 500`,
230
+ args: [this.profileId],
231
+ })
232
+
233
+ const noCompare = Number(compareCount?.cnt ?? 0) === 0
234
+ const noAlternative = Number(altCount?.cnt ?? 0) === 0
235
+ const thinPosts = Number(thin?.cnt ?? 0)
236
+
237
+ const advice: string[] = []
238
+ if (missingTypes.includes('listicle')) advice.push('Write a "Top 10 X" listicle — high traffic format.')
239
+ if (missingTypes.includes('how-to')) advice.push('Write a "How to X" guide — high search intent.')
240
+ if (missingTypes.includes('ultimate-guide')) advice.push('Write an ultimate guide — best for LLM citations.')
241
+ if (missingTypes.includes('qa')) advice.push('Write an FAQ article — targets long-tail queries.')
242
+ if (noCompare) advice.push('Create compare pages (X vs Y) — high buying intent.')
243
+ if (noAlternative) advice.push('Create "alternatives to X" pages — high buying intent.')
244
+ if (thinPosts > 0) advice.push(`${thinPosts} thin posts (<500 words) need expanding.`)
245
+
246
+ return { missing_types: missingTypes, thin_posts: thinPosts, no_compare: noCompare, no_alternative: noAlternative, advice }
247
+ }
248
+
249
+ private toSlug(s: string): string {
250
+ return s.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, 80)
251
+ }
252
+
253
+ // ── llms.txt awareness ───────────────────────────────────────────────────────
254
+ // Your live app generates llms.txt at /llms.txt — agent checks it exists
255
+ // and advises on content. Generation is server-side, not agent's job.
256
+
257
+ async checkLLMSTxt(): Promise<{ exists: boolean; url: string; advice: string[] }> {
258
+ await this.init()
259
+ const url = `https://${this.ctx.profile.slug}.businesskit.io/llms.txt`
260
+ let exists = false
261
+ try {
262
+ const res = await fetch(url, { method: 'HEAD' })
263
+ exists = res.ok
264
+ } catch { /* network error */ }
265
+
266
+ const advice: string[] = []
267
+ if (!exists) {
268
+ advice.push('llms.txt not reachable at ' + url)
269
+ advice.push('Ensure the live app is generating it at /llms.txt')
270
+ } else {
271
+ advice.push('llms.txt exists — AI crawlers (GPTBot, ClaudeBot, PerplexityBot) can discover your content')
272
+ advice.push('Review it includes your latest products and top published posts')
273
+ }
274
+ return { exists, url, advice }
275
+ }
276
+ }
277
+
278
+ function safeJSON(v: unknown, fb: unknown) {
279
+ try { return JSON.parse(v as string) } catch { return fb }
280
+ }
281
+
282
+ export const seoAgent = new SEOAgent()