@lssm/lib.evolution 0.0.0-canary-20251206160926
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -0
- package/dist/ai-agent/dist/approval/index.js +1 -0
- package/dist/ai-agent/dist/approval/workflow.js +1 -0
- package/dist/analyzer/spec-analyzer.d.ts +34 -0
- package/dist/analyzer/spec-analyzer.js +1 -0
- package/dist/approval/integration.d.ts +42 -0
- package/dist/approval/integration.js +1 -0
- package/dist/generator/ai-spec-generator.d.ts +55 -0
- package/dist/generator/ai-spec-generator.js +19 -0
- package/dist/generator/spec-generator.d.ts +46 -0
- package/dist/generator/spec-generator.js +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -0
- package/dist/lifecycle/dist/index.js +1 -0
- package/dist/lifecycle/dist/types/axes.js +1 -0
- package/dist/lifecycle/dist/types/milestones.js +1 -0
- package/dist/lifecycle/dist/types/signals.js +1 -0
- package/dist/lifecycle/dist/types/stages.js +1 -0
- package/dist/lifecycle/dist/utils/formatters.js +1 -0
- package/dist/observability/dist/index.js +1 -0
- package/dist/observability/dist/intent/detector.js +1 -0
- package/dist/observability/dist/lifecycle/dist/index.js +1 -0
- package/dist/observability/dist/lifecycle/dist/types/axes.js +1 -0
- package/dist/observability/dist/lifecycle/dist/types/milestones.js +1 -0
- package/dist/observability/dist/lifecycle/dist/types/signals.js +1 -0
- package/dist/observability/dist/lifecycle/dist/types/stages.js +1 -0
- package/dist/observability/dist/lifecycle/dist/utils/formatters.js +1 -0
- package/dist/observability/dist/logging/index.js +1 -0
- package/dist/observability/dist/metrics/index.js +1 -0
- package/dist/observability/dist/pipeline/evolution-pipeline.js +1 -0
- package/dist/observability/dist/pipeline/lifecycle-pipeline.js +1 -0
- package/dist/observability/dist/tracing/index.js +1 -0
- package/dist/observability/dist/tracing/middleware.js +1 -0
- package/dist/types.d.ts +131 -0
- package/package.json +49 -0
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# @lssm/lib.evolution
|
|
2
|
+
|
|
3
|
+
**Safe regeneration for ContractSpec** — Evolve specs automatically while preserving invariants.
|
|
4
|
+
|
|
5
|
+
Auto-evolution utilities that analyze telemetry, suggest spec improvements, and route changes through approval workflows. Regenerate code safely, one module at a time.
|
|
6
|
+
|
|
7
|
+
## Capabilities:
|
|
8
|
+
|
|
9
|
+
- Analyze telemetry to find anomalous specs
|
|
10
|
+
- Convert detected intent into spec suggestions
|
|
11
|
+
- Route suggestions through the AI approval workflow
|
|
12
|
+
- Persist approved specs back into the codebase
|
|
13
|
+
|
|
14
|
+
> Phase 3 anchor library – pairs with `@lssm/lib.observability` and `@lssm/lib.growth`.
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {
|
|
20
|
+
SpecAnalyzer,
|
|
21
|
+
SpecGenerator,
|
|
22
|
+
SpecSuggestionOrchestrator,
|
|
23
|
+
} from '@lssm/lib.evolution';
|
|
24
|
+
|
|
25
|
+
const analyzer = new SpecAnalyzer();
|
|
26
|
+
const stats = analyzer.analyzeSpecUsage(samples);
|
|
27
|
+
const anomalies = analyzer.detectAnomalies(stats);
|
|
28
|
+
|
|
29
|
+
const generator = new SpecGenerator({ getSpec });
|
|
30
|
+
const suggestion = generator.generateFromIntent(anomalies[0]);
|
|
31
|
+
|
|
32
|
+
await orchestrator.submit(suggestion, { agent: 'auto-evolve' });
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
See `app/docs/libraries/evolution` in `@lssm/app.web-contractspec-landing` for full docs.
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./workflow.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as e}from"node:crypto";
|
|
@@ -0,0 +1,34 @@
|
|
|
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 };
|
|
@@ -0,0 +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};
|
|
@@ -0,0 +1,42 @@
|
|
|
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 };
|
|
@@ -0,0 +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({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/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};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { EvolutionConfig, IntentPattern, SpecSuggestion } from "../types.js";
|
|
2
|
+
import { LanguageModel } from "ai";
|
|
3
|
+
|
|
4
|
+
//#region src/generator/ai-spec-generator.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for the AI-powered spec generator.
|
|
8
|
+
*/
|
|
9
|
+
interface AISpecGeneratorConfig {
|
|
10
|
+
/** AI SDK language model */
|
|
11
|
+
model: LanguageModel;
|
|
12
|
+
/** Evolution configuration */
|
|
13
|
+
evolutionConfig?: EvolutionConfig;
|
|
14
|
+
/** Custom system prompt */
|
|
15
|
+
systemPrompt?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* AI-powered spec generator using AI SDK v6.
|
|
19
|
+
*
|
|
20
|
+
* Uses structured output (Output.object) to generate
|
|
21
|
+
* well-formed spec suggestions from intent patterns.
|
|
22
|
+
*/
|
|
23
|
+
declare class AISpecGenerator {
|
|
24
|
+
private readonly model;
|
|
25
|
+
private readonly config;
|
|
26
|
+
private readonly systemPrompt;
|
|
27
|
+
constructor(options: AISpecGeneratorConfig);
|
|
28
|
+
/**
|
|
29
|
+
* Generate a spec suggestion from an intent pattern using AI.
|
|
30
|
+
*/
|
|
31
|
+
generateFromIntent(intent: IntentPattern, options?: {
|
|
32
|
+
additionalContext?: string;
|
|
33
|
+
existingSpec?: Record<string, unknown>;
|
|
34
|
+
}): Promise<SpecSuggestion>;
|
|
35
|
+
/**
|
|
36
|
+
* Generate multiple suggestions for a batch of intents.
|
|
37
|
+
*/
|
|
38
|
+
generateBatch(intents: IntentPattern[], options?: {
|
|
39
|
+
maxConcurrent?: number;
|
|
40
|
+
}): Promise<SpecSuggestion[]>;
|
|
41
|
+
/**
|
|
42
|
+
* Validate and enhance an existing suggestion using AI.
|
|
43
|
+
*/
|
|
44
|
+
enhanceSuggestion(suggestion: SpecSuggestion): Promise<SpecSuggestion>;
|
|
45
|
+
private buildPrompt;
|
|
46
|
+
private buildSuggestion;
|
|
47
|
+
private calculatePriority;
|
|
48
|
+
private determineInitialStatus;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Create an AI-powered spec generator.
|
|
52
|
+
*/
|
|
53
|
+
declare function createAISpecGenerator(config: AISpecGeneratorConfig): AISpecGenerator;
|
|
54
|
+
//#endregion
|
|
55
|
+
export { AISpecGenerator, AISpecGeneratorConfig, createAISpecGenerator };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{Output as t,generateText as n}from"ai";import{z 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};
|
|
@@ -0,0 +1,46 @@
|
|
|
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 };
|
|
@@ -0,0 +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};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
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 { AISpecGenerator, AISpecGeneratorConfig, createAISpecGenerator } from "./generator/ai-spec-generator.js";
|
|
5
|
+
import { FileSystemSuggestionWriter, FileSystemSuggestionWriterOptions, InMemorySpecSuggestionRepository, SpecSuggestionOrchestrator, SpecSuggestionOrchestratorOptions } from "./approval/integration.js";
|
|
6
|
+
export { AISpecGenerator, AISpecGeneratorConfig, 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, createAISpecGenerator };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
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";
|
|
@@ -0,0 +1 @@
|
|
|
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}({});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./stages.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./stages.js";
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"../types/stages.js";
|
|
@@ -0,0 +1 @@
|
|
|
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";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as e}from"node:crypto";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./types/stages.js";import"./utils/formatters.js";import"./types/axes.js";import"./types/signals.js";import"./types/milestones.js";
|
|
@@ -0,0 +1 @@
|
|
|
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}({});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./stages.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./stages.js";
|
|
@@ -0,0 +1 @@
|
|
|
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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"../types/stages.js";
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"../intent/detector.js";import"node:events";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"../metrics/index.js";import"../lifecycle/dist/utils/formatters.js";import"../lifecycle/dist/index.js";import"node:events";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{context as e,trace as t}from"@opentelemetry/api";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./index.js";import"../metrics/index.js";
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
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 };
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lssm/lib.evolution",
|
|
3
|
+
"version": "0.0.0-canary-20251206160926",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"publish:pkg": "bun publish --tolerate-republish --ignore-scripts --verbose",
|
|
14
|
+
"build": "bun build:bundle && bun build:types",
|
|
15
|
+
"build:bundle": "tsdown",
|
|
16
|
+
"build:types": "tsc --noEmit",
|
|
17
|
+
"dev": "bun build:bundle --watch",
|
|
18
|
+
"clean": "rimraf dist .turbo",
|
|
19
|
+
"lint": "bun lint:fix",
|
|
20
|
+
"lint:fix": "eslint src --fix",
|
|
21
|
+
"lint:check": "eslint src",
|
|
22
|
+
"test": "bun test"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
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:*"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@prisma/client": "7.1.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@lssm/tool.tsdown": "workspace:*",
|
|
38
|
+
"@lssm/tool.typescript": "workspace:*",
|
|
39
|
+
"tsdown": "^0.17.0",
|
|
40
|
+
"typescript": "^5.9.3"
|
|
41
|
+
},
|
|
42
|
+
"exports": {
|
|
43
|
+
".": "./dist/index.js",
|
|
44
|
+
"./*": "./*"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
}
|
|
49
|
+
}
|