@atlashub/smartstack-cli 3.31.0 → 3.32.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.
Files changed (52) hide show
  1. package/.documentation/installation.html +7 -2
  2. package/README.md +7 -1
  3. package/dist/index.js +33 -37
  4. package/dist/index.js.map +1 -1
  5. package/dist/mcp-entry.mjs +547 -97
  6. package/dist/mcp-entry.mjs.map +1 -1
  7. package/package.json +1 -1
  8. package/scripts/health-check.sh +2 -1
  9. package/templates/mcp-scaffolding/controller.cs.hbs +10 -7
  10. package/templates/mcp-scaffolding/entity-extension.cs.hbs +132 -124
  11. package/templates/mcp-scaffolding/frontend/api-client.ts.hbs +4 -4
  12. package/templates/mcp-scaffolding/tests/controller.test.cs.hbs +38 -15
  13. package/templates/mcp-scaffolding/tests/service.test.cs.hbs +20 -8
  14. package/templates/skills/apex/SKILL.md +7 -9
  15. package/templates/skills/apex/_shared.md +9 -2
  16. package/templates/skills/apex/references/code-generation.md +412 -0
  17. package/templates/skills/apex/references/post-checks.md +377 -37
  18. package/templates/skills/apex/references/smartstack-api.md +229 -5
  19. package/templates/skills/apex/references/smartstack-frontend.md +368 -11
  20. package/templates/skills/apex/references/smartstack-layers.md +54 -7
  21. package/templates/skills/apex/steps/step-00-init.md +1 -2
  22. package/templates/skills/apex/steps/step-01-analyze.md +45 -2
  23. package/templates/skills/apex/steps/step-02-plan.md +23 -2
  24. package/templates/skills/apex/steps/step-03-execute.md +195 -5
  25. package/templates/skills/apex/steps/step-04-examine.md +18 -5
  26. package/templates/skills/apex/steps/step-05-deep-review.md +9 -11
  27. package/templates/skills/apex/steps/step-06-resolve.md +5 -9
  28. package/templates/skills/apex/steps/step-07-tests.md +66 -1
  29. package/templates/skills/apex/steps/step-08-run-tests.md +12 -3
  30. package/templates/skills/application/references/provider-template.md +62 -39
  31. package/templates/skills/application/templates-backend.md +3 -3
  32. package/templates/skills/application/templates-frontend.md +12 -12
  33. package/templates/skills/application/templates-seed.md +14 -4
  34. package/templates/skills/business-analyse/SKILL.md +9 -6
  35. package/templates/skills/business-analyse/questionnaire/04-data.md +8 -0
  36. package/templates/skills/business-analyse/references/agent-module-prompt.md +84 -5
  37. package/templates/skills/business-analyse/references/agent-pooling-best-practices.md +83 -19
  38. package/templates/skills/business-analyse/references/consolidation-structural-checks.md +6 -2
  39. package/templates/skills/business-analyse/references/team-orchestration.md +443 -110
  40. package/templates/skills/business-analyse/references/validation-checklist.md +5 -4
  41. package/templates/skills/business-analyse/schemas/sections/analysis-schema.json +44 -0
  42. package/templates/skills/business-analyse/steps/step-03a2-analysis.md +72 -1
  43. package/templates/skills/business-analyse/steps/step-03c-compile.md +93 -7
  44. package/templates/skills/business-analyse/steps/step-03d-validate.md +34 -2
  45. package/templates/skills/business-analyse/steps/step-04b-analyze.md +40 -0
  46. package/templates/skills/controller/references/controller-code-templates.md +2 -2
  47. package/templates/skills/controller/templates.md +12 -12
  48. package/templates/skills/feature-full/steps/step-01-implementation.md +4 -4
  49. package/templates/skills/ralph-loop/references/category-rules.md +44 -2
  50. package/templates/skills/ralph-loop/references/compact-loop.md +37 -0
  51. package/templates/skills/ralph-loop/references/core-seed-data.md +51 -20
  52. package/templates/skills/review-code/references/owasp-api-top10.md +1 -1
