@businesskit/agent 1.0.3 → 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 (68) hide show
  1. package/.claude/settings.json +16 -0
  2. package/.claude/settings.local.json +11 -0
  3. package/.env.example +10 -0
  4. package/CLAUDE.md +32 -13
  5. package/PLAN.md +95 -134
  6. package/REFERENCE.md +60 -24
  7. package/agents/_base.ts +352 -44
  8. package/agents/analytics/SOUL.md +11 -0
  9. package/agents/analytics/analytics.ts +405 -0
  10. package/agents/business/SOUL.md +11 -0
  11. package/agents/{csuite/cbo.ts → business/business.ts} +2 -2
  12. package/agents/ceo/SOUL.md +15 -0
  13. package/agents/{csuite → ceo}/ceo.ts +33 -8
  14. package/agents/content/SOUL.md +11 -0
  15. package/agents/content/content.ts +379 -0
  16. package/agents/copywriting/SOUL.md +11 -0
  17. package/agents/courses/SOUL.md +11 -0
  18. package/agents/courses/courses.ts +451 -0
  19. package/agents/docs/SOUL.md +11 -0
  20. package/agents/forms/SOUL.md +11 -0
  21. package/agents/forms/forms.ts +364 -0
  22. package/agents/hiring/SOUL.md +11 -0
  23. package/agents/hiring/hiring.ts +314 -0
  24. package/agents/marketing/SOUL.md +15 -0
  25. package/agents/{csuite/cmo.ts → marketing/marketing.ts} +3 -3
  26. package/agents/newsletter/SOUL.md +11 -0
  27. package/agents/operations/SOUL.md +11 -0
  28. package/agents/operations/operations.ts +157 -0
  29. package/agents/sales/SOUL.md +44 -0
  30. package/agents/sales/sales.ts +883 -0
  31. package/agents/scheduler/SOUL.md +11 -0
  32. package/agents/{growth → scheduler}/scheduler.ts +2 -2
  33. package/agents/seo/SOUL.md +11 -0
  34. package/agents/{growth/seo-agent.ts → seo/seo.ts} +60 -54
  35. package/agents/social/SOUL.md +11 -0
  36. package/agents/social/social.ts +744 -0
  37. package/agents/store/SOUL.md +11 -0
  38. package/agents/store/store.ts +514 -0
  39. package/cli.ts +44 -25
  40. package/lib/cms.ts +88 -0
  41. package/lib/db.ts +58 -11
  42. package/lib/enums.ts +25 -0
  43. package/lib/groups.ts +122 -0
  44. package/lib/id.ts +38 -10
  45. package/lib/profile.ts +44 -8
  46. package/lib/schema.ts +2015 -0
  47. package/lib/validate.ts +33 -0
  48. package/package.json +1 -1
  49. package/scripts/generate-schema.ts +244 -0
  50. package/setup.ts +16 -2
  51. package/skills/schema/SKILL.md +57 -16
  52. package/tsconfig.json +2 -1
  53. package/agents/creators/blog-writer.ts +0 -347
  54. package/agents/creators/course-creator.ts +0 -106
  55. package/agents/creators/crm-agent.ts +0 -479
  56. package/agents/creators/forms-builder.ts +0 -90
  57. package/agents/creators/jobs-manager.ts +0 -82
  58. package/agents/creators/store-manager.ts +0 -138
  59. package/agents/csuite/coo.ts +0 -115
  60. package/agents/growth/analytics-agent.ts +0 -52
  61. package/agents/growth/social-agent.ts +0 -346
  62. /package/{ingest.md → .claude/commands/ingest.md} +0 -0
  63. /package/agents/{creators/copywriter.ts → copywriting/copywriting.ts} +0 -0
  64. /package/agents/{creators/docs-writer.ts → docs/docs.ts} +0 -0
  65. /package/agents/{creators/newsletter-writer.ts → newsletter/newsletter.ts} +0 -0
  66. /package/{ABOUT-ME.md → context/about-me.md} +0 -0
  67. /package/{brand-voice.md → context/brand-voice.md} +0 -0
  68. /package/{working-style.md → context/working-style.md} +0 -0
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Forms Agent — build forms, read submissions.
3
+ *
4
+ * DB contract (businesskit-files/forms.ts):
5
+ * - forms: id, profile_id, title, slug, published, hidden,
6
+ * thank_you_settings JSON, collection_id
7
+ * - questions: id, form_id, type, title, description, position,
8
+ * options JSON, embed_url, required, settings JSON
9
+ * - submissions: append-only (trg_submissions_no_delete blocks DELETE);
10
+ * has answers JSON, status ('viewed' default), UTM fields,
11
+ * device/os/browser, timing (started/submitted/duration_ms)
12
+ * - form_analytics: auto-seeded by trg_form_insert, trigger-maintained
13
+ *
14
+ * Triggers fire on our writes:
15
+ * - trg_form_insert → INSERT OR IGNORE form_analytics + bump cms_analytics (cat_34)
16
+ * - trg_form_update_published → flips cms_analytics draft/published
17
+ * - trg_form_delete → decrements cms_analytics; we soft-delete instead
18
+ * - trg_submission_insert → +1 form_analytics.submissions + cms_analytics.total_submissions
19
+ * - trg_submissions_no_delete → BEFORE DELETE raises ABORT
20
+ *
21
+ * The Forms cms row (cat_34) must exist for cms_analytics updates to land.
22
+ */
23
+
24
+ import { BaseAgent, db, ulid, iso } from '../_base.ts'
25
+ import { uniqueSlug } from '../../lib/slug.ts'
26
+ import { ensureCmsRow, CATEGORY } from '../../lib/cms.ts'
27
+
28
+ export type QuestionType =
29
+ | 'text' | 'textarea' | 'email' | 'select' | 'multiselect'
30
+ | 'rating' | 'date' | 'file' | 'url' | 'embed' | 'number' | 'boolean'
31
+
32
+ export type SubmissionStatus = 'viewed' | 'started' | 'partial' | 'submitted'
33
+
34
+ export interface Question {
35
+ type: QuestionType
36
+ title: string
37
+ description?: string
38
+ required?: boolean
39
+ options?: string[]
40
+ embed_url?: string
41
+ settings?: Record<string, unknown>
42
+ }
43
+
44
+ export interface ThankYou {
45
+ title?: string
46
+ message?: string
47
+ redirect_url?: string
48
+ }
49
+
50
+ export interface FormInput {
51
+ title: string
52
+ questions: Question[]
53
+ thank_you?: ThankYou
54
+ collection_id?: string
55
+ publish?: boolean
56
+ }
57
+
58
+ export interface FormPatch {
59
+ title?: string
60
+ thank_you?: ThankYou
61
+ collection_id?: string
62
+ }
63
+
64
+ export class FormsBuilder extends BaseAgent {
65
+ readonly name = 'Forms'
66
+ readonly title = 'Forms Builder'
67
+
68
+ // ── Forms ─────────────────────────────────────────────────────────────────
69
+
70
+ async create(input: FormInput) {
71
+ await this.init()
72
+ // Seed the Forms cms row so trg_form_insert's cms_analytics UPDATE lands.
73
+ await ensureCmsRow(this.profileId, CATEGORY.FORMS, { slug: 'forms', title: 'Forms' })
74
+
75
+ const id = ulid()
76
+ const slug = await uniqueSlug('forms', input.title, this.profileId)
77
+ const ts = iso()
78
+
79
+ // form_analytics is seeded by trg_form_insert — no manual INSERT needed.
80
+ const stmts: Array<{ sql: string; args: unknown[] }> = [{
81
+ sql: `INSERT INTO forms
82
+ (id, profile_id, title, slug, published, hidden,
83
+ thank_you_settings, collection_id, created_at)
84
+ VALUES (?,?,?,?,?,0,?,?,?)`,
85
+ args: [
86
+ id, this.profileId, input.title, slug,
87
+ input.publish ? 1 : 0,
88
+ input.thank_you ? JSON.stringify(input.thank_you) : null,
89
+ input.collection_id ?? null, ts,
90
+ ],
91
+ }]
92
+
93
+ input.questions.forEach((q, i) => {
94
+ stmts.push({
95
+ sql: `INSERT INTO questions
96
+ (id, form_id, type, title, description, position, options,
97
+ embed_url, required, settings)
98
+ VALUES (?,?,?,?,?,?,?,?,?,?)`,
99
+ args: [
100
+ ulid(), id, q.type, q.title, q.description ?? null, i,
101
+ q.options ? JSON.stringify(q.options) : null,
102
+ q.embed_url ?? null, q.required ? 1 : 0,
103
+ q.settings ? JSON.stringify(q.settings) : null,
104
+ ],
105
+ })
106
+ })
107
+
108
+ await db.batch(stmts)
109
+ await this.logMemory(`${input.publish ? 'Published' : 'Drafted'} form "${input.title}"`,
110
+ { id, slug, questions: input.questions.length })
111
+ return this.get(id)
112
+ }
113
+
114
+ async edit(id: string, patch: FormPatch) {
115
+ await this.init()
116
+ const sets: string[] = []
117
+ const args: unknown[] = []
118
+ if (patch.title !== undefined) { sets.push('title=?'); args.push(patch.title) }
119
+ if (patch.thank_you !== undefined) { sets.push('thank_you_settings=?'); args.push(JSON.stringify(patch.thank_you)) }
120
+ if (patch.collection_id !== undefined) { sets.push('collection_id=?'); args.push(patch.collection_id) }
121
+ if (!sets.length) return this.get(id)
122
+
123
+ await db.write({
124
+ sql: `UPDATE forms SET ${sets.join(',')} WHERE id=? AND profile_id=?`,
125
+ args: [...args, id, this.profileId],
126
+ })
127
+ return this.get(id)
128
+ }
129
+
130
+ async get(id: string) {
131
+ await this.init()
132
+ const [{ rows: [form] }, { rows: questions }] = await Promise.all([
133
+ db.execute({
134
+ sql: 'SELECT * FROM forms WHERE id=? AND profile_id=? LIMIT 1',
135
+ args: [id, this.profileId],
136
+ }),
137
+ db.execute({
138
+ sql: `SELECT q.* FROM questions q
139
+ JOIN forms f ON f.id = q.form_id
140
+ WHERE q.form_id=? AND f.profile_id=?
141
+ ORDER BY q.position ASC`,
142
+ args: [id, this.profileId],
143
+ }),
144
+ ])
145
+ if (!form) throw new Error(`Form not found: ${id}`)
146
+ return { ...form, questions }
147
+ }
148
+
149
+ async list(opts: { published?: boolean; include_hidden?: boolean } = {}) {
150
+ await this.init()
151
+ let where = 'WHERE f.profile_id=?'
152
+ const args: unknown[] = [this.profileId]
153
+ if (!opts.include_hidden) where += ' AND f.hidden=0'
154
+ if (opts.published !== undefined) { where += ' AND f.published=?'; args.push(opts.published ? 1 : 0) }
155
+
156
+ const { rows } = await db.execute({
157
+ sql: `SELECT f.id, f.title, f.slug, f.published, f.created_at,
158
+ fa.total_views, fa.submissions, fa.starts, fa.partials,
159
+ fa.avg_completion_ms
160
+ FROM forms f
161
+ LEFT JOIN form_analytics fa ON fa.form_id = f.id
162
+ ${where}
163
+ ORDER BY f.created_at DESC`,
164
+ args,
165
+ })
166
+ return rows
167
+ }
168
+
169
+ async publish(id: string) {
170
+ await super.publish('forms', id)
171
+ return this.get(id)
172
+ }
173
+
174
+ async unpublish(id: string) {
175
+ await this.init()
176
+ await db.write({
177
+ sql: `UPDATE forms SET published=0 WHERE id=? AND profile_id=?`,
178
+ args: [id, this.profileId],
179
+ })
180
+ return this.get(id)
181
+ }
182
+
183
+ /** Soft archive — never hard DELETE (trg_form_delete would decrement
184
+ * cms_analytics and also cascade-delete form_analytics). */
185
+ async archive(id: string) {
186
+ await super.archive('forms', id)
187
+ }
188
+
189
+ // ── Questions ─────────────────────────────────────────────────────────────
190
+
191
+ async addQuestion(formId: string, q: Question): Promise<string> {
192
+ await this.init()
193
+ await this.assertOwned(formId)
194
+ const { rows: [r] } = await db.execute({
195
+ sql: `SELECT COALESCE(MAX(position), -1) + 1 AS next
196
+ FROM questions WHERE form_id=?`,
197
+ args: [formId],
198
+ })
199
+ const id = ulid()
200
+ await db.write({
201
+ sql: `INSERT INTO questions
202
+ (id, form_id, type, title, description, position, options,
203
+ embed_url, required, settings)
204
+ VALUES (?,?,?,?,?,?,?,?,?,?)`,
205
+ args: [
206
+ id, formId, q.type, q.title, q.description ?? null,
207
+ Number(r?.next ?? 0),
208
+ q.options ? JSON.stringify(q.options) : null,
209
+ q.embed_url ?? null, q.required ? 1 : 0,
210
+ q.settings ? JSON.stringify(q.settings) : null,
211
+ ],
212
+ })
213
+ return id
214
+ }
215
+
216
+ async updateQuestion(formId: string, questionId: string, patch: Partial<Question>) {
217
+ await this.init()
218
+ await this.assertOwned(formId)
219
+ const sets: string[] = []
220
+ const args: unknown[] = []
221
+ if (patch.type !== undefined) { sets.push('type=?'); args.push(patch.type) }
222
+ if (patch.title !== undefined) { sets.push('title=?'); args.push(patch.title) }
223
+ if (patch.description !== undefined) { sets.push('description=?'); args.push(patch.description) }
224
+ if (patch.options !== undefined) { sets.push('options=?'); args.push(JSON.stringify(patch.options)) }
225
+ if (patch.embed_url !== undefined) { sets.push('embed_url=?'); args.push(patch.embed_url) }
226
+ if (patch.required !== undefined) { sets.push('required=?'); args.push(patch.required ? 1 : 0) }
227
+ if (patch.settings !== undefined) { sets.push('settings=?'); args.push(JSON.stringify(patch.settings)) }
228
+ if (!sets.length) return
229
+
230
+ await db.write({
231
+ sql: `UPDATE questions SET ${sets.join(',')}
232
+ WHERE id=? AND form_id=?`,
233
+ args: [...args, questionId, formId],
234
+ })
235
+ }
236
+
237
+ async removeQuestion(formId: string, questionId: string) {
238
+ await this.init()
239
+ await this.assertOwned(formId)
240
+ await db.write({
241
+ sql: `DELETE FROM questions WHERE id=? AND form_id=?`,
242
+ args: [questionId, formId],
243
+ })
244
+ // questions has no DELETE guard — safe to remove; just renumber positions.
245
+ await this.renumber(formId)
246
+ }
247
+
248
+ /** Reorder questions. Pass the new full order as a list of question ids. */
249
+ async reorderQuestions(formId: string, orderedIds: string[]) {
250
+ await this.init()
251
+ await this.assertOwned(formId)
252
+ const stmts = orderedIds.map((qid, i) => ({
253
+ sql: `UPDATE questions SET position=? WHERE id=? AND form_id=?`,
254
+ args: [i, qid, formId],
255
+ }))
256
+ if (stmts.length) await db.batch(stmts)
257
+ }
258
+
259
+ // ── Submissions (READ + status updates only — append-only by DB trigger) ──
260
+
261
+ async submissions(formId: string, opts: { status?: SubmissionStatus; limit?: number } = {}) {
262
+ await this.init()
263
+ await this.assertOwned(formId)
264
+ let where = 'WHERE form_id=?'
265
+ const args: unknown[] = [formId]
266
+ if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
267
+ const { rows } = await db.execute({
268
+ sql: `SELECT id, status, answers, city, country, referrer,
269
+ utm_source, utm_medium, utm_campaign,
270
+ started_at, submitted_at, duration_ms, created_at
271
+ FROM submissions ${where}
272
+ ORDER BY created_at DESC LIMIT ?`,
273
+ args: [...args, opts.limit ?? 100],
274
+ })
275
+ return rows
276
+ }
277
+
278
+ async getSubmission(formId: string, submissionId: string) {
279
+ await this.init()
280
+ await this.assertOwned(formId)
281
+ const { rows: [r] } = await db.execute({
282
+ sql: `SELECT * FROM submissions WHERE id=? AND form_id=? LIMIT 1`,
283
+ args: [submissionId, formId],
284
+ })
285
+ if (!r) throw new Error(`Submission not found: ${submissionId}`)
286
+ return r
287
+ }
288
+
289
+ async updateSubmissionStatus(formId: string, submissionId: string, status: SubmissionStatus) {
290
+ await this.init()
291
+ await this.assertOwned(formId)
292
+ await db.write({
293
+ sql: `UPDATE submissions SET status=? WHERE id=? AND form_id=?`,
294
+ args: [status, submissionId, formId],
295
+ })
296
+ }
297
+
298
+ /** Submissions inbox across every form the profile owns. */
299
+ async inbox(opts: { status?: SubmissionStatus; limit?: number } = {}) {
300
+ await this.init()
301
+ let where = 'WHERE f.profile_id=?'
302
+ const args: unknown[] = [this.profileId]
303
+ if (opts.status) { where += ' AND s.status=?'; args.push(opts.status) }
304
+ const { rows } = await db.execute({
305
+ sql: `SELECT s.id, s.form_id, s.status, s.city, s.country,
306
+ s.submitted_at, s.created_at,
307
+ f.title AS form_title, f.slug AS form_slug
308
+ FROM submissions s
309
+ JOIN forms f ON f.id = s.form_id
310
+ ${where}
311
+ ORDER BY s.created_at DESC LIMIT ?`,
312
+ args: [...args, opts.limit ?? 50],
313
+ })
314
+ return rows
315
+ }
316
+
317
+ // ── Summary ───────────────────────────────────────────────────────────────
318
+
319
+ /** Free inventory via cms_analytics (trigger-maintained, cat_34 = Forms). */
320
+ async summary() {
321
+ await this.init()
322
+ const { rows: [r] } = await db.execute({
323
+ sql: `SELECT a.total_posts, a.total_published, a.total_draft,
324
+ a.total_submissions, a.total_views
325
+ FROM cms c
326
+ LEFT JOIN cms_analytics a ON a.cms_id = c.id
327
+ WHERE c.profile_id=? AND c.category_id=?`,
328
+ args: [this.profileId, CATEGORY.FORMS],
329
+ })
330
+ return {
331
+ total: Number(r?.total_posts ?? 0),
332
+ live: Number(r?.total_published ?? 0),
333
+ drafts: Number(r?.total_draft ?? 0),
334
+ submissions: Number(r?.total_submissions ?? 0),
335
+ views: Number(r?.total_views ?? 0),
336
+ }
337
+ }
338
+
339
+ // ── Private helpers ───────────────────────────────────────────────────────
340
+
341
+ /** Assert the form belongs to this profile — guards question + submission ops
342
+ * since those tables have no profile_id column of their own. */
343
+ private async assertOwned(formId: string): Promise<void> {
344
+ const { rows: [r] } = await db.execute({
345
+ sql: `SELECT id FROM forms WHERE id=? AND profile_id=? LIMIT 1`,
346
+ args: [formId, this.profileId],
347
+ })
348
+ if (!r) throw new Error(`Form not found (or not yours): ${formId}`)
349
+ }
350
+
351
+ private async renumber(formId: string): Promise<void> {
352
+ const { rows } = await db.execute({
353
+ sql: `SELECT id FROM questions WHERE form_id=? ORDER BY position ASC`,
354
+ args: [formId],
355
+ })
356
+ const stmts = rows.map((r, i) => ({
357
+ sql: `UPDATE questions SET position=? WHERE id=? AND form_id=?`,
358
+ args: [i, r.id, formId],
359
+ }))
360
+ if (stmts.length) await db.batch(stmts)
361
+ }
362
+ }
363
+
364
+ export const formsBuilder = new FormsBuilder()
@@ -0,0 +1,11 @@
1
+ # hiring
2
+
3
+ Placeholder SOUL. See CLAUDE.md routing table and skills/hiring/SKILL.md (if present) for scope.
4
+
5
+ ## Rules
6
+
7
+ - Load skills on demand
8
+ - Draft before publish
9
+ - Archive not delete (hidden=1)
10
+ - Log every action to agent_memory
11
+ - Push reports to agent_reports mid-session
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Hiring Agent — Job listings & applications.
3
+ *
4
+ * DB contract (businesskit-files/jobs.ts):
5
+ * - job_listings: id, profile_id, user_id, title, company, location,
6
+ * location_type, employment_type, description, salary_*, slug, published,
7
+ * hidden, total_applicants (trigger-maintained), expires_at, form_settings
8
+ * - job_applications: id, job_id, profile_id, resume fields, applicant info,
9
+ * status ('viewed' default), UTM fields
10
+ * - job_analytics: 1 row per listing, auto-seeded by trg_job_listing_insert
11
+ *
12
+ * Triggers that fire on our writes:
13
+ * - trg_job_listing_insert → seeds job_analytics + bumps cms_analytics (cat_31)
14
+ * - trg_job_listing_update_published → flips draft/published on cms_analytics
15
+ * - trg_job_listing_delete → decrements cms_analytics; we soft-delete instead
16
+ * - trg_job_application_insert → increments job_analytics.total_applications
17
+ * + job_listings.total_applicants + cms_analytics
18
+ *
19
+ * For the cms_analytics cat_31 updates to land, the Jobs cms row must exist;
20
+ * ensureCmsRow() seeds it on first create().
21
+ *
22
+ * IDs are TEXT ulid(). Timestamps are ISO TEXT.
23
+ */
24
+
25
+ import { BaseAgent, db, ulid, iso } from '../_base.ts'
26
+ import { uniqueSlug } from '../../lib/slug.ts'
27
+ import { ensureCmsRow, CATEGORY } from '../../lib/cms.ts'
28
+
29
+ export type LocationType = 'remote' | 'onsite' | 'hybrid'
30
+ export type EmploymentType = 'full-time' | 'part-time' | 'contract' | 'freelance'
31
+ export type ApplicationStatus = 'viewed' | 'shortlisted' | 'interviewing' | 'offered' | 'hired' | 'rejected'
32
+
33
+ export interface JobInput {
34
+ title: string
35
+ company: string
36
+ location: string
37
+ location_type: LocationType
38
+ employment_type: EmploymentType
39
+ description: string
40
+ excerpt?: string
41
+ requirements?: string
42
+ salary_min?: number
43
+ salary_max?: number
44
+ salary_currency?: string
45
+ image_url?: string
46
+ expires_at?: string
47
+ ai_summary?: string
48
+ additional_details?: string
49
+ form_settings?: Record<string, unknown>
50
+ collection_id?: string
51
+ publish?: boolean
52
+ }
53
+
54
+ export interface JobUpdate {
55
+ title?: string
56
+ company?: string
57
+ location?: string
58
+ location_type?: LocationType
59
+ employment_type?: EmploymentType
60
+ description?: string
61
+ excerpt?: string
62
+ requirements?: string
63
+ salary_min?: number
64
+ salary_max?: number
65
+ salary_currency?: string
66
+ image_url?: string
67
+ expires_at?: string
68
+ ai_summary?: string
69
+ form_settings?: Record<string, unknown>
70
+ collection_id?: string
71
+ }
72
+
73
+ export class JobsManager extends BaseAgent {
74
+ readonly name = 'Hiring'
75
+ readonly title = 'Hiring Agent'
76
+
77
+ // ── Listings ──────────────────────────────────────────────────────────────
78
+
79
+ async create(input: JobInput) {
80
+ await this.init()
81
+ // Seed the Jobs cms row so trg_job_listing_insert's cms_analytics UPDATE
82
+ // has a row to hit.
83
+ await ensureCmsRow(this.profileId, CATEGORY.JOBS, { slug: 'jobs', title: 'Jobs' })
84
+
85
+ const id = ulid()
86
+ const slug = await uniqueSlug('job_listings', input.title, this.profileId)
87
+ const ts = iso()
88
+
89
+ // Validate salary bounds early (DB has no CHECK but negative salaries are nonsense).
90
+ const salaryMin = input.salary_min !== undefined ? Math.max(0, Math.round(input.salary_min)) : null
91
+ const salaryMax = input.salary_max !== undefined ? Math.max(0, Math.round(input.salary_max)) : null
92
+ if (salaryMin !== null && salaryMax !== null && salaryMax < salaryMin) {
93
+ throw new Error(`salary_max (${salaryMax}) must be ≥ salary_min (${salaryMin})`)
94
+ }
95
+
96
+ await db.write({
97
+ sql: `INSERT INTO job_listings
98
+ (id, profile_id, user_id, title, company, location, location_type,
99
+ employment_type, description, excerpt, requirements,
100
+ salary_min, salary_max, salary_currency, slug, image_url,
101
+ expires_at, ai_summary, additional_details, collection_id,
102
+ form_settings, published, hidden, created_at, updated_at)
103
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?)`,
104
+ args: [
105
+ id, this.profileId, this.userId,
106
+ input.title, input.company, input.location, input.location_type,
107
+ input.employment_type, input.description,
108
+ input.excerpt ?? null, input.requirements ?? null,
109
+ salaryMin, salaryMax, input.salary_currency ?? 'USD',
110
+ slug, input.image_url ?? null,
111
+ input.expires_at ?? null, input.ai_summary ?? null,
112
+ input.additional_details ?? null, input.collection_id ?? null,
113
+ JSON.stringify(input.form_settings ?? {}),
114
+ input.publish ? 1 : 0, ts, ts,
115
+ ],
116
+ })
117
+
118
+ await this.logMemory(`${input.publish ? 'Published' : 'Drafted'} job listing "${input.title}"`,
119
+ { id, slug, company: input.company })
120
+
121
+ return this.get(id)
122
+ }
123
+
124
+ async edit(id: string, patch: JobUpdate) {
125
+ await this.init()
126
+ const sets: string[] = ['updated_at=?']
127
+ const args: unknown[] = [iso()]
128
+
129
+ const fields: Array<[keyof JobUpdate, string]> = [
130
+ ['title', 'title'],
131
+ ['company', 'company'],
132
+ ['location', 'location'],
133
+ ['location_type', 'location_type'],
134
+ ['employment_type', 'employment_type'],
135
+ ['description', 'description'],
136
+ ['excerpt', 'excerpt'],
137
+ ['requirements', 'requirements'],
138
+ ['salary_min', 'salary_min'],
139
+ ['salary_max', 'salary_max'],
140
+ ['salary_currency', 'salary_currency'],
141
+ ['image_url', 'image_url'],
142
+ ['expires_at', 'expires_at'],
143
+ ['ai_summary', 'ai_summary'],
144
+ ['collection_id', 'collection_id'],
145
+ ]
146
+ for (const [k, col] of fields) {
147
+ if (patch[k] !== undefined) {
148
+ sets.push(`${col}=?`)
149
+ args.push(patch[k] as never)
150
+ }
151
+ }
152
+ if (patch.form_settings !== undefined) {
153
+ sets.push('form_settings=?')
154
+ args.push(JSON.stringify(patch.form_settings))
155
+ }
156
+ if (sets.length === 1) return this.get(id) // nothing to update
157
+
158
+ await db.write({
159
+ sql: `UPDATE job_listings SET ${sets.join(',')}
160
+ WHERE id=? AND profile_id=?`,
161
+ args: [...args, id, this.profileId],
162
+ })
163
+ return this.get(id)
164
+ }
165
+
166
+ async get(id: string) {
167
+ await this.init()
168
+ const { rows: [r] } = await db.execute({
169
+ sql: 'SELECT * FROM job_listings WHERE id=? AND profile_id=? LIMIT 1',
170
+ args: [id, this.profileId],
171
+ })
172
+ if (!r) throw new Error(`Job not found: ${id}`)
173
+ return r
174
+ }
175
+
176
+ async list(opts: { published?: boolean; include_hidden?: boolean } = {}) {
177
+ await this.init()
178
+ const args: unknown[] = [this.profileId]
179
+ let where = 'WHERE profile_id=?'
180
+ if (!opts.include_hidden) where += ' AND hidden=0'
181
+ if (opts.published !== undefined) {
182
+ where += ' AND published=?'
183
+ args.push(opts.published ? 1 : 0)
184
+ }
185
+ const { rows } = await db.execute({
186
+ sql: `SELECT id, title, company, location, location_type, employment_type,
187
+ salary_min, salary_max, salary_currency,
188
+ published, total_applicants, expires_at,
189
+ created_at, updated_at
190
+ FROM job_listings ${where}
191
+ ORDER BY created_at DESC`,
192
+ args,
193
+ })
194
+ return rows
195
+ }
196
+
197
+ /** Listings whose expires_at has passed — ready for review/soft-archive. */
198
+ async expiringSoon(withinDays = 7) {
199
+ await this.init()
200
+ const cutoff = new Date(Date.now() + withinDays * 86400_000).toISOString().slice(0, 19) + 'Z'
201
+ const { rows } = await db.execute({
202
+ sql: `SELECT id, title, company, expires_at, total_applicants
203
+ FROM job_listings
204
+ WHERE profile_id=? AND hidden=0 AND published=1
205
+ AND expires_at IS NOT NULL AND expires_at <= ?
206
+ ORDER BY expires_at ASC`,
207
+ args: [this.profileId, cutoff],
208
+ })
209
+ return rows
210
+ }
211
+
212
+ /** Flip published; trigger updates cms_analytics.total_published/total_draft. */
213
+ async publish(id: string) {
214
+ await super.publish('job_listings', id)
215
+ return this.get(id)
216
+ }
217
+
218
+ async unpublish(id: string) {
219
+ await this.init()
220
+ await db.write({
221
+ sql: `UPDATE job_listings SET published=0, updated_at=?
222
+ WHERE id=? AND profile_id=?`,
223
+ args: [iso(), id, this.profileId],
224
+ })
225
+ return this.get(id)
226
+ }
227
+
228
+ /** Soft archive (hidden=1). Never hard delete — would fire trg_job_listing_delete
229
+ * and decrement cms_analytics counters. */
230
+ async archive(id: string) {
231
+ await super.archive('job_listings', id)
232
+ }
233
+
234
+ // ── Applications ──────────────────────────────────────────────────────────
235
+
236
+ async applications(jobId: string, opts: { status?: ApplicationStatus; limit?: number } = {}) {
237
+ await this.init()
238
+ let where = 'WHERE job_id=? AND profile_id=?'
239
+ const args: unknown[] = [jobId, this.profileId]
240
+ if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
241
+
242
+ const { rows } = await db.execute({
243
+ sql: `SELECT id, full_name, email, phone, city, country, portfolio,
244
+ linkedin, github, skills, summary, status, created_at
245
+ FROM job_applications ${where}
246
+ ORDER BY created_at DESC LIMIT ?`,
247
+ args: [...args, opts.limit ?? 100],
248
+ })
249
+ return rows
250
+ }
251
+
252
+ async getApplication(id: string) {
253
+ await this.init()
254
+ const { rows: [r] } = await db.execute({
255
+ sql: `SELECT * FROM job_applications
256
+ WHERE id=? AND profile_id=? LIMIT 1`,
257
+ args: [id, this.profileId],
258
+ })
259
+ if (!r) throw new Error(`Application not found: ${id}`)
260
+ return r
261
+ }
262
+
263
+ /** Move application through the pipeline (viewed → shortlisted → … → hired/rejected). */
264
+ async updateApplicationStatus(id: string, status: ApplicationStatus) {
265
+ await this.init()
266
+ await db.write({
267
+ sql: `UPDATE job_applications SET status=?, updated_at=?
268
+ WHERE id=? AND profile_id=?`,
269
+ args: [status, iso(), id, this.profileId],
270
+ })
271
+ }
272
+
273
+ /** All applications across all the profile's jobs — hiring inbox. */
274
+ async inbox(opts: { status?: ApplicationStatus; limit?: number } = {}) {
275
+ await this.init()
276
+ let where = 'WHERE a.profile_id=?'
277
+ const args: unknown[] = [this.profileId]
278
+ if (opts.status) { where += ' AND a.status=?'; args.push(opts.status) }
279
+ const { rows } = await db.execute({
280
+ sql: `SELECT a.id, a.full_name, a.email, a.city, a.country, a.status,
281
+ a.created_at, j.title AS job_title, j.company
282
+ FROM job_applications a
283
+ JOIN job_listings j ON j.id = a.job_id
284
+ ${where}
285
+ ORDER BY a.created_at DESC LIMIT ?`,
286
+ args: [...args, opts.limit ?? 50],
287
+ })
288
+ return rows
289
+ }
290
+
291
+ // ── Summary ───────────────────────────────────────────────────────────────
292
+
293
+ /** Inventory: totals from cms_analytics (free — trigger-maintained). */
294
+ async summary() {
295
+ await this.init()
296
+ const { rows: [r] } = await db.execute({
297
+ sql: `SELECT a.total_posts, a.total_published, a.total_draft,
298
+ a.total_applications, a.total_views
299
+ FROM cms c
300
+ LEFT JOIN cms_analytics a ON a.cms_id = c.id
301
+ WHERE c.profile_id=? AND c.category_id=?`,
302
+ args: [this.profileId, CATEGORY.JOBS],
303
+ })
304
+ return {
305
+ total: Number(r?.total_posts ?? 0),
306
+ live: Number(r?.total_published ?? 0),
307
+ drafts: Number(r?.total_draft ?? 0),
308
+ applications: Number(r?.total_applications ?? 0),
309
+ views: Number(r?.total_views ?? 0),
310
+ }
311
+ }
312
+ }
313
+
314
+ export const jobsManager = new JobsManager()