@lssm/lib.evolution 0.4.1 → 1.41.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 (33) hide show
  1. package/dist/analyzer/spec-analyzer.js +1 -1
  2. package/dist/approval/integration.js +1 -1
  3. package/dist/generator/ai-spec-generator.js +19 -0
  4. package/dist/generator/spec-generator.js +1 -1
  5. package/dist/index.js +1 -1
  6. package/package.json +19 -13
  7. package/dist/ai-agent/dist/approval/index.js +0 -1
  8. package/dist/ai-agent/dist/approval/workflow.js +0 -1
  9. package/dist/analyzer/spec-analyzer.d.ts +0 -34
  10. package/dist/approval/integration.d.ts +0 -42
  11. package/dist/generator/spec-generator.d.ts +0 -46
  12. package/dist/index.d.ts +0 -5
  13. package/dist/lifecycle/dist/index.js +0 -1
  14. package/dist/lifecycle/dist/types/axes.js +0 -1
  15. package/dist/lifecycle/dist/types/milestones.js +0 -1
  16. package/dist/lifecycle/dist/types/signals.js +0 -1
  17. package/dist/lifecycle/dist/types/stages.js +0 -1
  18. package/dist/lifecycle/dist/utils/formatters.js +0 -1
  19. package/dist/observability/dist/index.js +0 -1
  20. package/dist/observability/dist/intent/detector.js +0 -1
  21. package/dist/observability/dist/lifecycle/dist/index.js +0 -1
  22. package/dist/observability/dist/lifecycle/dist/types/axes.js +0 -1
  23. package/dist/observability/dist/lifecycle/dist/types/milestones.js +0 -1
  24. package/dist/observability/dist/lifecycle/dist/types/signals.js +0 -1
  25. package/dist/observability/dist/lifecycle/dist/types/stages.js +0 -1
  26. package/dist/observability/dist/lifecycle/dist/utils/formatters.js +0 -1
  27. package/dist/observability/dist/logging/index.js +0 -1
  28. package/dist/observability/dist/metrics/index.js +0 -1
  29. package/dist/observability/dist/pipeline/evolution-pipeline.js +0 -1
  30. package/dist/observability/dist/pipeline/lifecycle-pipeline.js +0 -1
  31. package/dist/observability/dist/tracing/index.js +0 -1
  32. package/dist/observability/dist/tracing/middleware.js +0 -1
  33. package/dist/types.d.ts +0 -131