@@ -55,7 +55,7 @@
55
55
  | `scaffold_api_client` | Generate TypeScript API client | Frontend changes |
56
56
  | `scaffold_routes` | Generate React Router routes | Frontend changes |
57
57
 
58
- ### eXamine (step-04)
58
+ ### eXamine (step-04) — 30 POST-CHECKs
59
59
 
60
60
  | Tool | Purpose | Condition |
61
61
  |------|---------|-----------|
@@ -63,6 +63,13 @@
63
63
  | `validate_frontend_routes` | Validate route/layout alignment | Frontend changes |
64
64
  | `validate_security` | Check security patterns | API changes |
65
65
 
66
+ **Key BLOCKING POST-CHECKs (most common failures):**
67
+ - **#8:** Forms must be full pages — ZERO modals/dialogs
68
+ - **#13:** No hardcoded Tailwind colors — use CSS variables only
69
+ - **#6+27:** i18n in separate `locales/{lang}/{module}.json` — NEVER embedded in .ts
70
+ - **#10:** Form pages must have `.test.tsx` companion files
71
+ - **#28:** Pages must use `useTranslation` — no hardcoded strings
72
+
66
73
  ### Analysis (step-01)
67
74
 
68
75
  | Tool | Purpose |
@@ -70,7 +77,7 @@
70
77
  | `api_docs` | Existing API documentation |
71
78
  | `analyze_extension_points` | React extension points |
72
79
 
73
- ### Tests (step-07, if -t)
80
+ ### Tests (step-07)
74
81
 
75
82
  | Tool | Purpose |
76
83
  |------|---------|
