@businesskit/agent 1.0.2 → 1.0.4

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 (94) hide show
  1. package/.claude/settings.json +16 -0
  2. package/.claude/settings.local.json +11 -0
  3. package/.claude-plugin/marketplace.json +36 -0
  4. package/.claude-plugin/plugin.json +7 -28
  5. package/.env.example +10 -0
  6. package/CLAUDE.md +56 -195
  7. package/HEARTBEAT.md +81 -57
  8. package/PLAN.md +211 -119
  9. package/PRD-Agent-Composition.md +149 -0
  10. package/README.md +25 -11
  11. package/REFERENCE.md +160 -0
  12. package/SOUL.md +31 -0
  13. package/SYSTEM.md +22 -0
  14. package/agents/_base.ts +352 -44
  15. package/agents/analytics/SOUL.md +11 -0
  16. package/agents/analytics/analytics.ts +405 -0
  17. package/agents/business/SOUL.md +11 -0
  18. package/agents/{csuite/cbo.ts → business/business.ts} +2 -2
  19. package/agents/ceo/SOUL.md +15 -0
  20. package/agents/{csuite → ceo}/ceo.ts +33 -8
  21. package/agents/content/SOUL.md +11 -0
  22. package/agents/content/content.ts +379 -0
  23. package/agents/copywriting/SOUL.md +11 -0
  24. package/agents/courses/SOUL.md +11 -0
  25. package/agents/courses/courses.ts +451 -0
  26. package/agents/docs/SOUL.md +11 -0
  27. package/agents/forms/SOUL.md +11 -0
  28. package/agents/forms/forms.ts +364 -0
  29. package/agents/hiring/SOUL.md +11 -0
  30. package/agents/hiring/hiring.ts +314 -0
  31. package/agents/marketing/SOUL.md +15 -0
  32. package/agents/{csuite/cmo.ts → marketing/marketing.ts} +3 -3
  33. package/agents/newsletter/SOUL.md +11 -0
  34. package/agents/operations/SOUL.md +11 -0
  35. package/agents/operations/operations.ts +157 -0
  36. package/agents/sales/SOUL.md +44 -0
  37. package/agents/sales/sales.ts +883 -0
  38. package/agents/scheduler/SOUL.md +11 -0
  39. package/agents/{growth → scheduler}/scheduler.ts +2 -2
  40. package/agents/seo/SOUL.md +11 -0
  41. package/agents/{growth/seo-agent.ts → seo/seo.ts} +60 -54
  42. package/agents/social/SOUL.md +11 -0
  43. package/agents/social/social.ts +744 -0
  44. package/agents/store/SOUL.md +11 -0
  45. package/agents/store/store.ts +514 -0
  46. package/cli.ts +44 -25
  47. package/lib/cms.ts +88 -0
  48. package/lib/db.ts +58 -11
  49. package/lib/enums.ts +25 -0
  50. package/lib/groups.ts +122 -0
  51. package/lib/id.ts +38 -10
  52. package/lib/profile.ts +44 -8
  53. package/lib/schema.ts +2015 -0
  54. package/lib/validate.ts +33 -0
  55. package/package.json +1 -1
  56. package/scripts/generate-schema.ts +244 -0
  57. package/setup.ts +16 -2
  58. package/{.agents/skills/analytics.md → skills/analytics/SKILL.md} +6 -1
  59. package/{.agents/skills/brand.md → skills/brand/SKILL.md} +14 -1
  60. package/skills/ceo/SKILL.md +25 -0
  61. package/skills/cmo/SKILL.md +8 -0
  62. package/skills/humanizer/SKILL.md +270 -0
  63. package/skills/schema/SKILL.md +86 -0
  64. package/tsconfig.json +2 -1
  65. package/.agents/skills/schema.md +0 -45
  66. package/.agents/skills/store.md +0 -46
  67. package/.claude/skills/agents.md +0 -56
  68. package/.claude/skills/analytics.md +0 -7
  69. package/.claude/skills/brand.md +0 -44
  70. package/.claude/skills/humanizer.md +0 -474
  71. package/.claude/skills/schema.md +0 -45
  72. package/agents/creators/blog-writer.ts +0 -347
  73. package/agents/creators/course-creator.ts +0 -106
  74. package/agents/creators/crm-agent.ts +0 -479
  75. package/agents/creators/forms-builder.ts +0 -90
  76. package/agents/creators/jobs-manager.ts +0 -82
  77. package/agents/creators/store-manager.ts +0 -138
  78. package/agents/csuite/coo.ts +0 -115
  79. package/agents/growth/analytics-agent.ts +0 -52
  80. package/agents/growth/social-agent.ts +0 -346
  81. /package/{ingest.md → .claude/commands/ingest.md} +0 -0
  82. /package/agents/{creators/copywriter.ts → copywriting/copywriting.ts} +0 -0
  83. /package/agents/{creators/docs-writer.ts → docs/docs.ts} +0 -0
  84. /package/agents/{creators/newsletter-writer.ts → newsletter/newsletter.ts} +0 -0
  85. /package/{ABOUT-ME.md → context/about-me.md} +0 -0
  86. /package/{brand-voice.md → context/brand-voice.md} +0 -0
  87. /package/{working-style.md → context/working-style.md} +0 -0
  88. /package/{.claude/skills → skills}/README.md +0 -0
  89. /package/{.agents/skills/agents.md → skills/agents/SKILL.md} +0 -0
  90. /package/{.claude/skills/blog-writing.md → skills/blog-writer/SKILL.md} +0 -0
  91. /package/{.claude/skills/store-copywriting.md → skills/copywriting/SKILL.md} +0 -0
  92. /package/{.claude/skills/social-content.md → skills/social/SKILL.md} +0 -0
  93. /package/{.claude/skills → skills/social}/content-seo.md +0 -0
  94. /package/{.claude/skills/store.md → skills/store/SKILL.md} +0 -0
