@businesskit/agent 1.0.3 → 1.0.5

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 (130) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.cursor-plugin/plugin.json +25 -0
  3. package/.cursorrules +10 -0
  4. package/.superconsole-plugin/plugin.json +32 -0
  5. package/AGENTS.md +94 -63
  6. package/CLAUDE.md +11 -65
  7. package/GEMINI.md +11 -34
  8. package/README.md +106 -153
  9. package/assets/logo.svg +3 -0
  10. package/bin/businesskit.js +11 -17
  11. package/commands/add-contact.md +47 -0
  12. package/commands/add-inventory-from-invoice.md +80 -0
  13. package/commands/adjust-stock.md +46 -0
  14. package/commands/capabilities.md +33 -0
  15. package/commands/check-stock.md +43 -0
  16. package/commands/create-component.md +109 -0
  17. package/commands/create-invoice.md +69 -0
  18. package/commands/create-new-bill.md +65 -0
  19. package/commands/create-page.md +96 -0
  20. package/commands/list-components.md +41 -0
  21. package/commands/list-content.md +46 -0
  22. package/commands/list-pages.md +45 -0
  23. package/commands/publish-page.md +64 -0
  24. package/commands/send-invoice.md +42 -0
  25. package/commands/seo-audit.md +36 -0
  26. package/commands/update-contact.md +46 -0
  27. package/commands/update-content.md +47 -0
  28. package/commands/update-page.md +55 -0
  29. package/commands/update-price.md +47 -0
  30. package/commands/write-blog.md +52 -0
  31. package/commands/write-docs.md +84 -0
  32. package/commands/write-guide.md +46 -0
  33. package/commands/write-newsletter.md +46 -0
  34. package/mcp_config.json +8 -0
  35. package/package.json +34 -23
  36. package/plugin.json +32 -0
  37. package/scripts/generate-schema.ts +244 -0
  38. package/scripts/setup.sh +134 -0
  39. package/scripts/setup.ts +92 -0
  40. package/server.json +21 -0
  41. package/skills/README.md +19 -27
  42. package/skills/billing/SKILL.md +64 -0
  43. package/skills/brand/SKILL.md +30 -86
  44. package/skills/copywriting/SKILL.md +1 -1
  45. package/skills/crm/SKILL.md +38 -0
  46. package/skills/docs-cms/SKILL.md +53 -0
  47. package/skills/docs-cms/references/how-to.md +383 -0
  48. package/skills/inbox/SKILL.md +49 -0
  49. package/skills/inventory/SKILL.md +69 -0
  50. package/skills/pages/SKILL.md +169 -0
  51. package/skills/pages/references/sections-catalog.json +950 -0
  52. package/skills/social/SKILL.md +1 -1
  53. package/templates/antigravity.json +8 -0
  54. package/templates/claude-code.mcp.json +8 -0
  55. package/templates/cursor.mcp.json +8 -0
  56. package/templates/vscode.mcp.json +9 -0
  57. package/.claude/commands/analytics.md +0 -7
  58. package/.claude/commands/blog-writer.md +0 -9
  59. package/.claude/commands/cbo.md +0 -7
  60. package/.claude/commands/ceo.md +0 -10
  61. package/.claude/commands/cmo.md +0 -7
  62. package/.claude/commands/compress.md +0 -73
  63. package/.claude/commands/coo.md +0 -11
  64. package/.claude/commands/copywriter.md +0 -15
  65. package/.claude/commands/course-creator.md +0 -9
  66. package/.claude/commands/crm.md +0 -591
  67. package/.claude/commands/deep.md +0 -50
  68. package/.claude/commands/docs-writer.md +0 -8
  69. package/.claude/commands/forms-builder.md +0 -10
  70. package/.claude/commands/jobs-manager.md +0 -8
  71. package/.claude/commands/kb.md +0 -107
  72. package/.claude/commands/newsletter-writer.md +0 -9
  73. package/.claude/commands/preserve.md +0 -64
  74. package/.claude/commands/resume.md +0 -67
  75. package/.claude/commands/scheduler.md +0 -8
  76. package/.claude/commands/seo.md +0 -60
  77. package/.claude/commands/social.md +0 -51
  78. package/.claude/commands/store-manager.md +0 -11
  79. package/.env.example +0 -2
  80. package/.mcp.json +0 -3
  81. package/ABOUT-ME.md +0 -96
  82. package/HEARTBEAT.md +0 -105
  83. package/PLAN.md +0 -384
  84. package/PRD-Agent-Composition.md +0 -149
  85. package/PRD-Agent-Harness.md +0 -316
  86. package/REFERENCE.md +0 -124
  87. package/SOUL.md +0 -148
  88. package/SYSTEM.md +0 -71
  89. package/agents/_base.ts +0 -63
  90. package/agents/creators/blog-writer.ts +0 -347
  91. package/agents/creators/copywriter.ts +0 -89
  92. package/agents/creators/course-creator.ts +0 -106
  93. package/agents/creators/crm-agent.ts +0 -479
  94. package/agents/creators/docs-writer.ts +0 -77
  95. package/agents/creators/forms-builder.ts +0 -90
  96. package/agents/creators/jobs-manager.ts +0 -82
  97. package/agents/creators/newsletter-writer.ts +0 -91
  98. package/agents/creators/store-manager.ts +0 -138
  99. package/agents/csuite/cbo.ts +0 -109
  100. package/agents/csuite/ceo.ts +0 -121
  101. package/agents/csuite/cmo.ts +0 -109
  102. package/agents/csuite/coo.ts +0 -115
  103. package/agents/growth/analytics-agent.ts +0 -52
  104. package/agents/growth/scheduler.ts +0 -68
  105. package/agents/growth/seo-agent.ts +0 -282
  106. package/agents/growth/social-agent.ts +0 -346
  107. package/brand-voice.md +0 -127
  108. package/cli.ts +0 -125
  109. package/context/brand.md +0 -80
  110. package/context/business.md +0 -66
  111. package/ingest.md +0 -110
  112. package/lib/analytics.ts +0 -81
  113. package/lib/db.adapter.ts +0 -30
  114. package/lib/db.ts +0 -16
  115. package/lib/id.ts +0 -15
  116. package/lib/kb.ts +0 -337
  117. package/lib/memory.ts +0 -219
  118. package/lib/pattern-detector.ts +0 -169
  119. package/lib/profile.ts +0 -119
  120. package/lib/slug.ts +0 -30
  121. package/setup.ts +0 -127
  122. package/skills/agents/SKILL.md +0 -56
  123. package/skills/analytics/SKILL.md +0 -52
  124. package/skills/blog-writer/SKILL.md +0 -452
  125. package/skills/ceo/SKILL.md +0 -25
  126. package/skills/cmo/SKILL.md +0 -8
  127. package/skills/schema/SKILL.md +0 -45
  128. package/skills/store/SKILL.md +0 -62
  129. package/tsconfig.json +0 -13
  130. package/working-style.md +0 -87
