@lssm/module.learning-journey 0.0.0-canary-20251217063201 → 0.0.0-canary-20251217072406

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 (156) hide show
  1. package/dist/contracts/index.js +6 -1
  2. package/dist/contracts/models.d.ts +118 -118
  3. package/dist/contracts/models.js +389 -1
  4. package/dist/contracts/onboarding.d.ts +167 -167
  5. package/dist/contracts/onboarding.js +404 -1
  6. package/dist/contracts/operations.d.ts +70 -70
  7. package/dist/contracts/operations.js +151 -1
  8. package/dist/contracts/shared.js +5 -1
  9. package/dist/docs/index.js +1 -1
  10. package/dist/docs/learning-journey.docblock.js +61 -5
  11. package/dist/engines/index.js +5 -1
  12. package/dist/engines/srs.js +219 -1
  13. package/dist/engines/streak.js +193 -1
  14. package/dist/engines/xp.js +212 -1
  15. package/dist/entities/ai.d.ts +200 -200
  16. package/dist/entities/ai.js +376 -1
  17. package/dist/entities/course.d.ts +150 -150
  18. package/dist/entities/course.js +316 -1
  19. package/dist/entities/flashcard.d.ts +145 -145
  20. package/dist/entities/flashcard.js +249 -1
  21. package/dist/entities/gamification.d.ts +198 -198
  22. package/dist/entities/gamification.js +392 -1
  23. package/dist/entities/index.d.ts +605 -605
  24. package/dist/entities/index.js +44 -1
  25. package/dist/entities/learner.d.ts +192 -192
  26. package/dist/entities/learner.js +365 -1
  27. package/dist/entities/onboarding.d.ts +165 -165
  28. package/dist/entities/onboarding.js +307 -1
  29. package/dist/entities/quiz.d.ts +185 -185
  30. package/dist/entities/quiz.js +370 -1
  31. package/dist/events.d.ts +213 -213
  32. package/dist/events.js +583 -1
  33. package/dist/index.js +22 -1
  34. package/dist/learning-journey.feature.js +148 -1
  35. package/dist/libs/contracts/dist/capabilities/openbanking.js +88 -1
  36. package/dist/libs/contracts/dist/client/index.js +5 -1
  37. package/dist/libs/contracts/dist/client/react/feature-render.js +2 -1
  38. package/dist/libs/contracts/dist/client/react/form-render.js +4 -1
  39. package/dist/libs/contracts/dist/client/react/index.js +4 -1
  40. package/dist/libs/contracts/dist/contract-registry/index.js +1 -1
  41. package/dist/libs/contracts/dist/contract-registry/schemas.js +60 -1
  42. package/dist/libs/contracts/dist/docs/PUBLISHING.docblock.js +16 -76
  43. package/dist/libs/contracts/dist/docs/accessibility_wcag_compliance_specs.docblock.js +16 -350
  44. package/dist/libs/contracts/dist/docs/index.js +29 -1
  45. package/dist/libs/contracts/dist/docs/presentations.js +71 -1
  46. package/dist/libs/contracts/dist/docs/registry.js +44 -1
  47. package/dist/libs/contracts/dist/docs/tech/PHASE_1_QUICKSTART.docblock.js +16 -383
  48. package/dist/libs/contracts/dist/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.js +16 -68
  49. package/dist/libs/contracts/dist/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.js +16 -140
  50. package/dist/libs/contracts/dist/docs/tech/PHASE_4_PERSONALIZATION_ENGINE.docblock.js +16 -86
  51. package/dist/libs/contracts/dist/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS.docblock.js +16 -1
  52. package/dist/libs/contracts/dist/docs/tech/auth/better-auth-nextjs.docblock.js +24 -2
  53. package/dist/libs/contracts/dist/docs/tech/contracts/openapi-export.docblock.js +21 -2
  54. package/dist/libs/contracts/dist/docs/tech/lifecycle-stage-system.docblock.js +16 -213
  55. package/dist/libs/contracts/dist/docs/tech/llm/llm-integration.docblock.js +73 -5
  56. package/dist/libs/contracts/dist/docs/tech/mcp-endpoints.docblock.js +37 -1
  57. package/dist/libs/contracts/dist/docs/tech/presentation-runtime.docblock.js +16 -1
  58. package/dist/libs/contracts/dist/docs/tech/schema/README.docblock.js +20 -262
  59. package/dist/libs/contracts/dist/docs/tech/studio/learning-events.docblock.js +48 -1
  60. package/dist/libs/contracts/dist/docs/tech/studio/learning-journeys.docblock.js +24 -2
  61. package/dist/libs/contracts/dist/docs/tech/studio/platform-admin-panel.docblock.js +23 -2
  62. package/dist/libs/contracts/dist/docs/tech/studio/project-access-teams.docblock.js +25 -16
  63. package/dist/libs/contracts/dist/docs/tech/studio/project-routing.docblock.js +67 -1
  64. package/dist/libs/contracts/dist/docs/tech/studio/sandbox-unlogged.docblock.js +22 -2
  65. package/dist/libs/contracts/dist/docs/tech/studio/team-invitations.docblock.js +40 -36
  66. package/dist/libs/contracts/dist/docs/tech/studio/workspace-ops.docblock.js +47 -1
  67. package/dist/libs/contracts/dist/docs/tech/studio/workspaces.docblock.js +23 -2
  68. package/dist/libs/contracts/dist/docs/tech/telemetry-ingest.docblock.js +36 -3
  69. package/dist/libs/contracts/dist/docs/tech/templates/runtime.docblock.js +20 -1
  70. package/dist/libs/contracts/dist/docs/tech/vscode-extension.docblock.js +36 -3
  71. package/dist/libs/contracts/dist/docs/tech/workflows/overview.docblock.js +20 -1
  72. package/dist/libs/contracts/dist/events.js +10 -1
  73. package/dist/libs/contracts/dist/experiments/evaluator.js +1 -1
  74. package/dist/libs/contracts/dist/index.js +71 -1
  75. package/dist/libs/contracts/dist/install.js +2 -1
  76. package/dist/libs/contracts/dist/integrations/contracts.js +377 -1
  77. package/dist/libs/contracts/dist/integrations/index.js +18 -1
  78. package/dist/libs/contracts/dist/integrations/openbanking/contracts/accounts.js +228 -1
  79. package/dist/libs/contracts/dist/integrations/openbanking/contracts/balances.js +159 -1
  80. package/dist/libs/contracts/dist/integrations/openbanking/contracts/index.js +3 -1
  81. package/dist/libs/contracts/dist/integrations/openbanking/contracts/transactions.js +210 -1
  82. package/dist/libs/contracts/dist/integrations/openbanking/models.js +242 -1
  83. package/dist/libs/contracts/dist/integrations/openbanking/telemetry.js +13 -1
  84. package/dist/libs/contracts/dist/integrations/providers/elevenlabs.js +52 -1
  85. package/dist/libs/contracts/dist/integrations/providers/gcs-storage.js +75 -1
  86. package/dist/libs/contracts/dist/integrations/providers/gmail.js +87 -1
  87. package/dist/libs/contracts/dist/integrations/providers/google-calendar.js +66 -1
  88. package/dist/libs/contracts/dist/integrations/providers/index.js +11 -1
  89. package/dist/libs/contracts/dist/integrations/providers/mistral.js +68 -1
  90. package/dist/libs/contracts/dist/integrations/providers/postmark.js +68 -1
  91. package/dist/libs/contracts/dist/integrations/providers/powens.js +116 -1
  92. package/dist/libs/contracts/dist/integrations/providers/qdrant.js +73 -1
  93. package/dist/libs/contracts/dist/integrations/providers/registry.js +10 -1
  94. package/dist/libs/contracts/dist/integrations/providers/stripe.js +83 -1
  95. package/dist/libs/contracts/dist/integrations/providers/twilio-sms.js +61 -1
  96. package/dist/libs/contracts/dist/jsonschema.js +1 -1
  97. package/dist/libs/contracts/dist/knowledge/contracts.js +306 -1
  98. package/dist/libs/contracts/dist/knowledge/index.js +7 -1
  99. package/dist/libs/contracts/dist/knowledge/spaces/email-threads.js +34 -1
  100. package/dist/libs/contracts/dist/knowledge/spaces/financial-docs.js +34 -1
  101. package/dist/libs/contracts/dist/knowledge/spaces/financial-overview.js +38 -1
  102. package/dist/libs/contracts/dist/knowledge/spaces/index.js +6 -1
  103. package/dist/libs/contracts/dist/knowledge/spaces/product-canon.js +34 -1
  104. package/dist/libs/contracts/dist/knowledge/spaces/support-faq.js +37 -1
  105. package/dist/libs/contracts/dist/knowledge/spaces/uploaded-docs.js +34 -1
  106. package/dist/libs/contracts/dist/llm/exporters.js +19 -1
  107. package/dist/libs/contracts/dist/llm/index.js +2 -1
  108. package/dist/libs/contracts/dist/llm/prompts.js +1 -1
  109. package/dist/libs/contracts/dist/onboarding-base.js +196 -1
  110. package/dist/libs/contracts/dist/openapi.js +1 -1
  111. package/dist/libs/contracts/dist/ownership.js +21 -1
  112. package/dist/libs/contracts/dist/presentations.js +1 -1
  113. package/dist/libs/contracts/dist/presentations.v2.js +11 -1
  114. package/dist/libs/contracts/dist/prompt.js +1 -1
  115. package/dist/libs/contracts/dist/promptRegistry.js +1 -1
  116. package/dist/libs/contracts/dist/regenerator/index.js +1 -1
  117. package/dist/libs/contracts/dist/regenerator/service.js +6 -1
  118. package/dist/libs/contracts/dist/registry.js +2 -1
  119. package/dist/libs/contracts/dist/resources.js +1 -1
  120. package/dist/libs/contracts/dist/schema/dist/EnumType.js +2 -1
  121. package/dist/libs/contracts/dist/schema/dist/FieldType.js +49 -1
  122. package/dist/libs/contracts/dist/schema/dist/ScalarTypeEnum.js +236 -1
  123. package/dist/libs/contracts/dist/schema/dist/SchemaModel.js +34 -1
  124. package/dist/libs/contracts/dist/schema/dist/entity/defineEntity.js +1 -1
  125. package/dist/libs/contracts/dist/schema/dist/entity/index.js +2 -1
  126. package/dist/libs/contracts/dist/schema/dist/entity/types.js +1 -1
  127. package/dist/libs/contracts/dist/schema/dist/index.js +6 -1
  128. package/dist/libs/contracts/dist/server/graphql-pothos.js +6 -1
  129. package/dist/libs/contracts/dist/server/index.js +8 -1
  130. package/dist/libs/contracts/dist/server/mcp/createMcpServer.js +4 -1
  131. package/dist/libs/contracts/dist/server/mcp/registerPresentations.js +2 -1
  132. package/dist/libs/contracts/dist/server/mcp/registerPrompts.js +1 -1
  133. package/dist/libs/contracts/dist/server/mcp/registerResources.js +2 -1
  134. package/dist/libs/contracts/dist/server/mcp/registerTools.js +1 -1
  135. package/dist/libs/contracts/dist/server/provider-mcp.js +1 -1
  136. package/dist/libs/contracts/dist/server/rest-elysia.js +1 -1
  137. package/dist/libs/contracts/dist/server/rest-express.js +1 -1
  138. package/dist/libs/contracts/dist/server/rest-generic.js +1 -1
  139. package/dist/libs/contracts/dist/server/rest-next-app.js +1 -1
  140. package/dist/libs/contracts/dist/server/rest-next-pages.js +1 -1
  141. package/dist/libs/contracts/dist/spec.js +34 -1
  142. package/dist/libs/contracts/dist/telemetry/index.js +1 -1
  143. package/dist/libs/contracts/dist/telemetry/tracker.js +1 -1
  144. package/dist/libs/contracts/dist/tests/index.js +1 -1
  145. package/dist/libs/contracts/dist/tests/runner.js +2 -1
  146. package/dist/libs/contracts/dist/workflow/index.js +1 -1
  147. package/dist/libs/contracts/dist/workflow/runner.js +1 -1
  148. package/dist/libs/schema/dist/EnumType.js +2 -1
  149. package/dist/libs/schema/dist/FieldType.js +49 -1
  150. package/dist/libs/schema/dist/ScalarTypeEnum.js +236 -1
  151. package/dist/libs/schema/dist/SchemaModel.js +39 -1
  152. package/dist/libs/schema/dist/entity/defineEntity.js +236 -1
  153. package/dist/libs/schema/dist/entity/index.js +2 -1
  154. package/dist/libs/schema/dist/entity/types.js +1 -1
  155. package/dist/libs/schema/dist/index.js +6 -1
  156. package/package.json +5 -5