package/lib/cms.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * lib/cms.ts — cms row resolver.
3
+ *
4
+ * The app-side `cms` table is one row per content section (Blog, Notes, Jobs,
5
+ * Forms, Docs, etc.) keyed by (profile_id, category_id). Triggers on
6
+ * job_listings, forms, products, doc_articles, content all UPDATE `cms_analytics`
7
+ * for the matching cms_id — so the cms row must exist for counters to move.
8
+ *
9
+ * Use `ensureCmsRow()` before any INSERT into a table whose trigger touches
10
+ * cms_analytics. Idempotent — unique index on (profile_id, category_id).
11
+ *
12
+ * Category IDs (seeded by app; stable):
13
+ * cat_1 Links cat_31 Jobs
14
+ * cat_18 Courses cat_32 Docs (Knowledge Base)
15
+ * cat_19 Downloads cat_34 Forms
16
+ * cat_20 Newsletter cat_35 Blog
17
+ * cat_22 Meetings cat_36 Guides
18
+ * cat_24 Webinars cat_37 Notes
19
+ * cat_25 Services cat_38 Skills
20
+ * cat_27 Listing cat_39 Prompt
21
+ * cat_30 Booking cat_40 Compare
22
+ * cat_41 Alternative
23
+ * cat_42 Community cat_45 Posts
24
+ * cat_47 Pages cat_8 Events
25
+ * cat_21 Sponsorship
26
+ */
27
+
28
+ import { db } from './db.ts'
29
+ import { ulid } from './id.ts'
30
+
31
+ /** Find or create a cms row for (profile_id, category_id). Returns the cms.id. */
32
+ export async function ensureCmsRow(
33
+ profileId: string,
34
+ categoryId: string,
35
+ opts: { slug?: string; title?: string } = {},
36
+ ): Promise<string> {
37
+ const { rows: [existing] } = await db.execute({
38
+ sql: `SELECT id FROM cms WHERE profile_id=? AND category_id=? LIMIT 1`,
39
+ args: [profileId, categoryId],
40
+ })
41
+ if (existing?.id) return existing.id as string
42
+
43
+ const id = ulid()
44
+ await db.write({
45
+ sql: `INSERT OR IGNORE INTO cms (id, profile_id, slug, title, category_id)
46
+ VALUES (?, ?, ?, ?, ?)`,
47
+ args: [
48
+ id, profileId,
49
+ opts.slug ?? categoryId,
50
+ opts.title ?? categoryId,
51
+ categoryId,
52
+ ],
53
+ })
54
+
55
+ const { rows: [row] } = await db.execute({
56
+ sql: `SELECT id FROM cms WHERE profile_id=? AND category_id=? LIMIT 1`,
57
+ args: [profileId, categoryId],
58
+ })
59
+ return (row?.id as string) ?? id
60
+ }
61
+
62
+ /** Category IDs used by app — import by name to avoid magic strings. */
63
+ export const CATEGORY = {
64
+ LINKS: 'cat_1',
65
+ EVENTS: 'cat_8',
66
+ COURSES: 'cat_18',
67
+ DOWNLOADS: 'cat_19',
68
+ NEWSLETTER: 'cat_20',
69
+ SPONSORSHIP: 'cat_21',
70
+ MEETINGS: 'cat_22',
71
+ WEBINARS: 'cat_24',
72
+ SERVICES: 'cat_25',
73
+ LISTING: 'cat_27',
74
+ BOOKING: 'cat_30',
75
+ JOBS: 'cat_31',
76
+ DOCS: 'cat_32',
77
+ FORMS: 'cat_34',
78
+ BLOG: 'cat_35',
79
+ GUIDES: 'cat_36',
80
+ NOTES: 'cat_37',
81
+ SKILLS: 'cat_38',
82
+ PROMPT: 'cat_39',
83
+ COMPARE: 'cat_40',
84
+ ALTERNATIVE: 'cat_41',
85
+ COMMUNITY: 'cat_42',
86
+ POSTS: 'cat_45',
87
+ PAGES: 'cat_47',
88
+ } as const
package/lib/db.ts CHANGED
@@ -1,16 +1,63 @@
1
+ // lib/db.ts
2
+ // Turso DB client — retry on SQLITE_BUSY, optional read replica.
3
+ // Phase 1: .env credentials. Phase 2: swap via db.adapter.ts (one line).
4
+
1
5
  import { createClient, type Client } from '@libsql/client/web'
