@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/REFERENCE.md ADDED
@@ -0,0 +1,160 @@
1
+ # Reference
2
+
3
+ > Load this when you need schema details, full routing rules, or agent architecture.
4
+ > Don't load at session start — load on demand.
5
+
6
+ ---
7
+
8
+ ## Full Agent Routing
9
+
10
+ | Request | Agent |
11
+ |---|---|
12
+ | "brief me" / "weekly update" / "what's happening" | CEO |
13
+ | "revenue" / "pricing" / "sales breakdown" | CBO |
14
+ | "content calendar" / "what should I write next" | CMO |
15
+ | "publish queue" / "what's scheduled" | COO |
16
+ | "write a post" / "blog" / "listicle" / "guide" / "vs article" | Blog Writer |
17
+ | "newsletter" / "email subscribers" | Newsletter Writer |
18
+ | "product description" / "landing page" / "bio" | Copywriter |
19
+ | "course" / "lessons" / "module" | Course Creator |
20
+ | "add product" / "launch" / "store item" | Store Manager |
21
+ | "job listing" / "hiring" / "applications" | Jobs Manager |
22
+ | "form" / "intake" / "survey" | Forms Builder |
23
+ | "docs" / "knowledge base" / "help article" | Docs Writer |
24
+ | "lead" / "contact" / "deal" / "outreach" | CRM Agent |
25
+ | "post to" / "social" / "tweet" / "LinkedIn" | Social Agent |
26
+ | "analytics" / "traffic" / "how many clicks" | Analytics Agent |
27
+ | "SEO" / "meta" / "keyword" / "LLM visibility" | SEO Agent |
28
+ | "schedule" / "publish queue" / "cron" | Scheduler |
29
+
30
+ **Direction:** C-Suite delegates to Creators. Creators never call C-Suite.
31
+
32
+ ---
33
+
34
+ ## Schema Quick Reference
35
+
36
+ ### Content — unified `content` table
37
+
38
+ All blog/notes/guides/newsletter/compare/alternative/prompt/skills content lives in the single `content` table, keyed by `cms_id` (one row per section in `cms`, which has a `category_id`). There is no `posts`/`newsletter`/`notes`/... table.
39
+
40
+ Shared columns: `id, cms_id, category_id, profile_id, user_id, slug, title, content, excerpt, published, hidden, collection_id, seo_title (≤60), seo_description (≤160), seo_keywords, word_count, reading_time_mins, internal_links (int), sources JSON, created_at, updated_at`.
41
+
42
+ Resolve cms_id for a kind via `getCmsId(profileId, kind)` in `agents/content/content.ts`. The unique index is `(profile_id, category_id, slug)`.
43
+
44
+ Kind → category_id: blog=cat_35, notes=cat_37, guides=cat_36, newsletter=cat_20, compare=cat_40, alternative=cat_41, prompt=cat_39, skills=cat_38.
45
+
46
+ Docs are separate (INT AUTOINCREMENT ids): `doc_collections`, `doc_articles`.
47
+
48
+ ### Products
49
+
50
+ ```
51
+ type: download|course|meeting|webinar|event|listing|sponsorship|service
52
+ price_cents INT | slug UNIQUE | published | hidden=1 to archive
53
+ ```
54
+
55
+ ### Sales (CRM)
56
+
57
+ ```
58
+ -- Contacts (dashboard route: /dashboard/contacts/[id]/)
59
+ crm_contacts: lead_score(0-100), icp_match, outreach_status, agent_status,
60
+ auto_approve, suggested_dm, conversation_thread JSON,
61
+ agent_context JSON, is_duplicate, duplicate_of
62
+
63
+ -- Pipeline
64
+ crm_deals: stage (new|contacted|proposal|negotiation|won|lost)
65
+ value_cents, probability, expected_close_at, line_items JSON
66
+
67
+ -- Activity timeline — APPEND-ONLY, never UPDATE
68
+ crm_activities: approval_status (pending_approval→approved|auto_sent|rejected)
69
+ direction (outbound|inbound), sender (agent|you|contact)
70
+ type (dm|email|call|meeting|note|task_done|purchase|agent_action)
71
+
72
+ -- Supporting tables
73
+ crm_tasks: status (open|done), due_at, priority
74
+ crm_notes: pinned, body (rich text) — editable unlike activities
75
+ crm_groups: name, icon — membership via crm_contact_groups junction table
76
+ NEVER use LIKE '%grp_x%' — use lib/groups.ts helpers
77
+ crm_templates: type (dm|email|follow_up|proposal), reply_rate_pct
78
+ crm_proposals: public_slug, status (draft|sent|viewed|signed|paid|expired|declined)
79
+ email_opened_at, email_open_count, email_clicked_at
80
+ crm_invoices: invoice_number, public_slug, line_items JSON, total_cents
81
+ email_opened_at, email_open_count, email_clicked_at
82
+ crm_imports: source (csv|linkedin|twitter|apollo|agent), status
83
+ crm_analytics: DB TRIGGERS manage ALL counters — NEVER write manually
84
+ total_pending_approvals, reply_rate_pct, forecast_*_cents
85
+
86
+ -- Key rules for sales agent
87
+ 1. approval_status='pending_approval' on ALL outbound activities — never auto_send
88
+ unless contact.auto_approve=1
89
+ 2. crm_activities is append-only — insert correcting row, never UPDATE
90
+ 3. crm_analytics is trigger-managed — never INSERT or UPDATE
91
+ 4. Groups: use lib/groups.ts not JSON LIKE queries
92
+ 5. Proposals/invoices: email tracking columns written by email_events triggers
93
+ ```
94
+
95
+ ### Social
96
+
97
+ ```
98
+ social_accounts: connection_mode (zernio_byok|zernio_platform|direct|n8n)
99
+ social_posts: status, scheduled_for, zernio_post_id
100
+ Platform key NEVER used by agents — only via /api/social/schedule Worker endpoint
101
+ ```
102
+
103
+ ### Agent tables
104
+
105
+ ```
106
+ agent_memory: rolling 20 rows — logMemory() after every action
107
+ agent_notes: inbox|processing|done|archived
108
+ agent_kb: slug+summary index, content on demand
109
+ agent_reports: append-only, push mid-session so nothing is lost
110
+ agent_tasks: pending|active|running|done|paused|failed|cancelled
111
+ ```
112
+
113
+ ### IDs and timestamps
114
+
115
+ ```
116
+ ulid() — most tables
117
+ omit id — doc_* (AUTOINCREMENT)
118
+ now() = Math.floor(Date.now()/1000) — INT timestamp columns
119
+ iso() = new Date().toISOString().slice(0,19)+'Z' — TEXT timestamp columns
120
+ ```
121
+
122
+ ### Seeded categories (never insert new ones)
123
+
124
+ ```
125
+ cat_1=links cat_15=startups cat_18=courses cat_19=downloads
126
+ cat_31=jobs cat_32=docs cat_34=forms cat_35=blog
127
+ ```
128
+
129
+ ---
130
+
131
+ ## Agent Roster (18 agents)
132
+
133
+ ### C-Suite
134
+
135
+ ceo (orchestrator, can_create=1, can_assign=1)
136
+ operations (can_assign=1), business
137
+
138
+ ### Marketing
139
+
140
+ marketing, content, newsletter, copywriting, social, seo
141
+
142
+ ### Operations
143
+
144
+ store, courses, hiring, forms, docs, scheduler, design
145
+
146
+ ### Business
147
+
148
+ sales, analytics
149
+
150
+ **Reporting:** operations/business/marketing → ceo. All others → their group lead.
151
+
152
+ ---
153
+
154
+ ## Phase 2 (in-app CF Worker)
155
+
156
+ ```ts
157
+ // Only this changes between local CLI and in-app:
158
+ import { createAgentDB } from '~/lib/db.adapter'
159
+ const ceo = new CEO(createAgentDB(event))
160
+ ```
package/SOUL.md CHANGED
@@ -115,3 +115,34 @@ Phrases like "In today's fast-paced world" or "Unlock your potential" are flagge
115
115
  If an agent is asked to do something that conflicts with these rules,
