@lisa.ai/agent 2.6.2 → 2.6.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 +93 -89
- 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 ze=Object.create;var pe=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Qe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Xe=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ke(e))!Ve.call(t,o)&&o!==s&&pe(t,o,{get:()=>e[o],enumerable:!(n=Ze(e,o))||n.enumerable});return t};var k=(t,e,s)=>(s=t!=null?ze(Je(t)):{},Xe(e||!t||!t.__esModule?pe(s,"default",{value:t,enumerable:!0}):s,t));var He=Qe((Yt,it)=>{it.exports={name:"@lisa.ai/agent",version:"2.6.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 Ge=require("commander"),te=k(require("fs")),qe=k(require("path")),Be=k(require("readline"));var fe=k(require("dotenv"));fe.config({quiet:!0});async function Y(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 i=n.status===404?"not_found":"unreachable";return console.warn(i==="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:i}}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 De=require("child_process"),F=k(require("fs")),I=k(require("path"));var C=k(require("path")),S=k(require("fs"));function se(t,e=process.cwd(),s=[]){let n=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),o=s.map(u=>C.resolve(e,u)),i=new Map,r=new Set,l=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,p;for(;(p=l.exec(n))!==null;){let a=p[1].trim().split(" ");for(let m=1;m<Math.min(a.length,6);m++){let w=a.slice(0,m).join(" ");if(r.has(w))continue;r.add(w);let c=ne(w,e,o);if(c){let v=C.resolve(c);i.has(v)||i.set(v,C.relative(e,c));break}}}let d=/^FAIL\s+([a-zA-Z0-9_./-\\]+\.(?:spec|test)\.(ts|tsx|js|jsx))/gm,g;for(;(g=d.exec(n))!==null;){let u=g[1],a=C.isAbsolute(u)?u:C.resolve(e,u);!o.includes(a)&&S.existsSync(a)&&!i.has(a)&&i.set(a,C.relative(e,a))}return[...i.values()]}function W(t,e=[],s=process.cwd()){let n=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),o=e.map(c=>C.resolve(c));{let c=/(?:Chrome|Firefox|Safari)(?:\s+Headless)?\s+[\d.]+(?:\s+[\d.]+)*\s+\([^)]+\)\s+(.+?)\s+FAILED/g,v=new Set,f;for(;(f=c.exec(n))!==null;){let y=f[1].trim().split(" ");for(let $=1;$<Math.min(y.length,5);$++){let L=y.slice(0,$).join(" ");if(v.has(L))continue;v.add(L);let x=ne(L,s,o);if(x)return C.relative(s,x)}}}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 c=r[1];if(c){if(/(?:^|[/\\])(node_modules|dist|build)[/\\]/.test(c))continue;let v=C.isAbsolute(c)?c:C.resolve(s,c);if(!o.includes(v)&&S.existsSync(v))return c}}let l=/FAIL\s+([a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/gi,p;for(;(p=l.exec(n))!==null;){let c=p[1],v=C.isAbsolute(c)?c:C.resolve(s,c);if(!o.includes(v)&&S.existsSync(v))return c}let d=/([a-zA-Z]:[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue)|[a-zA-Z0-9_.\-\/\\]+\.(?:ts|tsx|js|jsx|vue))/g,g;for(;(g=d.exec(n))!==null;){let c=g[1];if(c){if(/(?:^|[/\\])(node_modules|dist|build)[/\\]/.test(c))continue;let v=C.isAbsolute(c)?c:C.resolve(s,c);if(!o.includes(v)&&S.existsSync(v))return c}}let u=/\b([A-Z][a-zA-Z0-9]{3,})\b/g,a,m=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(;(a=u.exec(n))!==null;){let c=a[1];if(!c||w.includes(c)||m.has(c)||/^[A-Z][A-Z0-9]{5,11}$/.test(c)||/^[A-Za-z0-9]{16,}$/.test(c))continue;m.add(c);let v=me(c,s,o);if(v)return C.relative(s,v)}return null}function ne(t,e,s){if(!S.existsSync(e))return null;let n=S.readdirSync(e);for(let o of n){let i=C.join(e,o);if(["node_modules","dist","build",".git",".angular"].includes(o))continue;let r;try{r=S.statSync(i)}catch{continue}if(r.isDirectory()){let l=ne(t,i,s);if(l)return l}else if(/\.(spec|test)\.(ts|tsx|js|jsx)$/.test(o)){if(s.includes(C.resolve(i)))continue;try{let l=S.readFileSync(i,"utf8");if(l.includes(`describe('${t}'`)||l.includes(`describe("${t}"`))return i}catch{continue}}}return null}function me(t,e,s){if(!S.existsSync(e))return null;let n=S.readdirSync(e);for(let o of n){let i=C.join(e,o);if(o==="node_modules"||o==="dist"||o==="build"||o===".git"||o===".angular")continue;let r;try{r=S.statSync(i)}catch{continue}if(r.isDirectory()){let l=me(t,i,s);if(l)return l}else if(o.match(/\.(ts|tsx|js|jsx|vue)$/)){let l=S.readFileSync(i,"utf8");if(l.includes(`class ${t}`)||l.includes(`function ${t}`)||l.includes(`const ${t}`)||l.includes(`let ${t}`)||l.includes(`exports.${t}`)||l.includes(`module.exports.${t}`)){let p=i,d=C.extname(i),g=i.slice(0,-d.length);if(!o.includes(".spec.")&&!o.includes(".test.")){let u=[`${g}.spec${d}`,`${g}.test${d}`,`${g}.spec.js`,`${g}.test.js`];for(let a of u)if(S.existsSync(a)){p=a;break}}if(!s.includes(C.resolve(p)))return p}}}return null}var q=require("ai"),he=require("@ai-sdk/openai"),ye=require("@ai-sdk/anthropic"),ve=require("@ai-sdk/google"),we=k(require("dotenv"));we.config({quiet:!0});var oe=15e3;function Le(t,e){return t.length<=oe?t:(console.warn(`[Lisa.ai LLM] ${e} is ${t.length} chars \u2014 truncating to ${oe} to stay within context window.`),t.slice(0,oe)+`
|
|
3
3
|
|
|
4
|
-
// ... (truncated)`)}function
|
|
5
|
-
${t.map(
|
|
4
|
+
// ... (truncated)`)}function xe(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 Ce(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(`
|
|
6
6
|
`)}
|
|
7
|
-
`}function
|
|
7
|
+
`}function z(t,e){if(t==="claude"){let o=e||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,ye.createAnthropic)({apiKey:o})(i)}if(t==="openai"){let o=e||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=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,ve.createGoogleGenerativeAI)({apiKey:s})(n)}async function $e(t,e,s,n,o,i,r,l){console.log(`[Lisa.ai Auto-Heal] Requesting fix from ${n} for ${t}...`);let p=z(n,o),d=`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,58 +21,58 @@ 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
|
|
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+)/),w=m?m[1]:"the component";d+=`
|
|
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 `+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."}d+=`
|
|
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}l&&l.length>0&&(
|
|
34
|
+
`+r}l&&l.length>0&&(d+=`
|
|
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
|
-
`+l.map((
|
|
39
|
-
[Pattern ${
|
|
40
|
-
${
|
|
41
|
-
`)),i&&(console.log(`[Lisa.ai Auto-Heal] Warning! Agent is looping on ${t}. Injecting previous failed context...`),
|
|
38
|
+
`+l.map((a,m)=>`
|
|
39
|
+
[Pattern ${m+1}]
|
|
40
|
+
${a}`).join(`
|
|
41
|
+
`)),i&&(console.log(`[Lisa.ai Auto-Heal] Warning! Agent is looping on ${t}. Injecting previous failed context...`),d+=`
|
|
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
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:
|
|
48
|
+
DO NOT repeat the identical code changes. Try a completely different programming approach, fix syntax typos, or check for missing imports.`);let{text:g}=await(0,q.generateText)({model:p,prompt:d}),u=g.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return u?u[1].trim():g.trim()}async function ke(t,e,s,n,o,i){console.log(`[Lisa.ai Coverage] Requesting test generation from ${s} for ${t}...`);let r=z(s,n),l=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
|
+
`,p=Ce(i),d=`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 (`+t+`) ---
|
|
54
|
-
`+
|
|
55
|
-
`+
|
|
54
|
+
`+Le(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"+l+`4. Aim for 100% logic coverage.
|
|
55
|
+
`+p,{text:g}=await(0,q.generateText)({model:r,prompt:d}),u=g.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),a=u?u[1].trim():g.trim();return xe(a,t),a}async function Ae(t,e,s,n,o,i,r,l){console.log(`[Lisa.ai Coverage] Requesting test update from ${o} for ${t}...`);let p=z(o,i),d=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
|
-
`,
|
|
57
|
+
`,g=Ce(l),u=`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 (`+t+`) ---
|
|
61
|
-
`+
|
|
61
|
+
`+Le(e,t)+`
|
|
62
62
|
|
|
63
63
|
--- Existing Test Suite (`+s+`) ---
|
|
64
|
-
`+
|
|
65
|
-
`+
|
|
66
|
-
[Lisa.ai PR Engine] Initializing Pull Request for ${t}...`);let e=(0,
|
|
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"+d+`4. Aim for 100% logic coverage across branches, lines, and functions.
|
|
65
|
+
`+g,{text:a}=await(0,q.generateText)({model:p,prompt:u}),m=a.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/),w=m?m[1].trim():a.trim();return xe(w,t),w}async function Z(t,e,s){let n=z(e,s),{text:o}=await(0,q.generateText)({model:n,prompt:t}),i=o.match(/```(?:typescript|ts|javascript|js)?\n([\s\S]*?)```/);return i?i[1].trim():o.trim()}var Se=k(require("simple-git")),je=require("@octokit/rest"),dt=require("dotenv/config");async function ie(t){console.log(`
|
|
66
|
+
[Lisa.ai PR Engine] Initializing Pull Request for ${t}...`);let e=(0,Se.default)(),n=`lisa-fix/build-error-${new Date().getTime()}`,o=`fix: automated auto-heal by Lisa.ai for ${t}`,i="main";try{i=(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(o),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}),l=process.env.GITHUB_REPOSITORY;if(l&&process.env.GITHUB_TOKEN){let[p,d]=l.split("/");console.log(`[Lisa.ai PR Engine] Opening Pull Request against ${p}/${d}...`);let g=await r.rest.pulls.create({owner:p,repo:d,title:o,body:`### Lisa.ai Auto-Healed Pull Request
|
|
67
67
|
This PR was automatically generated by Lisa.ai to resolve a failing compilation/build step.
|
|
68
68
|
|
|
69
69
|
**Healed File:** \`${t}\`
|
|
70
70
|
|
|
71
|
-
Please review the changes.`,head:
|
|
72
|
-
\u{1F6A8} [Lisa.ai PR Engine Error] Failed to create Pull Request:`,r.message)}finally{try{await e.checkout(i)}catch{}}}var
|
|
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
|
|
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=
|
|
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(
|
|
71
|
+
Please review the changes.`,head:n,base:i});console.log(`\u2705 [Lisa.ai PR Engine] Pull Request created successfully: ${g.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(i)}catch{}}}var be=k(require("dotenv"));be.config({quiet:!0});async function P(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 T=k(require("fs")),E=k(require("path"));var K=k(require("fs")),Ee=k(require("path")),O=".lisai.json",j=class{static _config=null;static _loaded=!1;static load(e=process.cwd()){if(this._loaded)return this._config;this._loaded=!0;let s=Ee.resolve(e,O);if(!K.existsSync(s))return null;try{let n=K.readFileSync(s,"utf-8");return this._config=JSON.parse(n),console.log(`[Lisa.ai Config] Loaded project config from ${O}`),this._config}catch(n){return console.warn(`[Lisa.ai Config] Warning: ${O} 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}"`),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 N=class{static scanRepository(e=process.cwd()){let s=E.resolve(e,"package.json"),n={type:"unknown",testingFramework:"none"};if(!T.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(T.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"&&(r.test?n.suggestedTestCommand="npm run test":n.testingFramework==="karma"?n.suggestedTestCommand="npx karma start":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(!T.existsSync(e))return n;let o=T.readdirSync(e),i=j.get(),r=i?.skipDirs??[],l=i?.skipFiles??[],p=i?.skipPaths??[],d=["node_modules","dist","build",".git",".angular","coverage","public","assets",...r],g=["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"],u=[/^\./,/\.config\.(js|ts|mjs|cjs)$/,/\.conf\.(js|ts|mjs|cjs)$/];for(let a of o){let m=E.join(e,a);if(d.includes(a))continue;let w;try{w=T.statSync(m)}catch{continue}if(w.isDirectory())n.push(...this.findUntestedFiles(m,s));else if(a.match(/\.(ts|tsx|js|jsx|vue)$/)&&!a.includes(".spec.")&&!a.includes(".test.")){if(g.includes(a)||l.includes(a)||u.some(y=>y.test(a)))continue;let c=E.extname(a),v=a.slice(0,-c.length);if(![E.join(e,`${v}.spec${c}`),E.join(e,`${v}.test${c}`),E.join(e,`${v}.spec.js`),E.join(e,`${v}.test.js`),E.join(e,`${v}.spec.ts`),E.join(e,`${v}.test.ts`)].some(y=>T.existsSync(y))){let y=E.relative(process.cwd(),m);if(p.some($=>y.startsWith($)))continue;s.includes(y)||n.push(y)}}}return n}};var Fe=require("child_process"),_=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="",o="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",o="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",o="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",o="vitest",e.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,Fe.spawnSync)(r,i.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=o,e}return e}};var J=k(require("fs")),re=k(require("path"));var U=class{static async provisionConfigurationFiles(e,s,n,o=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(p=>J.existsSync(re.join(o,p)))){console.log("[Lisa.ai Auto-Generator] Setup file detected. Bypassing initialization.");return}let l=`You are an expert ${e.type} architect.
|
|
76
76
|
Write a production-ready '${e.testingFramework}' configuration file for a standard '${e.type}' application.
|
|
77
77
|
The application resides in the root directory.
|
|
78
78
|
|
|
@@ -80,86 +80,90 @@ Requirements:
|
|
|
80
80
|
1. Ensure it specifically instruments code coverage.
|
|
81
81
|
2. Ensure standard transpilation (ts-jest for jest, or standard karma-webpack/karma-typescript implementations).
|
|
82
82
|
3. Do NOT wrap your response in markdown formatting (no \`\`\`javascript).
|
|
83
|
-
4. Return ONLY the raw code string block.`;try{let
|
|
84
|
-
\u274C [Lisa.ai Auto-Generator] Failed to author configuration file: ${
|
|
85
|
-
`)){let n
|
|
86
|
-
|
|
87
|
-
\
|
|
88
|
-
|
|
89
|
-
`)){let
|
|
90
|
-
|
|
91
|
-
\u2705 [Lisa.ai Success] Global Command executed successfully.`),o&&await De(o);return}catch(p){process.stdout.write(`
|
|
92
|
-
`),console.log("\u274C [Lisa.ai Failure] Global Command failed.");let v=(p.stderr||"")+`
|
|
93
|
-
`+(p.stdout||"")+`
|
|
94
|
-
`+(p.message||""),a=gt(v),h=Be(v);if(h){console.log(`
|
|
95
|
-
${h}`);let P=qe(v,10);if(P.length>0){let T=a?.failed??P.length;console.log(` Failing (${T}):`),P.forEach(S=>console.log(` \u2717 ${S}`)),T>P.length&&console.log(` ... and ${T-P.length} more`)}}(re>0||ae>0)&&console.log(` Session: ${re} healed ${ae} quarantined`),console.log(`
|
|
96
|
-
[Lisa.ai Auto-Heal] Analyzing errors...`);let u=ee(v,d,process.cwd());u||(console.error(`
|
|
97
|
-
\u{1F6A8} [Lisa.ai Error] Could not parse a valid failing file path from the logs (or all were explicitly skipped).`),process.exit(1));let y=H.resolve(process.cwd(),u);I.existsSync(y)||(console.error(`
|
|
98
|
-
\u{1F6A8} [Lisa.ai Error] Extracted file path does not exist: ${y}`),process.exit(1)),/[\\/](node_modules|dist|build)[\\/]/.test(y)&&(console.error(`
|
|
99
|
-
\u{1F6A8} [Lisa.ai Error] Refusing to modify a library file outside the project source: ${y}`),process.exit(1));let L=m[u]||0;if(L>=ie){console.warn(`
|
|
100
|
-
[Lisa.ai Auto-Heal] \u26A0\uFE0F ${u} has failed globally ${L} time(s) \u2014 exceeds threshold of ${ie}. Permanently skipping.`),d.push(u),await Y(t,e,1,null,n,i,void 0,l,d,0,m);return}console.log(`[Lisa.ai Auto-Heal] Identified bleeding file: ${u} (global fail count: ${L}/${ie})`);let x=1,k=!1,w=v,E,z="",Z="",ve=ft(t,u),tt=pt(y),K=Ue(t),de=(await He(v,K,i)).filter(P=>P.confidence>=.5).map(P=>P.fixHint);for(de.length>0&&console.log(`[Lisa.ai Memory] Found ${de.length} proven fix pattern(s) from Control Plane \u2014 injecting as LLM hint.`),await D({projectId:i,type:"heal",filePath:u,modelUsed:e,status:"running",details:"Agent is currently analyzing and applying patches...",...a&&{testTotal:a.total,testPassed:a.passed,testFailed:a.failed},testFramework:K});x<=n&&!k;){console.log(`
|
|
101
|
-
[Lisa.ai Micro-Heal] Isolating ${u} (Attempt ${x}/${n})`);let P=I.readFileSync(y,"utf-8"),T;for(let S=0;S<=3;S++)try{T=await Pe(u,P,w,e,l,E,tt,de);break}catch(O){let G=(O?.lastError??O)?.statusCode;if((G===529||G===500)&&S<3){let _=30*(S+1);console.warn(`
|
|
102
|
-
\u26A0\uFE0F [Lisa.ai LLM] API overloaded (HTTP ${G}). Waiting ${_}s before retry (${S+1}/3)...`),await new Promise(J=>setTimeout(J,_*1e3))}else{let _=O?.message??String(O);console.error(`
|
|
103
|
-
\u{1F6A8} [Lisa.ai LLM Error] API call failed for ${u}: ${_}`),console.warn("[Lisa.ai LLM Error] All retries exhausted \u2014 skipping this file for the current run.");break}}if(T===void 0)break;I.writeFileSync(y,T,"utf-8"),console.log(`[Lisa.ai Micro-Heal] Applied isolated patch to ${u}`),z=`### Auto-Heal Analysis Triggered
|
|
104
|
-
**Caught Error:**
|
|
83
|
+
4. Return ONLY the raw code string block.`;try{let p=await Z(l,s,n),d="";e.testingFramework==="jest"&&(d="jest.config.js"),e.testingFramework==="karma"&&(d="karma.conf.js"),e.testingFramework==="vitest"&&(d="vitest.config.ts");let g=re.join(o,d);J.writeFileSync(g,p,"utf-8"),console.log(`\u2705 [Lisa.ai Auto-Generator] Natively wrote ${d} to repository root.`)}catch(p){console.error(`
|
|
84
|
+
\u274C [Lisa.ai Auto-Generator] Failed to author configuration file: ${p.message}`),process.exit(1)}}};var Te=k(require("dotenv"));Te.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 Pe(t,e,s){if(s==="local")return[];let n=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3000";try{let o=new URLSearchParams({projectId:s,errorLog:t.slice(0,1e3),framework:e}),i=await fetch(`${n}/api/memory/lookup?${o}`);return i.ok?await i.json():[]}catch{return[]}}async function Re(t,e,s,n){if(n==="local")return;let o=process.env.LISA_CONTROL_PLANE_URL||"http://localhost:3000";try{await fetch(`${o}/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(i){console.debug(`[Lisa.ai Agent Debug] Failed to record memory pattern: ${i.message}`)}}var H=0,V=0,ae=new Set;function ue(t){return t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"")}function et(t){let s=[...ue(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(l=>l[3]!==void 0)??s[s.length-1],o=parseInt(n[2]),i=n[3]?parseInt(n[3]):0,r=parseInt(n[1])-i;return{total:o,passed:r,failed:i}}function le(t){let s=[...ue(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(d=>d[3]!==void 0)??s[s.length-1],o=parseInt(n[2]),i=n[3]?parseInt(n[3]):0,r=parseInt(n[1])-i,l=o>0?Math.round(r/o*100):0;return` [${"\u2588".repeat(Math.round(l/5))+"\u2591".repeat(20-Math.round(l/5))}] ${l}% ${r} passed ${i} failed ${o} total`}function Me(t,e=10){let s=[];for(let n of ue(t).split(`
|
|
85
|
+
`)){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>=e)break}}return s}function tt(t){let e=t.replace(/\.(spec|test)\.(ts|js|jsx|tsx)$/,".$2");if(e!==t&&F.existsSync(e))try{return console.log(` [Lisa.ai] \u{1F9E0} Sibling source found: ${I.basename(e)}`),F.readFileSync(e,"utf-8")}catch{return}}function st(t,e){let s=t.toLowerCase(),n=I.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 i=JSON.parse(F.readFileSync(I.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 l=i.scripts?.[r]?.toLowerCase()||"",p=s.includes("npm")?" --":"";if(l.includes("ng test")||l.includes("karma"))return`${t}${p} --include **/${n.base}`;if(l.includes("jest")||l.includes("vitest")||l.includes("playwright"))return`${t}${p} ${e}`}catch{}let o=s.includes("npm")?" --":"";return`${t}${o} ${e}`}return t}function ce(t,e=!1){return new Promise((s,n)=>{let o=(0,De.spawn)(t,{shell:!0,stdio:["ignore","pipe","pipe"]}),i="",r="";o.stdout?.on("data",l=>{let p=l.toString();if(i+=p,e)for(let d of p.split(`
|
|
86
|
+
`)){let g=d.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"").trim();g&&(/Executed\s+\d+\s+of\s+\d+/.test(g)?process.stdout.write(`\r ${g.padEnd(72)}`):/^\s*FAILED\b/.test(g)&&(process.stdout.write(`
|
|
87
|
+
`),console.log(` \u2717 ${g.trim()}`)))}}),o.stderr?.on("data",l=>{r+=l.toString()}),o.on("close",l=>{l===0?s({stdout:i,stderr:r}):n({message:`Process exited with code ${l}`,stdout:i,stderr:r})})})}function nt(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{F.writeFileSync(t,`// Quarantined by Lisa.ai \u2014 could not be automatically healed
|
|
88
|
+
describe('', () => {});
|
|
89
|
+
`,"utf-8"),console.log(" \u{1F6A8} Replaced with empty stub (Angular requires valid TS).")}catch{}else try{F.renameSync(t,t+".broken"),console.log(` \u{1F6A8} Renamed to ${I.basename(t)}.broken to skip in test runner.`)}catch{}}async function ot(t,e,s,n,o,i,r,l,p,d){let g=1,u=!1,a=s,m,w="",c="",v=tt(e),h=(await Pe(s,i,p)).filter(y=>y.confidence>=.5).map(y=>y.fixHint);for(h.length>0&&console.log(` [Memory] ${h.length} proven pattern(s) found \u2014 injecting as LLM hint.`);g<=l&&!u;){console.log(` [Attempt ${g}/${l}] Requesting fix from ${r}...`);let y=F.readFileSync(e,"utf-8"),$;for(let L=0;L<=3;L++)try{$=await $e(t,y,a,r,d,m,v,h);break}catch(x){let A=(x?.lastError??x)?.statusCode;if((A===529||A===500)&&L<3){let D=30*(L+1);console.warn(` \u26A0\uFE0F LLM overloaded (HTTP ${A}). Waiting ${D}s...`),await new Promise(M=>setTimeout(M,D*1e3))}else{console.error(` \u{1F6A8} LLM API failed: ${x?.message??String(x)}`);break}}if($===void 0)break;F.writeFileSync(e,$,"utf-8"),w=`### Auto-Heal Analysis
|
|
90
|
+
**Error:**
|
|
105
91
|
\`\`\`bash
|
|
106
|
-
${
|
|
92
|
+
${a.slice(0,2e3)}
|
|
107
93
|
\`\`\`
|
|
108
94
|
|
|
109
|
-
**
|
|
95
|
+
**Fix (${r}):**
|
|
110
96
|
\`\`\`typescript
|
|
111
|
-
${
|
|
112
|
-
\`\`\``;try{
|
|
113
|
-
`+
|
|
114
|
-
`+(
|
|
97
|
+
${$}
|
|
98
|
+
\`\`\``;try{await ce(o,!1),console.log(" \u2705 Isolated verification passed."),u=!0,c=$}catch(L){let x=L.stdout?L.stdout.toString():"";a=(L.stderr?L.stderr.toString():"")+`
|
|
99
|
+
`+x+`
|
|
100
|
+
`+(L.message||""),console.log(" \u274C Isolated verification failed.");let D=le(a);if(D&&console.log(D),Me(a,3).forEach(M=>console.log(` \u2717 ${M}`)),(n||"").toLowerCase().includes("ng test")||(n||"").toLowerCase().includes("karma")){let M=a.includes(I.basename(t)+":"),We=/ FAILED/.test(a);if(!M&&!We){console.log(" \u2705 Fix verified (build error is from other spec files, not this one)."),u=!0,c=$;continue}}m=`### Attempt ${g} Failed
|
|
115
101
|
\`\`\`typescript
|
|
116
|
-
${
|
|
102
|
+
${$}
|
|
117
103
|
\`\`\`
|
|
118
104
|
|
|
119
105
|
**New Error:**
|
|
120
|
-
${
|
|
121
|
-
|
|
122
|
-
[Lisa.ai
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
106
|
+
${a}`,g++}}return{status:u?"healed":"quarantined",details:w,lastCode:c}}async function Q(t,e,s=1,n=null,o=3,i="local",r,l){let p=j.load(process.cwd());if(p&&(j.applyEnvDefaults(p),!t&&p.testCommand&&(t=p.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${t}`))),!t){console.log(`
|
|
107
|
+
[Lisa.ai Auto-Discovery] No --command provided. Scanning framework...`);let f=N.scanRepository();f.testingFramework==="none"&&(f=await _.installMissingFramework(f),await U.provisionConfigurationFiles(f,e,l)),f.suggestedTestCommand?(t=f.suggestedTestCommand,console.log(`[Lisa.ai Auto-Discovery] Discovered command: ${t}`)):(console.error(`
|
|
108
|
+
\u{1F6A8} [Lisa.ai] Could not discover a test command. Pass --command explicitly.`),process.exit(1))}let d=Ie(t),g=[];console.log(`
|
|
109
|
+
[Lisa.ai] Running test suite (discovery pass)...`),console.log(`[Lisa.ai Executing] ${t} Model: ${e}`);let u;try{await ce(t,!0),process.stdout.write(`
|
|
110
|
+
`),console.log(`
|
|
111
|
+
\u2705 [Lisa.ai] All tests passing. Nothing to heal!`),n&&await ie(n);return}catch(f){process.stdout.write(`
|
|
112
|
+
`),u=(f.stderr||"")+`
|
|
113
|
+
`+(f.stdout||"")+`
|
|
114
|
+
`+(f.message||"")}let a=et(u),m=le(u);if(m){console.log(`
|
|
115
|
+
${m}`);let f=Me(u,10);if(f.length>0){let h=a?.failed??f.length;console.log(` Failing (${h}):`),f.forEach(y=>console.log(` \u2717 ${y}`)),h>f.length&&console.log(` ... and ${h-f.length} more`)}}let w=se(u,process.cwd(),g);if(w.length===0){let f=W(u,g,process.cwd());f||(console.error(`
|
|
116
|
+
\u{1F6A8} [Lisa.ai] Could not identify any failing spec files. Output format may be unsupported.`),process.exit(1)),w=[f]}let c=w.length;console.log(`
|
|
117
|
+
[Lisa.ai] Found ${c} failing spec(s). Healing each in isolation...`),console.log(`${"\u2500".repeat(60)}`);for(let f of w)P({projectId:i,type:"heal",filePath:f,modelUsed:e,status:"running",details:"Queued for isolated healing.",...a&&{testTotal:a.total,testPassed:a.passed,testFailed:a.failed},testFramework:d});for(let f=0;f<w.length;f++){let h=w[f],y=I.resolve(process.cwd(),h);if(console.log(`
|
|
118
|
+
[${f+1}/${c}] ${h}`),!F.existsSync(y)){console.warn(" \u26A0\uFE0F File not found \u2014 skipping.");continue}if(/[\\/](node_modules|dist|build)[\\/]/.test(y)){console.warn(" \u26A0\uFE0F Library file \u2014 refusing to modify.");continue}let $=st(t,h),L=await ot(h,y,u,t,$,d,e,o,i,l);L.status==="healed"?(H++,ae.add(h),console.log(` \u2705 Healed [${H} healed ${V} quarantined so far]`),P({projectId:i,type:"heal",filePath:h,modelUsed:e,status:"success",details:L.details,...a&&{testTotal:a.total,testPassed:a.passed,testFailed:a.failed},testFramework:d}),await Re(u,L.lastCode,d,i)):(V++,g.push(h),console.warn(` \u{1F6A8} Quarantined [${H} healed ${V} quarantined so far]`),P({projectId:i,type:"heal",filePath:h,modelUsed:e,status:"error",details:`Exhausted all ${o} attempts.
|
|
119
|
+
`+L.details,...a&&{testTotal:a.total,testPassed:a.passed,testFailed:a.failed},testFramework:d}),nt(y,h,t))}if(console.log(`
|
|
120
|
+
${"\u2500".repeat(60)}`),H>0){console.log("[Lisa.ai] Final verification run...");try{await ce(t,!0),process.stdout.write(`
|
|
121
|
+
`),console.log(`
|
|
122
|
+
\u2705 All tests passing!`)}catch(f){process.stdout.write(`
|
|
123
|
+
`);let h=(f.stderr||"")+`
|
|
124
|
+
`+(f.stdout||"")+`
|
|
125
|
+
`+(f.message||""),y=le(h);y&&console.log(`
|
|
126
|
+
${y}`);let $=se(h,process.cwd(),[]),L=$.filter(A=>ae.has(A)),x=$.filter(A=>!ae.has(A)&&!g.includes(A));L.length>0&&(console.warn(`
|
|
127
|
+
\u26A0\uFE0F ${L.length} spec(s) passed isolated verification but still fail globally:`),L.forEach(A=>console.warn(` \u2717 ${A}`)),console.warn(" These likely have cross-test shared state. Try higher maxRetries or fix manually.")),x.length>0&&(console.warn(`
|
|
128
|
+
\u2139\uFE0F ${x.length} additional failing spec(s) not in this run's queue:`),x.forEach(A=>console.warn(` \u2717 ${A}`)),console.warn(" Run lisa-agent heal again to address these."))}}let v=(a?.passed??0)+H;console.log(`
|
|
129
|
+
\u2705 Healed: ${H} / ${c}`),console.log(` \u{1F6A8} Quarantined: ${V}`),a&&console.log(` \u{1F4CA} Suite: ${a.passed} passing \u2192 ~${v} passing (est.)`),console.log(`${"\u2500".repeat(60)}
|
|
130
|
+
`),n&&await ie(n)}var Ue=require("child_process"),R=k(require("fs")),b=k(require("path"));var X=k(require("fs")),Oe=k(require("path"));function Ne(t){let e=Oe.resolve(process.cwd(),t);if(!X.existsSync(e))throw new Error(`[Lisa.ai Coverage Error] Coverage file not found at ${e}`);let s=X.readFileSync(e,"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 _e=new Set,ee=0,de=3;async function B(t,e,s=1,n=3,o="local",i){let r=j.load(process.cwd());r&&(j.applyEnvDefaults(r),!t&&r.testCommand&&(t=r.testCommand,console.log(`[Lisa.ai Config] Using testCommand from .lisai.json: ${t}`)));let l=N.scanRepository(),p=r?.testingFramework||(l.testingFramework!=="none"?l.testingFramework:void 0),d=r?.testTypes;if(!t){console.log(`
|
|
131
|
+
[Lisa.ai Auto-Discovery] No explicit --command provided. Initiating Autonomous Framework Fingerprinting...`);let u=l;if(u.testingFramework==="none"&&(u=await _.installMissingFramework(u),await U.provisionConfigurationFiles(u,e,i)),u.suggestedTestCommand){t=u.suggestedTestCommand;let a=u.testingFramework;(a==="jest"||a==="vitest")&&!t.includes("--coverage")&&(t=t.includes("npm run")?`${t} -- --coverage`:`${t} --coverage`,console.log(`[Lisa.ai Coverage] Coverage flag appended: ${t}`)),console.log(`[Lisa.ai Auto-Discovery] Bootstrapping execution with natively discovered command: ${t}`)}else console.error(`
|
|
128
132
|
\u{1F6A8} [Lisa.ai Fatal Error] Agent could not dynamically extrapolate a testing command for a Generic Node Environment. Please pass --command explicitly.`),process.exit(1)}console.log(`
|
|
129
|
-
[Lisa.ai Coverage] ${t} (Attempt ${s}/${
|
|
130
|
-
`);for(let
|
|
131
|
-
\u2705 [Lisa.ai Coverage] Tests passed successfully on attempt ${s}.`)}catch(
|
|
132
|
-
`+(
|
|
133
|
-
`+(
|
|
134
|
-
\u274C [Lisa.ai Coverage] Tests failed. Delegating to Auto-Heal...`),await
|
|
135
|
-
\u{1F504} [Lisa.ai Coverage] Auto-Heal successful. Restarting coverage analysis...`),await
|
|
136
|
-
[Lisa.ai Coverage] No failing spec file detected in error output. Tests may not exist yet \u2014 initiating Cold-Start Discovery...`)}try{let
|
|
137
|
-
[Lisa.ai Coverage] No coverage-summary.json found. Initiating Cold-Start Project Crawler...`),
|
|
138
|
-
\u274C [Lisa.ai Coverage] LLM call failed for ${
|
|
133
|
+
[Lisa.ai Coverage] ${t} (Attempt ${s}/${n}) Using Model: ${e}`),await P({projectId:o,type:"coverage",filePath:"global-test-suite",modelUsed:e,status:"running",details:"Agent is currently executing testing suite and validating coverage drops..."});let g=(u,a=!1)=>new Promise((m,w)=>{let c=(0,Ue.spawn)(u,{shell:!0,stdio:["ignore","pipe","pipe"]}),v="",f="";c.stdout?.on("data",h=>{let y=h.toString();if(v+=y,a){let $=y.split(`
|
|
134
|
+
`);for(let L of $){let x=L.match(/Executed\s+(\d+)\s+of\s+(\d+)/);if(x){let A=L.match(/(\d+)\s+FAILED/),D=A?A[1]:0,M=`\r\u23F3 [Lisa.ai Testing] Executed ${x[1]} of ${x[2]} (${D} FAILED) `;process.stdout.write(M)}}}}),c.stderr?.on("data",h=>{f+=h.toString()}),c.on("close",h=>{h===0?m():w({message:`Test process exited with code ${h}`,stdout:v,stderr:f})})});try{console.log("[Lisa.ai Coverage] Booting testing framework in the background. This may take a moment..."),await g(t,!0),console.log(`
|
|
135
|
+
\u2705 [Lisa.ai Coverage] Tests passed successfully on attempt ${s}.`)}catch(u){let a=(u.stderr||"")+`
|
|
136
|
+
`+(u.stdout||"")+`
|
|
137
|
+
`+(u.message||"");if(W(a,[],process.cwd())!==null){console.log(`
|
|
138
|
+
\u274C [Lisa.ai Coverage] Tests failed. Delegating to Auto-Heal...`),await Q(t,e,1,null,n,o,void 0,i),console.log(`
|
|
139
|
+
\u{1F504} [Lisa.ai Coverage] Auto-Heal successful. Restarting coverage analysis...`),await B(t,e,s+1,n,o,i);return}console.log(`
|
|
140
|
+
[Lisa.ai Coverage] No failing spec file detected in error output. Tests may not exist yet \u2014 initiating Cold-Start Discovery...`)}try{let u=b.resolve(process.cwd(),"coverage/coverage-summary.json"),a=[];if(R.existsSync(u))console.log("[Lisa.ai Coverage] Evaluating summary..."),a=Ne("coverage/coverage-summary.json");else{if(console.log(`
|
|
141
|
+
[Lisa.ai Coverage] No coverage-summary.json found. Initiating Cold-Start Project Crawler...`),a=N.findUntestedFiles(process.cwd(),[..._e]),a.length===0){console.log("\u2705 [Lisa.ai Coverage] Zero-Test scan complete. No untested source files discovered.");return}console.log(`[Lisa.ai Coverage] Discovered ${a.length} untested file(s). Seeding first test suite...`)}if(a.length===0){console.log("\u2705 [Lisa.ai Coverage] 100% Logic Coverage Verified! No un-covered files remaining.");return}console.log(`[Lisa.ai Coverage] Found ${a.length} file(s) below 100% threshold:`,a);let m=a[0],w=b.resolve(process.cwd(),m),c=b.parse(w),v=[b.join(c.dir,`${c.name}.spec${c.ext}`),b.join(c.dir,`${c.name}.test${c.ext}`),b.join(c.dir,`${c.name}.spec.js`),b.join(c.dir,`${c.name}.test.js`),b.join(c.dir,`${c.name}.spec.ts`),b.join(c.dir,`${c.name}.test.ts`)],f=null,h=b.join(c.dir,`${c.name}.spec${c.ext}`);for(let x of v)if(R.existsSync(x)){h=x,f=R.readFileSync(x,"utf-8");break}let y="",$=!1,L=R.readFileSync(w,"utf-8");try{f?(console.log(`[Lisa.ai Coverage] Existing test suite discovered for ${m}. Requesting single-pass logic coverage append...`),y=await Ae(m,L,b.relative(process.cwd(),h),f,e,i,p,d)):(console.log(`[Lisa.ai Coverage] Requesting newly generated test suite for ${m}...`),y=await ke(m,L,e,i,p,d)),ee=0,$=!0}catch(x){ee++,_e.add(m);let A=x.cause?.message?`${x.message} (cause: ${x.cause.message})`:x.message;if(console.error(`
|
|
142
|
+
\u274C [Lisa.ai Coverage] LLM call failed for ${m} \u2014 consecutive failure #${ee}/${de}`),console.error(` Error: ${A}`),ee>=de)throw new Error(`Systematic LLM failure: ${de} consecutive API calls failed.
|
|
139
143
|
This usually means your API key has insufficient credits, hit a rate limit, or the model is unavailable.
|
|
140
|
-
Last error: ${
|
|
141
|
-
Tip: Check your API key, account credits, and rate-limit quota for provider '${e}'.`)}if(
|
|
144
|
+
Last error: ${A}
|
|
145
|
+
Tip: Check your API key, account credits, and rate-limit quota for provider '${e}'.`)}if(!$){await B(t,e,s+1,n,o,i);return}R.writeFileSync(h,y,"utf-8"),console.log(`[Lisa.ai Coverage] Wrote Spec File to ${h}`),await P({projectId:o,type:"coverage",filePath:m,modelUsed:e,status:"success",details:`### Logic Coverage Action Detected
|
|
142
146
|
**Auto-Generated Specification Append (${e}):**
|
|
143
147
|
\`\`\`typescript
|
|
144
|
-
${
|
|
145
|
-
\`\`\``}),await
|
|
146
|
-
======================================================`),console.log(`\u2728 Lisa.ai Agent v${
|
|
147
|
-
`)}var
|
|
148
|
+
${y}
|
|
149
|
+
\`\`\``}),await B(t,e,s+1,n,o,i)}catch(u){console.error("[Lisa.ai Coverage loop failure]:",u.message),await P({projectId:o,type:"coverage",filePath:"coverage-loop",modelUsed:e,status:"error",details:`Coverage loop encountered an unrecoverable error: ${u.message}`})}}var Ye=He();function ge(){console.log(`
|
|
150
|
+
======================================================`),console.log(`\u2728 Lisa.ai Agent v${Ye.version} Running... `),console.log(" Where pure magic happens! \u{1FA84}"),console.log(`======================================================
|
|
151
|
+
`)}var G=new Ge.Command;G.name("lisa-agent").description("Lisa.ai - Autonomous CI/CD Platform Worker Agent").version(Ye.version);G.command("heal").description("Run a command and autonomously heal errors").option("-c, --command <type>","Command to execute (Optional for Auto-Discovery)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID to fetch dynamic config").action(async t=>{ge();let e=5,s=t.model,n;if(t.projectId){let i=await Y(t.projectId);if(!i.ok)i.reason==="not_found"?(console.error(`
|
|
148
152
|
\u{1F6A8} [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(`
|
|
149
153
|
\u26A0\uFE0F [Lisa.ai Warning] Control Plane is unreachable. Continuing with local CLI defaults (model=${s}, maxRetries=${e}).`);else{let r=i.config;console.log(`[Lisa.ai Agent] Dynamic Config Loaded: Provider=${r.modelProvider}, MaxRetries=${r.maxRetries}`),r.maxRetries<5&&console.warn(`
|
|
150
|
-
\u26A0\uFE0F [Lisa.ai Warning] Your Dashboard Analytics Config has maxRetries set to ${r.maxRetries}. Consider increasing this to 5+ in the WEB UI for complex Angular Healing!`),s=r.modelProvider,e=r.maxRetries,
|
|
154
|
+
\u26A0\uFE0F [Lisa.ai Warning] Your Dashboard Analytics Config has maxRetries set to ${r.maxRetries}. Consider increasing this to 5+ in the WEB UI for complex Angular Healing!`),s=r.modelProvider,e=r.maxRetries,n=r.apiKey,r.autoHealEnabled===!1&&(console.log("[Lisa.ai Agent] Auto-heal is disabled by Control Plane."),process.exit(1))}}let o=j.load(process.cwd());o&&(j.applyEnvDefaults(o),!t.projectId&&o.maxRetries!==void 0&&(e=o.maxRetries),!t.projectId&&o.provider&&t.model==="gemini"&&(s=o.provider),j.printSummary(o)),await Q(t.command,s,1,null,e,t.projectId||"local",void 0,n)});G.command("coverage").description("Run test command dynamically generating missing specs for 100% coverage").option("-c, --command <type>","Test command to execute (Optional for Auto-Discovery)").option("-m, --model <provider>","LLM provider to use (gemini, claude, openai)","gemini").option("-p, --project-id <id>","Control Plane Project ID to fetch dynamic config").action(async t=>{ge();let e=5,s=t.model,n;if(t.projectId){let i=await Y(t.projectId);if(!i.ok)i.reason==="not_found"?(console.error(`
|
|
151
155
|
\u{1F6A8} [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(`
|
|
152
156
|
\u26A0\uFE0F [Lisa.ai Warning] Control Plane is unreachable. Continuing with local CLI defaults (model=${s}, maxRetries=${e}).`);else{let r=i.config;console.log(`[Lisa.ai Agent] Dynamic Config Loaded: Provider=${r.modelProvider}, MaxRetries=${r.maxRetries}`),r.maxRetries<5&&console.warn(`
|
|
153
|
-
\u26A0\uFE0F [Lisa.ai Warning] Your Dashboard Analytics Config has maxRetries set to ${r.maxRetries}. Consider increasing this to 5+ in the WEB UI for complex Angular Healing!`),s=r.modelProvider,e=r.maxRetries,
|
|
154
|
-
[Lisa.ai Diagnose] Testing ${e} \u2192 model ID: ${
|
|
157
|
+
\u26A0\uFE0F [Lisa.ai Warning] Your Dashboard Analytics Config has maxRetries set to ${r.maxRetries}. Consider increasing this to 5+ in the WEB UI for complex Angular Healing!`),s=r.modelProvider,e=r.maxRetries,n=r.apiKey,r.autoHealEnabled===!1&&(console.log("[Lisa.ai Agent] Auto-heal is disabled by Control Plane."),process.exit(1))}}let o=j.load(process.cwd());o&&(j.applyEnvDefaults(o),!t.projectId&&o.maxRetries!==void 0&&(e=o.maxRetries),!t.projectId&&o.provider&&t.model==="gemini"&&(s=o.provider),j.printSummary(o)),await B(t.command,s,1,e,t.projectId||"local",n)});G.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=>{ge();let e=t.model,s;if(t.projectId){let i=await Y(t.projectId);i.ok?(e=i.config.modelProvider,s=i.config.apiKey,console.log(`[Lisa.ai Diagnose] Config fetched from Control Plane. Provider=${e}`)):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"}[e]||e;console.log(`
|
|
158
|
+
[Lisa.ai Diagnose] Testing ${e} \u2192 model ID: ${o}`);try{let i=await Z("Reply with exactly: LISA_OK",e,s);console.log(`
|
|
155
159
|
\u2705 [Lisa.ai Diagnose] ${e} is working correctly.`),console.log(` Model response: "${i}"`)}catch(i){console.error(`
|
|
156
160
|
\u274C [Lisa.ai Diagnose] ${e} call FAILED.`),console.error(` Error: ${i.message}`),i.cause&&console.error(` Cause: ${i.cause?.message??i.cause}`),console.error(`
|
|
157
|
-
Common causes:`),console.error(" \u2022 API key is invalid, expired, or has no credits"),console.error(" \u2022 Model ID is deprecated (current: claude-sonnet-4-6, gemini-2.0-flash, gpt-4o-mini)"),console.error(" \u2022 Rate limit exceeded \u2014 wait a minute and retry"),console.error(" \u2022 Network/proxy issue blocking api.anthropic.com"),process.exit(1)}});
|
|
158
|
-
\u274C [Lisa.ai Init] ${
|
|
161
|
+
Common causes:`),console.error(" \u2022 API key is invalid, expired, or has no credits"),console.error(" \u2022 Model ID is deprecated (current: claude-sonnet-4-6, gemini-2.0-flash, gpt-4o-mini)"),console.error(" \u2022 Rate limit exceeded \u2014 wait a minute and retry"),console.error(" \u2022 Network/proxy issue blocking api.anthropic.com"),process.exit(1)}});G.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=qe.resolve(process.cwd(),O);te.existsSync(e)&&!t.force&&(console.error(`
|
|
162
|
+
\u274C [Lisa.ai Init] ${O} already exists. Use --force to overwrite.`),process.exit(1));let s=Be.createInterface({input:process.stdin,output:process.stdout}),n=(g,u="")=>new Promise(a=>s.question(u?`${g} [${u}]: `:`${g}: `,m=>a(m.trim()||u)));console.log(`
|
|
159
163
|
\u{1F680} Lisa.ai Project Setup \u2014 press Enter to accept the default shown in [ ]
|
|
160
|
-
`);let
|
|
164
|
+
`);let o=await n("LLM provider (gemini / claude / openai)","gemini"),i=await n("Testing framework (jest / vitest / mocha / karma / cypress / playwright \u2014 leave empty to auto-detect)",""),r=await n("Test types to generate (unit / integration / e2e \u2014 comma-separated)","unit"),l=await n("Test command (leave empty for auto-discovery)",""),p=await n("Max heal retries","5");s.close();let d={provider:o,testTypes:r.split(",").map(g=>g.trim()).filter(Boolean),maxRetries:parseInt(p,10)||5,skipFiles:[],skipDirs:[],skipPaths:[]};i&&(d.testingFramework=i),l&&(d.testCommand=l),te.writeFileSync(e,JSON.stringify(d,null,2)+`
|
|
161
165
|
`,"utf-8"),console.log(`
|
|
162
|
-
\u2705 Created ${
|
|
163
|
-
`),console.log(JSON.stringify(
|
|
166
|
+
\u2705 Created ${O}:
|
|
167
|
+
`),console.log(JSON.stringify(d,null,2)),console.log(`
|
|
164
168
|
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 coverage analysis.
|
|
165
|
-
`)});
|
|
169
|
+
`)});G.parse(process.argv);
|