2
6
 
3
- function createDB(): Client {
4
- const url = process.env.TURSO_URL
5
- const token = process.env.TURSO_TOKEN
6
- if (!url || !token) {
7
- throw new Error(
8
- '\nMissing TURSO_URL or TURSO_TOKEN\n' +
9
- 'Copy .env.example → .env and paste your credentials.\n' +
10
- 'Find them: BusinessKit dashboard → Settings → Credentials\n'
11
- )
7
+ // Permissive statement type — the libSQL `InStatement` is strict about arg
8
+ // element types (`InValue`), but the agent layer uses `unknown[]` everywhere
9
+ // since we bind ids, ISO strings, integers, JSON blobs, and nulls freely.
10
+ // The runtime client accepts all of these; we forward them as `any`.
11
+ export type Stmt = { sql: string; args: unknown[] } | string
12
+
13
+ let _writer: Client | null = null
14
+ let _reader: Client | null = null
15
+
16
+ function writer(): Client {
17
+ if (!_writer) {
18
+ const url = process.env.TURSO_URL || ''
19
+ const token = process.env.TURSO_TOKEN || ''
20
+ if (!url || !token) throw new Error('TURSO_URL and TURSO_TOKEN required. Run: cp .env.example .env')
21
+ _writer = createClient({ url, authToken: token })
22
+ }
23
+ return _writer
24
+ }
25
+
26
+ function reader(): Client {
27
+ if (!_reader) {
28
+ const url = process.env.TURSO_REPLICA_URL || process.env.TURSO_URL || ''
29
+ const token = process.env.TURSO_TOKEN || ''
30
+ _reader = createClient({ url, authToken: token })
12
31
  }
13
- return createClient({ url, authToken: token })
32
+ return _reader
14
33
  }
15
34
 
16
- export const db = createDB()
35
+ // P0-3: SQLITE_BUSY retry — exponential backoff + jitter
36
+ export async function withRetry<T>(op: () => Promise<T>, maxTries = 5): Promise<T> {
37
+ for (let i = 0; i < maxTries; i++) {
38
+ try { return await op() }
39
+ catch (e: any) {
40
+ const retryable = /SQLITE_BUSY|database is locked|SQLITE_LOCKED/i.test(e?.message ?? '')
41
+ if (!retryable || i === maxTries - 1) throw e
42
+ await new Promise(r => setTimeout(r, 50 * 2 ** i + Math.random() * 50))
43
+ }
44
+ }
45
+ throw new Error('unreachable')
46
+ }
47
+
48
+ export const db = {
49
+ // Reads — replica if TURSO_REPLICA_URL set, otherwise primary
50
+ execute: (q: Stmt) =>
51
+ withRetry(() => reader().execute(q as any)),
52
+
53
+ // Writes — always primary
54
+ write: (q: Stmt) =>
55
+ withRetry(() => writer().execute(q as any)),
56
+
57
+ // P0-2: Atomic multi-statement batch — back-compat alias `batch` too
58
+ txn: (stmts: Stmt[]) =>
59
+ withRetry(() => writer().batch(stmts as any, 'write')),
60
+
61
+ batch: (stmts: Stmt[]) =>
62
+ withRetry(() => writer().batch(stmts as any, 'write')),
63
+ }
package/lib/enums.ts ADDED
@@ -0,0 +1,25 @@
1
+ // lib/enums.ts
2
+ // Single source of truth for all status strings used in DB writes.
3
+ // Never use raw string literals for statuses in agent files.
4
+ // Keep in sync with app repo's src/lib/enums.ts
5
+
6
+ export const CRM_CONTACT_STATUS = ['lead', 'prospect', 'customer', 'churned', 'archived'] as const
7
+ export const CRM_ACTIVITY_APPROVAL = ['pending_approval', 'approved', 'rejected', 'auto_sent'] as const
8
+ export const CRM_DEAL_STAGE = ['new', 'contacted', 'proposal', 'negotiation', 'won', 'lost'] as const
9
+ export const SOCIAL_POST_STATUS = ['draft', 'scheduled', 'queued', 'publishing', 'published', 'failed', 'cancelled'] as const
10
+ export const AGENT_NOTE_STATUS = ['inbox', 'processing', 'done', 'archived'] as const
11
+ export const AGENT_TASK_STATUS = ['pending', 'active', 'running', 'done', 'paused', 'failed', 'cancelled'] as const
12
+ export const AGENT_KB_ENTRY_TYPE = ['entity', 'concept', 'source', 'synthesis', 'index'] as const
13
+ export const APPROVAL_STATUS = ['pending_approval', 'approved', 'rejected', 'auto_sent'] as const
14
+ export const COMMUNITY_POST_STATUS = ['published', 'removed', 'pending'] as const
15
+ export const EMAIL_EVENT_TYPE = ['delivered', 'opened', 'clicked', 'bounced', 'complained', 'failed'] as const
16
+ export const AFFILIATE_COMMISSION = ['pending', 'approved', 'paid', 'void'] as const
17
+
18
+ export type CRMContactStatus = typeof CRM_CONTACT_STATUS[number]
19
+ export type CRMActivityApproval = typeof CRM_ACTIVITY_APPROVAL[number]
20
+ export type CRMDealStage = typeof CRM_DEAL_STAGE[number]
21
+ export type SocialPostStatus = typeof SOCIAL_POST_STATUS[number]
22
+ export type AgentNoteStatus = typeof AGENT_NOTE_STATUS[number]
23
+ export type AgentTaskStatus = typeof AGENT_TASK_STATUS[number]
24
+ export type AgentKBEntryType = typeof AGENT_KB_ENTRY_TYPE[number]
25
+ export type ApprovalStatus = typeof APPROVAL_STATUS[number]
package/lib/groups.ts ADDED
@@ -0,0 +1,122 @@
1
+ // lib/groups.ts — P0-4: CRM groups via junction table
2
+ // Replaces LIKE '%grp_x%' which is O(N), un-indexable, and has
3
+ // substring collision bug (grp_0055 matches grp_005).
4
+ //
5
+ // Requires: crm_contact_groups junction table (app-side migration).
6
+ // Gate on schema version before switching — see P1-1 in task spec.
7
+ //
8
+ // Old (delete everywhere):
9
+ // WHERE groups LIKE '%grp_005%'
10
+ // UPDATE crm_contacts SET groups = json_insert(groups, '$[#]', 'grp_005') WHERE id = ?
11
+ //
12
+ // New (use these helpers):
13
+
14
+ import { db } from './db.ts'
15
+ import { iso } from './id.ts'
16
+
17
+ /**
18
+ * Get contacts in a group — indexed, no substring collision.
19
+ */
20
+ export async function getContactsByGroup(
21
+ profileId: string,
22
+ groupId: string,
23
+ limit = 50,
24
+ offset = 0,
25
+ ): Promise<unknown[]> {
26
+ const { rows } = await db.execute({
27
+ sql: `SELECT c.*
28
+ FROM crm_contacts c
29
+ JOIN crm_contact_groups ccg ON ccg.contact_id = c.id
30
+ WHERE ccg.group_id = ?
31
+ AND c.profile_id = ?
32
+ AND c.archived = 0
33
+ ORDER BY c.last_activity_at DESC
34
+ LIMIT ? OFFSET ?`,
35
+ args: [groupId, profileId, limit, offset],
36
+ })
37
+ return rows
38
+ }
39
+
40
+ /**
41
+ * Add contact to group — idempotent (INSERT OR IGNORE).
42
+ * Also increments contact_count on crm_groups.
43
+ */
44
+ export async function addContactToGroup(
45
+ profileId: string,
46
+ contactId: string,
47
+ groupId: string,
48
+ ): Promise<void> {
49
+ await db.txn([
50
+ {
51
+ sql: `INSERT OR IGNORE INTO crm_contact_groups
52
+ (contact_id, group_id, profile_id, created_at)
53
+ VALUES (?, ?, ?, ?)`,
54
+ args: [contactId, groupId, profileId, iso()],
55
+ },
56
+ {
57
+ // Only increment if the row was actually new
58
+ sql: `UPDATE crm_groups
59
+ SET contact_count = (
60
+ SELECT COUNT(*) FROM crm_contact_groups WHERE group_id = ?
61
+ )
62
+ WHERE id = ? AND profile_id = ?`,
63
+ args: [groupId, groupId, profileId],
64
+ },
65
+ ])
66
+ }
67
+
68
+ /**
69
+ * Remove contact from group.
70
+ */
71
+ export async function removeContactFromGroup(
72
+ profileId: string,
73
+ contactId: string,
74
+ groupId: string,
75
+ ): Promise<void> {
76
+ await db.txn([
77
+ {
78
+ sql: `DELETE FROM crm_contact_groups
79
+ WHERE contact_id = ? AND group_id = ?`,
80
+ args: [contactId, groupId],
81
+ },
82
+ {
83
+ sql: `UPDATE crm_groups
84
+ SET contact_count = MAX(0, (
85
+ SELECT COUNT(*) FROM crm_contact_groups WHERE group_id = ?
86
+ ))
87
+ WHERE id = ? AND profile_id = ?`,
88
+ args: [groupId, groupId, profileId],
89
+ },
90
+ ])
91
+ }
92
+
93
+ /**
94
+ * Get all groups for a contact.
95
+ */
96
+ export async function getGroupsForContact(
97
+ profileId: string,
98
+ contactId: string,
99
+ ): Promise<unknown[]> {
100
+ const { rows } = await db.execute({
101
+ sql: `SELECT g.*
102
+ FROM crm_groups g
103
+ JOIN crm_contact_groups ccg ON ccg.group_id = g.id
104
+ WHERE ccg.contact_id = ?
105
+ AND g.profile_id = ?`,
106
+ args: [contactId, profileId],
107
+ })
108
+ return rows
109
+ }
110
+
111
+ /**
112
+ * Schema-version check — gate P0-4 on this.
113
+ * Returns true when crm_contact_groups table exists in UserDB.
114
+ */
115
+ export async function hasGroupsJunction(): Promise<boolean> {
116
+ try {
117
+ await db.execute(`SELECT 1 FROM crm_contact_groups LIMIT 0`)
118
+ return true
119
+ } catch {
120
+ return false
121
+ }
122
+ }
package/lib/id.ts CHANGED
@@ -1,15 +1,43 @@
1
- const ENC = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
1
+ // lib/id.ts — ID generation and idempotency helpers
2
2
 
3
+ /** UUID v4 for row IDs */
3
4
  export function ulid(): string {
4
- let t = Date.now(), time = ''
5
- for (let i = 9; i >= 0; i--) { time = ENC[t % 32] + time; t = Math.floor(t / 32) }
6
- const rand = new Uint8Array(10)
7
- crypto.getRandomValues(rand)
8
- return time + Array.from(rand, b => ENC[b % 32]).join('')
5
+ return crypto.randomUUID()
9
6
  }
10
7
 
11
- /** Unix epoch seconds — for INTEGER timestamp columns */
12
- export const now = () => Math.floor(Date.now() / 1000)
8
+ /** ISO timestamp for TEXT columns */
9
+ export function iso(): string {
10
+ return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
11
+ }
12
+
13
+ /** Unix epoch for INTEGER columns */
14
+ export function now(): number {
15
+ return Math.floor(Date.now() / 1000)
16
+ }
13
17
 
14
- /** ISO-8601 string — for TEXT timestamp columns (posts, jobs, forms, docs) */
15
- export const iso = () => new Date().toISOString().slice(0, 19) + 'Z'
18
+ /**
19
+ * P0-1: Idempotency key — UUID v7 style, timestamp-prefixed.
20
+ * One key per action per command invocation.
21
+ * Reuse the SAME key on retry within the same invocation.
22
+ *
23
+ * Usage:
24
+ * const key = generateIdempotencyKey()
25
+ * await db.txn([
26
+ * { sql: 'INSERT OR IGNORE INTO crm_activities (..., idempotency_key) VALUES (..., ?)', args: [..., key] },
27
+ * { sql: 'INSERT INTO agent_audit (..., idempotency_key) VALUES (..., ?)', args: [..., key] },
28
+ * ])
29
+ *
30
+ * Tables that gain idempotency_key column (coordinate with app team as columns land):
31
+ * crm_activities, crm_tasks, crm_notes, crm_proposals, crm_invoices
32
+ * social_posts, social_queue
33
+ * agent_notes, agent_reports, agent_tasks, agent_memory
34
+ *
35
+ * Until columns land: store key in metadata JSON blob where available.
36
+ */
37
+ export function generateIdempotencyKey(): string {
38
+ const ts = Date.now()
39
+ const rand = crypto.getRandomValues(new Uint8Array(10))
40
+ const tsHex = ts.toString(16).padStart(12, '0')
41
+ const randHex = Array.from(rand).map(b => b.toString(16).padStart(2, '0')).join('')
42
+ return `${tsHex.slice(0, 8)}-${tsHex.slice(8, 12)}-7${randHex.slice(0, 3)}-${randHex.slice(3, 7)}-${randHex.slice(7, 19)}`
43
+ }
package/lib/profile.ts CHANGED
@@ -60,17 +60,53 @@ export interface BrandContext {
60
60
 
61
61
  let _ctx: BrandContext | null = null
62
62
 
63
+ /**
64
+ * Load the brand context (profile + settings + credentials) from UserDB.
65
+ *
66
+ * Profile selection:
67
+ * 1. If PROFILE_ID env var is set → SELECT by that id (multi-profile DBs)
68
+ * 2. Otherwise → SELECT the only profile in the DB (single-profile default)
69
+ * 3. If DB has >1 profile and PROFILE_ID unset → throw with guidance
70
+ */
63
71
  export async function getBrandContext(client?: Client): Promise<BrandContext> {
64
72
  if (!client && _ctx) return _ctx
65
73
 
66
- const db = client ?? _defaultDB
67
- const [[p], [s], [c]] = await Promise.all([
68
- db.execute('SELECT * FROM profiles LIMIT 1').then(r => r.rows),
69
- db.execute('SELECT * FROM settings LIMIT 1').then(r => r.rows),
70
- db.execute('SELECT * FROM credentials LIMIT 1').then(r => r.rows),
71
- ])
74
+ // libSQL Client's `execute` has a strict `InStatement` type; our `db` wrapper
75
+ // accepts the looser `Stmt`. When an external Client is injected (phase 2),
76
+ // we cast through `any` to share call shapes.
77
+ const exec = (sql: string, args?: unknown[]) =>
78
+ (client
79
+ ? (client.execute as any)(args ? { sql, args } : sql)
80
+ : _defaultDB.execute(args ? { sql, args } : sql))
81
+
82
+ const pid = process.env.PROFILE_ID?.trim()
83
+
84
+ const profileRow = pid
85
+ ? await exec('SELECT * FROM profiles WHERE id=? LIMIT 1', [pid]).then((r: any) => r.rows[0])
86
+ : await (async () => {
87
+ const { rows } = await exec('SELECT * FROM profiles LIMIT 2')
88
+ if (rows.length > 1) {
89
+ throw new Error(
90
+ `UserDB has ${rows.length}+ profiles. Set PROFILE_ID in .env ` +
91
+ `to pick one (see .env.example).`,
92
+ )
93
+ }
94
+ return rows[0]
95
+ })()
96
+
97
+ if (!profileRow) {
98
+ throw new Error(
99
+ pid
100
+ ? `No profile found with id=${pid}. Check PROFILE_ID in .env.`
101
+ : 'No profile found — is your Turso DB provisioned? Run BusinessKit onboarding first.',
102
+ )
103
+ }
104
+ const p = profileRow
72
105
 
73
- if (!p) throw new Error('No profile found — is your Turso DB provisioned?')
106
+ const [[s], [c]] = await Promise.all([
107
+ exec('SELECT * FROM settings WHERE profile_id=? LIMIT 1', [p.id]).then((r: any) => r.rows),
108
+ exec('SELECT * FROM credentials WHERE profile_id=? LIMIT 1', [p.id]).then((r: any) => r.rows),
109
+ ])
74
110
 
75
111
  const parse = (v: unknown, fb: unknown) => { try { return JSON.parse(v as string) } catch { return fb } }
76
112
  const str = (v: unknown) => (v as string | null) ?? null
@@ -116,4 +152,4 @@ export async function getBrandContext(client?: Client): Promise<BrandContext> {
116
152
  return result
117
153
  }
118
154
 
119
- export const getProfile = async (client?: Client) => (await getBrandContext(client)).profile
155
+ export const getProfile = async (client?: Client) => (await getBrandContext(client)).profile