116
116
  it stops and surfaces the conflict before proceeding. It doesn't
117
117
  silently comply or silently refuse — it flags and asks.
118
+
119
+ ---
120
+
121
+ ## Skillify — every failure becomes permanent infrastructure
122
+
123
+ Inspired by Garry Tan's GBrain skillify pattern.
124
+
125
+ When an agent makes a mistake, gets confused, or takes an inefficient path:
126
+ **don't just fix it this session. Make it structurally impossible to repeat.**
127
+
128
+ **The pattern:**
129
+
130
+ 1. Identify the failure type: wrong side (deterministic work done in latent space), missing context, or wrong routing
131
+ 2. Write or update the relevant skill in `agent_skills` table
132
+ 3. If deterministic work was done in reasoning — write a `lib/` function for it instead
133
+ 4. Log the fix to `agent_memory` so it's permanent
134
+
135
+ **Deterministic vs latent:**
136
+
137
+ - **Deterministic** (never use LLM): counting rows, date math, formatting, reading known DB fields, routing decisions based on clear criteria
138
+ - **Latent** (LLM appropriate): tone, synthesis, summarising, writing, research, judgment calls
139
+
140
+ If an agent is doing date math in its head → that's a bug.
141
+ If an agent is reading 50 DB rows to find state that's in HEARTBEAT.md → that's a bug.
142
+ If an agent loads all skills when it only needs one → that's a bug.
143
+
144
+ Every one of these gets fixed in the code, not re-prompted.
145
+
146
+ **Dark skills (Garry's term):** Capabilities that exist in `agent_skills` or `.agents/skills/`
147
+ but aren't referenced anywhere agents can discover them are wasted. If you add a skill,
148
+ add it to the skills table in `CLAUDE.md`. Otherwise it's invisible.
package/SYSTEM.md CHANGED
@@ -4,6 +4,28 @@ You are an autonomous business agent for a creator running their business on Bus
4
4
 
5
5
  Your job is to get real business work done efficiently. Not to demonstrate capability. Not to be thorough for its own sake. To actually help someone run their business with minimal friction.
6
6
 
7
+ ## Four principles (Karpathy-adapted for business agents)
8
+
9
+ **1. Think before acting**
10
+ Don't assume. Don't silently pick an interpretation and run with it.
11
+ If unsure which product, contact, or platform — ask before writing.
12
+ State assumptions explicitly. Push back if a simpler approach exists.
13
+
14
+ **2. Minimum action that solves the problem**
15
+ No extra writes. No unrequested updates. No "while I'm at it" changes.
16
+ Update post title → touch only the title. Draft email → draft, don't send.
17
+ Every DB write should trace directly to what was asked.
18
+
19
+ **3. Surgical execution**
20
+ Touch only what the task requires.
21
+ Don't update adjacent records or clean up unrelated data.
22
+ Spot something broken but unrelated → mention it, don't fix it.
23
+
24
+ **4. Goal-driven loops**
25
+ Define success before starting.
26
+ "Fix the newsletter" → "draft, show, wait for approval, then send."
27
+ Let success criteria drive the loop, not constant clarification.
28
+
7
29
  ## Core constraint
8
30
 
9
31
  Every token costs money. Every unnecessary step wastes the user's time. Be direct. Be efficient. Do the work. Ask only when genuinely blocked.
package/agents/_base.ts CHANGED
@@ -1,63 +1,371 @@
1
- import { db } from '../lib/db.ts'
1
+ // agents/_base.ts
2
+ // BaseAgent — every agent extends this.
3
+ // Wires: profile isolation, idempotency, transactions, audit, memory cap.
4
+ //
5
+ // P0-1: generateIdempotencyKey() on every insert/update/archive
6
+ // P0-2: txn() for multi-statement flows (Turso atomic batch)
7
+ // P0-3: SQLITE_BUSY retry — via lib/db.ts (db.execute/write/txn all retry)
8
+ // P0-6: audit rows bundled in the same txn as every mutation helper
9
+ // P0-7: APPEND_ONLY guard — throws before hitting DB trigger
10
+ // P1-2: logMemory() trims to last 20 rows per agent
11
+ // P1-7: create() factory validates single-profile before construction
12
+ //
13
+ // Back-compat surface (every agent file uses these — keep stable):
14
+ // this.ctx / this.profileId / this.userId
15
+ // this.init() / this.archive() / this.publish() / this.count()
16
+ // re-exports: db, ulid, iso, now
17
+
18
+ import { db, type Stmt } from '../lib/db.ts'
2
19
  import { getBrandContext, type BrandContext } from '../lib/profile.ts'
3
- import { ulid, now, iso } from '../lib/id.ts'
4
- import type { Client } from '@libsql/client'
5
-
6
- /** Singleton Turso client — agents may import `db` for raw queries */
7
- export { db, ulid, now, iso }
8
-
9
- /**
10
- * BaseAgent — extend this for every agent.
11
- *
12
- * Provides:
13
- * - this.ctx → BrandContext (profile, settings, credentials)
14
- * - this.profileId → enforced on every write
15
- * - this.userId → from profile
16
- * - this.archive() → soft delete (hidden=1) for any table
17
- * - this.publish() → flip published=1 for any table
18
- * - this.count() → content inventory for any table
19
- */
20
+ import {
21
+ ulid, iso, now,
22
+ generateIdempotencyKey,
23
+ } from '../lib/id.ts'
24
+
25
+ export { db, ulid, iso, now }
26
+
20
27
  export abstract class BaseAgent {
21
28
  protected ctx!: BrandContext
22
- protected db: Client
29
+ protected readonly agentType: string
30
+
31
+ // Back-compat constructor — agents still do `new CEO()` as module singletons.
32
+ // Profile is loaded lazily via init() on first method call.
33
+ // Phase 2 will swap to BaseAgent.create() + sharedMap-injected client.
34
+ constructor(agentType?: string) {
35
+ this.agentType = agentType ?? this.constructor.name.toLowerCase()
36
+ }
37
+
38
+ // P1-1: schema-version cache — populated once per process on first init()
39
+ private static _migrations: Set<string> | null = null
40
+
41
+ /** Call at the start of any method that reads ctx / profileId / userId. */
42
+ protected async init(): Promise<void> {
43
+ if (!this.ctx) this.ctx = await getBrandContext()
44
+ if (BaseAgent._migrations === null) {
45
+ BaseAgent._migrations = new Set<string>()
46
+ try {
47
+ const { rows } = await db.execute(`SELECT id FROM _schema_migrations`)
48
+ for (const r of rows) BaseAgent._migrations.add(String(r.id))
49
+ } catch { /* pre-migration UserDB — empty set is fine */ }
50
+ }
51
+ }
52
+
53
+ /** P1-1: gate features on app-side migrations being applied. */
54
+ protected hasMigration(id: string): boolean {
55
+ return BaseAgent._migrations?.has(id) ?? false
56
+ }
23
57
 
24
- constructor(injectedDB?: Client) {
25
- this.db = injectedDB ?? db
58
+ protected get profileId(): string { return this.ctx.profile.id }
59
+ protected get userId(): string { return this.ctx.profile.user_id }
60
+
61
+ // P1-7: factory — asserts a profile will resolve before constructing.
62
+ // Single-profile UserDBs (the normal case) auto-pick. Multi-profile DBs
63
+ // must set PROFILE_ID in .env; that check lives in lib/profile.ts.
64
+ static async create<T extends BaseAgent>(
65
+ Cls: new (agentType?: string) => T,
66
+ agentType?: string,
67
+ ): Promise<T> {
68
+ const { rows } = await db.execute(`SELECT COUNT(*) as n FROM profiles`)
69
+ const n = Number(rows[0]?.n ?? 0)
70
+ if (n === 0) throw new Error('No profile in this UserDB — complete BusinessKit onboarding first')
71
+ const instance = new Cls(agentType)
72
+ await (instance as any).init() // throws with guidance if PROFILE_ID needed
73
+ return instance
74
+ }
75
+
76
+ // ── P0-2: atomic multi-statement batch ─────────────────────────────────────
77
+ protected async txn(stmts: Stmt[]): Promise<void> {
78
+ await db.txn(stmts)
26
79
  }
27
80
 
28
- /** Call at the start of any agent method that needs the DB */
29
- protected async init() {
30
- if (!this.ctx) this.ctx = await getBrandContext(this.db)
81
+ // ── P0-6: audit helper — always bundle inside txn with the mutation ────────
82
+ // Private: subclasses shouldn't call this directly, and renaming keeps
83
+ // agent-level `audit()` methods (e.g. SEOAgent.audit) free.
84
+ private auditStmt(opts: {
85
+ action: 'insert' | 'update' | 'archive'
86
+ table: string
87
+ rowId: string
88
+ diff: Record<string, unknown>
89
+ ikey: string
90
+ }): Stmt {
91
+ const raw = JSON.stringify(opts.diff)
92
+ const payload = raw.length > 4096
93
+ ? JSON.stringify({ _truncated: true, original_size_bytes: raw.length })
94
+ : raw
95
+ return {
96
+ sql: `INSERT OR IGNORE INTO agent_audit
97
+ (id, ts, agent_type, table_name, row_id, action, diff, idempotency_key)
98
+ VALUES (?,?,?,?,?,?,?,?)`,
99
+ args: [ulid(), now(), this.agentType, opts.table, opts.rowId, opts.action, payload, opts.ikey],
100
+ }
31
101
  }
32
102
 
33
- protected get profileId() { return this.ctx.profile.id }
34
- protected get userId() { return this.ctx.profile.user_id }
103
+ // ── P0-1 + P0-2 + P0-6: insert with idempotency + audit in one txn ─────────
104
+ // Silently falls back to plain INSERT if agent_audit doesn't exist yet
105
+ // (pre-migration UserDB). Never blocks agent progress on audit.
106
+ protected async insert(opts: {
107
+ table: string
108
+ id?: string
109
+ cols: Record<string, unknown>
110
+ }): Promise<{ inserted: boolean; id: string }> {
111
+ await this.init()
112
+ const id = opts.id ?? ulid()
113
+ const ikey = generateIdempotencyKey()
114
+ const row = { id, profile_id: this.profileId, ...opts.cols }
115
+ const keys = Object.keys(row)
116
+ const sql = `INSERT OR IGNORE INTO ${opts.table}
117
+ (${keys.join(',')}) VALUES (${keys.map(() => '?').join(',')})`
118
+ const args = Object.values(row)
35
119
 
36
- /** Soft delete — never hard delete */
37
- protected async archive(table: string, id: string | number) {
38
- const ts = typeof id === 'number'
39
- ? `updated_at='${iso()}'`
40
- : `updated_at=${now()}`
41
- await this.db.execute({ sql: `UPDATE ${table} SET hidden=1,${ts} WHERE id=?`, args: [id] })
120
+ try {
121
+ await this.txn([
122
+ { sql, args },
123
+ this.auditStmt({ action: 'insert', table: opts.table, rowId: id, diff: row, ikey }),
124
+ ])
125
+ } catch (e: any) {
126
+ if (/agent_audit/i.test(e?.message ?? '')) await db.write({ sql, args })
127
+ else throw e
128
+ }
129
+
130
+ const { rows } = await db.execute({ sql: `SELECT id FROM ${opts.table} WHERE id=?`, args: [id] })
131
+ return { inserted: rows.length > 0, id }
42
132
  }
43
133
 
44
- /** Publish any content row */
45
- protected async publish(table: string, id: string | number) {
46
- const ts = typeof id === 'number'
47
- ? `updated_at='${iso()}'`
48
- : `updated_at=${now()}`
49
- await this.db.execute({ sql: `UPDATE ${table} SET published=1,${ts} WHERE id=?`, args: [id] })
134
+ // ── P0-7: append-only guard — throws before the DB trigger does ────────────
135
+ // Matches the app-side schema: these tables block DELETE, not UPDATE.
136
+ // crm_activities in particular legitimately UPDATEs approval_status
137
+ // (pending_approval → approved|rejected|auto_sent) and read_at — the
138
+ // schema comment (crm.ts) explicitly calls this out.
139
+ // We only guard against UPDATEs on tables the app fully locks: agent_reports,
140
+ // email_events, clicks_analytics. crm_activities is excluded.
141
+ private static APPEND_ONLY = new Set([
142
+ 'agent_reports',
143
+ 'email_events',
144
+ 'clicks_analytics',
145
+ ])
146
+
147
+ // ── P0-2 + P0-6: UPDATE with audit in one txn ──────────────────────────────
148
+ protected async update(opts: {
149
+ table: string
150
+ id: string
151
+ cols: Record<string, unknown>
152
+ }): Promise<void> {
153
+ if (BaseAgent.APPEND_ONLY.has(opts.table))
154
+ throw new Error(`${opts.table} is append-only — insert a correcting row instead`)
155
+
156
+ await this.init()
157
+ const ikey = generateIdempotencyKey()
158
+ const sets = Object.keys(opts.cols).map(k => `${k}=?`).join(', ')
159
+ const sql = `UPDATE ${opts.table} SET ${sets}, updated_at=?
160
+ WHERE id=? AND profile_id=?`
161
+ const args = [...Object.values(opts.cols), iso(), opts.id, this.profileId]
162
+
163
+ try {
164
+ await this.txn([
165
+ { sql, args },
166
+ this.auditStmt({ action: 'update', table: opts.table, rowId: opts.id, diff: opts.cols, ikey }),
167
+ ])
168
+ } catch (e: any) {
169
+ if (/agent_audit/i.test(e?.message ?? '')) await db.write({ sql, args })
170
+ else throw e
171
+ }
50
172
  }
51
173
 
52
- /** Quick inventory: { total, live, drafts } */
53
- protected async count(table: string) {
54
- const { rows: [r] } = await this.db.execute({
174
+ // ── Soft-delete — never hard delete ───────────────────────────────────────
175
+ // Back-compat signature: (table, id) where id can be string or number.
176
+ protected async archive(table: string, id: string | number): Promise<void> {
177
+ if (BaseAgent.APPEND_ONLY.has(table))
178
+ throw new Error(`${table} is append-only — archive not allowed`)
179
+
180
+ await this.init()
181
+ const ikey = generateIdempotencyKey()
182
+ const tsCol = typeof id === 'number' ? now() : iso()
183
+ const sql = `UPDATE ${table} SET hidden=1, updated_at=? WHERE id=? AND profile_id=?`
184
+ const args = [tsCol, id, this.profileId]
185
+
186
+ try {
187
+ await this.txn([
188
+ { sql, args },
189
+ this.auditStmt({ action: 'archive', table, rowId: String(id), diff: { hidden: 1 }, ikey }),
190
+ ])
191
+ } catch (e: any) {
192
+ if (/agent_audit/i.test(e?.message ?? '')) await db.write({ sql, args })
193
+ else throw e
194
+ }
195
+ }
196
+
197
+ /** Publish any content row (flip published=1). Returns unknown so subclasses
198
+ * can override and return their fetched row. */
199
+ protected async publish(table: string, id: string | number): Promise<unknown> {
200
+ await this.init()
201
+ const tsCol = typeof id === 'number' ? now() : iso()
202
+ await db.write({
203
+ sql: `UPDATE ${table} SET published=1, updated_at=? WHERE id=? AND profile_id=?`,
204
+ args: [tsCol, id, this.profileId],
205
+ })
206
+ return undefined
207
+ }
208
+
209
+ /** Quick inventory: { total, live, drafts }. */
210
+ protected async count(table: string): Promise<{ total: number; live: number; drafts: number }> {
211
+ await this.init()
212
+ const { rows: [r] } = await db.execute({
55
213
  sql: `SELECT COUNT(*) total,
56
- SUM(CASE WHEN published=1 AND hidden=0 THEN 1 ELSE 0 END) live,
57
- SUM(CASE WHEN published=0 AND hidden=0 THEN 1 ELSE 0 END) drafts
214
+ SUM(CASE WHEN published=1 AND hidden=0 THEN 1 ELSE 0 END) live,
215
+ SUM(CASE WHEN published=0 AND hidden=0 THEN 1 ELSE 0 END) drafts
58
216
  FROM ${table} WHERE profile_id=?`,
59
217
  args: [this.profileId],
60
218
  })
61
- return { total: Number(r?.total ?? 0), live: Number(r?.live ?? 0), drafts: Number(r?.drafts ?? 0) }
219
+ return {
220
+ total: Number(r?.total ?? 0),
221
+ live: Number(r?.live ?? 0),
222
+ drafts: Number(r?.drafts ?? 0),
223
+ }
224
+ }
225
+
226
+ // ── P1-2: logMemory — write then trim to last 20 rows per agent ────────────
227
+ // agent_memory.id is INTEGER AUTOINCREMENT — let SQLite assign it.
228
+ // idempotency_key has a unique partial index; retries dedupe automatically.
229
+ protected async logMemory(action: string, meta: Record<string, unknown> = {}): Promise<void> {
230
+ await this.init()
231
+ try {
232
+ const ikey = generateIdempotencyKey()
233
+ await db.write({
234
+ sql: `INSERT OR IGNORE INTO agent_memory
235
+ (profile_id, session_date, agent, action, metadata, idempotency_key)
236
+ VALUES (?,?,?,?,?,?)`,
237
+ args: [
238
+ this.profileId, iso().slice(0, 10),
239
+ this.agentType, action, JSON.stringify(meta), ikey,
240
+ ],
241
+ })
242
+ await db.write({
243
+ sql: `DELETE FROM agent_memory
244
+ WHERE agent=? AND profile_id=?
245
+ AND id NOT IN (
246
+ SELECT id FROM agent_memory
247
+ WHERE agent=? AND profile_id=?
248
+ ORDER BY id DESC LIMIT 20
249
+ )`,
250
+ args: [this.agentType, this.profileId, this.agentType, this.profileId],
251
+ })
252
+ } catch { /* memory is best-effort — never block the agent */ }
253
+ }
254
+
255
+ // ── Agent tasks (kanban board — app-side dashboard renders these) ──────────
256
+ // Tables in `agent_tasks` (see businesskit-files/agent.ts). Each task has:
257
+ // status = 'pending' | 'active' | 'running' | 'done' | 'paused' | 'failed' | 'cancelled'
258
+ // source = 'user' | 'agent'
259
+ // schedule = optional cron string (NULL = on-demand)
260
+
261
+ /** Create a kanban task for an agent. Shows up in /dashboard/agents/tasks. */
262
+ protected async createAgentTask(opts: {
263
+ agent?: string // default: this agent
264
+ title: string
265
+ description?: string
266
+ command: string // e.g. 'weeklyBriefing', 'hotLeads', 'runPublishQueue'
267
+ params?: Record<string, unknown>
268
+ source?: 'user' | 'agent'
269
+ schedule?: string // cron; NULL = on-demand
270
+ timezone?: string
271
+ run_once?: boolean
272
+ next_run_at?: number
273
+ idempotency_key?: string
274
+ }): Promise<string> {
275
+ await this.init()
276
+ const id = ulid()
277
+ const ts = now()
278
+ const ikey = opts.idempotency_key ?? generateIdempotencyKey()
279
+ await db.write({
280
+ sql: `INSERT OR IGNORE INTO agent_tasks
281
+ (id, profile_id, agent, title, description, command, params, source,
282
+ schedule, timezone, run_once, status, next_run_at, idempotency_key,
283
+ created_at, updated_at)
284
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)`,
285
+ args: [
286
+ id, this.profileId, opts.agent ?? this.agentType,
287
+ opts.title, opts.description ?? null, opts.command,
288
+ JSON.stringify(opts.params ?? {}),
289
+ opts.source ?? 'agent',
290
+ opts.schedule ?? null, opts.timezone ?? 'UTC',
291
+ opts.run_once ? 1 : 0,
292
+ opts.next_run_at ?? null, ikey, ts, ts,
293
+ ],
294
+ })
295
+ return id
296
+ }
297
+
298
+ /** Move a task across the kanban: pending → active → running → done. */
299
+ protected async updateTaskStatus(
300
+ taskId: string,
301
+ status: 'pending' | 'active' | 'running' | 'done' | 'paused' | 'failed' | 'cancelled',
302
+ lastRunStatus?: string,
303
+ ): Promise<void> {
304
+ await this.init()
305
+ const ts = now()
306
+ const isTerminal = status === 'done' || status === 'failed' || status === 'cancelled'
307
+ await db.write({
308
+ sql: `UPDATE agent_tasks
309
+ SET status=?, last_run_status=?, last_run_at=?,
310
+ run_count=run_count+CASE WHEN ?=1 THEN 1 ELSE 0 END,
311
+ updated_at=?
312
+ WHERE id=? AND profile_id=?`,
313
+ args: [status, lastRunStatus ?? null, isTerminal ? ts : null,
314
+ isTerminal ? 1 : 0, ts, taskId, this.profileId],
315
+ })
316
+ }
317
+
318
+ /** List tasks for the kanban view. */
319
+ protected async listAgentTasks(opts: {
320
+ agent?: string
321
+ status?: 'pending' | 'active' | 'running' | 'done' | 'paused' | 'failed' | 'cancelled'
322
+ limit?: number
323
+ } = {}): Promise<unknown[]> {
324
+ await this.init()
325
+ let where = 'WHERE profile_id=? AND hidden=0'
326
+ const args: unknown[] = [this.profileId]
327
+ if (opts.agent) { where += ' AND agent=?'; args.push(opts.agent) }
328
+ if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
329
+ const { rows } = await db.execute({
330
+ sql: `SELECT id, agent, title, description, command, status,
331
+ schedule, next_run_at, last_run_at, last_run_status,
332
+ run_count, created_at
333
+ FROM agent_tasks ${where}
334
+ ORDER BY CASE status
335
+ WHEN 'running' THEN 0 WHEN 'active' THEN 1 WHEN 'pending' THEN 2
336
+ WHEN 'paused' THEN 3 WHEN 'done' THEN 4 ELSE 5 END,
337
+ created_at DESC LIMIT ?`,
338
+ args: [...args, opts.limit ?? 100],
339
+ })
340
+ return rows
341
+ }
342
+
343
+ // ── Agent reports — append-only, idempotent, mid-session safe ─────────────
344
+ // agent_reports has a unique partial index on idempotency_key — retries dedupe.
345
+ protected async pushReport(opts: {
346
+ title: string
347
+ type: string
348
+ content: string
349
+ summary?: string
350
+ html?: string
351
+ meta?: Record<string, unknown>
352
+ idempotency_key?: string
353
+ }): Promise<string> {
354
+ await this.init()
355
+ const id = ulid()
356
+ const ikey = opts.idempotency_key ?? generateIdempotencyKey()
357
+ await db.write({
358
+ sql: `INSERT OR IGNORE INTO agent_reports
359
+ (id, profile_id, agent, title, type, content, summary, html,
360
+ metadata, hidden, idempotency_key)
361
+ VALUES (?,?,?,?,?,?,?,?,?,0,?)`,
362
+ args: [
363
+ id, this.profileId, this.agentType,
364
+ opts.title, opts.type, opts.content,
365
+ opts.summary ?? null, opts.html ?? null,
366
+ JSON.stringify(opts.meta ?? {}), ikey,
367
+ ],
368
+ })
369
+ return id
62
370
  }
63
371
  }
@@ -0,0 +1,11 @@
1
+ # analytics
2
+
3
+ Placeholder SOUL. See CLAUDE.md routing table and skills/analytics/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