@devflow-tools/devflow 0.8.11 → 0.9.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.
- package/dist/hooks/post-tool-use.js +2 -2
- package/package.json +13 -13
- package/dist/cli.js +0 -46
- package/dist/fallback.html +0 -106
- package/dist/mcp-server.js +0 -2
- package/dist/plugin/hooks.json +0 -52
- package/dist/plugin/skills/devflow/SKILL.md +0 -20
- package/dist/plugin/skills/devflow:animation/SKILL.md +0 -38
- package/dist/plugin/skills/devflow:context/SKILL.md +0 -44
- package/dist/plugin/skills/devflow:css/SKILL.md +0 -38
- package/dist/plugin/skills/devflow:docker/SKILL.md +0 -42
- package/dist/plugin/skills/devflow:doctor/SKILL.md +0 -17
- package/dist/plugin/skills/devflow:electron/SKILL.md +0 -42
- package/dist/plugin/skills/devflow:git/SKILL.md +0 -42
- package/dist/plugin/skills/devflow:graph/SKILL.md +0 -37
- package/dist/plugin/skills/devflow:graphql/SKILL.md +0 -41
- package/dist/plugin/skills/devflow:knowledge/SKILL.md +0 -37
- package/dist/plugin/skills/devflow:memory/SKILL.md +0 -36
- package/dist/plugin/skills/devflow:nest/SKILL.md +0 -41
- package/dist/plugin/skills/devflow:nextjs/SKILL.md +0 -38
- package/dist/plugin/skills/devflow:performance/SKILL.md +0 -42
- package/dist/plugin/skills/devflow:react/SKILL.md +0 -50
- package/dist/plugin/skills/devflow:start/SKILL.md +0 -54
- package/dist/plugin/skills/devflow:tailwind/SKILL.md +0 -38
- package/dist/plugin/skills/devflow:taro/SKILL.md +0 -41
- package/dist/plugin/skills/devflow:ui-layout/SKILL.md +0 -38
- package/dist/plugin/skills/devflow:vue/SKILL.md +0 -45
- package/dist/plugin/skills/devflow:workflow/SKILL.md +0 -37
- package/dist/server.js +0 -10
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: devflow:workflow
|
|
3
|
-
description: 执行标准化开发工作流 — Bug 修复、功能开发、代码审查
|
|
4
|
-
required_mcp_tools:
|
|
5
|
-
- run_workflow
|
|
6
|
-
---
|
|
7
|
-
## MANDATORY FIRST STEP - Skill Registration
|
|
8
|
-
|
|
9
|
-
> **IMPORTANT: Before ANY other action, execute the registration command below. This is NON-NEGOTIABLE.**
|
|
10
|
-
|
|
11
|
-
```bash
|
|
12
|
-
mkdir -p ~/.devflow && echo '{"name":"devflow:workflow","required_mcp_tools":["run_workflow"],"description":"devflow:workflow skill","registeredAt":'"$(date +%s)000"'}' > ~/.devflow/current-skill.json
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
After registration, you **MUST** use ONLY these MCP tools for all work in this skill:
|
|
16
|
-
- `mcp__devflow__run_workflow`
|
|
17
|
-
|
|
18
|
-
**Never use direct tools** (Read, Write, Edit, Bash, Grep, etc.) for tasks that can be handled by the MCP tools above.
|
|
19
|
-
|
|
20
|
-
When the skill execution is complete, clean up:
|
|
21
|
-
```bash
|
|
22
|
-
rm -f ~/.devflow/current-skill.json ~/.devflow/current-execution-id
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
# /devflow:workflow
|
|
27
|
-
|
|
28
|
-
## 执行
|
|
29
|
-
|
|
30
|
-
调用 `run_workflow` MCP 工具:
|
|
31
|
-
|
|
32
|
-
```
|
|
33
|
-
type = "bugfix" | "feature" | "review"
|
|
34
|
-
input = 用户的查询内容
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
MCP 工具提供标准化的 DAG 步骤编排、人工确认节点、执行追踪和遥测记录。工作流执行过程中,MCP 工具会返回需要你介入的步骤,此时才根据步骤指引执行具体操作。
|
package/dist/server.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import'reflect-metadata';import {Reflector,APP_GUARD,APP_INTERCEPTOR,NestFactory}from'@nestjs/core';import {FastifyAdapter}from'@nestjs/platform-fastify';import {Readable}from'stream';import {Injectable,Inject,Global,Module,Optional,Get,Query,Param,Post,Body,Delete,Controller,Headers,Put,forwardRef,Res,Catch,UnauthorizedException,NotFoundException,BadRequestException,SetMetadata,Logger,HttpException,HttpStatus}from'@nestjs/common';import {existsSync,readFileSync}from'fs';import {join}from'path';import {createEngines}from'@devflow-tools/context-engine';import {TelemetryEngine}from'@devflow-tools/telemetry';import {MemoryEngine,checkOllama,getOllamaInfoMessage}from'@devflow-tools/memory-engine';import {WorkflowEngine}from'@devflow-tools/workflow-engine';import {clearPluginCache,loadPlugins}from'@devflow-tools/sdk';import {Subject}from'rxjs';import {KnowledgeEngine}from'@devflow-tools/knowledge-engine';import {BenchmarkEngine}from'@devflow-tools/benchmark';import {DevFlowDatabase}from'@devflow-tools/database';import {homedir}from'os';import {map}from'rxjs/operators';var be=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var i=(c,t,e,s)=>{for(var n=s>1?void 0:s?Pe(t,e):t,o=c.length-1,a;o>=0;o--)(a=c[o])&&(n=(s?a(t,e,n):a(n))||n);return s&&n&&be(t,e,n),n},r=(c,t)=>(e,s)=>t(e,s,c);var Et="isPublic",Yt=()=>SetMetadata(Et,true);var xt={MISSING_API_KEY:"AUTH_MISSING_API_KEY",INVALID_API_KEY:"AUTH_INVALID_API_KEY"};var xe=(process.env.DEVFLOW_API_KEYS??"dev-key-000000").split(",").map(c=>c.trim()).filter(Boolean),Y=class{constructor(t){this.reflector=t;}canActivate(t){if(this.reflector.getAllAndOverride(Et,[t.getHandler(),t.getClass()]))return true;let n=t.switchToHttp().getRequest().headers["x-api-key"];if(!n)throw new UnauthorizedException({error:{code:xt.MISSING_API_KEY,message:"X-API-Key header is required",details:{}}});if(!xe.includes(n))throw new UnauthorizedException({error:{code:xt.INVALID_API_KEY,message:"Invalid API key",details:{}}});return true}};Y=i([Injectable(),r(0,Inject(Reflector))],Y);var z=class{};z=i([Global(),Module({providers:[Y,{provide:APP_GUARD,useClass:Y}]})],z);var d={WORKFLOW_NOT_FOUND:"WORKFLOW_NOT_FOUND",RUN_NOT_FOUND:"RUN_NOT_FOUND",PROJECT_NOT_FOUND:"PROJECT_NOT_FOUND",NODE_NOT_FOUND:"NODE_NOT_FOUND",PLUGIN_NOT_FOUND:"PLUGIN_NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",VALIDATION_ERROR:"VALIDATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};var p=class{constructor(t){this.database=t;this.projects=new Map;this.activeProjectRoot=process.env.DEVFLOW_PROJECT_ROOT??null;}onModuleInit(){if(!process.env.DEVFLOW_PROJECT_ROOT&&this.database){let t=this.database.getSetting("activeProjectRoot");t&&(this.activeProjectRoot=t);}}setActiveProject(t){this.activeProjectRoot=t,this.database&&this.database.setSetting("activeProjectRoot",t);}disconnectProject(){this.activeProjectRoot=null,this.database&&this.database.deleteSetting("activeProjectRoot");}getActiveProjectRoot(){return this.activeProjectRoot}async list(){return Array.from(this.projects.values())}async getById(t){let e=this.projects.get(t);if(!e)throw new NotFoundException({error:{code:d.PROJECT_NOT_FOUND,message:`Project "${t}" not found`,details:{}}});return e}async create(t){let e=`proj_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,s={id:e,name:t.name,rootPath:t.rootPath,stack:t.stack,createdAt:Date.now()};return this.projects.set(e,s),this.activeProjectRoot||this.setActiveProject(t.rootPath),s}async delete(t){if(!this.projects.has(t))throw new NotFoundException({error:{code:d.PROJECT_NOT_FOUND,message:`Project "${t}" not found`,details:{}}});this.projects.delete(t);}async getOnboardingPack(t){let e=join(t,".devflow","onboarding-pack.json");if(!existsSync(e))throw new NotFoundException({error:{code:d.PROJECT_NOT_FOUND,message:"Onboarding pack not found. Run `devflow init` first.",details:{}}});return JSON.parse(readFileSync(e,"utf-8"))}async getOnboardingPackByRoot(t){let e=join(t,".devflow","onboarding-pack.json");try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}};p=i([Injectable(),r(0,Optional()),r(0,Inject("DATABASE"))],p);var h=class{constructor(t){this.service=t;}async list(){return this.service.list()}async getOnboardingPackByRoot(t){if(!t)throw new BadRequestException({error:{code:d.BAD_REQUEST,message:"rootPath is required",details:{}}});return this.service.getOnboardingPackByRoot(t)}async getById(t){return this.service.getById(t)}async getOnboardingPack(t){let e=await this.service.getById(t);return this.service.getOnboardingPack(e.rootPath)}async create(t){return this.service.create(t)}async connect(t){return this.service.setActiveProject(t.rootPath),{rootPath:t.rootPath}}async switchProject(t){return this.service.setActiveProject(t.rootPath),{rootPath:t.rootPath}}async getActive(){return {rootPath:this.service.getActiveProjectRoot()}}async disconnect(){return this.service.disconnectProject(),{ok:true}}async delete(t){return this.service.delete(t)}};i([Get()],h.prototype,"list",1),i([Get("onboarding-pack"),r(0,Query("rootPath"))],h.prototype,"getOnboardingPackByRoot",1),i([Get(":id"),r(0,Param("id"))],h.prototype,"getById",1),i([Get(":id/onboarding-pack"),r(0,Param("id"))],h.prototype,"getOnboardingPack",1),i([Post(),r(0,Body())],h.prototype,"create",1),i([Post("connect"),r(0,Body())],h.prototype,"connect",1),i([Post("switch"),r(0,Body())],h.prototype,"switchProject",1),i([Get("active")],h.prototype,"getActive",1),i([Delete("active")],h.prototype,"disconnect",1),i([Delete(":id"),r(0,Param("id"))],h.prototype,"delete",1),h=i([Controller("projects"),r(0,Inject(p))],h);var v=class{};v=i([Module({controllers:[h],providers:[p],exports:[p]})],v);var P=class{constructor(t){this.engine=new TelemetryEngine;this.db=t??null;}async recordEvent(t){this.db&&this.db.insertEvent?.({runId:t.runId,kind:t.kind,timestamp:t.timestamp,duration:t.duration,toolName:t.data?.toolName,pluginName:t.data?.mcpToolName,metadata:t.data});}async createSession(t){this.db&&this.db.insertSession({id:t.id,projectRoot:t.projectRoot,label:t.label,startedAt:t.startedAt});}async getSession(t){if(!this.db)throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Session "${t}" not found`,details:{}}});let e=this.db.getSession(t);if(!e)throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Session "${t}" not found`,details:{}}});return e}async listSessions(t,e,s){return this.db?this.db.listSessions(t,e,s):[]}async getSessionEvents(t){return this.db?this.db.listToolCallEventsBySession?.(t)??[]:[]}async closeSession(t,e){this.db&&this.db.closeSession(t,e);}async createSkillExecution(t){this.db&&this.db.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running"});}async listRuns(t,e,s){if(this.db)try{return this.db.listSessions(t,e).map(o=>({id:o.id,agent:"claude-code",mode:"hook",source:"hook",status:o.status,startedAt:o.startedAt,totalToolCalls:o.totalToolCalls,mcpToolCalls:o.mcpToolCalls,mcpComplianceRate:o.mcpToolCalls>0?Math.round(o.mcpToolCalls/o.totalToolCalls*100)/100:0}))}catch{}return []}async getRun(t){if(this.db)try{let s=this.db.getSession(t);if(s)return {meta:{runId:s.id,agent:"claude-code",mode:"hook",source:"hook"},status:s.status,startedAt:s.startedAt,finishedAt:s.finishedAt,totalToolCalls:s.totalToolCalls,mcpToolCalls:s.mcpToolCalls,steps:[]};let n=this.db.getSkillExecution(t);if(n)return {meta:{runId:n.executionId,agent:"claude-code",mode:"hook",source:"hook"},status:n.status,startedAt:n.startedAt,finishedAt:n.finishedAt,skillName:n.skillName,totalToolCalls:n.totalToolCalls,mcpToolCalls:n.mcpToolCalls,mcpComplianceRate:n.mcpComplianceRate,steps:[]}}catch{}let e=this.engine.runs.get(t);if(e)return e;throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Run "${t}" not found`,details:{}}})}async getTimeline(t,e){if(!this.db)return [];try{return this.db.listSessions(500,0).filter(n=>!(t&&n.startedAt<Number(t)||e&&n.startedAt>Number(e))).map(n=>({runId:n.id,stepId:n.id,type:"session",duration:n.durationMs,timestamp:n.startedAt}))}catch{return []}}async getRunEvents(t){if(this.db)try{let s=this.db.listToolCallEventsBySession(t);if(s&&s.length>0)return s;let n=this.db.listToolCallEvents(t);if(n&&n.length>0)return n}catch{}return await this.engine.listEvents(t)??[]}async getRunStats(t){if(this.db)try{let e=this.db.listToolCallEventsBySession(t)??this.db.listToolCallEvents(t)??[];if(e.length>0)return {totalEvents:e.length,llmCalls:0,totalTokens:0,toolUses:e.length,fileReads:0,fileWrites:0,bashCommands:0,errors:e.filter(s=>s.error).length,totalDuration:0,mcpToolCalls:e.filter(s=>s.isMcpTool).length,directToolCalls:e.filter(s=>!s.isMcpTool).length,mcpComplianceRate:e.length>0?e.filter(s=>s.isMcpTool).length/e.length:0}}catch{}return this.engine.getRunStats(t)}async endRun(t,e){await this.engine.endRun(t,e);}async getStats(t=7){if(!this.db)return this.emptyStats();let e=Date.now(),s=e-t*24*60*60*1e3;try{let o=this.db.listSessions(1e3,0).filter(u=>u.startedAt>=s),a={},l=0;for(let u of o){let y=new Date(u.startedAt).toISOString().slice(0,10);a[y]||(a[y]={runs:0}),a[y].runs++,l+=u.totalToolCalls??0;}return {period:{from:new Date(s).toISOString().slice(0,10),to:new Date(e).toISOString().slice(0,10)},summary:{totalRuns:o.length,completedRuns:o.filter(u=>u.status==="completed").length,failedRuns:o.filter(u=>u.status==="failed").length,totalTokens:0,totalLlmCalls:0,totalToolUses:l,avgRunDuration:o.length>0?Math.round(o.reduce((u,y)=>u+(y.durationMs??0),0)/o.length):0},byDay:Object.entries(a).map(([u,y])=>({date:u,tokens:0,...y})).sort((u,y)=>u.date.localeCompare(y.date)),byWorkflow:[],byPlugin:[]}}catch{return this.emptyStats()}}emptyStats(){return {period:{from:"",to:""},summary:{totalRuns:0,completedRuns:0,failedRuns:0,totalTokens:0,totalLlmCalls:0,totalToolUses:0,avgRunDuration:0},byDay:[],byWorkflow:[],byPlugin:[]}}async getRoiSummary(t=7){if(!this.db)return this.emptyRoiSummary();let e=Date.now(),s=e-t*24*60*60*1e3;try{let o=this.db.listSessions(1e3,0).filter(g=>g.startedAt>=s),a=o.length,l=o.filter(g=>g.status==="completed").length,u=o.filter(g=>g.status==="failed").length,y=a>0?Math.round(o.reduce((g,R)=>g+(R.durationMs??0),0)/a):0,mt={};for(let g of o){let R=new Date(g.startedAt).toISOString().slice(0,10);mt[R]||(mt[R]={runs:0,failures:0}),mt[R].runs++,g.status!=="completed"&&mt[R].failures++;}let Qt=this.db.listToolCallEventsBySessions(o.map(g=>g.id)),yt={tool_error:0,mcp_unavailable:0,unknown:0},St={};for(let g of o){let R=Qt[g.id]??[];for(let K of R){if(K.error){let k=K.error.toLowerCase();k.includes("mcp")||k.includes("unavailable")||k.includes("not found")?yt.mcp_unavailable++:k.includes("tool")||k.includes("command")||k.includes("error")?yt.tool_error++:yt.unknown++;}if(K.mcpToolName){let k=K.mcpToolName.split("_")[0];k&&(St[k]=(St[k]??0)+1);}}}return {period:{from:new Date(s).toISOString().slice(0,10),to:new Date(e).toISOString().slice(0,10)},overview:{totalRuns:a,completedRuns:l,failedRuns:u,avgDuration:y,firstPassSuccessRate:a>0?Math.round(l/a*1e4)/100:0},efficiency:{avgTimePerTask:y},failures:{total:u,breakdown:yt},workflows:[],plugins:Object.entries(St).map(([g,R])=>{let K=o.filter(kt=>(Qt[kt.id]??[]).some(Re=>Re.mcpToolName?.startsWith(g+"_"))),k=K.filter(kt=>kt.status==="completed").length,ye=K.length>0?Math.round(k/K.length*1e4)/100:0;return {name:g,runs:R,successRate:ye}}),byDay:Object.entries(mt).map(([g,R])=>({date:g,...R,tokens:0})).sort((g,R)=>g.date.localeCompare(R.date))}}catch{return this.emptyRoiSummary()}}emptyRoiSummary(){return {period:{from:"",to:""},overview:{totalRuns:0,completedRuns:0,failedRuns:0,avgDuration:0,avgTokens:0,firstPassSuccessRate:0,feedbackHitRate:0},efficiency:{totalTokensSaved:0,avgTimePerTask:0,avgRetryCount:0},failures:{total:0,breakdown:{tool_error:0,mcp_unavailable:0,unknown:0}},workflows:[],plugins:[],byDay:[]}}async recordExecutionStart(t){this.db&&this.db.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running"});}async recordToolCall(t){this.db&&this.db.insertToolCallEvent({eventId:t.eventId,executionId:t.executionId,sessionId:t.sessionId,timestamp:t.timestamp,toolName:t.toolName,toolType:t.toolType,isMcpTool:t.isMcpTool,mcpToolName:t.mcpToolName,mcpEnforced:t.mcpEnforced,mcpFallback:t.mcpFallback,kind:t.kind??"tool_use",input:t.input,duration:t.duration,parentToolCallId:t.parentToolCallId,subagentId:t.subagentId,error:t.error,blocked:t.blocked,blockReason:t.blockReason});}async updateToolCallOutput(t,e,s,n){this.db&&this.db.updateToolCallEvent(t,{output:JSON.stringify(e),duration:n});}async recordExecutionComplete(t){this.db&&this.db.updateSkillExecution(t.executionId,{status:t.status,finishedAt:t.finishedAt,totalDuration:t.summary.totalDuration,mcpComplianceRate:t.summary.mcpComplianceRate,totalToolCalls:t.summary.totalToolCalls,mcpToolCalls:t.summary.mcpToolCalls,directToolCalls:t.summary.directToolCalls,subagentCount:t.summary.subagentCount});}async getExecutions(t,e){return this.db?this.db.listSkillExecutions(t,e):[]}async getExecutionEvents(t){return this.db?this.db.listToolCallEvents(t):[]}async getMcpCompliance(){return this.db?this.db.getMcpCompliance():{overall:0,bySkill:{},missedTools:[]}}async classifyFailure(t){let e=await this.getRun(t).catch(()=>null);if(!e||e.status!=="failed")return {};let s=e.steps?.find(o=>o.status==="failed");if(!s)return {};let n=s.error?.toLowerCase()??"";return n.includes("context")||n.includes("insufficient")?{failureCategory:"context_insufficient",failureReason:"Context provided was insufficient for the task",suggestedActions:[{action:"Supplement task context",priority:"high"},{action:"View graph roots",priority:"medium"},{action:"Add related memory",priority:"medium"}]}:n.includes("knowledge")||n.includes("docs")?{failureCategory:"knowledge_missing",failureReason:"Required knowledge was not available",suggestedActions:[{action:"Sync knowledge source",priority:"high"},{action:"Add docs source",priority:"medium"}]}:n.includes("workflow")||n.includes("step")?{failureCategory:"workflow_design_issue",failureReason:"Workflow design issue detected",suggestedActions:[{action:"Adjust specific step",priority:"high"},{action:"Split workflow",priority:"medium"}]}:n.includes("tool")||n.includes("connection")?{failureCategory:"tool_error",failureReason:"Tool execution error",suggestedActions:[{action:"Check tool connectivity",priority:"high"},{action:"Retry or fallback",priority:"medium"}]}:{failureCategory:"agent_override",failureReason:"Agent override detected",suggestedActions:[{action:"Enable/strengthen enforcer",priority:"high"}]}}async cleanup(t){if(!this.db)return 0;try{this.db.cleanupStaleRecords?.();}catch{}let e=this.engine.runs,s=Date.now()-t*24*60*60*1e3,n=0;for(let[o,a]of e)a.startedAt&&a.startedAt<s&&(e.delete(o),n++);return n}async cleanupStaleRecords(){if(this.db)try{this.db.cleanupStaleRecords?.();}catch{}}async getFeedbackStats(t,e){return {total:0,hits:0,partials:0,misses:0,hitRate:0,partialRate:0,missRate:0}}async getOpsRoiSummary(){return {period:"all-time",totalRuns:0,successfulRuns:0,successRate:0,avgTokenUsage:0,avgDuration:0,feedbackHitRate:0,trend:"stable"}}async getExperimentalRoiSummary(){return {totalScenarios:0,avgTimeSavedRate:null,avgTokenReductionRate:null,avgFirstPassLift:null,avgReworkReductionRate:null,conclusion:"No experimental data available yet"}}async getPluginEffectiveness(t,e){if(!this.db)return {name:t,totalRuns:0,successRate:0,lastUsedAt:null};let s=this.db.listSessions(1e3,0),n=0;for(let o of s){let a=this.db.listToolCallEventsBySession(o.id);for(let l of a)l.mcpToolName?.startsWith(t+"_")&&n++;}return {name:t,totalRuns:n,successRate:0,lastUsedAt:null}}async getPluginUsageStats(t){let e=await this.getPluginEffectiveness(t);return {activeProjects:0,totalRuns:e.totalRuns,successfulRuns:0,lastUsedAt:e.lastUsedAt??void 0}}};P=i([Injectable(),r(0,Optional()),r(0,Inject("DATABASE"))],P);var j=class{constructor(t,e){this.telemetryService=t;this.database=e;this.projectStats=new Map;this.benchmarkResults=[];}async recordTelemetryEvent(t){let e=`evt_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,s=t.toolName?"tool_use":"step_end",n={id:e,runId:t.metadata?.runId??`event_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,stepId:e,kind:s,timestamp:Date.now(),duration:t.durationMs,data:{toolName:t.toolName,toolInput:t.args,errorMessage:t.error},metadata:{source:"claude-code"}};return await this.telemetryService.recordEvent(n),{eventId:e}}async getProjectStats(t){return this.database?this.database.getProjectStats(t):this.projectStats.get(t)??null}async updateProjectStats(t,e){if(this.database){let a={...await this.getProjectStats(t)??{projectRoot:t,totalRuns:0,successfulRuns:0,totalTokens:0,lastActiveAt:Date.now(),topTools:[]},...e,lastActiveAt:Date.now()};return await this.database.upsertProjectStats(a),a}let n={...this.projectStats.get(t)??{projectRoot:t,totalRuns:0,successfulRuns:0,totalTokens:0,lastActiveAt:Date.now(),topTools:[]},...e,lastActiveAt:Date.now()};return this.projectStats.set(t,n),n}recordBenchmarkResult(t){this.benchmarkResults.push(t);}getBenchmarkResults(t){return t?this.benchmarkResults.filter(e=>this.projectStats.get(e.scenarioId)?.projectRoot===t):this.benchmarkResults}async getPluginEffectiveness(t){return []}};j=i([Injectable(),r(0,Inject(P)),r(1,Optional()),r(1,Inject("DATABASE"))],j);var F=class{constructor(t){this.dataService=t;this.feedbackEntries=[];}async indexProject(t){let{context:e,codegraph:s}=await createEngines(t);await e.index(t);let n=s.getStats();return {totalFiles:n.fileCount,totalSymbols:n.nodeCount,lastIndexTime:n.lastUpdated,indexing:s.isIndexing()}}async getStatus(t){try{let{codegraph:e}=await createEngines(t),s=e.getStats();return {totalFiles:s.fileCount,totalSymbols:s.nodeCount,lastIndexTime:s.lastUpdated,indexing:e.isIndexing()}}catch{return {totalFiles:0,totalSymbols:0,lastIndexTime:0,indexing:false}}}async buildContext(t,e,s,n){let{context:o}=await createEngines(t);return o.build({query:e,mode:s,maxTokens:n??8e3,includeGraph:s==="deep"})}async buildTaskContext(t,e,s,n){let{context:o}=await createEngines(t);return o.buildTaskContext(e,{mode:s,maxTokens:n??8e3})}async findSymbol(t,e){let{indexer:s}=await createEngines(t);return s.findSymbol(e)}async recordFeedback(t,e,s,n){let o={query:e,feedback:s,timestamp:Date.now(),projectRoot:t};return this.feedbackEntries.push(o),this.dataService&&await this.dataService.recordTelemetryEvent({toolName:"context_feedback",args:{query:e,feedback:s,taskType:n?.taskType,contextMode:n?.contextMode,projectRoot:t},durationMs:0,success:true,metadata:{projectRoot:t,query:e,taskType:n?.taskType}}),o}async getFeedbackSummaries(){let t=this.feedbackEntries.length,e=this.feedbackEntries.filter(o=>o.feedback==="hit").length,s=this.feedbackEntries.filter(o=>o.feedback==="partial").length,n=this.feedbackEntries.filter(o=>o.feedback==="miss").length;return {total:t,hits:e,partials:s,misses:n,hitRate:t>0?e/t:0}}};F=i([Injectable(),r(0,Optional()),r(0,Inject(j))],F);var w=class{constructor(t,e){this.service=t;this.projects=e;}resolveRootPath(t,e){let s=t??e??this.projects.getActiveProjectRoot();if(!s)throw new BadRequestException("rootPath is required \u2014 no active project connected");return s}async status(t,e){let s=t??e??this.projects.getActiveProjectRoot();return s?this.service.getStatus(s):null}async index(t,e){return this.service.indexProject(this.resolveRootPath(t.rootPath,e))}async build(t,e){return this.service.buildContext(this.resolveRootPath(t.rootPath,e),t.query,t.mode??"fast",t.maxTokens)}async buildTask(t,e){return this.service.buildTaskContext(this.resolveRootPath(t.rootPath,e),t.query,t.mode??"fast",t.maxTokens)}async feedback(t,e){return this.service.recordFeedback(this.resolveRootPath(t.rootPath,e),t.query,t.feedback,{taskType:t.taskType,contextMode:t.contextMode,runId:t.runId,tokenCount:t.tokenCount})}async feedbackSummary(){return this.service.getFeedbackSummaries()}async findSymbol(t,e,s){return this.service.findSymbol(this.resolveRootPath(e,s),t)}};i([Get("status"),r(0,Query("rootPath")),r(1,Headers("x-devflow-project"))],w.prototype,"status",1),i([Post("index"),r(0,Body()),r(1,Headers("x-devflow-project"))],w.prototype,"index",1),i([Post("build"),r(0,Body()),r(1,Headers("x-devflow-project"))],w.prototype,"build",1),i([Post("build-task"),r(0,Body()),r(1,Headers("x-devflow-project"))],w.prototype,"buildTask",1),i([Post("feedback"),r(0,Body()),r(1,Headers("x-devflow-project"))],w.prototype,"feedback",1),i([Get("feedback-summary")],w.prototype,"feedbackSummary",1),i([Get("symbol/:name"),r(0,Param("name")),r(1,Query("rootPath")),r(2,Headers("x-devflow-project"))],w.prototype,"findSymbol",1),w=i([Controller("context"),r(0,Inject(F)),r(1,Inject(p))],w);var N=class{constructor(t){this.dataService=t;}async recordTelemetryEvent(t){return {success:true,...await this.dataService.recordTelemetryEvent(t)}}async getProjectStats(t){return this.dataService.getProjectStats(t)}async updateProjectStats(t){return this.dataService.updateProjectStats(t.projectRoot,t.stats)}recordBenchmarkResult(t){return this.dataService.recordBenchmarkResult(t),{success:true}}getBenchmarkResults(t){return this.dataService.getBenchmarkResults(t)}};i([Post("telemetry/event"),r(0,Body())],N.prototype,"recordTelemetryEvent",1),i([Get("project/stats"),r(0,Query("rootPath"))],N.prototype,"getProjectStats",1),i([Post("project/stats"),r(0,Body())],N.prototype,"updateProjectStats",1),i([Post("benchmark/result"),r(0,Body())],N.prototype,"recordBenchmarkResult",1),i([Get("benchmark/results"),r(0,Query("projectRoot"))],N.prototype,"getBenchmarkResults",1),N=i([Controller("data"),r(0,Inject(j))],N);var O=class{constructor(){this.engines=new Map;this.ENGINE_TTL=3600*1e3;}getEngine(t){let e=Date.now();for(let[o,a]of this.engines)if(e-a.lastAccess>this.ENGINE_TTL){try{a.engine.close?.();}catch{}this.engines.delete(o);}let s=t.replace(/\/+$/,""),n=this.engines.get(s);return n?n.lastAccess=e:(n={engine:new MemoryEngine(s),lastAccess:e},this.engines.set(s,n)),n.engine}async getAll(t){let e=this.getEngine(t),[s,n]=await Promise.all([e.listMemories(),checkOllama()]);return {memories:s.map(o=>({id:o.id,category:o.category,content:o.content,originalText:o.originalText,source:o.source,status:o.status,confidence:o.confidence,scope:o.scope,createdAt:o.createdAt,approvedAt:o.approvedAt})),ollama:{installed:n.installed,running:n.running,modelAvailable:n.modelAvailable,modelName:n.modelName,infoMessage:getOllamaInfoMessage(n)}}}async add(t,e){return this.getEngine(t).addMemory({category:e.category,content:e.content,source:"manual",confidence:1,scope:e.scope??""})}async update(t,e,s){await this.getEngine(t).updateMemory(e,s);}async delete(t,e){await this.getEngine(t).deleteMemory(e);}async getCandidates(t){return this.getEngine(t).getPendingMemories()}async approveCandidate(t,e){await this.getEngine(t).approveMemory(e);}async rejectCandidate(t,e){await this.getEngine(t).rejectMemory(e);}async search(t,e,s){return (await this.getEngine(t).search(e,s)).map(o=>o.entry)}async extract(t,e){return this.getEngine(t).extractMemories(e)}async getOllamaStatus(){let t=await checkOllama();return {...t,infoMessage:getOllamaInfoMessage(t)}}async updateLegacy(t,e,s,n){e!=="user"&&await this.getEngine(t).addMemory({category:"project_knowledge",content:`${s}: ${JSON.stringify(n)}`,source:"manual",confidence:1,scope:s});}async recordEvent(t,e){let s=this.getEngine(t);return await s.recordEvent({id:e.id,sessionId:e.sessionId,tool:e.tool,command:e.command,exitCode:e.exitCode,stderr:e.stderr,durationMs:e.durationMs,createdAt:Date.now()}),{acknowledged:true,extracted:(await s.extractFromEventsRealtime([{tool:e.tool,command:e.command,exitCode:e.exitCode,stderr:e.stderr}])).length}}async processSessionEvents(t){return this.getEngine(t).processSessionEvents()}};O=i([Injectable()],O);var m=class{constructor(t,e,s){this.service=t;this.memoryService=e;this.projectsService=s;}async listRuns(t,e,s){return this.service.listRuns(Number(t)||20,Number(e)||0,s)}async getRun(t){let e=await this.service.getRun(t),s=await this.service.classifyFailure(t);return {...e,...s}}async getTimeline(t,e){return this.service.getTimeline(t,e)}async getRunEvents(t){return this.service.getRunEvents(t)}async getRunStats(t){return this.service.getRunStats(t)}async completeRun(t){await this.service.endRun(t,{status:"success"});let e=await this.service.getRunEvents(t),s=this.projectsService.getActiveProjectRoot(),n=await this.memoryService.extract(s??"",e);return {extracted:Array.isArray(n)?n.length:0}}async getStats(t){return this.service.getStats(Number(t)||7)}async getRoiSummary(t){return this.service.getRoiSummary(Number(t)||7)}async cleanup(t){return {removedRuns:await this.service.cleanup(t.olderThanDays??30)}}async cleanupStale(){return await this.service.cleanupStaleRecords(),{ok:true}}async createSession(t){return await this.service.createSession(t),{id:t.id}}async listSessions(t,e,s){return this.service.listSessions(Number(t)||20,Number(e)||0,s)}async getSession(t){return this.service.getSession(t)}async getSessionEvents(t){return this.service.getSessionEvents(t)}async closeSession(t,e){return await this.service.closeSession(t,e.finishedAt),{}}async startSessionSkillExecution(t,e){return await this.service.createSkillExecution({...e,sessionId:t}),{executionId:e.executionId}}async startSkillExecution(t){return await this.service.recordExecutionStart(t),{executionId:t.executionId}}async recordToolCall(t){return await this.service.recordToolCall(t),{eventId:t.eventId}}async updateToolCallOutput(t){return await this.service.updateToolCallOutput(t.eventId,t.output,t.completedAt,t.duration),{}}async completeSkillExecution(t){return await this.service.recordExecutionComplete(t),{}}async getExecutions(t,e){return this.service.getExecutions(Number(t)||20,e)}async getExecutionEvents(t){return this.service.getExecutionEvents(t)}async getMcpCompliance(){return await this.service.getMcpCompliance()}};i([Get("runs"),r(0,Query("limit")),r(1,Query("offset")),r(2,Query("source"))],m.prototype,"listRuns",1),i([Get("runs/:id"),r(0,Param("id"))],m.prototype,"getRun",1),i([Get("timeline"),r(0,Query("from")),r(1,Query("to"))],m.prototype,"getTimeline",1),i([Get("runs/:runId/events"),r(0,Param("runId"))],m.prototype,"getRunEvents",1),i([Get("runs/:runId/stats"),r(0,Param("runId"))],m.prototype,"getRunStats",1),i([Post("runs/:id/complete"),r(0,Param("id"))],m.prototype,"completeRun",1),i([Get("stats"),r(0,Query("days"))],m.prototype,"getStats",1),i([Get("roi-summary"),r(0,Query("days"))],m.prototype,"getRoiSummary",1),i([Post("cleanup"),r(0,Body())],m.prototype,"cleanup",1),i([Post("cleanup-stale")],m.prototype,"cleanupStale",1),i([Post("sessions"),r(0,Body())],m.prototype,"createSession",1),i([Get("sessions"),r(0,Query("limit")),r(1,Query("offset")),r(2,Query("projectRoot"))],m.prototype,"listSessions",1),i([Get("sessions/:id"),r(0,Param("id"))],m.prototype,"getSession",1),i([Get("sessions/:id/events"),r(0,Param("id"))],m.prototype,"getSessionEvents",1),i([Post("sessions/:id/close"),r(0,Param("id")),r(1,Body())],m.prototype,"closeSession",1),i([Post("sessions/:id/skill-executions"),r(0,Param("id")),r(1,Body())],m.prototype,"startSessionSkillExecution",1),i([Post("skill-execution/start"),r(0,Body())],m.prototype,"startSkillExecution",1),i([Post("tool-call"),r(0,Body())],m.prototype,"recordToolCall",1),i([Post("tool-call/output"),r(0,Body())],m.prototype,"updateToolCallOutput",1),i([Post("skill-execution/complete"),r(0,Body())],m.prototype,"completeSkillExecution",1),i([Get("executions"),r(0,Query("limit")),r(1,Query("skillName"))],m.prototype,"getExecutions",1),i([Get("executions/:id/events"),r(0,Param("id"))],m.prototype,"getExecutionEvents",1),i([Get("mcp-compliance")],m.prototype,"getMcpCompliance",1),m=i([Controller("telemetry"),r(0,Inject(P)),r(1,Inject(O)),r(2,Inject(p))],m);var f=class{constructor(t,e){this.service=t;this.projects=e;}resolveRootPath(t,e){let s=t??e??this.projects.getActiveProjectRoot();if(!s)throw new BadRequestException({error:{code:d.BAD_REQUEST,message:"rootPath is required \u2014 no active project connected",details:{}}});return s}async getAll(t,e){return this.service.getAll(this.resolveRootPath(t,e))}async add(t,e,s){return this.service.add(this.resolveRootPath(t,s),e)}async update(t,e,s,n){return await this.service.update(this.resolveRootPath(t,n),e,s),{ok:true}}async delete(t,e,s){return await this.service.delete(this.resolveRootPath(t,s),e),{ok:true}}async getCandidates(t,e){return this.service.getCandidates(this.resolveRootPath(t,e))}async approve(t,e,s){return await this.service.approveCandidate(this.resolveRootPath(t,s),e),{approved:true}}async reject(t,e,s){return await this.service.rejectCandidate(this.resolveRootPath(t,s),e),{rejected:true}}async search(t,e,s){return this.service.search(this.resolveRootPath(t,s),e.query,{limit:e.limit,categories:e.categories})}async extract(t,e,s){return this.service.extract(this.resolveRootPath(t,s),e.events)}async ollamaStatus(){return this.service.getOllamaStatus()}async updateLegacy(t,e,s,n,o){return await this.service.updateLegacy(this.resolveRootPath(t,o),e,s,n.value),{ok:true}}async recordEvent(t,e,s){return this.service.recordEvent(this.resolveRootPath(t,s),e)}async processEvents(t,e,s){return this.service.processSessionEvents(this.resolveRootPath(t,e))}};i([Get(),r(0,Query("rootPath")),r(1,Headers("x-devflow-project"))],f.prototype,"getAll",1),i([Post(),r(0,Query("rootPath")),r(1,Body()),r(2,Headers("x-devflow-project"))],f.prototype,"add",1),i([Put(":id"),r(0,Query("rootPath")),r(1,Param("id")),r(2,Body()),r(3,Headers("x-devflow-project"))],f.prototype,"update",1),i([Delete(":id"),r(0,Query("rootPath")),r(1,Param("id")),r(2,Headers("x-devflow-project"))],f.prototype,"delete",1),i([Get("candidates"),r(0,Query("rootPath")),r(1,Headers("x-devflow-project"))],f.prototype,"getCandidates",1),i([Post("candidates/:id/approve"),r(0,Query("rootPath")),r(1,Param("id")),r(2,Headers("x-devflow-project"))],f.prototype,"approve",1),i([Post("candidates/:id/reject"),r(0,Query("rootPath")),r(1,Param("id")),r(2,Headers("x-devflow-project"))],f.prototype,"reject",1),i([Post("search"),r(0,Query("rootPath")),r(1,Body()),r(2,Headers("x-devflow-project"))],f.prototype,"search",1),i([Post("extract"),r(0,Query("rootPath")),r(1,Body()),r(2,Headers("x-devflow-project"))],f.prototype,"extract",1),i([Get("ollama/status")],f.prototype,"ollamaStatus",1),i([Put(":layer/:key"),r(0,Query("rootPath")),r(1,Param("layer")),r(2,Param("key")),r(3,Body()),r(4,Headers("x-devflow-project"))],f.prototype,"updateLegacy",1),i([Post("events"),r(0,Query("rootPath")),r(1,Body()),r(2,Headers("x-devflow-project"))],f.prototype,"recordEvent",1),i([Post("process"),r(0,Query("rootPath")),r(1,Headers("x-devflow-project")),r(2,Body())],f.prototype,"processEvents",1),f=i([Controller("memory"),r(0,Inject(O)),r(1,Inject(p))],f);var et=class{};et=i([Module({imports:[forwardRef(()=>T),v],controllers:[f],providers:[O],exports:[O]})],et);var H=class{};H=i([Module({imports:[et,v],controllers:[m],providers:[P],exports:[P]})],H);var st=class{};st=i([Module({imports:[H],controllers:[N],providers:[j],exports:[j]})],st);var T=class{};T=i([Module({imports:[v,st],controllers:[w],providers:[F],exports:[F]})],T);var M=class{async getFullGraph(t){let{graph:e}=await createEngines(t);return e.export()}async getLayeredGraph(t){let{graph:e}=await createEngines(t);return e.getLayeredGraph()}async getNode(t,e){let{codegraph:s}=await createEngines(t),n=s.getNode(e);if(!n)throw new NotFoundException({error:{code:d.NODE_NOT_FOUND,message:`Node "${e}" not found`,details:{}}});return n}async expandNode(t,e,s,n){let{graph:o}=await createEngines(t),a=o.expand([e],{depth:s,direction:n});return {node:a.nodes.find(l=>l.id===e),subGraph:a}}};M=i([Injectable()],M);var U=class{constructor(t,e){this.service=t;this.projects=e;}resolveRootPath(t,e){let s=t??e??this.projects.getActiveProjectRoot();if(!s)throw new BadRequestException({error:{code:d.BAD_REQUEST,message:"rootPath is required \u2014 no active project connected",details:{}}});return s}async getFullGraph(t,e,s){return e==="layered"?this.service.getLayeredGraph(this.resolveRootPath(t,s)):this.service.getFullGraph(this.resolveRootPath(t,s))}async getNode(t,e,s){return this.service.getNode(this.resolveRootPath(t,s),e)}async expandNode(t,e,s,n,o){return this.service.expandNode(this.resolveRootPath(t,o),e,Number(s)||2,n||"both")}};i([Get(),r(0,Query("rootPath")),r(1,Query("view")),r(2,Headers("x-devflow-project"))],U.prototype,"getFullGraph",1),i([Get(":nodeId"),r(0,Query("rootPath")),r(1,Param("nodeId")),r(2,Headers("x-devflow-project"))],U.prototype,"getNode",1),i([Get(":nodeId/expand"),r(0,Query("rootPath")),r(1,Param("nodeId")),r(2,Query("depth")),r(3,Query("direction")),r(4,Headers("x-devflow-project"))],U.prototype,"expandNode",1),U=i([Controller("graph"),r(0,Inject(M)),r(1,Inject(p))],U);var nt=class{};nt=i([Module({imports:[T,v],controllers:[U],providers:[M],exports:[M]})],nt);var B=class{constructor(t){this.db=t;this.engine=new WorkflowEngine;this.events=new Map;this.engineRunIds=new Map;}async onModuleInit(){try{clearPluginCache();let t=await loadPlugins(),e=Array.from(t.values());for(let n of e)for(let o of n.workflow?.templates??[])this.engine.register(o);let s=await this.engine.list();console.log(`[WorkflowService] Loaded ${e.length} plugins with ${s.length} workflows`);}catch(t){console.error("[WorkflowService] Failed to load plugins:",t);}}async list(){return this.engine.list()}async run(t,e){if(!(await this.engine.list()).find(a=>a.name===t))throw new NotFoundException({error:{code:d.WORKFLOW_NOT_FOUND,message:`Workflow "${t}" not found`,details:{}}});let n=`run_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,o=new Subject;if(this.events.set(n,o),this.db)try{this.db.insertSkillExecution({executionId:n,skillName:`workflow:${t}`,startedAt:Date.now(),status:"running"});}catch{}return this.engine.run(t,e).then(a=>{if(this.engineRunIds.set(n,a.runId),a.status!=="running"&&this.db)try{this.db.updateSkillExecution(n,{status:a.status==="success"?"completed":"failed",finishedAt:Date.now()});}catch{}this.engineRunIds.set(n,a.runId);let l=this.engine.getRun(a.runId);if(l){for(let u of l.steps)o.next({runId:n,stepId:u.stepId,status:u.status==="success"?"completed":u.status==="failed"?"failed":"started",output:u.output,error:u.error,timestamp:Date.now()});a.status!=="running"&&o.complete();}a.status==="running"&&this.engine.onEvent(a.runId,u=>{o.next({runId:n,stepId:u.stepId,status:u.type==="step-done"?"completed":u.type==="step-error"?"failed":"started",output:"output"in u?u.output:void 0,error:"error"in u?u.error:void 0,timestamp:Date.now()});});}).catch(a=>{if(this.db)try{this.db.updateSkillExecution(n,{status:"failed",finishedAt:Date.now()});}catch{}o.next({runId:n,stepId:"engine",status:"failed",error:a.message,timestamp:Date.now()}),o.complete();}),{runId:n}}async listRuns(t,e){return (await this.engine.listRuns()).map(o=>({runId:Array.from(this.engineRunIds.entries()).find(([,l])=>l===o.runId)?.[0]??o.runId,workflowName:o.type,status:o.status,steps:o.steps.map(l=>({stepId:l.stepId,status:l.status,output:l.output,error:l.error,startedAt:0})),startedAt:o.startedAt,finishedAt:o.finishedAt})).slice(e,e+t)}async getRun(t){let e=this.engineRunIds.get(t)??t,s=this.engine.getRun(e);if(!s)throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Run "${t}" not found`,details:{}}});return {runId:t,workflowName:s.type,status:s.status,steps:s.steps.map(n=>({stepId:n.stepId,status:n.status,output:n.output,error:n.error})),startedAt:s.startedAt,finishedAt:s.finishedAt}}streamRun(t){let e=this.events.get(t);if(!e)throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Run "${t}" not found`,details:{}}});return e}async approveRun(t){let e=this.engineRunIds.get(t)??t,s=this.engine.getRun(e);if(!s)throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Run "${t}" not found`,details:{}}});let n=s.steps.find(o=>o.status==="awaiting_approval");n&&await this.engine.approve(e,n.stepId);}async rejectRun(t,e){let s=this.engineRunIds.get(t)??t,n=this.engine.getRun(s);if(!n)throw new NotFoundException({error:{code:d.RUN_NOT_FOUND,message:`Run "${t}" not found`,details:{}}});let o=n.steps.find(a=>a.status==="awaiting_approval");o&&await this.engine.reject(s,o.stepId,e??"Rejected");}async getNextStep(t){if(!t){(await this.engine.list())[0];return null}let e=this.engineRunIds.get(t)??t,s=this.engine.getRun(e);return s?(Array.isArray(s.steps)?s.steps:[]).find(o=>o.status==="pending")??null:null}};B=i([Injectable(),r(0,Optional()),r(0,Inject("DATABASE"))],B);var b=class{constructor(t){this.service=t;}async list(){return this.service.list()}async run(t,e){return this.service.run(t,e.input??{})}async listRuns(t,e){return this.service.listRuns(Number(t)||20,Number(e)||0)}async getRun(t){return this.service.getRun(t)}async stream(t,e){e.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let n=this.service.streamRun(t).subscribe({next:o=>{e.raw.write(`event: step-${o.status}
|
|
2
|
-
data: ${JSON.stringify(o)}
|
|
3
|
-
|
|
4
|
-
`);},error:o=>{e.raw.write(`event: error
|
|
5
|
-
data: ${JSON.stringify({error:o.message})}
|
|
6
|
-
|
|
7
|
-
`),e.raw.end();},complete:()=>{e.raw.write(`event: done
|
|
8
|
-
data: {}
|
|
9
|
-
|
|
10
|
-
`),e.raw.end();}});e.raw.on("close",()=>n.unsubscribe());}async approve(t){return await this.service.approveRun(t),{approved:true}}async reject(t,e){return await this.service.rejectRun(t,e.reason),{rejected:true}}async nextStep(t){return this.service.getNextStep(t)}};i([Get()],b.prototype,"list",1),i([Post(":type/run"),r(0,Param("type")),r(1,Body())],b.prototype,"run",1),i([Get("runs"),r(0,Query("limit")),r(1,Query("offset"))],b.prototype,"listRuns",1),i([Get("runs/:id"),r(0,Param("id"))],b.prototype,"getRun",1),i([Get("runs/:id/stream"),r(0,Param("id")),r(1,Res())],b.prototype,"stream",1),i([Post("runs/:id/approve"),r(0,Param("id"))],b.prototype,"approve",1),i([Post("runs/:id/reject"),r(0,Param("id")),r(1,Body())],b.prototype,"reject",1),i([Get("next-step"),r(0,Query("runId"))],b.prototype,"nextStep",1),b=i([Controller("workflows"),r(0,Inject(B))],b);var it=class{};it=i([Module({controllers:[b],providers:[B],exports:[B]})],it);var L=class{constructor(t){this.projectsService=t;}getEngine(t){return new KnowledgeEngine({projectRoot:t})}async onModuleInit(){this._initKnowledge();}async _initKnowledge(){let t=this.projectsService.getActiveProjectRoot()??process.env.DEVFLOW_PROJECT_ROOT??process.cwd();try{let e=this.getEngine(t),s=await loadPlugins(),n=Array.from(s.values());for(let l of n)for(let u of l.knowledge?.sources??[])await e.registerSource({...u,version:u.version||l.meta.version});let o=await e.getSources(),a=Date.now()-10080*60*1e3;for(let l of o)(!l.lastSyncTime||l.lastSyncTime<a)&&await e.syncDocs(l.source.name);}catch{}}async search(t,e,s){return this.getEngine(t).search(e,{sources:s&&s!=="all"?[s]:void 0})}async sync(t,e){return this.getEngine(t).syncDocs(e??"")}async getSources(t){return this.getEngine(t).getSources()}};L=i([Injectable(),r(0,Inject(p))],L);var $=class{constructor(t,e){this.service=t;this.projects=e;}resolveRootPath(t,e){let s=t??e??this.projects.getActiveProjectRoot();if(!s)throw new BadRequestException("rootPath is required \u2014 no active project connected");return s}async search(t,e,s,n){return this.service.search(this.resolveRootPath(t,n),e??"",s)}async sync(t,e){return this.service.sync(this.resolveRootPath(t.rootPath,e),t.pluginName)}async getSources(t,e){return this.service.getSources(this.resolveRootPath(t,e))}};i([Get("search"),r(0,Query("rootPath")),r(1,Query("q")),r(2,Query("scope")),r(3,Headers("x-devflow-project"))],$.prototype,"search",1),i([Post("sync"),r(0,Body()),r(1,Headers("x-devflow-project"))],$.prototype,"sync",1),i([Get("sources"),r(0,Query("rootPath")),r(1,Headers("x-devflow-project"))],$.prototype,"getSources",1),$=i([Controller("knowledge"),r(0,Inject(L)),r(1,Inject(p))],$);var ot=class{};ot=i([Module({imports:[T,v],controllers:[$],providers:[L],exports:[L]})],ot);var q=class{constructor(){this.results=[];this.scenarioIds=[];this.engine=new BenchmarkEngine,this.registerDefaultScenarios();}registerDefaultScenarios(){let t=[{id:"understand-codebase",category:"understand",desc:"\u7406\u89E3\u4EE3\u7801\u5E93\u67B6\u6784",expectedFiles:2},{id:"modify-component",category:"modify",desc:"\u4FEE\u6539 React \u7EC4\u4EF6",expectedFiles:1,expectedComponents:1},{id:"review-code",category:"review",desc:"\u4EE3\u7801\u5BA1\u67E5",expectedIssues:2}];for(let e of t)this.engine.registerScenario(e),this.scenarioIds.push(e.id);}async runScenarioSet(t){let e=async a=>({prepTimeMs:1e3+Math.random()*500,tokenCount:500+Math.floor(Math.random()*200),firstPassSuccess:Math.random()>.5,reworkCount:Math.floor(Math.random()*3),durationMs:5e3+Math.random()*3e3}),s=async a=>({prepTimeMs:500+Math.random()*300,tokenCount:300+Math.floor(Math.random()*100),firstPassSuccess:Math.random()>.2,reworkCount:Math.floor(Math.random()*2),durationMs:3e3+Math.random()*2e3}),n=t??this.scenarioIds,o=await this.engine.runScenarioBatch(n,e,s);return this.results=o,o}async getScenarioResults(){return this.results.length===0&&await this.runScenarioSet(),this.results}async getComparisonSummary(){let t=await this.getScenarioResults(),e=t.length;return {totalScenarios:e,avgTimeSavedRate:t.reduce((s,n)=>s+n.comparison.timeSavedRate,0)/e,avgTokenReductionRate:t.reduce((s,n)=>s+n.comparison.tokenReductionRate,0)/e,avgFirstPassLift:t.reduce((s,n)=>s+n.comparison.firstPassLift,0)/e,avgReworkReductionRate:t.reduce((s,n)=>s+n.comparison.reworkReductionRate,0)/e}}async getExperimentalRoiSummary(){let t=await this.getComparisonSummary();return {totalScenarios:t.totalScenarios,avgTimeSavedRate:t.avgTimeSavedRate,avgTokenReductionRate:t.avgTokenReductionRate,avgFirstPassLift:t.avgFirstPassLift,avgReworkReductionRate:t.avgReworkReductionRate,conclusion:"DevFlow shows significant improvement in all metrics"}}};q=i([Injectable()],q);var D=class{constructor(t){this.service=t;}async run(t){return this.service.runScenarioSet(t.scenarioIds)}async getResults(){return this.service.getScenarioResults()}async getComparisonSummary(){return this.service.getComparisonSummary()}async getExperimentalRoiSummary(){return this.service.getExperimentalRoiSummary()}};i([Post("run"),r(0,Body())],D.prototype,"run",1),i([Get("results")],D.prototype,"getResults",1),i([Get("summary")],D.prototype,"getComparisonSummary",1),i([Get("roi-summary")],D.prototype,"getExperimentalRoiSummary",1),D=i([Controller("benchmark"),r(0,Inject(q))],D);var at=class{};at=i([Module({controllers:[D],providers:[q],exports:[q]})],at);var G=class{constructor(t){this.telemetryService=t;this.plugins=new Map;this.installRecords=[];}async list(t,e){let s=Array.from(this.plugins.values());if(t){let n=t.toLowerCase();s=s.filter(o=>o.name.toLowerCase().includes(n)||o.description.toLowerCase().includes(n));}return e&&(s=s.filter(n=>n.tags.includes(e))),s}async getByName(t){let e=this.plugins.get(t);if(!e)throw new NotFoundException({error:{code:d.PLUGIN_NOT_FOUND,message:`Plugin "${t}" not found`,details:{}}});return e}async publish(t){let e=t.npmPackage.replace(/^@devflow-tools\/plugin-/,""),s={name:e,npmPackage:t.npmPackage,version:t.version,description:t.description,tags:t.tags??[],createdAt:Date.now()};return this.plugins.set(e,s),s}async install(t,e){let s=t.startsWith("@devflow-tools/plugin-")?t:`@devflow-tools/plugin-${t}`,n=t.replace(/^@devflow-tools\/plugin-/,"");return this.plugins.set(n,{name:n,npmPackage:s,version:"0.1.0",description:"Installed plugin",tags:[],createdAt:Date.now()}),e&&await this.recordPluginInstall(n,e),{ok:true,name:n}}async uninstall(t,e){let s=t.replace(/^@devflow-tools\/plugin-/,"");return this.plugins.delete(s),e&&await this.recordPluginUninstall(s,e),{ok:true,name:s}}async recordPluginInstall(t,e){let s=this.installRecords.find(n=>n.pluginName===t&&n.projectRoot===e);s?s.uninstalledAt=void 0:this.installRecords.push({pluginName:t,projectRoot:e,installedAt:Date.now()});}async recordPluginUninstall(t,e){let s=this.installRecords.find(n=>n.pluginName===t&&n.projectRoot===e);s&&(s.uninstalledAt=Date.now());}async listInstalledProjects(t){return this.installRecords.filter(e=>e.pluginName===t&&!e.uninstalledAt).map(e=>e.projectRoot)}async buildPluginEffectiveness(t){let s=(await this.listInstalledProjects(t)).length,n=await this.telemetryService.getPluginUsageStats(t),o=s>0?n.activeProjects/s:0,a=n.totalRuns>0?n.successfulRuns/n.totalRuns:0,l="optimize";return o>.7&&a>.8?l="install":(o<.3||a<.5)&&(l="remove"),{name:t,installCount:s,usageCount:n.totalRuns,activeRate:o,successRate:a,lastUsedAt:n.lastUsedAt,recommendation:l}}async getPluginEffectiveness(t){let e=t?this.installRecords.filter(o=>o.projectRoot===t&&!o.uninstalledAt):this.installRecords.filter(o=>!o.uninstalledAt),s=[...new Set(e.map(o=>o.pluginName))],n=[];for(let o of s){let a=await this.buildPluginEffectiveness(o);n.push(a);}return n}};G=i([Injectable(),r(0,Inject(P))],G);var A=class{constructor(t){this.service=t;}async list(t,e){return this.service.list(t,e)}async getPluginEffectiveness(t){return this.service.getPluginEffectiveness(t)}async getByName(t){return this.service.getByName(t)}async publish(t){return this.service.publish(t)}async install(t,e){return this.service.install(t.name,t.rootPath??e)}async uninstall(t,e,s){return this.service.uninstall(t,e.rootPath??s)}};i([Get("plugins"),r(0,Query("search")),r(1,Query("tag"))],A.prototype,"list",1),i([Get("plugins/effectiveness"),r(0,Query("rootPath"))],A.prototype,"getPluginEffectiveness",1),i([Get("plugins/:name"),r(0,Param("name"))],A.prototype,"getByName",1),i([Post("plugins"),r(0,Body())],A.prototype,"publish",1),i([Post("plugins/install"),r(0,Body()),r(1,Headers("x-devflow-project"))],A.prototype,"install",1),i([Post("plugins/:name/uninstall"),r(0,Param("name")),r(1,Body()),r(2,Headers("x-devflow-project"))],A.prototype,"uninstall",1),A=i([Controller("registry"),r(0,Inject(G))],A);var ct=class{};ct=i([Module({imports:[H],controllers:[A],providers:[G],exports:[G]})],ct);var he={provide:"DATABASE",useFactory:()=>{let c=process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow","global");return new DevFlowDatabase(c)}},ut=class{};ut=i([Global(),Module({providers:[he],exports:[he]})],ut);var lt=class{intercept(t,e){return e.handle().pipe(map(s=>s&&typeof s=="object"&&"error"in s?s:{ok:true,data:s??null}))}};lt=i([Injectable()],lt);var X=class{constructor(){this.startTime=Date.now();}health(){return {version:"0.2.3",uptime:Date.now()-this.startTime}}};i([Yt(),Get("health")],X.prototype,"health",1),X=i([Controller()],X);var dt=class{};dt=i([Module({imports:[ut,z,v,T,nt,ot,it,at,ct],controllers:[X],providers:[{provide:APP_INTERCEPTOR,useClass:lt}]})],dt);function ve(c){return c===400?d.BAD_REQUEST:c===404?d.PROJECT_NOT_FOUND:c===422?d.VALIDATION_ERROR:d.INTERNAL_ERROR}var Q=class{constructor(){this.logger=new Logger(Q.name);}catch(t,e){let n=e.switchToHttp().getResponse();if(t instanceof HttpException){let o=t.getStatus(),a=t.getResponse();if(typeof a=="object"&&a!==null&&"error"in a){let u=a.error;if(typeof u=="object"&&u!==null&&"code"in u){n.status(o).send(a);return}let y=typeof a.message=="string"?a.message:"Request failed";n.status(o).send({error:{code:ve(o),message:y,details:{}}});return}let l=typeof a=="string"?a:a.message??"Request failed";n.status(o).send({error:{code:ve(o),message:l,details:{}}});return}this.logger.error("Unhandled exception",t instanceof Error?t.stack:String(t)),n.status(HttpStatus.INTERNAL_SERVER_ERROR).send({error:{code:d.INTERNAL_ERROR,message:"Internal server error",details:{}}});}};Q=i([Catch()],Q);async function dr(){let c=new FastifyAdapter,t=await NestFactory.create(dt,c);return t.setGlobalPrefix("api"),t.useGlobalFilters(new Q),t.enableCors({origin:true,credentials:true}),c.getInstance().addHook("preParsing",async(s,n,o)=>{if(s.headers["content-length"]==="0"){let a=Buffer.from("{}");return s.headers["content-length"]=String(a.length),Readable.from([a])}return o}),await t.listen({port:parseInt(process.env.PORT||"13337",10),host:"127.0.0.1"}),t}(process.argv[1]?.endsWith("main.js")||process.argv[1]?.endsWith("main.ts")||process.argv[1]?.endsWith("server.js"))&&dr();export{dr as bootstrap};
|