@lisa.ai/agent 2.9.3 → 2.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +110 -110
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var jt=Object.create;var _e=Object.defineProperty;var Et=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=Et(t,o))||n.enumerable});return e};var b=(e,t,s)=>(s=e!=null?jt(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.4",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")),T=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(m=>m[3]!==void 0)??s[s.length-1],u=parseInt(p[2]),v=p[3]?parseInt(p[3]):0,f=parseInt(p[1])-v;return{total:u,passed:f,failed:v}}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,v=n[2]?parseInt(n[2]):0;return{total:p,passed:v,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,v=t.match(/(\d+)\s+skipped/),f=v?parseInt(v[1]):0;return{total:u+p+f,passed:u,failed:p}}let r=t.match(/Tests\s+(?:(\d+)\s+failed\s*\|?\s*)?(\d+)\s+passed\s*\((\d+)\)/);if(r){let p=parseInt(r[3]),u=r[1]?parseInt(r[1]):0,v=parseInt(r[2]);return{total:p,passed:v,failed:u}}let a=t.match(/(\d+)\s+passing/),d=t.match(/(\d+)\s+failing/);if(a){let p=parseInt(a[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,r=new Set,a=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,d;for(;(d=a.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(r.has(k))continue;r.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)&&T.existsSync(c)&&!i.has(c)&&i.set(c,S.relative(t,c))}let v=/\[(?:chromium|firefox|webkit)\]\s+[>›]\s+([^\s:]+\.(?:spec|test)\.[tj]sx?):\d+:\d+\s+[>›]/g,f;for(;(f=v.exec(n))!==null;){let l=f[1],c=S.isAbsolute(l)?l:S.resolve(t,l);!o.includes(c)&&T.existsSync(c)&&!i.has(c)&&i.set(c,S.relative(t,c))}let m=/Running:\s+([^\s]+\.(?:cy|spec|test)\.[tj]sx?)/g,y;for(;(y=m.exec(n))!==null;){let l=y[1],c=S.isAbsolute(l)?l:S.resolve(t,l);if(!o.includes(c)&&T.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 h=$.slice(0,g).join(" ");if(c.has(h))continue;c.add(h);let w=Ae(h,s,o);if(w)return S.relative(s,w)}}}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,r;for(;(r=i.exec(n))!==null;){let l=r[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)&&T.existsSync(c))return l}}let a=/FAIL\s+([a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/gi,d;for(;(d=a.exec(n))!==null;){let l=d[1],c=S.isAbsolute(l)?l:S.resolve(s,l);if(!o.includes(c)&&T.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)&&T.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)&&T.existsSync(c))return l}}let v=/\b([A-Z][a-zA-Z0-9]{3,})\b/g,f,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(;(f=v.exec(n))!==null;){let l=f[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 c=Ge(l,s,o);if(c)return S.relative(s,c)}return null}function Ae(e,t,s){if(!T.existsSync(t))return null;let n=T.readdirSync(t);for(let o of n){let i=S.join(t,o);if(["node_modules","dist","build",".git",".angular"].includes(o))continue;let r;try{r=T.statSync(i)}catch{continue}if(r.isDirectory()){let a=Ae(e,i,s);if(a)return a}else if(/\.(spec|test)\.(ts|tsx|js|jsx)$/.test(o)){if(s.includes(S.resolve(i)))continue;try{let a=T.readFileSync(i,"utf8");if(a.includes(`describe('${e}'`)||a.includes(`describe("${e}"`))return i}catch{continue}}}return null}function Ge(e,t,s){if(!T.existsSync(t))return null;let n=T.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 r;try{r=T.statSync(i)}catch{continue}if(r.isDirectory()){let a=Ge(e,i,s);if(a)return a}else if(o.match(/\.(ts|tsx|js|jsx|vue)$/)){let a=T.readFileSync(i,"utf8");if(a.includes(`class ${e}`)||a.includes(`function ${e}`)||a.includes(`const ${e}`)||a.includes(`let ${e}`)||a.includes(`exports.${e}`)||a.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 v=[`${u}.spec${p}`,`${u}.test${p}`,`${u}.spec.js`,`${u}.test.js`];for(let f of v)if(T.existsSync(f)){d=f;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
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
5
|
${e.map(n=>` \u2022 ${t[n]??n}`).join(`
|
|
6
6
|
`)}
|
|
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
|
|
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,r,a){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 ---
|
|
@@ -21,23 +21,23 @@ 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(
|
|
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";p+=`
|
|
25
25
|
|
|
26
26
|
--- CRITICAL ARCHITECTURAL REQUIREMENT ---
|
|
27
|
-
The component `+
|
|
28
|
-
You MUST add `+
|
|
29
|
-
DO NOT add it to the 'declarations' array. If you omit `+
|
|
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."}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
|
-
`+a
|
|
34
|
+
`+r}a&&a.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
|
-
`+
|
|
39
|
-
[Pattern ${
|
|
40
|
-
${
|
|
38
|
+
`+a.map((f,m)=>`
|
|
39
|
+
[Pattern ${m+1}]
|
|
40
|
+
${f}`).join(`
|
|
41
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 ---
|
|
@@ -45,16 +45,16 @@ 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
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:u}=await(0,de.generateText)({model:d,prompt:p}),
|
|
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}),v=u.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return v?v[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 r=xe(s,n),a=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
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
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"+
|
|
55
|
-
`+d,{text:u}=await(0,de.generateText)({model:
|
|
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"+a+`4. Aim for 100% logic coverage.
|
|
55
|
+
`+d,{text:u}=await(0,de.generateText)({model:r,prompt:p}),v=u.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),f=v?v[1].trim():u.trim();return Ke(f,e),f}async function Ze(e,t,s,n,o,i,r,a){console.log(`[Lisa.ai Coverage] Requesting test update from ${o} for ${e}...`);let d=xe(o,i),p=r?`3. You MUST use the '${r}' testing framework exclusively. All new tests must follow '${r}' 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
|
-
`,u=Ve(
|
|
57
|
+
`,u=Ve(a),v=`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
60
|
--- Target File Content (`+e+`) ---
|
|
@@ -62,7 +62,7 @@ A source file lacks 100% test coverage. You must update its existing test suite
|
|
|
62
62
|
|
|
63
63
|
--- Existing Test Suite (`+s+`) ---
|
|
64
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:
|
|
65
|
+
`+u,{text:f}=await(0,de.generateText)({model:d,prompt:v}),m=f.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),y=m?m[1].trim():f.trim();return Ke(y,e),y}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
66
|
`),s=e.quarantinedFiles.length>0?e.quarantinedFiles.map(o=>`- \`${o}\``).join(`
|
|
67
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
68
|
`):"_Test counts not available._";return`## Lisa.ai Auto-Heal Report
|
|
@@ -82,12 +82,12 @@ ${n}
|
|
|
82
82
|
---
|
|
83
83
|
|
|
84
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()}`,
|
|
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()}`,r=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 a=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(a),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("/"),v=await new Xe.Octokit({auth:t}).rest.pulls.create({owner:d,repo:p,title:a,body:Rt(e),head:i,base:r});return console.log(`[Lisa.ai CI] Pull Request created: ${v.data.html_url}`),v.data.html_url}catch(a){return console.error(`[Lisa.ai CI] Failed to create PR: ${a.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
86
|
`)+`
|
|
87
|
-
`)}catch{}}var tt=b(require("dotenv"));tt.config({quiet:!0});async function
|
|
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(" "),
|
|
87
|
+
`)}catch{}}var tt=b(require("dotenv"));tt.config({quiet:!0});async function R(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",P=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.projectId&&s.push(`projectId=${t.projectId}`),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||{}},r=o.scripts||{};return i["@angular/core"]?n.type="angular":i.react?n.type="react":i.vue?n.type="vue":n.type="node",i.jest||r.test?.includes("jest")?n.testingFramework="jest":i.karma||r.test?.includes("karma")||r.test?.includes("ng test")?n.testingFramework="karma":(i.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(t,s=[]){let n=[];if(!Y.existsSync(t))return n;let o=Y.readdirSync(t),i=P.get(),r=i?.skipDirs??[],a=i?.skipFiles??[],d=i?.skipPaths??[],p=["node_modules","dist","build",".git",".angular","coverage","public","assets",...r],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"],v=[/^\./,/\.config\.(js|ts|mjs|cjs)$/,/\.conf\.(js|ts|mjs|cjs)$/];for(let f of o){let m=_.join(t,f);if(p.includes(f))continue;let y;try{y=Y.statSync(m)}catch{continue}if(y.isDirectory())n.push(...this.findUntestedFiles(m,s));else if(f.match(/\.(ts|tsx|js|jsx|vue)$/)&&!f.includes(".spec.")&&!f.includes(".test.")){if(u.includes(f)||a.includes(f)||v.some($=>$.test(f)))continue;let l=_.extname(f),c=f.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(),m);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(" "),r=process.platform==="win32"?`${i[0]}.cmd`:i[0];return(0,nt.spawnSync)(r,i.slice(1),{cwd:s,stdio:"inherit"}).status!==0&&(console.error(`
|
|
89
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
|
|
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 a=`You are an expert ${t.type} architect.
|
|
91
91
|
Write a production-ready '${t.testingFramework}' configuration file for a standard '${t.type}' application.
|
|
92
92
|
The application resides in the root directory.
|
|
93
93
|
|
|
@@ -95,8 +95,8 @@ Requirements:
|
|
|
95
95
|
1. Ensure it specifically instruments code coverage.
|
|
96
96
|
2. Ensure standard transpilation (ts-jest for jest, or standard karma-webpack/karma-typescript implementations).
|
|
97
97
|
3. Do NOT wrap your response in markdown formatting (no \`\`\`javascript).
|
|
98
|
-
4. Return ONLY the raw code string block.`;try{let d=await ie(
|
|
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
|
|
98
|
+
4. Return ONLY the raw code string block.`;try{let d=await ie(a,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 r=await i.json();return r.data??r}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';
|
|
100
100
|
|
|
101
101
|
export default defineConfig({
|
|
102
102
|
testDir: './e2e',
|
|
@@ -113,84 +113,84 @@ export default defineConfig({
|
|
|
113
113
|
{ name: 'chromium', use: { browserName: 'chromium' } },
|
|
114
114
|
],
|
|
115
115
|
});
|
|
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,
|
|
117
|
-
`)){let o=n.trim();if(/^FAILED/.test(o)||/ FAILED$/.test(o)){let
|
|
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,r=parseInt(n[1])-i,a=o>0?Math.round(r/o*100):0;return` [${"\u2588".repeat(Math.round(a/5))+"\u2591".repeat(20-Math.round(a/5))}] ${a}% ${r} 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 r=o.replace(/^(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:[\s.]\d+)*\s+\([^)]+\)\s+/,"").replace(/\s+FAILED$/,"").trim();if(s.push(r||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")),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=i.scripts?.[r]?.toLowerCase()||"",d=s.includes("npm")?" --":"";if(a.includes("ng test")||a.includes("karma"))return`${e}${d} --include **/${n.base}`;if(a.includes("jest")||a.includes("vitest")||a.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="",r="";o.stdout?.on("data",a=>{let d=a.toString();if(i+=d,t)for(let p of d.split(`
|
|
118
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",
|
|
119
|
+
`),console.log(` \u2717 ${u.trim()}`)))}}),o.stderr?.on("data",a=>{r+=a.toString()}),o.on("close",a=>{a===0?s({stdout:i,stderr:r}):n({message:`Process exited with code ${a}`,stdout:i,stderr:r})})})}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
|
|
120
120
|
describe('', () => {});
|
|
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,
|
|
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,r,a,d,p){let u=1,v=!1,f=s,m,y="",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<=a&&!v;){console.log(` [Attempt ${u}/${a}] Requesting fix from ${r}...`);let $=H.readFileSync(t,"utf-8"),g;for(let h=0;h<=3;h++)try{g=await ze(e,$,f,r,p,m,c,k);break}catch(w){let L=(w?.lastError??w)?.statusCode;if((L===529||L===500)&&h<3){let C=30*(h+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: ${w?.message??String(w)}`);break}}if(g===void 0)break;H.writeFileSync(t,g,"utf-8"),y=`### Auto-Heal Analysis
|
|
122
122
|
**Error:**
|
|
123
123
|
\`\`\`bash
|
|
124
|
-
${
|
|
124
|
+
${f.slice(0,2e3)}
|
|
125
125
|
\`\`\`
|
|
126
126
|
|
|
127
|
-
**Fix (${
|
|
127
|
+
**Fix (${r}):**
|
|
128
128
|
\`\`\`typescript
|
|
129
129
|
${g}
|
|
130
|
-
\`\`\``;try{await Ne(o,!1),console.log(" \u2705 Isolated verification passed."),
|
|
131
|
-
`+
|
|
132
|
-
`+(
|
|
130
|
+
\`\`\``;try{await Ne(o,!1),console.log(" \u2705 Isolated verification passed."),v=!0,l=g}catch(h){let w=h.stdout?h.stdout.toString():"";f=(h.stderr?h.stderr.toString():"")+`
|
|
131
|
+
`+w+`
|
|
132
|
+
`+(h.message||""),console.log(" \u274C Isolated verification failed.");let C=Me(f);if(C&&console.log(C),lt(f,3).forEach(F=>console.log(` \u2717 ${F}`)),(n||"").toLowerCase().includes("ng test")||(n||"").toLowerCase().includes("karma")){let F=f.includes(z.basename(e)+":"),G=/ FAILED/.test(f);if(!F&&!G){console.log(" \u2705 Fix verified (build error is from other spec files, not this one)."),v=!0,l=g;continue}}m=`### Attempt ${u} Failed
|
|
133
133
|
\`\`\`typescript
|
|
134
134
|
${g}
|
|
135
135
|
\`\`\`
|
|
136
136
|
|
|
137
137
|
**New Error:**
|
|
138
|
-
${
|
|
139
|
-
[Lisa.ai Heal${u}] Auto-detecting E2E framework...`);let
|
|
140
|
-
[Lisa.ai Auto-Discovery] No --command provided. Scanning framework...`);let
|
|
141
|
-
\u{1F6A8} [Lisa.ai] Could not discover a test command. Pass --command explicitly.`),process.exit(1))}let
|
|
142
|
-
[Lisa.ai Heal${u}] Targeting ${d.length} file(s) from --files`),c.forEach(
|
|
138
|
+
${f}`,u++}}return{status:v?"healed":"quarantined",details:y,lastCode:l}}async function Se(e,t,s=1,n=3,o="local",i,r,a="unit",d,p=!1){se=0,pe=0,ge.clear();let u=a==="unit"?"":` (${a})`,v=P.load(process.cwd());if(v&&P.applyEnvDefaults(v),a==="e2e"){if(!e&&v?.e2eCommand&&(e=v.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 h=ke(process.cwd());!h.installed&&h.framework==="playwright"&&Ce(process.cwd()),e=h.command,console.log(`[Lisa.ai Heal${u}] E2E command: ${e}`)}}else if(!e&&v?.testCommand&&(e=v.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 h=V.scanRepository();h.testingFramework==="none"&&(h=await ae.installMissingFramework(h),await re.provisionConfigurationFiles(h,t,r)),h.suggestedTestCommand?(e=h.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 f=le(e),m=[],y="",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(h=>console.log(` - ${h}`));else{console.log(`
|
|
143
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(`
|
|
144
144
|
`),console.log(`
|
|
145
|
-
\u2705 [Lisa.ai] All tests passing. Nothing to heal!`);let
|
|
146
|
-
`),
|
|
147
|
-
`+(
|
|
148
|
-
`+(
|
|
149
|
-
${
|
|
150
|
-
\u{1F6A8} [Lisa.ai] Could not identify any failing spec files. Output format may be unsupported.`),process.exit(1)),c=[
|
|
151
|
-
[Lisa.ai] Found ${x} failing spec(s). Healing each in isolation...`),console.log(`${"\u2500".repeat(60)}`);for(let
|
|
152
|
-
[${
|
|
153
|
-
`+F.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:
|
|
145
|
+
\u2705 [Lisa.ai] All tests passing. Nothing to heal!`);let w={healedFiles:[],quarantinedFiles:[],testCounts:null,allPassing:!0};return p&&Ie({healedFiles:[],quarantinedFiles:[],testCounts:null,modelProvider:t,framework:"unknown",scope:a},null),w}catch(w){process.stdout.write(`
|
|
146
|
+
`),y=(w.stderr||"")+`
|
|
147
|
+
`+(w.stdout||"")+`
|
|
148
|
+
`+(w.message||"")}l=Z(y);let h=Me(y);if(h){console.log(`
|
|
149
|
+
${h}`);let w=lt(y,10);if(w.length>0){let L=l?.failed??w.length;console.log(` Failing (${L}):`),w.forEach(C=>console.log(` \u2717 ${C}`)),L>w.length&&console.log(` ... and ${L-w.length} more`)}}if(c=Fe(y,process.cwd(),m),c.length===0){let w=ve(y,m,process.cwd());w||(console.error(`
|
|
150
|
+
\u{1F6A8} [Lisa.ai] Could not identify any failing spec files. Output format may be unsupported.`),process.exit(1)),c=[w]}}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 h of c)R({projectId:o,type:"heal",filePath:h,modelUsed:t,status:"running",details:"Queued for isolated healing.",...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:f});for(let h=0;h<c.length;h++){let w=c[h],L=z.resolve(process.cwd(),w);if(console.log(`
|
|
152
|
+
[${h+1}/${x}] ${w}`),!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,w),F=await Ut(w,L,y,e,C,f,t,n,o,r);F.status==="healed"?(se++,ge.add(w),console.log(` \u2705 Healed [${se} healed ${pe} quarantined so far]`),R({projectId:o,type:"heal",filePath:w,modelUsed:t,status:"success",details:F.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:f}),await at(y,F.lastCode,f,o)):(pe++,m.push(w),console.warn(` \u{1F6A8} Quarantined [${se} healed ${pe} quarantined so far]`),R({projectId:o,type:"heal",filePath:w,modelUsed:t,status:"error",details:`Exhausted all ${n} attempts.
|
|
153
|
+
`+F.details,...l&&{testTotal:l.total,testPassed:l.passed,testFailed:l.failed},testFramework:f}),Dt(L,w,e))}console.log(`
|
|
154
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(`
|
|
155
155
|
`),console.log(`
|
|
156
|
-
\u2705 All tests passing!`),k=!0}catch(
|
|
157
|
-
`);let
|
|
158
|
-
`+(
|
|
159
|
-
`+(
|
|
160
|
-
${L}`);let C=Fe(
|
|
156
|
+
\u2705 All tests passing!`),k=!0}catch(h){process.stdout.write(`
|
|
157
|
+
`);let w=(h.stderr||"")+`
|
|
158
|
+
`+(h.stdout||"")+`
|
|
159
|
+
`+(h.message||""),L=Me(w);L&&console.log(`
|
|
160
|
+
${L}`);let C=Fe(w,process.cwd(),[]),F=C.filter(M=>ge.has(M)),G=C.filter(M=>!ge.has(M)&&!m.includes(M));F.length>0&&(console.warn(`
|
|
161
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
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
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:[...
|
|
165
|
-
[Lisa.ai Unit] Reached maximum retries (${n}). Stopping.`);return}let
|
|
166
|
-
[Lisa.ai Auto-Discovery] No explicit --command provided. Auto-detecting coverage command...`);let
|
|
164
|
+
`);let g={healedFiles:[...ge],quarantinedFiles:[...m],testCounts:l,allPassing:k};if(p){let h={healedFiles:g.healedFiles,quarantinedFiles:g.quarantinedFiles,testCounts:g.testCounts,modelProvider:t,framework:f,scope:a},w=await et(h);Ie(h,w),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,r]of Object.entries(n))i!=="total"&&(r.lines.pct<100||r.statements.pct<100||r.functions.pct<100||r.branches.pct<100)&&o.push(i);return o}var dt=new Set,je=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,r){if(s>n){console.log(`
|
|
165
|
+
[Lisa.ai Unit] Reached maximum retries (${n}). Stopping.`);return}let a=P.load(process.cwd());a&&(P.applyEnvDefaults(a),!e&&a.testCommand&&(e=a.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${e}`)));let d=V.scanRepository(),p=a?.testingFramework||(d.testingFramework!=="none"?d.testingFramework:void 0),u=a?.testTypes;if(!e){console.log(`
|
|
166
|
+
[Lisa.ai Auto-Discovery] No explicit --command provided. Auto-detecting coverage command...`);let m=_t(d);if(m)e=m,console.log(`[Lisa.ai Auto-Discovery] Detected coverage command: ${e}`);else{let y=d;if(y.testingFramework==="none"&&(y=await ae.installMissingFramework(y),await re.provisionConfigurationFiles(y,t,i)),y.suggestedTestCommand){e=y.suggestedTestCommand;let l=y.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
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
|
|
169
|
-
`);for(let L of
|
|
170
|
-
`+
|
|
171
|
-
[Lisa.ai Unit] Tests passed on attempt ${s}.`)}catch(
|
|
172
|
-
`+(
|
|
173
|
-
`+(
|
|
168
|
+
[Lisa.ai Unit] ${e} (Attempt ${s}/${n}) Using Model: ${t}`);let v=le(e);await R({projectId:o,type:"unit",filePath:"global-test-suite",modelUsed:t,status:"running",details:"Agent is executing unit test suite and validating coverage...",testFramework:v});let f=(m,y=!1)=>new Promise((l,c)=>{let x=(0,pt.spawn)(m,{shell:!0,stdio:["ignore","pipe","pipe"]}),k="",$="";x.stdout?.on("data",g=>{let h=g.toString();if(k+=h,y){let w=h.split(`
|
|
169
|
+
`);for(let L of w){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 m=await f(e,!0),y=m.stdout+`
|
|
170
|
+
`+m.stderr,l=Z(y);l&&await R({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:v}),console.log(`
|
|
171
|
+
[Lisa.ai Unit] Tests passed on attempt ${s}.`)}catch(m){let y=(m.stderr||"")+`
|
|
172
|
+
`+(m.stdout||"")+`
|
|
173
|
+
`+(m.message||"");if(ve(y,[],process.cwd())!==null){console.log(`
|
|
174
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,
|
|
176
|
-
[Lisa.ai Unit] No failing spec detected. Tests may not exist yet \u2014 initiating Cold-Start Discovery...`)}try{let
|
|
177
|
-
[Lisa.ai Unit] Targeting ${
|
|
178
|
-
[Lisa.ai Unit] No coverage-summary.json found. Initiating Cold-Start Discovery...`),
|
|
179
|
-
[Lisa.ai Unit] LLM call failed for ${
|
|
175
|
+
[Lisa.ai Unit] Auto-Heal complete. Restarting unit analysis...`),await fe(e,t,s+1,n,o,i,r);return}console.log(`
|
|
176
|
+
[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(`
|
|
177
|
+
[Lisa.ai Unit] Targeting ${r.length} file(s) from --files`),m.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..."),m=ut("coverage/coverage-summary.json");else{if(console.log(`
|
|
178
|
+
[Lisa.ai Unit] No coverage-summary.json found. Initiating Cold-Start Discovery...`),m=V.findUntestedFiles(process.cwd(),[...dt]),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),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="",h=!1,w=W.readFileSync(l,"utf-8");try{k?(console.log(`[Lisa.ai Unit] Existing spec found for ${y}. Requesting coverage append...`),g=await Ze(y,w,D.relative(process.cwd(),$),k,t,i,p,u)):(console.log(`[Lisa.ai Unit] Generating new spec for ${y}...`),g=await ee(y,w,t,i,p,u)),je=0,h=!0}catch(L){je++,dt.add(y);let C=L.cause?.message?`${L.message} (cause: ${L.cause.message})`:L.message;if(console.error(`
|
|
179
|
+
[Lisa.ai Unit] LLM call failed for ${y} \u2014 consecutive failure #${je}/${De}`),console.error(` Error: ${C}`),je>=De)throw new Error(`Systematic LLM failure: ${De} consecutive API calls failed.
|
|
180
180
|
This usually means your API key has insufficient credits, hit a rate limit, or the model is unavailable.
|
|
181
181
|
Last error: ${C}
|
|
182
|
-
Tip: Check your API key, account credits, and rate-limit quota for provider '${t}'.`)}if(!
|
|
182
|
+
Tip: Check your API key, account credits, and rate-limit quota for provider '${t}'.`)}if(!h){await fe(e,t,s+1,n,o,i,r);return}W.writeFileSync($,g,"utf-8"),console.log(`[Lisa.ai Unit] Wrote spec to ${$}`),await R({projectId:o,type:"unit",filePath:y,modelUsed:t,status:"success",details:`### Unit Test Generated
|
|
183
183
|
**Auto-Generated Spec (${t}):**
|
|
184
184
|
\`\`\`typescript
|
|
185
185
|
${g}
|
|
186
|
-
\`\`\``,testFramework:
|
|
187
|
-
[Lisa.ai E2E] Reached maximum retries (${n}). Stopping.`);return}let
|
|
188
|
-
[Lisa.ai E2E] Framework: ${u} (Attempt ${s}/${n}) Model: ${t}`),!p.installed&&u==="playwright"&&Ce(
|
|
189
|
-
[Lisa.ai E2E] Targeting ${
|
|
186
|
+
\`\`\``,testFramework:v}),await fe(e,t,s+1,n,o,i,r)}catch(m){console.error("[Lisa.ai Unit loop failure]:",m.message),await R({projectId:o,type:"unit",filePath:"unit-loop",modelUsed:t,status:"error",details:`Unit test generation encountered an unrecoverable error: ${m.message}`,testFramework:v})}}var gt=require("child_process"),I=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(I.existsSync(i)){let a=I.readFileSync(i,"utf-8").matchAll(/path:\s*['"`]([^'"`]+)['"`]/g);for(let d of a)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(I.existsSync(i)){let a=I.readFileSync(i,"utf-8").matchAll(/path=["']([^"']+)["']/g);for(let d of a)d[1]&&t.push(d[1])}}return[...new Set(t)].sort()}async function ft(e,t,s=1,n=3,o="local",i,r){if(s>n){console.log(`
|
|
187
|
+
[Lisa.ai E2E] Reached maximum retries (${n}). Stopping.`);return}let a=process.cwd(),d=P.load(a);d&&(P.applyEnvDefaults(d),!e&&d.e2eCommand&&(e=d.e2eCommand,console.log(`[Lisa.ai Config] Using e2eCommand from .lisai.json: ${e}`)));let p=ke(a),u=d?.e2eFramework||p.framework;console.log(`
|
|
188
|
+
[Lisa.ai E2E] Framework: ${u} (Attempt ${s}/${n}) Model: ${t}`),!p.installed&&u==="playwright"&&Ce(a),e||(e=p.command,console.log(`[Lisa.ai E2E] Using auto-detected command: ${e}`)),await R({projectId:o,type:"e2e",filePath:"e2e-suite",modelUsed:t,status:"running",details:`E2E test generation started with ${u}`,testFramework:u});let v=0;if(r&&r.length>0){console.log(`
|
|
189
|
+
[Lisa.ai E2E] Targeting ${r.length} file(s) from --files`),r.forEach(x=>console.log(` - ${x}`));for(let x of r){let k=q.resolve(a,x);if(I.existsSync(k)){console.log(`[Lisa.ai E2E] Spec already exists: ${x} \u2014 will run as-is.`);continue}let $=q.dirname(k);I.existsSync($)||I.mkdirSync($,{recursive:!0}),console.log(`[Lisa.ai E2E] Generating E2E spec: ${x}...`);let g=`
|
|
190
190
|
E2E Test Generation Context:
|
|
191
191
|
- Framework: ${u}
|
|
192
192
|
- Target file: ${x}
|
|
193
|
-
- App Type: ${
|
|
193
|
+
- App Type: ${I.existsSync(q.join(a,"angular.json"))?"Angular":"Web App"}
|
|
194
194
|
- Base URL: http://localhost:4200
|
|
195
195
|
|
|
196
196
|
Generate a ${u} E2E test spec for "${x}".
|
|
@@ -201,11 +201,11 @@ The test should:
|
|
|
201
201
|
4. Assert critical UI elements are visible
|
|
202
202
|
|
|
203
203
|
Use @playwright/test imports. Keep it concise and practical.
|
|
204
|
-
`;try{let
|
|
204
|
+
`;try{let h=await ee(x,g,t,i,u,["e2e"]);I.writeFileSync(k,h,"utf-8"),console.log(`[Lisa.ai E2E] Wrote ${x}`),v++,await R({projectId:o,type:"e2e",filePath:x,modelUsed:t,status:"success",details:`Generated E2E spec: ${x}`,testFramework:u})}catch(h){console.error(`[Lisa.ai E2E] LLM failed for ${x}: ${h.message}`),await R({projectId:o,type:"e2e",filePath:x,modelUsed:t,status:"error",details:`LLM failed to generate E2E spec: ${h.message}`,testFramework:u})}}if(v===0&&r.every(x=>!I.existsSync(q.resolve(a,x)))){console.log("[Lisa.ai E2E] No specs generated. Check LLM connectivity with 'lisa-agent diagnose'.");return}}else{let x=Ot(a);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(a,"e2e");I.existsSync(k)||I.mkdirSync(k,{recursive:!0});let $=I.existsSync(k)?I.readdirSync(k).filter(g=>g.endsWith(".spec.ts")||g.endsWith(".test.ts")):[];for(let g of x){let w=`${(g||"home").replace(/\//g,"-")}.spec.ts`,L=q.join(k,w);if($.includes(w)){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=`
|
|
205
205
|
E2E Test Generation Context:
|
|
206
206
|
- Framework: ${u}
|
|
207
207
|
- Route: /${g}
|
|
208
|
-
- App Type: ${
|
|
208
|
+
- App Type: ${I.existsSync(q.join(a,"angular.json"))?"Angular":"Web App"}
|
|
209
209
|
- Base URL: http://localhost:4200
|
|
210
210
|
|
|
211
211
|
Generate a ${u} E2E test spec for the route "/${g}".
|
|
@@ -216,15 +216,15 @@ The test should:
|
|
|
216
216
|
4. Assert critical UI elements are visible
|
|
217
217
|
|
|
218
218
|
Use @playwright/test imports. Keep it concise and practical.
|
|
219
|
-
`,F=await ee(`e2e/${
|
|
220
|
-
[Lisa.ai E2E] Running E2E tests: ${e}`);let
|
|
219
|
+
`,F=await ee(`e2e/${w}`,C,t,i,u,["e2e"]);I.writeFileSync(L,F,"utf-8"),console.log(`[Lisa.ai E2E] Wrote ${w}`),v++,await R({projectId:o,type:"e2e",filePath:`e2e/${w}`,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 R({projectId:o,type:"e2e",filePath:`e2e/${w}`,modelUsed:t,status:"error",details:`LLM failed to generate E2E spec: ${C.message}`,testFramework:u})}}if(v===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 f="",m="",y=!1;try{await new Promise((x,k)=>{let $=(0,gt.spawn)(e,{shell:!0,stdio:["ignore","pipe","pipe"],cwd:a});$.stdout?.on("data",g=>{let h=g.toString();f+=h,process.stdout.write(h)}),$.stderr?.on("data",g=>{let h=g.toString();m+=h,process.stderr.write(h)}),$.on("close",g=>{g===0?x():k(new Error(`E2E tests exited with code ${g}`))})}),y=!0,console.log(`
|
|
221
221
|
[Lisa.ai E2E] All E2E tests passed.`)}catch{console.log(`
|
|
222
|
-
[Lisa.ai E2E] Some E2E tests failed. Run 'lisa-agent heal --type e2e' to auto-fix.`)}let l=
|
|
223
|
-
`+
|
|
224
|
-
[Lisa.ai Integration] Reached maximum retries (${n}). Stopping.`);return}let
|
|
225
|
-
[Lisa.ai Integration] App: ${p}, Framework: ${
|
|
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
|
|
227
|
-
[Lisa.ai Integration] Targeting ${
|
|
222
|
+
[Lisa.ai E2E] Some E2E tests failed. Run 'lisa-agent heal --type e2e' to auto-fix.`)}let l=f+`
|
|
223
|
+
`+m,c=Z(l);await R({projectId:o,type:"e2e",filePath:"e2e-suite",modelUsed:t,status:y?"success":"error",details:`E2E generation complete. ${v} 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")),E=b(require("path"));function Gt(e){let t=E.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=E.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 r=A.readFileSync(i,"utf-8");if(r.includes("@Component")&&r.includes("inject(")){let a=E.relative(e,i),d=a.replace(/\.ts$/,".integration.spec.ts");if(A.existsSync(E.join(e,d)))continue;let u=[...r.matchAll(/inject\((\w+)\)/g)].map(f=>f[1]),v=[];for(let f of u){let m=me(n,new RegExp(`${qt(f)}\\.ts$`));v.push(...m.map(y=>E.relative(e,y)))}s.push({filePath:a,relatedFiles:v,description:`Angular component+service integration: ${E.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=E.join(e,o);if(!A.existsSync(i))continue;let r=me(i,/\.(controller|route|router)\.(ts|js)$/).filter(a=>!a.includes(".spec.")&&!a.includes(".test.")&&!a.includes("node_modules"));for(let a of r){let d=E.relative(e,a),p=d.replace(/\.(ts|js)$/,".integration.spec.$1");A.existsSync(E.join(e,p))||s.push({filePath:d,relatedFiles:[],description:`API endpoint integration test for ${E.basename(a)} \u2014 test with supertest against real middleware chain`})}}}else{let n=E.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 a=[...A.readFileSync(i,"utf-8").matchAll(/from\s+['"]\.\.?\//g)];if(a.length>=2){let d=E.relative(e,i),p=d.replace(/\.(ts|js|tsx|jsx)$/,".integration.spec.$1");if(A.existsSync(E.join(e,p)))continue;s.push({filePath:d,relatedFiles:[],description:`Module integration: ${E.basename(i)} imports ${a.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 r=E.join(e,i);try{A.statSync(r).isDirectory()?s.push(...me(r,t)):t.test(i)&&s.push(r)}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,r){if(s>n){console.log(`
|
|
224
|
+
[Lisa.ai Integration] Reached maximum retries (${n}). Stopping.`);return}let a=process.cwd(),d=P.load(a);d&&(P.applyEnvDefaults(d),!e&&d.testCommand&&(e=d.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${e}`)));let p=Gt(a),u=V.scanRepository(),v=d?.testingFramework||(u.testingFramework!=="none"?u.testingFramework:void 0);console.log(`
|
|
225
|
+
[Lisa.ai Integration] App: ${p}, Framework: ${v||"auto"} (Attempt ${s}/${n}) Model: ${t}`),e||(u.suggestedTestCommand?e=u.suggestedTestCommand:A.existsSync(E.join(a,"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 f=le(e);await R({projectId:o,type:"integration",filePath:"integration-suite",modelUsed:t,status:"running",details:`Integration test generation started for ${p} app`,testFramework:f});let m;if(r&&r.length>0)m=r.map(g=>({filePath:g,relatedFiles:[],description:"User-specified"})),console.log(`
|
|
227
|
+
[Lisa.ai Integration] Targeting ${r.length} file(s) from --files`),m.forEach(g=>console.log(` - ${g.filePath}`));else{if(m=Ht(a,p),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(g=>console.log(` - ${g.filePath}: ${g.description}`))}let y=0;for(let g of m){let h=E.resolve(a,g.filePath);if(!A.existsSync(h))continue;let w=E.parse(h),L=E.join(w.dir,`${w.name}.integration.spec${w.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(h,"utf-8"),F="";for(let M of g.relatedFiles.slice(0,3)){let j=E.resolve(a,M);if(A.existsSync(j)){let U=A.readFileSync(j,"utf-8");F+=`
|
|
228
228
|
|
|
229
229
|
// --- Related file: ${M} ---
|
|
230
230
|
${U.slice(0,5e3)}`}}let G=`
|
|
@@ -251,23 +251,23 @@ ${C.slice(0,1e4)}
|
|
|
251
251
|
|
|
252
252
|
${F?`Related modules:
|
|
253
253
|
${F}`:""}
|
|
254
|
-
`;try{let M=await ee(g.filePath,G,t,i,
|
|
255
|
-
[Lisa.ai Integration] Running tests to verify generated specs: ${e}`);let l="",c="",x=!1;try{await new Promise((g,
|
|
254
|
+
`;try{let M=await ee(g.filePath,G,t,i,v,["integration"]);A.writeFileSync(L,M,"utf-8"),console.log(`[Lisa.ai Integration] Wrote ${E.relative(a,L)}`),y++,await R({projectId:o,type:"integration",filePath:g.filePath,modelUsed:t,status:"success",details:`Generated integration spec: ${g.description}`,testFramework:f})}catch(M){console.error(`[Lisa.ai Integration] LLM failed for ${g.filePath}: ${M.message}`)}}if(y===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,h)=>{let w=(0,mt.spawn)(e,{shell:!0,stdio:["ignore","pipe","pipe"],cwd:a});w.stdout?.on("data",L=>{let C=L.toString();l+=C,process.stdout.write(C)}),w.stderr?.on("data",L=>{let C=L.toString();c+=C,process.stderr.write(C)}),w.on("close",L=>{L===0?g():h(new Error(`Tests exited with code ${L}`))})}),x=!0,console.log(`
|
|
256
256
|
[Lisa.ai Integration] All tests passed including integration specs.`)}catch{console.log(`
|
|
257
257
|
[Lisa.ai Integration] Some tests failed. Run 'lisa-agent heal --type integration' to auto-fix.`)}let k=l+`
|
|
258
|
-
`+c,$=Z(k);await
|
|
258
|
+
`+c,$=Z(k);await R({projectId:o,type:"integration",filePath:"integration-suite",modelUsed:t,status:x?"success":"error",details:`Integration test generation complete. ${y} new spec(s) generated.`,...$&&{testTotal:$.total,testPassed:$.passed,testFailed:$.failed},testFramework:f})}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
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
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
|
|
262
|
-
Vulnerabilities found:`),wt(
|
|
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
|
|
264
|
-
`)){let U=
|
|
265
|
-
\u2705 [Lisa.ai Audit] All vulnerabilities fixed by safe auto-fix!`);return}let
|
|
266
|
-
[Lisa.ai Audit] Safe auto-fix resolved ${l} vulnerability(-ies).`),
|
|
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:
|
|
268
|
-
\u2705 [Lisa.ai Audit] All vulnerabilities resolved!`);return}}let{stdout:k}=await ce(p),$=await Ue(k)??h
|
|
261
|
+
\u2705 [Lisa.ai Audit] No vulnerabilities found! Repository is clean.`);return}let r=await Ue(o);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(`
|
|
262
|
+
Vulnerabilities found:`),wt(a),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 j of d.split(`
|
|
264
|
+
`)){let U=j.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:v}=await ce(p);if(v===0){console.log(`
|
|
265
|
+
\u2705 [Lisa.ai Audit] All vulnerabilities fixed by safe auto-fix!`);return}let f=await Ue(u);if(!f){console.warn("[Lisa.ai Audit] Could not parse post-fix audit output.");return}let m=Object.values(f.vulnerabilities),y=f.metadata.vulnerabilities,l=a.total-y.total;console.log(`
|
|
266
|
+
[Lisa.ai Audit] Safe auto-fix resolved ${l} vulnerability(-ies).`),y.total>0&&(console.log(" Remaining:"),wt(y));let c=m.filter(j=>typeof j.fixAvailable=="object"&&!j.fixAvailable.isSemVerMajor).map(j=>j.fixAvailable),x=[...new Map(c.map(j=>[j.name,j])).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:j,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)??f,h=Object.values($.vulnerabilities).sort((j,U)=>(yt[U.severity]??0)-(yt[j.severity]??0)).slice(0,10).filter(j=>j.fixAvailable===!1?!0:typeof j.fixAvailable=="object"?j.fixAvailable.isSemVerMajor:!1);if(h.length===0){console.log(`
|
|
269
269
|
\u2705 [Lisa.ai Audit] No breaking-change or unfixable vulnerabilities remain.`);return}console.log(`
|
|
270
|
-
[Lisa.ai Audit] ${
|
|
270
|
+
[Lisa.ai Audit] ${h.length} vulnerability(-ies) require manual attention.`),console.log(`[Lisa.ai Audit] Consulting ${e} for remediation guidance...`);let w={};try{w=JSON.parse(Q.readFileSync(J.resolve(process.cwd(),"package.json"),"utf8"))}catch{}let L={...w.dependencies??{},...w.devDependencies??{}},C=h.map(j=>{let U=j.fixAvailable,oe=U===!1?"no fix available yet":`upgrade to ${U.name}@${U.version} (BREAKING \u2014 major version bump)`,B=L[j.name]?`current: ${L[j.name]}`:"transitive dependency";return`\u2022 ${j.name} (${j.severity}) \u2014 ${B} \u2014 ${oe}`}).join(`
|
|
271
271
|
`),F=`You are a Node.js security expert helping a developer fix npm vulnerabilities.
|
|
272
272
|
|
|
273
273
|
These vulnerabilities remain after safe auto-fixes were applied. Each requires either a breaking upgrade or has no automated fix:
|
|
@@ -280,33 +280,33 @@ For each vulnerability:
|
|
|
280
280
|
3. If the upgrade is breaking (major version), note the most likely code change needed (e.g. renamed API, changed import path).
|
|
281
281
|
4. If no fix exists, suggest a workaround or safe alternative package.
|
|
282
282
|
|
|
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
|
|
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 j=await ie(F,e,s);console.log(`
|
|
284
284
|
Remediation guidance:
|
|
285
|
-
`);for(let B of
|
|
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: ${
|
|
285
|
+
`);for(let B of j.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: ${w.name??J.basename(process.cwd())}`,"","## Summary","","| Severity | Initial | Remaining |","|----------|---------|-----------|",...["critical","high","moderate","low"].map(B=>{let ue=a[B]??0,bt=$.metadata.vulnerabilities[B]??0;return`| ${B} | ${ue} | ${bt} |`}),"","## Vulnerabilities Requiring Manual Action","",C,"",`## Remediation Guidance (${e})`,"",j].join(`
|
|
287
287
|
`);Q.writeFileSync(U,oe,"utf-8"),console.log(`
|
|
288
|
-
[Lisa.ai Audit] Full report saved to: lisa-audit-report.md`)}catch(
|
|
289
|
-
[Lisa.ai Audit] LLM guidance failed: ${
|
|
290
|
-
${"\u2500".repeat(50)}`),console.log(" Lisa.ai Audit Complete"),console.log(` \u2705 Fixed: ${M} / ${
|
|
288
|
+
[Lisa.ai Audit] Full report saved to: lisa-audit-report.md`)}catch(j){console.error(`
|
|
289
|
+
[Lisa.ai Audit] LLM guidance failed: ${j.message}`),console.log(" Run 'npm audit' manually and address the remaining vulnerabilities.")}let G=$.metadata.vulnerabilities,M=a.total-G.total;console.log(`
|
|
290
|
+
${"\u2500".repeat(50)}`),console.log(" Lisa.ai Audit Complete"),console.log(` \u2705 Fixed: ${M} / ${a.total}`),console.log(` \u26A0\uFE0F Remaining: ${G.total} (see lisa-audit-report.md)`),console.log(`${"\u2500".repeat(50)}
|
|
291
291
|
`)}var St=Lt();function ne(){let e=St.version;console.log(`
|
|
292
292
|
\x1B[38;2;99;102;241m\u2554\u2550\u2557\x1B[0m \x1B[1mLisa.ai Agent\x1B[0m v${e}
|
|
293
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
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
|
|
296
|
-
[Lisa.ai Agent Error] Project '${
|
|
297
|
-
[Lisa.ai Warning] Control Plane is unreachable. Continuing with local CLI defaults (model=${s}, maxRetries=${t}).`);else{let a=
|
|
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))}}
|
|
299
|
-
[Lisa.ai Error] Invalid heal type '${e.type}'. Valid types: ${t.join(", ")}`),process.exit(1));let n=e.files?e.files.split(",").map(
|
|
300
|
-
[Lisa.ai Diagnose] Testing ${t} \u2192 model ID: ${
|
|
301
|
-
[Lisa.ai Diagnose] ${t} is working correctly.`),console.log(` Model response: "${
|
|
302
|
-
[Lisa.ai Diagnose] ${t} call FAILED.`),console.error(` Error: ${
|
|
295
|
+
`)}async function Ee(e){let t=5,s=e.model,n,o=P.load(process.cwd()),i=e.projectId||o?.projectId||"local";if(i!=="local"){let r=await ye(i);if(!r.ok)r.reason==="not_found"?(console.error(`
|
|
296
|
+
[Lisa.ai Agent Error] Project '${i}' 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=r.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))}}return o&&(P.applyEnvDefaults(o),!e.projectId&&!o.projectId&&o.maxRetries!==void 0&&(t=o.maxRetries),!e.projectId&&!o.projectId&&o.provider&&e.model==="gemini"&&(s=o.provider),P.printSummary(o)),{model:s,maxRetries:t,apiKey:n,projectId:i}}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(r=>r.trim()):void 0,o=e.ci===!0,i=await Ee(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 Ee(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 Ee(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 Ee(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,n=P.load(process.cwd()),o=e.projectId||n?.projectId||"local";if(o!=="local"){let a=await ye(o);a.ok?(t=a.config.modelProvider,s=a.config.apiKey,console.log(`[Lisa.ai Diagnose] Config fetched from Control Plane. Provider=${t}`)):console.warn(`[Lisa.ai Diagnose] Control Plane ${a.reason}. Using local env for API key.`)}let r={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: ${r}`);try{let a=await ie("Reply with exactly: LISA_OK",t,s);console.log(`
|
|
301
|
+
[Lisa.ai Diagnose] ${t} is working correctly.`),console.log(` Model response: "${a}"`)}catch(a){console.error(`
|
|
302
|
+
[Lisa.ai Diagnose] ${t} call FAILED.`),console.error(` Error: ${a.message}`),a.cause&&console.error(` Cause: ${a.cause?.message??a.cause}`),console.error(`
|
|
303
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=(
|
|
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=(m,y="")=>new Promise(l=>s.question(y?`${m} [${y}]: `:`${m}: `,c=>l(c.trim()||y)));console.log(`
|
|
305
305
|
Lisa.ai Project Setup \u2014 press Enter to accept the default shown in [ ]
|
|
306
|
-
`);let o=await n("LLM provider (gemini / claude / openai)","gemini"),
|
|
306
|
+
`);let o=await n("Control Plane project ID (leave empty for local-only mode)",""),i=await n("LLM provider (gemini / claude / openai)","gemini"),r=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)",""),d=await n("Test types to generate (unit / integration / e2e \u2014 comma-separated)","unit"),p=await n("Test command (leave empty for auto-discovery)",""),u=await n("E2E command (leave empty for auto-discovery)",""),v=await n("Max heal retries","5");s.close();let f={...o?{projectId:o}:{},provider:i,testTypes:d.split(",").map(m=>m.trim()).filter(Boolean),maxRetries:parseInt(v,10)||5,skipFiles:[],skipDirs:[],skipPaths:[]};r&&(f.testingFramework=r),a&&(f.e2eFramework=a),p&&(f.testCommand=p),u&&(f.e2eCommand=u),X.writeFileSync(t,JSON.stringify(f,null,2)+`
|
|
307
307
|
`,"utf-8"),console.log(`
|
|
308
308
|
Created ${te}:
|
|
309
|
-
`),console.log(JSON.stringify(
|
|
309
|
+
`),console.log(JSON.stringify(f,null,2)),console.log(`
|
|
310
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.
|
|
311
311
|
`)});function Kt(e,t){return`# Lisa.ai Auto-Heal Workflow
|
|
312
312
|
# Generated by: lisa-agent init-ci
|
|
@@ -350,8 +350,8 @@ jobs:
|
|
|
350
350
|
GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
|
|
351
351
|
run: lisa-agent heal --model ${e} --ci
|
|
352
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",
|
|
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",r=Kt(o,i);X.mkdirSync(t,{recursive:!0}),X.writeFileSync(s,r,"utf-8"),console.log(`
|
|
354
354
|
Created: .github/workflows/lisa-heal.yml`),console.log(`
|
|
355
355
|
Required repository secret: ${i}`),console.log(" Set it in: GitHub repo > Settings > Secrets and variables > Actions"),console.log(`
|
|
356
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
|
|
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,n=P.load(process.cwd()),o=e.projectId||n?.projectId||"local";if(o!=="local"){let i=await ye(o);i.ok?(t=i.config.modelProvider,s=i.config.apiKey,console.log(`[Lisa.ai Audit] Config fetched from Control Plane. Provider=${t}`)):console.warn(`[Lisa.ai Audit] Control Plane ${i.reason}. Using local env for API key.`)}await $t(t,o,s)});K.parse(process.argv);
|