start-vibing-stacks 1.9.0 → 1.9.1

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.
package/dist/ui.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Start Vibing Stacks — Terminal UI
3
3
  */
4
4
  import chalk from 'chalk';
5
- const VERSION = '1.9.0';
5
+ const VERSION = '1.9.1';
6
6
  const gradient = (text) => {
7
7
  const colors = [chalk.hex('#FF6B6B'), chalk.hex('#FF8E53'), chalk.hex('#FFBD2E'), chalk.hex('#48BB78'), chalk.hex('#4299E1'), chalk.hex('#9F7AEA')];
8
8
  return text.split('').map((c, i) => colors[i % colors.length](c)).join('');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "start-vibing-stacks",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "AI-powered multi-stack dev workflow for Claude Code. Supports PHP, Node.js, Python and more.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,385 @@
1
+ # MariaDB + Octane — Database Patterns for Persistent Workers
2
+
3
+ **ALWAYS invoke when writing queries, migrations, models, or DB config in Laravel Octane.**
4
+
5
+ ## Why Octane Changes Everything
6
+
7
+ ```
8
+ Traditional PHP: Octane (RoadRunner):
9
+ ┌──────────┐ ┌──────────────────────┐
10
+ │ Request → │ │ Worker boots ONCE │
11
+ │ Boot app │ │ ↓ │
12
+ │ DB connect│ │ Request 1 → process │
13
+ │ Process │ │ Request 2 → process │ ← SAME connection
14
+ │ DB close │ │ Request 3 → process │ ← SAME state
15
+ │ Die │ │ ...500 requests... │
16
+ └──────────┘ │ Worker restarts │
17
+ └──────────────────────┘
18
+
19
+ Problems in Octane:
20
+ - Connection stays open → stale connections, gone away errors
21
+ - Transaction leaks → uncommitted TX bleeds to next request
22
+ - Query builder state → leftover bindings
23
+ - String truncation → silent data loss in strict mode OFF
24
+ ```
25
+
26
+ ## Connection Configuration
27
+
28
+ ```php
29
+ // config/database.php
30
+ 'mysql' => [
31
+ 'driver' => 'mysql',
32
+ 'host' => env('DB_HOST', '127.0.0.1'),
33
+ 'port' => env('DB_PORT', '3306'),
34
+ 'database' => env('DB_DATABASE'),
35
+ 'username' => env('DB_USERNAME'),
36
+ 'password' => env('DB_PASSWORD'),
37
+ 'charset' => 'utf8mb4',
38
+ 'collation' => 'utf8mb4_unicode_ci',
39
+ 'prefix' => '',
40
+ 'strict' => true, // ← MANDATORY
41
+ 'engine' => 'InnoDB',
42
+ 'options' => [
43
+ PDO::ATTR_PERSISTENT => true, // ← Octane reuses connections
44
+ PDO::ATTR_EMULATE_PREPARES => false, // ← Real prepared statements
45
+ PDO::ATTR_STRINGIFY_FETCHES => false, // ← Preserve int/float types
46
+ PDO::MYSQL_ATTR_FOUND_ROWS => true, // ← Accurate affected rows
47
+ ],
48
+ 'modes' => [
49
+ 'STRICT_TRANS_TABLES', // ← Errors instead of truncation
50
+ 'NO_ZERO_IN_DATE', // ← No 0000-00-00 dates
51
+ 'NO_ZERO_DATE',
52
+ 'ERROR_FOR_DIVISION_BY_ZERO',
53
+ 'NO_ENGINE_SUBSTITUTION',
54
+ 'ONLY_FULL_GROUP_BY', // ← Force explicit GROUP BY
55
+ ],
56
+ ],
57
+ ```
58
+
59
+ ### Why `strict => true` + SQL Modes
60
+
61
+ ```
62
+ strict: false (DEFAULT MariaDB):
63
+ INSERT INTO users (name) VALUES ('This is a very long name that exceeds the column limit')
64
+ → Silently TRUNCATES to column length! No error! DATA LOST!
65
+
66
+ strict: true (OUR STANDARD):
67
+ → ERROR 1406: Data too long for column 'name'
68
+ → You KNOW the problem immediately
69
+ ```
70
+
71
+ **Rule:** `strict => true` is NON-NEGOTIABLE. Every silent truncation is a bug waiting to explode.
72
+
73
+ ## Octane Connection Flush (MANDATORY)
74
+
75
+ ```php
76
+ // app/Providers/AppServiceProvider.php
77
+ use Laravel\Octane\Facades\Octane;
78
+
79
+ public function boot(): void
80
+ {
81
+ // Flush stale connections between requests
82
+ Octane::prepare(function ($sandbox) {
83
+ $sandbox->flushDatabaseConnections();
84
+ });
85
+
86
+ // Also flush on tick (long-running operations)
87
+ Octane::tick('db-health', function () {
88
+ try {
89
+ DB::connection()->getPdo();
90
+ } catch (\Exception $e) {
91
+ DB::reconnect();
92
+ }
93
+ })->seconds(30);
94
+ }
95
+ ```
96
+
97
+ ## Migration Patterns
98
+
99
+ ### Column Definitions — Be Explicit
100
+
101
+ ```php
102
+ // ✅ ALWAYS define exact lengths — no surprises with strict mode
103
+ Schema::create('leads', function (Blueprint $table) {
104
+ $table->uuid('id')->primary();
105
+
106
+ // Strings: ALWAYS define max length
107
+ $table->string('name', 255); // varchar(255)
108
+ $table->string('email', 320); // RFC 5321 max email
109
+ $table->string('phone', 20); // E.164 max
110
+ $table->string('status', 30); // enum-like but flexible
111
+ $table->string('country_code', 3); // ISO 3166-1 alpha-2/3
112
+ $table->string('currency', 3); // ISO 4217
113
+
114
+ // Use text() for unbounded content
115
+ $table->text('notes'); // 64KB
116
+ $table->mediumText('description'); // 16MB
117
+ $table->longText('raw_payload'); // 4GB
118
+
119
+ // Decimals: ALWAYS precision + scale
120
+ $table->decimal('price', 10, 2); // 99,999,999.99
121
+ $table->decimal('commission_rate', 5, 4); // 0.0000 to 9.9999
122
+ $table->unsignedBigInteger('impressions')->default(0);
123
+
124
+ // Dates
125
+ $table->timestamp('converted_at')->nullable();
126
+ $table->timestamps(); // created_at, updated_at
127
+ $table->softDeletes(); // deleted_at
128
+
129
+ // JSON (MariaDB 10.2+)
130
+ $table->json('metadata')->nullable();
131
+
132
+ // Indexes
133
+ $table->index('status');
134
+ $table->index(['status', 'created_at']); // Composite for common queries
135
+ $table->unique('email');
136
+ });
137
+ ```
138
+
139
+ ### Index Strategy for MariaDB
140
+
141
+ ```php
142
+ // ✅ Composite indexes — leftmost prefix rule
143
+ $table->index(['user_id', 'status', 'created_at']);
144
+ // Covers: WHERE user_id = ?
145
+ // Covers: WHERE user_id = ? AND status = ?
146
+ // Covers: WHERE user_id = ? AND status = ? ORDER BY created_at
147
+ // Does NOT cover: WHERE status = ? (user_id not in query)
148
+
149
+ // ✅ Covering index for frequent queries
150
+ $table->index(['domain_id', 'status', 'created_at', 'id'], 'idx_leads_dashboard');
151
+
152
+ // ✅ Partial-like with generated column (MariaDB 10.2+)
153
+ // For: WHERE JSON_EXTRACT(metadata, '$.source') = 'google'
154
+ $table->string('metadata_source', 50)->virtualAs("JSON_UNQUOTE(JSON_EXTRACT(metadata, '$.source'))");
155
+ $table->index('metadata_source');
156
+ ```
157
+
158
+ ## Eloquent Patterns for Octane
159
+
160
+ ### Scoped Queries (avoid stale state)
161
+
162
+ ```php
163
+ class Lead extends Model
164
+ {
165
+ use HasUuids;
166
+
167
+ // ✅ Scopes — reusable, composable
168
+ public function scopeActive(Builder $query): Builder
169
+ {
170
+ return $query->where('status', 'active');
171
+ }
172
+
173
+ public function scopeForUser(Builder $query, string $userId): Builder
174
+ {
175
+ return $query->where('user_id', $userId);
176
+ }
177
+
178
+ public function scopeCreatedBetween(Builder $query, Carbon $from, Carbon $to): Builder
179
+ {
180
+ return $query->whereBetween('created_at', [$from, $to]);
181
+ }
182
+ }
183
+
184
+ // Usage (always fresh query, no state leaks):
185
+ Lead::query()
186
+ ->active()
187
+ ->forUser($request->user()->id)
188
+ ->createdBetween(now()->subDays(30), now())
189
+ ->paginate(20);
190
+ ```
191
+
192
+ ### N+1 Prevention
193
+
194
+ ```php
195
+ // ✅ ALWAYS eager load relationships
196
+ class LeadController extends Controller
197
+ {
198
+ public function index(Request $request): JsonResponse
199
+ {
200
+ $leads = Lead::query()
201
+ ->with(['domain:id,name', 'user:id,name,email']) // Select only needed columns
202
+ ->select('id', 'name', 'email', 'status', 'domain_id', 'user_id', 'created_at')
203
+ ->forUser($request->user()->id)
204
+ ->latest()
205
+ ->paginate(20);
206
+
207
+ return LeadResource::collection($leads);
208
+ }
209
+ }
210
+
211
+ // ❌ NEVER in Octane (N+1 with persistent connections = compounding slowness)
212
+ foreach ($leads as $lead) {
213
+ echo $lead->domain->name; // N+1 query PER lead, PER request, ALL DAY
214
+ }
215
+ ```
216
+
217
+ ### Bulk Operations (Octane-safe)
218
+
219
+ ```php
220
+ // ✅ Chunked processing — controls memory in long-lived worker
221
+ Lead::query()
222
+ ->where('status', 'pending')
223
+ ->chunkById(500, function ($leads) {
224
+ foreach ($leads as $lead) {
225
+ ProcessLeadJob::dispatch($lead);
226
+ }
227
+ });
228
+
229
+ // ✅ Bulk insert (single query)
230
+ Lead::insert(
231
+ collect($rows)->map(fn ($row) => [
232
+ 'id' => Str::uuid()->toString(),
233
+ 'name' => $row['name'],
234
+ 'email' => $row['email'],
235
+ 'created_at' => now(),
236
+ 'updated_at' => now(),
237
+ ])->toArray()
238
+ );
239
+
240
+ // ✅ Bulk update
241
+ Lead::query()
242
+ ->whereIn('id', $ids)
243
+ ->update(['status' => 'processed', 'processed_at' => now()]);
244
+
245
+ // ❌ NEVER in Octane (memory grows with each request)
246
+ $allLeads = Lead::all(); // Loads EVERYTHING into worker memory
247
+ ```
248
+
249
+ ### Transaction Safety in Octane
250
+
251
+ ```php
252
+ // ✅ Always explicit transactions with try/catch
253
+ // In Octane, an uncaught exception leaves the TX open for the NEXT request!
254
+ try {
255
+ DB::beginTransaction();
256
+
257
+ $lead = Lead::create($validated);
258
+ $lead->attempts()->create(['status' => 'new']);
259
+ ConversionService::fire($lead);
260
+
261
+ DB::commit();
262
+ } catch (\Throwable $e) {
263
+ DB::rollBack(); // ← CRITICAL in Octane — prevents TX leak
264
+ report($e);
265
+ throw $e;
266
+ }
267
+
268
+ // ✅ Or use the closure syntax (auto-rollback on exception)
269
+ $lead = DB::transaction(function () use ($validated) {
270
+ $lead = Lead::create($validated);
271
+ $lead->attempts()->create(['status' => 'new']);
272
+ return $lead;
273
+ }, attempts: 3); // Retry on deadlock
274
+ ```
275
+
276
+ ## Query Performance
277
+
278
+ ### Explain Before Deploy
279
+
280
+ ```php
281
+ // In Tinker or test:
282
+ DB::enableQueryLog();
283
+ $leads = Lead::query()->active()->forUser($userId)->paginate(20);
284
+ $queries = DB::getQueryLog();
285
+
286
+ // Check for full table scans:
287
+ // EXPLAIN SELECT * FROM leads WHERE user_id = ? AND status = 'active'
288
+ // Look for: type=ref or type=range (GOOD), type=ALL (BAD — full scan)
289
+ ```
290
+
291
+ ### Pagination (NEVER offset for large tables)
292
+
293
+ ```php
294
+ // ✅ Cursor pagination (fast on large tables)
295
+ $leads = Lead::query()
296
+ ->where('user_id', $userId)
297
+ ->orderBy('id')
298
+ ->cursorPaginate(20);
299
+
300
+ // ✅ Standard pagination (OK for admin panels)
301
+ $leads = Lead::query()->paginate(20);
302
+
303
+ // ❌ NEVER manual offset on large tables
304
+ Lead::query()->offset(100000)->limit(20)->get();
305
+ // Full scan of 100,000 rows just to skip them!
306
+ ```
307
+
308
+ ### Count Optimization
309
+
310
+ ```php
311
+ // ❌ SLOW on large tables
312
+ $total = Lead::count(); // Full table scan
313
+
314
+ // ✅ Approximate count (MariaDB)
315
+ $total = DB::selectOne("SELECT TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_NAME = 'leads'")->TABLE_ROWS;
316
+
317
+ // ✅ Exact count with cache
318
+ $total = Cache::remember("leads:count:{$userId}", 60, function () use ($userId) {
319
+ return Lead::where('user_id', $userId)->count();
320
+ });
321
+ ```
322
+
323
+ ## Model Casts (Strict Types)
324
+
325
+ ```php
326
+ class Lead extends Model
327
+ {
328
+ protected $casts = [
329
+ 'metadata' => 'array', // JSON → array (auto encode/decode)
330
+ 'price' => 'decimal:2', // Always 2 decimal places
331
+ 'is_active' => 'boolean', // 1/0 → true/false
332
+ 'converted_at' => 'immutable_datetime', // Carbon Immutable (Octane-safe)
333
+ 'impressions' => 'integer', // String → int
334
+ 'status' => LeadStatus::class, // Backed enum
335
+ ];
336
+ }
337
+
338
+ // ✅ Backed enums for status columns
339
+ enum LeadStatus: string
340
+ {
341
+ case Pending = 'pending';
342
+ case Active = 'active';
343
+ case Converted = 'converted';
344
+ case Rejected = 'rejected';
345
+ }
346
+ ```
347
+
348
+ ## Health Check
349
+
350
+ ```php
351
+ // routes/web.php — Octane worker health
352
+ Route::get('/health', function () {
353
+ try {
354
+ DB::connection()->getPdo();
355
+ $dbOk = true;
356
+ } catch (\Exception $e) {
357
+ DB::reconnect();
358
+ $dbOk = false;
359
+ }
360
+
361
+ return response()->json([
362
+ 'status' => $dbOk ? 'healthy' : 'degraded',
363
+ 'db' => $dbOk,
364
+ 'worker_memory' => memory_get_usage(true) / 1024 / 1024 . ' MB',
365
+ 'worker_peak' => memory_get_peak_usage(true) / 1024 / 1024 . ' MB',
366
+ ], $dbOk ? 200 : 503);
367
+ });
368
+ ```
369
+
370
+ ## FORBIDDEN
371
+
372
+ | ❌ Don't | ✅ Do |
373
+ |---|---|
374
+ | `strict => false` | `strict => true` + SQL modes |
375
+ | `$table->string('name')` (no length) | `$table->string('name', 255)` |
376
+ | `Lead::all()` in Octane | `Lead::query()->paginate()` or `chunkById()` |
377
+ | Uncaught exception in transaction | `DB::transaction()` closure or explicit rollBack |
378
+ | `$_GET`, `$_POST` | `$request->input()` |
379
+ | `static $cache = []` | Instance property or Redis cache |
380
+ | `offset()` on large tables | `cursorPaginate()` |
381
+ | `migrate:fresh`, `db:wipe` | Incremental migrations only |
382
+ | No index on WHERE/ORDER columns | Composite indexes matching query patterns |
383
+ | `Lead::count()` on millions of rows | Cached count or approximate count |
384
+ | `'metadata' => 'json'` cast | `'metadata' => 'array'` (auto decode) |
385
+ | `datetime` cast | `immutable_datetime` (Octane-safe, no mutation) |