@lisa.ai/agent 2.9.1 → 2.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +49 -0
  2. package/dist/index.js +222 -159
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -149,6 +149,33 @@ lisa-agent init # interactive wizard
149
149
  lisa-agent init --force # overwrite existing config
150
150
  ```
151
151
 
152
+ ### `init-ci` — Generate GitHub Actions Workflow
153
+
154
+ Scaffolds a `.github/workflows/lisa-heal.yml` file so Lisa.ai runs automatically on every push.
155
+
156
+ ```bash
157
+ lisa-agent init-ci # defaults to Gemini
158
+ lisa-agent init-ci --model claude # use Claude as the LLM provider
159
+ lisa-agent init-ci --force # overwrite existing workflow
160
+ ```
161
+
162
+ The generated workflow:
163
+ 1. Triggers on push to `main`/`master`/`develop` (+ manual dispatch)
164
+ 2. Installs project dependencies and Lisa.ai Agent
165
+ 3. Runs `lisa-agent heal --ci`
166
+ 4. If tests fail and Lisa heals them, opens a PR automatically
167
+ 5. Writes a step summary to the GitHub Actions UI
168
+
169
+ **Required setup:** Add your LLM API key as a repository secret in GitHub (Settings > Secrets > Actions). The secret name depends on the provider:
170
+
171
+ | Provider | Secret name |
172
+ |---|---|
173
+ | Gemini | `GOOGLE_GENERATIVE_AI_API_KEY` |
174
+ | Claude | `ANTHROPIC_API_KEY` |
175
+ | OpenAI | `OPENAI_API_KEY` |
176
+
177
+ `GITHUB_TOKEN` is provided automatically by GitHub Actions — no PAT needed.
178
+
152
179
  ## Common Options
153
180
 
154
181
  All test commands (`heal`, `unit`, `e2e`, `integration`, `audit`) accept:
@@ -160,6 +187,7 @@ All test commands (`heal`, `unit`, `e2e`, `integration`, `audit`) accept:
160
187
  | `-p, --project-id <id>` | Control Plane project for remote config + telemetry | `local` |
161
188
  | `-f, --files <paths>` | Target specific files (comma-separated, bypasses discovery) | All files |
162
189
  | `-t, --type <scope>` | (heal only) Test type to heal: `unit`, `e2e`, `integration` | `unit` |
190
+ | `--ci` | (heal only) CI mode: commit healed files + open PR + write step summary | Off |
163
191
 
164
192
  ## Configuration
165
193
 
@@ -280,6 +308,27 @@ lisa-agent e2e --files e2e/login.spec.ts --model gemini
280
308
  lisa-agent integration --files src/services/user.service.ts --model openai
281
309
  ```
282
310
 
311
+ ### GitHub Actions CI — auto-heal on every push
312
+ ```bash
313
+ # One-time setup: generate the workflow file
314
+ lisa-agent init-ci --model gemini
315
+
316
+ # Then add your API key as a GitHub secret:
317
+ # Repo > Settings > Secrets > Actions > GOOGLE_GENERATIVE_AI_API_KEY
318
+
319
+ # That's it! On every push, Lisa.ai will:
320
+ # 1. Run your tests
321
+ # 2. Auto-heal any failures
322
+ # 3. Open a PR with the fixes for review
323
+ ```
324
+
325
+ ### Run heal in CI mode locally (test without pushing)
326
+ ```bash
327
+ lisa-agent heal --ci --model gemini
328
+ # Runs the full heal loop, then attempts to commit + open PR.
329
+ # Without GITHUB_TOKEN set, PR creation is gracefully skipped.
330
+ ```
331
+
283
332
  ### Full CI/CD pipeline with Control Plane