@@ -1,383 +1,16 @@
1
- import{a as e}from"../registry.js";e([{id:`docs.tech.PHASE_1_QUICKSTART`,title:`Phase 1: API Reference Index`,summary:`Quick reference for all new Phase 1 APIs.`,kind:`reference`,visibility:`public`,route:`/docs/tech/PHASE_1_QUICKSTART`,tags:[`tech`,`PHASE_1_QUICKSTART`],body:`# Phase 1: API Reference Index
2
-
3
- Quick reference for all new Phase 1 APIs.
4
-
5
- ---
6
-
7
- ## @lssm/lib.multi-tenancy
8
-
9
- ### RLS
10
- \`\`\`typescript
11
- import { createRlsMiddleware, type TenantIdProvider } from '@lssm/lib.multi-tenancy/rls';
12
- \`\`\`
13
-
14
- ### Provisioning
15
- \`\`\`typescript
16
- import {
17
- TenantProvisioningService,
18
- type CreateTenantInput,
19
- type TenantProvisioningConfig
20
- } from '@lssm/lib.multi-tenancy/provisioning';
21
- \`\`\`
22
-
23
- ### Isolation
24
- \`\`\`typescript
25
- import { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';
26
- \`\`\`
27
-
28
- ---
29
-
30
- ## @lssm/lib.observability
31
-
32
- ### Tracing
33
- \`\`\`typescript
34
- import {
35
- getTracer,
36
- traceAsync,
37
- traceSync,
38
- createTracingMiddleware
39
- } from '@lssm/lib.observability/tracing';
40
- \`\`\`
41
-
42
- ### Metrics
43
- \`\`\`typescript
44
- import {
45
- getMeter,
46
- createCounter,
47
- createUpDownCounter,
48
- createHistogram,
49
- standardMetrics
50
- } from '@lssm/lib.observability/metrics';
51
- \`\`\`
52
-
53
- ### Logging
54
- \`\`\`typescript
55
- import {
56
- Logger,
57
- logger,
58
- type LogLevel,
59
- type LogEntry
60
- } from '@lssm/lib.observability/logging';
61
- \`\`\`
62
-
63
- ---
64
-
65
- ## @lssm/lib.resilience
66
-
67
- ### Circuit Breaker
68
- \`\`\`typescript
69
- import {
70
- CircuitBreaker,
71
- type CircuitState,
72
- type CircuitBreakerConfig
73
- } from '@lssm/lib.resilience/circuit-breaker';
74
- \`\`\`
75
-
76
- ### Retry
77
- \`\`\`typescript
78
- import { retry } from '@lssm/lib.resilience/retry';
79
- \`\`\`
80
-
81
- ### Timeout
82
- \`\`\`typescript
83
- import { timeout } from '@lssm/lib.resilience/timeout';
84
- \`\`\`
85
-
86
- ### Fallback
87
- \`\`\`typescript
88
- import { fallback } from '@lssm/lib.resilience/fallback';
89
- \`\`\`
90
-
91
- ---
92
-
93
- ## Enhanced: @lssm/lib.contracts
94
-
95
- ### DataViews
96
- \`\`\`typescript
97
- import { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';
98
- import { DataViewRuntime } from '@lssm/lib.contracts/data-views/runtime';
99
- \`\`\`
100
-
101
- ### Workflows
102
- \`\`\`typescript
103
- import { SLAMonitor, type SLABreachEvent } from '@lssm/lib.contracts/workflow/sla-monitor';
104
- import { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';
105
- \`\`\`
106
-
107
- ---
108
-
109
- ## Enhanced: @lssm/lib.design-system
110
-
111
- ### DataView Components
112
- \`\`\`typescript
113
- import { DataViewRenderer } from '@lssm/lib.design-system/components/data-view/DataViewRenderer';
114
- // Also available: DataViewList, DataViewTable, DataViewDetail
115
- \`\`\`
116
-
117
- ---
118
-
119
- ## Usage Examples
120
-
121
- ### Complete Workflow with All Features
122
-
123
- \`\`\`typescript
124
- import { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';
125
- import { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';
126
- import { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';
127
- import { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';
128
- import { traceAsync } from '@lssm/lib.observability/tracing';
129
-
130
- const runner = new WorkflowRunner({
131
- registry,
132
- stateStore: new PrismaStateStore(db),
133
- opExecutor: async (op, input, ctx) => {
134
- return traceAsync(\`op.\${op.name}\`, async (span) => {
135
- span.setAttribute('operation', op.name);
136
- const breaker = getCircuitBreaker(op.name);
137
- return breaker.execute(() => executeOperation(op, input, ctx));
138
- });
139
- },
140
- eventEmitter: (event, payload) => {
141
- if (event.startsWith('workflow.')) {
142
- logger.info(event, payload);
143
- }
144
- },
145
- });
146
-
147
- const monitor = new SLAMonitor((event, payload) => {
148
- logger.warn('SLA_BREACH', payload);
149
- alertOps(payload);
150
- });
151
-
152
- // Start workflow
153
- const workflowId = await runner.start('payment.flow', 1);
154
-
155
- // Monitor SLA
156
- const state = await runner.getState(workflowId);
157
- const spec = registry.get('payment.flow', 1);
158
- monitor.check(state, spec!);
159
- \`\`\`
160
-
161
- ### Complete DataView with Observability
162
-
163
- \`\`\`typescript
164
- import { DataViewRenderer } from '@lssm/lib.design-system';
165
- import { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';
166
- import { traceAsync } from '@lssm/lib.observability/tracing';
167
- import { MyDataView } from './specs/users.data-view';
168
-
169
- export function UserListPage() {
170
- const [page, setPage] = useState(1);
171
- const [users, setUsers] = useState([]);
172
-
173
- const loadUsers = async () => {
174
- return traceAsync('load_users', async (span) => {
175
- const generator = new DataViewQueryGenerator(MyDataView);
176
- const query = generator.generate({ pagination: { page, pageSize: 20 } });
177
-
178
- span.setAttribute('page', page);
179
- const result = await api.execute(query);
180
- setUsers(result.data);
181
- });
182
- };
183
-
184
- return (
185
- <DataViewRenderer
186
- spec={MyDataView}
187
- items={users}
188
- pagination={{ page, pageSize: 20, total: users.length }}
189
- onPageChange={setPage}
190
- />
191
- );
192
- }
193
- \`\`\`
194
-
195
- ### Complete Multi-Tenant Setup
196
-
197
- \`\`\`typescript
198
- // 1. RLS Middleware
199
- import { createRlsMiddleware } from '@lssm/lib.multi-tenancy/rls';
200
- db.$use(createRlsMiddleware(() => req.tenantId));
201
-
202
- // 2. Tenant Provisioning
203
- import { TenantProvisioningService } from '@lssm/lib.multi-tenancy/provisioning';
204
- const service = new TenantProvisioningService({ db });
205
-
206
- // 3. Create new tenant
207
- await service.provision({
208
- id: 'acme',
209
- name: 'Acme Corp',
210
- slug: 'acme',
211
- ownerEmail: 'admin@acme.com',
212
- });
213
-
214
- // 4. Validate isolation in tests
215
- import { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';
216
-
217
- test('queries are isolated', () => {
218
- const isValid = IsolationValidator.validateQuery(
219
- 'User',
220
- 'findMany',
221
- { where: { tenantId: 'acme' } },
222
- 'acme'
223
- );
224
- expect(isValid).toBe(true);
225
- });
226
- \`\`\`
227
-
228
- ---
229
-
230
- ## Testing
231
-
232
- ### Test Circuit Breakers
233
-
234
- \`\`\`typescript
235
- import { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';
236
-
237
- test('circuit opens after threshold', async () => {
238
- const breaker = new CircuitBreaker({
239
- failureThreshold: 3,
240
- resetTimeoutMs: 5000,
241
- });
242
-
243
- // Trigger failures
244
- for (let i = 0; i < 3; i++) {
245
- await expect(
246
- breaker.execute(() => Promise.reject('error'))
247
- ).rejects.toThrow();
248
- }
249
-
250
- // Circuit should be open
251
- await expect(
252
- breaker.execute(() => Promise.resolve('ok'))
253
- ).rejects.toThrow('CircuitBreaker is OPEN');
254
- });
255
- \`\`\`
256
-
257
- ### Test Workflow Retry
258
-
259
- \`\`\`typescript
260
- test('workflow retries on failure', async () => {
261
- let attempts = 0;
262
- const opExecutor = async () => {
263
- attempts++;
264
- if (attempts < 3) throw new Error('fail');
265
- return 'success';
266
- };
267
-
268
- const runner = new WorkflowRunner({ /* ... */ opExecutor });
269
- await runner.executeStep(workflowId);
270
-
271
- expect(attempts).toBe(3);
272
- });
273
- \`\`\`
274
-
275
- ---
276
-
277
- ## Common Patterns
278
-
279
- ### Pattern: Resilient External Call
280
-
281
- \`\`\`typescript
282
- import { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';
283
- import { retry } from '@lssm/lib.resilience/retry';
284
- import { timeout } from '@lssm/lib.resilience/timeout';
285
- import { traceAsync } from '@lssm/lib.observability/tracing';
286
-
287
- const breaker = new CircuitBreaker({ failureThreshold: 5, resetTimeoutMs: 30000 });
288
-
289
- export async function callExternalAPI(input: any) {
290
- return traceAsync('external_api_call', async (span) => {
291
- span.setAttribute('service', 'stripe');
292
-
293
- return breaker.execute(() =>
294
- retry(
295
- () => timeout(() => stripe.api.call(input), 5000),
296
- 3,
297
- 1000,
298
- true
299
- )
300
- );
301
- });
302
- }
303
- \`\`\`
304
-
305
- **Benefits**: Circuit breaker + retry + timeout + tracing in one place.
306
-
307
- ---
308
-
309
- ### Pattern: Tenant-Aware Operation
310
-
311
- \`\`\`typescript
312
- import { traceAsync } from '@lssm/lib.observability/tracing';
313
-
314
- export async function listUsers(tenantId: string) {
315
- return traceAsync('list_users', async (span) => {
316
- span.setAttribute('tenant_id', tenantId);
317
-
318
- // RLS middleware will inject WHERE tenantId = ?
319
- return db.user.findMany();
320
- });
321
- }
322
- \`\`\`
323
-
324
- ---
325
-
326
- ### Pattern: Monitored Workflow
327
-
328
- \`\`\`typescript
329
- import { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';
330
- import { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';
331
- import { logger } from '@lssm/lib.observability/logging';
332
-
333
- const monitor = new SLAMonitor((event, payload) => {
334
- logger.warn('workflow.sla_breach', payload);
335
- });
336
-
337
- // In workflow poller
338
- const state = await runner.getState(workflowId);
339
- const spec = registry.get(state.workflowName, state.workflowVersion);
340
- if (spec) {
341
- monitor.check(state, spec);
342
- }
343
- \`\`\`
344
-
345
- ---
346
-
347
- ## Next Steps
348
-
349
- 1. **Implement one quick win** (30 minutes)
350
- 2. **Add tests for new functionality** (1 hour)
351
- 3. **Deploy to staging and verify observability** (1 hour)
352
- 4. **Roll out to production** (monitor closely)
353
- 5. **Read full documentation** at https://contractspec.lssm.tech/docs
354
-
355
- ---
356
-
357
- **Questions?** See \`/docs/guides/phase-1-migration\` or reach out via https://contractspec.lssm.tech/contact
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
- `}]);
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_1_QUICKSTART.docblock.js
4
+ const tech_PHASE_1_QUICKSTART_DocBlocks = [{
5
+ id: "docs.tech.PHASE_1_QUICKSTART",
6
+ title: "Phase 1: API Reference Index",
7
+ summary: "Quick reference for all new Phase 1 APIs.",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_1_QUICKSTART",
11
+ tags: ["tech", "PHASE_1_QUICKSTART"],
12
+ body: "# Phase 1: API Reference Index\n\nQuick reference for all new Phase 1 APIs.\n\n---\n\n## @lssm/lib.multi-tenancy\n\n### RLS\n```typescript\nimport { createRlsMiddleware, type TenantIdProvider } from '@lssm/lib.multi-tenancy/rls';\n```\n\n### Provisioning\n```typescript\nimport { \n TenantProvisioningService,\n type CreateTenantInput,\n type TenantProvisioningConfig \n} from '@lssm/lib.multi-tenancy/provisioning';\n```\n\n### Isolation\n```typescript\nimport { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';\n```\n\n---\n\n## @lssm/lib.observability\n\n### Tracing\n```typescript\nimport { \n getTracer,\n traceAsync,\n traceSync,\n createTracingMiddleware \n} from '@lssm/lib.observability/tracing';\n```\n\n### Metrics\n```typescript\nimport {\n getMeter,\n createCounter,\n createUpDownCounter,\n createHistogram,\n standardMetrics\n} from '@lssm/lib.observability/metrics';\n```\n\n### Logging\n```typescript\nimport {\n Logger,\n logger,\n type LogLevel,\n type LogEntry\n} from '@lssm/lib.observability/logging';\n```\n\n---\n\n## @lssm/lib.resilience\n\n### Circuit Breaker\n```typescript\nimport {\n CircuitBreaker,\n type CircuitState,\n type CircuitBreakerConfig\n} from '@lssm/lib.resilience/circuit-breaker';\n```\n\n### Retry\n```typescript\nimport { retry } from '@lssm/lib.resilience/retry';\n```\n\n### Timeout\n```typescript\nimport { timeout } from '@lssm/lib.resilience/timeout';\n```\n\n### Fallback\n```typescript\nimport { fallback } from '@lssm/lib.resilience/fallback';\n```\n\n---\n\n## Enhanced: @lssm/lib.contracts\n\n### DataViews\n```typescript\nimport { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';\nimport { DataViewRuntime } from '@lssm/lib.contracts/data-views/runtime';\n```\n\n### Workflows\n```typescript\nimport { SLAMonitor, type SLABreachEvent } from '@lssm/lib.contracts/workflow/sla-monitor';\nimport { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';\n```\n\n---\n\n## Enhanced: @lssm/lib.design-system\n\n### DataView Components\n```typescript\nimport { DataViewRenderer } from '@lssm/lib.design-system/components/data-view/DataViewRenderer';\n// Also available: DataViewList, DataViewTable, DataViewDetail\n```\n\n---\n\n## Usage Examples\n\n### Complete Workflow with All Features\n\n```typescript\nimport { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';\nimport { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';\nimport { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';\nimport { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';\nimport { traceAsync } from '@lssm/lib.observability/tracing';\n\nconst runner = new WorkflowRunner({\n registry,\n stateStore: new PrismaStateStore(db),\n opExecutor: async (op, input, ctx) => {\n return traceAsync(`op.${op.name}`, async (span) => {\n span.setAttribute('operation', op.name);\n const breaker = getCircuitBreaker(op.name);\n return breaker.execute(() => executeOperation(op, input, ctx));\n });\n },\n eventEmitter: (event, payload) => {\n if (event.startsWith('workflow.')) {\n logger.info(event, payload);\n }\n },\n});\n\nconst monitor = new SLAMonitor((event, payload) => {\n logger.warn('SLA_BREACH', payload);\n alertOps(payload);\n});\n\n// Start workflow\nconst workflowId = await runner.start('payment.flow', 1);\n\n// Monitor SLA\nconst state = await runner.getState(workflowId);\nconst spec = registry.get('payment.flow', 1);\nmonitor.check(state, spec!);\n```\n\n### Complete DataView with Observability\n\n```typescript\nimport { DataViewRenderer } from '@lssm/lib.design-system';\nimport { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';\nimport { traceAsync } from '@lssm/lib.observability/tracing';\nimport { MyDataView } from './specs/users.data-view';\n\nexport function UserListPage() {\n const [page, setPage] = useState(1);\n const [users, setUsers] = useState([]);\n\n const loadUsers = async () => {\n return traceAsync('load_users', async (span) => {\n const generator = new DataViewQueryGenerator(MyDataView);\n const query = generator.generate({ pagination: { page, pageSize: 20 } });\n \n span.setAttribute('page', page);\n const result = await api.execute(query);\n setUsers(result.data);\n });\n };\n\n return (\n <DataViewRenderer\n spec={MyDataView}\n items={users}\n pagination={{ page, pageSize: 20, total: users.length }}\n onPageChange={setPage}\n />\n );\n}\n```\n\n### Complete Multi-Tenant Setup\n\n```typescript\n// 1. RLS Middleware\nimport { createRlsMiddleware } from '@lssm/lib.multi-tenancy/rls';\ndb.$use(createRlsMiddleware(() => req.tenantId));\n\n// 2. Tenant Provisioning\nimport { TenantProvisioningService } from '@lssm/lib.multi-tenancy/provisioning';\nconst service = new TenantProvisioningService({ db });\n\n// 3. Create new tenant\nawait service.provision({\n id: 'acme',\n name: 'Acme Corp',\n slug: 'acme',\n ownerEmail: 'admin@acme.com',\n});\n\n// 4. Validate isolation in tests\nimport { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';\n\ntest('queries are isolated', () => {\n const isValid = IsolationValidator.validateQuery(\n 'User',\n 'findMany',\n { where: { tenantId: 'acme' } },\n 'acme'\n );\n expect(isValid).toBe(true);\n});\n```\n\n---\n\n## Testing\n\n### Test Circuit Breakers\n\n```typescript\nimport { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';\n\ntest('circuit opens after threshold', async () => {\n const breaker = new CircuitBreaker({\n failureThreshold: 3,\n resetTimeoutMs: 5000,\n });\n\n // Trigger failures\n for (let i = 0; i < 3; i++) {\n await expect(\n breaker.execute(() => Promise.reject('error'))\n ).rejects.toThrow();\n }\n\n // Circuit should be open\n await expect(\n breaker.execute(() => Promise.resolve('ok'))\n ).rejects.toThrow('CircuitBreaker is OPEN');\n});\n```\n\n### Test Workflow Retry\n\n```typescript\ntest('workflow retries on failure', async () => {\n let attempts = 0;\n const opExecutor = async () => {\n attempts++;\n if (attempts < 3) throw new Error('fail');\n return 'success';\n };\n\n const runner = new WorkflowRunner({ /* ... */ opExecutor });\n await runner.executeStep(workflowId);\n \n expect(attempts).toBe(3);\n});\n```\n\n---\n\n## Common Patterns\n\n### Pattern: Resilient External Call\n\n```typescript\nimport { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';\nimport { retry } from '@lssm/lib.resilience/retry';\nimport { timeout } from '@lssm/lib.resilience/timeout';\nimport { traceAsync } from '@lssm/lib.observability/tracing';\n\nconst breaker = new CircuitBreaker({ failureThreshold: 5, resetTimeoutMs: 30000 });\n\nexport async function callExternalAPI(input: any) {\n return traceAsync('external_api_call', async (span) => {\n span.setAttribute('service', 'stripe');\n \n return breaker.execute(() =>\n retry(\n () => timeout(() => stripe.api.call(input), 5000),\n 3,\n 1000,\n true\n )\n );\n });\n}\n```\n\n**Benefits**: Circuit breaker + retry + timeout + tracing in one place.\n\n---\n\n### Pattern: Tenant-Aware Operation\n\n```typescript\nimport { traceAsync } from '@lssm/lib.observability/tracing';\n\nexport async function listUsers(tenantId: string) {\n return traceAsync('list_users', async (span) => {\n span.setAttribute('tenant_id', tenantId);\n \n // RLS middleware will inject WHERE tenantId = ?\n return db.user.findMany();\n });\n}\n```\n\n---\n\n### Pattern: Monitored Workflow\n\n```typescript\nimport { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';\nimport { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';\nimport { logger } from '@lssm/lib.observability/logging';\n\nconst monitor = new SLAMonitor((event, payload) => {\n logger.warn('workflow.sla_breach', payload);\n});\n\n// In workflow poller\nconst state = await runner.getState(workflowId);\nconst spec = registry.get(state.workflowName, state.workflowVersion);\nif (spec) {\n monitor.check(state, spec);\n}\n```\n\n---\n\n## Next Steps\n\n1. **Implement one quick win** (30 minutes)\n2. **Add tests for new functionality** (1 hour)\n3. **Deploy to staging and verify observability** (1 hour)\n4. **Roll out to production** (monitor closely)\n5. **Read full documentation** at https://contractspec.lssm.tech/docs\n\n---\n\n**Questions?** See `/docs/guides/phase-1-migration` or reach out via https://contractspec.lssm.tech/contact\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_1_QUICKSTART_DocBlocks);
15
+
16
+ //#endregion
@@ -1,68 +1,16 @@
1
- import{a as e}from"../registry.js";e([{id:`docs.tech.PHASE_2_AI_NATIVE_OPERATIONS`,title:`Phase 2: AI-Native Operations`,summary:`_Last updated: 2025-11-20_`,kind:`reference`,visibility:`public`,route:`/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS`,tags:[`tech`,`PHASE_2_AI_NATIVE_OPERATIONS`],body:`# Phase 2: AI-Native Operations
2
-
3
- _Last updated: 2025-11-20_
4
-
5
- Phase 2 turns ContractSpec into an AI-first operations stack. The new libraries below are the building blocks used by support bots, growth agents, and human-in-the-loop flows.
6
-
7
- ## Libraries
8
-
9
- ### @lssm/lib.ai-agent
10
-
11
- - **Spec + Registry**: \`defineAgent\`, \`AgentRegistry\` keep agent definitions type-safe.
12
- - **Runner**: \`AgentRunner\` drives LLM conversations, tool calls, retries, escalation, and telemetry hooks.
13
- - **Tools**: \`ToolExecutor\` standardizes schema validation + timeouts.
14
- - **Memory**: \`InMemoryAgentMemory\` + interfaces for plugging persistent stores.
15
- - **Approvals**: new \`ApprovalWorkflow\` + \`InMemoryApprovalStore\` capture low-confidence decisions and surface them to reviewers.
16
-
17
- ### @lssm/lib.support-bot
18
-
19
- Composable support automation primitives:
20
-
21
- - \`TicketClassifier\` → heuristics + optional LLM validation for category, priority, sentiment.
22
- - \`TicketResolver\` → RAG pipeline backed by knowledge spaces.
23
- - \`AutoResponder\` → tone-aware drafts with citations.
24
- - \`SupportFeedbackLoop\` → tracks resolution rates.
25
- - \`createSupportTools\` → ready-made tool definitions for AgentRunner.
26
-
27
- ### @lssm/lib.content-gen
28
-
29
- Content generators that consume a \`ContentBrief\` and output production-ready assets:
30
-
31
- - \`BlogGenerator\`, \`LandingPageGenerator\`, \`EmailCampaignGenerator\`, \`SocialPostGenerator\`.
32
- - \`SeoOptimizer\` builds metadata + schema markup.
33
-
34
- ### @lssm/lib.analytics
35
-
36
- Queryless analytics helpers:
37
-
38
- - \`FunnelAnalyzer\` – conversion/drop-off per step.
39
- - \`CohortTracker\` – retention + LTV per cohort.
40
- - \`ChurnPredictor\` – recency/frequency/error scoring.
41
- - \`GrowthHypothesisGenerator\` – surfaces experiment ideas from metric trends.
42
-
43
- ### @lssm/lib.growth
44
-
45
- A/B testing toolkit:
46
-
47
- - \`ExperimentRegistry\` + \`ExperimentRunner\` – deterministic bucketing.
48
- - \`ExperimentTracker\` – persist exposures + metrics.
49
- - \`StatsEngine\` – Welch’s t-test + improvement calculations.
50
-
51
- ### Human-in-the-loop UI
52
-
53
- \`@lssm/lib.design-system\` now exposes:
54
-
55
- - \`ApprovalQueue\` – list + act on pending approvals.
56
- - \`AgentMonitor\` – live view of agent sessions with confidence + status.
57
-
58
- ## Examples
59
-
60
- - \`examples/ai-support-bot/setup.ts\` shows ticket classification → resolution → response draft.
61
- - \`examples/content-generation/generate.ts\` produces blog, landing, email, social, SEO output from one brief.
62
-
63
- ## Next Steps
64
-
65
- 1. Wire these libraries into vertical apps (H-Circle, ArtisanOS, etc.).
66
- 2. Add background workers that consume the new analytics/growth trackers.
67
- 3. Expand web-landing to highlight these Phase 2 capabilities (see separate TODO).
68
- `}]);
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.js
4
+ const tech_PHASE_2_AI_NATIVE_OPERATIONS_DocBlocks = [{
5
+ id: "docs.tech.PHASE_2_AI_NATIVE_OPERATIONS",
6
+ title: "Phase 2: AI-Native Operations",
7
+ summary: "_Last updated: 2025-11-20_",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS",
11
+ tags: ["tech", "PHASE_2_AI_NATIVE_OPERATIONS"],
12
+ body: "# Phase 2: AI-Native Operations\n\n_Last updated: 2025-11-20_\n\nPhase 2 turns ContractSpec into an AI-first operations stack. The new libraries below are the building blocks used by support bots, growth agents, and human-in-the-loop flows.\n\n## Libraries\n\n### @lssm/lib.ai-agent\n\n- **Spec + Registry**: `defineAgent`, `AgentRegistry` keep agent definitions type-safe.\n- **Runner**: `AgentRunner` drives LLM conversations, tool calls, retries, escalation, and telemetry hooks.\n- **Tools**: `ToolExecutor` standardizes schema validation + timeouts.\n- **Memory**: `InMemoryAgentMemory` + interfaces for plugging persistent stores.\n- **Approvals**: new `ApprovalWorkflow` + `InMemoryApprovalStore` capture low-confidence decisions and surface them to reviewers.\n\n### @lssm/lib.support-bot\n\nComposable support automation primitives:\n\n- `TicketClassifier` → heuristics + optional LLM validation for category, priority, sentiment.\n- `TicketResolver` → RAG pipeline backed by knowledge spaces.\n- `AutoResponder` → tone-aware drafts with citations.\n- `SupportFeedbackLoop` → tracks resolution rates.\n- `createSupportTools` → ready-made tool definitions for AgentRunner.\n\n### @lssm/lib.content-gen\n\nContent generators that consume a `ContentBrief` and output production-ready assets:\n\n- `BlogGenerator`, `LandingPageGenerator`, `EmailCampaignGenerator`, `SocialPostGenerator`.\n- `SeoOptimizer` builds metadata + schema markup.\n\n### @lssm/lib.analytics\n\nQueryless analytics helpers:\n\n- `FunnelAnalyzer` – conversion/drop-off per step.\n- `CohortTracker` – retention + LTV per cohort.\n- `ChurnPredictor` – recency/frequency/error scoring.\n- `GrowthHypothesisGenerator` – surfaces experiment ideas from metric trends.\n\n### @lssm/lib.growth\n\nA/B testing toolkit:\n\n- `ExperimentRegistry` + `ExperimentRunner` – deterministic bucketing.\n- `ExperimentTracker` – persist exposures + metrics.\n- `StatsEngine` – Welch’s t-test + improvement calculations.\n\n### Human-in-the-loop UI\n\n`@lssm/lib.design-system` now exposes:\n\n- `ApprovalQueue` – list + act on pending approvals.\n- `AgentMonitor` – live view of agent sessions with confidence + status.\n\n## Examples\n\n- `examples/ai-support-bot/setup.ts` shows ticket classification → resolution → response draft.\n- `examples/content-generation/generate.ts` produces blog, landing, email, social, SEO output from one brief.\n\n## Next Steps\n\n1. Wire these libraries into vertical apps (H-Circle, ArtisanOS, etc.).\n2. Add background workers that consume the new analytics/growth trackers.\n3. Expand web-landing to highlight these Phase 2 capabilities (see separate TODO).\n"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_2_AI_NATIVE_OPERATIONS_DocBlocks);
15
+
16
+ //#endregion
@@ -1,140 +1,16 @@
1
- import{a as e}from"../registry.js";e([{id:`docs.tech.PHASE_3_AUTO_EVOLUTION`,title:`Phase 3: Auto-Evolution Technical Notes`,summary:`**Status**: In progress`,kind:`reference`,visibility:`public`,route:`/docs/tech/PHASE_3_AUTO_EVOLUTION`,tags:[`tech`,`PHASE_3_AUTO_EVOLUTION`],body:`# Phase 3: Auto-Evolution Technical Notes
2
-
3
- **Status**: In progress
4
- **Last updated**: 2025-11-21
5
-
6
- Phase 3 introduces self-learning capabilities that analyze production telemetry, suggest new specs, safely roll out variants, and generate golden tests from real traffic. This document captures the main building blocks delivered in this iteration.
7
-
8
- ---
9
-
10
- ## 1. Libraries
11
-
12
- ### @lssm/lib.evolution
13
-
14
- - \`SpecAnalyzer\` converts raw telemetry samples into usage stats + anomalies.
15
- - \`SpecGenerator\` produces \`SpecSuggestion\` objects and validates confidence thresholds.
16
- - \`SpecSuggestionOrchestrator\` routes proposals through the AI approval workflow and writes approved specs to \`packages/libs/contracts/src/generated\`.
17
- - Storage adapters:
18
- - \`InMemorySpecSuggestionRepository\` for tests.
19
- - \`PrismaSpecSuggestionRepository\` persists to the new Prisma model (see §4).
20
- - \`FileSystemSuggestionWriter\` emits JSON envelopes for git review.
21
-
22
- ### @lssm/lib.observability
23
-
24
- - Added intent detection modules:
25
- - \`IntentAggregator\` batches telemetry into rolling windows.
26
- - \`IntentDetector\` surfaces latency/error/throughput regressions and sequential intents.
27
- - \`EvolutionPipeline\` orchestrates aggregation → detection → intent events and exposes hooks for downstream orchestrators.
28
- - \`createTracingMiddleware\` now accepts \`resolveOperation\`/\`onSample\` hooks to feed telemetry samples into the pipeline.
29
-
30
- ### @lssm/lib.growth
31
-
32
- - New \`spec-experiments\` module:
33
- - \`SpecExperimentRegistry\`, \`SpecExperimentRunner\`, \`SpecExperimentAdapter\`.
34
- - \`SpecExperimentAnalyzer\` + \`SpecExperimentController\` handle guardrails and staged rollouts.
35
- - Helper \`createSpecVariantResolver\` plugs directly into \`HandlerCtx.specVariantResolver\`.
36
- - \`SpecVariantResolver\` is now a first-class concept in \`@lssm/lib.contracts\`. The runtime will attempt to execute variant specs before falling back to the registered handler.
37
-
38
- ### @lssm/lib.testing
39
-
40
- - \`TrafficRecorder\` + \`TrafficStore\` capture production requests with sampling and sanitization hooks.
41
- - \`GoldenTestGenerator\` converts \`TrafficSnapshot\`s into Vitest/Jest suites.
42
- - \`generateVitestSuite\` / \`generateJestSuite\` output self-contained test files, and \`runGoldenTests\` offers a programmatic harness for CI pipelines.
43
-
44
- ---
45
-
46
- ## 2. Telemetry → Intent → Spec Pipeline
47
-
48
- 1. \`createTracingMiddleware({ onSample })\` emits \`TelemetrySample\`s for every HTTP request.
49
- 2. \`IntentAggregator\` groups samples into statistical windows (default 15 minutes).
50
- 3. \`IntentDetector\` raises signals for:
51
- - Error spikes
52
- - Latency regressions
53
- - Throughput drops
54
- - Sequential workflows that hint at missing specs
55
- 4. \`EvolutionPipeline\` emits \`intent.detected\` events and hands them to \`SpecGenerator\`.
56
- 5. \`SpecSuggestionOrchestrator\` persists suggestions, triggers approval workflows, and—upon approval—writes JSON envelopes to \`packages/.../contracts/src/generated\`.
57
-
58
- ---
59
-
60
- ## 3. Spec Experiments & Rollouts
61
-
62
- 1. Register spec experiments in \`SpecExperimentRegistry\` with control + variant bindings.
63
- 2. Expose bucketed specs by attaching \`createSpecVariantResolver\` to \`HandlerCtx.specVariantResolver\` inside adapters.
64
- 3. Record outcomes via \`SpecExperimentAdapter.trackOutcome()\` (latency + error metrics).
65
- 4. \`SpecExperimentController\` uses guardrails from config and \`SpecExperimentAnalyzer\` to:
66
- - Auto-rollback on error/latency breaches.
67
- - Advance rollout stages (1% → 10% → 50% → 100%) when metrics stay green.
68
-
69
- ---
70
-
71
- ## 4. Data Models (Prisma)
72
-
73
- File: \`packages/libs/database/prisma/schema.prisma\`
74
-
75
- - \`SpecSuggestion\` – stores serialized suggestion payloads + statuses.
76
- - \`IntentSnapshot\` – captured detector output for auditing/training.
77
- - \`TrafficSnapshot\` – persisted production traffic (input/output/error blobs).
78
- - \`SpecExperiment\` / \`SpecExperimentMetric\` – rollout state + metrics for each variant.
79
-
80
- > Run \`bun database generate\` after pulling to refresh the Prisma client.
81
-
82
- ---
83
-
84
- ## 5. Golden Test Workflow
85
-
86
- 1. Capture traffic via middleware or direct \`TrafficRecorder.record\`.
87
- 2. Use the new CLI command to materialize suites:
88
-
89
- \`\`\`bash
90
- contractspec test generate \\
91
- --operation billing.createInvoice \\
92
- --output tests/billing.createInvoice.golden.test.ts \\
93
- --runner-import ./tests/run-operation \\
94
- --runner-fn runBillingCommand \\
95
- --from-production \\
96
- --days 7 \\
97
- --sample-rate 0.05
98
- \`\`\`
99
-
100
- 3. Generated files import your runner and assert against recorded outputs (or expected errors for negative paths).
101
-
102
- ---
103
-
104
- ## 6. Operational Notes
105
-
106
- - **Approvals**: By default, every suggestion still requires human approval. \`EvolutionConfig.autoApproveThreshold\` can be tuned per environment but should remain conservative (<0.3) until OverlaySpec tooling lands.
107
- - **Sampling**: Keep \`TrafficRecorder.sampleRate\` ≤ 0.05 in production to avoid sensitive payload storage; scrub PII through the \`sanitize\` callback before persistence.
108
- - **Rollouts**: Guardrails default to 5% error-rate and 750ms P99 latency. Override per experiment to match SLOs.
109
-
110
- ---
111
-
112
- ## 7. Next Steps
113
-
114
- 1. Wire \`SpecExperimentAdapter.trackOutcome\` into adapters (REST, GraphQL, Workers) so every execution logs metrics automatically.
115
- 2. Add a UI for reviewing \`SpecSuggestion\` objects alongside approval status.
116
- 3. Expand \`TrafficRecorder\` to ship directly to the Prisma-backed store (currently in-memory by default).
117
- 4. Integrate \`EvolutionPipeline\` events with the Regenerator to close the loop (auto-open proposals + attach evidence).
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
- `}]);
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.js
4
+ const tech_PHASE_3_AUTO_EVOLUTION_DocBlocks = [{
5
+ id: "docs.tech.PHASE_3_AUTO_EVOLUTION",
6
+ title: "Phase 3: Auto-Evolution Technical Notes",
7
+ summary: "**Status**: In progress",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_3_AUTO_EVOLUTION",
11
+ tags: ["tech", "PHASE_3_AUTO_EVOLUTION"],
12
+ body: "# Phase 3: Auto-Evolution Technical Notes\n\n**Status**: In progress \n**Last updated**: 2025-11-21 \n\nPhase 3 introduces self-learning capabilities that analyze production telemetry, suggest new specs, safely roll out variants, and generate golden tests from real traffic. This document captures the main building blocks delivered in this iteration.\n\n---\n\n## 1. Libraries\n\n### @lssm/lib.evolution\n\n- `SpecAnalyzer` converts raw telemetry samples into usage stats + anomalies.\n- `SpecGenerator` produces `SpecSuggestion` objects and validates confidence thresholds.\n- `SpecSuggestionOrchestrator` routes proposals through the AI approval workflow and writes approved specs to `packages/libs/contracts/src/generated`.\n- Storage adapters:\n - `InMemorySpecSuggestionRepository` for tests.\n - `PrismaSpecSuggestionRepository` persists to the new Prisma model (see §4).\n - `FileSystemSuggestionWriter` emits JSON envelopes for git review.\n\n### @lssm/lib.observability\n\n- Added intent detection modules:\n - `IntentAggregator` batches telemetry into rolling windows.\n - `IntentDetector` surfaces latency/error/throughput regressions and sequential intents.\n- `EvolutionPipeline` orchestrates aggregation → detection → intent events and exposes hooks for downstream orchestrators.\n- `createTracingMiddleware` now accepts `resolveOperation`/`onSample` hooks to feed telemetry samples into the pipeline.\n\n### @lssm/lib.growth\n\n- New `spec-experiments` module:\n - `SpecExperimentRegistry`, `SpecExperimentRunner`, `SpecExperimentAdapter`.\n - `SpecExperimentAnalyzer` + `SpecExperimentController` handle guardrails and staged rollouts.\n - Helper `createSpecVariantResolver` plugs directly into `HandlerCtx.specVariantResolver`.\n- `SpecVariantResolver` is now a first-class concept in `@lssm/lib.contracts`. The runtime will attempt to execute variant specs before falling back to the registered handler.\n\n### @lssm/lib.testing\n\n- `TrafficRecorder` + `TrafficStore` capture production requests with sampling and sanitization hooks.\n- `GoldenTestGenerator` converts `TrafficSnapshot`s into Vitest/Jest suites.\n- `generateVitestSuite` / `generateJestSuite` output self-contained test files, and `runGoldenTests` offers a programmatic harness for CI pipelines.\n\n---\n\n## 2. Telemetry → Intent → Spec Pipeline\n\n1. `createTracingMiddleware({ onSample })` emits `TelemetrySample`s for every HTTP request.\n2. `IntentAggregator` groups samples into statistical windows (default 15 minutes).\n3. `IntentDetector` raises signals for:\n - Error spikes\n - Latency regressions\n - Throughput drops\n - Sequential workflows that hint at missing specs\n4. `EvolutionPipeline` emits `intent.detected` events and hands them to `SpecGenerator`.\n5. `SpecSuggestionOrchestrator` persists suggestions, triggers approval workflows, and—upon approval—writes JSON envelopes to `packages/.../contracts/src/generated`.\n\n---\n\n## 3. Spec Experiments & Rollouts\n\n1. Register spec experiments in `SpecExperimentRegistry` with control + variant bindings.\n2. Expose bucketed specs by attaching `createSpecVariantResolver` to `HandlerCtx.specVariantResolver` inside adapters.\n3. Record outcomes via `SpecExperimentAdapter.trackOutcome()` (latency + error metrics).\n4. `SpecExperimentController` uses guardrails from config and `SpecExperimentAnalyzer` to:\n - Auto-rollback on error/latency breaches.\n - Advance rollout stages (1% → 10% → 50% → 100%) when metrics stay green.\n\n---\n\n## 4. Data Models (Prisma)\n\nFile: `packages/libs/database/prisma/schema.prisma`\n\n- `SpecSuggestion` – stores serialized suggestion payloads + statuses.\n- `IntentSnapshot` – captured detector output for auditing/training.\n- `TrafficSnapshot` – persisted production traffic (input/output/error blobs).\n- `SpecExperiment` / `SpecExperimentMetric` – rollout state + metrics for each variant.\n\n> Run `bun database generate` after pulling to refresh the Prisma client.\n\n---\n\n## 5. Golden Test Workflow\n\n1. Capture traffic via middleware or direct `TrafficRecorder.record`.\n2. Use the new CLI command to materialize suites:\n\n```bash\ncontractspec test generate \\\n --operation billing.createInvoice \\\n --output tests/billing.createInvoice.golden.test.ts \\\n --runner-import ./tests/run-operation \\\n --runner-fn runBillingCommand \\\n --from-production \\\n --days 7 \\\n --sample-rate 0.05\n```\n\n3. Generated files import your runner and assert against recorded outputs (or expected errors for negative paths).\n\n---\n\n## 6. Operational Notes\n\n- **Approvals**: By default, every suggestion still requires human approval. `EvolutionConfig.autoApproveThreshold` can be tuned per environment but should remain conservative (<0.3) until OverlaySpec tooling lands.\n- **Sampling**: Keep `TrafficRecorder.sampleRate` ≤ 0.05 in production to avoid sensitive payload storage; scrub PII through the `sanitize` callback before persistence.\n- **Rollouts**: Guardrails default to 5% error-rate and 750ms P99 latency. Override per experiment to match SLOs.\n\n---\n\n## 7. Next Steps\n\n1. Wire `SpecExperimentAdapter.trackOutcome` into adapters (REST, GraphQL, Workers) so every execution logs metrics automatically.\n2. Add a UI for reviewing `SpecSuggestion` objects alongside approval status.\n3. Expand `TrafficRecorder` to ship directly to the Prisma-backed store (currently in-memory by default).\n4. Integrate `EvolutionPipeline` events with the Regenerator to close the loop (auto-open proposals + attach evidence).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_3_AUTO_EVOLUTION_DocBlocks);
15
+
16
+ //#endregion