@@ -1 +1 @@
1
- import"../observability/dist/index.js";import{e}from"../lifecycle/dist/types/stages.js";import"../lifecycle/dist/index.js";import{randomUUID as t}from"node:crypto";const n={minSampleSize:50,errorRateThreshold:.05,latencyP99ThresholdMs:750};var r=class{logger;minSampleSize;errorRateThreshold;latencyP99ThresholdMs;throughputDropThreshold;constructor(e={}){this.logger=e.logger,this.minSampleSize=e.minSampleSize??n.minSampleSize,this.errorRateThreshold=e.errorRateThreshold??n.errorRateThreshold,this.latencyP99ThresholdMs=e.latencyP99ThresholdMs??n.latencyP99ThresholdMs,this.throughputDropThreshold=e.throughputDropThreshold??.2}analyzeSpecUsage(e){if(!e.length)return this.logger?.debug(`SpecAnalyzer.analyzeSpecUsage.skip`,{reason:`no-samples`}),[];let t=new Map;for(let n of e){let e=this.operationKey(n),r=t.get(e)??[];r.push(n),t.set(e,r)}return[...t.values()].filter(e=>{let t=e.length>=this.minSampleSize;return t||this.logger?.debug(`SpecAnalyzer.analyzeSpecUsage.skipOperation`,{operation:this.operationKey(e[0]),sampleSize:e.length,minSampleSize:this.minSampleSize}),t}).map(e=>this.buildUsageStats(e))}detectAnomalies(e,t){let n=[];if(!e.length)return this.logger?.debug(`SpecAnalyzer.detectAnomalies.skip`,{reason:`no-stats`}),n;let r=new Map((t??[]).map(e=>[this.operationKey(e.operation),e]));for(let t of e){let e=[];if(t.errorRate>=this.errorRateThreshold){e.push({type:`telemetry`,description:`Error rate ${t.errorRate.toFixed(2)} exceeded threshold ${this.errorRateThreshold}`,data:{errorRate:t.errorRate}}),n.push({operation:t.operation,severity:this.toSeverity(t.errorRate/this.errorRateThreshold),metric:`error-rate`,description:`Error rate spike`,detectedAt:new Date,threshold:this.errorRateThreshold,observedValue:t.errorRate,evidence:e});continue}if(t.p99LatencyMs>=this.latencyP99ThresholdMs){e.push({type:`telemetry`,description:`P99 latency ${t.p99LatencyMs}ms exceeded threshold ${this.latencyP99ThresholdMs}ms`,data:{p99LatencyMs:t.p99LatencyMs}}),n.push({operation:t.operation,severity:this.toSeverity(t.p99LatencyMs/this.latencyP99ThresholdMs),metric:`latency`,description:`Latency regression detected`,detectedAt:new Date,threshold:this.latencyP99ThresholdMs,observedValue:t.p99LatencyMs,evidence:e});continue}let i=r.get(this.operationKey(t.operation));if(i){let r=(i.totalCalls-t.totalCalls)/i.totalCalls;r>=this.throughputDropThreshold&&(e.push({type:`telemetry`,description:`Throughput dropped by ${(r*100).toFixed(1)}% compared to baseline`,data:{baselineCalls:i.totalCalls,currentCalls:t.totalCalls}}),n.push({operation:t.operation,severity:this.toSeverity(r/this.throughputDropThreshold),metric:`throughput`,description:`Usage drop detected`,detectedAt:new Date,threshold:this.throughputDropThreshold,observedValue:r,evidence:e}))}}return n}toIntentPatterns(e,n){let r=new Map(n.map(e=>[this.operationKey(e.operation),e]));return e.map(e=>{let n=r.get(this.operationKey(e.operation)),i={score:Math.min(1,(e.observedValue??0)/(e.threshold??1)),sampleSize:n?.totalCalls??0,pValue:void 0};return{id:t(),type:this.mapMetricToIntent(e.metric),description:e.description,operation:e.operation,confidence:i,metadata:{observedValue:e.observedValue,threshold:e.threshold},evidence:e.evidence}})}suggestOptimizations(e,t,n){let r=new Map(this.groupByOperation(t)),i=[];for(let t of e){let e=this.operationKey(t.operation),a=r.get(e)??[];for(let e of a)if(e.metric===`latency`)i.push(this.applyLifecycleContext({operation:t.operation,category:`performance`,summary:`Latency regression detected`,justification:`P99 latency at ${t.p99LatencyMs}ms`,recommendedActions:[`Add batching or caching layer`,`Replay golden tests to capture slow inputs`]},n?.stage));else if(e.metric===`error-rate`){let e=Object.entries(t.topErrors).sort((e,t)=>t[1]-e[1])[0]?.[0];i.push(this.applyLifecycleContext({operation:t.operation,category:`error-handling`,summary:`Error spike detected`,justification:e?`Dominant error code ${e}`:`Increase in failures`,recommendedActions:[`Generate regression spec from failing payloads`,`Add policy guardrails before rollout`]},n?.stage))}else e.metric===`throughput`&&i.push(this.applyLifecycleContext({operation:t.operation,category:`performance`,summary:`Throughput drop detected`,justification:`Significant traffic reduction relative to baseline`,recommendedActions:[`Validate routing + feature flag bucketing`,`Backfill spec variant to rehydrate demand`]},n?.stage))}return i}operationKey(e){let t=`operation`in e?e.operation:e;return`${t.name}.v${t.version}${t.tenantId?`@${t.tenantId}`:``}`}buildUsageStats(e){let t=e.map(e=>e.durationMs).sort((e,t)=>e-t),n=e.filter(e=>!e.success),r=e.length,a=(r-n.length)/r,o=n.length/r,s=t.reduce((e,t)=>e+t,0)/r,c=n.reduce((e,t)=>(t.errorCode&&(e[t.errorCode]=(e[t.errorCode]??0)+1),e),{}),l=e.map(e=>e.timestamp.getTime()),u=new Date(Math.min(...l)),d=new Date(Math.max(...l));return{operation:e[0].operation,totalCalls:r,successRate:a,errorRate:o,averageLatencyMs:s,p95LatencyMs:i(t,.95),p99LatencyMs:i(t,.99),maxLatencyMs:Math.max(...t),lastSeenAt:d,windowStart:u,windowEnd:d,topErrors:c}}toSeverity(e){return e>=2?`high`:e>=1.3?`medium`:`low`}mapMetricToIntent(e){switch(e){case`error-rate`:return`error-spike`;case`latency`:return`latency-regression`;case`throughput`:return`throughput-drop`;default:return`schema-mismatch`}}groupByOperation(e){let t=new Map;for(let n of e){let e=this.operationKey(n.operation),r=t.get(e)??[];r.push(n),t.set(e,r)}return t}applyLifecycleContext(e,t){if(t===void 0)return e;let n=o[a(t)]?.[e.category];return n?{...e,lifecycleStage:t,lifecycleNotes:n.message,recommendedActions:s([...e.recommendedActions,...n.supplementalActions])}:{...e,lifecycleStage:t}}};function i(e,t){return e.length?e.length===1?e[0]:e[Math.min(e.length-1,Math.floor(t*e.length))]:0}const a=t=>t<=2?`early`:t===e.ProductMarketFit?`pmf`:t===e.GrowthScaleUp||t===e.ExpansionPlatform?`scale`:`mature`,o={early:{performance:{message:`Favor guardrails that protect learning velocity before heavy rewrites.`,supplementalActions:[`Wrap risky changes behind progressive delivery flags`]},"error-handling":{message:`Make failures loud and recoverable so you can learn faster.`,supplementalActions:[`Add auto-rollbacks or manual kill switches`]}},pmf:{performance:{message:`Stabilize the core use case to avoid regressions while demand grows.`,supplementalActions:[`Instrument regression tests on critical specs`]}},scale:{performance:{message:`Prioritize resilience and multi-tenant safety as volumes expand.`,supplementalActions:[`Introduce workload partitioning or isolation per tenant`]},"error-handling":{message:`Contain blast radius with policy fallbacks and circuit breakers.`,supplementalActions:[`Add circuit breakers to high-risk operations`]}},mature:{performance:{message:`Optimize for margins and predictable SLAs.`,supplementalActions:[`Capture unit-cost impacts alongside latency fixes`]},"error-handling":{message:`Prevent regressions with automated regression specs before deploy.`,supplementalActions:[`Run auto-evolution simulations on renewal scenarios`]}}},s=e=>{let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n};export{r as SpecAnalyzer};
1
+ import"@lssm/lib.observability";import{randomUUID as e}from"node:crypto";import{LifecycleStage as t}from"@lssm/lib.lifecycle";const n={minSampleSize:50,errorRateThreshold:.05,latencyP99ThresholdMs:750};var r=class{logger;minSampleSize;errorRateThreshold;latencyP99ThresholdMs;throughputDropThreshold;constructor(e={}){this.logger=e.logger,this.minSampleSize=e.minSampleSize??n.minSampleSize,this.errorRateThreshold=e.errorRateThreshold??n.errorRateThreshold,this.latencyP99ThresholdMs=e.latencyP99ThresholdMs??n.latencyP99ThresholdMs,this.throughputDropThreshold=e.throughputDropThreshold??.2}analyzeSpecUsage(e){if(!e.length)return this.logger?.debug(`SpecAnalyzer.analyzeSpecUsage.skip`,{reason:`no-samples`}),[];let t=new Map;for(let n of e){let e=this.operationKey(n),r=t.get(e)??[];r.push(n),t.set(e,r)}return[...t.values()].filter(e=>{let t=e.length>=this.minSampleSize;return t||this.logger?.debug(`SpecAnalyzer.analyzeSpecUsage.skipOperation`,{operation:this.operationKey(e[0]),sampleSize:e.length,minSampleSize:this.minSampleSize}),t}).map(e=>this.buildUsageStats(e))}detectAnomalies(e,t){let n=[];if(!e.length)return this.logger?.debug(`SpecAnalyzer.detectAnomalies.skip`,{reason:`no-stats`}),n;let r=new Map((t??[]).map(e=>[this.operationKey(e.operation),e]));for(let t of e){let e=[];if(t.errorRate>=this.errorRateThreshold){e.push({type:`telemetry`,description:`Error rate ${t.errorRate.toFixed(2)} exceeded threshold ${this.errorRateThreshold}`,data:{errorRate:t.errorRate}}),n.push({operation:t.operation,severity:this.toSeverity(t.errorRate/this.errorRateThreshold),metric:`error-rate`,description:`Error rate spike`,detectedAt:new Date,threshold:this.errorRateThreshold,observedValue:t.errorRate,evidence:e});continue}if(t.p99LatencyMs>=this.latencyP99ThresholdMs){e.push({type:`telemetry`,description:`P99 latency ${t.p99LatencyMs}ms exceeded threshold ${this.latencyP99ThresholdMs}ms`,data:{p99LatencyMs:t.p99LatencyMs}}),n.push({operation:t.operation,severity:this.toSeverity(t.p99LatencyMs/this.latencyP99ThresholdMs),metric:`latency`,description:`Latency regression detected`,detectedAt:new Date,threshold:this.latencyP99ThresholdMs,observedValue:t.p99LatencyMs,evidence:e});continue}let i=r.get(this.operationKey(t.operation));if(i){let r=(i.totalCalls-t.totalCalls)/i.totalCalls;r>=this.throughputDropThreshold&&(e.push({type:`telemetry`,description:`Throughput dropped by ${(r*100).toFixed(1)}% compared to baseline`,data:{baselineCalls:i.totalCalls,currentCalls:t.totalCalls}}),n.push({operation:t.operation,severity:this.toSeverity(r/this.throughputDropThreshold),metric:`throughput`,description:`Usage drop detected`,detectedAt:new Date,threshold:this.throughputDropThreshold,observedValue:r,evidence:e}))}}return n}toIntentPatterns(t,n){let r=new Map(n.map(e=>[this.operationKey(e.operation),e]));return t.map(t=>{let n=r.get(this.operationKey(t.operation)),i={score:Math.min(1,(t.observedValue??0)/(t.threshold??1)),sampleSize:n?.totalCalls??0,pValue:void 0};return{id:e(),type:this.mapMetricToIntent(t.metric),description:t.description,operation:t.operation,confidence:i,metadata:{observedValue:t.observedValue,threshold:t.threshold},evidence:t.evidence}})}suggestOptimizations(e,t,n){let r=new Map(this.groupByOperation(t)),i=[];for(let t of e){let e=this.operationKey(t.operation),a=r.get(e)??[];for(let e of a)if(e.metric===`latency`)i.push(this.applyLifecycleContext({operation:t.operation,category:`performance`,summary:`Latency regression detected`,justification:`P99 latency at ${t.p99LatencyMs}ms`,recommendedActions:[`Add batching or caching layer`,`Replay golden tests to capture slow inputs`]},n?.stage));else if(e.metric===`error-rate`){let e=Object.entries(t.topErrors).sort((e,t)=>t[1]-e[1])[0]?.[0];i.push(this.applyLifecycleContext({operation:t.operation,category:`error-handling`,summary:`Error spike detected`,justification:e?`Dominant error code ${e}`:`Increase in failures`,recommendedActions:[`Generate regression spec from failing payloads`,`Add policy guardrails before rollout`]},n?.stage))}else e.metric===`throughput`&&i.push(this.applyLifecycleContext({operation:t.operation,category:`performance`,summary:`Throughput drop detected`,justification:`Significant traffic reduction relative to baseline`,recommendedActions:[`Validate routing + feature flag bucketing`,`Backfill spec variant to rehydrate demand`]},n?.stage))}return i}operationKey(e){let t=`operation`in e?e.operation:e;return`${t.name}.v${t.version}${t.tenantId?`@${t.tenantId}`:``}`}buildUsageStats(e){let t=e.map(e=>e.durationMs).sort((e,t)=>e-t),n=e.filter(e=>!e.success),r=e.length,a=(r-n.length)/r,o=n.length/r,s=t.reduce((e,t)=>e+t,0)/r,c=n.reduce((e,t)=>(t.errorCode&&(e[t.errorCode]=(e[t.errorCode]??0)+1),e),{}),l=e.map(e=>e.timestamp.getTime()),u=new Date(Math.min(...l)),d=new Date(Math.max(...l));return{operation:e[0].operation,totalCalls:r,successRate:a,errorRate:o,averageLatencyMs:s,p95LatencyMs:i(t,.95),p99LatencyMs:i(t,.99),maxLatencyMs:Math.max(...t),lastSeenAt:d,windowStart:u,windowEnd:d,topErrors:c}}toSeverity(e){return e>=2?`high`:e>=1.3?`medium`:`low`}mapMetricToIntent(e){switch(e){case`error-rate`:return`error-spike`;case`latency`:return`latency-regression`;case`throughput`:return`throughput-drop`;default:return`schema-mismatch`}}groupByOperation(e){let t=new Map;for(let n of e){let e=this.operationKey(n.operation),r=t.get(e)??[];r.push(n),t.set(e,r)}return t}applyLifecycleContext(e,t){if(t===void 0)return e;let n=o[a(t)]?.[e.category];return n?{...e,lifecycleStage:t,lifecycleNotes:n.message,recommendedActions:s([...e.recommendedActions,...n.supplementalActions])}:{...e,lifecycleStage:t}}};function i(e,t){return e.length?e.length===1?e[0]:e[Math.min(e.length-1,Math.floor(t*e.length))]:0}const a=e=>e<=2?`early`:e===t.ProductMarketFit?`pmf`:e===t.GrowthScaleUp||e===t.ExpansionPlatform?`scale`:`mature`,o={early:{performance:{message:`Favor guardrails that protect learning velocity before heavy rewrites.`,supplementalActions:[`Wrap risky changes behind progressive delivery flags`]},"error-handling":{message:`Make failures loud and recoverable so you can learn faster.`,supplementalActions:[`Add auto-rollbacks or manual kill switches`]}},pmf:{performance:{message:`Stabilize the core use case to avoid regressions while demand grows.`,supplementalActions:[`Instrument regression tests on critical specs`]}},scale:{performance:{message:`Prioritize resilience and multi-tenant safety as volumes expand.`,supplementalActions:[`Introduce workload partitioning or isolation per tenant`]},"error-handling":{message:`Contain blast radius with policy fallbacks and circuit breakers.`,supplementalActions:[`Add circuit breakers to high-risk operations`]}},mature:{performance:{message:`Optimize for margins and predictable SLAs.`,supplementalActions:[`Capture unit-cost impacts alongside latency fixes`]},"error-handling":{message:`Prevent regressions with automated regression specs before deploy.`,supplementalActions:[`Run auto-evolution simulations on renewal scenarios`]}}},s=e=>{let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n};export{r as SpecAnalyzer};
@@ -1 +1 @@
1
- import"../ai-agent/dist/approval/index.js";import{mkdir as e,writeFile as t}from"node:fs/promises";import{join as n}from"node:path";var r=class{constructor(e){this.options=e}async submit(e,t,n){return await this.options.repository.create(e),t&&this.options.approval&&await this.options.approval.requestApproval(t,n??e.proposal.summary,{suggestionId:e.id}),e}async approve(e,t,n){let r=await this.ensureSuggestion(e);await this.options.repository.updateStatus(e,`approved`,{reviewer:t,notes:n,decidedAt:new Date}),this.options.writer&&await this.options.writer.write({...r,status:`approved`,approvals:{reviewer:t,notes:n,decidedAt:new Date,status:`approved`}})}async reject(e,t,n){await this.options.repository.updateStatus(e,`rejected`,{reviewer:t,notes:n,decidedAt:new Date})}list(e){return this.options.repository.list(e)}async ensureSuggestion(e){let t=await this.options.repository.getById(e);if(!t)throw Error(`Spec suggestion ${e} not found`);return t}},i=class{outputDir;filenameTemplate;constructor(e={}){this.outputDir=e.outputDir??n(process.cwd(),`packages/contractspec/packages/libs/contracts/src/generated`),this.filenameTemplate=e.filenameTemplate??(e=>`${e.target?.name??e.intent.id}.v${e.target?.version??`next`}.suggestion.json`)}async write(r){await e(this.outputDir,{recursive:!0});let i=this.filenameTemplate(r),a=n(this.outputDir,i),s=o(r);return await t(a,JSON.stringify(s,null,2)),a}},a=class{items=new Map;async create(e){this.items.set(e.id,e)}async getById(e){return this.items.get(e)}async updateStatus(e,t,n){let r=await this.getById(e);r&&this.items.set(e,{...r,status:t,approvals:{reviewer:n?.reviewer,notes:n?.notes,decidedAt:n?.decidedAt,status:t}})}async list(e){let t=[...this.items.values()];return e?t.filter(t=>!(e.status&&t.status!==e.status||e.operationName&&t.target?.name!==e.operationName)):t}};function o(e){let{proposal:t,...n}=e,{spec:r,...i}=t;return{...n,proposal:{...i,specMeta:r?.meta},createdAt:e.createdAt.toISOString(),intent:{...e.intent,confidence:{...e.intent.confidence},evidence:e.intent.evidence}}}export{i as FileSystemSuggestionWriter,a as InMemorySpecSuggestionRepository,r as SpecSuggestionOrchestrator};
1
+ import{mkdir as e,writeFile as t}from"node:fs/promises";import{join as n}from"node:path";import"@lssm/lib.ai-agent/approval";var r=class{constructor(e){this.options=e}async submit(e,t,n){return await this.options.repository.create(e),t&&this.options.approval&&await this.options.approval.requestApproval({sessionId:t.sessionId,agentId:t.agentId,tenantId:t.tenantId,toolName:`evolution.apply_suggestion`,toolCallId:e.id,toolArgs:{suggestionId:e.id},reason:n??e.proposal.summary,payload:{suggestionId:e.id}}),e}async approve(e,t,n){let r=await this.ensureSuggestion(e);await this.options.repository.updateStatus(e,`approved`,{reviewer:t,notes:n,decidedAt:new Date}),this.options.writer&&await this.options.writer.write({...r,status:`approved`,approvals:{reviewer:t,notes:n,decidedAt:new Date,status:`approved`}})}async reject(e,t,n){await this.options.repository.updateStatus(e,`rejected`,{reviewer:t,notes:n,decidedAt:new Date})}list(e){return this.options.repository.list(e)}async ensureSuggestion(e){let t=await this.options.repository.getById(e);if(!t)throw Error(`Spec suggestion ${e} not found`);return t}},i=class{outputDir;filenameTemplate;constructor(e={}){this.outputDir=e.outputDir??n(process.cwd(),`packages/libs/contracts/src/generated`),this.filenameTemplate=e.filenameTemplate??(e=>`${e.target?.name??e.intent.id}.v${e.target?.version??`next`}.suggestion.json`)}async write(r){await e(this.outputDir,{recursive:!0});let i=this.filenameTemplate(r),a=n(this.outputDir,i),s=o(r);return await t(a,JSON.stringify(s,null,2)),a}},a=class{items=new Map;async create(e){this.items.set(e.id,e)}async getById(e){return this.items.get(e)}async updateStatus(e,t,n){let r=await this.getById(e);r&&this.items.set(e,{...r,status:t,approvals:{reviewer:n?.reviewer,notes:n?.notes,decidedAt:n?.decidedAt,status:t}})}async list(e){let t=[...this.items.values()];return e?t.filter(t=>!(e.status&&t.status!==e.status||e.operationName&&t.target?.name!==e.operationName)):t}};function o(e){let{proposal:t,...n}=e,{spec:r,...i}=t;return{...n,proposal:{...i,specMeta:r?.meta},createdAt:e.createdAt.toISOString(),intent:{...e.intent,confidence:{...e.intent.confidence},evidence:e.intent.evidence}}}export{i as FileSystemSuggestionWriter,a as InMemorySpecSuggestionRepository,r as SpecSuggestionOrchestrator};
@@ -0,0 +1,19 @@
1
+ import{randomUUID as e}from"node:crypto";import{Output as t,generateText as n}from"ai";import*as r from"zod";const i=r.object({summary:r.string().describe(`Brief summary of the proposed change`),rationale:r.string().describe(`Detailed explanation of why this change is needed`),changeType:r.enum([`new-spec`,`revision`,`policy-update`,`schema-update`]).describe(`Type of change being proposed`),recommendedActions:r.array(r.string()).describe(`List of specific actions to implement the change`),estimatedImpact:r.enum([`low`,`medium`,`high`]).describe(`Estimated impact of implementing this change`),riskLevel:r.enum([`low`,`medium`,`high`]).describe(`Risk level associated with this change`),diff:r.string().optional().describe(`Optional diff or code snippet showing the change`)});var a=class{model;config;systemPrompt;constructor(e){this.model=e.model,this.config=e.evolutionConfig??{},this.systemPrompt=e.systemPrompt??`You are a ContractSpec evolution expert. Your role is to analyze telemetry data, anomalies, and usage patterns to suggest improvements to API contracts and specifications.
2
+
3
+ When generating suggestions:
4
+ 1. Be specific and actionable
5
+ 2. Consider backwards compatibility
6
+ 3. Prioritize stability and reliability
7
+ 4. Explain the rationale clearly
8
+ 5. Estimate impact and risk accurately`}async generateFromIntent(e,r={}){let a=this.buildPrompt(e,r),{output:o}=await n({model:this.model,system:this.systemPrompt,prompt:a,output:t.object({schema:i})});return this.buildSuggestion(e,o)}async generateBatch(e,t={}){let n=t.maxConcurrent??3,r=[];for(let t=0;t<e.length;t+=n){let i=e.slice(t,t+n),a=await Promise.all(i.map(e=>this.generateFromIntent(e)));r.push(...a)}return r}async enhanceSuggestion(e){let r=`Review and enhance this spec suggestion:
9
+
10
+ Intent: ${e.intent.type} - ${e.intent.description}
11
+ Current Summary: ${e.proposal.summary}
12
+ Current Rationale: ${e.proposal.rationale}
13
+
14
+ Evidence:
15
+ ${e.evidence.map(e=>`- ${e.type}: ${e.description}`).join(`
16
+ `)}
17
+
18
+ Please provide an improved version with more specific recommendations.`,{output:a}=await n({model:this.model,system:this.systemPrompt,prompt:r,output:t.object({schema:i})});return{...e,proposal:{...e.proposal,summary:a.summary,rationale:a.rationale,changeType:a.changeType,diff:a.diff,metadata:{...e.proposal.metadata,aiEnhanced:!0,recommendedActions:a.recommendedActions,estimatedImpact:a.estimatedImpact,riskLevel:a.riskLevel}}}}buildPrompt(e,t){let n=[`Analyze this intent pattern and generate a spec suggestion:`,``,`Intent Type: ${e.type}`,`Description: ${e.description}`,`Confidence: ${(e.confidence.score*100).toFixed(0)}% (sample size: ${e.confidence.sampleSize})`];if(e.operation&&n.push(`Operation: ${e.operation.name} v${e.operation.version}`),e.evidence.length>0){n.push(``,`Evidence:`);for(let t of e.evidence)n.push(`- [${t.type}] ${t.description}`)}return e.metadata&&n.push(``,`Metadata: ${JSON.stringify(e.metadata,null,2)}`),t.existingSpec&&n.push(``,`Existing Spec:`,"```json",JSON.stringify(t.existingSpec,null,2),"```"),t.additionalContext&&n.push(``,`Additional Context:`,t.additionalContext),n.join(`
19
+ `)}buildSuggestion(t,n){let r=new Date,i={summary:n.summary,rationale:n.rationale,changeType:n.changeType,diff:n.diff,metadata:{aiGenerated:!0,recommendedActions:n.recommendedActions,estimatedImpact:n.estimatedImpact,riskLevel:n.riskLevel}};return{id:e(),intent:t,target:t.operation,proposal:i,confidence:t.confidence.score,priority:this.calculatePriority(t,n),createdAt:r,createdBy:`ai-spec-generator`,status:this.determineInitialStatus(t),evidence:t.evidence,tags:[`ai-generated`,t.type]}}calculatePriority(e,t){let n=t.estimatedImpact===`high`?1:t.estimatedImpact===`medium`?.5:.25,r=e.confidence.score,i=e.type===`error-spike`?.3:e.type===`latency-regression`?.2:0,a=n*.4+r*.4+i;return a>=.7?`high`:a>=.4?`medium`:`low`}determineInitialStatus(e){return this.config.autoApproveThreshold&&e.confidence.score>=this.config.autoApproveThreshold&&!this.config.requireApproval?`approved`:`pending`}};function o(e){return new a(e)}export{a as AISpecGenerator,o as createAISpecGenerator};
@@ -1 +1 @@
1
- import"../observability/dist/index.js";import{randomUUID as e}from"node:crypto";var t=class{config;logger;clock;getSpec;constructor(e={}){this.config=e.config??{},this.logger=e.logger,this.clock=e.clock??(()=>new Date),this.getSpec=e.getSpec}generateFromIntent(t,n={}){let r=this.clock(),i=n.summary??`${this.intentToVerb(t.type)} ${t.operation?.name??`operation`}`,a=n.rationale??[t.description,t.metadata?.observedValue?`Observed ${t.metadata.observedValue}`:void 0].filter(Boolean).join(` — `);return{id:e(),intent:t,target:t.operation,proposal:{summary:i,rationale:a,changeType:n.changeType??this.inferChangeType(t),kind:n.kind,spec:n.spec,diff:n.diff,metadata:n.metadata},confidence:t.confidence.score,priority:this.intentToPriority(t),createdAt:r,createdBy:n.createdBy??`auto-evolution`,status:n.status??`pending`,evidence:t.evidence,tags:n.tags}}generateVariant(e,t,r,i={}){if(!this.getSpec)throw Error(`SpecGenerator requires getSpec() to generate variants`);let a=this.getSpec(e.name,e.version);if(!a)throw Error(`Cannot generate variant; spec ${e.name}.v${e.version} not found`);let o=n(a,t);return this.generateFromIntent(r,{...i,spec:o})}validateSuggestion(e,t=this.config){let n=[];t.minConfidence!=null&&e.confidence<t.minConfidence&&n.push(`Confidence ${e.confidence.toFixed(2)} below minimum ${t.minConfidence}`),t.requireApproval&&e.status===`approved`&&n.push(`Suggestion cannot be auto-approved when approval is required`),e.proposal.spec&&!e.proposal.spec.meta?.name&&n.push(`Proposal spec must include meta.name`),e.proposal.summary||n.push(`Proposal summary is required`);let r=n.length===0;return r||this.logger?.warn(`SpecGenerator.validateSuggestion.failed`,{suggestionId:e.id,reasons:n}),{ok:r,reasons:n}}intentToVerb(e){switch(e){case`error-spike`:return`Stabilize`;case`latency-regression`:return`Optimize`;case`missing-operation`:return`Introduce`;case`throughput-drop`:return`Rebalance`;default:return`Adjust`}}intentToPriority(e){let t=e.confidence.score;return e.type===`error-spike`||t>=.8?`high`:t>=.5?`medium`:`low`}inferChangeType(e){switch(e.type){case`missing-operation`:return`new-spec`;case`schema-mismatch`:return`schema-update`;case`error-spike`:return`policy-update`;default:return`revision`}}};function n(e,t){return{...e,...t,meta:{...e.meta,...t.meta},io:{...e.io,...t.io},policy:{...e.policy,...t.policy},telemetry:{...e.telemetry,...t.telemetry},sideEffects:{...e.sideEffects,...t.sideEffects}}}export{t as SpecGenerator};
1
+ import"@lssm/lib.observability";import{randomUUID as e}from"node:crypto";var t=class{config;logger;clock;getSpec;constructor(e={}){this.config=e.config??{},this.logger=e.logger,this.clock=e.clock??(()=>new Date),this.getSpec=e.getSpec}generateFromIntent(t,n={}){let r=this.clock(),i=n.summary??`${this.intentToVerb(t.type)} ${t.operation?.name??`operation`}`,a=n.rationale??[t.description,t.metadata?.observedValue?`Observed ${t.metadata.observedValue}`:void 0].filter(Boolean).join(` — `);return{id:e(),intent:t,target:t.operation,proposal:{summary:i,rationale:a,changeType:n.changeType??this.inferChangeType(t),kind:n.kind,spec:n.spec,diff:n.diff,metadata:n.metadata},confidence:t.confidence.score,priority:this.intentToPriority(t),createdAt:r,createdBy:n.createdBy??`auto-evolution`,status:n.status??`pending`,evidence:t.evidence,tags:n.tags}}generateVariant(e,t,r,i={}){if(!this.getSpec)throw Error(`SpecGenerator requires getSpec() to generate variants`);let a=this.getSpec(e.name,e.version);if(!a)throw Error(`Cannot generate variant; spec ${e.name}.v${e.version} not found`);let o=n(a,t);return this.generateFromIntent(r,{...i,spec:o})}validateSuggestion(e,t=this.config){let n=[];t.minConfidence!=null&&e.confidence<t.minConfidence&&n.push(`Confidence ${e.confidence.toFixed(2)} below minimum ${t.minConfidence}`),t.requireApproval&&e.status===`approved`&&n.push(`Suggestion cannot be auto-approved when approval is required`),e.proposal.spec&&!e.proposal.spec.meta?.name&&n.push(`Proposal spec must include meta.name`),e.proposal.summary||n.push(`Proposal summary is required`);let r=n.length===0;return r||this.logger?.warn(`SpecGenerator.validateSuggestion.failed`,{suggestionId:e.id,reasons:n}),{ok:r,reasons:n}}intentToVerb(e){switch(e){case`error-spike`:return`Stabilize`;case`latency-regression`:return`Optimize`;case`missing-operation`:return`Introduce`;case`throughput-drop`:return`Rebalance`;default:return`Adjust`}}intentToPriority(e){let t=e.confidence.score;return e.type===`error-spike`||t>=.8?`high`:t>=.5?`medium`:`low`}inferChangeType(e){switch(e.type){case`missing-operation`:return`new-spec`;case`schema-mismatch`:return`schema-update`;case`error-spike`:return`policy-update`;default:return`revision`}}};function n(e,t){return{...e,...t,meta:{...e.meta,...t.meta},io:{...e.io,...t.io},policy:{...e.policy,...t.policy},telemetry:{...e.telemetry,...t.telemetry},sideEffects:{...e.sideEffects,...t.sideEffects}}}export{t as SpecGenerator};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SpecAnalyzer as e}from"./analyzer/spec-analyzer.js";import{SpecGenerator as t}from"./generator/spec-generator.js";import{FileSystemSuggestionWriter as n,InMemorySpecSuggestionRepository as r,SpecSuggestionOrchestrator as i}from"./approval/integration.js";export{n as FileSystemSuggestionWriter,r as InMemorySpecSuggestionRepository,e as SpecAnalyzer,t as SpecGenerator,i as SpecSuggestionOrchestrator};
1
+ import{SpecAnalyzer as e}from"./analyzer/spec-analyzer.js";import{SpecGenerator as t}from"./generator/spec-generator.js";import{AISpecGenerator as n,createAISpecGenerator as r}from"./generator/ai-spec-generator.js";import{FileSystemSuggestionWriter as i,InMemorySpecSuggestionRepository as a,SpecSuggestionOrchestrator as o}from"./approval/integration.js";export{n as AISpecGenerator,i as FileSystemSuggestionWriter,a as InMemorySpecSuggestionRepository,e as SpecAnalyzer,t as SpecGenerator,o as SpecSuggestionOrchestrator,r as createAISpecGenerator};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lssm/lib.evolution",
3
- "version": "0.4.1",
3
+ "version": "1.41.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -19,29 +19,35 @@
19
19
  "lint": "bun lint:fix",