284
333
  ```bash
285
334
  lisa-agent heal --command "npm test" --model gemini --project-id "prod-api"
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Et=Object.create;var Ue=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var Ft=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Pt=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ct(e))!At.call(t,i)&&i!==s&&Ue(t,i,{get:()=>e[i],enumerable:!(n=jt(e,i))||n.enumerable});return t};var j=(t,e,s)=>(s=t!=null?Et(bt(t)):{},Pt(e||!t||!t.__esModule?Ue(s,"default",{value:t,enumerable:!0}):s,t));var vt=Ft((Zs,Bt)=>{Bt.exports={name:"@lisa.ai/agent",version:"2.9.1",description:"Lisa.ai Autonomous CI/CD Worker Agent",main:"dist/index.js",bin:{"lisa-agent":"dist/index.js"},files:["dist/"],scripts:{build:"tsup",typecheck:"tsc --noEmit",start:"node dist/index.js",dev:"ts-node src/index.ts",prepublishOnly:"npm run typecheck && npm run build"},keywords:["lisa","ci","cd","agent"],author:"Lisa.ai",license:"ISC",dependencies:{"@ai-sdk/anthropic":"^3.0.46","@ai-sdk/google":"^3.0.30","@ai-sdk/openai":"^3.0.30","@octokit/rest":"^22.0.1",ai:"^6.0.94",commander:"^11.1.0",dotenv:"^17.3.1","simple-git":"^3.31.1"},devDependencies:{"@types/jest":"^30.0.0","@types/node":"^20.0.0","ts-node":"^10.9.1",tsup:"^8.5.1",typescript:"^5.0.0"}}});var xt=require("commander"),Ee=j(require("fs")),$t=j(require("path")),Lt=j(require("readline"));var Oe=j(require("dotenv"));Oe.config({quiet:!0});async function ge(t){let e=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3000";try{let s=`${e}/api/config/${t}`;console.log(`[Lisa.ai Agent] Fetching dynamic configuration from ${s}...`);let n=await fetch(s);if(!n.ok){let o=n.status===404?"not_found":"unreachable";return console.warn(o==="not_found"?`[Lisa.ai Agent Warning] Control Plane returned 404. Project '${t}' not found.`:`[Lisa.ai Agent Warning] Control Plane returned ${n.status}. Falling back to local defaults.`),{ok:!1,reason:o}}return{ok:!0,config:await n.json()}}catch{return console.warn(`[Lisa.ai Agent Warning] Failed to reach Control Plane (${e}). Using local fallback configuration.`),{ok:!1,reason:"unreachable"}}}var ot=require("child_process"),_=j(require("fs")),V=j(require("path"));var S=j(require("path")),T=j(require("fs"));function fe(t){return t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"")}function Z(t){let e=fe(t),s=[...e.matchAll(/Executed\s+(\d+)\s+of\s+(\d+)(?:\s+\((\d+)\s+FAILED\))?/g)];if(s.length>0){let u=[...s].reverse().find(m=>m[3]!==void 0)??s[s.length-1],p=parseInt(u[2]),w=u[3]?parseInt(u[3]):0,h=parseInt(u[1])-w;return{total:p,passed:h,failed:w}}let n=e.match(/Tests:\s+(?:(\d+)\s+failed,?\s*)?(?:(\d+)\s+passed,?\s*)?(\d+)\s+total/);if(n){let u=parseInt(n[3]),p=n[1]?parseInt(n[1]):0,w=n[2]?parseInt(n[2]):0;return{total:u,passed:w,failed:p}}let i=e.match(/(\d+)\s+failed/),o=e.match(/(\d+)\s+passed/);if(o||i){let u=i?parseInt(i[1]):0,p=o?parseInt(o[1]):0,w=e.match(/(\d+)\s+skipped/),h=w?parseInt(w[1]):0;return{total:p+u+h,passed:p,failed:u}}let r=e.match(/Tests\s+(?:(\d+)\s+failed\s*\|?\s*)?(\d+)\s+passed\s*\((\d+)\)/);if(r){let u=parseInt(r[3]),p=r[1]?parseInt(r[1]):0,w=parseInt(r[2]);return{total:u,passed:w,failed:p}}let a=e.match(/(\d+)\s+passing/),g=e.match(/(\d+)\s+failing/);if(a){let u=parseInt(a[1]),p=g?parseInt(g[1]):0;return{total:u+p,passed:u,failed:p}}return null}function Ce(t,e=process.cwd(),s=[]){let n=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),i=s.map(l=>S.resolve(e,l)),o=new Map,r=new Set,a=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,g;for(;(g=a.exec(n))!==null;){let d=g[1].trim().split(" ");for(let v=1;v<Math.min(d.length,6);v++){let k=d.slice(0,v).join(" ");if(r.has(k))continue;r.add(k);let f=be(k,e,i);if(f){let c=S.resolve(f);o.has(c)||o.set(c,S.relative(e,f));break}}}let u=/^FAIL\s+([a-zA-Z0-9_./-\\]+\.(?:spec|test)\.(ts|tsx|js|jsx))/gm,p;for(;(p=u.exec(n))!==null;){let l=p[1],d=S.isAbsolute(l)?l:S.resolve(e,l);!i.includes(d)&&T.existsSync(d)&&!o.has(d)&&o.set(d,S.relative(e,d))}let w=/\[(?:chromium|firefox|webkit)\]\s+[>›]\s+([^\s:]+\.(?:spec|test)\.[tj]sx?):\d+:\d+\s+[>›]/g,h;for(;(h=w.exec(n))!==null;){let l=h[1],d=S.isAbsolute(l)?l:S.resolve(e,l);!i.includes(d)&&T.existsSync(d)&&!o.has(d)&&o.set(d,S.relative(e,d))}let m=/Running:\s+([^\s]+\.(?:cy|spec|test)\.[tj]sx?)/g,y;for(;(y=m.exec(n))!==null;){let l=y[1],d=S.isAbsolute(l)?l:S.resolve(e,l);if(!i.includes(d)&&T.existsSync(d)&&!o.has(d)){let v=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(v+"\\s+\\d+\\s+\\d+\\s+([1-9]\\d*)").test(n)&&o.set(d,S.relative(e,d))}}return[...o.values()]}function me(t,e=[],s=process.cwd()){let n=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),i=e.map(l=>S.resolve(l));{let l=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,d=new Set,v;for(;(v=l.exec(n))!==null;){let f=v[1].trim().split(" ");for(let c=1;c<Math.min(f.length,5);c++){let x=f.slice(0,c).join(" ");if(d.has(x))continue;d.add(x);let L=be(x,s,i);if(L)return S.relative(s,L)}}}let o=/([a-zA-Z]:[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue)|[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))(?:\s*[:(])/g,r;for(;(r=o.exec(n))!==null;){let l=r[1];if(l){if(/(?:^|[/\\])(node_modules|dist|build)[/\\]/.test(l))continue;let d=S.isAbsolute(l)?l:S.resolve(s,l);if(!i.includes(d)&&T.existsSync(d))return l}}let a=/FAIL\s+([a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/gi,g;for(;(g=a.exec(n))!==null;){let l=g[1],d=S.isAbsolute(l)?l:S.resolve(s,l);if(!i.includes(d)&&T.existsSync(d))return l}{let l=/\[(?:chromium|firefox|webkit)\]\s+[>›]\s+([^\s:]+\.(?:spec|test)\.[tj]sx?):\d+:\d+\s+[>›]/g,d;for(;(d=l.exec(n))!==null;){let v=d[1],k=S.isAbsolute(v)?v:S.resolve(s,v);if(!i.includes(k)&&T.existsSync(k))return v}}let u=/([a-zA-Z]:[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue)|[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/g,p;for(;(p=u.exec(n))!==null;){let l=p[1];if(l){if(/(?:^|[/\\])(node_modules|dist|build)[/\\]/.test(l))continue;let d=S.isAbsolute(l)?l:S.resolve(s,l);if(!i.includes(d)&&T.existsSync(d))return l}}let w=/\b([A-Z][a-zA-Z0-9]{3,})\b/g,h,m=new Set,y=["Error","TypeError","SyntaxError","ReferenceError","RangeError","Object","Boolean","String","Number","Array","NullInjectorError","NullInjector","R3Injector","ChainedInjector","Module","Component","Standalone","Application","App2","TestBed","UserContext","Chrome","ChromeHeadless","Karma","Launching","Starting","Headless","Connected","Executed","INFO","SUCCESS","FAILED","Building","Initial","Names","Lazy","Source","Find","NotFound","NG0201","Windows","Linux","Macintosh","Users","AppData","Local","Temp","Process","Unexpected","Expected","Validation","Directory","Configuration","Documentation"];for(;(h=w.exec(n))!==null;){let l=h[1];if(!l||y.includes(l)||m.has(l)||/^[A-Z][A-Z0-9]{5,11}$/.test(l)||/^[A-Za-z0-9]{16,}$/.test(l))continue;m.add(l);let d=_e(l,s,i);if(d)return S.relative(s,d)}return null}function be(t,e,s){if(!T.existsSync(e))return null;let n=T.readdirSync(e);for(let i of n){let o=S.join(e,i);if(["node_modules","dist","build",".git",".angular"].includes(i))continue;let r;try{r=T.statSync(o)}catch{continue}if(r.isDirectory()){let a=be(t,o,s);if(a)return a}else if(/\.(spec|test)\.(ts|tsx|js|jsx)$/.test(i)){if(s.includes(S.resolve(o)))continue;try{let a=T.readFileSync(o,"utf8");if(a.includes(`describe('${t}'`)||a.includes(`describe("${t}"`))return o}catch{continue}}}return null}function _e(t,e,s){if(!T.existsSync(e))return null;let n=T.readdirSync(e);for(let i of n){let o=S.join(e,i);if(i==="node_modules"||i==="dist"||i==="build"||i===".git"||i===".angular")continue;let r;try{r=T.statSync(o)}catch{continue}if(r.isDirectory()){let a=_e(t,o,s);if(a)return a}else if(i.match(/\.(ts|tsx|js|jsx|vue)$/)){let a=T.readFileSync(o,"utf8");if(a.includes(`class ${t}`)||a.includes(`function ${t}`)||a.includes(`const ${t}`)||a.includes(`let ${t}`)||a.includes(`exports.${t}`)||a.includes(`module.exports.${t}`)){let g=o,u=S.extname(o),p=o.slice(0,-u.length);if(!i.includes(".spec.")&&!i.includes(".test.")){let w=[`${p}.spec${u}`,`${p}.test${u}`,`${p}.spec.js`,`${p}.test.js`];for(let h of w)if(T.existsSync(h)){g=h;break}}if(!s.includes(S.resolve(g)))return g}}}return null}var de=require("ai"),Ge=require("@ai-sdk/openai"),He=require("@ai-sdk/anthropic"),Be=require("@ai-sdk/google"),qe=j(require("dotenv"));qe.config({quiet:!0});var Ae=15e3;function We(t,e){return t.length<=Ae?t:(console.warn(`[Lisa.ai LLM] ${e} is ${t.length} chars \u2014 truncating to ${Ae} to stay within context window.`),t.slice(0,Ae)+`
2
+ "use strict";var Et=Object.create;var _e=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Ft=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty;var It=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Tt=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ft(t))!Pt.call(e,o)&&o!==s&&_e(e,o,{get:()=>t[o],enumerable:!(n=jt(t,o))||n.enumerable});return e};var b=(e,t,s)=>(s=e!=null?Et(At(e)):{},Tt(t||!e||!e.__esModule?_e(s,"default",{value:e,enumerable:!0}):s,e));var Lt=It((tn,Wt)=>{Wt.exports={name:"@lisa.ai/agent",version:"2.9.3",description:"Lisa.ai Autonomous CI/CD Worker Agent",main:"dist/index.js",bin:{"lisa-agent":"dist/index.js"},files:["dist/"],scripts:{build:"tsup",typecheck:"tsc --noEmit",start:"node dist/index.js",dev:"ts-node src/index.ts",prepublishOnly:"npm run typecheck && npm run build"},keywords:["lisa","ci","cd","agent"],author:"Lisa.ai",license:"ISC",dependencies:{"@ai-sdk/anthropic":"^3.0.46","@ai-sdk/google":"^3.0.30","@ai-sdk/openai":"^3.0.30","@octokit/rest":"^22.0.1",ai:"^6.0.94",commander:"^11.1.0",dotenv:"^17.3.1","simple-git":"^3.31.1"},devDependencies:{"@types/jest":"^30.0.0","@types/node":"^20.0.0","ts-node":"^10.9.1",tsup:"^8.5.1",typescript:"^5.0.0"}}});var kt=require("commander"),X=b(require("fs")),he=b(require("path")),Ct=b(require("readline"));var Oe=b(require("dotenv"));Oe.config({quiet:!0});async function ye(e){let t=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3088";try{let s=`${t}/api/v1/lisa/config/${e}`;console.log(`[Lisa.ai Agent] Fetching dynamic configuration from ${s}...`);let n=await fetch(s);if(!n.ok){let i=n.status===404?"not_found":"unreachable";return console.warn(i==="not_found"?`[Lisa.ai Agent Warning] Control Plane returned 404. Project '${e}' not found.`:`[Lisa.ai Agent Warning] Control Plane returned ${n.status}. Falling back to local defaults.`),{ok:!1,reason:i}}return{ok:!0,config:await n.json()}}catch{return console.warn(`[Lisa.ai Agent Warning] Failed to reach Control Plane (${t}). Using local fallback configuration.`),{ok:!1,reason:"unreachable"}}}var rt=require("child_process"),H=b(require("fs")),z=b(require("path"));var S=b(require("path")),I=b(require("fs"));function we(e){return e.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"")}function Z(e){let t=we(e),s=[...t.matchAll(/Executed\s+(\d+)\s+of\s+(\d+)(?:\s+\((\d+)\s+FAILED\))?/g)];if(s.length>0){let p=[...s].reverse().find(f=>f[3]!==void 0)??s[s.length-1],u=parseInt(p[2]),y=p[3]?parseInt(p[3]):0,h=parseInt(p[1])-y;return{total:u,passed:h,failed:y}}let n=t.match(/Tests:\s+(?:(\d+)\s+failed,?\s*)?(?:(\d+)\s+passed,?\s*)?(\d+)\s+total/);if(n){let p=parseInt(n[3]),u=n[1]?parseInt(n[1]):0,y=n[2]?parseInt(n[2]):0;return{total:p,passed:y,failed:u}}let o=t.match(/(\d+)\s+failed/),i=t.match(/(\d+)\s+passed/);if(i||o){let p=o?parseInt(o[1]):0,u=i?parseInt(i[1]):0,y=t.match(/(\d+)\s+skipped/),h=y?parseInt(y[1]):0;return{total:u+p+h,passed:u,failed:p}}let a=t.match(/Tests\s+(?:(\d+)\s+failed\s*\|?\s*)?(\d+)\s+passed\s*\((\d+)\)/);if(a){let p=parseInt(a[3]),u=a[1]?parseInt(a[1]):0,y=parseInt(a[2]);return{total:p,passed:y,failed:u}}let r=t.match(/(\d+)\s+passing/),d=t.match(/(\d+)\s+failing/);if(r){let p=parseInt(r[1]),u=d?parseInt(d[1]):0;return{total:p+u,passed:p,failed:u}}return null}function Fe(e,t=process.cwd(),s=[]){let n=e.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),o=s.map(l=>S.resolve(t,l)),i=new Map,a=new Set,r=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,d;for(;(d=r.exec(n))!==null;){let c=d[1].trim().split(" ");for(let x=1;x<Math.min(c.length,6);x++){let k=c.slice(0,x).join(" ");if(a.has(k))continue;a.add(k);let $=Ae(k,t,o);if($){let g=S.resolve($);i.has(g)||i.set(g,S.relative(t,$));break}}}let p=/^FAIL\s+([a-zA-Z0-9_./-\\]+\.(?:spec|test)\.(ts|tsx|js|jsx))/gm,u;for(;(u=p.exec(n))!==null;){let l=u[1],c=S.isAbsolute(l)?l:S.resolve(t,l);!o.includes(c)&&I.existsSync(c)&&!i.has(c)&&i.set(c,S.relative(t,c))}let y=/\[(?:chromium|firefox|webkit)\]\s+[>›]\s+([^\s:]+\.(?:spec|test)\.[tj]sx?):\d+:\d+\s+[>›]/g,h;for(;(h=y.exec(n))!==null;){let l=h[1],c=S.isAbsolute(l)?l:S.resolve(t,l);!o.includes(c)&&I.existsSync(c)&&!i.has(c)&&i.set(c,S.relative(t,c))}let f=/Running:\s+([^\s]+\.(?:cy|spec|test)\.[tj]sx?)/g,w;for(;(w=f.exec(n))!==null;){let l=w[1],c=S.isAbsolute(l)?l:S.resolve(t,l);if(!o.includes(c)&&I.existsSync(c)&&!i.has(c)){let x=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(x+"\\s+\\d+\\s+\\d+\\s+([1-9]\\d*)").test(n)&&i.set(c,S.relative(t,c))}}return[...i.values()]}function ve(e,t=[],s=process.cwd()){let n=e.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),o=t.map(l=>S.resolve(l));{let l=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,c=new Set,x;for(;(x=l.exec(n))!==null;){let $=x[1].trim().split(" ");for(let g=1;g<Math.min($.length,5);g++){let m=$.slice(0,g).join(" ");if(c.has(m))continue;c.add(m);let v=Ae(m,s,o);if(v)return S.relative(s,v)}}}let i=/([a-zA-Z]:[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue)|[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))(?:\s*[:(])/g,a;for(;(a=i.exec(n))!==null;){let l=a[1];if(l){if(/(?:^|[/\\])(node_modules|dist|build)[/\\]/.test(l))continue;let c=S.isAbsolute(l)?l:S.resolve(s,l);if(!o.includes(c)&&I.existsSync(c))return l}}let r=/FAIL\s+([a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/gi,d;for(;(d=r.exec(n))!==null;){let l=d[1],c=S.isAbsolute(l)?l:S.resolve(s,l);if(!o.includes(c)&&I.existsSync(c))return l}{let l=/\[(?:chromium|firefox|webkit)\]\s+[>›]\s+([^\s:]+\.(?:spec|test)\.[tj]sx?):\d+:\d+\s+[>›]/g,c;for(;(c=l.exec(n))!==null;){let x=c[1],k=S.isAbsolute(x)?x:S.resolve(s,x);if(!o.includes(k)&&I.existsSync(k))return x}}let p=/([a-zA-Z]:[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue)|[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/g,u;for(;(u=p.exec(n))!==null;){let l=u[1];if(l){if(/(?:^|[/\\])(node_modules|dist|build)[/\\]/.test(l))continue;let c=S.isAbsolute(l)?l:S.resolve(s,l);if(!o.includes(c)&&I.existsSync(c))return l}}let y=/\b([A-Z][a-zA-Z0-9]{3,})\b/g,h,f=new Set,w=["Error","TypeError","SyntaxError","ReferenceError","RangeError","Object","Boolean","String","Number","Array","NullInjectorError","NullInjector","R3Injector","ChainedInjector","Module","Component","Standalone","Application","App2","TestBed","UserContext","Chrome","ChromeHeadless","Karma","Launching","Starting","Headless","Connected","Executed","INFO","SUCCESS","FAILED","Building","Initial","Names","Lazy","Source","Find","NotFound","NG0201","Windows","Linux","Macintosh","Users","AppData","Local","Temp","Process","Unexpected","Expected","Validation","Directory","Configuration","Documentation"];for(;(h=y.exec(n))!==null;){let l=h[1];if(!l||w.includes(l)||f.has(l)||/^[A-Z][A-Z0-9]{5,11}$/.test(l)||/^[A-Za-z0-9]{16,}$/.test(l))continue;f.add(l);let c=Ge(l,s,o);if(c)return S.relative(s,c)}return null}function Ae(e,t,s){if(!I.existsSync(t))return null;let n=I.readdirSync(t);for(let o of n){let i=S.join(t,o);if(["node_modules","dist","build",".git",".angular"].includes(o))continue;let a;try{a=I.statSync(i)}catch{continue}if(a.isDirectory()){let r=Ae(e,i,s);if(r)return r}else if(/\.(spec|test)\.(ts|tsx|js|jsx)$/.test(o)){if(s.includes(S.resolve(i)))continue;try{let r=I.readFileSync(i,"utf8");if(r.includes(`describe('${e}'`)||r.includes(`describe("${e}"`))return i}catch{continue}}}return null}function Ge(e,t,s){if(!I.existsSync(t))return null;let n=I.readdirSync(t);for(let o of n){let i=S.join(t,o);if(o==="node_modules"||o==="dist"||o==="build"||o===".git"||o===".angular")continue;let a;try{a=I.statSync(i)}catch{continue}if(a.isDirectory()){let r=Ge(e,i,s);if(r)return r}else if(o.match(/\.(ts|tsx|js|jsx|vue)$/)){let r=I.readFileSync(i,"utf8");if(r.includes(`class ${e}`)||r.includes(`function ${e}`)||r.includes(`const ${e}`)||r.includes(`let ${e}`)||r.includes(`exports.${e}`)||r.includes(`module.exports.${e}`)){let d=i,p=S.extname(i),u=i.slice(0,-p.length);if(!o.includes(".spec.")&&!o.includes(".test.")){let y=[`${u}.spec${p}`,`${u}.test${p}`,`${u}.spec.js`,`${u}.test.js`];for(let h of y)if(I.existsSync(h)){d=h;break}}if(!s.includes(S.resolve(d)))return d}}}return null}var de=require("ai"),He=require("@ai-sdk/openai"),qe=require("@ai-sdk/anthropic"),Be=require("@ai-sdk/google"),Ye=b(require("dotenv"));Ye.config({quiet:!0});var Pe=15e3;function We(e,t){return e.length<=Pe?e:(console.warn(`[Lisa.ai LLM] ${t} is ${e.length} chars \u2014 truncating to ${Pe} to stay within context window.`),e.slice(0,Pe)+`
3
3
 
4
- // ... (truncated)`)}function Ye(t,e){if(!/\b(describe|it\(|test\(|expect\(|beforeEach|afterEach|suite|assert\.|cy\.)\b/.test(t))throw new Error(`LLM returned a non-code response for ${e} (possible context overflow). Skipping to prevent file corruption.`)}function Ve(t){if(!t||t.length===0)return"";let e={unit:"unit tests \u2014 test every function/method in complete isolation, mocking ALL external dependencies, services, and I/O",integration:"integration tests \u2014 test how modules work together using real service/repository layers; for HTTP routes use supertest or equivalent",e2e:"end-to-end tests \u2014 simulate complete user flows using the configured e2e framework (Playwright/Cypress); cover the full path from HTTP request to response or UI action to assertion"};return`5. Test scope \u2014 generate ALL of the following test types for this file:
5
- ${t.map(n=>` \u2022 ${e[n]??n}`).join(`
4
+ // ... (truncated)`)}function Ke(e,t){if(!/\b(describe|it\(|test\(|expect\(|beforeEach|afterEach|suite|assert\.|cy\.)\b/.test(e))throw new Error(`LLM returned a non-code response for ${t} (possible context overflow). Skipping to prevent file corruption.`)}function Ve(e){if(!e||e.length===0)return"";let t={unit:"unit tests \u2014 test every function/method in complete isolation, mocking ALL external dependencies, services, and I/O",integration:"integration tests \u2014 test how modules work together using real service/repository layers; for HTTP routes use supertest or equivalent",e2e:"end-to-end tests \u2014 simulate complete user flows using the configured e2e framework (Playwright/Cypress); cover the full path from HTTP request to response or UI action to assertion"};return`5. Test scope \u2014 generate ALL of the following test types for this file:
5
+ ${e.map(n=>` \u2022 ${t[n]??n}`).join(`
6
6
  `)}
7
- `}function he(t,e){if(t==="claude"){let i=e||process.env.ANTHROPIC_API_KEY;if(!i)throw new Error("No Anthropic API key provided by local ENV or Control Plane");let o=process.env.LISA_CLAUDE_MODEL||"claude-haiku-4-5";return(0,He.createAnthropic)({apiKey:i})(o)}if(t==="openai"){let i=e||process.env.OPENAI_API_KEY;if(!i)throw new Error("No OpenAI API key provided by local ENV or Control Plane");let o=process.env.LISA_OPENAI_MODEL||"gpt-4o-mini";return(0,Ge.createOpenAI)({apiKey:i})(o)}let s=e||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!s)throw new Error("No Google API key provided by local ENV or Control Plane");let n=process.env.LISA_GOOGLE_MODEL||"gemini-2.0-flash";return(0,Be.createGoogleGenerativeAI)({apiKey:s})(n)}async function Ke(t,e,s,n,i,o,r,a){console.log(`[Lisa.ai Auto-Heal] Requesting fix from ${n} for ${t}...`);let g=he(n,i),u=`You are Lisa.ai, an autonomous CI/CD expert platform.
7
+ `}function xe(e,t){if(e==="claude"){let o=t||process.env.ANTHROPIC_API_KEY;if(!o)throw new Error("No Anthropic API key provided by local ENV or Control Plane");let i=process.env.LISA_CLAUDE_MODEL||"claude-haiku-4-5";return(0,qe.createAnthropic)({apiKey:o})(i)}if(e==="openai"){let o=t||process.env.OPENAI_API_KEY;if(!o)throw new Error("No OpenAI API key provided by local ENV or Control Plane");let i=process.env.LISA_OPENAI_MODEL||"gpt-4o-mini";return(0,He.createOpenAI)({apiKey:o})(i)}let s=t||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!s)throw new Error("No Google API key provided by local ENV or Control Plane");let n=process.env.LISA_GOOGLE_MODEL||"gemini-2.0-flash";return(0,Be.createGoogleGenerativeAI)({apiKey:s})(n)}async function ze(e,t,s,n,o,i,a,r){console.log(`[Lisa.ai Auto-Heal] Requesting fix from ${n} for ${e}...`);let d=xe(n,o),p=`You are Lisa.ai, an autonomous CI/CD expert platform.
8
8
  A build/compilation error occurred. Your task is to fix the provided file so that the error resolves.
9
9
 
10
10
  --- Error Log ---
11
11
  `+s+`
12
12
 
13
- --- Target File Content (`+t+`) ---
14
- `+e+`
13
+ --- Target File Content (`+e+`) ---
14
+ `+t+`
15
15
 
16
16
  --- Constraints ---
17
17
  1. Do not delete business logic unless absolutely necessary to resolve a missing dependency.
@@ -21,67 +21,82 @@ A build/compilation error occurred. Your task is to fix the provided file so tha
21
21
  5. FRAMEWORK TEST RULE: If fixing a testing file ('.spec' or '.test') and an Angular error happens like 'NullInjectorError: No provider for X', you MUST add X to the 'providers' array in 'TestBed.configureTestingModule' or import the required testing module. If a React testing library error arises, fix the render context.
22
22
  6. CRITICAL ANGULAR RULE: If an Angular component imports 'RouterLink' or uses '[routerLink]' in its template, you MUST provide 'ActivatedRoute' in the providers array or import 'RouterTestingModule'. If it uses HTTP, import 'HttpClientTestingModule'.
23
23
  7. CRITICAL STANDALONE RULE: If a component has 'standalone: true' in its decorator (check the Sibling Context!), you MUST NOT add it to the 'declarations' array. Instead, you MUST add it to the 'imports' array within 'TestBed.configureTestingModule'.
24
- 8. Return the code wrapped in a markdown code block (\`\`\`typescript ... \`\`\`). Do not include any explanation or intro text.`;if(r){if(/standalone\s*:\s*true/.test(r)){let m=r.match(/export class (\w+)/),y=m?m[1]:"the component";u+=`
24
+ 8. Return the code wrapped in a markdown code block (\`\`\`typescript ... \`\`\`). Do not include any explanation or intro text.`;if(a){if(/standalone\s*:\s*true/.test(a)){let f=a.match(/export class (\w+)/),w=f?f[1]:"the component";p+=`
25
25
 
26
26
  --- CRITICAL ARCHITECTURAL REQUIREMENT ---
27
- The component `+y+` is marked as STANDALONE (standalone: true).
28
- You MUST add `+y+` to the 'imports' array within 'TestBed.configureTestingModule'.
29
- DO NOT add it to the 'declarations' array. If you omit `+y+" from 'imports', the test will fail."}u+=`
27
+ The component `+w+` is marked as STANDALONE (standalone: true).
28
+ You MUST add `+w+` to the 'imports' array within 'TestBed.configureTestingModule'.
29
+ DO NOT add it to the 'declarations' array. If you omit `+w+" from 'imports', the test will fail."}p+=`
30
30
 
31
31
  --- Sibling Component / Service Context ---
32
32
  You are fixing a '.spec' test file. Here is the actual implementation code for the component you are testing.
33
33
  Use this to identify EXACTLY which imports, Services, and Variables need to be mocked inside your 'TestBed'.
34
- `+r}a&&a.length>0&&(u+=`
34
+ `+a}r&&r.length>0&&(p+=`
35
35
 
36
36
  --- MEMORY ENGINE: PROVEN FIX PATTERNS ---
37
37
  The following fix patterns were SUCCESSFULLY used to resolve identical errors in past runs. Prioritise these approaches before trying anything novel:
38
- `+a.map((h,m)=>`
39
- [Pattern ${m+1}]
38
+ `+r.map((h,f)=>`
39
+ [Pattern ${f+1}]
40
40
  ${h}`).join(`
41
- `)),o&&(console.log(`[Lisa.ai Auto-Heal] Warning! Agent is looping on ${t}. Injecting previous failed context...`),u+=`
41
+ `)),i&&(console.log(`[Lisa.ai Auto-Heal] Warning! Agent is looping on ${e}. Injecting previous failed context...`),p+=`
42
42
 
43
43
  --- CRITICAL WARNING ---
44
44
  You previously attempted to fix this file but the compiler REJECTED your fix!
45
45
  Here is the previous analysis and failed fix you attempted:
46
- `+o+`
46
+ `+i+`
47
47
 
48
- DO NOT repeat the identical code changes. Try a completely different programming approach, fix syntax typos, or check for missing imports.`);let{text:p}=await(0,de.generateText)({model:g,prompt:u}),w=p.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return w?w[1].trim():p.trim()}async function X(t,e,s,n,i,o){console.log(`[Lisa.ai Coverage] Requesting test generation from ${s} for ${t}...`);let r=he(s,n),a=i?`3. You MUST use the '${i}' testing framework exclusively. All imports, describe/it/test blocks, and mock utilities must follow '${i}' conventions.
48
+ DO NOT repeat the identical code changes. Try a completely different programming approach, fix syntax typos, or check for missing imports.`);let{text:u}=await(0,de.generateText)({model:d,prompt:p}),y=u.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return y?y[1].trim():u.trim()}async function ee(e,t,s,n,o,i){console.log(`[Lisa.ai Coverage] Requesting test generation from ${s} for ${e}...`);let a=xe(s,n),r=o?`3. You MUST use the '${o}' testing framework exclusively. All imports, describe/it/test blocks, and mock utilities must follow '${o}' conventions.
49
49
  `:`3. Include all necessary imports assuming a standard testing framework (Jest/Karma/Vitest) is available.
50
- `,g=Ve(o),u=`You are Lisa.ai, an autonomous CI/CD expert platform.
50
+ `,d=Ve(i),p=`You are Lisa.ai, an autonomous CI/CD expert platform.
51
51
  A source file lacks 100% test coverage. Your task is to generate a comprehensive testing suite covering all branches, lines, and functions.
52
52
 
53
- --- Target File Content (`+t+`) ---
54
- `+We(e,t)+"\n\n--- Constraints ---\n1. Return the generated test code wrapped in a markdown code block (```typescript ... ```).\n2. Do not include any explanation or intro text.\n"+a+`4. Aim for 100% logic coverage.
55
- `+g,{text:p}=await(0,de.generateText)({model:r,prompt:u}),w=p.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),h=w?w[1].trim():p.trim();return Ye(h,t),h}async function ze(t,e,s,n,i,o,r,a){console.log(`[Lisa.ai Coverage] Requesting test update from ${i} for ${t}...`);let g=he(i,o),u=r?`3. You MUST use the '${r}' testing framework exclusively. All new tests must follow '${r}' conventions and integrate cleanly with the existing suite.
53
+ --- Target File Content (`+e+`) ---
54
+ `+We(t,e)+"\n\n--- Constraints ---\n1. Return the generated test code wrapped in a markdown code block (```typescript ... ```).\n2. Do not include any explanation or intro text.\n"+r+`4. Aim for 100% logic coverage.
55
+ `+d,{text:u}=await(0,de.generateText)({model:a,prompt:p}),y=u.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),h=y?y[1].trim():u.trim();return Ke(h,e),h}async function Ze(e,t,s,n,o,i,a,r){console.log(`[Lisa.ai Coverage] Requesting test update from ${o} for ${e}...`);let d=xe(o,i),p=a?`3. You MUST use the '${a}' testing framework exclusively. All new tests must follow '${a}' conventions and integrate cleanly with the existing suite.
56
56
  `:`3. Append missing tests to the existing suite. Do not delete existing passing tests unless they are fundamentally broken.
57
- `,p=Ve(a),w=`You are Lisa.ai, an autonomous CI/CD expert platform.
57
+ `,u=Ve(r),y=`You are Lisa.ai, an autonomous CI/CD expert platform.
58
58
  A source file lacks 100% test coverage. You must update its existing test suite to achieve full coverage.
59
59
 
60
- --- Target File Content (`+t+`) ---
61
- `+We(e,t)+`
60
+ --- Target File Content (`+e+`) ---
61
+ `+We(t,e)+`
62
62
 
63
63
  --- Existing Test Suite (`+s+`) ---
64
- `+n+"\n\n--- Constraints ---\n1. Return the updated complete test code wrapped in a markdown code block (```typescript ... ```).\n2. Do not include any explanation or intro text.\n"+u+`4. Aim for 100% logic coverage across branches, lines, and functions.
65
- `+p,{text:h}=await(0,de.generateText)({model:g,prompt:w}),m=h.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),y=m?m[1].trim():h.trim();return Ye(y,t),y}async function se(t,e,s){let n=he(e,s),{text:i}=await(0,de.generateText)({model:n,prompt:t}),o=i.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return o?o[1].trim():i.trim()}var Ze=j(require("simple-git")),Je=require("@octokit/rest"),zt=require("dotenv/config");async function Fe(t){console.log(`
66
- [Lisa.ai PR Engine] Initializing Pull Request for ${t}...`);let e=(0,Ze.default)(),n=`lisa-fix/build-error-${new Date().getTime()}`,i=`fix: automated auto-heal by Lisa.ai for ${t}`,o="main";try{o=(await e.revparse(["--abbrev-ref","HEAD"])).trim()}catch{}try{await e.addConfig("user.name","Lisa.ai"),await e.addConfig("user.email","lisa@lisa.ai"),await e.checkoutLocalBranch(n),await e.add(t),await e.commit(i),console.log(`[Lisa.ai PR Engine] Committed changes to branch ${n}`),console.log("[Lisa.ai PR Engine] Pushing branch to remote origin..."),await e.push("origin",n,{"--set-upstream":null});let r=new Je.Octokit({auth:process.env.GITHUB_TOKEN}),a=process.env.GITHUB_REPOSITORY;if(a&&process.env.GITHUB_TOKEN){let[g,u]=a.split("/");console.log(`[Lisa.ai PR Engine] Opening Pull Request against ${g}/${u}...`);let p=await r.rest.pulls.create({owner:g,repo:u,title:i,body:`### Lisa.ai Auto-Healed Pull Request
67
- This PR was automatically generated by Lisa.ai to resolve a failing compilation/build step.
68
-
69
- **Healed File:** \`${t}\`
70
-
71
- Please review the changes.`,head:n,base:o});console.log(`\u2705 [Lisa.ai PR Engine] Pull Request created successfully: ${p.data.html_url}`)}else console.log("\u26A0\uFE0F [Lisa.ai PR Engine] GITHUB_TOKEN or GITHUB_REPOSITORY not set. Skipping GitHub Pull Request creation.")}catch(r){console.error(`
72
- \u{1F6A8} [Lisa.ai PR Engine Error] Failed to create Pull Request:`,r.message)}finally{try{await e.checkout(o)}catch{}}}var Qe=j(require("dotenv"));Qe.config({quiet:!0});async function I(t){let s=`${process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3000"}/api/telemetry`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).catch(n=>{console.debug(`[Lisa.ai Agent Debug] Failed to report telemetry: ${n.message}`)})}var q=j(require("fs")),U=j(require("path"));var ye=j(require("fs")),Xe=j(require("path")),ee=".lisai.json",R=class{static _config=null;static _loaded=!1;static load(e=process.cwd()){if(this._loaded)return this._config;this._loaded=!0;let s=Xe.resolve(e,ee);if(!ye.existsSync(s))return null;try{let n=ye.readFileSync(s,"utf-8");return this._config=JSON.parse(n),console.log(`[Lisa.ai Config] Loaded project config from ${ee}`),this._config}catch(n){return console.warn(`[Lisa.ai Config] Warning: ${ee} found but failed to parse \u2014 ${n.message}. Using defaults.`),null}}static get(){return this._config}static applyEnvDefaults(e){if(!e.model)return;let s={claude:"LISA_CLAUDE_MODEL",openai:"LISA_OPENAI_MODEL",gemini:"LISA_GOOGLE_MODEL"},n=e.provider;n&&s[n]&&!process.env[s[n]]&&(process.env[s[n]]=e.model,console.log(`[Lisa.ai Config] Model override applied: ${n} \u2192 ${e.model}`))}static printSummary(e){let s=[];e.provider&&s.push(`provider=${e.provider}`),e.model&&s.push(`model=${e.model}`),e.testingFramework&&s.push(`testingFramework=${e.testingFramework}`),e.testTypes?.length&&s.push(`testTypes=[${e.testTypes.join(",")}]`),e.maxRetries!==void 0&&s.push(`maxRetries=${e.maxRetries}`),e.testCommand&&s.push(`testCommand="${e.testCommand}"`),e.e2eFramework&&s.push(`e2eFramework=${e.e2eFramework}`),e.e2eCommand&&s.push(`e2eCommand="${e.e2eCommand}"`),s.length&&console.log(`[Lisa.ai Config] Settings: ${s.join(", ")}`),e.skipFiles?.length&&console.log(`[Lisa.ai Config] Extra skip files : ${e.skipFiles.join(", ")}`),e.skipDirs?.length&&console.log(`[Lisa.ai Config] Extra skip dirs : ${e.skipDirs.join(", ")}`),e.skipPaths?.length&&console.log(`[Lisa.ai Config] Extra skip paths : ${e.skipPaths.join(", ")}`)}};var Y=class{static scanRepository(e=process.cwd()){let s=U.resolve(e,"package.json"),n={type:"unknown",testingFramework:"none"};if(!q.existsSync(s))return console.warn(`[Lisa.ai AutoDiscovery] No package.json found at ${s}. Defaulting to Generic Node.`),n.type="node",n;let i=JSON.parse(q.readFileSync(s,"utf8")),o={...i.dependencies||{},...i.devDependencies||{}},r=i.scripts||{};return o["@angular/core"]?n.type="angular":o.react?n.type="react":o.vue?n.type="vue":n.type="node",o.jest||r.test?.includes("jest")?n.testingFramework="jest":o.karma||r.test?.includes("karma")||r.test?.includes("ng test")?n.testingFramework="karma":(o.vitest||r.test?.includes("vitest"))&&(n.testingFramework="vitest"),n.testingFramework!=="none"&&(n.testingFramework==="karma"?n.type==="angular"?n.suggestedTestCommand="npx ng test --no-watch --browsers=ChromeHeadless":n.suggestedTestCommand="npx karma start --single-run --browsers=ChromeHeadless":r.test?n.suggestedTestCommand="npm run test":n.testingFramework==="jest"?n.suggestedTestCommand="npx jest --coverage":n.testingFramework==="vitest"&&(n.suggestedTestCommand="npx vitest run --coverage")),n}static findUntestedFiles(e,s=[]){let n=[];if(!q.existsSync(e))return n;let i=q.readdirSync(e),o=R.get(),r=o?.skipDirs??[],a=o?.skipFiles??[],g=o?.skipPaths??[],u=["node_modules","dist","build",".git",".angular","coverage","public","assets",...r],p=["main.ts","index.ts","index.js","index.jsx","app.config.ts","app.routes.ts","styles.css","styles.scss","tailwind.config.js","tailwind.config.ts","eslint.config.js","eslint.config.ts","jest.config.js","jest.config.ts","jest.config.mjs","jest.setup.js","jest.setup.ts","webpack.config.js","webpack.config.ts","babel.config.js","babel.config.ts","rollup.config.js","rollup.config.ts","vite.config.js","vite.config.ts","vitest.config.js","vitest.config.ts","karma.conf.js","karma.config.js","prettier.config.js","prettier.config.ts","postcss.config.js","postcss.config.ts","gulpfile.js","Gulpfile.js",".eslintrc.js",".eslintrc.ts",".babelrc.js"],w=[/^\./,/\.config\.(js|ts|mjs|cjs)$/,/\.conf\.(js|ts|mjs|cjs)$/];for(let h of i){let m=U.join(e,h);if(u.includes(h))continue;let y;try{y=q.statSync(m)}catch{continue}if(y.isDirectory())n.push(...this.findUntestedFiles(m,s));else if(h.match(/\.(ts|tsx|js|jsx|vue)$/)&&!h.includes(".spec.")&&!h.includes(".test.")){if(p.includes(h)||a.includes(h)||w.some(f=>f.test(h)))continue;let l=U.extname(h),d=h.slice(0,-l.length);if(![U.join(e,`${d}.spec${l}`),U.join(e,`${d}.test${l}`),U.join(e,`${d}.spec.js`),U.join(e,`${d}.test.js`),U.join(e,`${d}.spec.ts`),U.join(e,`${d}.test.ts`)].some(f=>q.existsSync(f))){let f=U.relative(process.cwd(),m);if(g.some(c=>f.startsWith(c)))continue;s.includes(f)||n.push(f)}}}return n}};var et=require("child_process"),ne=class{static async installMissingFramework(e,s=process.cwd()){if(e.testingFramework!=="none")return e;console.log(`
73
- [Lisa.ai Auto-Installer] \u{1F6A8} No testing framework detected for ${e.type} architecture.`),console.log("[Lisa.ai Auto-Installer] \u{1FA84} Initiating Zero-Config Installation Protocol...");let n="",i="none";switch(e.type){case"angular":console.log("[Lisa.ai Auto-Installer] Provisioning Angular TestBed environment..."),n="npm install --save-dev karma karma-chrome-launcher karma-coverage karma-jasmine jasmine-core @types/jasmine",i="karma",e.suggestedTestCommand="npm run test";break;case"react":case"node":default:console.log("[Lisa.ai Auto-Installer] Provisioning Universal Jest environment..."),n="npm install --save-dev jest @types/jest ts-jest",i="jest",e.suggestedTestCommand="npx jest --coverage";break;case"vue":console.log("[Lisa.ai Auto-Installer] Provisioning Vue Vitest environment..."),n="npm install --save-dev vitest @vue/test-utils jsdom",i="vitest",e.suggestedTestCommand="npx vitest run --coverage";break}if(n){console.log(`[Lisa.ai Executing] ${n}`);let o=n.split(" "),r=process.platform==="win32"?`${o[0]}.cmd`:o[0];return(0,et.spawnSync)(r,o.slice(1),{cwd:s,stdio:"inherit"}).status!==0&&(console.error(`
74
- \u274C [Lisa.ai Auto-Installer] Failed to construct dynamic testing environment.`),process.exit(1)),console.log("\u2705 [Lisa.ai Auto-Installer] Framework successfully injected."),e.testingFramework=i,e}return e}};var we=j(require("fs")),Pe=j(require("path"));var oe=class{static async provisionConfigurationFiles(e,s,n,i=process.cwd()){if(e.testingFramework==="none")return;if(console.log(`
75
- [Lisa.ai Auto-Generator] \u{1FA84} Analyzing ${e.type} architecture to generate ${e.testingFramework} configuration specs...`),["jest.config.js","jest.config.ts","karma.conf.js","vitest.config.ts","vitest.config.js"].some(g=>we.existsSync(Pe.join(i,g)))){console.log("[Lisa.ai Auto-Generator] Setup file detected. Bypassing initialization.");return}let a=`You are an expert ${e.type} architect.
76
- Write a production-ready '${e.testingFramework}' configuration file for a standard '${e.type}' application.
64
+ `+n+"\n\n--- Constraints ---\n1. Return the updated complete test code wrapped in a markdown code block (```typescript ... ```).\n2. Do not include any explanation or intro text.\n"+p+`4. Aim for 100% logic coverage across branches, lines, and functions.
65
+ `+u,{text:h}=await(0,de.generateText)({model:d,prompt:y}),f=h.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),w=f?f[1].trim():h.trim();return Ke(w,e),w}async function ie(e,t,s){let n=xe(t,s),{text:o}=await(0,de.generateText)({model:n,prompt:e}),i=o.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return i?i[1].trim():o.trim()}var Je=b(require("fs")),Qe=b(require("simple-git")),Xe=require("@octokit/rest"),Xt=require("dotenv/config");function Rt(e){let t=e.healedFiles.map(o=>`- \`${o}\``).join(`
66
+ `),s=e.quarantinedFiles.length>0?e.quarantinedFiles.map(o=>`- \`${o}\``).join(`
67
+ `):"_None \u2014 all failures healed successfully._",n=e.testCounts?["| Metric | Before | After (est.) |","|---|---|---|",`| Passing | ${e.testCounts.passed} | ~${e.testCounts.passed+e.healedFiles.length} |`,`| Failing | ${e.testCounts.failed} | ~${Math.max(0,e.testCounts.failed-e.healedFiles.length)} |`,`| Total | ${e.testCounts.total} | ${e.testCounts.total} |`].join(`
68
+ `):"_Test counts not available._";return`## Lisa.ai Auto-Heal Report
69
+
70
+ ### Summary
71
+ Lisa.ai automatically healed **${e.healedFiles.length}** failing test spec(s) using **${e.modelProvider}** (${e.framework}, scope: ${e.scope}).
72
+
73
+ ### Healed Files
74
+ ${t}
75
+
76
+ ### Quarantined Files (could not auto-heal)
77
+ ${s}
78
+
79
+ ### Test Suite Impact
80
+ ${n}
81
+
82
+ ---
83
+
84
+ > This PR was generated automatically by [Lisa.ai](https://www.npmjs.com/package/@lisa.ai/agent).
85
+ > Please review the changes before merging.`}async function et(e){if(e.healedFiles.length===0)return console.log("[Lisa.ai CI] No files were healed. Skipping PR creation."),null;let t=process.env.GITHUB_TOKEN,s=process.env.GITHUB_REPOSITORY;if(!t||!s)return console.log("[Lisa.ai CI] GITHUB_TOKEN or GITHUB_REPOSITORY not set. Skipping PR creation."),null;let n=(0,Qe.default)(),i=`lisa-fix/auto-heal-${Date.now()}`,a=process.env.GITHUB_REF_NAME||"main";try{await n.addConfig("user.name","Lisa.ai"),await n.addConfig("user.email","lisa@lisa.ai"),await n.checkoutLocalBranch(i),await n.add(e.healedFiles);let r=e.healedFiles.length===1?`fix: Lisa.ai auto-healed ${e.healedFiles[0]}`:`fix: Lisa.ai auto-healed ${e.healedFiles.length} failing test specs`;await n.commit(r),console.log(`[Lisa.ai CI] Committed ${e.healedFiles.length} file(s) to branch ${i}`),await n.push("origin",i,{"--set-upstream":null}),console.log("[Lisa.ai CI] Pushed branch to origin.");let[d,p]=s.split("/"),y=await new Xe.Octokit({auth:t}).rest.pulls.create({owner:d,repo:p,title:r,body:Rt(e),head:i,base:a});return console.log(`[Lisa.ai CI] Pull Request created: ${y.data.html_url}`),y.data.html_url}catch(r){return console.error(`[Lisa.ai CI] Failed to create PR: ${r.message}`),null}}function Ie(e,t){let s=process.env.GITHUB_STEP_SUMMARY;if(!s)return;let n=["## Lisa.ai Heal Results","","| Metric | Value |","|---|---|",`| Files Healed | ${e.healedFiles.length} |`,`| Files Quarantined | ${e.quarantinedFiles.length} |`,`| Model | ${e.modelProvider} |`,`| Framework | ${e.framework} |`,`| Scope | ${e.scope} |`];e.testCounts&&n.push(`| Tests Passing (before) | ${e.testCounts.passed} |`,`| Tests Failing (before) | ${e.testCounts.failed} |`),t&&n.push("",`**Pull Request:** ${t}`),e.healedFiles.length>0&&(n.push("","### Healed Files"),e.healedFiles.forEach(o=>n.push(`- \`${o}\``))),e.quarantinedFiles.length>0&&(n.push("","### Quarantined Files"),e.quarantinedFiles.forEach(o=>n.push(`- \`${o}\``)));try{Je.appendFileSync(s,n.join(`
86
+ `)+`
87
+ `)}catch{}}var tt=b(require("dotenv"));tt.config({quiet:!0});async function T(e){let s=`${process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3088"}/api/v1/lisa/telemetry`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(n=>{console.debug(`[Lisa.ai Agent Debug] Failed to report telemetry: ${n.message}`)})}var Y=b(require("fs")),_=b(require("path"));var $e=b(require("fs")),st=b(require("path")),te=".lisai.json",R=class{static _config=null;static _loaded=!1;static load(t=process.cwd()){if(this._loaded)return this._config;this._loaded=!0;let s=st.resolve(t,te);if(!$e.existsSync(s))return null;try{let n=$e.readFileSync(s,"utf-8");return this._config=JSON.parse(n),console.log(`[Lisa.ai Config] Loaded project config from ${te}`),this._config}catch(n){return console.warn(`[Lisa.ai Config] Warning: ${te} found but failed to parse \u2014 ${n.message}. Using defaults.`),null}}static get(){return this._config}static applyEnvDefaults(t){if(!t.model)return;let s={claude:"LISA_CLAUDE_MODEL",openai:"LISA_OPENAI_MODEL",gemini:"LISA_GOOGLE_MODEL"},n=t.provider;n&&s[n]&&!process.env[s[n]]&&(process.env[s[n]]=t.model,console.log(`[Lisa.ai Config] Model override applied: ${n} \u2192 ${t.model}`))}static printSummary(t){let s=[];t.provider&&s.push(`provider=${t.provider}`),t.model&&s.push(`model=${t.model}`),t.testingFramework&&s.push(`testingFramework=${t.testingFramework}`),t.testTypes?.length&&s.push(`testTypes=[${t.testTypes.join(",")}]`),t.maxRetries!==void 0&&s.push(`maxRetries=${t.maxRetries}`),t.testCommand&&s.push(`testCommand="${t.testCommand}"`),t.e2eFramework&&s.push(`e2eFramework=${t.e2eFramework}`),t.e2eCommand&&s.push(`e2eCommand="${t.e2eCommand}"`),s.length&&console.log(`[Lisa.ai Config] Settings: ${s.join(", ")}`),t.skipFiles?.length&&console.log(`[Lisa.ai Config] Extra skip files : ${t.skipFiles.join(", ")}`),t.skipDirs?.length&&console.log(`[Lisa.ai Config] Extra skip dirs : ${t.skipDirs.join(", ")}`),t.skipPaths?.length&&console.log(`[Lisa.ai Config] Extra skip paths : ${t.skipPaths.join(", ")}`)}};var V=class{static scanRepository(t=process.cwd()){let s=_.resolve(t,"package.json"),n={type:"unknown",testingFramework:"none"};if(!Y.existsSync(s))return console.warn(`[Lisa.ai AutoDiscovery] No package.json found at ${s}. Defaulting to Generic Node.`),n.type="node",n;let o=JSON.parse(Y.readFileSync(s,"utf8")),i={...o.dependencies||{},...o.devDependencies||{}},a=o.scripts||{};return i["@angular/core"]?n.type="angular":i.react?n.type="react":i.vue?n.type="vue":n.type="node",i.jest||a.test?.includes("jest")?n.testingFramework="jest":i.karma||a.test?.includes("karma")||a.test?.includes("ng test")?n.testingFramework="karma":(i.vitest||a.test?.includes("vitest"))&&(n.testingFramework="vitest"),n.testingFramework!=="none"&&(n.testingFramework==="karma"?n.type==="angular"?n.suggestedTestCommand="npx ng test --no-watch --browsers=ChromeHeadless":n.suggestedTestCommand="npx karma start --single-run --browsers=ChromeHeadless":a.test?n.suggestedTestCommand="npm run test":n.testingFramework==="jest"?n.suggestedTestCommand="npx jest --coverage":n.testingFramework==="vitest"&&(n.suggestedTestCommand="npx vitest run --coverage")),n}static findUntestedFiles(t,s=[]){let n=[];if(!Y.existsSync(t))return n;let o=Y.readdirSync(t),i=R.get(),a=i?.skipDirs??[],r=i?.skipFiles??[],d=i?.skipPaths??[],p=["node_modules","dist","build",".git",".angular","coverage","public","assets",...a],u=["main.ts","index.ts","index.js","index.jsx","app.config.ts","app.routes.ts","styles.css","styles.scss","tailwind.config.js","tailwind.config.ts","eslint.config.js","eslint.config.ts","jest.config.js","jest.config.ts","jest.config.mjs","jest.setup.js","jest.setup.ts","webpack.config.js","webpack.config.ts","babel.config.js","babel.config.ts","rollup.config.js","rollup.config.ts","vite.config.js","vite.config.ts","vitest.config.js","vitest.config.ts","karma.conf.js","karma.config.js","prettier.config.js","prettier.config.ts","postcss.config.js","postcss.config.ts","gulpfile.js","Gulpfile.js",".eslintrc.js",".eslintrc.ts",".babelrc.js"],y=[/^\./,/\.config\.(js|ts|mjs|cjs)$/,/\.conf\.(js|ts|mjs|cjs)$/];for(let h of o){let f=_.join(t,h);if(p.includes(h))continue;let w;try{w=Y.statSync(f)}catch{continue}if(w.isDirectory())n.push(...this.findUntestedFiles(f,s));else if(h.match(/\.(ts|tsx|js|jsx|vue)$/)&&!h.includes(".spec.")&&!h.includes(".test.")){if(u.includes(h)||r.includes(h)||y.some($=>$.test(h)))continue;let l=_.extname(h),c=h.slice(0,-l.length);if(![_.join(t,`${c}.spec${l}`),_.join(t,`${c}.test${l}`),_.join(t,`${c}.spec.js`),_.join(t,`${c}.test.js`),_.join(t,`${c}.spec.ts`),_.join(t,`${c}.test.ts`)].some($=>Y.existsSync($))){let $=_.relative(process.cwd(),f);if(d.some(g=>$.startsWith(g)))continue;s.includes($)||n.push($)}}}return n}};var nt=require("child_process"),ae=class{static async installMissingFramework(t,s=process.cwd()){if(t.testingFramework!=="none")return t;console.log(`
88
+ [Lisa.ai Auto-Installer] \u{1F6A8} No testing framework detected for ${t.type} architecture.`),console.log("[Lisa.ai Auto-Installer] \u{1FA84} Initiating Zero-Config Installation Protocol...");let n="",o="none";switch(t.type){case"angular":console.log("[Lisa.ai Auto-Installer] Provisioning Angular TestBed environment..."),n="npm install --save-dev karma karma-chrome-launcher karma-coverage karma-jasmine jasmine-core @types/jasmine",o="karma",t.suggestedTestCommand="npm run test";break;case"react":case"node":default:console.log("[Lisa.ai Auto-Installer] Provisioning Universal Jest environment..."),n="npm install --save-dev jest @types/jest ts-jest",o="jest",t.suggestedTestCommand="npx jest --coverage";break;case"vue":console.log("[Lisa.ai Auto-Installer] Provisioning Vue Vitest environment..."),n="npm install --save-dev vitest @vue/test-utils jsdom",o="vitest",t.suggestedTestCommand="npx vitest run --coverage";break}if(n){console.log(`[Lisa.ai Executing] ${n}`);let i=n.split(" "),a=process.platform==="win32"?`${i[0]}.cmd`:i[0];return(0,nt.spawnSync)(a,i.slice(1),{cwd:s,stdio:"inherit"}).status!==0&&(console.error(`
89
+ \u274C [Lisa.ai Auto-Installer] Failed to construct dynamic testing environment.`),process.exit(1)),console.log("\u2705 [Lisa.ai Auto-Installer] Framework successfully injected."),t.testingFramework=o,t}return t}};var Le=b(require("fs")),Te=b(require("path"));var re=class{static async provisionConfigurationFiles(t,s,n,o=process.cwd()){if(t.testingFramework==="none")return;if(console.log(`
90
+ [Lisa.ai Auto-Generator] \u{1FA84} Analyzing ${t.type} architecture to generate ${t.testingFramework} configuration specs...`),["jest.config.js","jest.config.ts","karma.conf.js","vitest.config.ts","vitest.config.js"].some(d=>Le.existsSync(Te.join(o,d)))){console.log("[Lisa.ai Auto-Generator] Setup file detected. Bypassing initialization.");return}let r=`You are an expert ${t.type} architect.
91
+ Write a production-ready '${t.testingFramework}' configuration file for a standard '${t.type}' application.
77
92
  The application resides in the root directory.
78
93
 
79
94
  Requirements:
80
95
  1. Ensure it specifically instruments code coverage.
81
96
  2. Ensure standard transpilation (ts-jest for jest, or standard karma-webpack/karma-typescript implementations).
82
97
  3. Do NOT wrap your response in markdown formatting (no \`\`\`javascript).
83
- 4. Return ONLY the raw code string block.`;try{let g=await se(a,s,n),u="";e.testingFramework==="jest"&&(u="jest.config.js"),e.testingFramework==="karma"&&(u="karma.conf.js"),e.testingFramework==="vitest"&&(u="vitest.config.ts");let p=Pe.join(i,u);we.writeFileSync(p,g,"utf-8"),console.log(`\u2705 [Lisa.ai Auto-Generator] Natively wrote ${u} to repository root.`)}catch(g){console.error(`
84
- \u274C [Lisa.ai Auto-Generator] Failed to author configuration file: ${g.message}`),process.exit(1)}}};var tt=j(require("dotenv"));tt.config({quiet:!0});function ie(t){let e=t.toLowerCase();return e.includes("karma")||e.includes("ng test")?"karma":e.includes("jest")?"jest":e.includes("vitest")?"vitest":e.includes("playwright")?"playwright":e.includes("cypress")?"cypress":e.includes("mocha")?"mocha":"unknown"}async function st(t,e,s){if(s==="local")return[];let n=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3000";try{let i=new URLSearchParams({projectId:s,errorLog:t.slice(0,1e3),framework:e}),o=await fetch(`${n}/api/memory/lookup?${i}`);return o.ok?await o.json():[]}catch{return[]}}async function nt(t,e,s,n){if(n==="local")return;let i=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3000";try{await fetch(`${i}/api/memory/record`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,errorLog:t.slice(0,1e3),fixHint:e.slice(0,2e3),framework:s})}),console.log("[Lisa.ai Memory] Fix pattern recorded to Control Plane.")}catch(o){console.debug(`[Lisa.ai Agent Debug] Failed to record memory pattern: ${o.message}`)}}var M=j(require("fs")),O=j(require("path")),Te=require("child_process");function ve(t){if(M.existsSync(O.join(t,"playwright.config.ts"))||M.existsSync(O.join(t,"playwright.config.js")))return{framework:"playwright",configFile:M.existsSync(O.join(t,"playwright.config.ts"))?"playwright.config.ts":"playwright.config.js",command:"npx playwright test",installed:!0};if(M.existsSync(O.join(t,"cypress.config.ts"))||M.existsSync(O.join(t,"cypress.config.js"))||M.existsSync(O.join(t,"cypress.json")))return{framework:"cypress",configFile:M.existsSync(O.join(t,"cypress.config.ts"))?"cypress.config.ts":M.existsSync(O.join(t,"cypress.config.js"))?"cypress.config.js":"cypress.json",command:"npx cypress run",installed:!0};let e=O.join(t,"package.json");if(M.existsSync(e)){let s=JSON.parse(M.readFileSync(e,"utf-8")),n={...s.dependencies||{},...s.devDependencies||{}};if(n["@playwright/test"])return{framework:"playwright",configFile:null,command:"npx playwright test",installed:!0};if(n.cypress)return{framework:"cypress",configFile:null,command:"npx cypress run",installed:!0}}return{framework:"playwright",configFile:null,command:"npx playwright test",installed:!1}}function xe(t){console.log("[Lisa.ai E2E] No E2E framework detected. Installing Playwright...");try{(0,Te.execSync)("npm install -D @playwright/test",{cwd:t,stdio:"pipe"}),console.log("[Lisa.ai E2E] Playwright installed.")}catch(s){throw console.error(`[Lisa.ai E2E] Failed to install Playwright: ${s.message}`),new Error("Could not install @playwright/test. Please install it manually.")}try{console.log("[Lisa.ai E2E] Installing Playwright browsers..."),(0,Te.execSync)("npx playwright install --with-deps chromium",{cwd:t,stdio:"pipe"}),console.log("[Lisa.ai E2E] Chromium browser installed.")}catch{console.warn("[Lisa.ai E2E Warning] Browser install failed. You may need to run 'npx playwright install' manually.")}M.existsSync(O.join(t,"playwright.config.ts"))||(M.writeFileSync(O.join(t,"playwright.config.ts"),`import { defineConfig } from '@playwright/test';
98
+ 4. Return ONLY the raw code string block.`;try{let d=await ie(r,s,n),p="";t.testingFramework==="jest"&&(p="jest.config.js"),t.testingFramework==="karma"&&(p="karma.conf.js"),t.testingFramework==="vitest"&&(p="vitest.config.ts");let u=Te.join(o,p);Le.writeFileSync(u,d,"utf-8"),console.log(`\u2705 [Lisa.ai Auto-Generator] Natively wrote ${p} to repository root.`)}catch(d){console.error(`
99
+ \u274C [Lisa.ai Auto-Generator] Failed to author configuration file: ${d.message}`),process.exit(1)}}};var ot=b(require("dotenv"));ot.config({quiet:!0});function le(e){let t=e.toLowerCase();return t.includes("karma")||t.includes("ng test")?"karma":t.includes("jest")?"jest":t.includes("vitest")?"vitest":t.includes("playwright")?"playwright":t.includes("cypress")?"cypress":t.includes("mocha")?"mocha":"unknown"}async function it(e,t,s){if(s==="local")return[];let n=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3088";try{let o=new URLSearchParams({projectId:s,errorLog:e.slice(0,1e3),framework:t}),i=await fetch(`${n}/api/v1/lisa/memory/lookup?${o}`);if(!i.ok)return[];let a=await i.json();return a.data??a}catch{return[]}}async function at(e,t,s,n){if(n==="local")return;let o=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3088";try{await fetch(`${o}/api/v1/lisa/memory/record`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,errorLog:e.slice(0,1e3),fixHint:t.slice(0,2e3),framework:s})}),console.log("[Lisa.ai Memory] Fix pattern recorded to Control Plane.")}catch(i){console.debug(`[Lisa.ai Agent Debug] Failed to record memory pattern: ${i.message}`)}}var N=b(require("fs")),O=b(require("path")),Re=require("child_process");function ke(e){if(N.existsSync(O.join(e,"playwright.config.ts"))||N.existsSync(O.join(e,"playwright.config.js")))return{framework:"playwright",configFile:N.existsSync(O.join(e,"playwright.config.ts"))?"playwright.config.ts":"playwright.config.js",command:"npx playwright test",installed:!0};if(N.existsSync(O.join(e,"cypress.config.ts"))||N.existsSync(O.join(e,"cypress.config.js"))||N.existsSync(O.join(e,"cypress.json")))return{framework:"cypress",configFile:N.existsSync(O.join(e,"cypress.config.ts"))?"cypress.config.ts":N.existsSync(O.join(e,"cypress.config.js"))?"cypress.config.js":"cypress.json",command:"npx cypress run",installed:!0};let t=O.join(e,"package.json");if(N.existsSync(t)){let s=JSON.parse(N.readFileSync(t,"utf-8")),n={...s.dependencies||{},...s.devDependencies||{}};if(n["@playwright/test"])return{framework:"playwright",configFile:null,command:"npx playwright test",installed:!0};if(n.cypress)return{framework:"cypress",configFile:null,command:"npx cypress run",installed:!0}}return{framework:"playwright",configFile:null,command:"npx playwright test",installed:!1}}function Ce(e){console.log("[Lisa.ai E2E] No E2E framework detected. Installing Playwright...");try{(0,Re.execSync)("npm install -D @playwright/test",{cwd:e,stdio:"pipe"}),console.log("[Lisa.ai E2E] Playwright installed.")}catch(s){throw console.error(`[Lisa.ai E2E] Failed to install Playwright: ${s.message}`),new Error("Could not install @playwright/test. Please install it manually.")}try{console.log("[Lisa.ai E2E] Installing Playwright browsers..."),(0,Re.execSync)("npx playwright install --with-deps chromium",{cwd:e,stdio:"pipe"}),console.log("[Lisa.ai E2E] Chromium browser installed.")}catch{console.warn("[Lisa.ai E2E Warning] Browser install failed. You may need to run 'npx playwright install' manually.")}N.existsSync(O.join(e,"playwright.config.ts"))||(N.writeFileSync(O.join(e,"playwright.config.ts"),`import { defineConfig } from '@playwright/test';
85
100
 
86
101
  export default defineConfig({
87
102
  testDir: './e2e',
@@ -98,87 +113,87 @@ export default defineConfig({
98
113
  { name: 'chromium', use: { browserName: 'chromium' } },
99
114
  ],
100
115
  });
101
- `,"utf-8"),console.log("[Lisa.ai E2E] Generated playwright.config.ts"));let e=O.join(t,"e2e");M.existsSync(e)||(M.mkdirSync(e,{recursive:!0}),console.log("[Lisa.ai E2E] Created e2e/ directory"))}var re=0,$e=0,Ie=new Set;function Re(t){let s=[...fe(t).matchAll(/Executed\s+(\d+)\s+of\s+(\d+)(?:\s+\((\d+)\s+FAILED\))?/g)];if(s.length===0)return null;let n=[...s].reverse().find(u=>u[3]!==void 0)??s[s.length-1],i=parseInt(n[2]),o=n[3]?parseInt(n[3]):0,r=parseInt(n[1])-o,a=i>0?Math.round(r/i*100):0;return` [${"\u2588".repeat(Math.round(a/5))+"\u2591".repeat(20-Math.round(a/5))}] ${a}% ${r} passed ${o} failed ${i} total`}function it(t,e=10){let s=[];for(let n of fe(t).split(`
102
- `)){let i=n.trim();if(/^FAILED/.test(i)||/ FAILED$/.test(i)){let r=i.replace(/^(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:[\s.]\d+)*\s+\([^)]+\)\s+/,"").replace(/\s+FAILED$/,"").trim();if(s.push(r||i),s.length>=e)break}}return s}function Tt(t){let e=t.replace(/\.(spec|test)\.(ts|js|jsx|tsx)$/,".$2");if(e!==t&&_.existsSync(e))try{return console.log(` [Lisa.ai] \u{1F9E0} Sibling source found: ${V.basename(e)}`),_.readFileSync(e,"utf-8")}catch{return}}function It(t,e){let s=t.toLowerCase(),n=V.parse(e);if(s.includes("ng test")||s.includes("karma"))return`${t} --include **/${n.base}`;if(s.includes("jest")||s.includes("vitest")||s.includes("playwright"))return`${t} ${e}`;if(s.includes("cypress"))return`${t} --spec ${e}`;if(s.includes("npm")||s.includes("yarn")||s.includes("pnpm")){try{let o=JSON.parse(_.readFileSync(V.resolve(process.cwd(),"package.json"),"utf8")),r="test";s.includes("npm run ")?r=s.split("npm run ")[1].split(" ")[0]:s.includes("yarn ")?r=s.split("yarn ")[1].split(" ")[0]:s.includes("pnpm ")&&(r=s.split("pnpm ")[1].split(" ")[0]);let a=o.scripts?.[r]?.toLowerCase()||"",g=s.includes("npm")?" --":"";if(a.includes("ng test")||a.includes("karma"))return`${t}${g} --include **/${n.base}`;if(a.includes("jest")||a.includes("vitest")||a.includes("playwright"))return`${t}${g} ${e}`}catch{}let i=s.includes("npm")?" --":"";return`${t}${i} ${e}`}return t}function Me(t,e=!1){return new Promise((s,n)=>{let i=(0,ot.spawn)(t,{shell:!0,stdio:["ignore","pipe","pipe"]}),o="",r="";i.stdout?.on("data",a=>{let g=a.toString();if(o+=g,e)for(let u of g.split(`
103
- `)){let p=u.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"").trim();p&&(/Executed\s+\d+\s+of\s+\d+/.test(p)?process.stdout.write(`\r ${p.padEnd(72)}`):/^\s*FAILED\b/.test(p)&&(process.stdout.write(`
104
- `),console.log(` \u2717 ${p.trim()}`)))}}),i.stderr?.on("data",a=>{r+=a.toString()}),i.on("close",a=>{a===0?s({stdout:o,stderr:r}):n({message:`Process exited with code ${a}`,stdout:o,stderr:r})})})}function Rt(t,e,s){if(!e.match(/\.(spec|test)\.(ts|js|tsx|jsx|vue)$/))return;if((s||"").toLowerCase().includes("ng test")||(s||"").toLowerCase().includes("karma"))try{_.writeFileSync(t,`// Quarantined by Lisa.ai \u2014 could not be automatically healed
116
+ `,"utf-8"),console.log("[Lisa.ai E2E] Generated playwright.config.ts"));let t=O.join(e,"e2e");N.existsSync(t)||(N.mkdirSync(t,{recursive:!0}),console.log("[Lisa.ai E2E] Created e2e/ directory"))}var se=0,pe=0,ge=new Set;function Me(e){let s=[...we(e).matchAll(/Executed\s+(\d+)\s+of\s+(\d+)(?:\s+\((\d+)\s+FAILED\))?/g)];if(s.length===0)return null;let n=[...s].reverse().find(p=>p[3]!==void 0)??s[s.length-1],o=parseInt(n[2]),i=n[3]?parseInt(n[3]):0,a=parseInt(n[1])-i,r=o>0?Math.round(a/o*100):0;return` [${"\u2588".repeat(Math.round(r/5))+"\u2591".repeat(20-Math.round(r/5))}] ${r}% ${a} passed ${i} failed ${o} total`}function lt(e,t=10){let s=[];for(let n of we(e).split(`
117
+ `)){let o=n.trim();if(/^FAILED/.test(o)||/ FAILED$/.test(o)){let a=o.replace(/^(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:[\s.]\d+)*\s+\([^)]+\)\s+/,"").replace(/\s+FAILED$/,"").trim();if(s.push(a||o),s.length>=t)break}}return s}function Mt(e){let t=e.replace(/\.(spec|test)\.(ts|js|jsx|tsx)$/,".$2");if(t!==e&&H.existsSync(t))try{return console.log(` [Lisa.ai] \u{1F9E0} Sibling source found: ${z.basename(t)}`),H.readFileSync(t,"utf-8")}catch{return}}function Nt(e,t){let s=e.toLowerCase(),n=z.parse(t);if(s.includes("ng test")||s.includes("karma"))return`${e} --include **/${n.base}`;if(s.includes("jest")||s.includes("vitest")||s.includes("playwright"))return`${e} ${t}`;if(s.includes("cypress"))return`${e} --spec ${t}`;if(s.includes("npm")||s.includes("yarn")||s.includes("pnpm")){try{let i=JSON.parse(H.readFileSync(z.resolve(process.cwd(),"package.json"),"utf8")),a="test";s.includes("npm run ")?a=s.split("npm run ")[1].split(" ")[0]:s.includes("yarn ")?a=s.split("yarn ")[1].split(" ")[0]:s.includes("pnpm ")&&(a=s.split("pnpm ")[1].split(" ")[0]);let r=i.scripts?.[a]?.toLowerCase()||"",d=s.includes("npm")?" --":"";if(r.includes("ng test")||r.includes("karma"))return`${e}${d} --include **/${n.base}`;if(r.includes("jest")||r.includes("vitest")||r.includes("playwright"))return`${e}${d} ${t}`}catch{}let o=s.includes("npm")?" --":"";return`${e}${o} ${t}`}return e}function Ne(e,t=!1){return new Promise((s,n)=>{let o=(0,rt.spawn)(e,{shell:!0,stdio:["ignore","pipe","pipe"]}),i="",a="";o.stdout?.on("data",r=>{let d=r.toString();if(i+=d,t)for(let p of d.split(`
118
+ `)){let u=p.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"").trim();u&&(/Executed\s+\d+\s+of\s+\d+/.test(u)?process.stdout.write(`\r ${u.padEnd(72)}`):/^\s*FAILED\b/.test(u)&&(process.stdout.write(`
119
+ `),console.log(` \u2717 ${u.trim()}`)))}}),o.stderr?.on("data",r=>{a+=r.toString()}),o.on("close",r=>{r===0?s({stdout:i,stderr:a}):n({message:`Process exited with code ${r}`,stdout:i,stderr:a})})})}function Dt(e,t,s){if(!t.match(/\.(spec|test)\.(ts|js|tsx|jsx|vue)$/))return;if((s||"").toLowerCase().includes("ng test")||(s||"").toLowerCase().includes("karma"))try{H.writeFileSync(e,`// Quarantined by Lisa.ai \u2014 could not be automatically healed
105
120
  describe('', () => {});
106
- `,"utf-8"),console.log(" \u{1F6A8} Replaced with empty stub (Angular requires valid TS).")}catch{}else try{_.renameSync(t,t+".broken"),console.log(` \u{1F6A8} Renamed to ${V.basename(t)}.broken to skip in test runner.`)}catch{}}async function Mt(t,e,s,n,i,o,r,a,g,u){let p=1,w=!1,h=s,m,y="",l="",d=Tt(e),k=(await st(s,o,g)).filter(f=>f.confidence>=.5).map(f=>f.fixHint);for(k.length>0&&console.log(` [Memory] ${k.length} proven pattern(s) found \u2014 injecting as LLM hint.`);p<=a&&!w;){console.log(` [Attempt ${p}/${a}] Requesting fix from ${r}...`);let f=_.readFileSync(e,"utf-8"),c;for(let x=0;x<=3;x++)try{c=await Ke(t,f,h,r,u,m,d,k);break}catch(L){let $=(L?.lastError??L)?.statusCode;if(($===529||$===500)&&x<3){let E=30*(x+1);console.warn(` \u26A0\uFE0F LLM overloaded (HTTP ${$}). Waiting ${E}s...`),await new Promise(A=>setTimeout(A,E*1e3))}else{console.error(` \u{1F6A8} LLM API failed: ${L?.message??String(L)}`);break}}if(c===void 0)break;_.writeFileSync(e,c,"utf-8"),y=`### Auto-Heal Analysis
121
+ `,"utf-8"),console.log(" \u{1F6A8} Replaced with empty stub (Angular requires valid TS).")}catch{}else try{H.renameSync(e,e+".broken"),console.log(` \u{1F6A8} Renamed to ${z.basename(e)}.broken to skip in test runner.`)}catch{}}async function Ut(e,t,s,n,o,i,a,r,d,p){let u=1,y=!1,h=s,f,w="",l="",c=Mt(t),k=(await it(s,i,d)).filter($=>$.confidence>=.5).map($=>$.fixHint);for(k.length>0&&console.log(` [Memory] ${k.length} proven pattern(s) found \u2014 injecting as LLM hint.`);u<=r&&!y;){console.log(` [Attempt ${u}/${r}] Requesting fix from ${a}...`);let $=H.readFileSync(t,"utf-8"),g;for(let m=0;m<=3;m++)try{g=await ze(e,$,h,a,p,f,c,k);break}catch(v){let L=(v?.lastError??v)?.statusCode;if((L===529||L===500)&&m<3){let C=30*(m+1);console.warn(` \u26A0\uFE0F LLM overloaded (HTTP ${L}). Waiting ${C}s...`),await new Promise(F=>setTimeout(F,C*1e3))}else{console.error(` \u{1F6A8} LLM API failed: ${v?.message??String(v)}`);break}}if(g===void 0)break;H.writeFileSync(t,g,"utf-8"),w=`### Auto-Heal Analysis
107
122
  **Error:**
108
123
  \`\`\`bash
109
124
  ${h.slice(0,2e3)}
110
125
  \`\`\`
111
126
 
112
- **Fix (${r}):**
127
+ **Fix (${a}):**
113
128
  \`\`\`typescript
114
- ${c}
115
- \`\`\``;try{await Me(i,!1),console.log(" \u2705 Isolated verification passed."),w=!0,l=c}catch(x){let L=x.stdout?x.stdout.toString():"";h=(x.stderr?x.stderr.toString():"")+`
116
- `+L+`
117
- `+(x.message||""),console.log(" \u274C Isolated verification failed.");let E=Re(h);if(E&&console.log(E),it(h,3).forEach(A=>console.log(` \u2717 ${A}`)),(n||"").toLowerCase().includes("ng test")||(n||"").toLowerCase().includes("karma")){let A=h.includes(V.basename(t)+":"),z=/ FAILED/.test(h);if(!A&&!z){console.log(" \u2705 Fix verified (build error is from other spec files, not this one)."),w=!0,l=c;continue}}m=`### Attempt ${p} Failed
129
+ ${g}
130
+ \`\`\``;try{await Ne(o,!1),console.log(" \u2705 Isolated verification passed."),y=!0,l=g}catch(m){let v=m.stdout?m.stdout.toString():"";h=(m.stderr?m.stderr.toString():"")+`
131
+ `+v+`
132
+ `+(m.message||""),console.log(" \u274C Isolated verification failed.");let C=Me(h);if(C&&console.log(C),lt(h,3).forEach(F=>console.log(` \u2717 ${F}`)),(n||"").toLowerCase().includes("ng test")||(n||"").toLowerCase().includes("karma")){let F=h.includes(z.basename(e)+":"),G=/ FAILED/.test(h);if(!F&&!G){console.log(" \u2705 Fix verified (build error is from other spec files, not this one)."),y=!0,l=g;continue}}f=`### Attempt ${u} Failed
118
133
  \`\`\`typescript
119
- ${c}
134
+ ${g}
120
135
  \`\`\`
121
136
 
122
137
  **New Error:**
123
- ${h}`,p++}}return{status:w?"healed":"quarantined",details:y,lastCode:l}}async function Le(t,e,s=1,n=null,i=3,o="local",r,a,g="unit",u){let p=g==="unit"?"":` (${g})`,w=R.load(process.cwd());if(w&&R.applyEnvDefaults(w),g==="e2e"){if(!t&&w?.e2eCommand&&(t=w.e2eCommand,console.log(`[Lisa.ai Config] Using e2eCommand from .lisai.json: ${t}`)),!t){console.log(`
124
- [Lisa.ai Heal${p}] Auto-detecting E2E framework...`);let f=ve(process.cwd());!f.installed&&f.framework==="playwright"&&xe(process.cwd()),t=f.command,console.log(`[Lisa.ai Heal${p}] E2E command: ${t}`)}}else if(!t&&w?.testCommand&&(t=w.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${t}`)),!t){console.log(`
125
- [Lisa.ai Auto-Discovery] No --command provided. Scanning framework...`);let f=Y.scanRepository();f.testingFramework==="none"&&(f=await ne.installMissingFramework(f),await oe.provisionConfigurationFiles(f,e,a)),f.suggestedTestCommand?(t=f.suggestedTestCommand,console.log(`[Lisa.ai Auto-Discovery] Discovered command: ${t}`)):(console.error(`
126
- \u{1F6A8} [Lisa.ai] Could not discover a test command. Pass --command explicitly.`),process.exit(1))}let h=ie(t),m=[],y="",l=null,d;if(u&&u.length>0)d=u,console.log(`
127
- [Lisa.ai Heal${p}] Targeting ${u.length} file(s) from --files`),d.forEach(f=>console.log(` - ${f}`));else{console.log(`
128
- [Lisa.ai Heal${p}] Running test suite (discovery pass)...`),console.log(`[Lisa.ai Executing] ${t} Model: ${e}`);try{await Me(t,!0),process.stdout.write(`
138
+ ${h}`,u++}}return{status:y?"healed":"quarantined",details:w,lastCode:l}}async function Se(e,t,s=1,n=3,o="local",i,a,r="unit",d,p=!1){se=0,pe=0,ge.clear();let u=r==="unit"?"":` (${r})`,y=R.load(process.cwd());if(y&&R.applyEnvDefaults(y),r==="e2e"){if(!e&&y?.e2eCommand&&(e=y.e2eCommand,console.log(`[Lisa.ai Config] Using e2eCommand from .lisai.json: ${e}`)),!e){console.log(`
139
+ [Lisa.ai Heal${u}] Auto-detecting E2E framework...`);let m=ke(process.cwd());!m.installed&&m.framework==="playwright"&&Ce(process.cwd()),e=m.command,console.log(`[Lisa.ai Heal${u}] E2E command: ${e}`)}}else if(!e&&y?.testCommand&&(e=y.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${e}`)),!e){console.log(`
140
+ [Lisa.ai Auto-Discovery] No --command provided. Scanning framework...`);let m=V.scanRepository();m.testingFramework==="none"&&(m=await ae.installMissingFramework(m),await re.provisionConfigurationFiles(m,t,a)),m.suggestedTestCommand?(e=m.suggestedTestCommand,console.log(`[Lisa.ai Auto-Discovery] Discovered command: ${e}`)):(console.error(`
141
+ \u{1F6A8} [Lisa.ai] Could not discover a test command. Pass --command explicitly.`),process.exit(1))}let h=le(e),f=[],w="",l=null,c;if(d&&d.length>0)c=d,console.log(`
142
+ [Lisa.ai Heal${u}] Targeting ${d.length} file(s) from --files`),c.forEach(m=>console.log(` - ${m}`));else{console.log(`
143
+ [Lisa.ai Heal${u}] Running test suite (discovery pass)...`),console.log(`[Lisa.ai Executing] ${e} Model: ${t}`);try{await Ne(e,!0),process.stdout.write(`
129
144
  `),console.log(`
130
- \u2705 [Lisa.ai] All tests passing. Nothing to heal!`),n&&await Fe(n);return}catch(c){process.stdout.write(`
131
- `),y=(c.stderr||"")+`
132
- `+(c.stdout||"")+`
133
- `+(c.message||"")}l=Z(y);let f=Re(y);if(f){console.log(`
134
- ${f}`);let c=it(y,10);if(c.length>0){let x=l?.failed??c.length;console.log(` Failing (${x}):`),c.forEach(L=>console.log(` \u2717 ${L}`)),x>c.length&&console.log(` ... and ${x-c.length} more`)}}if(d=Ce(y,process.cwd(),m),d.length===0){let c=me(y,m,process.cwd());c||(console.error(`
135
- \u{1F6A8} [Lisa.ai] Could not identify any failing spec files. Output format may be unsupported.`),process.exit(1)),d=[c]}}let v=d.length;console.log(`
136
- [Lisa.ai] Found ${v} failing spec(s). Healing each in isolation...`),console.log(`${"\u2500".repeat(60)}`);for(let f of d)I({projectId:o,type:"heal",filePath:f,modelUsed:e,status:"running",details:"Queued for isolated healing.",...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:h});for(let f=0;f<d.length;f++){let c=d[f],x=V.resolve(process.cwd(),c);if(console.log(`
137
- [${f+1}/${v}] ${c}`),!_.existsSync(x)){console.warn(" \u26A0\uFE0F File not found \u2014 skipping.");continue}if(/[\\/](node_modules|dist|build)[\\/]/.test(x)){console.warn(" \u26A0\uFE0F Library file \u2014 refusing to modify.");continue}let L=It(t,c),$=await Mt(c,x,y,t,L,h,e,i,o,a);$.status==="healed"?(re++,Ie.add(c),console.log(` \u2705 Healed [${re} healed ${$e} quarantined so far]`),I({projectId:o,type:"heal",filePath:c,modelUsed:e,status:"success",details:$.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:h}),await nt(y,$.lastCode,h,o)):($e++,m.push(c),console.warn(` \u{1F6A8} Quarantined [${re} healed ${$e} quarantined so far]`),I({projectId:o,type:"heal",filePath:c,modelUsed:e,status:"error",details:`Exhausted all ${i} attempts.
138
- `+$.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:h}),Rt(x,c,t))}if(console.log(`
139
- ${"\u2500".repeat(60)}`),re>0){console.log("[Lisa.ai] Final verification run...");try{await Me(t,!0),process.stdout.write(`
145
+ \u2705 [Lisa.ai] All tests passing. Nothing to heal!`);let v={healedFiles:[],quarantinedFiles:[],testCounts:null,allPassing:!0};return p&&Ie({healedFiles:[],quarantinedFiles:[],testCounts:null,modelProvider:t,framework:"unknown",scope:r},null),v}catch(v){process.stdout.write(`
146
+ `),w=(v.stderr||"")+`
147
+ `+(v.stdout||"")+`
148
+ `+(v.message||"")}l=Z(w);let m=Me(w);if(m){console.log(`
149
+ ${m}`);let v=lt(w,10);if(v.length>0){let L=l?.failed??v.length;console.log(` Failing (${L}):`),v.forEach(C=>console.log(` \u2717 ${C}`)),L>v.length&&console.log(` ... and ${L-v.length} more`)}}if(c=Fe(w,process.cwd(),f),c.length===0){let v=ve(w,f,process.cwd());v||(console.error(`
150
+ \u{1F6A8} [Lisa.ai] Could not identify any failing spec files. Output format may be unsupported.`),process.exit(1)),c=[v]}}let x=c.length;console.log(`
151
+ [Lisa.ai] Found ${x} failing spec(s). Healing each in isolation...`),console.log(`${"\u2500".repeat(60)}`);for(let m of c)T({projectId:o,type:"heal",filePath:m,modelUsed:t,status:"running",details:"Queued for isolated healing.",...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:h});for(let m=0;m<c.length;m++){let v=c[m],L=z.resolve(process.cwd(),v);if(console.log(`
152
+ [${m+1}/${x}] ${v}`),!H.existsSync(L)){console.warn(" \u26A0\uFE0F File not found \u2014 skipping.");continue}if(/[\\/](node_modules|dist|build)[\\/]/.test(L)){console.warn(" \u26A0\uFE0F Library file \u2014 refusing to modify.");continue}let C=Nt(e,v),F=await Ut(v,L,w,e,C,h,t,n,o,a);F.status==="healed"?(se++,ge.add(v),console.log(` \u2705 Healed [${se} healed ${pe} quarantined so far]`),T({projectId:o,type:"heal",filePath:v,modelUsed:t,status:"success",details:F.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:h}),await at(w,F.lastCode,h,o)):(pe++,f.push(v),console.warn(` \u{1F6A8} Quarantined [${se} healed ${pe} quarantined so far]`),T({projectId:o,type:"heal",filePath:v,modelUsed:t,status:"error",details:`Exhausted all ${n} attempts.
153
+ `+F.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:h}),Dt(L,v,e))}console.log(`
154
+ ${"\u2500".repeat(60)}`);let k=!1;if(se>0){console.log("[Lisa.ai] Final verification run...");try{await Ne(e,!0),process.stdout.write(`
140
155
  `),console.log(`
141
- \u2705 All tests passing!`)}catch(f){process.stdout.write(`
142
- `);let c=(f.stderr||"")+`
143
- `+(f.stdout||"")+`
144
- `+(f.message||""),x=Re(c);x&&console.log(`
145
- ${x}`);let L=Ce(c,process.cwd(),[]),$=L.filter(A=>Ie.has(A)),E=L.filter(A=>!Ie.has(A)&&!m.includes(A));$.length>0&&(console.warn(`
146
- \u26A0\uFE0F ${$.length} spec(s) passed isolated verification but still fail globally:`),$.forEach(A=>console.warn(` \u2717 ${A}`)),console.warn(" These likely have cross-test shared state. Try higher maxRetries or fix manually.")),E.length>0&&(console.warn(`
147
- \u2139\uFE0F ${E.length} additional failing spec(s) not in this run's queue:`),E.forEach(A=>console.warn(` \u2717 ${A}`)),console.warn(" Run lisa-agent heal again to address these."))}}let k=(l?.passed??0)+re;console.log(`
148
- \u2705 Healed: ${re} / ${v}`),console.log(` \u{1F6A8} Quarantined: ${$e}`),l&&console.log(` \u{1F4CA} Suite: ${l.passed} passing \u2192 ~${k} passing (est.)`),console.log(`${"\u2500".repeat(60)}
149
- `),n&&await Fe(n)}var ct=require("child_process"),W=j(require("fs")),D=j(require("path"));var ke=j(require("fs")),rt=j(require("path"));function at(t){let e=rt.resolve(process.cwd(),t);if(!ke.existsSync(e))throw new Error(`[Lisa.ai Coverage Error] Coverage file not found at ${e}`);let s=ke.readFileSync(e,"utf-8"),n=JSON.parse(s),i=[];for(let[o,r]of Object.entries(n))o!=="total"&&(r.lines.pct<100||r.statements.pct<100||r.functions.pct<100||r.branches.pct<100)&&i.push(o);return i}var lt=new Set,Se=0,De=3;function Dt(t){let e=t.testingFramework,s=process.cwd();return W.existsSync(D.join(s,"angular.json"))?"npx ng test --no-watch --code-coverage --browsers=ChromeHeadless":e==="jest"?"npx jest --coverage --coverageReporters=json-summary":e==="vitest"?"npx vitest run --coverage":[".mocharc.yml",".mocharc.yaml",".mocharc.json",".mocharc.js"].some(i=>W.existsSync(D.join(s,i)))?"npx nyc --reporter=json-summary mocha":null}async function pe(t,e,s=1,n=3,i="local",o,r){if(s>n){console.log(`
150
- [Lisa.ai Unit] Reached maximum retries (${n}). Stopping.`);return}let a=R.load(process.cwd());a&&(R.applyEnvDefaults(a),!t&&a.testCommand&&(t=a.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${t}`)));let g=Y.scanRepository(),u=a?.testingFramework||(g.testingFramework!=="none"?g.testingFramework:void 0),p=a?.testTypes;if(!t){console.log(`
151
- [Lisa.ai Auto-Discovery] No explicit --command provided. Auto-detecting coverage command...`);let m=Dt(g);if(m)t=m,console.log(`[Lisa.ai Auto-Discovery] Detected coverage command: ${t}`);else{let y=g;if(y.testingFramework==="none"&&(y=await ne.installMissingFramework(y),await oe.provisionConfigurationFiles(y,e,o)),y.suggestedTestCommand){t=y.suggestedTestCommand;let l=y.testingFramework;(l==="jest"||l==="vitest")&&!t.includes("--coverage")&&(t=t.includes("npm run")?`${t} -- --coverage`:`${t} --coverage`,console.log(`[Lisa.ai Unit] Coverage flag appended: ${t}`)),console.log(`[Lisa.ai Auto-Discovery] Bootstrapping with discovered command: ${t}`)}else console.error(`
152
- [Lisa.ai Fatal Error] Could not auto-detect a test framework. Please pass --command explicitly or add a .lisai.json config.`),process.exit(1)}}console.log(`
153
- [Lisa.ai Unit] ${t} (Attempt ${s}/${n}) Using Model: ${e}`);let w=ie(t);await I({projectId:i,type:"unit",filePath:"global-test-suite",modelUsed:e,status:"running",details:"Agent is executing unit test suite and validating coverage...",testFramework:w});let h=(m,y=!1)=>new Promise((l,d)=>{let v=(0,ct.spawn)(m,{shell:!0,stdio:["ignore","pipe","pipe"]}),k="",f="";v.stdout?.on("data",c=>{let x=c.toString();if(k+=x,y){let L=x.split(`
154
- `);for(let $ of L){let E=$.match(/Executed\s+(\d+)\s+of\s+(\d+)/);if(E){let A=$.match(/(\d+)\s+FAILED/),z=A?A[1]:0,H=`\r[Lisa.ai Testing] Executed ${E[1]} of ${E[2]} (${z} FAILED) `;process.stdout.write(H)}}}}),v.stderr?.on("data",c=>{f+=c.toString()}),v.on("close",c=>{c===0?l({stdout:k,stderr:f}):d({message:`Test process exited with code ${c}`,stdout:k,stderr:f})})});try{console.log("[Lisa.ai Unit] Running tests with coverage. This may take a moment...");let m=await h(t,!0),y=m.stdout+`
155
- `+m.stderr,l=Z(y);l&&await I({projectId:i,type:"unit",filePath:"global-test-suite",modelUsed:e,status:"success",details:`Tests passed on attempt ${s}.`,testTotal:l.total,testPassed:l.passed,testFailed:l.failed,testFramework:w}),console.log(`
156
- [Lisa.ai Unit] Tests passed on attempt ${s}.`)}catch(m){let y=(m.stderr||"")+`
156
+ \u2705 All tests passing!`),k=!0}catch(m){process.stdout.write(`
157
+ `);let v=(m.stderr||"")+`
157
158
  `+(m.stdout||"")+`
158
- `+(m.message||"");if(me(y,[],process.cwd())!==null){console.log(`
159
- [Lisa.ai Unit] Tests failed. Delegating to Auto-Heal...`),await Le(t,e,1,null,n,i,void 0,o),console.log(`
160
- [Lisa.ai Unit] Auto-Heal complete. Restarting unit analysis...`),await pe(t,e,s+1,n,i,o,r);return}console.log(`
161
- [Lisa.ai Unit] No failing spec detected. Tests may not exist yet \u2014 initiating Cold-Start Discovery...`)}try{let m=[];if(r&&r.length>0)m=r,console.log(`
162
- [Lisa.ai Unit] Targeting ${r.length} file(s) from --files`),m.forEach($=>console.log(` - ${$}`));else{let $=D.resolve(process.cwd(),"coverage/coverage-summary.json");if(W.existsSync($))console.log("[Lisa.ai Unit] Evaluating coverage summary..."),m=at("coverage/coverage-summary.json");else{if(console.log(`
163
- [Lisa.ai Unit] No coverage-summary.json found. Initiating Cold-Start Discovery...`),m=Y.findUntestedFiles(process.cwd(),[...lt]),m.length===0){console.log("[Lisa.ai Unit] No untested source files discovered.");return}console.log(`[Lisa.ai Unit] Discovered ${m.length} untested file(s). Generating specs...`)}if(m.length===0){console.log("[Lisa.ai Unit] 100% coverage achieved. No uncovered files remaining.");return}}console.log(`[Lisa.ai Unit] Found ${m.length} file(s) below threshold:`,m);let y=m[0],l=D.resolve(process.cwd(),y),d=D.parse(l),v=[D.join(d.dir,`${d.name}.spec${d.ext}`),D.join(d.dir,`${d.name}.test${d.ext}`),D.join(d.dir,`${d.name}.spec.js`),D.join(d.dir,`${d.name}.test.js`),D.join(d.dir,`${d.name}.spec.ts`),D.join(d.dir,`${d.name}.test.ts`)],k=null,f=D.join(d.dir,`${d.name}.spec${d.ext}`);for(let $ of v)if(W.existsSync($)){f=$,k=W.readFileSync($,"utf-8");break}let c="",x=!1,L=W.readFileSync(l,"utf-8");try{k?(console.log(`[Lisa.ai Unit] Existing spec found for ${y}. Requesting coverage append...`),c=await ze(y,L,D.relative(process.cwd(),f),k,e,o,u,p)):(console.log(`[Lisa.ai Unit] Generating new spec for ${y}...`),c=await X(y,L,e,o,u,p)),Se=0,x=!0}catch($){Se++,lt.add(y);let E=$.cause?.message?`${$.message} (cause: ${$.cause.message})`:$.message;if(console.error(`
164
- [Lisa.ai Unit] LLM call failed for ${y} \u2014 consecutive failure #${Se}/${De}`),console.error(` Error: ${E}`),Se>=De)throw new Error(`Systematic LLM failure: ${De} consecutive API calls failed.
159
+ `+(m.message||""),L=Me(v);L&&console.log(`
160
+ ${L}`);let C=Fe(v,process.cwd(),[]),F=C.filter(M=>ge.has(M)),G=C.filter(M=>!ge.has(M)&&!f.includes(M));F.length>0&&(console.warn(`
161
+ \u26A0\uFE0F ${F.length} spec(s) passed isolated verification but still fail globally:`),F.forEach(M=>console.warn(` \u2717 ${M}`)),console.warn(" These likely have cross-test shared state. Try higher maxRetries or fix manually.")),G.length>0&&(console.warn(`
162
+ \u2139\uFE0F ${G.length} additional failing spec(s) not in this run's queue:`),G.forEach(M=>console.warn(` \u2717 ${M}`)),console.warn(" Run lisa-agent heal again to address these."))}}let $=(l?.passed??0)+se;console.log(`
163
+ \u2705 Healed: ${se} / ${x}`),console.log(` \u{1F6A8} Quarantined: ${pe}`),l&&console.log(` \u{1F4CA} Suite: ${l.passed} passing \u2192 ~${$} passing (est.)`),console.log(`${"\u2500".repeat(60)}
164
+ `);let g={healedFiles:[...ge],quarantinedFiles:[...f],testCounts:l,allPassing:k};if(p){let m={healedFiles:g.healedFiles,quarantinedFiles:g.quarantinedFiles,testCounts:g.testCounts,modelProvider:t,framework:h,scope:r},v=await et(m);Ie(m,v),g.allPassing||(process.exitCode=1)}return g}var pt=require("child_process"),W=b(require("fs")),D=b(require("path"));var be=b(require("fs")),ct=b(require("path"));function ut(e){let t=ct.resolve(process.cwd(),e);if(!be.existsSync(t))throw new Error(`[Lisa.ai Coverage Error] Coverage file not found at ${t}`);let s=be.readFileSync(t,"utf-8"),n=JSON.parse(s),o=[];for(let[i,a]of Object.entries(n))i!=="total"&&(a.lines.pct<100||a.statements.pct<100||a.functions.pct<100||a.branches.pct<100)&&o.push(i);return o}var dt=new Set,Ee=0,De=3;function _t(e){let t=e.testingFramework,s=process.cwd();return W.existsSync(D.join(s,"angular.json"))?"npx ng test --no-watch --code-coverage --browsers=ChromeHeadless":t==="jest"?"npx jest --coverage --coverageReporters=json-summary":t==="vitest"?"npx vitest run --coverage":[".mocharc.yml",".mocharc.yaml",".mocharc.json",".mocharc.js"].some(o=>W.existsSync(D.join(s,o)))?"npx nyc --reporter=json-summary mocha":null}async function fe(e,t,s=1,n=3,o="local",i,a){if(s>n){console.log(`
165
+ [Lisa.ai Unit] Reached maximum retries (${n}). Stopping.`);return}let r=R.load(process.cwd());r&&(R.applyEnvDefaults(r),!e&&r.testCommand&&(e=r.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${e}`)));let d=V.scanRepository(),p=r?.testingFramework||(d.testingFramework!=="none"?d.testingFramework:void 0),u=r?.testTypes;if(!e){console.log(`
166
+ [Lisa.ai Auto-Discovery] No explicit --command provided. Auto-detecting coverage command...`);let f=_t(d);if(f)e=f,console.log(`[Lisa.ai Auto-Discovery] Detected coverage command: ${e}`);else{let w=d;if(w.testingFramework==="none"&&(w=await ae.installMissingFramework(w),await re.provisionConfigurationFiles(w,t,i)),w.suggestedTestCommand){e=w.suggestedTestCommand;let l=w.testingFramework;(l==="jest"||l==="vitest")&&!e.includes("--coverage")&&(e=e.includes("npm run")?`${e} -- --coverage`:`${e} --coverage`,console.log(`[Lisa.ai Unit] Coverage flag appended: ${e}`)),console.log(`[Lisa.ai Auto-Discovery] Bootstrapping with discovered command: ${e}`)}else console.error(`
167
+ [Lisa.ai Fatal Error] Could not auto-detect a test framework. Please pass --command explicitly or add a .lisai.json config.`),process.exit(1)}}console.log(`
168
+ [Lisa.ai Unit] ${e} (Attempt ${s}/${n}) Using Model: ${t}`);let y=le(e);await T({projectId:o,type:"unit",filePath:"global-test-suite",modelUsed:t,status:"running",details:"Agent is executing unit test suite and validating coverage...",testFramework:y});let h=(f,w=!1)=>new Promise((l,c)=>{let x=(0,pt.spawn)(f,{shell:!0,stdio:["ignore","pipe","pipe"]}),k="",$="";x.stdout?.on("data",g=>{let m=g.toString();if(k+=m,w){let v=m.split(`
169
+ `);for(let L of v){let C=L.match(/Executed\s+(\d+)\s+of\s+(\d+)/);if(C){let F=L.match(/(\d+)\s+FAILED/),G=F?F[1]:0,M=`\r[Lisa.ai Testing] Executed ${C[1]} of ${C[2]} (${G} FAILED) `;process.stdout.write(M)}}}}),x.stderr?.on("data",g=>{$+=g.toString()}),x.on("close",g=>{g===0?l({stdout:k,stderr:$}):c({message:`Test process exited with code ${g}`,stdout:k,stderr:$})})});try{console.log("[Lisa.ai Unit] Running tests with coverage. This may take a moment...");let f=await h(e,!0),w=f.stdout+`
170
+ `+f.stderr,l=Z(w);l&&await T({projectId:o,type:"unit",filePath:"global-test-suite",modelUsed:t,status:"success",details:`Tests passed on attempt ${s}.`,testTotal:l.total,testPassed:l.passed,testFailed:l.failed,testFramework:y}),console.log(`
171
+ [Lisa.ai Unit] Tests passed on attempt ${s}.`)}catch(f){let w=(f.stderr||"")+`
172
+ `+(f.stdout||"")+`
173
+ `+(f.message||"");if(ve(w,[],process.cwd())!==null){console.log(`
174
+ [Lisa.ai Unit] Tests failed. Delegating to Auto-Heal...`),await Se(e,t,1,n,o,void 0,i),console.log(`
175
+ [Lisa.ai Unit] Auto-Heal complete. Restarting unit analysis...`),await fe(e,t,s+1,n,o,i,a);return}console.log(`
176
+ [Lisa.ai Unit] No failing spec detected. Tests may not exist yet \u2014 initiating Cold-Start Discovery...`)}try{let f=[];if(a&&a.length>0)f=a,console.log(`
177
+ [Lisa.ai Unit] Targeting ${a.length} file(s) from --files`),f.forEach(L=>console.log(` - ${L}`));else{let L=D.resolve(process.cwd(),"coverage/coverage-summary.json");if(W.existsSync(L))console.log("[Lisa.ai Unit] Evaluating coverage summary..."),f=ut("coverage/coverage-summary.json");else{if(console.log(`
178
+ [Lisa.ai Unit] No coverage-summary.json found. Initiating Cold-Start Discovery...`),f=V.findUntestedFiles(process.cwd(),[...dt]),f.length===0){console.log("[Lisa.ai Unit] No untested source files discovered.");return}console.log(`[Lisa.ai Unit] Discovered ${f.length} untested file(s). Generating specs...`)}if(f.length===0){console.log("[Lisa.ai Unit] 100% coverage achieved. No uncovered files remaining.");return}}console.log(`[Lisa.ai Unit] Found ${f.length} file(s) below threshold:`,f);let w=f[0],l=D.resolve(process.cwd(),w),c=D.parse(l),x=[D.join(c.dir,`${c.name}.spec${c.ext}`),D.join(c.dir,`${c.name}.test${c.ext}`),D.join(c.dir,`${c.name}.spec.js`),D.join(c.dir,`${c.name}.test.js`),D.join(c.dir,`${c.name}.spec.ts`),D.join(c.dir,`${c.name}.test.ts`)],k=null,$=D.join(c.dir,`${c.name}.spec${c.ext}`);for(let L of x)if(W.existsSync(L)){$=L,k=W.readFileSync(L,"utf-8");break}let g="",m=!1,v=W.readFileSync(l,"utf-8");try{k?(console.log(`[Lisa.ai Unit] Existing spec found for ${w}. Requesting coverage append...`),g=await Ze(w,v,D.relative(process.cwd(),$),k,t,i,p,u)):(console.log(`[Lisa.ai Unit] Generating new spec for ${w}...`),g=await ee(w,v,t,i,p,u)),Ee=0,m=!0}catch(L){Ee++,dt.add(w);let C=L.cause?.message?`${L.message} (cause: ${L.cause.message})`:L.message;if(console.error(`
179
+ [Lisa.ai Unit] LLM call failed for ${w} \u2014 consecutive failure #${Ee}/${De}`),console.error(` Error: ${C}`),Ee>=De)throw new Error(`Systematic LLM failure: ${De} consecutive API calls failed.
165
180
  This usually means your API key has insufficient credits, hit a rate limit, or the model is unavailable.
166
- Last error: ${E}
167
- Tip: Check your API key, account credits, and rate-limit quota for provider '${e}'.`)}if(!x){await pe(t,e,s+1,n,i,o,r);return}W.writeFileSync(f,c,"utf-8"),console.log(`[Lisa.ai Unit] Wrote spec to ${f}`),await I({projectId:i,type:"unit",filePath:y,modelUsed:e,status:"success",details:`### Unit Test Generated
168
- **Auto-Generated Spec (${e}):**
181
+ Last error: ${C}
182
+ Tip: Check your API key, account credits, and rate-limit quota for provider '${t}'.`)}if(!m){await fe(e,t,s+1,n,o,i,a);return}W.writeFileSync($,g,"utf-8"),console.log(`[Lisa.ai Unit] Wrote spec to ${$}`),await T({projectId:o,type:"unit",filePath:w,modelUsed:t,status:"success",details:`### Unit Test Generated
183
+ **Auto-Generated Spec (${t}):**
169
184
  \`\`\`typescript
170
- ${c}
171
- \`\`\``,testFramework:w}),await pe(t,e,s+1,n,i,o,r)}catch(m){console.error("[Lisa.ai Unit loop failure]:",m.message),await I({projectId:i,type:"unit",filePath:"unit-loop",modelUsed:e,status:"error",details:`Unit test generation encountered an unrecoverable error: ${m.message}`,testFramework:w})}}var dt=require("child_process"),P=j(require("fs")),G=j(require("path"));function Nt(t){let e=[],s=["src/app/app.routes.ts","src/app/app-routing.module.ts"];for(let i of s){let o=G.join(t,i);if(P.existsSync(o)){let a=P.readFileSync(o,"utf-8").matchAll(/path:\s*['"`]([^'"`]+)['"`]/g);for(let g of a)g[1]&&g[1]!=="**"&&e.push(g[1])}}let n=["src/App.tsx","src/App.jsx","src/routes.tsx","src/routes.jsx"];for(let i of n){let o=G.join(t,i);if(P.existsSync(o)){let a=P.readFileSync(o,"utf-8").matchAll(/path=["']([^"']+)["']/g);for(let g of a)g[1]&&e.push(g[1])}}return[...new Set(e)].sort()}async function pt(t,e,s=1,n=3,i="local",o,r){if(s>n){console.log(`
172
- [Lisa.ai E2E] Reached maximum retries (${n}). Stopping.`);return}let a=process.cwd(),g=R.load(a);g&&(R.applyEnvDefaults(g),!t&&g.e2eCommand&&(t=g.e2eCommand,console.log(`[Lisa.ai Config] Using e2eCommand from .lisai.json: ${t}`)));let u=ve(a),p=g?.e2eFramework||u.framework;console.log(`
173
- [Lisa.ai E2E] Framework: ${p} (Attempt ${s}/${n}) Model: ${e}`),!u.installed&&p==="playwright"&&xe(a),t||(t=u.command,console.log(`[Lisa.ai E2E] Using auto-detected command: ${t}`)),await I({projectId:i,type:"e2e",filePath:"e2e-suite",modelUsed:e,status:"running",details:`E2E test generation started with ${p}`,testFramework:p});let w=0;if(r&&r.length>0){console.log(`
174
- [Lisa.ai E2E] Targeting ${r.length} file(s) from --files`),r.forEach(v=>console.log(` - ${v}`));for(let v of r){let k=G.resolve(a,v);if(P.existsSync(k)){console.log(`[Lisa.ai E2E] Spec already exists: ${v} \u2014 will run as-is.`);continue}let f=G.dirname(k);P.existsSync(f)||P.mkdirSync(f,{recursive:!0}),console.log(`[Lisa.ai E2E] Generating E2E spec: ${v}...`);let c=`
185
+ ${g}
186
+ \`\`\``,testFramework:y}),await fe(e,t,s+1,n,o,i,a)}catch(f){console.error("[Lisa.ai Unit loop failure]:",f.message),await T({projectId:o,type:"unit",filePath:"unit-loop",modelUsed:t,status:"error",details:`Unit test generation encountered an unrecoverable error: ${f.message}`,testFramework:y})}}var gt=require("child_process"),P=b(require("fs")),q=b(require("path"));function Ot(e){let t=[],s=["src/app/app.routes.ts","src/app/app-routing.module.ts"];for(let o of s){let i=q.join(e,o);if(P.existsSync(i)){let r=P.readFileSync(i,"utf-8").matchAll(/path:\s*['"`]([^'"`]+)['"`]/g);for(let d of r)d[1]&&d[1]!=="**"&&t.push(d[1])}}let n=["src/App.tsx","src/App.jsx","src/routes.tsx","src/routes.jsx"];for(let o of n){let i=q.join(e,o);if(P.existsSync(i)){let r=P.readFileSync(i,"utf-8").matchAll(/path=["']([^"']+)["']/g);for(let d of r)d[1]&&t.push(d[1])}}return[...new Set(t)].sort()}async function ft(e,t,s=1,n=3,o="local",i,a){if(s>n){console.log(`
187
+ [Lisa.ai E2E] Reached maximum retries (${n}). Stopping.`);return}let r=process.cwd(),d=R.load(r);d&&(R.applyEnvDefaults(d),!e&&d.e2eCommand&&(e=d.e2eCommand,console.log(`[Lisa.ai Config] Using e2eCommand from .lisai.json: ${e}`)));let p=ke(r),u=d?.e2eFramework||p.framework;console.log(`
188
+ [Lisa.ai E2E] Framework: ${u} (Attempt ${s}/${n}) Model: ${t}`),!p.installed&&u==="playwright"&&Ce(r),e||(e=p.command,console.log(`[Lisa.ai E2E] Using auto-detected command: ${e}`)),await T({projectId:o,type:"e2e",filePath:"e2e-suite",modelUsed:t,status:"running",details:`E2E test generation started with ${u}`,testFramework:u});let y=0;if(a&&a.length>0){console.log(`
189
+ [Lisa.ai E2E] Targeting ${a.length} file(s) from --files`),a.forEach(x=>console.log(` - ${x}`));for(let x of a){let k=q.resolve(r,x);if(P.existsSync(k)){console.log(`[Lisa.ai E2E] Spec already exists: ${x} \u2014 will run as-is.`);continue}let $=q.dirname(k);P.existsSync($)||P.mkdirSync($,{recursive:!0}),console.log(`[Lisa.ai E2E] Generating E2E spec: ${x}...`);let g=`
175
190
  E2E Test Generation Context:
176
- - Framework: ${p}
177
- - Target file: ${v}
178
- - App Type: ${P.existsSync(G.join(a,"angular.json"))?"Angular":"Web App"}
191
+ - Framework: ${u}
192
+ - Target file: ${x}
193
+ - App Type: ${P.existsSync(q.join(r,"angular.json"))?"Angular":"Web App"}
179
194
  - Base URL: http://localhost:4200
180
195
 
181
- Generate a ${p} E2E test spec for "${v}".
196
+ Generate a ${u} E2E test spec for "${x}".
182
197
  The test should:
183
198
  1. Navigate to the relevant page
184
199
  2. Verify the page loads correctly
@@ -186,14 +201,14 @@ The test should:
186
201
  4. Assert critical UI elements are visible
187
202
 
188
203
  Use @playwright/test imports. Keep it concise and practical.
189
- `;try{let x=await X(v,c,e,o,p,["e2e"]);P.writeFileSync(k,x,"utf-8"),console.log(`[Lisa.ai E2E] Wrote ${v}`),w++,await I({projectId:i,type:"e2e",filePath:v,modelUsed:e,status:"success",details:`Generated E2E spec: ${v}`,testFramework:p})}catch(x){console.error(`[Lisa.ai E2E] LLM failed for ${v}: ${x.message}`),await I({projectId:i,type:"e2e",filePath:v,modelUsed:e,status:"error",details:`LLM failed to generate E2E spec: ${x.message}`,testFramework:p})}}if(w===0&&r.every(v=>!P.existsSync(G.resolve(a,v)))){console.log("[Lisa.ai E2E] No specs generated. Check LLM connectivity with 'lisa-agent diagnose'.");return}}else{let v=Nt(a);v.length===0?(console.log("[Lisa.ai E2E] No routes discovered. Will generate basic smoke test."),v.push("")):console.log(`[Lisa.ai E2E] Discovered ${v.length} route(s):`,v);let k=G.join(a,"e2e");P.existsSync(k)||P.mkdirSync(k,{recursive:!0});let f=P.existsSync(k)?P.readdirSync(k).filter(c=>c.endsWith(".spec.ts")||c.endsWith(".test.ts")):[];for(let c of v){let L=`${(c||"home").replace(/\//g,"-")}.spec.ts`,$=G.join(k,L);if(f.includes(L)){console.log(`[Lisa.ai E2E] Spec already exists for /${c} \u2014 skipping.`);continue}console.log(`[Lisa.ai E2E] Generating E2E spec for /${c}...`);try{let E=`
204
+ `;try{let m=await ee(x,g,t,i,u,["e2e"]);P.writeFileSync(k,m,"utf-8"),console.log(`[Lisa.ai E2E] Wrote ${x}`),y++,await T({projectId:o,type:"e2e",filePath:x,modelUsed:t,status:"success",details:`Generated E2E spec: ${x}`,testFramework:u})}catch(m){console.error(`[Lisa.ai E2E] LLM failed for ${x}: ${m.message}`),await T({projectId:o,type:"e2e",filePath:x,modelUsed:t,status:"error",details:`LLM failed to generate E2E spec: ${m.message}`,testFramework:u})}}if(y===0&&a.every(x=>!P.existsSync(q.resolve(r,x)))){console.log("[Lisa.ai E2E] No specs generated. Check LLM connectivity with 'lisa-agent diagnose'.");return}}else{let x=Ot(r);x.length===0?(console.log("[Lisa.ai E2E] No routes discovered. Will generate basic smoke test."),x.push("")):console.log(`[Lisa.ai E2E] Discovered ${x.length} route(s):`,x);let k=q.join(r,"e2e");P.existsSync(k)||P.mkdirSync(k,{recursive:!0});let $=P.existsSync(k)?P.readdirSync(k).filter(g=>g.endsWith(".spec.ts")||g.endsWith(".test.ts")):[];for(let g of x){let v=`${(g||"home").replace(/\//g,"-")}.spec.ts`,L=q.join(k,v);if($.includes(v)){console.log(`[Lisa.ai E2E] Spec already exists for /${g} \u2014 skipping.`);continue}console.log(`[Lisa.ai E2E] Generating E2E spec for /${g}...`);try{let C=`
190
205
  E2E Test Generation Context:
191
- - Framework: ${p}
192
- - Route: /${c}
193
- - App Type: ${P.existsSync(G.join(a,"angular.json"))?"Angular":"Web App"}
206
+ - Framework: ${u}
207
+ - Route: /${g}
208
+ - App Type: ${P.existsSync(q.join(r,"angular.json"))?"Angular":"Web App"}
194
209
  - Base URL: http://localhost:4200
195
210
 
196
- Generate a ${p} E2E test spec for the route "/${c}".
211
+ Generate a ${u} E2E test spec for the route "/${g}".
197
212
  The test should:
198
213
  1. Navigate to the route
199
214
  2. Verify the page loads correctly
@@ -201,27 +216,27 @@ The test should:
201
216
  4. Assert critical UI elements are visible
202
217
 
203
218
  Use @playwright/test imports. Keep it concise and practical.
204
- `,A=await X(`e2e/${L}`,E,e,o,p,["e2e"]);P.writeFileSync($,A,"utf-8"),console.log(`[Lisa.ai E2E] Wrote ${L}`),w++,await I({projectId:i,type:"e2e",filePath:`e2e/${L}`,modelUsed:e,status:"success",details:`Generated E2E spec for route /${c}`,testFramework:p})}catch(E){console.error(`[Lisa.ai E2E] LLM failed for /${c}: ${E.message}`),await I({projectId:i,type:"e2e",filePath:`e2e/${L}`,modelUsed:e,status:"error",details:`LLM failed to generate E2E spec: ${E.message}`,testFramework:p})}}if(w===0&&f.length===0){console.log("[Lisa.ai E2E] No specs generated. Check LLM connectivity with 'lisa-agent diagnose'.");return}}console.log(`
205
- [Lisa.ai E2E] Running E2E tests: ${t}`);let h="",m="",y=!1;try{await new Promise((v,k)=>{let f=(0,dt.spawn)(t,{shell:!0,stdio:["ignore","pipe","pipe"],cwd:a});f.stdout?.on("data",c=>{let x=c.toString();h+=x,process.stdout.write(x)}),f.stderr?.on("data",c=>{let x=c.toString();m+=x,process.stderr.write(x)}),f.on("close",c=>{c===0?v():k(new Error(`E2E tests exited with code ${c}`))})}),y=!0,console.log(`
219
+ `,F=await ee(`e2e/${v}`,C,t,i,u,["e2e"]);P.writeFileSync(L,F,"utf-8"),console.log(`[Lisa.ai E2E] Wrote ${v}`),y++,await T({projectId:o,type:"e2e",filePath:`e2e/${v}`,modelUsed:t,status:"success",details:`Generated E2E spec for route /${g}`,testFramework:u})}catch(C){console.error(`[Lisa.ai E2E] LLM failed for /${g}: ${C.message}`),await T({projectId:o,type:"e2e",filePath:`e2e/${v}`,modelUsed:t,status:"error",details:`LLM failed to generate E2E spec: ${C.message}`,testFramework:u})}}if(y===0&&$.length===0){console.log("[Lisa.ai E2E] No specs generated. Check LLM connectivity with 'lisa-agent diagnose'.");return}}console.log(`
220
+ [Lisa.ai E2E] Running E2E tests: ${e}`);let h="",f="",w=!1;try{await new Promise((x,k)=>{let $=(0,gt.spawn)(e,{shell:!0,stdio:["ignore","pipe","pipe"],cwd:r});$.stdout?.on("data",g=>{let m=g.toString();h+=m,process.stdout.write(m)}),$.stderr?.on("data",g=>{let m=g.toString();f+=m,process.stderr.write(m)}),$.on("close",g=>{g===0?x():k(new Error(`E2E tests exited with code ${g}`))})}),w=!0,console.log(`
206
221
  [Lisa.ai E2E] All E2E tests passed.`)}catch{console.log(`
207
222
  [Lisa.ai E2E] Some E2E tests failed. Run 'lisa-agent heal --type e2e' to auto-fix.`)}let l=h+`
208
- `+m,d=Z(l);await I({projectId:i,type:"e2e",filePath:"e2e-suite",modelUsed:e,status:y?"success":"error",details:`E2E generation complete. ${w} new spec(s) generated.`,...d&&{testTotal:d.total,testPassed:d.passed,testFailed:d.failed},testFramework:p})}var ut=require("child_process"),F=j(require("fs")),b=j(require("path"));function Ut(t){let e=b.join(t,"package.json");if(!F.existsSync(e))return"node";let s=JSON.parse(F.readFileSync(e,"utf-8")),n={...s.dependencies||{},...s.devDependencies||{}};return n["@angular/core"]?"angular":n.react?"react":n.vue?"vue":n["@nestjs/core"]?"nestjs":n.express?"express":"node"}function Ot(t,e){let s=[];if(e==="angular"){let n=b.join(t,"src","app");if(!F.existsSync(n))return s;let i=ue(n,/\.(ts)$/).filter(o=>!o.includes(".spec.")&&!o.includes(".test.")&&!o.includes("node_modules"));for(let o of i){let r=F.readFileSync(o,"utf-8");if(r.includes("@Component")&&r.includes("inject(")){let a=b.relative(t,o),g=a.replace(/\.ts$/,".integration.spec.ts");if(F.existsSync(b.join(t,g)))continue;let p=[...r.matchAll(/inject\((\w+)\)/g)].map(h=>h[1]),w=[];for(let h of p){let m=ue(n,new RegExp(`${_t(h)}\\.ts$`));w.push(...m.map(y=>b.relative(t,y)))}s.push({filePath:a,relatedFiles:w,description:`Angular component+service integration: ${b.basename(o)} injects ${p.join(", ")}`})}}}else if(e==="express"||e==="nestjs"){let n=["src","server","api","routes","controllers"];for(let i of n){let o=b.join(t,i);if(!F.existsSync(o))continue;let r=ue(o,/\.(controller|route|router)\.(ts|js)$/).filter(a=>!a.includes(".spec.")&&!a.includes(".test.")&&!a.includes("node_modules"));for(let a of r){let g=b.relative(t,a),u=g.replace(/\.(ts|js)$/,".integration.spec.$1");F.existsSync(b.join(t,u))||s.push({filePath:g,relatedFiles:[],description:`API endpoint integration test for ${b.basename(a)} \u2014 test with supertest against real middleware chain`})}}}else{let n=b.join(t,"src");if(F.existsSync(n)){let i=ue(n,/\.(ts|js|tsx|jsx)$/).filter(o=>!o.includes(".spec.")&&!o.includes(".test.")&&!o.includes("node_modules"));for(let o of i){let a=[...F.readFileSync(o,"utf-8").matchAll(/from\s+['"]\.\.?\//g)];if(a.length>=2){let g=b.relative(t,o),u=g.replace(/\.(ts|js|tsx|jsx)$/,".integration.spec.$1");if(F.existsSync(b.join(t,u)))continue;s.push({filePath:g,relatedFiles:[],description:`Module integration: ${b.basename(o)} imports ${a.length} local modules`})}}}}return s}function ue(t,e){let s=[],n=["node_modules","dist","build",".git",".angular","coverage"];if(!F.existsSync(t))return s;let i=F.readdirSync(t);for(let o of i){if(n.includes(o))continue;let r=b.join(t,o);try{F.statSync(r).isDirectory()?s.push(...ue(r,e)):e.test(o)&&s.push(r)}catch{continue}}return s}function _t(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}async function gt(t,e,s=1,n=3,i="local",o,r){if(s>n){console.log(`
209
- [Lisa.ai Integration] Reached maximum retries (${n}). Stopping.`);return}let a=process.cwd(),g=R.load(a);g&&(R.applyEnvDefaults(g),!t&&g.testCommand&&(t=g.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${t}`)));let u=Ut(a),p=Y.scanRepository(),w=g?.testingFramework||(p.testingFramework!=="none"?p.testingFramework:void 0);console.log(`
210
- [Lisa.ai Integration] App: ${u}, Framework: ${w||"auto"} (Attempt ${s}/${n}) Model: ${e}`),t||(p.suggestedTestCommand?t=p.suggestedTestCommand:F.existsSync(b.join(a,"angular.json"))?t="npx ng test --no-watch --browsers=ChromeHeadless":(console.error(`
211
- [Lisa.ai Fatal Error] Could not auto-detect a test command. Please pass --command explicitly.`),process.exit(1)),console.log(`[Lisa.ai Integration] Auto-detected command: ${t}`));let h=ie(t);await I({projectId:i,type:"integration",filePath:"integration-suite",modelUsed:e,status:"running",details:`Integration test generation started for ${u} app`,testFramework:h});let m;if(r&&r.length>0)m=r.map(c=>({filePath:c,relatedFiles:[],description:"User-specified"})),console.log(`
212
- [Lisa.ai Integration] Targeting ${r.length} file(s) from --files`),m.forEach(c=>console.log(` - ${c.filePath}`));else{if(m=Ot(a,u),m.length===0){console.log("[Lisa.ai Integration] No integration targets discovered. The project may already have full integration coverage.");return}console.log(`[Lisa.ai Integration] Found ${m.length} integration target(s):`),m.forEach(c=>console.log(` - ${c.filePath}: ${c.description}`))}let y=0;for(let c of m){let x=b.resolve(a,c.filePath);if(!F.existsSync(x))continue;let L=b.parse(x),$=b.join(L.dir,`${L.name}.integration.spec${L.ext}`);if(F.existsSync($)){console.log(`[Lisa.ai Integration] Spec exists for ${c.filePath} \u2014 skipping.`);continue}console.log(`[Lisa.ai Integration] Generating integration spec for ${c.filePath}...`);let E=F.readFileSync(x,"utf-8"),A="";for(let H of c.relatedFiles.slice(0,3)){let C=b.resolve(a,H);if(F.existsSync(C)){let N=F.readFileSync(C,"utf-8");A+=`
223
+ `+f,c=Z(l);await T({projectId:o,type:"e2e",filePath:"e2e-suite",modelUsed:t,status:w?"success":"error",details:`E2E generation complete. ${y} new spec(s) generated.`,...c&&{testTotal:c.total,testPassed:c.passed,testFailed:c.failed},testFramework:u})}var mt=require("child_process"),A=b(require("fs")),j=b(require("path"));function Gt(e){let t=j.join(e,"package.json");if(!A.existsSync(t))return"node";let s=JSON.parse(A.readFileSync(t,"utf-8")),n={...s.dependencies||{},...s.devDependencies||{}};return n["@angular/core"]?"angular":n.react?"react":n.vue?"vue":n["@nestjs/core"]?"nestjs":n.express?"express":"node"}function Ht(e,t){let s=[];if(t==="angular"){let n=j.join(e,"src","app");if(!A.existsSync(n))return s;let o=me(n,/\.(ts)$/).filter(i=>!i.includes(".spec.")&&!i.includes(".test.")&&!i.includes("node_modules"));for(let i of o){let a=A.readFileSync(i,"utf-8");if(a.includes("@Component")&&a.includes("inject(")){let r=j.relative(e,i),d=r.replace(/\.ts$/,".integration.spec.ts");if(A.existsSync(j.join(e,d)))continue;let u=[...a.matchAll(/inject\((\w+)\)/g)].map(h=>h[1]),y=[];for(let h of u){let f=me(n,new RegExp(`${qt(h)}\\.ts$`));y.push(...f.map(w=>j.relative(e,w)))}s.push({filePath:r,relatedFiles:y,description:`Angular component+service integration: ${j.basename(i)} injects ${u.join(", ")}`})}}}else if(t==="express"||t==="nestjs"){let n=["src","server","api","routes","controllers"];for(let o of n){let i=j.join(e,o);if(!A.existsSync(i))continue;let a=me(i,/\.(controller|route|router)\.(ts|js)$/).filter(r=>!r.includes(".spec.")&&!r.includes(".test.")&&!r.includes("node_modules"));for(let r of a){let d=j.relative(e,r),p=d.replace(/\.(ts|js)$/,".integration.spec.$1");A.existsSync(j.join(e,p))||s.push({filePath:d,relatedFiles:[],description:`API endpoint integration test for ${j.basename(r)} \u2014 test with supertest against real middleware chain`})}}}else{let n=j.join(e,"src");if(A.existsSync(n)){let o=me(n,/\.(ts|js|tsx|jsx)$/).filter(i=>!i.includes(".spec.")&&!i.includes(".test.")&&!i.includes("node_modules"));for(let i of o){let r=[...A.readFileSync(i,"utf-8").matchAll(/from\s+['"]\.\.?\//g)];if(r.length>=2){let d=j.relative(e,i),p=d.replace(/\.(ts|js|tsx|jsx)$/,".integration.spec.$1");if(A.existsSync(j.join(e,p)))continue;s.push({filePath:d,relatedFiles:[],description:`Module integration: ${j.basename(i)} imports ${r.length} local modules`})}}}}return s}function me(e,t){let s=[],n=["node_modules","dist","build",".git",".angular","coverage"];if(!A.existsSync(e))return s;let o=A.readdirSync(e);for(let i of o){if(n.includes(i))continue;let a=j.join(e,i);try{A.statSync(a).isDirectory()?s.push(...me(a,t)):t.test(i)&&s.push(a)}catch{continue}}return s}function qt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}async function ht(e,t,s=1,n=3,o="local",i,a){if(s>n){console.log(`
224
+ [Lisa.ai Integration] Reached maximum retries (${n}). Stopping.`);return}let r=process.cwd(),d=R.load(r);d&&(R.applyEnvDefaults(d),!e&&d.testCommand&&(e=d.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${e}`)));let p=Gt(r),u=V.scanRepository(),y=d?.testingFramework||(u.testingFramework!=="none"?u.testingFramework:void 0);console.log(`
225
+ [Lisa.ai Integration] App: ${p}, Framework: ${y||"auto"} (Attempt ${s}/${n}) Model: ${t}`),e||(u.suggestedTestCommand?e=u.suggestedTestCommand:A.existsSync(j.join(r,"angular.json"))?e="npx ng test --no-watch --browsers=ChromeHeadless":(console.error(`
226
+ [Lisa.ai Fatal Error] Could not auto-detect a test command. Please pass --command explicitly.`),process.exit(1)),console.log(`[Lisa.ai Integration] Auto-detected command: ${e}`));let h=le(e);await T({projectId:o,type:"integration",filePath:"integration-suite",modelUsed:t,status:"running",details:`Integration test generation started for ${p} app`,testFramework:h});let f;if(a&&a.length>0)f=a.map(g=>({filePath:g,relatedFiles:[],description:"User-specified"})),console.log(`
227
+ [Lisa.ai Integration] Targeting ${a.length} file(s) from --files`),f.forEach(g=>console.log(` - ${g.filePath}`));else{if(f=Ht(r,p),f.length===0){console.log("[Lisa.ai Integration] No integration targets discovered. The project may already have full integration coverage.");return}console.log(`[Lisa.ai Integration] Found ${f.length} integration target(s):`),f.forEach(g=>console.log(` - ${g.filePath}: ${g.description}`))}let w=0;for(let g of f){let m=j.resolve(r,g.filePath);if(!A.existsSync(m))continue;let v=j.parse(m),L=j.join(v.dir,`${v.name}.integration.spec${v.ext}`);if(A.existsSync(L)){console.log(`[Lisa.ai Integration] Spec exists for ${g.filePath} \u2014 skipping.`);continue}console.log(`[Lisa.ai Integration] Generating integration spec for ${g.filePath}...`);let C=A.readFileSync(m,"utf-8"),F="";for(let M of g.relatedFiles.slice(0,3)){let E=j.resolve(r,M);if(A.existsSync(E)){let U=A.readFileSync(E,"utf-8");F+=`
213
228
 
214
- // --- Related file: ${H} ---
215
- ${N.slice(0,5e3)}`}}let z=`
216
- INTEGRATION TEST \u2014 ${c.description}
229
+ // --- Related file: ${M} ---
230
+ ${U.slice(0,5e3)}`}}let G=`
231
+ INTEGRATION TEST \u2014 ${g.description}
217
232
 
218
233
  Generate an integration test that exercises real module interactions (NOT mocked).
219
- ${u==="angular"?`
234
+ ${p==="angular"?`
220
235
  - Use TestBed with real service providers (not jasmine.createSpyObj)
221
236
  - Import the actual component and its real dependencies
222
237
  - Test that the component and service work together correctly
223
238
  - Use HttpClientTestingModule for HTTP calls
224
- `:u==="express"||u==="nestjs"?`
239
+ `:p==="express"||p==="nestjs"?`
225
240
  - Use supertest to make real HTTP requests against the app
226
241
  - Test the full middleware chain (auth, validation, handler)
227
242
  - Use a test database or in-memory mock for data layer
@@ -232,32 +247,32 @@ ${u==="angular"?`
232
247
  `}
233
248
 
234
249
  Source file:
235
- ${E.slice(0,1e4)}
250
+ ${C.slice(0,1e4)}
236
251
 
237
- ${A?`Related modules:
238
- ${A}`:""}
239
- `;try{let H=await X(c.filePath,z,e,o,w,["integration"]);F.writeFileSync($,H,"utf-8"),console.log(`[Lisa.ai Integration] Wrote ${b.relative(a,$)}`),y++,await I({projectId:i,type:"integration",filePath:c.filePath,modelUsed:e,status:"success",details:`Generated integration spec: ${c.description}`,testFramework:h})}catch(H){console.error(`[Lisa.ai Integration] LLM failed for ${c.filePath}: ${H.message}`)}}if(y===0){console.log("[Lisa.ai Integration] No new integration specs generated.");return}console.log(`
240
- [Lisa.ai Integration] Running tests to verify generated specs: ${t}`);let l="",d="",v=!1;try{await new Promise((c,x)=>{let L=(0,ut.spawn)(t,{shell:!0,stdio:["ignore","pipe","pipe"],cwd:a});L.stdout?.on("data",$=>{let E=$.toString();l+=E,process.stdout.write(E)}),L.stderr?.on("data",$=>{let E=$.toString();d+=E,process.stderr.write(E)}),L.on("close",$=>{$===0?c():x(new Error(`Tests exited with code ${$}`))})}),v=!0,console.log(`
252
+ ${F?`Related modules:
253
+ ${F}`:""}
254
+ `;try{let M=await ee(g.filePath,G,t,i,y,["integration"]);A.writeFileSync(L,M,"utf-8"),console.log(`[Lisa.ai Integration] Wrote ${j.relative(r,L)}`),w++,await T({projectId:o,type:"integration",filePath:g.filePath,modelUsed:t,status:"success",details:`Generated integration spec: ${g.description}`,testFramework:h})}catch(M){console.error(`[Lisa.ai Integration] LLM failed for ${g.filePath}: ${M.message}`)}}if(w===0){console.log("[Lisa.ai Integration] No new integration specs generated.");return}console.log(`
255
+ [Lisa.ai Integration] Running tests to verify generated specs: ${e}`);let l="",c="",x=!1;try{await new Promise((g,m)=>{let v=(0,mt.spawn)(e,{shell:!0,stdio:["ignore","pipe","pipe"],cwd:r});v.stdout?.on("data",L=>{let C=L.toString();l+=C,process.stdout.write(C)}),v.stderr?.on("data",L=>{let C=L.toString();c+=C,process.stderr.write(C)}),v.on("close",L=>{L===0?g():m(new Error(`Tests exited with code ${L}`))})}),x=!0,console.log(`
241
256
  [Lisa.ai Integration] All tests passed including integration specs.`)}catch{console.log(`
242
257
  [Lisa.ai Integration] Some tests failed. Run 'lisa-agent heal --type integration' to auto-fix.`)}let k=l+`
243
- `+d,f=Z(k);await I({projectId:i,type:"integration",filePath:"integration-suite",modelUsed:e,status:v?"success":"error",details:`Integration test generation complete. ${y} new spec(s) generated.`,...f&&{testTotal:f.total,testPassed:f.passed,testFailed:f.failed},testFramework:h})}var ht=j(require("dotenv")),yt=require("child_process"),Q=j(require("fs")),J=j(require("path"));ht.config({quiet:!0});function ae(t){return new Promise(e=>{let s=(0,yt.spawn)(t,{shell:!0,stdio:["ignore","pipe","pipe"]}),n="",i="";s.stdout?.on("data",o=>{n+=o.toString()}),s.stderr?.on("data",o=>{i+=o.toString()}),s.on("close",o=>e({stdout:n,stderr:i,code:o??1}))})}function Gt(){return Q.existsSync(J.resolve(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Q.existsSync(J.resolve(process.cwd(),"yarn.lock"))?"yarn":"npm"}var Ht={critical:"\u{1F534}",high:"\u{1F7E0}",moderate:"\u{1F7E1}",low:"\u{1F535}",info:"\u26AA"},ft={critical:5,high:4,moderate:3,low:2,info:1};function mt(t){let e=["critical","high","moderate","low","info"];for(let s of e){let n=t[s]??0;n>0&&console.log(` ${Ht[s]} ${s.padEnd(10)} ${n}`)}console.log(` ${"\u2500".repeat(22)}`),console.log(` ${"Total".padEnd(10)} ${t.total}`)}async function Ne(t){try{return JSON.parse(t)}catch{return null}}async function wt(t,e="local",s){Q.existsSync(J.resolve(process.cwd(),"package.json"))||(console.error(`
244
- \u{1F6A8} [Lisa.ai Audit] No package.json found in ${process.cwd()}.`),console.error(" The audit command currently supports Node.js / npm projects only."),process.exit(1));let n=Gt();console.log(`[Lisa.ai Audit] Package manager: ${n}`),console.log(`
245
- [Lisa.ai Audit] Scanning for vulnerabilities...`);let{stdout:i,code:o}=await ae(n==="npm"?"npm audit --json":n==="yarn"?"yarn audit --json":"pnpm audit --json");if(o===0){console.log(`
246
- \u2705 [Lisa.ai Audit] No vulnerabilities found! Repository is clean.`);return}let r=await Ne(i);r||(console.error("[Lisa.ai Audit] Could not parse audit output. Run 'npm audit' manually to investigate."),process.exit(1));let a=r.metadata.vulnerabilities;console.log(`
247
- Vulnerabilities found:`),mt(a),console.log(`
248
- [Lisa.ai Audit] Applying safe automatic fixes (npm audit fix)...`);let{stdout:g}=await ae(n==="npm"?"npm audit fix":n==="yarn"?"yarn upgrade":"pnpm audit fix");for(let C of g.split(`
249
- `)){let N=C.trim();N&&!N.startsWith("npm warn")&&!N.startsWith("npm notice")&&console.log(` ${N}`)}let u=n==="npm"?"npm audit --json":n==="yarn"?"yarn audit --json":"pnpm audit --json",{stdout:p,code:w}=await ae(u);if(w===0){console.log(`
250
- \u2705 [Lisa.ai Audit] All vulnerabilities fixed by safe auto-fix!`);return}let h=await Ne(p);if(!h){console.warn("[Lisa.ai Audit] Could not parse post-fix audit output.");return}let m=Object.values(h.vulnerabilities),y=h.metadata.vulnerabilities,l=a.total-y.total;console.log(`
251
- [Lisa.ai Audit] Safe auto-fix resolved ${l} vulnerability(-ies).`),y.total>0&&(console.log(" Remaining:"),mt(y));let d=m.filter(C=>typeof C.fixAvailable=="object"&&!C.fixAvailable.isSemVerMajor).map(C=>C.fixAvailable),v=[...new Map(d.map(C=>[C.name,C])).values()];if(v.length>0){console.log(`
252
- [Lisa.ai Audit] Applying ${v.length} non-breaking targeted upgrade(s)...`);for(let te of v){let B=`npm install ${te.name}@${te.version}`;console.log(` \u2192 ${B}`);let{stderr:ce}=await ae(B);ce&&!ce.includes("npm warn")&&console.warn(` ${ce.trim()}`)}let{stdout:C,code:N}=await ae(u);if(N===0){console.log(`
253
- \u2705 [Lisa.ai Audit] All vulnerabilities resolved!`);return}}let{stdout:k}=await ae(u),f=await Ne(k)??h,x=Object.values(f.vulnerabilities).sort((C,N)=>(ft[N.severity]??0)-(ft[C.severity]??0)).slice(0,10).filter(C=>C.fixAvailable===!1?!0:typeof C.fixAvailable=="object"?C.fixAvailable.isSemVerMajor:!1);if(x.length===0){console.log(`
258
+ `+c,$=Z(k);await T({projectId:o,type:"integration",filePath:"integration-suite",modelUsed:t,status:x?"success":"error",details:`Integration test generation complete. ${w} new spec(s) generated.`,...$&&{testTotal:$.total,testPassed:$.passed,testFailed:$.failed},testFramework:h})}var vt=b(require("dotenv")),xt=require("child_process"),Q=b(require("fs")),J=b(require("path"));vt.config({quiet:!0});function ce(e){return new Promise(t=>{let s=(0,xt.spawn)(e,{shell:!0,stdio:["ignore","pipe","pipe"]}),n="",o="";s.stdout?.on("data",i=>{n+=i.toString()}),s.stderr?.on("data",i=>{o+=i.toString()}),s.on("close",i=>t({stdout:n,stderr:o,code:i??1}))})}function Bt(){return Q.existsSync(J.resolve(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Q.existsSync(J.resolve(process.cwd(),"yarn.lock"))?"yarn":"npm"}var Yt={critical:"\u{1F534}",high:"\u{1F7E0}",moderate:"\u{1F7E1}",low:"\u{1F535}",info:"\u26AA"},yt={critical:5,high:4,moderate:3,low:2,info:1};function wt(e){let t=["critical","high","moderate","low","info"];for(let s of t){let n=e[s]??0;n>0&&console.log(` ${Yt[s]} ${s.padEnd(10)} ${n}`)}console.log(` ${"\u2500".repeat(22)}`),console.log(` ${"Total".padEnd(10)} ${e.total}`)}async function Ue(e){try{return JSON.parse(e)}catch{return null}}async function $t(e,t="local",s){Q.existsSync(J.resolve(process.cwd(),"package.json"))||(console.error(`
259
+ \u{1F6A8} [Lisa.ai Audit] No package.json found in ${process.cwd()}.`),console.error(" The audit command currently supports Node.js / npm projects only."),process.exit(1));let n=Bt();console.log(`[Lisa.ai Audit] Package manager: ${n}`),console.log(`
260
+ [Lisa.ai Audit] Scanning for vulnerabilities...`);let{stdout:o,code:i}=await ce(n==="npm"?"npm audit --json":n==="yarn"?"yarn audit --json":"pnpm audit --json");if(i===0){console.log(`
261
+ \u2705 [Lisa.ai Audit] No vulnerabilities found! Repository is clean.`);return}let a=await Ue(o);a||(console.error("[Lisa.ai Audit] Could not parse audit output. Run 'npm audit' manually to investigate."),process.exit(1));let r=a.metadata.vulnerabilities;console.log(`
262
+ Vulnerabilities found:`),wt(r),console.log(`
263
+ [Lisa.ai Audit] Applying safe automatic fixes (npm audit fix)...`);let{stdout:d}=await ce(n==="npm"?"npm audit fix":n==="yarn"?"yarn upgrade":"pnpm audit fix");for(let E of d.split(`
264
+ `)){let U=E.trim();U&&!U.startsWith("npm warn")&&!U.startsWith("npm notice")&&console.log(` ${U}`)}let p=n==="npm"?"npm audit --json":n==="yarn"?"yarn audit --json":"pnpm audit --json",{stdout:u,code:y}=await ce(p);if(y===0){console.log(`
265
+ \u2705 [Lisa.ai Audit] All vulnerabilities fixed by safe auto-fix!`);return}let h=await Ue(u);if(!h){console.warn("[Lisa.ai Audit] Could not parse post-fix audit output.");return}let f=Object.values(h.vulnerabilities),w=h.metadata.vulnerabilities,l=r.total-w.total;console.log(`
266
+ [Lisa.ai Audit] Safe auto-fix resolved ${l} vulnerability(-ies).`),w.total>0&&(console.log(" Remaining:"),wt(w));let c=f.filter(E=>typeof E.fixAvailable=="object"&&!E.fixAvailable.isSemVerMajor).map(E=>E.fixAvailable),x=[...new Map(c.map(E=>[E.name,E])).values()];if(x.length>0){console.log(`
267
+ [Lisa.ai Audit] Applying ${x.length} non-breaking targeted upgrade(s)...`);for(let oe of x){let B=`npm install ${oe.name}@${oe.version}`;console.log(` \u2192 ${B}`);let{stderr:ue}=await ce(B);ue&&!ue.includes("npm warn")&&console.warn(` ${ue.trim()}`)}let{stdout:E,code:U}=await ce(p);if(U===0){console.log(`
268
+ \u2705 [Lisa.ai Audit] All vulnerabilities resolved!`);return}}let{stdout:k}=await ce(p),$=await Ue(k)??h,m=Object.values($.vulnerabilities).sort((E,U)=>(yt[U.severity]??0)-(yt[E.severity]??0)).slice(0,10).filter(E=>E.fixAvailable===!1?!0:typeof E.fixAvailable=="object"?E.fixAvailable.isSemVerMajor:!1);if(m.length===0){console.log(`
254
269
  \u2705 [Lisa.ai Audit] No breaking-change or unfixable vulnerabilities remain.`);return}console.log(`
255
- [Lisa.ai Audit] ${x.length} vulnerability(-ies) require manual attention.`),console.log(`[Lisa.ai Audit] Consulting ${t} for remediation guidance...`);let L={};try{L=JSON.parse(Q.readFileSync(J.resolve(process.cwd(),"package.json"),"utf8"))}catch{}let $={...L.dependencies??{},...L.devDependencies??{}},E=x.map(C=>{let N=C.fixAvailable,te=N===!1?"no fix available yet":`upgrade to ${N.name}@${N.version} (BREAKING \u2014 major version bump)`,B=$[C.name]?`current: ${$[C.name]}`:"transitive dependency";return`\u2022 ${C.name} (${C.severity}) \u2014 ${B} \u2014 ${te}`}).join(`
256
- `),A=`You are a Node.js security expert helping a developer fix npm vulnerabilities.
270
+ [Lisa.ai Audit] ${m.length} vulnerability(-ies) require manual attention.`),console.log(`[Lisa.ai Audit] Consulting ${e} for remediation guidance...`);let v={};try{v=JSON.parse(Q.readFileSync(J.resolve(process.cwd(),"package.json"),"utf8"))}catch{}let L={...v.dependencies??{},...v.devDependencies??{}},C=m.map(E=>{let U=E.fixAvailable,oe=U===!1?"no fix available yet":`upgrade to ${U.name}@${U.version} (BREAKING \u2014 major version bump)`,B=L[E.name]?`current: ${L[E.name]}`:"transitive dependency";return`\u2022 ${E.name} (${E.severity}) \u2014 ${B} \u2014 ${oe}`}).join(`
271
+ `),F=`You are a Node.js security expert helping a developer fix npm vulnerabilities.
257
272
 
258
273
  These vulnerabilities remain after safe auto-fixes were applied. Each requires either a breaking upgrade or has no automated fix:
259
274
 
260
- ${E}
275
+ ${C}
261
276
 
262
277
  For each vulnerability:
263
278
  1. Briefly explain the security risk (1 sentence).
@@ -265,30 +280,78 @@ For each vulnerability:
265
280
  3. If the upgrade is breaking (major version), note the most likely code change needed (e.g. renamed API, changed import path).
266
281
  4. If no fix exists, suggest a workaround or safe alternative package.
267
282
 
268
- Be concrete. Use numbered items. If a vulnerability is a transitive dependency, explain how to force a resolution override in package.json.`;try{let C=await se(A,t,s);console.log(`
283
+ Be concrete. Use numbered items. If a vulnerability is a transitive dependency, explain how to force a resolution override in package.json.`;try{let E=await ie(F,e,s);console.log(`
269
284
  Remediation guidance:
270
- `);for(let B of C.split(`
271
- `))console.log(` ${B}`);let N=J.resolve(process.cwd(),"lisa-audit-report.md"),te=["# Lisa.ai Security Audit Report","",`Generated: ${new Date().toISOString()}`,`Project: ${L.name??J.basename(process.cwd())}`,"","## Summary","","| Severity | Initial | Remaining |","|----------|---------|-----------|",...["critical","high","moderate","low"].map(B=>{let ce=a[B]??0,St=f.metadata.vulnerabilities[B]??0;return`| ${B} | ${ce} | ${St} |`}),"","## Vulnerabilities Requiring Manual Action","",E,"",`## Remediation Guidance (${t})`,"",C].join(`
272
- `);Q.writeFileSync(N,te,"utf-8"),console.log(`
273
- [Lisa.ai Audit] Full report saved to: lisa-audit-report.md`)}catch(C){console.error(`
274
- [Lisa.ai Audit] LLM guidance failed: ${C.message}`),console.log(" Run 'npm audit' manually and address the remaining vulnerabilities.")}let z=f.metadata.vulnerabilities,H=a.total-z.total;console.log(`
275
- ${"\u2500".repeat(50)}`),console.log(" Lisa.ai Audit Complete"),console.log(` \u2705 Fixed: ${H} / ${a.total}`),console.log(` \u26A0\uFE0F Remaining: ${z.total} (see lisa-audit-report.md)`),console.log(`${"\u2500".repeat(50)}
276
- `)}var kt=vt();function le(){console.log(`
277
- ======================================================`),console.log(` Lisa.ai Agent v${kt.version}`),console.log(" Autonomous CI/CD Platform Worker"),console.log(`======================================================
278
- `)}async function je(t){let e=5,s=t.model,n;if(t.projectId){let o=await ge(t.projectId);if(!o.ok)o.reason==="not_found"?(console.error(`
279
- [Lisa.ai Agent Error] Project '${t.projectId}' does not exist on the Control Plane. Please create it in the Dashboard first or run locally without a project ID.`),process.exit(1)):console.warn(`
280
- [Lisa.ai Warning] Control Plane is unreachable. Continuing with local CLI defaults (model=${s}, maxRetries=${e}).`);else{let r=o.config;console.log(`[Lisa.ai Agent] Dynamic Config Loaded: Provider=${r.modelProvider}, MaxRetries=${r.maxRetries}`),r.maxRetries<5&&console.warn(`
281
- [Lisa.ai Warning] maxRetries is ${r.maxRetries}. Consider increasing to 5+ for complex projects.`),s=r.modelProvider,e=r.maxRetries,n=r.apiKey,r.agentEnabled===!1&&(console.log("[Lisa.ai Agent] Agent is disabled by Control Plane for this project."),process.exit(1))}}let i=R.load(process.cwd());return i&&(R.applyEnvDefaults(i),!t.projectId&&i.maxRetries!==void 0&&(e=i.maxRetries),!t.projectId&&i.provider&&t.model==="gemini"&&(s=i.provider),R.printSummary(i)),{model:s,maxRetries:e,apiKey:n,projectId:t.projectId||"local"}}var K=new xt.Command;K.name("lisa-agent").description("Lisa.ai - Autonomous CI/CD Platform Worker Agent").version(kt.version);K.command("heal").description("Run tests and autonomously heal all failures via LLM + Memory Engine").option("-c, --command <type>","Test command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-t, --type <scope>","Test type to heal: unit (default), e2e, integration","unit").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async t=>{le();let e=["unit","e2e","integration"],s=t.type;e.includes(s)||(console.error(`
282
- [Lisa.ai Error] Invalid heal type '${t.type}'. Valid types: ${e.join(", ")}`),process.exit(1));let n=t.files?t.files.split(",").map(o=>o.trim()):void 0,i=await je(t);await Le(t.command,i.model,1,null,i.maxRetries,i.projectId,void 0,i.apiKey,s,n)});K.command("unit").description("Generate missing unit test specs to reach 100% coverage (auto-detects framework)").option("-c, --command <type>","Test+coverage command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async t=>{le();let e=t.files?t.files.split(",").map(n=>n.trim()):void 0,s=await je(t);await pe(t.command,s.model,1,s.maxRetries,s.projectId,s.apiKey,e)});K.command("e2e").description("Generate E2E tests via Playwright (auto-installs if none detected)").option("-c, --command <type>","E2E command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async t=>{le();let e=t.files?t.files.split(",").map(n=>n.trim()):void 0,s=await je(t);await pt(t.command,s.model,1,s.maxRetries,s.projectId,s.apiKey,e)});K.command("integration").description("Generate integration tests for module seams (component+service, API+DB)").option("-c, --command <type>","Test command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async t=>{le();let e=t.files?t.files.split(",").map(n=>n.trim()):void 0,s=await je(t);await gt(t.command,s.model,1,s.maxRetries,s.projectId,s.apiKey,e)});K.command("diagnose").description("Test LLM connectivity and API key health without running the full agent").option("-m, --model <provider>","LLM provider to test (gemini, claude, openai)","claude").option("-p, --project-id <id>","Control Plane Project ID to fetch API key from").action(async t=>{le();let e=t.model,s;if(t.projectId){let o=await ge(t.projectId);o.ok?(e=o.config.modelProvider,s=o.config.apiKey,console.log(`[Lisa.ai Diagnose] Config fetched from Control Plane. Provider=${e}`)):console.warn(`[Lisa.ai Diagnose] Control Plane ${o.reason}. Using local env for API key.`)}let i={claude:process.env.LISA_CLAUDE_MODEL||"claude-haiku-4-5",openai:process.env.LISA_OPENAI_MODEL||"gpt-4o-mini",gemini:process.env.LISA_GOOGLE_MODEL||"gemini-2.0-flash"}[e]||e;console.log(`
283
- [Lisa.ai Diagnose] Testing ${e} \u2192 model ID: ${i}`);try{let o=await se("Reply with exactly: LISA_OK",e,s);console.log(`
284
- [Lisa.ai Diagnose] ${e} is working correctly.`),console.log(` Model response: "${o}"`)}catch(o){console.error(`
285
- [Lisa.ai Diagnose] ${e} call FAILED.`),console.error(` Error: ${o.message}`),o.cause&&console.error(` Cause: ${o.cause?.message??o.cause}`),console.error(`
286
- Common causes:`),console.error(" - API key is invalid, expired, or has no credits"),console.error(" - Model ID is deprecated (current: claude-sonnet-4-6, gemini-2.0-flash, gpt-4o-mini)"),console.error(" - Rate limit exceeded \u2014 wait a minute and retry"),console.error(" - Network/proxy issue blocking api.anthropic.com"),process.exit(1)}});K.command("init").description("Interactively create a .lisai.json config file in the current project").option("--force","Overwrite existing .lisai.json if it exists").action(async t=>{let e=$t.resolve(process.cwd(),ee);Ee.existsSync(e)&&!t.force&&(console.error(`
287
- [Lisa.ai Init] ${ee} already exists. Use --force to overwrite.`),process.exit(1));let s=Lt.createInterface({input:process.stdin,output:process.stdout}),n=(h,m="")=>new Promise(y=>s.question(m?`${h} [${m}]: `:`${h}: `,l=>y(l.trim()||m)));console.log(`
285
+ `);for(let B of E.split(`
286
+ `))console.log(` ${B}`);let U=J.resolve(process.cwd(),"lisa-audit-report.md"),oe=["# Lisa.ai Security Audit Report","",`Generated: ${new Date().toISOString()}`,`Project: ${v.name??J.basename(process.cwd())}`,"","## Summary","","| Severity | Initial | Remaining |","|----------|---------|-----------|",...["critical","high","moderate","low"].map(B=>{let ue=r[B]??0,bt=$.metadata.vulnerabilities[B]??0;return`| ${B} | ${ue} | ${bt} |`}),"","## Vulnerabilities Requiring Manual Action","",C,"",`## Remediation Guidance (${e})`,"",E].join(`
287
+ `);Q.writeFileSync(U,oe,"utf-8"),console.log(`
288
+ [Lisa.ai Audit] Full report saved to: lisa-audit-report.md`)}catch(E){console.error(`
289
+ [Lisa.ai Audit] LLM guidance failed: ${E.message}`),console.log(" Run 'npm audit' manually and address the remaining vulnerabilities.")}let G=$.metadata.vulnerabilities,M=r.total-G.total;console.log(`
290
+ ${"\u2500".repeat(50)}`),console.log(" Lisa.ai Audit Complete"),console.log(` \u2705 Fixed: ${M} / ${r.total}`),console.log(` \u26A0\uFE0F Remaining: ${G.total} (see lisa-audit-report.md)`),console.log(`${"\u2500".repeat(50)}
291
+ `)}var St=Lt();function ne(){let e=St.version;console.log(`
292
+ \x1B[38;2;99;102;241m\u2554\u2550\u2557\x1B[0m \x1B[1mLisa.ai Agent\x1B[0m v${e}
293
+ \x1B[38;2;99;102;241m\u2551\x1B[38;2;129;140;248m\u26A1\x1B[38;2;99;102;241m\u2551\x1B[0m Autonomous CI/CD Platform
294
+ \x1B[38;2;99;102;241m\u255A\u2550\u255D\x1B[0m \x1B[2mheal \xB7 unit \xB7 e2e \xB7 integration \xB7 audit\x1B[0m
295
+ `)}async function je(e){let t=5,s=e.model,n;if(e.projectId){let i=await ye(e.projectId);if(!i.ok)i.reason==="not_found"?(console.error(`
296
+ [Lisa.ai Agent Error] Project '${e.projectId}' does not exist on the Control Plane. Please create it in the Dashboard first or run locally without a project ID.`),process.exit(1)):console.warn(`
297
+ [Lisa.ai Warning] Control Plane is unreachable. Continuing with local CLI defaults (model=${s}, maxRetries=${t}).`);else{let a=i.config;console.log(`[Lisa.ai Agent] Dynamic Config Loaded: Provider=${a.modelProvider}, MaxRetries=${a.maxRetries}`),a.maxRetries<5&&console.warn(`
298
+ [Lisa.ai Warning] maxRetries is ${a.maxRetries}. Consider increasing to 5+ for complex projects.`),s=a.modelProvider,t=a.maxRetries,n=a.apiKey,a.agentEnabled===!1&&(console.log("[Lisa.ai Agent] Agent is disabled by Control Plane for this project."),process.exit(1))}}let o=R.load(process.cwd());return o&&(R.applyEnvDefaults(o),!e.projectId&&o.maxRetries!==void 0&&(t=o.maxRetries),!e.projectId&&o.provider&&e.model==="gemini"&&(s=o.provider),R.printSummary(o)),{model:s,maxRetries:t,apiKey:n,projectId:e.projectId||"local"}}var K=new kt.Command;K.name("lisa-agent").description("Lisa.ai - Autonomous CI/CD Platform Worker Agent").version(St.version);K.command("heal").description("Run tests and autonomously heal all failures via LLM + Memory Engine").option("-c, --command <type>","Test command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-t, --type <scope>","Test type to heal: unit (default), e2e, integration","unit").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").option("--ci","CI mode: commit healed files, open PR, write GitHub Actions step summary").action(async e=>{ne();let t=["unit","e2e","integration"],s=e.type;t.includes(s)||(console.error(`
299
+ [Lisa.ai Error] Invalid heal type '${e.type}'. Valid types: ${t.join(", ")}`),process.exit(1));let n=e.files?e.files.split(",").map(a=>a.trim()):void 0,o=e.ci===!0,i=await je(e);await Se(e.command,i.model,1,i.maxRetries,i.projectId,void 0,i.apiKey,s,n,o)});K.command("unit").description("Generate missing unit test specs to reach 100% coverage (auto-detects framework)").option("-c, --command <type>","Test+coverage command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async e=>{ne();let t=e.files?e.files.split(",").map(n=>n.trim()):void 0,s=await je(e);await fe(e.command,s.model,1,s.maxRetries,s.projectId,s.apiKey,t)});K.command("e2e").description("Generate E2E tests via Playwright (auto-installs if none detected)").option("-c, --command <type>","E2E command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async e=>{ne();let t=e.files?e.files.split(",").map(n=>n.trim()):void 0,s=await je(e);await ft(e.command,s.model,1,s.maxRetries,s.projectId,s.apiKey,t)});K.command("integration").description("Generate integration tests for module seams (component+service, API+DB)").option("-c, --command <type>","Test command to execute (auto-detected if omitted)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").option("-f, --files <paths>","Target specific files (comma-separated, bypasses discovery)").action(async e=>{ne();let t=e.files?e.files.split(",").map(n=>n.trim()):void 0,s=await je(e);await ht(e.command,s.model,1,s.maxRetries,s.projectId,s.apiKey,t)});K.command("diagnose").description("Test LLM connectivity and API key health without running the full agent").option("-m, --model <provider>","LLM provider to test (gemini, claude, openai)","claude").option("-p, --project-id <id>","Control Plane Project ID to fetch API key from").action(async e=>{ne();let t=e.model,s;if(e.projectId){let i=await ye(e.projectId);i.ok?(t=i.config.modelProvider,s=i.config.apiKey,console.log(`[Lisa.ai Diagnose] Config fetched from Control Plane. Provider=${t}`)):console.warn(`[Lisa.ai Diagnose] Control Plane ${i.reason}. Using local env for API key.`)}let o={claude:process.env.LISA_CLAUDE_MODEL||"claude-haiku-4-5",openai:process.env.LISA_OPENAI_MODEL||"gpt-4o-mini",gemini:process.env.LISA_GOOGLE_MODEL||"gemini-2.0-flash"}[t]||t;console.log(`
300
+ [Lisa.ai Diagnose] Testing ${t} \u2192 model ID: ${o}`);try{let i=await ie("Reply with exactly: LISA_OK",t,s);console.log(`
301
+ [Lisa.ai Diagnose] ${t} is working correctly.`),console.log(` Model response: "${i}"`)}catch(i){console.error(`
302
+ [Lisa.ai Diagnose] ${t} call FAILED.`),console.error(` Error: ${i.message}`),i.cause&&console.error(` Cause: ${i.cause?.message??i.cause}`),console.error(`
303
+ Common causes:`),console.error(" - API key is invalid, expired, or has no credits"),console.error(" - Model ID is deprecated (current: claude-sonnet-4-6, gemini-2.0-flash, gpt-4o-mini)"),console.error(" - Rate limit exceeded \u2014 wait a minute and retry"),console.error(" - Network/proxy issue blocking api.anthropic.com"),process.exit(1)}});K.command("init").description("Interactively create a .lisai.json config file in the current project").option("--force","Overwrite existing .lisai.json if it exists").action(async e=>{let t=he.resolve(process.cwd(),te);X.existsSync(t)&&!e.force&&(console.error(`
304
+ [Lisa.ai Init] ${te} already exists. Use --force to overwrite.`),process.exit(1));let s=Ct.createInterface({input:process.stdin,output:process.stdout}),n=(h,f="")=>new Promise(w=>s.question(f?`${h} [${f}]: `:`${h}: `,l=>w(l.trim()||f)));console.log(`
288
305
  Lisa.ai Project Setup \u2014 press Enter to accept the default shown in [ ]
289
- `);let i=await n("LLM provider (gemini / claude / openai)","gemini"),o=await n("Testing framework (jest / vitest / mocha / karma / jasmine \u2014 leave empty to auto-detect)",""),r=await n("E2E framework (playwright / cypress \u2014 leave empty for Playwright default)",""),a=await n("Test types to generate (unit / integration / e2e \u2014 comma-separated)","unit"),g=await n("Test command (leave empty for auto-discovery)",""),u=await n("E2E command (leave empty for auto-discovery)",""),p=await n("Max heal retries","5");s.close();let w={provider:i,testTypes:a.split(",").map(h=>h.trim()).filter(Boolean),maxRetries:parseInt(p,10)||5,skipFiles:[],skipDirs:[],skipPaths:[]};o&&(w.testingFramework=o),r&&(w.e2eFramework=r),g&&(w.testCommand=g),u&&(w.e2eCommand=u),Ee.writeFileSync(e,JSON.stringify(w,null,2)+`
306
+ `);let o=await n("LLM provider (gemini / claude / openai)","gemini"),i=await n("Testing framework (jest / vitest / mocha / karma / jasmine \u2014 leave empty to auto-detect)",""),a=await n("E2E framework (playwright / cypress \u2014 leave empty for Playwright default)",""),r=await n("Test types to generate (unit / integration / e2e \u2014 comma-separated)","unit"),d=await n("Test command (leave empty for auto-discovery)",""),p=await n("E2E command (leave empty for auto-discovery)",""),u=await n("Max heal retries","5");s.close();let y={provider:o,testTypes:r.split(",").map(h=>h.trim()).filter(Boolean),maxRetries:parseInt(u,10)||5,skipFiles:[],skipDirs:[],skipPaths:[]};i&&(y.testingFramework=i),a&&(y.e2eFramework=a),d&&(y.testCommand=d),p&&(y.e2eCommand=p),X.writeFileSync(t,JSON.stringify(y,null,2)+`
290
307
  `,"utf-8"),console.log(`
291
- Created ${ee}:
292
- `),console.log(JSON.stringify(w,null,2)),console.log(`
308
+ Created ${te}:
309
+ `),console.log(JSON.stringify(y,null,2)),console.log(`
293
310
  Tip: add "model" to pin a specific model ID (e.g. "claude-sonnet-4-6").`),console.log(` Edit skipFiles / skipDirs / skipPaths to exclude files from test analysis.
294
- `)});K.command("audit").description("Scan for npm vulnerabilities and auto-fix where safe; consult LLM for manual fixes").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").action(async t=>{le();let e=t.model,s;if(t.projectId){let n=await ge(t.projectId);n.ok?(e=n.config.modelProvider,s=n.config.apiKey,console.log(`[Lisa.ai Audit] Config fetched from Control Plane. Provider=${e}`)):console.warn(`[Lisa.ai Audit] Control Plane ${n.reason}. Using local env for API key.`)}await wt(e,t.projectId||"local",s)});K.parse(process.argv);
311
+ `)});function Kt(e,t){return`# Lisa.ai Auto-Heal Workflow
312
+ # Generated by: lisa-agent init-ci
313
+ # Docs: https://www.npmjs.com/package/@lisa.ai/agent
314
+
315
+ name: Lisa.ai Auto-Heal
316
+
317
+ on:
318
+ push:
319
+ branches: [ main, master, develop ]
320
+ workflow_dispatch: {}
321
+
322
+ permissions:
323
+ contents: write
324
+ pull-requests: write
325
+
326
+ jobs:
327
+ heal:
328
+ runs-on: ubuntu-latest
329
+ timeout-minutes: 15
330
+
331
+ steps:
332
+ - name: Checkout repository
333
+ uses: actions/checkout@v4
334
+
335
+ - name: Setup Node.js
336
+ uses: actions/setup-node@v4
337
+ with:
338
+ node-version: '20'
339
+ cache: 'npm'
340
+
341
+ - name: Install project dependencies
342
+ run: npm ci
343
+
344
+ - name: Install Lisa.ai Agent
345
+ run: npm install -g @lisa.ai/agent
346
+
347
+ - name: Run Lisa.ai Heal
348
+ env:
349
+ ${t}: \${{ secrets.${t} }}
350
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
351
+ run: lisa-agent heal --model ${e} --ci
352
+ `}K.command("init-ci").description("Generate a GitHub Actions workflow file for Lisa.ai CI/CD healing").option("--force","Overwrite existing workflow file").option("-m, --model <provider>","LLM provider for the workflow (gemini, claude, openai)","gemini").action(async e=>{ne();let t=he.resolve(process.cwd(),".github","workflows"),s=he.join(t,"lisa-heal.yml");X.existsSync(s)&&!e.force&&(console.error(`
353
+ [Lisa.ai Init-CI] .github/workflows/lisa-heal.yml already exists. Use --force to overwrite.`),process.exit(1));let n={gemini:"GOOGLE_GENERATIVE_AI_API_KEY",claude:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY"},o=e.model||"gemini",i=n[o]||"GOOGLE_GENERATIVE_AI_API_KEY",a=Kt(o,i);X.mkdirSync(t,{recursive:!0}),X.writeFileSync(s,a,"utf-8"),console.log(`
354
+ Created: .github/workflows/lisa-heal.yml`),console.log(`
355
+ Required repository secret: ${i}`),console.log(" Set it in: GitHub repo > Settings > Secrets and variables > Actions"),console.log(`
356
+ The workflow will:`),console.log(" 1. Run on every push to main/master/develop"),console.log(" 2. Install dependencies + run lisa-agent heal --ci"),console.log(" 3. If tests fail and Lisa heals them, open a PR automatically"),console.log(` 4. If all tests pass or nothing can be healed, report status
357
+ `)});K.command("audit").description("Scan for npm vulnerabilities and auto-fix where safe; consult LLM for manual fixes").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID").action(async e=>{ne();let t=e.model,s;if(e.projectId){let n=await ye(e.projectId);n.ok?(t=n.config.modelProvider,s=n.config.apiKey,console.log(`[Lisa.ai Audit] Config fetched from Control Plane. Provider=${t}`)):console.warn(`[Lisa.ai Audit] Control Plane ${n.reason}. Using local env for API key.`)}await $t(t,e.projectId||"local",s)});K.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lisa.ai/agent",
3
- "version": "2.9.1",
3
+ "version": "2.9.3",
4
4
  "description": "Lisa.ai Autonomous CI/CD Worker Agent",
5
5
  "main": "dist/index.js",
6
6
  "bin": {