-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
1377 lines (1244 loc) · 37 KB
/
Copy pathdb.ts
File metadata and controls
1377 lines (1244 loc) · 37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Database } from "@db/sqlite";
const dbPath = Deno.env.get("DATABASE_PATH") || "data.db";
const db = new Database(dbPath);
// Enable WAL mode for better concurrency
db.exec("PRAGMA journal_mode=WAL");
// Migration: add description column (idempotent)
try {
db.exec(`ALTER TABLE apps ADD COLUMN description TEXT DEFAULT ''`);
} catch {
// Column already exists
}
// Migration: add PRD/ERD/POC plan columns
try { db.exec(`ALTER TABLE apps ADD COLUMN prd TEXT DEFAULT ''`); } catch {}
try { db.exec(`ALTER TABLE apps ADD COLUMN erd TEXT DEFAULT ''`); } catch {}
try { db.exec(`ALTER TABLE apps ADD COLUMN poc_plan TEXT DEFAULT ''`); } catch {}
// Migration: add disabled/disabled_reason columns
try { db.exec(`ALTER TABLE apps ADD COLUMN disabled INTEGER DEFAULT 0`); } catch {}
try { db.exec(`ALTER TABLE apps ADD COLUMN disabled_reason TEXT DEFAULT ''`); } catch {}
// Migration: add build_status/failure_reason columns for async generation
try { db.exec(`ALTER TABLE apps ADD COLUMN build_status TEXT DEFAULT 'ready'`); } catch {}
try { db.exec(`ALTER TABLE apps ADD COLUMN failure_reason TEXT DEFAULT ''`); } catch {}
// Create meta tables
db.exec(`
CREATE TABLE IF NOT EXISTS apps (
id TEXT PRIMARY KEY,
github_issue_url TEXT NOT NULL,
title TEXT NOT NULL,
html TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS app_schemas (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT NOT NULL,
table_name TEXT NOT NULL,
columns TEXT NOT NULL,
UNIQUE(app_id, table_name)
)
`);
// Conversation persistence for LLM chat
db.exec(`
CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY,
app_id TEXT NOT NULL,
title TEXT NOT NULL DEFAULT 'New conversation',
system_prompt TEXT,
model TEXT NOT NULL DEFAULT 'sonnet',
temperature REAL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
// Agent system tables
db.exec(`
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
app_id TEXT NOT NULL,
name TEXT NOT NULL,
static_prompt TEXT NOT NULL DEFAULT '',
model TEXT NOT NULL DEFAULT 'sonnet',
temperature REAL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS guidelines (
id TEXT PRIMARY KEY,
app_id TEXT NOT NULL,
name TEXT NOT NULL,
content TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS agent_guidelines (
agent_id TEXT NOT NULL,
guideline_id TEXT NOT NULL,
PRIMARY KEY (agent_id, guideline_id)
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS mcp_servers (
id TEXT PRIMARY KEY,
app_id TEXT NOT NULL,
name TEXT NOT NULL,
url TEXT NOT NULL,
api_key TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS agent_mcp_servers (
agent_id TEXT NOT NULL,
mcp_server_id TEXT NOT NULL,
PRIMARY KEY (agent_id, mcp_server_id)
)
`);
// Migration: add agent_id column to conversations (nullable for backward compat)
try {
db.exec(`ALTER TABLE conversations ADD COLUMN agent_id TEXT`);
} catch {
// Column already exists
}
// UX lessons learned from edit requests
db.exec(`
CREATE TABLE IF NOT EXISTS ux_lessons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lesson TEXT NOT NULL,
source_app_id TEXT,
source_edit_description TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
// Edit requests from non-root users
db.exec(`
CREATE TABLE IF NOT EXISTS edit_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT NOT NULL,
username TEXT NOT NULL,
description TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
// App credentials for per-app auth
db.exec(`
CREATE TABLE IF NOT EXISTS app_credentials (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
// Usage tracking for API spend
db.exec(`
CREATE TABLE IF NOT EXISTS usage_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT NOT NULL,
endpoint TEXT NOT NULL,
model TEXT NOT NULL,
input_tokens INTEGER NOT NULL,
output_tokens INTEGER NOT NULL,
cost_dollars REAL NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
// External data connections for apps
db.exec(`
CREATE TABLE IF NOT EXISTS app_connections (
id TEXT PRIMARY KEY,
app_id TEXT NOT NULL,
type TEXT NOT NULL,
name TEXT NOT NULL,
connection_string TEXT,
config TEXT DEFAULT '{}',
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
// Migration: add OAuth columns to app_connections
try { db.exec(`ALTER TABLE app_connections ADD COLUMN oauth_provider TEXT`); } catch {}
try { db.exec(`ALTER TABLE app_connections ADD COLUMN oauth_access_token TEXT`); } catch {}
try { db.exec(`ALTER TABLE app_connections ADD COLUMN oauth_refresh_token TEXT`); } catch {}
try { db.exec(`ALTER TABLE app_connections ADD COLUMN oauth_token_expires_at TEXT`); } catch {}
// === Spend Tracking ===
const MODEL_PRICING: Record<string, { input: number; output: number }> = {
"claude-opus-4-6": { input: 15, output: 75 },
"claude-sonnet-4-6": { input: 3, output: 15 },
"claude-sonnet-4-5-20250929": { input: 3, output: 15 },
"claude-haiku-4-5-20251001": { input: 0.80, output: 4 },
"gpt-4o": { input: 2.50, output: 10 },
};
const SPEND_LIMIT = 50; // dollars
export function logUsage(
appId: string,
endpoint: string,
model: string,
inputTokens: number,
outputTokens: number,
): void {
const pricing = MODEL_PRICING[model] ?? { input: 3, output: 15 }; // default to sonnet pricing
const cost = (inputTokens / 1_000_000) * pricing.input + (outputTokens / 1_000_000) * pricing.output;
db.exec(
`INSERT INTO usage_log (app_id, endpoint, model, input_tokens, output_tokens, cost_dollars) VALUES (?, ?, ?, ?, ?, ?)`,
[appId, endpoint, model, inputTokens, outputTokens, cost],
);
// Auto-disable if spend exceeds limit
const totalSpend = getAppSpend(appId);
if (totalSpend > SPEND_LIMIT) {
const status = isAppDisabled(appId);
if (!status.disabled) {
disableApp(appId, `Auto-disabled: spend exceeded $${SPEND_LIMIT}`);
console.log(`[spend] App ${appId} auto-disabled at $${totalSpend.toFixed(2)}`);
}
}
}
export function getAppSpend(appId: string): number {
const row = db
.prepare("SELECT SUM(cost_dollars) as total FROM usage_log WHERE app_id = ?")
.get(appId) as { total: number | null } | undefined;
return row?.total ?? 0;
}
export function getAllAppSpends(): Record<string, number> {
const rows = db
.prepare("SELECT app_id, SUM(cost_dollars) as total FROM usage_log GROUP BY app_id")
.all() as { app_id: string; total: number }[];
const result: Record<string, number> = {};
for (const row of rows) {
result[row.app_id] = row.total;
}
return result;
}
export function disableApp(appId: string, reason: string): void {
db.exec(`UPDATE apps SET disabled = 1, disabled_reason = ? WHERE id = ?`, [reason, appId]);
}
export function enableApp(appId: string): void {
db.exec(`UPDATE apps SET disabled = 0, disabled_reason = '' WHERE id = ?`, [appId]);
}
export function isAppDisabled(appId: string): { disabled: boolean; reason: string } {
const row = db
.prepare("SELECT disabled, disabled_reason FROM apps WHERE id = ?")
.get(appId) as { disabled: number; disabled_reason: string } | undefined;
if (!row) return { disabled: false, reason: "" };
return { disabled: row.disabled === 1, reason: row.disabled_reason || "" };
}
export function saveAppCredentials(
appId: string,
username: string,
password: string,
): void {
db.exec(
`INSERT INTO app_credentials (app_id, username, password) VALUES (?, ?, ?)`,
[appId, username, password],
);
}
export function getAppCredentialsByUsername(
username: string,
): { app_id: string; username: string; password: string } | null {
const row = db
.prepare(
"SELECT app_id, username, password FROM app_credentials WHERE username = ?",
)
.get(username) as
| { app_id: string; username: string; password: string }
| undefined;
return row ?? null;
}
export function getAppCredentials(
appId: string,
): { username: string; password: string } | null {
const row = db
.prepare("SELECT username, password FROM app_credentials WHERE app_id = ?")
.get(appId) as { username: string; password: string } | undefined;
return row ?? null;
}
export function updateAppCredentials(
appId: string,
username: string,
password: string,
): void {
db.exec(`DELETE FROM app_credentials WHERE app_id = ?`, [appId]);
db.exec(
`INSERT INTO app_credentials (app_id, username, password) VALUES (?, ?, ?)`,
[appId, username, password],
);
}
export function deleteAppCredentials(appId: string): void {
db.exec(`DELETE FROM app_credentials WHERE app_id = ?`, [appId]);
}
export function deleteApp(appId: string): void {
// Find dynamic tables for this app
const schemas = db
.prepare("SELECT table_name FROM app_schemas WHERE app_id = ?")
.all(appId) as { table_name: string }[];
// Drop dynamic tables
for (const schema of schemas) {
const ftn = fullTableName(appId, schema.table_name);
db.exec(`DROP TABLE IF EXISTS "${ftn}"`);
}
// Delete from meta tables
db.exec(`DELETE FROM app_schemas WHERE app_id = ?`, [appId]);
db.exec(`DELETE FROM app_credentials WHERE app_id = ?`, [appId]);
// Delete conversations and messages for this app
const convos = db
.prepare("SELECT id FROM conversations WHERE app_id = ?")
.all(appId) as { id: string }[];
for (const conv of convos) {
db.exec(`DELETE FROM messages WHERE conversation_id = ?`, [conv.id]);
}
db.exec(`DELETE FROM conversations WHERE app_id = ?`, [appId]);
// Delete agent system data for this app
const agentIds = db
.prepare("SELECT id FROM agents WHERE app_id = ?")
.all(appId) as { id: string }[];
for (const agent of agentIds) {
db.exec(`DELETE FROM agent_guidelines WHERE agent_id = ?`, [agent.id]);
db.exec(`DELETE FROM agent_mcp_servers WHERE agent_id = ?`, [agent.id]);
}
db.exec(`DELETE FROM agents WHERE app_id = ?`, [appId]);
const guidelineIds = db
.prepare("SELECT id FROM guidelines WHERE app_id = ?")
.all(appId) as { id: string }[];
for (const g of guidelineIds) {
db.exec(`DELETE FROM agent_guidelines WHERE guideline_id = ?`, [g.id]);
}
db.exec(`DELETE FROM guidelines WHERE app_id = ?`, [appId]);
const mcpServerIds = db
.prepare("SELECT id FROM mcp_servers WHERE app_id = ?")
.all(appId) as { id: string }[];
for (const s of mcpServerIds) {
db.exec(`DELETE FROM agent_mcp_servers WHERE mcp_server_id = ?`, [s.id]);
}
db.exec(`DELETE FROM mcp_servers WHERE app_id = ?`, [appId]);
db.exec(`DELETE FROM app_connections WHERE app_id = ?`, [appId]);
db.exec(`DELETE FROM usage_log WHERE app_id = ?`, [appId]);
db.exec(`DELETE FROM apps WHERE id = ?`, [appId]);
}
export function listAppsWithCredentials(): {
id: string;
title: string;
description: string;
prd: string;
erd: string;
poc_plan: string;
github_issue_url: string;
created_at: string;
cred_username: string | null;
cred_password: string | null;
disabled: number;
disabled_reason: string;
build_status: string;
failure_reason: string;
}[] {
return db
.prepare(
`SELECT a.id, a.title, a.description, a.prd, a.erd, a.poc_plan, a.github_issue_url, a.created_at,
a.disabled, a.disabled_reason, a.build_status, a.failure_reason,
ac.username AS cred_username, ac.password AS cred_password
FROM apps a
LEFT JOIN app_credentials ac ON a.id = ac.app_id
ORDER BY a.created_at DESC`,
)
.all() as {
id: string;
title: string;
description: string;
prd: string;
erd: string;
poc_plan: string;
github_issue_url: string;
created_at: string;
cred_username: string | null;
cred_password: string | null;
disabled: number;
disabled_reason: string;
build_status: string;
failure_reason: string;
}[];
}
// Conversation helpers
export function createConversation(
id: string,
appId: string,
title: string,
systemPrompt?: string,
model?: string,
temperature?: number,
): void {
db.exec(
`INSERT INTO conversations (id, app_id, title, system_prompt, model, temperature) VALUES (?, ?, ?, ?, ?, ?)`,
[
id,
appId,
title,
systemPrompt ?? null,
model ?? "sonnet",
temperature ?? null,
],
);
}
export interface ConversationRecord {
id: string;
app_id: string;
title: string;
system_prompt: string | null;
model: string;
temperature: number | null;
created_at: string;
updated_at: string;
}
export function getConversation(id: string): ConversationRecord | null {
const row = db.prepare("SELECT * FROM conversations WHERE id = ?").get(id) as
| Record<string, unknown>
| undefined;
return row ? (row as unknown as ConversationRecord) : null;
}
export function listConversations(appId: string): {
id: string;
title: string;
created_at: string;
updated_at: string;
}[] {
return db
.prepare(
"SELECT id, title, created_at, updated_at FROM conversations WHERE app_id = ? ORDER BY updated_at DESC",
)
.all(appId) as {
id: string;
title: string;
created_at: string;
updated_at: string;
}[];
}
export function addMessage(
conversationId: string,
role: string,
content: string,
): number {
const id = db
.prepare(
`INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)`,
)
.run(conversationId, role, content);
db.exec(
`UPDATE conversations SET updated_at = datetime('now') WHERE id = ?`,
[conversationId],
);
return id;
}
export function getMessages(conversationId: string): {
id: number;
role: string;
content: string;
created_at: string;
}[] {
return db
.prepare(
"SELECT id, role, content, created_at FROM messages WHERE conversation_id = ? ORDER BY id ASC",
)
.all(conversationId) as {
id: number;
role: string;
content: string;
created_at: string;
}[];
}
export function updateConversationTitle(id: string, title: string): void {
db.exec(
`UPDATE conversations SET title = ?, updated_at = datetime('now') WHERE id = ?`,
[title, id],
);
}
export function deleteConversation(id: string): void {
db.exec(`DELETE FROM messages WHERE conversation_id = ?`, [id]);
db.exec(`DELETE FROM conversations WHERE id = ?`, [id]);
}
export interface ColumnDef {
name: string;
type: "TEXT" | "INTEGER" | "REAL" | "BOOLEAN";
nullable?: boolean;
default?: string | number | null;
}
export interface TableDef {
name: string;
columns: ColumnDef[];
}
function sqlType(colType: string): string {
switch (colType.toUpperCase()) {
case "TEXT":
return "TEXT";
case "INTEGER":
return "INTEGER";
case "REAL":
return "REAL";
case "BOOLEAN":
return "INTEGER";
default:
return "TEXT";
}
}
function fullTableName(appId: string, tableName: string): string {
const shortId = appId.replace(/-/g, "");
return `app_${shortId}_${tableName}`;
}
export function createAppTables(appId: string, tables: TableDef[]): void {
for (const table of tables) {
const ftn = fullTableName(appId, table.name);
const colDefs = table.columns.map((col) => {
let def = `"${col.name}" ${sqlType(col.type)}`;
// Don't enforce NOT NULL — generated HTML may omit fields
if (col.default !== undefined && col.default !== null) {
def += ` DEFAULT ${typeof col.default === "string" ? `'${col.default}'` : col.default}`;
}
return def;
});
db.exec(`
CREATE TABLE IF NOT EXISTS "${ftn}" (
id INTEGER PRIMARY KEY AUTOINCREMENT,
${colDefs.join(",\n ")}
)
`);
// Save schema metadata
db.exec(
`INSERT OR REPLACE INTO app_schemas (app_id, table_name, columns) VALUES (?, ?, ?)`,
[appId, table.name, JSON.stringify(table.columns)],
);
}
}
export function getAppSchema(
appId: string,
tableName: string,
): ColumnDef[] | null {
const row = db
.prepare(
"SELECT columns FROM app_schemas WHERE app_id = ? AND table_name = ?",
)
.get(appId, tableName) as { columns: string } | undefined;
return row ? JSON.parse(row.columns) : null;
}
export function getAllAppSchemas(
appId: string,
): { tableName: string; columns: ColumnDef[] }[] {
const rows = db
.prepare("SELECT table_name, columns FROM app_schemas WHERE app_id = ?")
.all(appId) as { table_name: string; columns: string }[];
return rows.map((r) => ({
tableName: r.table_name,
columns: JSON.parse(r.columns),
}));
}
export function validateRowData(
columns: ColumnDef[],
data: Record<string, unknown>,
): { valid: boolean; errors: string[] } {
const errors: string[] = [];
// Only type-check fields that are present — let SQLite enforce NOT NULL constraints
for (const col of columns) {
const val = data[col.name];
if (val === undefined || val === null) continue;
switch (col.type.toUpperCase()) {
case "INTEGER":
case "BOOLEAN":
if (typeof val !== "number" && typeof val !== "boolean") {
errors.push(`${col.name} must be a number`);
}
break;
case "REAL":
if (typeof val !== "number") {
errors.push(`${col.name} must be a number`);
}
break;
case "TEXT":
// Coerce numbers/booleans to string silently rather than rejecting
break;
}
}
return { valid: errors.length === 0, errors };
}
export function insertRow(ftn: string, data: Record<string, unknown>): number {
const keys = Object.keys(data);
const placeholders = keys.map(() => "?").join(", ");
const values = keys.map((k) => data[k]) as (
| string
| number
| boolean
| null
)[];
const result = db
.prepare(
`INSERT INTO "${ftn}" (${keys.map((k) => `"${k}"`).join(", ")}) VALUES (${placeholders})`,
)
.run(...values);
return result;
}
export function getRows(
ftn: string,
limit = 100,
offset = 0,
): Record<string, unknown>[] {
return db
.prepare(`SELECT * FROM "${ftn}" LIMIT ? OFFSET ?`)
.all(limit, offset) as Record<string, unknown>[];
}
export function getRow(
ftn: string,
id: number,
): Record<string, unknown> | null {
const row = db.prepare(`SELECT * FROM "${ftn}" WHERE id = ?`).get(id) as
| Record<string, unknown>
| undefined;
return row ?? null;
}
export function updateRow(
ftn: string,
id: number,
data: Record<string, unknown>,
): boolean {
const keys = Object.keys(data);
if (keys.length === 0) return false;
const setClauses = keys.map((k) => `"${k}" = ?`).join(", ");
const values = keys.map((k) => data[k]) as (
| string
| number
| boolean
| null
)[];
db.prepare(`UPDATE "${ftn}" SET ${setClauses} WHERE id = ?`).run(
...values,
id,
);
return true;
}
export function deleteRow(ftn: string, id: number): boolean {
db.prepare(`DELETE FROM "${ftn}" WHERE id = ?`).run(id);
return true;
}
export function getFullTableName(appId: string, tableName: string): string {
return fullTableName(appId, tableName);
}
// App record helpers
export function saveApp(
id: string,
issueUrl: string,
title: string,
html: string,
description?: string,
prd?: string,
erd?: string,
): void {
// Use upsert: if a placeholder row exists (from async creation), update it; otherwise insert
const existing = db.prepare("SELECT id FROM apps WHERE id = ?").get(id);
if (existing) {
db.exec(
`UPDATE apps SET github_issue_url = ?, title = ?, html = ?, description = ?, prd = ?, erd = ?, build_status = 'ready', updated_at = datetime('now') WHERE id = ?`,
[issueUrl, title, html, description ?? "", prd ?? "", erd ?? "", id],
);
} else {
db.exec(
`INSERT INTO apps (id, github_issue_url, title, html, description, prd, erd, build_status) VALUES (?, ?, ?, ?, ?, ?, ?, 'ready')`,
[id, issueUrl, title, html, description ?? "", prd ?? "", erd ?? ""],
);
}
}
export function createAppPlaceholder(
id: string,
title: string,
description: string,
): void {
db.exec(
`INSERT INTO apps (id, github_issue_url, title, html, description, build_status) VALUES (?, ?, ?, ?, ?, ?)`,
[id, "manual-input", title, "", description, "building_prd"],
);
}
export function updateAppBuildStatus(
appId: string,
status: "building_prd" | "building_erd" | "building_app" | "ready" | "failed",
failureReason?: string,
): void {
db.exec(
`UPDATE apps SET build_status = ?, failure_reason = ?, updated_at = datetime('now') WHERE id = ?`,
[status, failureReason ?? "", appId],
);
}
export function getAppBuildStatus(appId: string): {
id: string;
title: string;
build_status: string;
failure_reason: string;
has_prd: boolean;
has_erd: boolean;
} | null {
const row = db
.prepare("SELECT id, title, build_status, failure_reason, prd, erd FROM apps WHERE id = ?")
.get(appId) as { id: string; title: string; build_status: string; failure_reason: string; prd: string; erd: string } | undefined;
if (!row) return null;
return {
id: row.id,
title: row.title,
build_status: row.build_status,
failure_reason: row.failure_reason,
has_prd: Boolean(row.prd),
has_erd: Boolean(row.erd),
};
}
export function getApp(id: string): {
id: string;
github_issue_url: string;
title: string;
html: string;
description: string;
prd: string;
erd: string;
poc_plan: string;
created_at: string;
updated_at: string;
} | null {
const row = db.prepare("SELECT * FROM apps WHERE id = ?").get(id) as
| Record<string, string>
| undefined;
return row
? (row as {
id: string;
github_issue_url: string;
title: string;
html: string;
description: string;
prd: string;
erd: string;
poc_plan: string;
created_at: string;
updated_at: string;
})
: null;
}
export function listApps(): {
id: string;
title: string;
github_issue_url: string;
created_at: string;
}[] {
return db
.prepare(
"SELECT id, title, github_issue_url, created_at FROM apps ORDER BY created_at DESC",
)
.all() as {
id: string;
title: string;
github_issue_url: string;
created_at: string;
}[];
}
export function updateAppTitle(appId: string, title: string): void {
db.exec(
`UPDATE apps SET title = ?, updated_at = datetime('now') WHERE id = ?`,
[title, appId],
);
}
export function updateAppHtml(appId: string, html: string): void {
db.exec(
`UPDATE apps SET html = ?, updated_at = datetime('now') WHERE id = ?`,
[html, appId],
);
}
export function updateAppPrd(appId: string, prd: string): void {
db.exec(
`UPDATE apps SET prd = ?, updated_at = datetime('now') WHERE id = ?`,
[prd, appId],
);
}
export function updateAppErd(appId: string, erd: string): void {
db.exec(
`UPDATE apps SET erd = ?, updated_at = datetime('now') WHERE id = ?`,
[erd, appId],
);
}
export function updateAppPocPlan(appId: string, pocPlan: string): void {
db.exec(
`UPDATE apps SET poc_plan = ?, updated_at = datetime('now') WHERE id = ?`,
[pocPlan, appId],
);
}
export function addColumnToTable(
appId: string,
tableName: string,
col: ColumnDef,
): void {
const ftn = fullTableName(appId, tableName);
const defaultClause =
col.default !== undefined && col.default !== null
? ` DEFAULT ${typeof col.default === "string" ? `'${col.default}'` : col.default}`
: "";
try {
db.exec(
`ALTER TABLE "${ftn}" ADD COLUMN "${col.name}" ${sqlType(col.type)}${defaultClause}`,
);
} catch {
// Column already exists — ignore
return;
}
// Update schema metadata
const existing = getAppSchema(appId, tableName) ?? [];
existing.push(col);
db.exec(
`UPDATE app_schemas SET columns = ? WHERE app_id = ? AND table_name = ?`,
[JSON.stringify(existing), appId, tableName],
);
}
// === Edit Requests ===
export function saveEditRequest(
appId: string,
username: string,
description: string,
): void {
db.exec(
`INSERT INTO edit_requests (app_id, username, description) VALUES (?, ?, ?)`,
[appId, username, description],
);
}
export function listEditRequests(appId: string): {
id: number;
app_id: string;
username: string;
description: string;
created_at: string;
}[] {
return db
.prepare(
"SELECT * FROM edit_requests WHERE app_id = ? ORDER BY created_at DESC",
)
.all(appId) as {
id: number;
app_id: string;
username: string;
description: string;
created_at: string;
}[];
}
export function deleteEditRequest(id: number): void {
db.exec(`DELETE FROM edit_requests WHERE id = ?`, [id]);
}
// === UX Lessons ===
export function saveUxLesson(
lesson: string,
sourceAppId?: string,
sourceEditDescription?: string,
): void {
db.exec(
`INSERT INTO ux_lessons (lesson, source_app_id, source_edit_description) VALUES (?, ?, ?)`,
[lesson, sourceAppId ?? null, sourceEditDescription ?? null],
);
}
export function listUxLessons(): {
id: number;
lesson: string;
source_app_id: string | null;
source_edit_description: string | null;
created_at: string;
}[] {
return db
.prepare("SELECT * FROM ux_lessons ORDER BY created_at ASC")
.all() as {
id: number;
lesson: string;
source_app_id: string | null;
source_edit_description: string | null;
created_at: string;
}[];
}
export function listUxLessonsForApp(appId: string): {
id: number;
lesson: string;
source_app_id: string | null;
source_edit_description: string | null;
created_at: string;
}[] {
return db
.prepare("SELECT * FROM ux_lessons WHERE source_app_id = ? ORDER BY created_at ASC")
.all(appId) as {
id: number;
lesson: string;
source_app_id: string | null;
source_edit_description: string | null;
created_at: string;
}[];
}
export function deleteUxLesson(id: number): void {
db.exec(`DELETE FROM ux_lessons WHERE id = ?`, [id]);
}
export function listAllEditRequests(): {
id: number;
app_id: string;
username: string;
description: string;
created_at: string;
}[] {
return db
.prepare("SELECT * FROM edit_requests ORDER BY created_at DESC")
.all() as {
id: number;
app_id: string;
username: string;
description: string;
created_at: string;
}[];
}
// === Agent CRUD ===
export interface AgentRecord {
id: string;
app_id: string;
name: string;
static_prompt: string;