20
20
  "lint:fix": "eslint src --fix",
21
21
  "lint:check": "eslint src",
22
- "test": "bun run"
22
+ "test": "bun test"
23
23
  },
24
24
  "dependencies": {
25
- "@lssm/lib.ai-agent": "0.4.1",
26
- "@lssm/lib.contracts": "1.11.1",
27
- "@lssm/lib.lifecycle": "0.3.1",
28
- "@lssm/lib.observability": "0.4.1",
29
- "@lssm/lib.schema": "1.11.1"
25
+ "ai": "beta",
26
+ "zod": "^4.1.13",
27
+ "@lssm/lib.ai-agent": "workspace:*",
28
+ "@lssm/lib.contracts": "workspace:*",
29
+ "@lssm/lib.lifecycle": "workspace:*",
30
+ "@lssm/lib.observability": "workspace:*",
31
+ "@lssm/lib.schema": "workspace:*"
30
32
  },
31
33
  "peerDependencies": {
32
- "@prisma/client": "7.0.1"
34
+ "@prisma/client": "7.1.0"
33
35
  },
34
36
  "devDependencies": {
35
- "@lssm/tool.tsdown": "0.12.1",
36
- "@lssm/tool.typescript": "0.11.1",
37
- "tsdown": "^0.16.6",
37
+ "@lssm/tool.tsdown": "workspace:*",
38
+ "@lssm/tool.typescript": "workspace:*",
39
+ "tsdown": "^0.17.4",
38
40
  "typescript": "^5.9.3"
39
41
  },
