@zaaxch/grasp-cli 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,1376 @@
1
+ export const AGENTS_PRODUCT_NOTES_SENTINEL = '<!-- GRASP:PRODUCT_NOTES -->';
2
+ export const GITIGNORE_PRODUCT_SENTINEL = '# GRASP:PRODUCT_IGNORES';
3
+ function extractLockedBySentinel(content, sentinel) {
4
+ const idx = content.indexOf(sentinel);
5
+ if (idx === -1)
6
+ return content;
7
+ return content.slice(0, idx + sentinel.length) + '\n';
8
+ }
9
+ function mergeWithSentinel(lockedTemplate, existingContent, sentinel, placeholderComment) {
10
+ const lockedPart = extractLockedBySentinel(lockedTemplate, sentinel);
11
+ if (!existingContent) {
12
+ return `${lockedPart}\n${placeholderComment}\n`;
13
+ }
14
+ const idx = existingContent.indexOf(sentinel);
15
+ if (idx === -1) {
16
+ return `${lockedPart}\n${placeholderComment}\n`;
17
+ }
18
+ const suffix = existingContent.slice(idx + sentinel.length);
19
+ return `${lockedPart.replace(/\n$/, '')}${suffix}`;
20
+ }
21
+ export function extractLockedAgentsSection(content) {
22
+ return extractLockedBySentinel(content, AGENTS_PRODUCT_NOTES_SENTINEL);
23
+ }
24
+ export function mergeAgentsWithProductNotes(lockedTemplate, existingContent) {
25
+ return mergeWithSentinel(lockedTemplate, existingContent, AGENTS_PRODUCT_NOTES_SENTINEL, '<!-- Add app-specific product notes below this line. Content above the sentinel is byte-locked by `grasp sync`. -->');
26
+ }
27
+ export function extractLockedGitignoreSection(content) {
28
+ return extractLockedBySentinel(content, GITIGNORE_PRODUCT_SENTINEL);
29
+ }
30
+ export function mergeGitignoreWithProductRules(lockedTemplate, existingContent) {
31
+ return mergeWithSentinel(lockedTemplate, existingContent, GITIGNORE_PRODUCT_SENTINEL, '# Add app-specific ignore patterns below this line. Content above the sentinel is byte-locked by `grasp sync`.');
32
+ }
33
+ function renderDbImport(config) {
34
+ return config.database === 'mongo'
35
+ ? `import { createMongoStore } from '@zaaxch/grasp-mongo'`
36
+ : `import { createPostgresStore } from '@zaaxch/grasp-postgres'`;
37
+ }
38
+ function renderDbConnect(config, options = {}) {
39
+ if (config.database === 'mongo') {
40
+ return ` const mongoUri =
41
+ process.env['MONGODB_URI'] ?? 'mongodb://127.0.0.1:27017/?replicaSet=rs0&directConnection=true'
42
+ const mongoDbName = process.env['MONGODB_DB_NAME'] ?? config.app.name.replace(/-/g, '_')
43
+ const db = await createMongoStore({
44
+ uri: mongoUri,
45
+ dbName: mongoDbName,
46
+ collections: registeredCollections,
47
+ })`;
48
+ }
49
+ if (options.schemaMode) {
50
+ return ` const postgresUrl =
51
+ process.env['DATABASE_SCHEMA_URL'] ??
52
+ process.env['DATABASE_URL'] ??
53
+ 'postgresql://grasp:grasp@127.0.0.1:5432/grasp'
54
+ const appUser = process.env['POSTGRES_APP_USER']?.trim()
55
+ const db = await createPostgresStore({
56
+ connectionString: postgresUrl,
57
+ tables: registeredTables,
58
+ ...(appUser ? { appUser } : {}),
59
+ })`;
60
+ }
61
+ return ` const postgresUrl = process.env['DATABASE_URL'] ?? 'postgresql://grasp:grasp@127.0.0.1:5432/grasp'
62
+ const db = await createPostgresStore({ connectionString: postgresUrl, tables: registeredTables })`;
63
+ }
64
+ function renderServerMainTs(config) {
65
+ const isMongo = config.database === 'mongo';
66
+ const dbImport = renderDbImport(config);
67
+ const dbConnect = renderDbConnect(config);
68
+ return `import { existsSync } from 'node:fs'
69
+ import { dirname, resolve } from 'node:path'
70
+ import { fileURLToPath } from 'node:url'
71
+ import {
72
+ createBillingService,
73
+ createCompositeAuthVerifier,
74
+ createDevAuthManager,
75
+ createEmailAdapter,
76
+ createFirebaseAuthVerifier,
77
+ createGraspLogger,
78
+ createGraspServer,
79
+ createStripeProvider,
80
+ connectGraspRedis,
81
+ } from '@zaaxch/grasp-server'
82
+ ${dbImport}
83
+ import config from '../../grasp.config.js'
84
+ import { appContract } from '../contracts/index.js'
85
+ import { serverFeatures, ${isMongo ? 'registeredCollections' : 'registeredTables'} } from './features/index.js'
86
+
87
+ const logger = createGraspLogger({
88
+ appName: config.app.name,
89
+ level: (process.env['LOG_LEVEL'] as 'info' | 'debug' | 'warn' | 'error' | undefined) ?? 'info',
90
+ })
91
+
92
+ async function start(): Promise<void> {
93
+ ${dbConnect}
94
+ const redis = await connectGraspRedis({
95
+ url: process.env['REDIS_URL'] ?? 'redis://127.0.0.1:6379',
96
+ })
97
+ const email = createEmailAdapter({ config, env: process.env, logger })
98
+
99
+ const devAuth =
100
+ config.auth.enabled &&
101
+ process.env['NODE_ENV'] !== 'production' &&
102
+ process.env['GRASP_DEV_AUTH'] === 'true'
103
+ ? createDevAuthManager(
104
+ process.env['GRASP_DEV_AUTH_SECRET']
105
+ ? { secret: process.env['GRASP_DEV_AUTH_SECRET'] }
106
+ : {},
107
+ )
108
+ : undefined
109
+
110
+ const firebase =
111
+ config.auth.enabled &&
112
+ (process.env['FIREBASE_PROJECT_ID'] || process.env['GOOGLE_APPLICATION_CREDENTIALS'])
113
+ ? createFirebaseAuthVerifier({
114
+ ...(process.env['FIREBASE_PROJECT_ID']
115
+ ? { projectId: process.env['FIREBASE_PROJECT_ID'] }
116
+ : {}),
117
+ ...(process.env['GOOGLE_APPLICATION_CREDENTIALS']
118
+ ? { serviceAccountPath: process.env['GOOGLE_APPLICATION_CREDENTIALS'] }
119
+ : {}),
120
+ })
121
+ : undefined
122
+
123
+ const auth = createCompositeAuthVerifier({
124
+ ...(firebase !== undefined ? { firebase } : {}),
125
+ ...(devAuth !== undefined ? { devAuth } : {}),
126
+ })
127
+
128
+ const stripeSecret = process.env['STRIPE_SECRET_KEY']?.trim()
129
+ const stripeWebhookSecret = process.env['STRIPE_WEBHOOK_SECRET']?.trim()
130
+ const provider =
131
+ stripeSecret && stripeWebhookSecret
132
+ ? createStripeProvider({ secretKey: stripeSecret, webhookSecret: stripeWebhookSecret })
133
+ : undefined
134
+
135
+ const billing = createBillingService({
136
+ config,
137
+ store: db,
138
+ ...(provider !== undefined ? { provider } : {}),
139
+ env: process.env,
140
+ ...(process.env['APP_BASE_URL'] ? { baseUrl: process.env['APP_BASE_URL'] } : {}),
141
+ })
142
+
143
+ const __dirname = dirname(fileURLToPath(import.meta.url))
144
+ const compiledPublicDir = resolve(__dirname, '..', '..', 'public')
145
+ const publicDir = existsSync(compiledPublicDir)
146
+ ? compiledPublicDir
147
+ : resolve(__dirname, '..', '..', 'dist', 'public')
148
+
149
+ const server = createGraspServer({
150
+ config,
151
+ appContract,
152
+ features: serverFeatures,
153
+ store: db,
154
+ db,
155
+ redis,
156
+ auth,
157
+ ...(devAuth !== undefined ? { devAuth } : {}),
158
+ billing,
159
+ email,
160
+ logger,
161
+ env: process.env,
162
+ publicDir,
163
+ trustProxy: process.env['NODE_ENV'] === 'production' ? 1 : false,
164
+ })
165
+
166
+ const port = Number(process.env['PORT'] ?? 3000)
167
+ await server.listen(port, '0.0.0.0')
168
+ logger.info('Grasp API server listening', { port, database: config.database })
169
+
170
+ let shuttingDown = false
171
+ const shutdown = async (signal: string): Promise<void> => {
172
+ if (shuttingDown) return
173
+ shuttingDown = true
174
+ logger.info('Shutting down Grasp API server', { signal })
175
+ await server.close()
176
+ await redis.close()
177
+ await db.close()
178
+ }
179
+
180
+ process.once('SIGINT', () => {
181
+ void shutdown('SIGINT')
182
+ })
183
+ process.once('SIGTERM', () => {
184
+ void shutdown('SIGTERM')
185
+ })
186
+ }
187
+
188
+ void start().catch((err) => {
189
+ logger.error('Fatal server startup error', { error: err })
190
+ process.exitCode = 1
191
+ })
192
+ `;
193
+ }
194
+ function renderServerWorkerTs(config) {
195
+ const isMongo = config.database === 'mongo';
196
+ const dbImport = renderDbImport(config);
197
+ const dbConnect = renderDbConnect(config);
198
+ return `import {
199
+ connectGraspRedis,
200
+ createEmailAdapter,
201
+ createGraspLogger,
202
+ createGraspWorker,
203
+ } from '@zaaxch/grasp-server'
204
+ ${dbImport}
205
+ import config from '../../grasp.config.js'
206
+ import { serverFeatures, ${isMongo ? 'registeredCollections' : 'registeredTables'} } from './features/index.js'
207
+
208
+ const logger = createGraspLogger({
209
+ appName: \`\${config.app.name}-worker\`,
210
+ level: (process.env['LOG_LEVEL'] as 'info' | 'debug' | 'warn' | 'error' | undefined) ?? 'info',
211
+ })
212
+
213
+ async function start(): Promise<void> {
214
+ ${dbConnect}
215
+ const redis = await connectGraspRedis({
216
+ url: process.env['REDIS_URL'] ?? 'redis://127.0.0.1:6379',
217
+ })
218
+ const email = createEmailAdapter({ config, env: process.env, logger })
219
+
220
+ const worker = createGraspWorker({
221
+ store: db,
222
+ db,
223
+ redis,
224
+ email,
225
+ logger,
226
+ features: serverFeatures,
227
+ })
228
+
229
+ await worker.start()
230
+ logger.info('Grasp worker started', { workerId: worker.workerId })
231
+
232
+ let shuttingDown = false
233
+ const shutdown = async (signal: string): Promise<void> => {
234
+ if (shuttingDown) return
235
+ shuttingDown = true
236
+ logger.info('Stopping Grasp worker', { signal })
237
+ await worker.stop()
238
+ await redis.close()
239
+ await db.close()
240
+ }
241
+
242
+ process.once('SIGINT', () => {
243
+ void shutdown('SIGINT')
244
+ })
245
+ process.once('SIGTERM', () => {
246
+ void shutdown('SIGTERM')
247
+ })
248
+ }
249
+
250
+ void start().catch((err) => {
251
+ logger.error('Fatal worker startup error', { error: err })
252
+ process.exitCode = 1
253
+ })
254
+ `;
255
+ }
256
+ function renderServerSchemaTs(config) {
257
+ const isMongo = config.database === 'mongo';
258
+ const dbImport = renderDbImport(config);
259
+ const dbConnect = renderDbConnect(config, { schemaMode: true });
260
+ return `${dbImport}
261
+ import config from '../../grasp.config.js'
262
+ import { ${isMongo ? 'registeredCollections' : 'registeredTables'} } from './features/index.js'
263
+
264
+ async function apply(): Promise<void> {
265
+ ${dbConnect}
266
+ try {
267
+ const result = await db.applySchema()
268
+ console.log(JSON.stringify({ ok: true, applied: result.applied }))
269
+ } finally {
270
+ await db.close()
271
+ }
272
+ }
273
+
274
+ void apply().catch((err) => {
275
+ console.error(err)
276
+ process.exitCode = 1
277
+ })
278
+ `;
279
+ }
280
+ function renderServerOpsTs(config) {
281
+ const isMongo = config.database === 'mongo';
282
+ const dbImport = renderDbImport(config);
283
+ const dbConnect = renderDbConnect(config);
284
+ return `import {
285
+ createBillingService,
286
+ createDevAuthManager,
287
+ createStripeProvider,
288
+ runGraspOpsCli,
289
+ } from '@zaaxch/grasp-server'
290
+ ${dbImport}
291
+ import config from '../../grasp.config.js'
292
+ import { serverFeatures, ${isMongo ? 'registeredCollections' : 'registeredTables'} } from './features/index.js'
293
+
294
+ async function main(): Promise<void> {
295
+ ${dbConnect}
296
+ try {
297
+ const stripeSecret = process.env['STRIPE_SECRET_KEY']?.trim()
298
+ const stripeWebhookSecret = process.env['STRIPE_WEBHOOK_SECRET']?.trim()
299
+ const provider =
300
+ stripeSecret && stripeWebhookSecret
301
+ ? createStripeProvider({ secretKey: stripeSecret, webhookSecret: stripeWebhookSecret })
302
+ : undefined
303
+ const billing = createBillingService({
304
+ config,
305
+ store: db,
306
+ ...(provider !== undefined ? { provider } : {}),
307
+ env: process.env,
308
+ })
309
+ const devAuth =
310
+ config.auth.enabled &&
311
+ process.env['NODE_ENV'] !== 'production' &&
312
+ process.env['GRASP_DEV_AUTH'] === 'true'
313
+ ? createDevAuthManager(
314
+ process.env['GRASP_DEV_AUTH_SECRET']
315
+ ? { secret: process.env['GRASP_DEV_AUTH_SECRET'] }
316
+ : {},
317
+ )
318
+ : undefined
319
+
320
+ const res = await runGraspOpsCli(process.argv.slice(2), {
321
+ config,
322
+ store: db,
323
+ db,
324
+ billing,
325
+ features: serverFeatures,
326
+ env: process.env,
327
+ ...(devAuth !== undefined ? { devAuth } : {}),
328
+ })
329
+ console.log(res.output)
330
+ process.exitCode = res.exitCode
331
+ } finally {
332
+ await db.close()
333
+ }
334
+ }
335
+
336
+ void main().catch((err) => {
337
+ console.error(err instanceof Error ? err.message : String(err))
338
+ process.exitCode = 1
339
+ })
340
+ `;
341
+ }
342
+ function renderServerMcpTs(config) {
343
+ const isMongo = config.database === 'mongo';
344
+ const dbImport = renderDbImport(config);
345
+ const dbConnect = renderDbConnect(config);
346
+ return `import {
347
+ connectGraspRedis,
348
+ createEmailAdapter,
349
+ createGraspLogger,
350
+ createGraspMcpServer,
351
+ } from '@zaaxch/grasp-server'
352
+ ${dbImport}
353
+ import config from '../../grasp.config.js'
354
+ import { serverFeatures, ${isMongo ? 'registeredCollections' : 'registeredTables'} } from './features/index.js'
355
+
356
+ const logger = createGraspLogger({
357
+ appName: \`\${config.app.name}-mcp\`,
358
+ level: (process.env['LOG_LEVEL'] as 'info' | 'debug' | 'warn' | 'error' | undefined) ?? 'info',
359
+ })
360
+
361
+ async function start(): Promise<void> {
362
+ ${dbConnect}
363
+ const redis = await connectGraspRedis({
364
+ url: process.env['REDIS_URL'] ?? 'redis://127.0.0.1:6379',
365
+ })
366
+ const email = createEmailAdapter({ config, env: process.env, logger })
367
+
368
+ const allowedHosts = (process.env['MCP_ALLOWED_HOSTS'] ?? 'localhost,127.0.0.1')
369
+ .split(',')
370
+ .map((host) => host.trim())
371
+ .filter(Boolean)
372
+ const bearerToken = process.env['MCP_BEARER_TOKEN']?.trim()
373
+
374
+ const mcp = createGraspMcpServer({
375
+ config,
376
+ features: serverFeatures,
377
+ store: db,
378
+ db,
379
+ redis,
380
+ email,
381
+ logger,
382
+ allowedHosts,
383
+ ...(bearerToken ? { bearerToken } : {}),
384
+ })
385
+
386
+ const port = Number(process.env['MCP_PORT'] ?? 3001)
387
+ const host = process.env['MCP_HOST']?.trim() || '127.0.0.1'
388
+ await mcp.listen(port, host)
389
+ logger.info('Grasp MCP server listening', { port, host, database: config.database })
390
+
391
+ let shuttingDown = false
392
+ const shutdown = async (signal: string): Promise<void> => {
393
+ if (shuttingDown) return
394
+ shuttingDown = true
395
+ logger.info('Stopping Grasp MCP server', { signal })
396
+ await mcp.close()
397
+ await redis.close()
398
+ await db.close()
399
+ }
400
+
401
+ process.once('SIGINT', () => {
402
+ void shutdown('SIGINT')
403
+ })
404
+ process.once('SIGTERM', () => {
405
+ void shutdown('SIGTERM')
406
+ })
407
+ }
408
+
409
+ void start().catch((err) => {
410
+ logger.error('Fatal MCP server startup error', { error: err })
411
+ process.exitCode = 1
412
+ })
413
+ `;
414
+ }
415
+ function renderWebMainTs(config) {
416
+ const customLayoutImport = config.ui.layout === 'custom' ? `import AppLayout from './AppLayout.vue'\n` : '';
417
+ const layoutOption = config.ui.layout === 'custom' ? ` layoutComponent: AppLayout,\n` : '';
418
+ return `import './styles.css'
419
+ import { createGraspVueApp } from '@zaaxch/grasp-vue'
420
+ import config from '../../grasp.config.js'
421
+ import { appContract } from '../contracts/index.js'
422
+ ${customLayoutImport}import LandingPage from './LandingPage.vue'
423
+ import { featureNavItems, featureRoutes } from './features/index.js'
424
+ import { appTheme } from './theme.js'
425
+
426
+ const firebaseApiKey = import.meta.env['VITE_FIREBASE_API_KEY']
427
+ const firebaseProjectId = import.meta.env['VITE_FIREBASE_PROJECT_ID']
428
+
429
+ const app = createGraspVueApp({
430
+ config,
431
+ contract: appContract,
432
+ landingComponent: LandingPage,
433
+ featureRoutes,
434
+ navItems: featureNavItems,
435
+ ${layoutOption} theme: appTheme,
436
+ authenticatedHome: featureNavItems[0]?.to ?? '/settings',
437
+ ...(firebaseApiKey && firebaseProjectId
438
+ ? {
439
+ firebaseConfig: {
440
+ apiKey: firebaseApiKey,
441
+ projectId: firebaseProjectId,
442
+ ...(import.meta.env['VITE_FIREBASE_AUTH_DOMAIN']
443
+ ? { authDomain: import.meta.env['VITE_FIREBASE_AUTH_DOMAIN'] }
444
+ : {}),
445
+ ...(import.meta.env['VITE_FIREBASE_APP_ID']
446
+ ? { appId: import.meta.env['VITE_FIREBASE_APP_ID'] }
447
+ : {}),
448
+ },
449
+ }
450
+ : {}),
451
+ })
452
+
453
+ app.mount('#app')
454
+ `;
455
+ }
456
+ function renderDockerComposeDev(config) {
457
+ const dbService = config.database === 'mongo'
458
+ ? ` db:
459
+ image: mongo:8
460
+ command: ['--replSet', 'rs0', '--bind_ip_all', '--quiet']
461
+ volumes:
462
+ - grasp_dev_db:/data/db
463
+ healthcheck:
464
+ test:
465
+ [
466
+ 'CMD',
467
+ 'mongosh',
468
+ '--quiet',
469
+ '--eval',
470
+ "try { if (!rs.status().ok) throw 1; } catch (e) { rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'db:27017'}]}); } if (!db.hello().isWritablePrimary) quit(1);",
471
+ ]
472
+ interval: 2s
473
+ timeout: 5s
474
+ retries: 25`
475
+ : ` db:
476
+ image: postgres:17-alpine
477
+ environment:
478
+ POSTGRES_USER: grasp
479
+ POSTGRES_PASSWORD: grasp_dev_password
480
+ POSTGRES_DB: ${config.app.name.replace(/-/g, '_')}
481
+ volumes:
482
+ - grasp_dev_db:/var/lib/postgresql/data
483
+ healthcheck:
484
+ test: ['CMD-SHELL', 'pg_isready -U grasp -d ${config.app.name.replace(/-/g, '_')}']
485
+ interval: 2s
486
+ timeout: 5s
487
+ retries: 25`;
488
+ const dbEnv = config.database === 'mongo'
489
+ ? ` MONGODB_URI: mongodb://db:27017/?replicaSet=rs0&directConnection=true
490
+ MONGODB_DB_NAME: ${config.app.name.replace(/-/g, '_')}`
491
+ : ` DATABASE_URL: postgresql://grasp:grasp_dev_password@db:5432/${config.app.name.replace(/-/g, '_')}`;
492
+ const workerService = config.worker.enabled
493
+ ? `
494
+ worker:
495
+ build:
496
+ context: .
497
+ dockerfile: Dockerfile.dev
498
+ command: pnpm dev:worker
499
+ depends_on:
500
+ schema-init:
501
+ condition: service_completed_successfully
502
+ redis:
503
+ condition: service_healthy
504
+ volumes:
505
+ - .:/app
506
+ - grasp_dev_node_modules:/app/node_modules
507
+ environment:
508
+ NODE_ENV: development
509
+ ${dbEnv}
510
+ REDIS_URL: redis://redis:6379
511
+ GRASP_CAPTURE_EMAILS: 'true'`
512
+ : '';
513
+ const mcpService = config.mcp.enabled
514
+ ? `
515
+ mcp:
516
+ build:
517
+ context: .
518
+ dockerfile: Dockerfile.dev
519
+ command: pnpm dev:mcp
520
+ depends_on:
521
+ schema-init:
522
+ condition: service_completed_successfully
523
+ redis:
524
+ condition: service_healthy
525
+ ports:
526
+ - '127.0.0.1:3001:3001'
527
+ volumes:
528
+ - .:/app
529
+ - grasp_dev_node_modules:/app/node_modules
530
+ environment:
531
+ NODE_ENV: development
532
+ MCP_PORT: '3001'
533
+ MCP_HOST: 0.0.0.0
534
+ MCP_ALLOWED_HOSTS: localhost,127.0.0.1,mcp
535
+ MCP_BEARER_TOKEN: \${MCP_BEARER_TOKEN:-grasp-dev-mcp-token}
536
+ ${dbEnv}
537
+ REDIS_URL: redis://redis:6379
538
+ GRASP_CAPTURE_EMAILS: 'true'`
539
+ : '';
540
+ return `services:
541
+ ${dbService}
542
+
543
+ redis:
544
+ image: redis:7-alpine
545
+ healthcheck:
546
+ test: ['CMD', 'redis-cli', 'ping']
547
+ interval: 2s
548
+ timeout: 5s
549
+ retries: 20
550
+
551
+ schema-init:
552
+ build:
553
+ context: .
554
+ dockerfile: Dockerfile.dev
555
+ command: pnpm dev:schema
556
+ depends_on:
557
+ db:
558
+ condition: service_healthy
559
+ volumes:
560
+ - .:/app
561
+ - grasp_dev_node_modules:/app/node_modules
562
+ environment:
563
+ ${dbEnv}
564
+
565
+ api:
566
+ build:
567
+ context: .
568
+ dockerfile: Dockerfile.dev
569
+ command: pnpm dev:server
570
+ depends_on:
571
+ schema-init:
572
+ condition: service_completed_successfully
573
+ redis:
574
+ condition: service_healthy
575
+ ports:
576
+ - '127.0.0.1:3000:3000'
577
+ volumes:
578
+ - .:/app
579
+ - grasp_dev_node_modules:/app/node_modules
580
+ environment:
581
+ NODE_ENV: development
582
+ PORT: '3000'
583
+ ${dbEnv}
584
+ REDIS_URL: redis://redis:6379
585
+ GRASP_DEV_AUTH: 'true'
586
+ GRASP_CAPTURE_EMAILS: 'true'${[workerService, mcpService].filter(Boolean).length > 0 ? `\n${[workerService, mcpService].filter(Boolean).join('\n')}` : ''}
587
+
588
+ web:
589
+ build:
590
+ context: .
591
+ dockerfile: Dockerfile.dev
592
+ command: pnpm dev:web
593
+ depends_on:
594
+ - api
595
+ ports:
596
+ - '127.0.0.1:5173:5173'
597
+ volumes:
598
+ - .:/app
599
+ - grasp_dev_node_modules:/app/node_modules
600
+ environment:
601
+ GRASP_API_ORIGIN: http://api:3000
602
+
603
+ volumes:
604
+ grasp_dev_db:
605
+ grasp_dev_node_modules:
606
+ `;
607
+ }
608
+ function renderDockerComposeTest(config) {
609
+ const dbService = config.database === 'mongo'
610
+ ? ` db:
611
+ image: mongo:8
612
+ command: ['--replSet', 'rs0', '--bind_ip_all', '--quiet']
613
+ tmpfs:
614
+ - /data/db
615
+ healthcheck:
616
+ test:
617
+ [
618
+ 'CMD',
619
+ 'mongosh',
620
+ '--quiet',
621
+ '--eval',
622
+ "try { if (!rs.status().ok) throw 1; } catch (e) { rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'db:27017'}]}); } if (!db.hello().isWritablePrimary) quit(1);",
623
+ ]
624
+ interval: 2s
625
+ timeout: 5s
626
+ retries: 25`
627
+ : ` db:
628
+ image: postgres:17-alpine
629
+ environment:
630
+ POSTGRES_USER: grasp
631
+ POSTGRES_PASSWORD: grasp_test_password
632
+ POSTGRES_DB: grasp_test
633
+ tmpfs:
634
+ - /var/lib/postgresql/data
635
+ healthcheck:
636
+ test: ['CMD-SHELL', 'pg_isready -U grasp -d grasp_test']
637
+ interval: 2s
638
+ timeout: 5s
639
+ retries: 25`;
640
+ const dbEnv = config.database === 'mongo'
641
+ ? ` GRASP_TEST_MONGO_URI: mongodb://db:27017/?replicaSet=rs0&directConnection=true`
642
+ : ` GRASP_TEST_POSTGRES_URL: postgresql://grasp:grasp_test_password@db:5432/grasp_test`;
643
+ return `services:
644
+ ${dbService}
645
+
646
+ redis:
647
+ image: redis:7-alpine
648
+ healthcheck:
649
+ test: ['CMD', 'redis-cli', 'ping']
650
+ interval: 2s
651
+ timeout: 5s
652
+ retries: 20
653
+
654
+ test:
655
+ build:
656
+ context: .
657
+ dockerfile: Dockerfile.dev
658
+ command: pnpm test
659
+ depends_on:
660
+ db:
661
+ condition: service_healthy
662
+ redis:
663
+ condition: service_healthy
664
+ volumes:
665
+ - .:/app
666
+ - grasp_test_node_modules:/app/node_modules
667
+ environment:
668
+ NODE_ENV: test
669
+ ${dbEnv}
670
+ GRASP_TEST_REDIS_URL: redis://redis:6379
671
+ GRASP_DEV_AUTH: 'true'
672
+ GRASP_CAPTURE_EMAILS: 'true'
673
+
674
+ volumes:
675
+ grasp_test_node_modules:
676
+ `;
677
+ }
678
+ function renderDockerComposeProd(config) {
679
+ const dbName = config.app.name.replace(/-/g, '_');
680
+ const dbService = config.database === 'mongo'
681
+ ? ` db:
682
+ image: mongo:8
683
+ restart: unless-stopped
684
+ command: ['--replSet', 'rs0', '--bind_ip_all', '--keyFile', '/etc/mongo-keyfile', '--auth']
685
+ environment:
686
+ MONGO_INITDB_ROOT_USERNAME: \${MONGO_ROOT_USER}
687
+ MONGO_INITDB_ROOT_PASSWORD: \${MONGO_ROOT_PASSWORD}
688
+ volumes:
689
+ - \${DATA_DIR}/mongo:/data/db
690
+ - \${SHARED_DIR}/mongo-keyfile:/etc/mongo-keyfile:ro
691
+ healthcheck:
692
+ test: ['CMD', 'mongosh', '--quiet', '--eval', 'db.adminCommand("ping").ok']
693
+ interval: 5s
694
+ timeout: 5s
695
+ retries: 20`
696
+ : ` db:
697
+ image: postgres:17-alpine
698
+ restart: unless-stopped
699
+ environment:
700
+ POSTGRES_USER: \${POSTGRES_ROOT_USER}
701
+ POSTGRES_PASSWORD: \${POSTGRES_ROOT_PASSWORD}
702
+ POSTGRES_DB: ${dbName}
703
+ POSTGRES_APP_USER: \${POSTGRES_APP_USER}
704
+ POSTGRES_APP_PASSWORD: \${POSTGRES_APP_PASSWORD}
705
+ volumes:
706
+ - \${DATA_DIR}/postgres:/var/lib/postgresql/data
707
+ - ./deploy/postgres/10-init-app-user.sh:/docker-entrypoint-initdb.d/10-init-app-user.sh:ro
708
+ healthcheck:
709
+ test: ['CMD-SHELL', 'pg_isready -U \${POSTGRES_ROOT_USER} -d ${dbName}']
710
+ interval: 5s
711
+ timeout: 5s
712
+ retries: 20`;
713
+ const dbEnv = config.database === 'mongo'
714
+ ? ` MONGODB_URI: mongodb://\${MONGO_APP_USER}:\${MONGO_APP_PASSWORD}@db:27017/${dbName}?authSource=${dbName}&replicaSet=rs0&directConnection=true
715
+ MONGODB_DB_NAME: ${dbName}`
716
+ : ` DATABASE_URL: postgresql://\${POSTGRES_APP_USER}:\${POSTGRES_APP_PASSWORD}@db:5432/${dbName}`;
717
+ const schemaDbEnv = config.database === 'mongo'
718
+ ? dbEnv
719
+ : ` DATABASE_SCHEMA_URL: postgresql://\${POSTGRES_ROOT_USER}:\${POSTGRES_ROOT_PASSWORD}@db:5432/${dbName}
720
+ POSTGRES_APP_USER: \${POSTGRES_APP_USER}`;
721
+ const workerService = config.worker.enabled
722
+ ? `
723
+ worker:
724
+ image: \${GHCR_IMAGE}:\${IMAGE_TAG}
725
+ restart: unless-stopped
726
+ command: ['node', 'dist/src/server/worker.js']
727
+ env_file:
728
+ - \${SHARED_DIR}/.env.production
729
+ environment:
730
+ NODE_ENV: production
731
+ ${dbEnv}
732
+ REDIS_URL: redis://:\${REDIS_PASSWORD}@redis:6379
733
+ depends_on:
734
+ schema-init:
735
+ condition: service_completed_successfully
736
+ redis:
737
+ condition: service_healthy`
738
+ : '';
739
+ const mcpService = config.mcp.enabled
740
+ ? `
741
+ mcp:
742
+ image: \${GHCR_IMAGE}:\${IMAGE_TAG}
743
+ restart: unless-stopped
744
+ command: ['node', 'dist/src/server/mcp.js']
745
+ ports:
746
+ - '127.0.0.1:\${MCP_PORT:-3001}:3001'
747
+ env_file:
748
+ - \${SHARED_DIR}/.env.production
749
+ environment:
750
+ NODE_ENV: production
751
+ MCP_PORT: '3001'
752
+ MCP_HOST: 0.0.0.0
753
+ ${dbEnv}
754
+ REDIS_URL: redis://:\${REDIS_PASSWORD}@redis:6379
755
+ healthcheck:
756
+ test:
757
+ [
758
+ 'CMD',
759
+ 'node',
760
+ '-e',
761
+ "fetch('http://127.0.0.1:3001/health').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))",
762
+ ]
763
+ interval: 10s
764
+ timeout: 5s
765
+ retries: 10
766
+ depends_on:
767
+ schema-init:
768
+ condition: service_completed_successfully
769
+ redis:
770
+ condition: service_healthy`
771
+ : '';
772
+ return `services:
773
+ caddy:
774
+ image: caddy:2.11.4-alpine
775
+ restart: unless-stopped
776
+ ports:
777
+ - '80:80'
778
+ - '443:443'
779
+ volumes:
780
+ - ./Caddyfile:/etc/caddy/Caddyfile:ro
781
+ - \${SHARED_DIR}/caddy/data:/data
782
+ - \${SHARED_DIR}/caddy/config:/config
783
+ depends_on:
784
+ api:
785
+ condition: service_healthy
786
+
787
+ ${dbService}
788
+
789
+ redis:
790
+ image: redis:7-alpine
791
+ restart: unless-stopped
792
+ command:
793
+ [
794
+ 'redis-server',
795
+ '--requirepass',
796
+ '\${REDIS_PASSWORD}',
797
+ '--appendonly',
798
+ 'yes',
799
+ '--appendfsync',
800
+ 'everysec',
801
+ '--maxmemory-policy',
802
+ 'noeviction',
803
+ ]
804
+ volumes:
805
+ - \${DATA_DIR}/redis:/data
806
+ healthcheck:
807
+ test: ['CMD', 'redis-cli', '-a', '\${REDIS_PASSWORD}', 'ping']
808
+ interval: 5s
809
+ timeout: 5s
810
+ retries: 20
811
+
812
+ schema-init:
813
+ image: \${GHCR_IMAGE}:\${IMAGE_TAG}
814
+ command: ['node', 'dist/src/server/schema.js']
815
+ env_file:
816
+ - \${SHARED_DIR}/.env.production
817
+ environment:
818
+ NODE_ENV: production
819
+ ${schemaDbEnv}
820
+ depends_on:
821
+ db:
822
+ condition: service_healthy
823
+
824
+ api:
825
+ image: \${GHCR_IMAGE}:\${IMAGE_TAG}
826
+ restart: unless-stopped
827
+ env_file:
828
+ - \${SHARED_DIR}/.env.production
829
+ environment:
830
+ NODE_ENV: production
831
+ PORT: '3000'
832
+ APP_BASE_URL: https://${config.app.domain}
833
+ ${dbEnv}
834
+ REDIS_URL: redis://:\${REDIS_PASSWORD}@redis:6379
835
+ healthcheck:
836
+ test:
837
+ [
838
+ 'CMD',
839
+ 'node',
840
+ '-e',
841
+ "fetch('http://127.0.0.1:3000/api/health').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))",
842
+ ]
843
+ interval: 10s
844
+ timeout: 5s
845
+ retries: 10
846
+ depends_on:
847
+ schema-init:
848
+ condition: service_completed_successfully
849
+ redis:
850
+ condition: service_healthy${[workerService, mcpService].filter(Boolean).length > 0 ? `\n${[workerService, mcpService].filter(Boolean).join('\n')}` : ''}
851
+ `;
852
+ }
853
+ export function generateLockedFiles(config) {
854
+ const domain = config.app.domain === 'localhost' ? ':80' : config.app.domain;
855
+ const dbName = config.app.name.replace(/-/g, '_');
856
+ const agentsMd = `# ${config.app.displayName} — Grasp Architecture Rules
857
+
858
+ This repository uses the **Grasp** immutable runtime shell.
859
+
860
+ ## Non-Negotiable Rules
861
+
862
+ 1. **Never edit byte-locked files** listed in \`grasp.lock.json\` (Docker, Compose, Caddyfile, CI workflows, \`src/server/{main,worker,schema,ops,mcp}.ts\`, \`src/web/main.ts\`, \`tsconfig*.json\`, \`vite.config.ts\`). Preserve \`# GRASP:PRODUCT_IGNORES\` in \`.gitignore\` and put product-specific ignore globs below it.
863
+ 2. **Never import vendor drivers directly** inside \`src/contracts/\`, \`src/server/features/\`, or \`src/web/features/\`:
864
+ - Banned: \`express\`, \`cors\`, \`stripe\`, \`firebase\`, \`firebase-admin\`, \`mongodb\`, \`mongoose\`, \`pg\`, \`postgres\`, \`redis\`, \`ioredis\`, \`axios\`, \`bull\`, \`bullmq\`, \`nodemailer\`, \`winston\`, \`cron-parser\`, \`@modelcontextprotocol/sdk\`.
865
+ - Browser feature code must never call global \`fetch\` or \`new EventSource(...)\`; always use \`useGraspApi()\` / \`useGraspShell()\`.
866
+ 3. **Directory lockdown**:
867
+ - All backend features live in \`src/server/features/<name>/<name>.{repo,procedures,service,jobs,eraser,http,mcp,ops}.ts\`.
868
+ - \`<feature>.repo.ts\` is strictly private to \`<feature>\`; sibling features must import \`<feature>.service.ts\`.
869
+ - \`src/contracts/\` may only import \`zod\` and \`@zaaxch/grasp-core\`.
870
+ 4. **Routing & Auth modes**:
871
+ - Custom public frontend pages can set \`meta: { auth: 'public', layout: 'standalone' }\` (no shell sidebar) or \`meta: { auth: 'public' }\` (shell layout).
872
+ - Apps without end-user accounts can set \`auth: { enabled: false }\` in \`grasp.config.ts\` (no login screen, anonymous public procedures work immediately).
873
+ - Custom HTTP callback/webhook routes belong in \`defineHttpRoute\` (\`<feature>.contract.ts\`) + \`defineHttpRoutes\` (\`<feature>.http.ts\`), never raw Express handlers.
874
+ 5. **Dependency allowlist**: Every external npm dependency must be declared in \`grasp.config.ts -> allowedDependencies\`.
875
+ 6. **Always verify before finishing**: Run \`pnpm check\` (or \`npx grasp check\`), \`pnpm typecheck\`, and \`pnpm test\`.
876
+
877
+ ${AGENTS_PRODUCT_NOTES_SENTINEL}
878
+ `;
879
+ const files = [
880
+ {
881
+ path: '.gitignore',
882
+ content: `node_modules/
883
+ dist/
884
+ coverage/
885
+ *.tsbuildinfo
886
+ .env
887
+ .env.*
888
+ !.env.example
889
+ !.env.*.example
890
+ .DS_Store
891
+
892
+ ${GITIGNORE_PRODUCT_SENTINEL}
893
+ `,
894
+ },
895
+ {
896
+ path: '.gitattributes',
897
+ content: `* text=auto eol=lf
898
+ *.png binary
899
+ *.jpg binary
900
+ *.jpeg binary
901
+ *.gif binary
902
+ *.ico binary
903
+ *.webp binary
904
+ *.pdf binary
905
+ `,
906
+ },
907
+ {
908
+ path: '.prettierrc.json',
909
+ content: `{
910
+ "semi": false,
911
+ "singleQuote": true,
912
+ "trailingComma": "all",
913
+ "printWidth": 100,
914
+ "tabWidth": 2
915
+ }
916
+ `,
917
+ },
918
+ {
919
+ path: '.prettierignore',
920
+ content: `node_modules/
921
+ dist/
922
+ coverage/
923
+ pnpm-lock.yaml
924
+ grasp.lock.json
925
+ `,
926
+ },
927
+ {
928
+ path: 'tsconfig.json',
929
+ content: `{
930
+ "compilerOptions": {
931
+ "target": "ES2023",
932
+ "module": "NodeNext",
933
+ "moduleResolution": "NodeNext",
934
+ "strict": true,
935
+ "noUncheckedIndexedAccess": true,
936
+ "exactOptionalPropertyTypes": true,
937
+ "verbatimModuleSyntax": true,
938
+ "skipLibCheck": true,
939
+ "noEmit": true,
940
+ "types": ["node"]
941
+ },
942
+ "include": ["grasp.config.ts", "src/contracts/**/*.ts", "src/server/**/*.ts"]
943
+ }
944
+ `,
945
+ },
946
+ {
947
+ path: 'tsconfig.server.json',
948
+ content: `{
949
+ "compilerOptions": {
950
+ "target": "ES2023",
951
+ "module": "NodeNext",
952
+ "moduleResolution": "NodeNext",
953
+ "strict": true,
954
+ "noUncheckedIndexedAccess": true,
955
+ "exactOptionalPropertyTypes": true,
956
+ "verbatimModuleSyntax": true,
957
+ "skipLibCheck": true,
958
+ "rootDir": ".",
959
+ "outDir": "dist",
960
+ "types": ["node"]
961
+ },
962
+ "include": ["grasp.config.ts", "src/contracts/**/*.ts", "src/server/**/*.ts"],
963
+ "exclude": ["src/**/__tests__/**"]
964
+ }
965
+ `,
966
+ },
967
+ {
968
+ path: 'tsconfig.web.json',
969
+ content: `{
970
+ "compilerOptions": {
971
+ "target": "ES2023",
972
+ "module": "ESNext",
973
+ "moduleResolution": "Bundler",
974
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
975
+ "strict": true,
976
+ "noUncheckedIndexedAccess": true,
977
+ "exactOptionalPropertyTypes": true,
978
+ "verbatimModuleSyntax": true,
979
+ "skipLibCheck": true,
980
+ "noEmit": true,
981
+ "types": ["vite/client", "node"]
982
+ },
983
+ "include": ["grasp.config.ts", "src/contracts/**/*.ts", "src/web/**/*.ts", "src/web/**/*.vue"]
984
+ }
985
+ `,
986
+ },
987
+ {
988
+ path: 'vitest.config.ts',
989
+ content: `import vue from '@vitejs/plugin-vue'
990
+ import { defineConfig } from 'vitest/config'
991
+
992
+ export default defineConfig({
993
+ plugins: [vue()],
994
+ test: {
995
+ include: ['src/**/__tests__/**/*.test.ts'],
996
+ environment: 'node',
997
+ },
998
+ })
999
+ `,
1000
+ },
1001
+ {
1002
+ path: 'index.html',
1003
+ content: `<!doctype html>
1004
+ <html lang="en">
1005
+ <head>
1006
+ <meta charset="UTF-8" />
1007
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1008
+ <title>${config.app.displayName}</title>
1009
+ </head>
1010
+ <body>
1011
+ <div id="app"></div>
1012
+ <script type="module" src="/src/web/main.ts"></script>
1013
+ </body>
1014
+ </html>
1015
+ `,
1016
+ },
1017
+ {
1018
+ path: 'vite.config.ts',
1019
+ content: `import tailwindcss from '@tailwindcss/vite'
1020
+ import vue from '@vitejs/plugin-vue'
1021
+ import { defineConfig } from 'vite'
1022
+
1023
+ export default defineConfig({
1024
+ plugins: [vue(), tailwindcss()],
1025
+ build: {
1026
+ outDir: 'dist/public',
1027
+ emptyOutDir: true,
1028
+ },
1029
+ server: {
1030
+ host: '0.0.0.0',
1031
+ port: 5173,
1032
+ proxy: {
1033
+ '/api': {
1034
+ target: process.env['GRASP_API_ORIGIN'] ?? 'http://127.0.0.1:3000',
1035
+ changeOrigin: true,
1036
+ },
1037
+ },
1038
+ },
1039
+ })
1040
+ `,
1041
+ },
1042
+ {
1043
+ path: 'src/server/main.ts',
1044
+ content: renderServerMainTs(config),
1045
+ },
1046
+ {
1047
+ path: 'src/server/worker.ts',
1048
+ content: renderServerWorkerTs(config),
1049
+ },
1050
+ {
1051
+ path: 'src/server/schema.ts',
1052
+ content: renderServerSchemaTs(config),
1053
+ },
1054
+ {
1055
+ path: 'src/server/ops.ts',
1056
+ content: renderServerOpsTs(config),
1057
+ },
1058
+ ...(config.mcp.enabled
1059
+ ? [
1060
+ {
1061
+ path: 'src/server/mcp.ts',
1062
+ content: renderServerMcpTs(config),
1063
+ },
1064
+ ]
1065
+ : []),
1066
+ {
1067
+ path: 'src/web/main.ts',
1068
+ content: renderWebMainTs(config),
1069
+ },
1070
+ {
1071
+ path: 'Dockerfile',
1072
+ content: `# syntax=docker/dockerfile:1
1073
+ FROM node:24-alpine AS build
1074
+ WORKDIR /app
1075
+ RUN corepack enable && corepack prepare pnpm@11.22.0 --activate
1076
+ COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
1077
+ RUN pnpm install --frozen-lockfile
1078
+ COPY . .
1079
+ RUN --mount=type=secret,id=ui_env_production,target=/app/.env.production,required=false \\
1080
+ pnpm build
1081
+
1082
+ FROM node:24-alpine AS prod
1083
+ WORKDIR /app
1084
+ ENV NODE_ENV=production
1085
+ RUN corepack enable && corepack prepare pnpm@11.22.0 --activate
1086
+ COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
1087
+ RUN pnpm install --prod --frozen-lockfile
1088
+ COPY --from=build /app/dist ./dist
1089
+ COPY --from=build /app/grasp.config.ts ./grasp.config.ts
1090
+ USER node
1091
+ EXPOSE 3000
1092
+ CMD ["node", "dist/src/server/main.js"]
1093
+ `,
1094
+ },
1095
+ {
1096
+ path: 'Dockerfile.dev',
1097
+ content: `FROM node:24-alpine
1098
+ WORKDIR /app
1099
+ RUN corepack enable && corepack prepare pnpm@11.22.0 --activate
1100
+ COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
1101
+ RUN pnpm install --frozen-lockfile || pnpm install
1102
+ COPY . .
1103
+ `,
1104
+ },
1105
+ {
1106
+ path: 'docker-compose.dev.yml',
1107
+ content: renderDockerComposeDev(config),
1108
+ },
1109
+ {
1110
+ path: 'docker-compose.test.yml',
1111
+ content: renderDockerComposeTest(config),
1112
+ },
1113
+ {
1114
+ path: 'docker-compose.yml',
1115
+ content: renderDockerComposeProd(config),
1116
+ },
1117
+ {
1118
+ path: 'Caddyfile',
1119
+ content: `${domain} {
1120
+ encode zstd gzip
1121
+ reverse_proxy api:3000
1122
+ }
1123
+ `,
1124
+ },
1125
+ {
1126
+ path: 'deploy/deploy_remote.sh',
1127
+ mode: 'executable',
1128
+ content: `#!/usr/bin/env bash
1129
+ set -euo pipefail
1130
+
1131
+ IMAGE_TAG="\${1:?Missing 40-char SHA image tag}"
1132
+ GHCR_IMAGE="\${2:?Missing GHCR image name}"
1133
+
1134
+ APP_ROOT="/opt/${config.app.name}"
1135
+ CURRENT_DIR="\${APP_ROOT}/current"
1136
+ SHARED_DIR="\${APP_ROOT}/shared"
1137
+ INFRA_ENV="\${SHARED_DIR}/.env.infrastructure"
1138
+
1139
+ if [[ ! -f "\${INFRA_ENV}" ]]; then
1140
+ echo "Missing \${INFRA_ENV}" >&2
1141
+ exit 1
1142
+ fi
1143
+
1144
+ TMP_ENV="\$(mktemp)"
1145
+ grep -v -E '^(IMAGE_TAG|GHCR_IMAGE)=' "\${INFRA_ENV}" > "\${TMP_ENV}" || true
1146
+ printf 'GHCR_IMAGE=%s\\nIMAGE_TAG=%s\\n' "\${GHCR_IMAGE}" "\${IMAGE_TAG}" >> "\${TMP_ENV}"
1147
+ chmod 600 "\${TMP_ENV}"
1148
+ mv "\${TMP_ENV}" "\${INFRA_ENV}"
1149
+
1150
+ cd "\${CURRENT_DIR}"
1151
+ docker compose --env-file "\${INFRA_ENV}" config -q
1152
+ docker compose --env-file "\${INFRA_ENV}" pull
1153
+ docker compose --env-file "\${INFRA_ENV}" up -d --wait
1154
+ docker compose --env-file "\${INFRA_ENV}" up -d --force-recreate --no-deps caddy
1155
+ `,
1156
+ },
1157
+ ...(config.database === 'postgres'
1158
+ ? [
1159
+ {
1160
+ path: 'deploy/postgres/10-init-app-user.sh',
1161
+ mode: 'executable',
1162
+ content: `#!/usr/bin/env bash
1163
+ set -euo pipefail
1164
+
1165
+ if [[ -z "\${POSTGRES_APP_USER:-}" || -z "\${POSTGRES_APP_PASSWORD:-}" ]]; then
1166
+ exit 0
1167
+ fi
1168
+
1169
+ if [[ "\${POSTGRES_APP_USER}" == "\${POSTGRES_USER}" ]]; then
1170
+ exit 0
1171
+ fi
1172
+
1173
+ psql -v ON_ERROR_STOP=1 --username "\${POSTGRES_USER}" --dbname "\${POSTGRES_DB}" \\
1174
+ -v app_user="\${POSTGRES_APP_USER}" \\
1175
+ -v app_pass="\${POSTGRES_APP_PASSWORD}" <<'EOSQL'
1176
+ SELECT format(
1177
+ 'DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = %L) THEN CREATE ROLE %I LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; ELSE ALTER ROLE %I WITH PASSWORD %L; END IF; END $$;',
1178
+ :'app_user', :'app_user', :'app_pass', :'app_user', :'app_pass'
1179
+ ) \\gexec
1180
+ SELECT format('GRANT CONNECT ON DATABASE %I TO %I;', current_database(), :'app_user') \\gexec
1181
+ EOSQL
1182
+ `,
1183
+ },
1184
+ ]
1185
+ : []),
1186
+ {
1187
+ path: '.env.production.example',
1188
+ content: `FIREBASE_PROJECT_ID=
1189
+ GOOGLE_APPLICATION_CREDENTIALS=/opt/${config.app.name}/shared/firebase-sa.json
1190
+ STRIPE_SECRET_KEY=
1191
+ STRIPE_WEBHOOK_SECRET=
1192
+ STRIPE_PORTAL_CONFIGURATION_ID=
1193
+ RESEND_API_KEY=
1194
+ EMAIL_FROM=noreply@${config.app.domain}
1195
+ LOG_LEVEL=info
1196
+ ${config.mcp.enabled ? `MCP_ALLOWED_HOSTS=localhost,127.0.0.1\nMCP_BEARER_TOKEN=\n` : ''}`,
1197
+ },
1198
+ {
1199
+ path: '.env.infrastructure.example',
1200
+ content: `SHARED_DIR=/opt/${config.app.name}/shared
1201
+ DATA_DIR=/opt/${config.app.name}/shared/data
1202
+ GHCR_IMAGE=ghcr.io/owner/${config.app.name}
1203
+ IMAGE_TAG=0000000000000000000000000000000000000000
1204
+ REDIS_PASSWORD=change-me
1205
+ ${config.database === 'mongo' ? `MONGO_ROOT_USER=root\nMONGO_ROOT_PASSWORD=change-me\nMONGO_APP_USER=${dbName}\nMONGO_APP_PASSWORD=change-me` : `POSTGRES_ROOT_USER=postgres\nPOSTGRES_ROOT_PASSWORD=change-me\nPOSTGRES_APP_USER=${dbName}\nPOSTGRES_APP_PASSWORD=change-me`}
1206
+ `,
1207
+ },
1208
+ {
1209
+ path: '.github/workflows/release-image.yml',
1210
+ content: `name: Validate and publish release image
1211
+
1212
+ on:
1213
+ pull_request:
1214
+ branches: [main]
1215
+ push:
1216
+ branches: [main]
1217
+
1218
+ permissions:
1219
+ contents: read
1220
+ packages: write
1221
+
1222
+ jobs:
1223
+ validate:
1224
+ runs-on: ubuntu-latest
1225
+ steps:
1226
+ - uses: actions/checkout@v6
1227
+ - uses: pnpm/action-setup@v4
1228
+ with:
1229
+ version: 11.22.0
1230
+ - uses: actions/setup-node@v6
1231
+ with:
1232
+ node-version: 24
1233
+ cache: pnpm
1234
+ - run: pnpm install --frozen-lockfile
1235
+ - run: pnpm check
1236
+ - run: pnpm typecheck
1237
+ - run: pnpm build
1238
+ - run: docker compose -f docker-compose.test.yml up --abort-on-container-exit --exit-code-from test
1239
+
1240
+ publish:
1241
+ needs: validate
1242
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
1243
+ runs-on: ubuntu-latest
1244
+ steps:
1245
+ - uses: actions/checkout@v6
1246
+ - uses: docker/login-action@v3
1247
+ with:
1248
+ registry: ghcr.io
1249
+ username: \${{ github.actor }}
1250
+ password: \${{ secrets.GITHUB_TOKEN }}
1251
+ - uses: docker/setup-buildx-action@v3
1252
+ - name: Write UI production env
1253
+ env:
1254
+ UI_ENV_PRODUCTION: \${{ secrets.UI_ENV_PRODUCTION }}
1255
+ run: printf '%s\\n' "$UI_ENV_PRODUCTION" > .env.production.build
1256
+ - uses: docker/build-push-action@v6
1257
+ with:
1258
+ context: .
1259
+ push: true
1260
+ tags: ghcr.io/\${{ github.repository_owner }}/${config.app.name}:\${{ github.sha }}
1261
+ secrets: |
1262
+ "ui_env_production=.env.production.build"
1263
+ `,
1264
+ },
1265
+ {
1266
+ path: '.github/workflows/deploy.yml',
1267
+ content: `name: Deploy release image to DigitalOcean
1268
+
1269
+ on:
1270
+ workflow_dispatch:
1271
+ inputs:
1272
+ image_tag:
1273
+ description: Full 40-character commit SHA published to ghcr.io
1274
+ required: true
1275
+ type: string
1276
+
1277
+ permissions:
1278
+ contents: read
1279
+ packages: read
1280
+
1281
+ jobs:
1282
+ deploy:
1283
+ runs-on: ubuntu-latest
1284
+ environment: production
1285
+ steps:
1286
+ - run: '[[ "\${{ inputs.image_tag }}" =~ ^[0-9a-f]{40}$ ]]'
1287
+ - uses: actions/checkout@v6
1288
+ with:
1289
+ ref: \${{ inputs.image_tag }}
1290
+ fetch-depth: 0
1291
+ - run: git merge-base --is-ancestor \${{ inputs.image_tag }} origin/main
1292
+ - name: Configure SSH and deploy
1293
+ env:
1294
+ DEPLOY_HOST: \${{ vars.DEPLOY_HOST }}
1295
+ DEPLOY_USER: \${{ vars.DEPLOY_USER }}
1296
+ DEPLOY_SSH_KEY: \${{ secrets.DEPLOY_SSH_KEY }}
1297
+ GHCR_PULL_TOKEN: \${{ secrets.GITHUB_TOKEN }}
1298
+ run: |
1299
+ install -m 700 -d ~/.ssh
1300
+ printf '%s\\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_deploy
1301
+ chmod 600 ~/.ssh/id_deploy
1302
+ ssh -o StrictHostKeyChecking=accept-new -i ~/.ssh/id_deploy "\${DEPLOY_USER}@\${DEPLOY_HOST}" \\
1303
+ "echo '$GHCR_PULL_TOKEN' | docker login ghcr.io -u '\${{ github.actor }}' --password-stdin && install -m 755 -d /opt/${config.app.name}/current/deploy${config.database === 'postgres' ? ` /opt/${config.app.name}/current/deploy/postgres` : ''}"
1304
+ scp -i ~/.ssh/id_deploy docker-compose.yml Caddyfile "\${DEPLOY_USER}@\${DEPLOY_HOST}:/opt/${config.app.name}/current/"
1305
+ scp -i ~/.ssh/id_deploy deploy/deploy_remote.sh "\${DEPLOY_USER}@\${DEPLOY_HOST}:/opt/${config.app.name}/current/deploy/"${config.database === 'postgres' ? `\n scp -i ~/.ssh/id_deploy deploy/postgres/10-init-app-user.sh "\${DEPLOY_USER}@\${DEPLOY_HOST}:/opt/${config.app.name}/current/deploy/postgres/"` : ''}
1306
+ ssh -i ~/.ssh/id_deploy "\${DEPLOY_USER}@\${DEPLOY_HOST}" \\
1307
+ "chmod +x /opt/${config.app.name}/current/deploy/deploy_remote.sh${config.database === 'postgres' ? ` /opt/${config.app.name}/current/deploy/postgres/10-init-app-user.sh` : ''} && /opt/${config.app.name}/current/deploy/deploy_remote.sh '\${{ inputs.image_tag }}' 'ghcr.io/\${{ github.repository_owner }}/${config.app.name}'"
1308
+ `,
1309
+ },
1310
+ {
1311
+ path: 'AGENTS.md',
1312
+ content: agentsMd,
1313
+ },
1314
+ {
1315
+ path: 'CLAUDE.md',
1316
+ content: `# Claude Code Guidance
1317
+
1318
+ Read [AGENTS.md](./AGENTS.md) and the local skills under [\`.agents/skills/\`](./.agents/skills/) before modifying any files in this Grasp project.
1319
+ `,
1320
+ },
1321
+ {
1322
+ path: '.agents/skills/add-feature/SKILL.md',
1323
+ content: `---
1324
+ name: add-feature
1325
+ description: Scaffold and implement a new full-stack vertical feature slice following Grasp boundaries.
1326
+ ---
1327
+
1328
+ 1. Run \`npx grasp feature <name>\` (camelCase lowercase start, e.g. \`projects\`).
1329
+ 2. Edit \`src/contracts/<name>.contract.ts\` using \`zod\` + \`@zaaxch/grasp-core\` (\`defineProcedure\`, \`defineStream\`, \`defineHttpRoute\`).
1330
+ 3. Implement persistence exclusively in \`src/server/features/<name>/<name>.repo.ts\`.
1331
+ 4. Implement handlers in \`src/server/features/<name>/<name>.procedures.ts\`, plus optional \`<name>.http.ts\` (\`defineHttpRoutes\`), \`<name>.mcp.ts\` (\`defineMcpTool\`), and \`<name>.ops.ts\` (\`defineOpsCommand\`).
1332
+ 5. Build views under \`src/web/features/<name>/views/\` using \`useGraspApi()\` and PrimeVue 4 + Tailwind. Set \`meta: { auth: 'public', layout: 'standalone' }\` on routes that should render publicly outside the shell chrome.
1333
+ 6. Run \`pnpm check && pnpm typecheck && pnpm test\`.
1334
+ `,
1335
+ },
1336
+ {
1337
+ path: '.agents/skills/add-job/SKILL.md',
1338
+ content: `---
1339
+ name: add-job
1340
+ description: Add a background outbox job or distributed cron schedule to an existing feature slice.
1341
+ ---
1342
+
1343
+ 1. Create \`src/server/features/<feature>/<feature>.jobs.ts\` using \`defineJob\` / \`defineSchedule\` from \`@zaaxch/grasp-server\`.
1344
+ 2. Export jobs/schedules via \`defineServerFeature\` in \`src/server/features/index.ts\`.
1345
+ 3. Enqueue jobs transactionally from procedures via \`ctx.jobs.enqueue(job, payload, { tx })\`.
1346
+ `,
1347
+ },
1348
+ {
1349
+ path: '.agents/skills/configure-billing/SKILL.md',
1350
+ content: `---
1351
+ name: configure-billing
1352
+ description: Configure Stripe plans, trial days, limits, and credit packs declaratively.
1353
+ ---
1354
+
1355
+ 1. Edit \`grasp.config.ts\` under \`billing.freePlan\`, \`billing.plans\`, and \`billing.creditPacks\`.
1356
+ 2. Ensure \`freePlan.limits\` and every paid plan share the exact same limit keys.
1357
+ 3. Enforce gates via procedure \`entitlement: { minPlan, requireLimit }\`, \`ctx.quota.consumeWithQuota\`, and \`ctx.credits.spendCredits\`.
1358
+ 4. For accounts without end-user login, set \`auth: { enabled: false }\` in \`grasp.config.ts\`.
1359
+ `,
1360
+ },
1361
+ {
1362
+ path: '.agents/skills/customize-ui/SKILL.md',
1363
+ content: `---
1364
+ name: customize-ui
1365
+ description: Customize app branding, theme tokens, landing page, or AppLayout without mutating the shell.
1366
+ ---
1367
+
1368
+ 1. Customize PrimeVue preset & CSS variables in \`src/web/theme.ts\` and Tailwind tokens in \`src/web/styles.css\`.
1369
+ 2. Edit \`src/web/LandingPage.vue\` for unique marketing/hero UI, or add public routes with \`meta: { auth: 'public', layout: 'standalone' }\`.
1370
+ 3. Set \`ui.layout: 'custom'\` in \`grasp.config.ts\` and create \`src/web/AppLayout.vue\` if custom navigation chrome is needed, then run \`npx grasp sync\`.
1371
+ `,
1372
+ },
1373
+ ];
1374
+ return files;
1375
+ }
1376
+ //# sourceMappingURL=templates.js.map