@@ -1,66 +0,0 @@
1
- # Business Context
2
-
3
- > Keep this updated quarterly. Agents use it for CEO briefings and strategy.
4
-
5
- ---
6
-
7
- ## Current goals (this quarter)
8
- <!-- What are you trying to achieve in the next 90 days?
9
- Example:
10
- 1. Reach $10k MRR
11
- 2. Grow newsletter to 2,000 subscribers
12
- 3. Launch the new course on pricing strategy
13
- 4. Hire a part-time VA
14
- -->
15
-
16
- [Your goals here]
17
-
18
- ## Current focus
19
- <!-- What is the one thing you're working on right now?
20
- Example:
21
- Launching my email course by April 30. Everything else is secondary.
22
- -->
23
-
24
- [Your current focus here]
25
-
26
- ## Revenue model
27
- <!-- How do you make money? What are your revenue streams?
28
- Example:
29
- - Courses: 60% of revenue
30
- - Coaching: 30% of revenue
31
- - Affiliate: 10% of revenue
32
- Primary metric: monthly revenue. Target: $8k/month
33
- -->
34
-
35
- [Your revenue model here]
36
-
37
- ## Content publishing schedule
38
- <!-- How often do you publish? On what channels?
39
- Example:
40
- - Blog: 2x per week (Monday, Thursday)
41
- - Newsletter: every Tuesday
42
- - LinkedIn: 3x per week
43
- - Twitter: daily
44
- -->
45
-
46
- [Your publishing schedule here]
47
-
48
- ## Tools and integrations
49
- <!-- What tools do you use that agents should know about?
50
- Example:
51
- - n8n: automation webhook at [URL]
52
- - Notion: task board at [URL]
53
- - Resend: email delivery
54
- - Paddle: payments
55
- -->
56
-
57
- [Your tools here]
58
-
59
- ## Competitors and comparisons
60
- <!-- Who are the main alternatives in your space?
61
- Example:
62
- Main competitors: Teachable, Podia, Gumroad
63
- We're different because: we're built for creators who want to own their data
64
- -->
65
-
66
- [Your competitive context here]
package/ingest.md DELETED
@@ -1,110 +0,0 @@
1
- # /ingest — Process Inbox Into Knowledge Base
2
-
3
- Process everything in `agent_notes` with `status='inbox'` into the knowledge base.
4
- This is the magic moment: raw captures → structured, cross-linked wiki pages.
5
-
6
- Run this periodically — not every session. Daily or weekly depending on how much you capture.
7
-
8
- ---
9
-
10
- ## What it does
11
-
12
- 1. Fetch unprocessed notes from `agent_notes` (status='inbox')
13
- 2. For each note, decide: new KB entry OR update existing one
14
- 3. Cross-reference with existing KB index (slug + summary scan — no full content load)
15
- 4. Write or update KB entry with cross-links
16
- 5. If new note contradicts existing entry → mark existing stale first
17
- 6. File the note as processed
18
-
19
- ---
20
-
21
- ## Steps
22
-
23
- ```ts
24
- import { getInboxNotes, getIndex, searchKB, getEntry,
25
- upsertEntry, markStale, markNoteProcessed } from './lib/kb.ts'
26
-
27
- // 1. Load index — cheap, summaries only
28
- const index = await getIndex({ limit: 200 })
29
- console.log(`KB has ${index.length} entries`)
30
-
31
- // 2. Get inbox
32
- const notes = await getInboxNotes(20)
33
- if (!notes.length) {
34
- console.log('Inbox empty — nothing to process')
35
- return
36
- }
37
- console.log(`Processing ${notes.length} notes...`)
38
-
39
- // 3. For each note:
40
- for (const note of notes) {
41
- // a. Search for related existing entries
42
- const term = extractKeyTerm(note.content) // first meaningful phrase
43
- const hits = await searchKB(term, 5)
44
-
45
- // b. Decide: update existing or create new?
46
- if (hits.length && isSameConcept(note.content, hits[0])) {
47
- // Load the full entry only for the one we're updating
48
- const existing = await getEntry(hits[0].slug)
49
- // Check for contradiction
50
- if (contradicts(note.content, existing?.content)) {
51
- await markStale(hits[0].slug)
52
- }
53
- // Integrate new info into existing entry
54
- await upsertEntry({
55
- ...existing,
56
- content: integrate(existing.content, note.content),
57
- summary: refreshSummary(existing.content, note.content),
58
- source_note_ids: [...existing.source_note_ids, note.id],
59
- version: existing.version + 1,
60
- })
61
- await markNoteProcessed(note.id, `Integrated into: ${hits[0].slug}`)
62
- } else {
63
- // New entity or concept
64
- const slug = generateSlug(note.content)
65
- await upsertEntry({
66
- entry_type: classifyNote(note.content), // entity/concept/source/synthesis
67
- title: extractTitle(note.content),
68
- slug,
69
- content: compileWikiPage(note.content),
70
- summary: oneSentenceSummary(note.content),
71
- source_note_ids: [note.id],
72
- tags: extractTags(note.content),
73
- })
74
- await markNoteProcessed(note.id, `Compiled into new KB entry: ${slug}`)
75
- }
76
- }
77
- ```
78
-
79
- ## After each ingest
80
-
81
- - Log to `agent_memory`: how many notes processed, how many new entries, how many updated
82
- - Run stale check: show any entries marked stale that need updating
83
- - Push summary to `agent_reports` if batch was large (10+ notes)
84
-
85
- ## Stale handling
86
-
87
- After processing inbox, check for stale entries:
88
-
89
- ```ts
90
- const stale = await getStaleEntries()
91
- if (stale.length) {
92
- console.log(`${stale.length} entries need updating:`)
93
- stale.forEach(e => console.log(` - ${e.slug}: ${e.summary}`))
94
- // Offer to update them or leave for next /ingest run
95
- }
96
- ```
97
-
98
- ## When to run /ingest
99
-
100
- - After a batch of notes have been added to inbox
101
- - Before a deep research session (so KB is fresh)
102
- - Weekly at minimum if you capture regularly
103
- - Run by Scheduler agent on a weekly cron
104
-
105
- ## One new source can ripple through 10-15 pages
106
-
107
- That's the Karpathy insight. When you ingest a new article about email deliverability,
108
- the agent updates not just the deliverability entry — it checks every entry that
109
- references it (SES setup, ConvertKit comparison, newsletter strategy) and updates
110
- the cross-links. That's what makes the KB compound over time.
package/lib/analytics.ts DELETED
@@ -1,81 +0,0 @@
1
- import { db } from './db.ts'
2
-
3
- const parseArr = (v: unknown): number[] => { try { return JSON.parse(v as string) } catch { return [] } }
4
- const parseObj = (v: unknown): Record<string, number> => { try { return JSON.parse(v as string) } catch { return {} } }
5
- const top = (obj: Record<string, number>, n = 5) =>
6
- Object.entries(obj).sort((a, b) => b[1] - a[1]).slice(0, n)
7
-
8
- export async function profileSummary(profileId: string) {
9
- const { rows: [r] } = await db.execute({
10
- sql: 'SELECT * FROM profile_analytics WHERE profile_id=? LIMIT 1',
11
- args: [profileId],
12
- })
13
- if (!r) return null
14
-
15
- const rev30d = parseArr(r.revenue_30d)
16
- const revLife = parseObj(r.revenue_lifetime)
17
- const clicks30d = parseArr(r.analytics_30d)
18
-
19
- const half = Math.floor(rev30d.length / 2)
20
- const recent = rev30d.slice(half).reduce((a, b) => a + b, 0)
21
- const prior = rev30d.slice(0, half).reduce((a, b) => a + b, 0)
22
- const revTrend = prior
23
- ? `${recent >= prior ? '+' : ''}${Math.round(((recent - prior) / prior) * 100)}%`
24
- : 'new'
25
-
26
- return {
27
- total_clicks: (r.total_clicks as number) ?? 0,
28
- total_sales: (r.total_sales as number) ?? 0,
29
- total_revenue: Object.values(revLife).reduce((a, b) => a + b, 0),
30
- revenue_30d: rev30d,
31
- clicks_30d: clicks30d,
32
- revenue_trend: revTrend,
33
- top_countries: top(parseObj(r.country_clicks)),
34
- top_referrers: top(parseObj(r.referrer_clicks)),
35
- }
36
- }
37
-
38
- export async function productSummary(profileId: string) {
39
- const { rows } = await db.execute({
40
- sql: `SELECT pa.*, p.title, p.type
41
- FROM product_analytics pa
42
- JOIN products p ON p.id = pa.product_id
43
- WHERE pa.profile_id=?
44
- ORDER BY pa.total_revenue_cents DESC`,
45
- args: [profileId],
46
- })
47
- return rows.map(r => ({
48
- id: r.product_id as string,
49
- title: r.title as string,
50
- type: r.type as string,
51
- sales: (r.total_sales as number) ?? 0,
52
- revenue: (r.total_revenue_cents as number) ?? 0,
53
- rev30d: parseArr(r.revenue_30d),
54
- }))
55
- }
56
-
57
- export async function linkSummary(profileId: string, limit = 10) {
58
- const { rows } = await db.execute({
59
- sql: `SELECT la.link_id, la.total_clicks, la.analytics_7d, l.title, l.url
60
- FROM link_analytics la JOIN links l ON l.id = la.link_id
61
- WHERE la.profile_id=? ORDER BY la.total_clicks DESC LIMIT ?`,
62
- args: [profileId, limit],
63
- })
64
- return rows.map(r => ({
65
- id: r.link_id as string,
66
- title: r.title as string,
67
- url: r.url as string,
68
- clicks: (r.total_clicks as number) ?? 0,
69
- last7d: parseArr(r.analytics_7d),
70
- }))
71
- }
72
-
73
- export async function formSummary(profileId: string) {
74
- const { rows } = await db.execute({
75
- sql: `SELECT f.id, f.title, fa.views, fa.submissions
76
- FROM forms f LEFT JOIN form_analytics fa ON fa.form_id = f.id
77
- WHERE f.profile_id=? AND f.hidden=0 ORDER BY fa.submissions DESC`,
78
- args: [profileId],
79
- })
80
- return rows
81
- }
package/lib/db.adapter.ts DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * db.adapter.ts — Universal DB adapter
3
- *
4
- * This is the ONE file that differs between Phase 1 and Phase 2.
5
- * Everything else (agents, lib/) is identical in both environments.
6
- *
7
- * Phase 1 (local / CLI / Claude Code):
8
- * db is created from process.env in lib/db.ts
9
- *
10
- * Phase 2 (Cloudflare Worker / Qwik routeAction$):
11
- * db is injected from event.sharedMap — already decrypted + connected
12
- * by plugin.ts. Import createAgentDB() instead of db directly.
13
- */
14
-
15
- import type { Client } from '@libsql/client'
16
-
17
- /**
18
- * Phase 2: extract the raw libSQL client from Qwik's sharedMap.
19
- * sharedMap["userClient"] is set by plugin.ts on every request.
20
- */
21
- export function createAgentDB(event: { sharedMap: Map<string, unknown> }): Client {
22
- const client = event.sharedMap.get('userClient') as Client | undefined
23
- if (!client) {
24
- throw new Error(
25
- 'No userClient in sharedMap. ' +
26
- 'Ensure plugin.ts has run and the user has a connected Turso DB.'
27
- )
28
- }
29
- return client
30
- }
package/lib/db.ts DELETED
@@ -1,16 +0,0 @@
1
- import { createClient, type Client } from '@libsql/client/web'
2
-
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
- )
12
- }
13
- return createClient({ url, authToken: token })
14
- }
15
-
16
- export const db = createDB()
package/lib/id.ts DELETED
@@ -1,15 +0,0 @@
1
- const ENC = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
2
-
3
- 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('')
9
- }
10
-
11
- /** Unix epoch seconds — for INTEGER timestamp columns */
12
- export const now = () => Math.floor(Date.now() / 1000)
13
-
14
- /** ISO-8601 string — for TEXT timestamp columns (posts, jobs, forms, docs) */
15
- export const iso = () => new Date().toISOString().slice(0, 19) + 'Z'
package/lib/kb.ts DELETED
@@ -1,337 +0,0 @@
1
- /**
2
- * kb.ts — Karpathy LLM Wiki for BusinessKit agents
3
- *
4
- * The agent_kb table is a persistent, compounding knowledge base.
5
- * Agents maintain it. Users only read it.
6
- *
7
- * Three-layer architecture (Karpathy):
8
- * agent_notes → raw sources (user drops anything here)
9
- * agent_kb → compiled wiki (agent integrates, cross-references, updates)
10
- * agent_skills → schema (tells agent how the KB is structured)
11
- *
12
- * How it works:
13
- * 1. User drops notes into agent_notes (links, ideas, articles, screenshots)
14
- * 2. Agent runs processInboxNotes() periodically
15
- * 3. Agent reads each note, decides: new KB entry OR update existing one
16
- * 4. If new source contradicts existing entry → marks stale=1
17
- * 5. One new source can update 10-15 existing KB pages (Karpathy's observation)
18
- * 6. Answers to user questions get filed back as KB entries (compounding)
19
- *
20
- * Index pattern (token-efficient):
21
- * Agent reads slug+summary only (getIndex) → cheap scan
22
- * Drills into content only for relevant entries (getEntry)
23
- * Never loads all content at once
24
- */
25
-
26
- import { db } from './db.ts'
27
- import { getProfile } from './profile.ts'
28
- import { ulid, iso } from './id.ts'
29
-
30
- export type KBEntryType = 'entity' | 'concept' | 'source' | 'synthesis' | 'index'
31
-
32
- export interface KBEntry {
33
- id: string
34
- profile_id: string
35
- entry_type: KBEntryType
36
- title: string
37
- slug: string
38
- content: string
39
- summary: string | null
40
- related_ids: string[]
41
- source_note_ids: string[]
42
- tags: string[]
43
- stale: number
44
- version: number
45
- updated_at: string
46
- }
47
-
48
- export interface KBIndexEntry {
49
- id: string
50
- slug: string
51
- title: string
52
- summary: string | null
53
- entry_type: KBEntryType
54
- stale: number
55
- updated_at: string
56
- }
57
-
58
- // ─────────────────────────────────────────────────────────────────────────────
59
- // Read
60
- // ─────────────────────────────────────────────────────────────────────────────
61
-
62
- /**
63
- * Load the KB index — slug + summary only.
64
- * Token-efficient: agent uses this to find relevant entries without loading content.
65
- * Karpathy: "agent reads the index first, finds relevant pages, drills in."
66
- */
67
- export async function getIndex(opts: {
68
- entry_type?: KBEntryType
69
- stale_only?: boolean
70
- limit?: number
71
- } = {}): Promise<KBIndexEntry[]> {
72
- const profile = await getProfile()
73
- const args: unknown[] = [profile.id]
74
- let where = 'WHERE profile_id=? AND hidden=0'
75
-
76
- if (opts.entry_type) { where += ' AND entry_type=?'; args.push(opts.entry_type) }
77
- if (opts.stale_only) { where += ' AND stale=1' }
78
-
79
- args.push(opts.limit ?? 200)
80
- const { rows } = await db.execute({
81
- sql: `SELECT id,slug,title,summary,entry_type,stale,updated_at
82
- FROM agent_kb ${where}
83
- ORDER BY updated_at DESC LIMIT ?`,
84
- args,
85
- })
86
- return rows.map(parse_index) as KBIndexEntry[]
87
- }
88
-
89
- /**
90
- * Get a full KB entry by slug. Loads content.
91
- * Only call after finding the slug in getIndex().
92
- */
93
- export async function getEntry(slug: string): Promise<KBEntry | null> {
94
- const profile = await getProfile()
95
- const { rows: [r] } = await db.execute({
96
- sql: `SELECT * FROM agent_kb WHERE profile_id=? AND slug=? AND hidden=0 LIMIT 1`,
97
- args: [profile.id, slug],
98
- })
99
- return r ? parse_entry(r) : null
100
- }
101
-
102
- /**
103
- * Get multiple entries by their IDs (for loading related_ids).
104
- * Returns slug+summary only — caller drills into content if needed.
105
- */
106
- export async function getRelated(ids: string[]): Promise<KBIndexEntry[]> {
107
- if (!ids.length) return []
108
- const profile = await getProfile()
109
- const placeholders = ids.map(() => '?').join(',')
110
- const { rows } = await db.execute({
111
- sql: `SELECT id,slug,title,summary,entry_type,stale,updated_at
112
- FROM agent_kb WHERE profile_id=? AND id IN (${placeholders}) AND hidden=0`,
113
- args: [profile.id, ...ids],
114
- })
115
- return rows.map(parse_index) as KBIndexEntry[]
116
- }
117
-
118
- /**
119
- * Search KB by title/content match.
120
- * Simple full-text via LIKE — sufficient at KB scale (<500 entries).
121
- */
122
- export async function searchKB(query: string, limit = 20): Promise<KBIndexEntry[]> {
123
- const profile = await getProfile()
124
- const term = `%${query}%`
125
- const { rows } = await db.execute({
126
- sql: `SELECT id,slug,title,summary,entry_type,stale,updated_at
127
- FROM agent_kb
128
- WHERE profile_id=? AND hidden=0
129
- AND (title LIKE ? OR summary LIKE ? OR content LIKE ?)
130
- ORDER BY updated_at DESC LIMIT ?`,
131
- args: [profile.id, term, term, term, limit],
132
- })
133
- return rows.map(parse_index) as KBIndexEntry[]
134
- }
135
-
136
- // ─────────────────────────────────────────────────────────────────────────────
137
- // Write (agent-only — users never write directly)
138
- // ─────────────────────────────────────────────────────────────────────────────
139
-
140
- /**
141
- * Create or update a KB entry by slug (upsert).
142
- * Agent calls this when integrating a new source or updating an existing page.
143
- * Karpathy: "one new source can ripple through 10-15 existing pages."
144
- */
145
- export async function upsertEntry(input: {
146
- entry_type: KBEntryType
147
- title: string
148
- slug: string
149
- content: string
150
- summary?: string
151
- related_ids?: string[]
152
- source_note_ids?: string[]
153
- tags?: string[]
154
- }): Promise<string> {
155
- const profile = await getProfile()
156
- const existing = await getEntry(input.slug)
157
- const now = iso()
158
-
159
- if (existing) {
160
- // Update — increment version, clear stale flag
161
- await db.execute({
162
- sql: `UPDATE agent_kb SET
163
- title=?,content=?,summary=?,related_ids=?,
164
- source_note_ids=?,tags=?,stale=0,
165
- version=version+1,updated_at=?
166
- WHERE id=?`,
167
- args: [
168
- input.title, input.content,
169
- input.summary ?? null,
170
- JSON.stringify(input.related_ids ?? []),
171
- JSON.stringify(input.source_note_ids ?? []),
172
- JSON.stringify(input.tags ?? []),
173
- now, existing.id,
174
- ],
175
- })
176
- return existing.id
177
- }
178
-
179
- // Create new entry
180
- const id = ulid()
181
- await db.execute({
182
- sql: `INSERT INTO agent_kb
183
- (id,profile_id,entry_type,title,slug,content,summary,
184
- related_ids,source_note_ids,tags,created_at,updated_at)
185
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
186
- args: [
187
- id, profile.id, input.entry_type,
188
- input.title, input.slug, input.content,
189
- input.summary ?? null,
190
- JSON.stringify(input.related_ids ?? []),
191
- JSON.stringify(input.source_note_ids ?? []),
192
- JSON.stringify(input.tags ?? []),
193
- now, now,
194
- ],
195
- })
196
- return id
197
- }
198
-
199
- /**
200
- * Mark an entry as stale when new info contradicts it.
201
- * Agent reviews stale entries and updates them.
202
- */
203
- export async function markStale(slug: string): Promise<void> {
204
- const profile = await getProfile()
205
- await db.execute({
206
- sql: `UPDATE agent_kb SET stale=1,updated_at=? WHERE profile_id=? AND slug=?`,
207
- args: [iso(), profile.id, slug],
208
- })
209
- }
210
-
211
- /**
212
- * File back an agent answer as a KB synthesis entry.
213
- * Karpathy: "your questions and the agents' answers get filed back as new wiki pages."
214
- * Call this whenever the agent produces a useful analysis or answer.
215
- */
216
- export async function fileAnswer(
217
- question: string,
218
- answer: string,
219
- related_slugs: string[] = []
220
- ): Promise<string> {
221
- const slug = 'qa-' + question.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 50)
222
- const summary = answer.slice(0, 200).replace(/\n/g, ' ') + '…'
223
-
224
- const related_ids: string[] = []
225
- for (const s of related_slugs) {
226
- const e = await getEntry(s)
227
- if (e) related_ids.push(e.id)
228
- }
229
-
230
- return upsertEntry({
231
- entry_type: 'synthesis',
232
- title: question,
233
- slug,
234
- content: `# Q: ${question}\n\n${answer}`,
235
- summary,
236
- related_ids,
237
- tags: ['qa', 'synthesis'],
238
- })
239
- }
240
-
241
- // ─────────────────────────────────────────────────────────────────────────────
242
- // Process inbox notes → KB (the core Karpathy integration loop)
243
- // ─────────────────────────────────────────────────────────────────────────────
244
-
245
- /**
246
- * Get unprocessed notes from agent_notes (status='inbox').
247
- * Agent reads these, integrates them into KB, marks them 'done'.
248
- */
249
- export async function getInboxNotes(limit = 10): Promise<Array<{
250
- id: string; content: string; tags: string[]
251
- }>> {
252
- const profile = await getProfile()
253
- const { rows } = await db.execute({
254
- sql: `SELECT id,content,tags FROM agent_notes
255
- WHERE profile_id=? AND status='inbox' AND hidden=0
256
- ORDER BY created_at ASC LIMIT ?`,
257
- args: [profile.id, limit],
258
- })
259
- return rows.map(r => ({
260
- id: r.id as string,
261
- content: r.content as string,
262
- tags: safeJSON(r.tags, []) as string[],
263
- }))
264
- }
265
-
266
- /**
267
- * Mark a note as processed after integrating it into KB.
268
- */
269
- export async function markNoteProcessed(
270
- noteId: string,
271
- agentResponse: string
272
- ): Promise<void> {
273
- const profile = await getProfile()
274
- await db.execute({
275
- sql: `UPDATE agent_notes SET status='done',agent_response=?,updated_at=?
276
- WHERE id=? AND profile_id=?`,
277
- args: [agentResponse, iso(), noteId, profile.id],
278
- })
279
- }
280
-
281
- /**
282
- * Get all stale entries for agent review.
283
- * Agent should update these when it has new info.
284
- */
285
- export async function getStaleEntries(): Promise<KBIndexEntry[]> {
286
- return getIndex({ stale_only: true })
287
- }
288
-
289
- /**
290
- * Format the KB index as a compact context string for agents.
291
- * Token-efficient — only slug, type, and summary.
292
- */
293
- export async function kbContext(limit = 50): Promise<string> {
294
- const index = await getIndex({ limit })
295
- if (!index.length) return '(Knowledge base is empty — add notes via agent_notes inbox)'
296
-
297
- const lines = index.map(e =>
298
- `[${e.entry_type}] ${e.slug}: ${e.summary ?? e.title}${e.stale ? ' ⚠️ stale' : ''}`
299
- )
300
- return `## Knowledge Base Index (${index.length} entries)\n${lines.join('\n')}`
301
- }
302
-
303
- // ─── helpers ─────────────────────────────────────────────────────────────────
304
-
305
- function safeJSON(v: unknown, fb: unknown) {
306
- try { return JSON.parse(v as string) } catch { return fb }
307
- }
308
-
309
- function parse_index(r: Record<string, unknown>): KBIndexEntry {
310
- return {
311
- id: r.id as string,
312
- slug: r.slug as string,
313
- title: r.title as string,
314
- summary: r.summary as string | null,
315
- entry_type: r.entry_type as KBEntryType,
316
- stale: r.stale as number,
317
- updated_at: r.updated_at as string,
318
- }
319
- }
320
-
321
- function parse_entry(r: Record<string, unknown>): KBEntry {
322
- return {
323
- id: r.id as string,
324
- profile_id: r.profile_id as string,
325
- entry_type: r.entry_type as KBEntryType,
326
- title: r.title as string,
327
- slug: r.slug as string,
328
- content: r.content as string,
329
- summary: r.summary as string | null,
330
- related_ids: safeJSON(r.related_ids, []) as string[],
331
- source_note_ids: safeJSON(r.source_note_ids, []) as string[],
332
- tags: safeJSON(r.tags, []) as string[],
333
- stale: r.stale as number,
334
- version: r.version as number,
335
- updated_at: r.updated_at as string,
336
- }
337
- }