40
42
  "exports": {
41
- ".": "./dist/index.js",
43
+ ".": "./src/index.ts",
42
44
  "./*": "./*"
43
45
  },
44
46
  "publishConfig": {
45
- "access": "public"
47
+ "access": "public",
48
+ "exports": {
49
+ ".": "./dist/index.js",
50
+ "./*": "./*"
51
+ }
46
52
  }
47
53
  }
@@ -1 +0,0 @@
1
- import"./workflow.js";
@@ -1 +0,0 @@
1
- import{randomUUID as e}from"node:crypto";
@@ -1,34 +0,0 @@
1
- import { IntentPattern, OperationMetricSample, OptimizationHint, SpecAnomaly, SpecUsageStats } from "../types.js";
2
- import { LifecycleStage } from "@lssm/lib.lifecycle";
3
- import { Logger } from "@lssm/lib.observability";
4
-
5
- //#region src/analyzer/spec-analyzer.d.ts
6
- interface SpecAnalyzerOptions {
7
- logger?: Logger;
8
- minSampleSize?: number;
9
- errorRateThreshold?: number;
10
- latencyP99ThresholdMs?: number;
11
- throughputDropThreshold?: number;
12
- }
13
- declare class SpecAnalyzer {
14
- private readonly logger?;
15
- private readonly minSampleSize;
16
- private readonly errorRateThreshold;
17
- private readonly latencyP99ThresholdMs;
18
- private readonly throughputDropThreshold;
19
- constructor(options?: SpecAnalyzerOptions);
20
- analyzeSpecUsage(samples: OperationMetricSample[]): SpecUsageStats[];
21
- detectAnomalies(stats: SpecUsageStats[], baseline?: SpecUsageStats[]): SpecAnomaly[];
22
- toIntentPatterns(anomalies: SpecAnomaly[], stats: SpecUsageStats[]): IntentPattern[];
23
- suggestOptimizations(stats: SpecUsageStats[], anomalies: SpecAnomaly[], lifecycleContext?: {
24
- stage: LifecycleStage;
25
- }): OptimizationHint[];
26
- private operationKey;
27
- private buildUsageStats;
28
- private toSeverity;
29
- private mapMetricToIntent;
30
- private groupByOperation;
31
- private applyLifecycleContext;
32
- }
33
- //#endregion
34
- export { SpecAnalyzer, SpecAnalyzerOptions };
@@ -1,42 +0,0 @@
1
- import { SpecSuggestion, SpecSuggestionFilters, SpecSuggestionRepository, SpecSuggestionWriter, SuggestionStatus } from "../types.js";
2
- import { ApprovalWorkflow } from "@lssm/lib.ai-agent/approval";
3
- import { AgentSessionState } from "@lssm/lib.ai-agent/types";
4
-
5
- //#region src/approval/integration.d.ts
6
- interface SpecSuggestionOrchestratorOptions {
7
- repository: SpecSuggestionRepository;
8
- approval?: ApprovalWorkflow;
9
- writer?: SpecSuggestionWriter;
10
- }
11
- declare class SpecSuggestionOrchestrator {
12
- private readonly options;
13
- constructor(options: SpecSuggestionOrchestratorOptions);
14
- submit(suggestion: SpecSuggestion, session?: AgentSessionState, approvalReason?: string): Promise<SpecSuggestion>;
15
- approve(id: string, reviewer: string, notes?: string): Promise<void>;
16
- reject(id: string, reviewer: string, notes?: string): Promise<void>;
17
- list(filters?: SpecSuggestionFilters): Promise<SpecSuggestion[]>;
18
- private ensureSuggestion;
19
- }
20
- interface FileSystemSuggestionWriterOptions {
21
- outputDir?: string;
22
- filenameTemplate?: (suggestion: SpecSuggestion) => string;
23
- }
24
- declare class FileSystemSuggestionWriter implements SpecSuggestionWriter {
25
- private readonly outputDir;
26
- private readonly filenameTemplate;
27
- constructor(options?: FileSystemSuggestionWriterOptions);
28
- write(suggestion: SpecSuggestion): Promise<string>;
29
- }
30
- declare class InMemorySpecSuggestionRepository implements SpecSuggestionRepository {
31
- private readonly items;
32
- create(suggestion: SpecSuggestion): Promise<void>;
33
- getById(id: string): Promise<SpecSuggestion | undefined>;
34
- updateStatus(id: string, status: SuggestionStatus, metadata?: {
35
- reviewer?: string;
36
- notes?: string;
37
- decidedAt?: Date;
38
- }): Promise<void>;
39
- list(filters?: SpecSuggestionFilters): Promise<SpecSuggestion[]>;
40
- }
41
- //#endregion
42
- export { FileSystemSuggestionWriter, FileSystemSuggestionWriterOptions, InMemorySpecSuggestionRepository, SpecSuggestionOrchestrator, SpecSuggestionOrchestratorOptions };
@@ -1,46 +0,0 @@
1
- import { EvolutionConfig, IntentPattern, OperationCoordinate, SpecSuggestion, SpecSuggestionProposal, SuggestionStatus } from "../types.js";
2
- import { ContractSpec, ResourceRefDescriptor } from "@lssm/lib.contracts";
3
- import { AnySchemaModel } from "@lssm/lib.schema";
4
- import { Logger } from "@lssm/lib.observability";
5
-
6
- //#region src/generator/spec-generator.d.ts
7
- type AnyContract = ContractSpec<AnySchemaModel, AnySchemaModel | ResourceRefDescriptor<boolean>>;
8
- interface SpecGeneratorOptions {
9
- config?: EvolutionConfig;
10
- logger?: Logger;
11
- clock?: () => Date;
12
- getSpec?: (name: string, version?: number) => AnyContract | undefined;
13
- }
14
- interface GenerateSpecOptions {
15
- summary?: string;
16
- rationale?: string;
17
- changeType?: SpecSuggestionProposal['changeType'];
18
- kind?: SpecSuggestionProposal['kind'];
19
- spec?: AnyContract;
20
- diff?: string;
21
- metadata?: Record<string, unknown>;
22
- status?: SuggestionStatus;
23
- tags?: string[];
24
- createdBy?: string;
25
- }
26
- type SpecPatch = Partial<ContractSpec<AnySchemaModel, AnySchemaModel | ResourceRefDescriptor<boolean>>> & {
27
- meta?: Partial<AnyContract['meta']>;
28
- };
29
- declare class SpecGenerator {
30
- private readonly config;
31
- private readonly logger?;
32
- private readonly clock;
33
- private readonly getSpec?;
34
- constructor(options?: SpecGeneratorOptions);
35
- generateFromIntent(intent: IntentPattern, options?: GenerateSpecOptions): SpecSuggestion;
36
- generateVariant(operation: OperationCoordinate, patch: SpecPatch, intent: IntentPattern, options?: Omit<GenerateSpecOptions, 'spec'>): SpecSuggestion;
37
- validateSuggestion(suggestion: SpecSuggestion, config?: EvolutionConfig): {
38
- ok: boolean;
39
- reasons: string[];
40
- };
41
- private intentToVerb;
42
- private intentToPriority;
43
- private inferChangeType;
44
- }
45
- //#endregion
46
- export { GenerateSpecOptions, SpecGenerator, SpecGeneratorOptions, SpecPatch };
package/dist/index.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import { AnomalySeverity, EvolutionConfig, IntentPattern, OperationCoordinate, OperationMetricSample, OptimizationHint, PatternConfidence, SpecAnomaly, SpecSuggestion, SpecSuggestionFilters, SpecSuggestionProposal, SpecSuggestionRepository, SpecSuggestionWriter, SpecUsageStats, SuggestionEvidence, SuggestionStatus } from "./types.js";
2
- import { SpecAnalyzer, SpecAnalyzerOptions } from "./analyzer/spec-analyzer.js";
3
- import { GenerateSpecOptions, SpecGenerator, SpecGeneratorOptions, SpecPatch } from "./generator/spec-generator.js";
4
- import { FileSystemSuggestionWriter, FileSystemSuggestionWriterOptions, InMemorySpecSuggestionRepository, SpecSuggestionOrchestrator, SpecSuggestionOrchestratorOptions } from "./approval/integration.js";
5
- export { AnomalySeverity, EvolutionConfig, FileSystemSuggestionWriter, FileSystemSuggestionWriterOptions, GenerateSpecOptions, InMemorySpecSuggestionRepository, IntentPattern, OperationCoordinate, OperationMetricSample, OptimizationHint, PatternConfidence, SpecAnalyzer, SpecAnalyzerOptions, SpecAnomaly, SpecGenerator, SpecGeneratorOptions, SpecPatch, SpecSuggestion, SpecSuggestionFilters, SpecSuggestionOrchestrator, SpecSuggestionOrchestratorOptions, SpecSuggestionProposal, SpecSuggestionRepository, SpecSuggestionWriter, SpecUsageStats, SuggestionEvidence, SuggestionStatus };
@@ -1 +0,0 @@
1
- import{e,n as t}from"./types/stages.js";import"./types/axes.js";import"./types/signals.js";import"./types/milestones.js";import"./utils/formatters.js";
@@ -1 +0,0 @@
1
- (function(e){return e.Sketch=`Sketch`,e.Prototype=`Prototype`,e.Mvp=`MVP`,e.V1=`V1`,e.Ecosystem=`Ecosystem`,e})({}),function(e){return e.Solo=`Solo`,e.TinyTeam=`TinyTeam`,e.FunctionalOrg=`FunctionalOrg`,e.MultiTeam=`MultiTeam`,e.Bureaucratic=`Bureaucratic`,e}({}),function(e){return e.Bootstrapped=`Bootstrapped`,e.PreSeed=`PreSeed`,e.Seed=`Seed`,e.SeriesAorB=`SeriesAorB`,e.LateStage=`LateStage`,e}({});
@@ -1 +0,0 @@
1
- import"./stages.js";
@@ -1 +0,0 @@
1
- import"./stages.js";
@@ -1 +0,0 @@
1
- let e=function(e){return e[e.Exploration=0]=`Exploration`,e[e.ProblemSolutionFit=1]=`ProblemSolutionFit`,e[e.MvpEarlyTraction=2]=`MvpEarlyTraction`,e[e.ProductMarketFit=3]=`ProductMarketFit`,e[e.GrowthScaleUp=4]=`GrowthScaleUp`,e[e.ExpansionPlatform=5]=`ExpansionPlatform`,e[e.MaturityRenewal=6]=`MaturityRenewal`,e}({});e.Exploration,e.ProblemSolutionFit,e.MvpEarlyTraction,e.ProductMarketFit,e.GrowthScaleUp,e.ExpansionPlatform,e.MaturityRenewal;const t={[e.Exploration]:{id:e.Exploration,order:0,slug:`exploration`,name:`Exploration / Ideation`,question:`Is there a problem worth my time?`,signals:[`20+ discovery interviews`,`Clear problem statement`,`Named ICP`],traps:[`Branding before discovery`,`Premature tooling decisions`],focusAreas:[`Customer discovery`,`Problem definition`,`Segment clarity`]},[e.ProblemSolutionFit]:{id:e.ProblemSolutionFit,order:1,slug:`problem-solution-fit`,name:`Problem–Solution Fit`,question:`Do people care enough about this solution?`,signals:[`Prototype reuse`,`Referral energy`,`Pre-pay interest`],traps:[`“Market is huge” without users`,`Skipping qualitative loops`],focusAreas:[`Solution hypothesis`,`Value messaging`,`Feedback capture`]},[e.MvpEarlyTraction]:{id:e.MvpEarlyTraction,order:2,slug:`mvp-early-traction`,name:`MVP & Early Traction`,question:`Can we get real usage and learn fast?`,signals:[`20–50 named active users`,`Weekly releases`,`Noisy feedback`],traps:[`Overbuilt infra for 10 users`,`Undefined retention metric`],focusAreas:[`Activation`,`Cohort tracking`,`Feedback rituals`]},[e.ProductMarketFit]:{id:e.ProductMarketFit,order:3,slug:`product-market-fit`,name:`Product–Market Fit`,question:`Is this pulling us forward?`,signals:[`Retention without heroics`,`Organic word-of-mouth`,`Value stories`],traps:[`Hero growth that does not scale`,`Ignoring churn signals`],focusAreas:[`Retention`,`Reliability`,`ICP clarity`]},[e.GrowthScaleUp]:{id:e.GrowthScaleUp,order:4,slug:`growth-scale-up`,name:`Growth / Scale-up`,question:`Can we grow this repeatably?`,signals:[`Predictable channels`,`Specialized hires`,`Unit economics on track`],traps:[`Paid spend masking retention gaps`,`Infra debt blocking launches`],focusAreas:[`Ops systems`,`Growth loops`,`Reliability engineering`]},[e.ExpansionPlatform]:{id:e.ExpansionPlatform,order:5,slug:`expansion-platform`,name:`Expansion / Platform`,question:`What is the next growth curve?`,signals:[`Stable core metrics`,`Partner/API demand`,`Ecosystem pull`],traps:[`Platform theater before wedge is solid`],focusAreas:[`Partnerships`,`APIs`,`New market validation`]},[e.MaturityRenewal]:{id:e.MaturityRenewal,order:6,slug:`maturity-renewal`,name:`Maturity / Renewal`,question:`Optimize, reinvent, or sunset?`,signals:[`Margin focus`,`Portfolio bets`,`Narrative refresh`],traps:[`Assuming past success is enough`],focusAreas:[`Cost optimization`,`Reinvention bets`,`Sunset planning`]}};export{e,t as n};
@@ -1 +0,0 @@
1
- import"../types/stages.js";
@@ -1 +0,0 @@
1
- import"./tracing/index.js";import{i as e,n as t,t as n}from"./metrics/index.js";import{n as r}from"./logging/index.js";import"./tracing/middleware.js";import"./intent/detector.js";import"./pipeline/evolution-pipeline.js";import"./pipeline/lifecycle-pipeline.js";
@@ -1 +0,0 @@
1
- import{randomUUID as e}from"node:crypto";
@@ -1 +0,0 @@
1
- import"./types/stages.js";import"./utils/formatters.js";import"./types/axes.js";import"./types/signals.js";import"./types/milestones.js";
@@ -1 +0,0 @@
1
- (function(e){return e.Sketch=`Sketch`,e.Prototype=`Prototype`,e.Mvp=`MVP`,e.V1=`V1`,e.Ecosystem=`Ecosystem`,e})({}),function(e){return e.Solo=`Solo`,e.TinyTeam=`TinyTeam`,e.FunctionalOrg=`FunctionalOrg`,e.MultiTeam=`MultiTeam`,e.Bureaucratic=`Bureaucratic`,e}({}),function(e){return e.Bootstrapped=`Bootstrapped`,e.PreSeed=`PreSeed`,e.Seed=`Seed`,e.SeriesAorB=`SeriesAorB`,e.LateStage=`LateStage`,e}({});
@@ -1 +0,0 @@
1
- import"./stages.js";
@@ -1 +0,0 @@
1
- import"./stages.js";
@@ -1 +0,0 @@
1
- let e=function(e){return e[e.Exploration=0]=`Exploration`,e[e.ProblemSolutionFit=1]=`ProblemSolutionFit`,e[e.MvpEarlyTraction=2]=`MvpEarlyTraction`,e[e.ProductMarketFit=3]=`ProductMarketFit`,e[e.GrowthScaleUp=4]=`GrowthScaleUp`,e[e.ExpansionPlatform=5]=`ExpansionPlatform`,e[e.MaturityRenewal=6]=`MaturityRenewal`,e}({});e.Exploration,e.ProblemSolutionFit,e.MvpEarlyTraction,e.ProductMarketFit,e.GrowthScaleUp,e.ExpansionPlatform,e.MaturityRenewal,e.Exploration,e.Exploration,e.ProblemSolutionFit,e.ProblemSolutionFit,e.MvpEarlyTraction,e.MvpEarlyTraction,e.ProductMarketFit,e.ProductMarketFit,e.GrowthScaleUp,e.GrowthScaleUp,e.ExpansionPlatform,e.ExpansionPlatform,e.MaturityRenewal,e.MaturityRenewal;
@@ -1 +0,0 @@
1
- import"../types/stages.js";
@@ -1 +0,0 @@
1
- import{context as e,trace as t}from"@opentelemetry/api";var n=class{constructor(e){this.serviceName=e}log(n,r,i={}){let a=t.getSpan(e.active()),o=a?.spanContext().traceId,s=a?.spanContext().spanId,c={timestamp:new Date().toISOString(),service:this.serviceName,level:n,message:r,traceId:o,spanId:s,...i};console.log(JSON.stringify(c))}debug(e,t){this.log(`debug`,e,t)}info(e,t){this.log(`info`,e,t)}warn(e,t){this.log(`warn`,e,t)}error(e,t){this.log(`error`,e,t)}};new n(process.env.OTEL_SERVICE_NAME||`unknown-service`);export{n};
@@ -1 +0,0 @@
1
- import{metrics as e}from"@opentelemetry/api";function t(t=`@lssm/lib.observability`){return e.getMeter(t)}function n(e,n,r){return t(r).createCounter(e,{description:n})}function r(e,n,r){return t(r).createHistogram(e,{description:n})}n(`http_requests_total`,`Total HTTP requests`),r(`http_request_duration_seconds`,`HTTP request duration`),n(`operation_errors_total`,`Total operation errors`),r(`workflow_duration_seconds`,`Workflow execution duration`);export{r as i,n,t};
@@ -1 +0,0 @@
1
- import"../intent/detector.js";import"node:events";
@@ -1 +0,0 @@
1
- import"../metrics/index.js";import"../lifecycle/dist/utils/formatters.js";import"../lifecycle/dist/index.js";import"node:events";
@@ -1 +0,0 @@
1
- import{context as e,trace as t}from"@opentelemetry/api";
@@ -1 +0,0 @@
1
- import"./index.js";import"../metrics/index.js";
package/dist/types.d.ts DELETED
@@ -1,131 +0,0 @@
1
- import { ContractSpec, OpKind, ResourceRefDescriptor } from "@lssm/lib.contracts";
2
- import { AnySchemaModel } from "@lssm/lib.schema";
3
- import { LifecycleStage } from "@lssm/lib.lifecycle";
4
-
5
- //#region src/types.d.ts
6
- type AnomalySeverity = 'low' | 'medium' | 'high';
7
- type SuggestionStatus = 'pending' | 'approved' | 'rejected';
8
- interface OperationCoordinate {
9
- name: string;
10
- version: number;
11
- tenantId?: string;
12
- }
13
- interface OperationMetricSample {
14
- operation: OperationCoordinate;
15
- durationMs: number;
16
- success: boolean;
17
- timestamp: Date;
18
- payloadSizeBytes?: number;
19
- errorCode?: string;
20
- errorMessage?: string;
21
- actor?: string;
22
- channel?: string;
23
- traceId?: string;
24
- metadata?: Record<string, unknown>;
25
- }
26
- interface SpecUsageStats {
27
- operation: OperationCoordinate;
28
- totalCalls: number;
29
- successRate: number;
30
- errorRate: number;
31
- averageLatencyMs: number;
32
- p95LatencyMs: number;
33
- p99LatencyMs: number;
34
- maxLatencyMs: number;
35
- lastSeenAt: Date;
36
- windowStart: Date;
37
- windowEnd: Date;
38
- topErrors: Record<string, number>;
39
- }
40
- interface SuggestionEvidence {
41
- type: 'telemetry' | 'user-feedback' | 'simulation' | 'test';
42
- description: string;
43
- data?: Record<string, unknown>;
44
- }
45
- interface SpecAnomaly {
46
- operation: OperationCoordinate;
47
- severity: AnomalySeverity;
48
- metric: 'latency' | 'error-rate' | 'throughput' | 'policy' | 'schema';
49
- description: string;
50
- detectedAt: Date;
51
- threshold?: number;
52
- observedValue?: number;
53
- evidence: SuggestionEvidence[];
54
- }
55
- interface PatternConfidence {
56
- score: number;
57
- sampleSize: number;
58
- pValue?: number;
59
- }
60
- interface IntentPattern {
61
- id: string;
62
- type: 'latency-regression' | 'error-spike' | 'missing-operation' | 'chained-intent' | 'throughput-drop' | 'schema-mismatch';
63
- description: string;
64
- operation?: OperationCoordinate;
65
- confidence: PatternConfidence;
66
- metadata?: Record<string, unknown>;
67
- evidence: SuggestionEvidence[];
68
- }
69
- interface SpecSuggestionProposal {
70
- summary: string;
71
- rationale: string;
72
- changeType: 'new-spec' | 'revision' | 'policy-update' | 'schema-update';
73
- kind?: OpKind;
74
- spec?: ContractSpec<AnySchemaModel, AnySchemaModel | ResourceRefDescriptor<boolean>>;
75
- diff?: string;
76
- metadata?: Record<string, unknown>;
77
- }
78
- interface SpecSuggestion {
79
- id: string;
80
- intent: IntentPattern;
81
- target?: OperationCoordinate;
82
- proposal: SpecSuggestionProposal;
83
- confidence: number;
84
- createdAt: Date;
85
- createdBy: string;
86
- status: SuggestionStatus;
87
- evidence: SuggestionEvidence[];
88
- priority: 'low' | 'medium' | 'high';
89
- tags?: string[];
90
- approvals?: {
91
- reviewer?: string;
92
- notes?: string;
93
- decidedAt?: Date;
94
- status?: SuggestionStatus;
95
- };
96
- }
97
- interface EvolutionConfig {
98
- minConfidence?: number;
99
- autoApproveThreshold?: number;
100
- maxSuggestionsPerOperation?: number;
101
- requireApproval?: boolean;
102
- maxConcurrentExperiments?: number;
103
- }
104
- interface SpecSuggestionFilters {
105
- status?: SuggestionStatus;
106
- operationName?: string;
107
- }
108
- interface SpecSuggestionRepository {
109
- create(suggestion: SpecSuggestion): Promise<void>;
110
- getById(id: string): Promise<SpecSuggestion | undefined>;
111
- updateStatus(id: string, status: SuggestionStatus, metadata?: {
112
- reviewer?: string;
113
- notes?: string;
114
- decidedAt?: Date;
115
- }): Promise<void>;
116
- list(filters?: SpecSuggestionFilters): Promise<SpecSuggestion[]>;
117
- }
118
- interface SpecSuggestionWriter {
119
- write(suggestion: SpecSuggestion): Promise<string>;
120
- }
121
- interface OptimizationHint {
122
- operation: OperationCoordinate;
123
- category: 'schema' | 'policy' | 'performance' | 'error-handling';
124
- summary: string;
125
- justification: string;
126
- recommendedActions: string[];
127
- lifecycleStage?: LifecycleStage;
128
- lifecycleNotes?: string;
129
- }
130
- //#endregion
131
- export { AnomalySeverity, EvolutionConfig, IntentPattern, OperationCoordinate, OperationMetricSample, OptimizationHint, PatternConfidence, SpecAnomaly, SpecSuggestion, SpecSuggestionFilters, SpecSuggestionProposal, SpecSuggestionRepository, SpecSuggestionWriter, SpecUsageStats, SuggestionEvidence, SuggestionStatus };