@@ -0,0 +1,412 @@
1
+ # Code Generation — Pattern Reference
2
+
3
+ > **Source of truth:** feature.json `analysis.entities[].codePattern`
4
+ > **Loaded by:** step-01 (analyze), step-03 (execute)
5
+ > **Shared by:** /business-analyse + /apex
6
+
7
+ ---
8
+
9
+ ## Code Strategies
10
+
11
+ | Strategy | Pattern | Example | Use Case |
12
+ |----------|---------|---------|----------|
13
+ | `sequential` | `{tenant}-{prefix}-{N:digits}` | `acme-emp-00001` | Employees, customers, projects |
14
+ | `timestamp-daily` | `{tenant}-{prefix}-{yyyyMMdd}-{N:3}` | `acme-inv-20260215-001` | Invoices, orders, receipts |
15
+ | `timestamp-minute` | `{tenant}-{prefix}-{yyyyMMddHHmm}-{N:3}` | `acme-ticket-202602151430-001` | Tickets, incidents, requests |
16
+ | `year-sequential` | `{tenant}-{prefix}-{yyyy}-{N:digits}` | `acme-ctr-2026-00001` | Contracts, policies, agreements |
17
+ | `uuid-short` | `{tenant}-{prefix}-{8hex}` | `acme-ref-a1b2c3d4` | Reference tables, categories, tags |
18
+ | `manual` | User-provided | `custom-code` | No auto-generation |
19
+
20
+ ---
21
+
22
+ ## Volume-to-Digits (x10 Rule)
23
+
24
+ Anticipate volume growth by multiplying estimated records by 10:
25
+
26
+ ```
27
+ digits = max(4, ceil(log10(estimatedVolume * 10)))
28
+ ```
29
+
30
+ | Estimated Volume | x10 | Digits | Max Capacity |
31
+ |-----------------|-----|--------|-------------|
32
+ | 100 | 1,000 | 4 | 9,999 |
33
+ | 1,000 | 10,000 | 5 | 99,999 |
34
+ | 10,000 | 100,000 | 6 | 999,999 |
35
+ | 100,000 | 1,000,000 | 7 | 9,999,999 |
36
+
37
+ **Default:** If no volume estimate is provided, use 5 digits (capacity: 99,999).
38
+
39
+ ---
40
+
41
+ ## Strategy Selection Heuristic
42
+
43
+ When the user does not specify a strategy, apply these defaults based on entity name:
44
+
45
+ | Entity name pattern | Default strategy | Rationale |
46
+ |--------------------|-----------------|-----------|
47
+ | Invoice, Order, Receipt, Bill, Delivery | `timestamp-daily` | Date context aids lookup and sorting |
48
+ | Ticket, Request, Incident, Support, Alert | `timestamp-minute` | High-frequency, time-sensitive items |
49
+ | Contract, Agreement, Policy, License, Subscription | `year-sequential` | Yearly lifecycle, annual numbering |
50
+ | Reference, Category, Tag, Type, Status, Config | `uuid-short` | Lookup tables, no sequential need |
51
+ | Employee, Customer, Client, Partner, Project, Product, Department | `sequential` | Standard business entities |
52
+ | Any other entity | `sequential` | Safe default |
53
+
54
+ ---
55
+
56
+ ## Code Regex
57
+
58
+ **Updated pattern** (supports hyphens for generated codes):
59
+
60
+ ```
61
+ ^[a-z0-9_-]+$
62
+ ```
63
+
64
+ The previous pattern `^[a-z0-9_]+$` did NOT support hyphens, which are the default separator in all auto-generated codes. All validators MUST use the updated regex.
65
+
66
+ ---
67
+
68
+ ## Feature.json — codePattern Structure
69
+
70
+ Stored in `analysis.entities[].codePattern`:
71
+
72
+ ```json
73
+ {
74
+ "name": "Employee",
75
+ "description": "Company employee",
76
+ "attributes": [...],
77
+ "relationships": [...],
78
+ "codePattern": {
79
+ "strategy": "sequential",
80
+ "prefix": "emp",
81
+ "includeTenantSlug": true,
82
+ "separator": "-",
83
+ "estimatedVolume": 1000,
84
+ "digits": 5,
85
+ "example": "acme-emp-00001"
86
+ }
87
+ }
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Backend Architecture
93
+
94
+ ### CodeStrategy Enum
95
+
96
+ ```csharp
97
+ namespace SmartStack.Application.Common.Models.CodeGeneration;
98
+
99
+ public enum CodeStrategy
100
+ {
101
+ Sequential,
102
+ TimestampDaily,
103
+ TimestampMinute,
104
+ YearSequential,
105
+ UuidShort,
106
+ Manual
107
+ }
108
+ ```
109
+
110
+ ### CodePatternConfig Record
111
+
112
+ ```csharp
113
+ namespace SmartStack.Application.Common.Models.CodeGeneration;
114
+
115
+ public record CodePatternConfig(
116
+ CodeStrategy Strategy = CodeStrategy.Sequential,
117
+ string Prefix = "item",
118
+ bool IncludeTenantSlug = true,
119
+ string Separator = "-",
120
+ int EstimatedVolume = 1000,
121
+ int Digits = 5);
122
+ ```
123
+
124
+ ### ICodeGenerator<TEntity> Interface
125
+
126
+ ```csharp
127
+ namespace SmartStack.Application.Common.Interfaces.CodeGeneration;
128
+
129
+ /// <summary>
130
+ /// Generates unique codes for entities following configurable patterns.
131
+ /// </summary>
132
+ public interface ICodeGenerator<TEntity> where TEntity : class
133
+ {
134
+ /// <summary>
135
+ /// Generate the next unique code for the current tenant.
136
+ /// Handles concurrency via retry on unique constraint violation (3 attempts).
137
+ /// </summary>
138
+ Task<string> NextCodeAsync(CancellationToken ct = default);
139
+ }
140
+ ```
141
+
142
+ ### CodeGenerator<TEntity> Implementation
143
+
144
+ ```csharp
145
+ using Microsoft.EntityFrameworkCore;
146
+ using Microsoft.Extensions.Logging;
147
+ using SmartStack.Application.Common.Interfaces.Tenants;
148
+ using SmartStack.Application.Common.Interfaces.Persistence;
149
+ using SmartStack.Application.Common.Models.CodeGeneration;
150
+
151
+ namespace SmartStack.Infrastructure.Services.CodeGeneration;
152
+
153
+ public class CodeGenerator<TEntity> : ICodeGenerator<TEntity>
154
+ where TEntity : class
155
+ {
156
+ private readonly IExtensionsDbContext _db;
157
+ private readonly ICurrentTenantService _currentTenant;
158
+ private readonly CodePatternConfig _config;
159
+ private readonly ILogger<CodeGenerator<TEntity>> _logger;
160
+ private const int MaxRetries = 3;
161
+
162
+ public CodeGenerator(
163
+ IExtensionsDbContext db,
164
+ ICurrentTenantService currentTenant,
165
+ CodePatternConfig config,
166
+ ILogger<CodeGenerator<TEntity>> logger)
167
+ {
168
+ _db = db;
169
+ _currentTenant = currentTenant;
170
+ _config = config;
171
+ _logger = logger;
172
+ }
173
+
174
+ public async Task<string> NextCodeAsync(CancellationToken ct = default)
175
+ {
176
+ var tenantId = _currentTenant.TenantId
177
+ ?? throw new UnauthorizedAccessException("Tenant context is required");
178
+ var tenantSlug = _currentTenant.TenantSlug ?? "default";
179
+
180
+ for (var attempt = 0; attempt < MaxRetries; attempt++)
181
+ {
182
+ try
183
+ {
184
+ var code = await GenerateCodeAsync(tenantId, tenantSlug, ct);
185
+ return code;
186
+ }
187
+ catch (DbUpdateException ex) when (IsUniqueConstraintViolation(ex))
188
+ {
189
+ _logger.LogWarning(
190
+ "Code generation retry {Attempt}/{Max} for {Entity} tenant {TenantId}",
191
+ attempt + 1, MaxRetries, typeof(TEntity).Name, tenantId);
192
+
193
+ if (attempt == MaxRetries - 1)
194
+ throw new InvalidOperationException(
195
+ $"Failed to generate unique code for {typeof(TEntity).Name} after {MaxRetries} attempts", ex);
196
+ }
197
+ }
198
+
199
+ throw new InvalidOperationException("Code generation exhausted all retries");
200
+ }
201
+
202
+ private async Task<string> GenerateCodeAsync(
203
+ Guid tenantId, string tenantSlug, CancellationToken ct)
204
+ {
205
+ var sep = _config.Separator;
206
+ var parts = new List<string>();
207
+
208
+ // 1. Tenant prefix (dynamic slug)
209
+ if (_config.IncludeTenantSlug)
210
+ parts.Add(tenantSlug.ToLowerInvariant());
211
+
212
+ // 2. Entity prefix
213
+ parts.Add(_config.Prefix);
214
+
215
+ // 3. Date segment (for timestamp strategies)
216
+ var now = DateTime.UtcNow;
217
+ switch (_config.Strategy)
218
+ {
219
+ case CodeStrategy.TimestampDaily:
220
+ parts.Add(now.ToString("yyyyMMdd"));
221
+ break;
222
+ case CodeStrategy.TimestampMinute:
223
+ parts.Add(now.ToString("yyyyMMddHHmm"));
224
+ break;
225
+ case CodeStrategy.YearSequential:
226
+ parts.Add(now.ToString("yyyy"));
227
+ break;
228
+ }
229
+
230
+ // 4. Sequential number or UUID segment
231
+ if (_config.Strategy == CodeStrategy.UuidShort)
232
+ {
233
+ parts.Add(Guid.NewGuid().ToString("N")[..8]);
234
+ }
235
+ else if (_config.Strategy != CodeStrategy.Manual)
236
+ {
237
+ var codePrefix = string.Join(sep, parts) + sep;
238
+ var nextSeq = await GetNextSequenceAsync(tenantId, codePrefix, ct);
239
+ parts.Add(nextSeq.ToString().PadLeft(_config.Digits, '0'));
240
+ }
241
+
242
+ return string.Join(sep, parts);
243
+ }
244
+
245
+ private async Task<int> GetNextSequenceAsync(
246
+ Guid tenantId, string codePrefix, CancellationToken ct)
247
+ {
248
+ // Find the highest existing sequence matching the prefix
249
+ var maxCode = await _db.Set<TEntity>()
250
+ .Where(e => EF.Property<Guid>(e, "TenantId") == tenantId)
251
+ .Where(e => !EF.Property<bool>(e, "IsDeleted"))
252
+ .Where(e => EF.Property<string>(e, "Code").StartsWith(codePrefix))
253
+ .Select(e => EF.Property<string>(e, "Code"))
254
+ .OrderByDescending(c => c)
255
+ .FirstOrDefaultAsync(ct);
256
+
257
+ if (maxCode == null) return 1;
258
+
259
+ // Extract the last segment (sequential number)
260
+ var lastSegment = maxCode.Split(_config.Separator[0]).Last();
261
+ return int.TryParse(lastSegment, out var seq) ? seq + 1 : 1;
262
+ }
263
+
264
+ private static bool IsUniqueConstraintViolation(DbUpdateException ex)
265
+ {
266
+ var message = ex.InnerException?.Message ?? "";
267
+ return message.Contains("UNIQUE", StringComparison.OrdinalIgnoreCase)
268
+ || message.Contains("duplicate", StringComparison.OrdinalIgnoreCase)
269
+ || message.Contains("IX_", StringComparison.OrdinalIgnoreCase)
270
+ || message.Contains("Cannot insert duplicate key", StringComparison.OrdinalIgnoreCase);
271
+ }
272
+ }
273
+ ```
274
+
275
+ ---
276
+
277
+ ## DI Registration Pattern
278
+
279
+ In `DependencyInjection.cs` (Infrastructure layer):
280
+
281
+ ```csharp
282
+ // One registration per entity with auto-generated code
283
+ services.AddScoped<ICodeGenerator<Employee>>(sp =>
284
+ new CodeGenerator<Employee>(
285
+ sp.GetRequiredService<IExtensionsDbContext>(),
286
+ sp.GetRequiredService<ICurrentTenantService>(),
287
+ new CodePatternConfig(
288
+ Strategy: CodeStrategy.Sequential,
289
+ Prefix: "emp",
290
+ IncludeTenantSlug: true,
291
+ Separator: "-",
292
+ EstimatedVolume: 1000,
293
+ Digits: 5),
294
+ sp.GetRequiredService<ILogger<CodeGenerator<Employee>>>()));
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Service Integration Pattern
300
+
301
+ When `codePattern.strategy != "manual"`, the service's `CreateAsync` method uses `ICodeGenerator<T>`:
302
+
303
+ ```csharp
304
+ public class EmployeeService : IEmployeeService
305
+ {
306
+ private readonly IExtensionsDbContext _db;
307
+ private readonly ICurrentTenantService _currentTenant;
308
+ private readonly ICodeGenerator<Employee> _codeGenerator;
309
+
310
+ public EmployeeService(
311
+ IExtensionsDbContext db,
312
+ ICurrentTenantService currentTenant,
313
+ ICodeGenerator<Employee> codeGenerator)
314
+ {
315
+ _db = db;
316
+ _currentTenant = currentTenant;
317
+ _codeGenerator = codeGenerator;
318
+ }
319
+
320
+ public async Task<EmployeeResponseDto> CreateAsync(
321
+ CreateEmployeeDto dto, CancellationToken ct = default)
322
+ {
323
+ var tenantId = _currentTenant.TenantId
324
+ ?? throw new UnauthorizedAccessException("Tenant context is required");
325
+
326
+ // Auto-generate code (NOT from DTO)
327
+ var code = await _codeGenerator.NextCodeAsync(ct);
328
+
329
+ var entity = Employee.Create(
330
+ tenantId: tenantId,
331
+ code: code,
332
+ name: dto.Name,
333
+ createdBy: null);
334
+
335
+ _db.Employees.Add(entity);
336
+ await _db.SaveChangesAsync(ct);
337
+
338
+ return MapToDto(entity);
339
+ }
340
+ }
341
+ ```
342
+
343
+ ---
344
+
345
+ ## CreateDto Changes (when auto-generated)
346
+
347
+ When `codePattern.strategy != "manual"`:
348
+ - **REMOVE** `Code` from `CreateDto` (auto-generated, not user-provided)
349
+ - **KEEP** `Code` in `ResponseDto` (returned to user after creation)
350
+ - **KEEP** `Code` in `UpdateDto` ONLY if code is mutable (rare)
351
+
352
+ ```csharp
353
+ // CreateDto when strategy != manual — NO Code property
354
+ public record CreateEmployeeDto
355
+ {
356
+ [Required]
357
+ public string Name { get; init; } = string.Empty;
358
+ // Code is auto-generated by ICodeGenerator — not in CreateDto
359
+ }
360
+
361
+ // ResponseDto — ALWAYS includes Code
362
+ public record EmployeeResponseDto
363
+ {
364
+ public Guid Id { get; init; }
365
+ public string Code { get; init; } = string.Empty;
366
+ public string Name { get; init; } = string.Empty;
367
+ }
368
+ ```
369
+
370
+ ---
371
+
372
+ ## Anti-Pattern: Count() + 1 (Race Condition)
373
+
374
+ ```csharp
375
+ // WRONG — concurrent requests generate duplicate codes
376
+ var count = await _db.Employees
377
+ .Where(e => e.TenantId == tenantId)
378
+ .CountAsync(ct);
379
+ return $"emp-{(count + 1):D5}";
380
+
381
+ // CORRECT — use ICodeGenerator with retry on unique constraint violation
382
+ var code = await _codeGenerator.NextCodeAsync(ct);
383
+ ```
384
+
385
+ **Why it's wrong:** `Count() + 1` causes **race conditions** — two concurrent requests get the same count and generate duplicate codes. The `ICodeGenerator` approach uses `OrderByDescending` on existing codes + retry on unique constraint violation for safe concurrency.
386
+
387
+ ---
388
+
389
+ ## Validator Regex Update
390
+
391
+ All entity validators MUST use the updated regex:
392
+
393
+ ```csharp
394
+ // OLD (FORBIDDEN): ^[a-z0-9_]+$
395
+ // NEW (REQUIRED): ^[a-z0-9_-]+$
396
+ RuleFor(x => x.Code)
397
+ .NotEmpty()
398
+ .MaximumLength(100)
399
+ .Matches("^[a-z0-9_-]+$")
400
+ .WithMessage("Code must be lowercase alphanumeric with underscores and hyphens");
401
+ ```
402
+
403
+ > **Note:** When `codePattern.strategy != "manual"`, the Code field is NOT in CreateDto, so the CreateValidator does NOT have a Code rule. The UpdateValidator still has it if Code is mutable.
404
+
405
+ ---
406
+
407
+ ## Edge Cases
408
+
409
+ 1. **Concurrency:** The retry mechanism (3 attempts) handles typical SmartStack workloads (< 10 concurrent creates/second/tenant). For extreme volumes, consider DB sequences.
410
+ 2. **Tenant slug null:** Falls back to `"default"` — should only happen in test/seed scenarios.
411
+ 3. **Midnight/minute boundary:** For `timestamp-daily` and `timestamp-minute`, the sequence resets naturally within each time period. Two requests straddling midnight get different date prefixes.
412
+ 4. **Backward compatibility:** Existing entities without `codePattern` are treated as `strategy: "manual"` (current behavior preserved).