kwikqa 0.8.0 → 0.8.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  What's new in each release of the KwikQA CLI.
4
4
 
5
+ ## 0.8.1 — 2026-11-17
6
+
7
+ ### Changed
8
+
9
+ - KwikQA supports every release of the Node.js 22, 24, and 26 long-term support lines, and later versions (`^22.0.0 || ^24.0.0 || >=26.0.0`). 0.8.0 asked for each line's November 2026 security release, so a Node.js one patch behind, like the one GitHub's Ubuntu runners had that day, got npm's `EBADENGINE` warning, and npm's `engine-strict` setting refused to install KwikQA on it. CI now tests the first and the latest release of each line. Keeping Node.js up to date with its security releases is still recommended.
10
+
5
11
  ## 0.8.0 — 2026-11-17
6
12
 
7
13
  ### Added
package/README.md CHANGED
@@ -40,7 +40,7 @@ Using pnpm, Yarn, or Bun? See [Package managers and monorepos](#package-managers
40
40
 
41
41
  ## Requirements
42
42
 
43
- - Node.js 22 (22.23.5 or later), 24 (24.22.3 or later), or 26 (26.13.1 or later): the long-term support releases, each tested in CI
43
+ - Node.js 22, 24, 26, or later: any release of the long-term support lines, each tested in CI at its first and latest release
44
44
  - Playwright Test, Cypress, or WebdriverIO (Mocha or Jasmine) installed in your project with npm,
45
45
  pnpm, Yarn, or Bun. KwikQA runs your project's own copy and never installs packages or browsers.
46
46
  - A git repository
@@ -665,7 +665,7 @@ The `exit 1` keeps the job failed: KwikQA exits with the analysis's code, which
665
665
  ### Jenkins
666
666
 
667
667
  In a Pipeline, run `kwikqa ci` when the tests fail, with its tokens bound only around it. The agent
668
- needs Node.js 22 (22.23.5 or later), 24 (24.22.3 or later), or 26 (26.13.1 or later).
668
+ needs Node.js 22, 24, 26, or later.
669
669
 
670
670
  ```groovy
671
671
  stage('e2e') {
package/dist/kwikqa.mjs CHANGED
@@ -255,7 +255,7 @@ ${l.join(`
255
255
  `).split(`
256
256
  `);return t.at(-1)===""?t.slice(0,-1):t}function pw(e,t){let n=QP(e),r=QP(t),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;let a=0;for(;a<n.length-s&&a<r.length-s&&n[n.length-1-a]===r[r.length-1-a];)a+=1;let o=n.slice(s,n.length-a),d=r.slice(s,r.length-a);if((o.length+1)*(d.length+1)>vG)return;let l=d.length+1,c=new Int32Array((o.length+1)*l);for(let g=o.length-1;g>=0;g-=1)for(let w=d.length-1;w>=0;w-=1)c[g*l+w]=o[g]===d[w]?(c[(g+1)*l+w+1]??0)+1:Math.max(c[(g+1)*l+w]??0,c[g*l+w+1]??0);let u=[],p,f=()=>{p!==void 0&&u.push(p),p=void 0},m=0,h=0;for(;m<o.length||h<d.length;){if(m<o.length&&h<d.length&&o[m]===d[h]){f(),m+=1,h+=1;continue}p??={resultLine:s+h+1,deleted:[],added:[]},h<d.length&&(m>=o.length||(c[m*l+h+1]??0)>(c[(m+1)*l+h]??0))?(p.added.push(d[h]??""),h+=1):(p.deleted.push(o[m]??""),m+=1)}return f(),u}function XP(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function gw(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}async function kG(e,t,n){let r=await rr(e.gitRoot,t.commit,Nr(e.workspaceRoot,e.gitRoot,n),YP);if(r.kind==="absent")return{kind:"repair-config-missing",message:`\`kwikqa check\` judges changes by the committed ${n}, and ${t.revision} has none. Run \`kwikqa init\`, then commit ${n}.`};let s=r.kind==="read"?gw(r.bytes):void 0,a;try{a=s===void 0?void 0:JSON.parse(s)}catch{a=void 0}if(a===void 0)return{kind:"repair-config-invalid",message:`The committed ${n} is not UTF-8 JSON of at most ${YP} bytes.`};let o=dr(a);return o.kind==="valid"?o:{kind:"repair-config-invalid",message:`The committed ${n} is invalid: ${o.issues.join(" ")}`}}var RG=/\.(?:[cm]?[jt]sx?|java|py)$/i;function xG(e){return e.startsWith(".kwikqa/")||e===Os}async function _G(e,t,n){let r=u=>({findings:[{kind:"not-checked",path:e,message:u}]}),s=xd(e);if(!RG.test(e)||s===void 0)return r("KwikQA checks JavaScript, TypeScript, Java, and Python test code, so this file's change was not checked.");let a=pw(t,n);if(a===void 0)return r("The changed part of this file is too large to compare line by line.");let o=a.reduce((u,p)=>u+p.deleted.length+p.added.length,0);if(!await ca(e,n))return{changedLines:o,findings:[{kind:"failed",path:e,message:"The file no longer parses."}]};if(!await ca(e,t))return{changedLines:o,findings:[{kind:"not-checked",path:e,message:"The file didn't parse before the change, so the change can't be compared."}]};let d=[],l=await rw(t,n,s);if(l.length>0){let u=l.map(f=>f.split(/[.:!]/).at(-1)??f),p=a.find(f=>f.deleted.some(m=>u.some(h=>m.includes(h))))??a[0];d.push({kind:"failed",path:e,...p===void 0?{}:{line:p.resultLine},message:iw("change",l)})}let c=await Ju(t,n,s);if(c.length>0){let u=m=>a.some(h=>m>=h.resultLine&&m<h.resultLine+h.added.length),p=c.flatMap(m=>m.patternCalls.map(h=>XP(n,h.start))),f=p.find(u)??p[0];d.push({kind:"failed",path:e,...f===void 0?{}:{line:f},message:sw("change",c.map(m=>m.matcher))})}for(let u of await nw(t,n,s))d.push({kind:"failed",path:e,line:XP(n,u.start),message:ZP(Ku)});for(let u of a)for(let p of await Yu(u.deleted.join(`
257
257
  `),u.added.join(`
258
- `),{},"change",s)){let f=await IG(u,p,s);d.push({kind:"failed",path:e,line:f,message:ZP(p)})}return{changedLines:o,findings:d}}async function IG(e,t,n){for(let[r,s]of e.added.entries())if((await Yu("",s,{},"change",n)).includes(t))return e.resultLine+r;return e.resultLine}function ZP(e){let t=`${e.charAt(0).toUpperCase()}${e.slice(1)}`;return t.endsWith(".")?t:`${t}.`}function TG(e){return[...e].sort((t,n)=>(t.path===void 0?1:0)-(n.path===void 0?1:0)||(t.path??"").localeCompare(n.path??"")||(t.line??0)-(n.line??0))}function hw(e,t){let n=TG(t);return{gate:e,status:n.some(r=>r.kind==="failed")?"failed":n.some(r=>r.kind==="not-checked")?"not-checked":"passed",findings:n}}async function yw(e){let t=new Date().toISOString(),n=await yG(e.workspaceRoot),r=await sn(n),s=e.configPath??bG,a=await Fg(r,"HEAD");if(a===void 0)return{kind:"unavailable",reason:"no-repository",message:"`kwikqa check` compares your changes with a commit, so it needs a git repository with at least one commit."};let o={revision:"HEAD",commit:a};if(e.base!==void 0){let O=await Fg(r,e.base),I=O===void 0?void 0:await mS(r,O);if(I===void 0)return{kind:"unavailable",reason:"unknown-base",message:O===void 0?`\`--base ${e.base}\` names no commit in this repository. Fetch it first, or name a branch, tag, or commit.`:`The current branch shares no history with ${e.base}.`};o={revision:e.base,commit:I}}let d=await kG({workspaceRoot:n,gitRoot:r},o,s);if(d.kind!=="valid")return{kind:"unavailable",reason:d.kind,message:d.message};let{config:l}=d,c=e.analysis===void 0?void 0:await GP(wG(n,e.analysis),e.analysis);if(c?.kind==="unreadable")return{kind:"unavailable",reason:"analysis-unreadable",message:c.message};let u=[],p=[],f=0,m=0;for(let O of await hS(r,o.commit)){let I=gS(n,r,O.path);if(I===void 0){u.push({path:O.path,change:O.change,scope:"outside"}),p.push({kind:"failed",path:O.path,message:"Outside this workspace, so outside the test code kwikqa.config.json lets KwikQA edit."});continue}if(xG(I))continue;let N=Jn(I)?void 0:di(I,l.editablePaths);if(N===void 0||Yn(I,l)){let C=O.change==="deleted"?void 0:await W(n,I,tp);u.push({path:I,change:O.change,scope:"outside",...C?.kind==="read"?{sha256:C.sha256}:{}}),p.push({kind:"failed",path:I,message:"Outside the test code kwikqa.config.json lets KwikQA edit. KwikQA never changes other files to make a test pass, so a change that does fails the check."});continue}if(f+=1,O.change==="deleted"){u.push({path:I,change:"deleted",scope:N.class}),p.push({kind:"failed",path:I,message:"Deleted. Deleting test code deletes the tests it holds or supports."});continue}let T=O.change==="added"?{kind:"read",bytes:new Uint8Array}:await rr(r,o.commit,O.path,tp),S=await W(n,I,tp),L=T.kind==="read"?gw(T.bytes):T.kind,j=S.kind==="read"?gw(S.bytes):void 0,M;S.kind==="unauthorized"?M={findings:[{kind:"failed",path:I,message:"Not a regular file inside the workspace, such as a symbolic link."}]}:L==="over-budget"||S.kind==="over-budget"?M={findings:[{kind:"not-checked",path:I,message:`Larger than ${tp} bytes, so its change was not checked.`}]}:L===void 0||L==="absent"||j===void 0?M={findings:[{kind:"not-checked",path:I,message:"Not readable as UTF-8 text, so its change was not checked."}]}:M=await _G(I,L,j),m+=M.changedLines??0,u.push({path:I,change:O.change,scope:N.class,...M.changedLines===void 0?{}:{changedLines:M.changedLines},...S.kind==="read"?{sha256:S.sha256}:{}}),p.push(...M.findings)}if(u.length===0)return{kind:"nothing-to-check",base:o,message:o.revision==="HEAD"?"Nothing to check: there are no uncommitted changes.":`Nothing to check: nothing changed since the branch left ${o.revision}.`};let{maxFiles:h,maxChangedLines:g}=l.budgets;(f>h||m>g)&&p.push({kind:"failed",message:`The change touches ${f} test file${f===1?"":"s"} and ${m} line${m===1?"":"s"}; kwikqa.config.json lets one repair change at most ${h} file${h===1?"":"s"} and ${g} lines.`});let w=await JP({workspaceRoot:n,gitRoot:r,base:o,changes:u,...c===void 0?{}:{analysis:c.record}}),y=hw("scope-and-policy",p),b={...hw("ownership",w.findings),...w.analysis===void 0?{}:{analysis:w.analysis}},v={workspaceRoot:n,gitRoot:r,base:o,changes:u,tests:w.tests,earlierGateFailed:y.status==="failed"||b.status==="failed",...e.validation===void 0?{}:{interaction:e.validation},...e.validationTimeoutMs===void 0?{}:{timeoutMs:e.validationTimeoutMs}},R=w.record,_=R?.framework!==void 0&&Hn(R.framework)?R.framework:void 0,P=hw("validation",R!==void 0&&_!==void 0?await VP({...v,record:R,framework:_,allRefused:w.allRefused===!0}):await FP({...v,...R===void 0?{}:{record:R}})),E=[y,b,P];return{kind:"checked",outcome:E.some(O=>O.status==="failed")?"failed":E.some(O=>O.status==="not-checked")?"incomplete":"passed",checkedAt:t,base:o,changes:u,gates:E}}import{createHash as SG}from"node:crypto";import{join as AG,relative as PG,sep as EG}from"node:path";var tE="kwikqa.config.json",CG=256*1024;async function nE(e,t){let n=await W(e,t,CG);if(n.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${t}; none was found in the workspace.`};if(n.kind!=="read")return{kind:"repair-config-invalid",message:`${t} could not be read: ${n.message}`};let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{return{kind:"repair-config-invalid",message:`${t} is not valid UTF-8 JSON.`}}let s=dr(r);return s.kind!=="valid"?{kind:"repair-config-invalid",message:s.issues.join(" ")}:{...s,bytes:n.bytes}}async function zi(e,t=tE){let n=await nE(e,t);return n.kind==="valid"?n.config.ci?.fix:void 0}async function NG(e,t,n,r){if(e.ci===void 0)return{};if(t.config.ci?.fix===void 0)return{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-missing",message:`\`kwikqa fix\` needs a terminal, unless ${r} has a committed ci.fix policy, which lets it validate a repair on this runner and open a draft pull request.`}};let s=PG(n.gitRoot,AG(n.workspaceRoot,r)).split(EG).join("/");return await fS(n.gitRoot,s,t.bytes)?{approver:{kind:"ci-policy",...e.ci,policyHash:SG("sha256").update(t.bytes).digest("hex")}}:{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-uncommitted",message:`${r} differs from its committed version, so its ci.fix policy wasn't reviewed; a fix in CI runs only under the committed policy.`}}}function OG(e,t,n){let r=new Set(n.map(a=>a.toLocaleLowerCase("en-US"))),s=new Set;for(let a of e.evidence){if(a.locator.type!=="source-range")continue;let o=a.locator.path;di(o,t.editablePaths)!==void 0&&!Yn(o,t)&&!Jn(o)&&!r.has(o.toLocaleLowerCase("en-US"))&&s.add(o)}return[...s].sort()}async function np(e){let t=e.now??(()=>new Date().toISOString()),n=await Cr(e.workspaceRoot);if(n.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:n.message};let{workspaceRoot:r,gitRoot:s,dirtyPaths:a,pristine:o}=n.status,d=e.configPath??tE,l=await nE(r,d);if(l.kind!=="valid")return{outcome:"operation-failed",reasonCode:l.kind,message:l.message};let c=l.config,u=await NG(e,l,{workspaceRoot:r,gitRoot:s},d);if("refusal"in u)return u.refusal;let{approver:p}=u;if(e.retryRepairSessionId!==void 0&&(await Ir(r,e.retryRepairSessionId).catch(()=>{}))?.state!=="retry-approval-required")return{outcome:"operation-failed",reasonCode:"no-retry-available",message:"That repair session has no retry available; only one retry follows a failed validation."};let f=await wd({...e,workspaceRoot:r,gitRoot:s,repairableOnly:!0},t);if(f.kind==="unreadable")return{outcome:f.outcome,reasonCode:f.reasonCode,message:f.message};let{stage:m}=f,h={workspaceRoot:r,gitRoot:s,dirtyPaths:a},g=(_,P=[],E)=>($,O={})=>Fu(_,Du(_,"fix",P.length===0?$:{...$,message:`${P.join(" ")} ${$.message}`},t,{repository:{pristine:o,dirtyPaths:a},...O}),e.persist!==!1).then(I=>E===void 0?I:{...I,fixGroups:E}),w=FG(m,e);if("refusal"in w)return g(m)(w.refusal);let y=e.oneGroup===void 0?void 0:VG(m);if(w.groups.length===0&&e.oneGroup!==void 0)return g(m,[],{groups:y??[]})({outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:BG(e.oneGroup)});if(w.groups.length===0){let{packet:_}=m,{diagnosis:P,grading:E}=m.result;return m.result.outcome!=="diagnosed"||_===void 0||P===void 0||E===void 0?g(m)(m.result):eE(e,m,{packet:_,diagnosis:P,grading:E},c,t,g(m),h,p)}let b=(m.clusterStages??[]).flatMap(_=>_.refusal===void 0?[]:[_.refusal.message]),v=[],R=new Map;for(let _ of w.groups){let P=await e.fixInReview?.(_.cluster.signals);P===void 0?v.push(_):(R.set(_.representativeId,P),b.push(`Failure group ${ww(m,_)}: ${P.reason}.`))}if(v.length===0)return g(m,[],y===void 0?void 0:{groups:UG(y,R)})({outcome:"abstained-from-repair",reasonCode:"fix-in-review",message:b.join(" ")});await e.repairSession?.open(v.length);try{let _;for(let P of v){let E=DG(m,P),{packet:$}=E,{diagnosis:O,grading:I}=P.result;if($===void 0||O===void 0||I===void 0)continue;let N=y===void 0?void 0:{groups:y,attempted:P.representativeId};if(_=await eE(e,E,{packet:$,diagnosis:O,grading:I},c,t,g(E,b,N),h,p),!LG(_))return _;b.push(`Failure group ${ww(m,P)}: ${_.message}`)}return _??g(m)(m.result)}finally{await e.repairSession?.close()}}var MG=3,$G=new Set(["model-declined-repair","repair-not-eligible","failure-not-reproduced","insufficient-ownership-evidence","intent-ambiguous","invalid-replacement","unauthorized-target","dirty-target-file","source-hash-mismatch","non-unique-match","overlapping-replacement","forbidden-edit","parse-failed","budget-exceeded","unreadable-target"]);function LG(e){return e.outcome==="abstained-from-repair"?$G.has(e.reasonCode):e.outcome==="validation-unavailable"&&e.record?.application.status==="not-run"}function ww(e,t){return(e.clusterStages??[]).indexOf(t)+1}function DG(e,t){return{...e,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},result:t.result,clusterStages:[t,...(e.clusterStages??[]).filter(n=>n!==t)],representativeId:t.representativeId}}function FG(e,t){let n=e.clusterStages??[];if(t.group!==void 0){let a=n[t.group-1];return a===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${t.group}; this run has ${n.length}.`}}:a.refusal!==void 0?{refusal:{outcome:"abstained-from-repair",reasonCode:"not-a-browser-test",message:a.refusal.message}}:da([a]).includes(a)?{groups:[a]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${t.group} is not diagnosed as the test's fault (${a.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=da(n);if(t.oneGroup!==void 0)return{groups:jG(r,t.oneGroup)};let s=t.repairSession===void 0||t.retryRepairSessionId!==void 0?1:MG;return{groups:r.slice(0,s)}}function jG(e,t){let{retryOf:n}=t,r=n===void 0?e.find(s=>!t.tried.includes(s.representativeId)):e.find(s=>s.cluster.logicalTestIds.includes(n));return r===void 0?[]:[r]}function BG(e){return e.retryOf===void 0?"No repair-eligible failure group is left to try, so no repair was requested.":"The failure group whose validation failed is no longer repair-eligible in the retry's report, so no repair was requested."}function VG(e){let t=e.clusterStages??[],n=new Set(da(t));return t.map(r=>({number:ww(e,r),representativeId:r.representativeId,logicalTestIds:r.cluster.logicalTestIds,repairable:n.has(r),reasonCode:r.result.reasonCode,message:r.result.message}))}function UG(e,t){return e.map(n=>{let r=t.get(n.representativeId);return r===void 0?n:{...n,inReview:r}})}async function HG(e,t){let{interaction:n}=e;if(n.confirmFailure===void 0||e.retryRepairSessionId!==void 0)return;let r=t.clusterStages?.[0]?.cluster.logicalTestIds??t.failing,s=t.representativeId??r[0];if(s===void 0)return;let a=await n.confirmFailure(t.run,r);if(a.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(a.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:a.message};let o=r.filter(l=>a.failedAgain.includes(l));if(o.includes(s))return{status:"reproduced",logicalTestIds:r,failedAgain:o};let d=t.run.logicalTests.find(l=>l.logicalTestId===s)?.title;return{status:"not-reproduced",logicalTestIds:r,failedAgain:o,message:`${d===void 0?"The failing test":`"${d}"`} passed when re-run, so the failure looks flaky or depends on state the re-run did not have. KwikQA does not patch a test that passes; no repair was requested.`}}async function eE(e,t,n,r,s,a,o,d){let{packet:l,diagnosis:c,grading:u}=n,p=[...c.hypotheses].sort((b,v)=>b.rank-v.rank)[0],f=e.repairCaps??e.remote.caps,m=await wy({packet:l,diagnosis:c,grading:u,hypothesisId:p?.hypothesisId??"",editablePaths:OG(l,r,o.dirtyPaths),budgets:r.budgets,model:e.repairModel??e.remote.model,caps:f,transport:e.remote.transport,now:s()});if(m.kind!=="preview-ready"){let b=m.reasonCode==="repair-not-eligible"&&p?.probableOwner!=="test-support"?Lu(c):m.reasonCode,v=m.reasonCode==="repair-not-eligible"||$u.has(m.reasonCode);return a({outcome:v?"abstained-from-repair":"operation-failed",reasonCode:b,message:m.message},{proposal:{status:v?"not-eligible":"failed"},repairAudit:m.audit})}let h=await HG(e,t),g=(b,v={})=>a(b,{...h===void 0?{}:{confirmation:h},...v});if(h?.status==="not-reproduced")return g({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:h.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await e.interaction.approveRepairRequest(m.prepared.preview))return g({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let w=await by({prepared:m.prepared,authorization:{bindingHash:m.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:s(),authorizationId:oa()},authorizationStore:e.authorizationStore??new Ei,transport:e.remote.transport,now:s()});if(w.kind==="declined")return g({outcome:"abstained-from-repair",reasonCode:w.reasonCode,message:w.message},{proposal:{status:"not-eligible"},repairAudit:w.audit});if(w.kind!=="proposed")return g({outcome:"operation-failed",reasonCode:w.reasonCode,message:w.message},{proposal:{status:"failed"},repairAudit:w.audit});let y=await dw({packet:l,diagnosis:c,grading:u,config:r,snapshot:{workspaceRoot:o.workspaceRoot,gitRoot:o.gitRoot,dirtyPaths:o.dirtyPaths,validation:[]},intent:w.draft.intent,replacements:w.draft.replacements});if(y.kind==="rejected"){let[b]=y.reasons;return g({outcome:"abstained-from-repair",reasonCode:b?.code??"invalid-replacement",message:y.reasons.map(v=>v.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:w.audit,proposalRejections:y.reasons})}return e.proposeOnly===!0?g({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:w.audit,repairProposal:y.proposal}):$P({input:e,now:s,run:t.run,packet:l,diagnosis:c,...t.representativeId===void 0?{}:{representativeId:t.representativeId},...t.clusterStages?.[0]===void 0?{}:{memberIds:t.clusterStages[0].cluster.logicalTestIds},proposal:y.proposal,config:r,repository:o,diagnosisAudit:t.result.audit,repairAudit:w.audit,caps:f,...e.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:e.retryRepairSessionId}},...d===void 0?{}:{ciApprover:d},finish:g})}import{randomUUID as zG}from"node:crypto";import{realpath as qG}from"node:fs/promises";import{join as GG,relative as KG,sep as bw}from"node:path";var WG={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},JG=32*1024*1024,YG=new Set(["applied","validating"]);function QG(){return`vld_${zG().replaceAll("-","").slice(0,24)}`}function XG(e){return{config:e.config,snapshot:{workspaceRoot:e.workspace.workspaceRoot,gitRoot:e.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:e.workspace,maxTargetBytes:e.maxTargetBytes}}function ZG(e,t,n){let r=s=>KG(e,`${t}${bw}${s.split("/").join(bw)}`).split(bw).join("/");for(let s of n.commandRecords){let a=s.artifacts.find(l=>l.path.endsWith("/report.json"));if(a!==void 0)return r(a.path);let d=s.artifacts.filter(l=>Bl.test(l.path.split("/").at(-1)??""))[0];if(d!==void 0)return r(d.path.split("/").slice(0,-1).join("/"))}}async function e9(e,t,n){let r=t.group;if(r===void 0||r.logicalTestIds.length===0||e.checkGroup===void 0)return;let{logicalTestIds:s}=r,a=`${s.length} other test${s.length===1?"":"s"}`,o=await _t(GG(n,r.reportPath),{workspaceRoot:n,gitRoot:t.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),d=o.kind==="parsed"?new Set(o.run.logicalTests.map(p=>p.logicalTestId)):void 0;if(o.kind!=="parsed"||!s.every(p=>d?.has(p)))return{status:"unavailable",logicalTestIds:s,message:`The report fix read has changed, so the group's ${a} were not re-run.`};let l=await e.checkGroup(o.run,s);if(l.kind==="declined")return{status:"declined",logicalTestIds:s,message:`The group's ${a} were not re-run.`};if(l.kind==="unavailable")return{status:"unavailable",logicalTestIds:s,message:l.message};let c=s.filter(p=>l.failedAgain.includes(p)),u=c.map(p=>o.run.logicalTests.find(f=>f.logicalTestId===p)?.title??p).map(p=>`"${p}"`).join(", ");return{status:"rerun",logicalTestIds:s,stillFailing:c,message:c.length===0?`The group's ${a} pass now as well.`:`${c.length} of the group's ${a} still fail${c.length===1?"s":""}: ${u}. The patch stays; run \`kwikqa fix\` again for them.`}}async function Sd(e){let t=e.now??(()=>new Date().toISOString()),n=()=>new Date().toISOString(),r=await qG(e.workspaceRoot),s=await bh(r);if(s.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:s.reasons.map($=>$.message).join(" ")};let a=s.transactions.filter($=>YG.has($.phase));if(a.length!==1||a[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:a.length===0?"There is no applied repair waiting for validation. Run `kwikqa fix` first.":"More than one repair is waiting for validation; recover the workspace first."};let o=await Ne(r,a[0].transactionId),d=o.manifest.preview.authoritativeValidation,l=await EP(r,d.repairSessionId,d.attemptOrdinal);if(l.transactionId!==o.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(l.plan.planHash!==d.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=XG(l),u=l.transactionId,p=l.plan,f=[],m;if(o.state.phase==="validating"){let $=o.state.history.findLast(O=>O.type==="validation-started");if($?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");m=$.validationRunId}else{m=QG();let $=await zy({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,now:n()});if($.kind==="rejected"||$.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:$.reasons.map(O=>O.message).join(" ")};for(let O of p.commands)if(!(!O.required||O.timing!=="post-patch")){if(e.signal?.aborted===!0)break;await Gr({workspaceRoot:r,repositoryRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,commandId:O.commandId,limits:WG,...e.signal===void 0?{}:{signal:e.signal}}).catch(I=>{qr(O.kind)&&f.push($a(I))})}}let h=await _m({workspaceRoot:r,gitRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,...l.baseline===void 0?{}:{baseline:l.baseline},reportMaxBytes:JG,completedAt:n()}),g=h.manifest,w={repairSessionId:l.repairSessionId,attempt:l.attempt,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash},y;if(g.status==="passed"){let $=await qy({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash,now:n(),approvedCommands:p.commands.map(O=>({commandId:O.commandId,executable:O.executable}))});if($.kind==="completed"){await Po({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let O=await e9(e,l,r);return vw(e,l,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${O?.message===void 0?"":` ${O.message}`}`,application:"applied",validation:"passed",repair:w,...O===void 0?{}:{groupCheck:O}})}y="reasons"in $?$.reasons.map(O=>O.message).join(" "):"KwikQA couldn't complete the validation."}y===void 0&&await Po({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let b=await vh(c,u,n());y!==void 0&&await Po({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let v=y!==void 0?"unavailable":g.status==="passed"?"incomplete":g.status,R=v==="failed"?"validation-failed":v==="unavailable"?"validation-unavailable":"validation-incomplete";if(b.kind!=="rolled-back")return vw(e,l,t,{outcome:"repair-failed",reasonCode:"rollback-conflicted",message:"Validation did not pass and the patch could not be rolled back automatically because the files changed; resolve them manually.",application:"recovery-required",validation:v==="blocked"?"incomplete":v,repair:w});let P=(await Sh({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,proof:{transactionId:u,phase:"rolled-back",transactionRevision:b.transaction.revision},now:t()})).retry!==void 0,E=P?ZG(r,h.directory,g):void 0;return vw(e,l,t,{outcome:"repair-failed",reasonCode:R,message:`${f.length===0?"":`KwikQA couldn't complete a command: ${f.join(" ")} `}${y===void 0?"":`${y} `}${P?"Validation did not pass, so the patch was rolled back. One retry is available.":"Validation did not pass, so the patch was rolled back. No retry remains."}`,application:"rolled-back",validation:v==="blocked"?"incomplete":v,repair:{...w,retryAvailable:P,...E===void 0?{}:{retryReportPath:E}}})}async function vw(e,t,n,r){let s={schemaVersion:"1.5",recordId:Nu(),command:"validate",...t.record,recordedAt:n(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:r.application},validation:{status:r.validation},repair:r.repair,...r.groupCheck===void 0?{}:{groupCheck:r.groupCheck},outcome:r.outcome,reasonCode:r.reasonCode,message:r.message};if(e.persist===!1)return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s};try{let a=await gd(t.workspace.workspaceRoot,s);return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,recordPath:a}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${s.message} The run record could not be written safely under .kwikqa/runs/.`,record:s}}}import{readFile as t9}from"node:fs/promises";var Ad="X-KwikQA-CI";function kw(e){let t=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[^A-Za-z0-9]+/,"");return t===void 0||t===""?void 0:t.slice(0,100)}function n9(e){let t=(e??"").split("/").map(n=>kw(n)).filter(n=>n!==void 0);return t.length===0?void 0:t.join("/").slice(0,200)}function Rw(e){try{return e===void 0||e===""?void 0:new URL(e).host.toLowerCase()}catch{return}}function rE(e){return e==="public"||e==="internal"||e==="private"?e:void 0}function rp(e,t){let n=n9(t.owner),r=kw(t.name),s=kw(t.author);if(!(t.host===void 0||n===void 0||r===void 0))return{system:e,host:t.host,owner:n,name:r,...t.visibility===void 0?{}:{visibility:t.visibility},...s===void 0?{}:{author:s}}}async function r9(e){let[t,n]=(e.GITHUB_REPOSITORY??"").split("/"),r={};try{e.GITHUB_EVENT_PATH!==void 0&&e.GITHUB_EVENT_PATH!==""&&(r=JSON.parse(await t9(e.GITHUB_EVENT_PATH,"utf8")))}catch{r={}}let s=r.repository,a=rE(s?.visibility)??(s?.private===!0?"private":s?.private===!1?"public":void 0),o=r.pull_request?.user?.login;return rp("github",{host:Rw(e.GITHUB_SERVER_URL)??"github.com",owner:t,name:n,...a===void 0?{}:{visibility:a},...typeof o=="string"?{author:o}:{}})}function i9(e){let t=e.CI_PROJECT_PATH??"",n=t.lastIndexOf("/"),r=rE(e.CI_PROJECT_VISIBILITY);return rp("gitlab",{host:e.CI_SERVER_HOST?.toLowerCase()??Rw(e.CI_SERVER_URL),owner:n>0?t.slice(0,n):e.CI_PROJECT_NAMESPACE,name:n>0?t.slice(n+1):e.CI_PROJECT_NAME,...r===void 0?{}:{visibility:r},...e.CI_MERGE_REQUEST_IID===void 0?{}:{author:e.GITLAB_USER_LOGIN}})}function s9(e){let t=e.SYSTEM_COLLECTIONURI??"",n;try{n=new URL(t).pathname.split("/").filter(Boolean)[0]}catch{n=void 0}return rp("azure",{host:Rw(t),owner:[n,e.SYSTEM_TEAMPROJECT].filter(Boolean).join("/"),name:e.BUILD_REPOSITORY_NAME,...e.BUILD_REASON==="PullRequest"?{author:e.BUILD_REQUESTEDFORID}:{}})}function a9(e){let t=e.GIT_URL??e.CHANGE_URL??"",n=/^(?:https?:\/\/([^/]+)\/|git@([^:]+):)(.+?)\/([^/]+?)(?:\.git)?(?:\/(?:pull|-\/merge_requests)\/\d+)?\/?$/.exec(t),r=(n?.[1]??n?.[2])?.toLowerCase();return rp("jenkins",{host:r,owner:n?.[3],name:n?.[4],...e.CHANGE_AUTHOR===void 0?{}:{author:e.CHANGE_AUTHOR}})}function xw(e){if(e.GITHUB_ACTIONS==="true")return"github";if(e.TF_BUILD==="True")return"azure";if(e.GITLAB_CI==="true")return"gitlab";if(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)return"jenkins"}async function iE(e){switch(xw(e)){case"github":return r9(e);case"azure":return s9(e);case"gitlab":return i9(e);case"jenkins":return a9(e);default:return}}function sE(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function aE(e){let t=l=>{let c=e[l]?.trim();return c===void 0||c===""?void 0:c},n=t("KWIKQA_SHARD"),r,s;if(e.GITHUB_ACTIONS==="true"){let l=t("GITHUB_RUN_ID");r=l===void 0?void 0:`${l}-${t("GITHUB_RUN_ATTEMPT")??"1"}`,s=[t("GITHUB_JOB"),t("RUNNER_NAME")].filter(Boolean).join(":")||void 0}else if(e.TF_BUILD==="True"){let l=t("BUILD_BUILDID");r=l===void 0?void 0:`${l}-${t("SYSTEM_JOBATTEMPT")??"1"}`,s=t("SYSTEM_JOBID")}else e.GITLAB_CI==="true"?(r=t("CI_PIPELINE_ID"),s=t("CI_JOB_ID")):(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)&&(r=t("BUILD_TAG"),s=[t("STAGE_NAME"),t("NODE_NAME"),t("EXECUTOR_NUMBER")].filter(Boolean).join(":")||void 0);s=n??s;let a=l=>l===void 0?void 0:l.replace(/[^A-Za-z0-9._:/-]/g,"-").slice(0,200),o=a(r),d=a(s);return o===void 0||d===void 0?void 0:{run:o,job:d}}var o9="X-KwikQA-CI-Identity",d9="https://kwikqa.com",l9=6e4,c9=6e4,u9=1e4;function p9(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}function f9(e,t,n,r){let s,a=0;return{token:async()=>{if(s!==void 0&&s.until>r())return s.value;if(!(a>r()))try{let o=new URL(e);if(o.protocol!=="https:")return;o.searchParams.set("audience",d9);let d=await n(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(u9)}),l=await d.json();if(!d.ok||typeof l.value!="string"||l.value==="")throw new Error("no token");let c=p9(l.value)??r()+5*6e4;return s={value:l.value,until:c-l9},l.value}catch{s=void 0,a=r()+c9;return}}}}function oE(e,t,n=Date.now){let r=e.KWIKQA_ID_TOKEN?.trim();if(r!==void 0&&r!=="")return{token:async()=>r};let s=e.ACTIONS_ID_TOKEN_REQUEST_URL,a=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(e.GITHUB_ACTIONS==="true"&&s&&a)return f9(s,a,t,n)}function dE(e,t){return t===void 0?e:(async(n,r)=>{let s=new Headers(r?.headers);if(!s.has(Ad))return e(n,r);let a=await t.token();return a!==void 0&&s.set(o9,a),e(n,{...r,headers:s})})}var m9=1200*1e3,h9=10,g9=1e3,y9=15e3,w9=3e3,b9=6e4,lE=3e4,v9=2;function Iw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function uE(e){try{let t=await e.json();return Iw(t)?t:void 0}catch{return}}async function k9(e){return await uE(e)??{}}function cE(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(y9,Math.max(g9,e)):w9}function _w(e){let t=Iw(e.error)?e.error:void 0;return typeof t?.message=="string"?t.message:void 0}var ip=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let n=performance.now(),r=()=>performance.now()-n;for(let s=0;;s+=1){let a=await this.#e(t,r);if(a!=="interrupted")return a;if(s===v9)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:r()};this.options.onRestart?.()}}async#e(t,n){let r=(p,f)=>({kind:"failed",code:p,message:f,elapsedMs:n()}),s=At(t);if(s!==void 0)return{kind:"failed",code:"invalid-request",message:s,elapsedMs:0};let a;try{a=await this.#n("POST","/v1/jobs",b9,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(p){return r("network-error",`The model request could not reach the KwikQA service (${Ni(p)}).`)}let o=await k9(a);if(a.status!==202){let p=eu(o);return{kind:"failed",code:"http-error",message:_w(o)??"The KwikQA service refused the model request.",httpStatus:a.status,...p===void 0?{}:{providerCode:p},elapsedMs:n()}}let d=o.jobId;if(typeof d!="string"||d==="")return r("invalid-json","The KwikQA service did not name the job it started.");let l=this.options.sleep??(p=>new Promise(f=>setTimeout(f,p))),c=cE(o.pollAfterMs),u=0;for(;;){if(n()>(this.options.maxWaitMs??m9))return await this.#t(d),r("timeout","The model did not answer in time; nothing was charged.");await l(c);let p;try{p=await this.#n("GET",`/v1/jobs/${d}`,lE)}catch{p=new Response(null,{status:599})}let f=p.status>=500?void 0:await uE(p);if(p.status===404)return"interrupted";if(p.status<500&&!p.ok)return{kind:"failed",code:"http-error",message:_w(f??{})??"The KwikQA service refused to report the job.",httpStatus:p.status,elapsedMs:n()};if(f===void 0){if(u+=1,u>h9)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}if(u=0,f.status==="running"){this.options.onProgress?.(n()),c=cE(f.pollAfterMs);continue}if(f.status==="failed")return Iw(f.error)&&f.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:_w(f)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:n()};if(f.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#t(d);let m=typeof f.httpStatus=="number"?f.httpStatus:502,h=f.result,g=m>=200&&m<300;if(!g||ld(h)){let w=eu(h),y=g?w??502:m;return{kind:"failed",code:"http-error",message:Kg(y,h),httpStatus:y,...w===void 0?{}:{providerCode:w},elapsedMs:n()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:m,body:h,elapsedMs:n()}}}async#t(t){try{await this.#n("DELETE",`/v1/jobs/${t}`,lE)}catch{}}#n(t,n,r,s={}){return this.options.fetch(`${this.options.baseUrl}${n}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...s.headers},...s.body===void 0?{}:{body:s.body},redirect:"error",signal:AbortSignal.timeout(r)})}};var qi="0.8.0";var R9="https://api.kwikqa.com",Nn="https://kwikqa.com/dashboard/";function pE(e){return e.hosted??!(e.plan==="byo"||e.plan==="byo-team"||e.plan==="byo-enterprise")}function x9(e){return e?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var yt=class extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r}status;code};function cr(e,t){return(e.KWIKQA_API_URL??(t===void 0||t===""?R9:t)).replace(/\/+$/,"")}function fE(e){let t=e?.messages;if(!Array.isArray(t))return;let n=t.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(n!==void 0)try{let r=JSON.parse(n.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var _9=`kwikqa/${qi}`;function I9(e){return((t,n)=>{let r=new Headers(n?.headers);return r.set("User-Agent",_9),e(t,{...n,headers:r})})}var Ht=class{constructor(t,n,r=fetch,s,a){this.baseUrl=t;this.token=n;this.ciContext=s;this.fetchImpl=I9(dE(r,a))}baseUrl;token;ciContext;fetchImpl;async#e(t,n,r,s,a){let o=()=>this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:{Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...s===void 0?{}:{"X-KwikQA-Retry-Ticket":s},...a===void 0?{}:{"X-KwikQA-Session":a},...this.ciContext===void 0?{}:{[Ad]:this.ciContext}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),d;try{d=await o().catch(c=>{if(t==="GET")return o();throw c})}catch(c){throw new yt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${Ni(c)}).`)}let l;try{l=await d.json()}catch{l=void 0}if(!d.ok){let c=l?.error;throw new yt(d.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${d.status}.`)}return l}startDeviceLogin(){return this.#e("POST","/v1/auth/device")}pollDeviceLogin(t){return this.#e("POST","/v1/auth/token",{deviceCode:t})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(t,n){return this.#e("POST","/v1/billing/checkout",{plan:t,...n})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(t,n,r){return this.#e("POST","/v1/usage/reserve",t,n,r)}openSession(t,n="diagnosis"){return this.#e("POST","/v1/usage/session",n==="diagnosis"?{requests:t}:{requests:t,kind:n})}async claimGroups(t,n,r){let s=await this.#e("POST","/v1/ci/groups",{run:t,job:n,groups:r});return new Map((s.groups??[]).flatMap(a=>typeof a.group=="string"&&(a.diagnosedBy==="this-job"||a.diagnosedBy==="another-job")?[[a.group,a.diagnosedBy]]:[]))}async closeSession(t){let r=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,t))?.retryTicket;return typeof r=="string"&&r!==""?{retryTicket:r}:{}}reportInsights(t){return this.#e("POST","/v1/insights",{events:t})}reportResults(t){return this.#e("POST","/v1/results",{events:t})}releaseUsage(t,n){return this.#e("POST","/v1/usage/release",{id:t,status:n})}logout(){return this.#e("POST","/v1/auth/logout")}transport(t){let n=a=>{let o=fE(a),d=x9(a)?t.session?.():t.repairSession?.();return{...t.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":t.retryTicket},...d===void 0?{}:{"X-KwikQA-Session":d},...o===void 0?{}:{"X-KwikQA-Framework":o},...this.ciContext===void 0?{}:{[Ad]:this.ciContext}}},r=a=>{let o=a?.kwikqa?.retryTicket;typeof o=="string"&&o!==""&&t.onRetryTicket?.(o)},s=new Ci({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:n,onCompletionBody:r});return t.jobs!==!0||this.token===void 0?s:new ip({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:s,headers:n,onCompletionBody:r,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},sp=class{constructor(t,n,r={}){this.inner=t;this.client=n;this.options=r}inner;client;options;get routing(){return this.inner.routing??"router"}preflight(t){return this.inner.preflight(t)}async complete(t){let r=t.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",s;try{let o=fE(t.body);s=await this.client.reserveUsage({kind:r,model:t.route.modelId,provider:t.route.providerSlug,...o===void 0?{}:{framework:o}},this.options.retryTicket,r==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(o){if(!(o instanceof yt))throw o;return{kind:"failed",code:"http-error",message:o.message,elapsedMs:0,...o.status===0?{}:{httpStatus:o.status}}}s.retryTicket!==void 0&&this.options.onRetryTicket?.(s.retryTicket);let a=await this.inner.complete(t);return a.kind!=="response"&&await this.client.releaseUsage(s.id,a.httpStatus??599).catch(()=>{}),a}};var T9={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},S9={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function mE(e){let t=(e.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function wt(e){return`${T9[mE(e)]} kwikqa`}function Tw(e,t){return`${S9[mE(e)]} ${t}`}var U={ok:0,failed:1,usage:2,account:3};function Pd(e){return`Not signed in. Run \`${wt(e.env)} login\` first.`}function Lr(e,t){for(let n of t.messages)e.io.error(n);return t.exit}function hE(e){return e==="repair-failed"||e==="validation-unavailable"||e==="operation-failed"?U.failed:U.ok}async function zt(e,t){try{return await t()}catch(n){if(n instanceof yt)return e.io.error(n.message),[401,402,403,409].includes(n.status)?U.account:U.failed;throw n}}function ap(e){return e.sleep??(t=>new Promise(n=>setTimeout(n,t)))}function gE(e,t){let n=(e.env.CI??"").trim().toLowerCase();return t&&e.io.interactive&&(n===""||n==="false"||n==="0")}import{spawn as A9}from"node:child_process";function yE(e,t=process.platform){let n;try{n=new URL(e)}catch{return Promise.resolve(!1)}if(n.protocol!=="https:"&&n.protocol!=="http:")return Promise.resolve(!1);let[r,s]=t==="darwin"?["open",[n.href]]:t==="win32"?["explorer.exe",[n.href]]:["xdg-open",[n.href]];return new Promise(a=>{try{let o=A9(r,s,{stdio:"ignore",detached:!0});o.once("error",()=>a(!1)),o.once("spawn",()=>{o.unref(),a(!0)})}catch{a(!1)}})}import{mkdir as P9,readFile as E9,rm as C9,writeFile as N9}from"node:fs/promises";import{homedir as wE}from"node:os";import{join as Ed}from"node:path";function bE(e){return e.KWIKQA_CONFIG_DIR!==void 0&&e.KWIKQA_CONFIG_DIR!==""?e.KWIKQA_CONFIG_DIR:process.platform==="win32"?Ed(e.APPDATA??Ed(wE(),"AppData","Roaming"),"kwikqa"):Ed(e.XDG_CONFIG_HOME??Ed(wE(),".config"),"kwikqa")}function Sw(e){return Ed(bE(e),"credentials.json")}async function On(e){if(e.KWIKQA_TOKEN!==void 0&&e.KWIKQA_TOKEN.trim()!=="")return{token:e.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await E9(Sw(e),"utf8"));return typeof t.token!="string"||t.token===""||typeof t.login!="string"||typeof t.apiUrl!="string"?void 0:{token:t.token,login:t.login,apiUrl:t.apiUrl}}catch{return}}async function vE(e,t){await P9(bE(e),{recursive:!0,mode:448}),await N9(Sw(e),`${JSON.stringify(t)}
258
+ `),{},"change",s)){let f=await IG(u,p,s);d.push({kind:"failed",path:e,line:f,message:ZP(p)})}return{changedLines:o,findings:d}}async function IG(e,t,n){for(let[r,s]of e.added.entries())if((await Yu("",s,{},"change",n)).includes(t))return e.resultLine+r;return e.resultLine}function ZP(e){let t=`${e.charAt(0).toUpperCase()}${e.slice(1)}`;return t.endsWith(".")?t:`${t}.`}function TG(e){return[...e].sort((t,n)=>(t.path===void 0?1:0)-(n.path===void 0?1:0)||(t.path??"").localeCompare(n.path??"")||(t.line??0)-(n.line??0))}function hw(e,t){let n=TG(t);return{gate:e,status:n.some(r=>r.kind==="failed")?"failed":n.some(r=>r.kind==="not-checked")?"not-checked":"passed",findings:n}}async function yw(e){let t=new Date().toISOString(),n=await yG(e.workspaceRoot),r=await sn(n),s=e.configPath??bG,a=await Fg(r,"HEAD");if(a===void 0)return{kind:"unavailable",reason:"no-repository",message:"`kwikqa check` compares your changes with a commit, so it needs a git repository with at least one commit."};let o={revision:"HEAD",commit:a};if(e.base!==void 0){let O=await Fg(r,e.base),I=O===void 0?void 0:await mS(r,O);if(I===void 0)return{kind:"unavailable",reason:"unknown-base",message:O===void 0?`\`--base ${e.base}\` names no commit in this repository. Fetch it first, or name a branch, tag, or commit.`:`The current branch shares no history with ${e.base}.`};o={revision:e.base,commit:I}}let d=await kG({workspaceRoot:n,gitRoot:r},o,s);if(d.kind!=="valid")return{kind:"unavailable",reason:d.kind,message:d.message};let{config:l}=d,c=e.analysis===void 0?void 0:await GP(wG(n,e.analysis),e.analysis);if(c?.kind==="unreadable")return{kind:"unavailable",reason:"analysis-unreadable",message:c.message};let u=[],p=[],f=0,m=0;for(let O of await hS(r,o.commit)){let I=gS(n,r,O.path);if(I===void 0){u.push({path:O.path,change:O.change,scope:"outside"}),p.push({kind:"failed",path:O.path,message:"Outside this workspace, so outside the test code kwikqa.config.json lets KwikQA edit."});continue}if(xG(I))continue;let N=Jn(I)?void 0:di(I,l.editablePaths);if(N===void 0||Yn(I,l)){let C=O.change==="deleted"?void 0:await W(n,I,tp);u.push({path:I,change:O.change,scope:"outside",...C?.kind==="read"?{sha256:C.sha256}:{}}),p.push({kind:"failed",path:I,message:"Outside the test code kwikqa.config.json lets KwikQA edit. KwikQA never changes other files to make a test pass, so a change that does fails the check."});continue}if(f+=1,O.change==="deleted"){u.push({path:I,change:"deleted",scope:N.class}),p.push({kind:"failed",path:I,message:"Deleted. Deleting test code deletes the tests it holds or supports."});continue}let T=O.change==="added"?{kind:"read",bytes:new Uint8Array}:await rr(r,o.commit,O.path,tp),S=await W(n,I,tp),L=T.kind==="read"?gw(T.bytes):T.kind,j=S.kind==="read"?gw(S.bytes):void 0,M;S.kind==="unauthorized"?M={findings:[{kind:"failed",path:I,message:"Not a regular file inside the workspace, such as a symbolic link."}]}:L==="over-budget"||S.kind==="over-budget"?M={findings:[{kind:"not-checked",path:I,message:`Larger than ${tp} bytes, so its change was not checked.`}]}:L===void 0||L==="absent"||j===void 0?M={findings:[{kind:"not-checked",path:I,message:"Not readable as UTF-8 text, so its change was not checked."}]}:M=await _G(I,L,j),m+=M.changedLines??0,u.push({path:I,change:O.change,scope:N.class,...M.changedLines===void 0?{}:{changedLines:M.changedLines},...S.kind==="read"?{sha256:S.sha256}:{}}),p.push(...M.findings)}if(u.length===0)return{kind:"nothing-to-check",base:o,message:o.revision==="HEAD"?"Nothing to check: there are no uncommitted changes.":`Nothing to check: nothing changed since the branch left ${o.revision}.`};let{maxFiles:h,maxChangedLines:g}=l.budgets;(f>h||m>g)&&p.push({kind:"failed",message:`The change touches ${f} test file${f===1?"":"s"} and ${m} line${m===1?"":"s"}; kwikqa.config.json lets one repair change at most ${h} file${h===1?"":"s"} and ${g} lines.`});let w=await JP({workspaceRoot:n,gitRoot:r,base:o,changes:u,...c===void 0?{}:{analysis:c.record}}),y=hw("scope-and-policy",p),b={...hw("ownership",w.findings),...w.analysis===void 0?{}:{analysis:w.analysis}},v={workspaceRoot:n,gitRoot:r,base:o,changes:u,tests:w.tests,earlierGateFailed:y.status==="failed"||b.status==="failed",...e.validation===void 0?{}:{interaction:e.validation},...e.validationTimeoutMs===void 0?{}:{timeoutMs:e.validationTimeoutMs}},R=w.record,_=R?.framework!==void 0&&Hn(R.framework)?R.framework:void 0,P=hw("validation",R!==void 0&&_!==void 0?await VP({...v,record:R,framework:_,allRefused:w.allRefused===!0}):await FP({...v,...R===void 0?{}:{record:R}})),E=[y,b,P];return{kind:"checked",outcome:E.some(O=>O.status==="failed")?"failed":E.some(O=>O.status==="not-checked")?"incomplete":"passed",checkedAt:t,base:o,changes:u,gates:E}}import{createHash as SG}from"node:crypto";import{join as AG,relative as PG,sep as EG}from"node:path";var tE="kwikqa.config.json",CG=256*1024;async function nE(e,t){let n=await W(e,t,CG);if(n.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${t}; none was found in the workspace.`};if(n.kind!=="read")return{kind:"repair-config-invalid",message:`${t} could not be read: ${n.message}`};let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{return{kind:"repair-config-invalid",message:`${t} is not valid UTF-8 JSON.`}}let s=dr(r);return s.kind!=="valid"?{kind:"repair-config-invalid",message:s.issues.join(" ")}:{...s,bytes:n.bytes}}async function zi(e,t=tE){let n=await nE(e,t);return n.kind==="valid"?n.config.ci?.fix:void 0}async function NG(e,t,n,r){if(e.ci===void 0)return{};if(t.config.ci?.fix===void 0)return{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-missing",message:`\`kwikqa fix\` needs a terminal, unless ${r} has a committed ci.fix policy, which lets it validate a repair on this runner and open a draft pull request.`}};let s=PG(n.gitRoot,AG(n.workspaceRoot,r)).split(EG).join("/");return await fS(n.gitRoot,s,t.bytes)?{approver:{kind:"ci-policy",...e.ci,policyHash:SG("sha256").update(t.bytes).digest("hex")}}:{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-uncommitted",message:`${r} differs from its committed version, so its ci.fix policy wasn't reviewed; a fix in CI runs only under the committed policy.`}}}function OG(e,t,n){let r=new Set(n.map(a=>a.toLocaleLowerCase("en-US"))),s=new Set;for(let a of e.evidence){if(a.locator.type!=="source-range")continue;let o=a.locator.path;di(o,t.editablePaths)!==void 0&&!Yn(o,t)&&!Jn(o)&&!r.has(o.toLocaleLowerCase("en-US"))&&s.add(o)}return[...s].sort()}async function np(e){let t=e.now??(()=>new Date().toISOString()),n=await Cr(e.workspaceRoot);if(n.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:n.message};let{workspaceRoot:r,gitRoot:s,dirtyPaths:a,pristine:o}=n.status,d=e.configPath??tE,l=await nE(r,d);if(l.kind!=="valid")return{outcome:"operation-failed",reasonCode:l.kind,message:l.message};let c=l.config,u=await NG(e,l,{workspaceRoot:r,gitRoot:s},d);if("refusal"in u)return u.refusal;let{approver:p}=u;if(e.retryRepairSessionId!==void 0&&(await Ir(r,e.retryRepairSessionId).catch(()=>{}))?.state!=="retry-approval-required")return{outcome:"operation-failed",reasonCode:"no-retry-available",message:"That repair session has no retry available; only one retry follows a failed validation."};let f=await wd({...e,workspaceRoot:r,gitRoot:s,repairableOnly:!0},t);if(f.kind==="unreadable")return{outcome:f.outcome,reasonCode:f.reasonCode,message:f.message};let{stage:m}=f,h={workspaceRoot:r,gitRoot:s,dirtyPaths:a},g=(_,P=[],E)=>($,O={})=>Fu(_,Du(_,"fix",P.length===0?$:{...$,message:`${P.join(" ")} ${$.message}`},t,{repository:{pristine:o,dirtyPaths:a},...O}),e.persist!==!1).then(I=>E===void 0?I:{...I,fixGroups:E}),w=FG(m,e);if("refusal"in w)return g(m)(w.refusal);let y=e.oneGroup===void 0?void 0:VG(m);if(w.groups.length===0&&e.oneGroup!==void 0)return g(m,[],{groups:y??[]})({outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:BG(e.oneGroup)});if(w.groups.length===0){let{packet:_}=m,{diagnosis:P,grading:E}=m.result;return m.result.outcome!=="diagnosed"||_===void 0||P===void 0||E===void 0?g(m)(m.result):eE(e,m,{packet:_,diagnosis:P,grading:E},c,t,g(m),h,p)}let b=(m.clusterStages??[]).flatMap(_=>_.refusal===void 0?[]:[_.refusal.message]),v=[],R=new Map;for(let _ of w.groups){let P=await e.fixInReview?.(_.cluster.signals);P===void 0?v.push(_):(R.set(_.representativeId,P),b.push(`Failure group ${ww(m,_)}: ${P.reason}.`))}if(v.length===0)return g(m,[],y===void 0?void 0:{groups:UG(y,R)})({outcome:"abstained-from-repair",reasonCode:"fix-in-review",message:b.join(" ")});await e.repairSession?.open(v.length);try{let _;for(let P of v){let E=DG(m,P),{packet:$}=E,{diagnosis:O,grading:I}=P.result;if($===void 0||O===void 0||I===void 0)continue;let N=y===void 0?void 0:{groups:y,attempted:P.representativeId};if(_=await eE(e,E,{packet:$,diagnosis:O,grading:I},c,t,g(E,b,N),h,p),!LG(_))return _;b.push(`Failure group ${ww(m,P)}: ${_.message}`)}return _??g(m)(m.result)}finally{await e.repairSession?.close()}}var MG=3,$G=new Set(["model-declined-repair","repair-not-eligible","failure-not-reproduced","insufficient-ownership-evidence","intent-ambiguous","invalid-replacement","unauthorized-target","dirty-target-file","source-hash-mismatch","non-unique-match","overlapping-replacement","forbidden-edit","parse-failed","budget-exceeded","unreadable-target"]);function LG(e){return e.outcome==="abstained-from-repair"?$G.has(e.reasonCode):e.outcome==="validation-unavailable"&&e.record?.application.status==="not-run"}function ww(e,t){return(e.clusterStages??[]).indexOf(t)+1}function DG(e,t){return{...e,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},result:t.result,clusterStages:[t,...(e.clusterStages??[]).filter(n=>n!==t)],representativeId:t.representativeId}}function FG(e,t){let n=e.clusterStages??[];if(t.group!==void 0){let a=n[t.group-1];return a===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${t.group}; this run has ${n.length}.`}}:a.refusal!==void 0?{refusal:{outcome:"abstained-from-repair",reasonCode:"not-a-browser-test",message:a.refusal.message}}:da([a]).includes(a)?{groups:[a]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${t.group} is not diagnosed as the test's fault (${a.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=da(n);if(t.oneGroup!==void 0)return{groups:jG(r,t.oneGroup)};let s=t.repairSession===void 0||t.retryRepairSessionId!==void 0?1:MG;return{groups:r.slice(0,s)}}function jG(e,t){let{retryOf:n}=t,r=n===void 0?e.find(s=>!t.tried.includes(s.representativeId)):e.find(s=>s.cluster.logicalTestIds.includes(n));return r===void 0?[]:[r]}function BG(e){return e.retryOf===void 0?"No repair-eligible failure group is left to try, so no repair was requested.":"The failure group whose validation failed is no longer repair-eligible in the retry's report, so no repair was requested."}function VG(e){let t=e.clusterStages??[],n=new Set(da(t));return t.map(r=>({number:ww(e,r),representativeId:r.representativeId,logicalTestIds:r.cluster.logicalTestIds,repairable:n.has(r),reasonCode:r.result.reasonCode,message:r.result.message}))}function UG(e,t){return e.map(n=>{let r=t.get(n.representativeId);return r===void 0?n:{...n,inReview:r}})}async function HG(e,t){let{interaction:n}=e;if(n.confirmFailure===void 0||e.retryRepairSessionId!==void 0)return;let r=t.clusterStages?.[0]?.cluster.logicalTestIds??t.failing,s=t.representativeId??r[0];if(s===void 0)return;let a=await n.confirmFailure(t.run,r);if(a.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(a.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:a.message};let o=r.filter(l=>a.failedAgain.includes(l));if(o.includes(s))return{status:"reproduced",logicalTestIds:r,failedAgain:o};let d=t.run.logicalTests.find(l=>l.logicalTestId===s)?.title;return{status:"not-reproduced",logicalTestIds:r,failedAgain:o,message:`${d===void 0?"The failing test":`"${d}"`} passed when re-run, so the failure looks flaky or depends on state the re-run did not have. KwikQA does not patch a test that passes; no repair was requested.`}}async function eE(e,t,n,r,s,a,o,d){let{packet:l,diagnosis:c,grading:u}=n,p=[...c.hypotheses].sort((b,v)=>b.rank-v.rank)[0],f=e.repairCaps??e.remote.caps,m=await wy({packet:l,diagnosis:c,grading:u,hypothesisId:p?.hypothesisId??"",editablePaths:OG(l,r,o.dirtyPaths),budgets:r.budgets,model:e.repairModel??e.remote.model,caps:f,transport:e.remote.transport,now:s()});if(m.kind!=="preview-ready"){let b=m.reasonCode==="repair-not-eligible"&&p?.probableOwner!=="test-support"?Lu(c):m.reasonCode,v=m.reasonCode==="repair-not-eligible"||$u.has(m.reasonCode);return a({outcome:v?"abstained-from-repair":"operation-failed",reasonCode:b,message:m.message},{proposal:{status:v?"not-eligible":"failed"},repairAudit:m.audit})}let h=await HG(e,t),g=(b,v={})=>a(b,{...h===void 0?{}:{confirmation:h},...v});if(h?.status==="not-reproduced")return g({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:h.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await e.interaction.approveRepairRequest(m.prepared.preview))return g({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let w=await by({prepared:m.prepared,authorization:{bindingHash:m.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:s(),authorizationId:oa()},authorizationStore:e.authorizationStore??new Ei,transport:e.remote.transport,now:s()});if(w.kind==="declined")return g({outcome:"abstained-from-repair",reasonCode:w.reasonCode,message:w.message},{proposal:{status:"not-eligible"},repairAudit:w.audit});if(w.kind!=="proposed")return g({outcome:"operation-failed",reasonCode:w.reasonCode,message:w.message},{proposal:{status:"failed"},repairAudit:w.audit});let y=await dw({packet:l,diagnosis:c,grading:u,config:r,snapshot:{workspaceRoot:o.workspaceRoot,gitRoot:o.gitRoot,dirtyPaths:o.dirtyPaths,validation:[]},intent:w.draft.intent,replacements:w.draft.replacements});if(y.kind==="rejected"){let[b]=y.reasons;return g({outcome:"abstained-from-repair",reasonCode:b?.code??"invalid-replacement",message:y.reasons.map(v=>v.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:w.audit,proposalRejections:y.reasons})}return e.proposeOnly===!0?g({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:w.audit,repairProposal:y.proposal}):$P({input:e,now:s,run:t.run,packet:l,diagnosis:c,...t.representativeId===void 0?{}:{representativeId:t.representativeId},...t.clusterStages?.[0]===void 0?{}:{memberIds:t.clusterStages[0].cluster.logicalTestIds},proposal:y.proposal,config:r,repository:o,diagnosisAudit:t.result.audit,repairAudit:w.audit,caps:f,...e.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:e.retryRepairSessionId}},...d===void 0?{}:{ciApprover:d},finish:g})}import{randomUUID as zG}from"node:crypto";import{realpath as qG}from"node:fs/promises";import{join as GG,relative as KG,sep as bw}from"node:path";var WG={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},JG=32*1024*1024,YG=new Set(["applied","validating"]);function QG(){return`vld_${zG().replaceAll("-","").slice(0,24)}`}function XG(e){return{config:e.config,snapshot:{workspaceRoot:e.workspace.workspaceRoot,gitRoot:e.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:e.workspace,maxTargetBytes:e.maxTargetBytes}}function ZG(e,t,n){let r=s=>KG(e,`${t}${bw}${s.split("/").join(bw)}`).split(bw).join("/");for(let s of n.commandRecords){let a=s.artifacts.find(l=>l.path.endsWith("/report.json"));if(a!==void 0)return r(a.path);let d=s.artifacts.filter(l=>Bl.test(l.path.split("/").at(-1)??""))[0];if(d!==void 0)return r(d.path.split("/").slice(0,-1).join("/"))}}async function e9(e,t,n){let r=t.group;if(r===void 0||r.logicalTestIds.length===0||e.checkGroup===void 0)return;let{logicalTestIds:s}=r,a=`${s.length} other test${s.length===1?"":"s"}`,o=await _t(GG(n,r.reportPath),{workspaceRoot:n,gitRoot:t.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),d=o.kind==="parsed"?new Set(o.run.logicalTests.map(p=>p.logicalTestId)):void 0;if(o.kind!=="parsed"||!s.every(p=>d?.has(p)))return{status:"unavailable",logicalTestIds:s,message:`The report fix read has changed, so the group's ${a} were not re-run.`};let l=await e.checkGroup(o.run,s);if(l.kind==="declined")return{status:"declined",logicalTestIds:s,message:`The group's ${a} were not re-run.`};if(l.kind==="unavailable")return{status:"unavailable",logicalTestIds:s,message:l.message};let c=s.filter(p=>l.failedAgain.includes(p)),u=c.map(p=>o.run.logicalTests.find(f=>f.logicalTestId===p)?.title??p).map(p=>`"${p}"`).join(", ");return{status:"rerun",logicalTestIds:s,stillFailing:c,message:c.length===0?`The group's ${a} pass now as well.`:`${c.length} of the group's ${a} still fail${c.length===1?"s":""}: ${u}. The patch stays; run \`kwikqa fix\` again for them.`}}async function Sd(e){let t=e.now??(()=>new Date().toISOString()),n=()=>new Date().toISOString(),r=await qG(e.workspaceRoot),s=await bh(r);if(s.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:s.reasons.map($=>$.message).join(" ")};let a=s.transactions.filter($=>YG.has($.phase));if(a.length!==1||a[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:a.length===0?"There is no applied repair waiting for validation. Run `kwikqa fix` first.":"More than one repair is waiting for validation; recover the workspace first."};let o=await Ne(r,a[0].transactionId),d=o.manifest.preview.authoritativeValidation,l=await EP(r,d.repairSessionId,d.attemptOrdinal);if(l.transactionId!==o.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(l.plan.planHash!==d.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=XG(l),u=l.transactionId,p=l.plan,f=[],m;if(o.state.phase==="validating"){let $=o.state.history.findLast(O=>O.type==="validation-started");if($?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");m=$.validationRunId}else{m=QG();let $=await zy({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,now:n()});if($.kind==="rejected"||$.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:$.reasons.map(O=>O.message).join(" ")};for(let O of p.commands)if(!(!O.required||O.timing!=="post-patch")){if(e.signal?.aborted===!0)break;await Gr({workspaceRoot:r,repositoryRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,commandId:O.commandId,limits:WG,...e.signal===void 0?{}:{signal:e.signal}}).catch(I=>{qr(O.kind)&&f.push($a(I))})}}let h=await _m({workspaceRoot:r,gitRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,...l.baseline===void 0?{}:{baseline:l.baseline},reportMaxBytes:JG,completedAt:n()}),g=h.manifest,w={repairSessionId:l.repairSessionId,attempt:l.attempt,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash},y;if(g.status==="passed"){let $=await qy({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash,now:n(),approvedCommands:p.commands.map(O=>({commandId:O.commandId,executable:O.executable}))});if($.kind==="completed"){await Po({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let O=await e9(e,l,r);return vw(e,l,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${O?.message===void 0?"":` ${O.message}`}`,application:"applied",validation:"passed",repair:w,...O===void 0?{}:{groupCheck:O}})}y="reasons"in $?$.reasons.map(O=>O.message).join(" "):"KwikQA couldn't complete the validation."}y===void 0&&await Po({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let b=await vh(c,u,n());y!==void 0&&await Po({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let v=y!==void 0?"unavailable":g.status==="passed"?"incomplete":g.status,R=v==="failed"?"validation-failed":v==="unavailable"?"validation-unavailable":"validation-incomplete";if(b.kind!=="rolled-back")return vw(e,l,t,{outcome:"repair-failed",reasonCode:"rollback-conflicted",message:"Validation did not pass and the patch could not be rolled back automatically because the files changed; resolve them manually.",application:"recovery-required",validation:v==="blocked"?"incomplete":v,repair:w});let P=(await Sh({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,proof:{transactionId:u,phase:"rolled-back",transactionRevision:b.transaction.revision},now:t()})).retry!==void 0,E=P?ZG(r,h.directory,g):void 0;return vw(e,l,t,{outcome:"repair-failed",reasonCode:R,message:`${f.length===0?"":`KwikQA couldn't complete a command: ${f.join(" ")} `}${y===void 0?"":`${y} `}${P?"Validation did not pass, so the patch was rolled back. One retry is available.":"Validation did not pass, so the patch was rolled back. No retry remains."}`,application:"rolled-back",validation:v==="blocked"?"incomplete":v,repair:{...w,retryAvailable:P,...E===void 0?{}:{retryReportPath:E}}})}async function vw(e,t,n,r){let s={schemaVersion:"1.5",recordId:Nu(),command:"validate",...t.record,recordedAt:n(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:r.application},validation:{status:r.validation},repair:r.repair,...r.groupCheck===void 0?{}:{groupCheck:r.groupCheck},outcome:r.outcome,reasonCode:r.reasonCode,message:r.message};if(e.persist===!1)return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s};try{let a=await gd(t.workspace.workspaceRoot,s);return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,recordPath:a}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${s.message} The run record could not be written safely under .kwikqa/runs/.`,record:s}}}import{readFile as t9}from"node:fs/promises";var Ad="X-KwikQA-CI";function kw(e){let t=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[^A-Za-z0-9]+/,"");return t===void 0||t===""?void 0:t.slice(0,100)}function n9(e){let t=(e??"").split("/").map(n=>kw(n)).filter(n=>n!==void 0);return t.length===0?void 0:t.join("/").slice(0,200)}function Rw(e){try{return e===void 0||e===""?void 0:new URL(e).host.toLowerCase()}catch{return}}function rE(e){return e==="public"||e==="internal"||e==="private"?e:void 0}function rp(e,t){let n=n9(t.owner),r=kw(t.name),s=kw(t.author);if(!(t.host===void 0||n===void 0||r===void 0))return{system:e,host:t.host,owner:n,name:r,...t.visibility===void 0?{}:{visibility:t.visibility},...s===void 0?{}:{author:s}}}async function r9(e){let[t,n]=(e.GITHUB_REPOSITORY??"").split("/"),r={};try{e.GITHUB_EVENT_PATH!==void 0&&e.GITHUB_EVENT_PATH!==""&&(r=JSON.parse(await t9(e.GITHUB_EVENT_PATH,"utf8")))}catch{r={}}let s=r.repository,a=rE(s?.visibility)??(s?.private===!0?"private":s?.private===!1?"public":void 0),o=r.pull_request?.user?.login;return rp("github",{host:Rw(e.GITHUB_SERVER_URL)??"github.com",owner:t,name:n,...a===void 0?{}:{visibility:a},...typeof o=="string"?{author:o}:{}})}function i9(e){let t=e.CI_PROJECT_PATH??"",n=t.lastIndexOf("/"),r=rE(e.CI_PROJECT_VISIBILITY);return rp("gitlab",{host:e.CI_SERVER_HOST?.toLowerCase()??Rw(e.CI_SERVER_URL),owner:n>0?t.slice(0,n):e.CI_PROJECT_NAMESPACE,name:n>0?t.slice(n+1):e.CI_PROJECT_NAME,...r===void 0?{}:{visibility:r},...e.CI_MERGE_REQUEST_IID===void 0?{}:{author:e.GITLAB_USER_LOGIN}})}function s9(e){let t=e.SYSTEM_COLLECTIONURI??"",n;try{n=new URL(t).pathname.split("/").filter(Boolean)[0]}catch{n=void 0}return rp("azure",{host:Rw(t),owner:[n,e.SYSTEM_TEAMPROJECT].filter(Boolean).join("/"),name:e.BUILD_REPOSITORY_NAME,...e.BUILD_REASON==="PullRequest"?{author:e.BUILD_REQUESTEDFORID}:{}})}function a9(e){let t=e.GIT_URL??e.CHANGE_URL??"",n=/^(?:https?:\/\/([^/]+)\/|git@([^:]+):)(.+?)\/([^/]+?)(?:\.git)?(?:\/(?:pull|-\/merge_requests)\/\d+)?\/?$/.exec(t),r=(n?.[1]??n?.[2])?.toLowerCase();return rp("jenkins",{host:r,owner:n?.[3],name:n?.[4],...e.CHANGE_AUTHOR===void 0?{}:{author:e.CHANGE_AUTHOR}})}function xw(e){if(e.GITHUB_ACTIONS==="true")return"github";if(e.TF_BUILD==="True")return"azure";if(e.GITLAB_CI==="true")return"gitlab";if(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)return"jenkins"}async function iE(e){switch(xw(e)){case"github":return r9(e);case"azure":return s9(e);case"gitlab":return i9(e);case"jenkins":return a9(e);default:return}}function sE(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function aE(e){let t=l=>{let c=e[l]?.trim();return c===void 0||c===""?void 0:c},n=t("KWIKQA_SHARD"),r,s;if(e.GITHUB_ACTIONS==="true"){let l=t("GITHUB_RUN_ID");r=l===void 0?void 0:`${l}-${t("GITHUB_RUN_ATTEMPT")??"1"}`,s=[t("GITHUB_JOB"),t("RUNNER_NAME")].filter(Boolean).join(":")||void 0}else if(e.TF_BUILD==="True"){let l=t("BUILD_BUILDID");r=l===void 0?void 0:`${l}-${t("SYSTEM_JOBATTEMPT")??"1"}`,s=t("SYSTEM_JOBID")}else e.GITLAB_CI==="true"?(r=t("CI_PIPELINE_ID"),s=t("CI_JOB_ID")):(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)&&(r=t("BUILD_TAG"),s=[t("STAGE_NAME"),t("NODE_NAME"),t("EXECUTOR_NUMBER")].filter(Boolean).join(":")||void 0);s=n??s;let a=l=>l===void 0?void 0:l.replace(/[^A-Za-z0-9._:/-]/g,"-").slice(0,200),o=a(r),d=a(s);return o===void 0||d===void 0?void 0:{run:o,job:d}}var o9="X-KwikQA-CI-Identity",d9="https://kwikqa.com",l9=6e4,c9=6e4,u9=1e4;function p9(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}function f9(e,t,n,r){let s,a=0;return{token:async()=>{if(s!==void 0&&s.until>r())return s.value;if(!(a>r()))try{let o=new URL(e);if(o.protocol!=="https:")return;o.searchParams.set("audience",d9);let d=await n(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(u9)}),l=await d.json();if(!d.ok||typeof l.value!="string"||l.value==="")throw new Error("no token");let c=p9(l.value)??r()+5*6e4;return s={value:l.value,until:c-l9},l.value}catch{s=void 0,a=r()+c9;return}}}}function oE(e,t,n=Date.now){let r=e.KWIKQA_ID_TOKEN?.trim();if(r!==void 0&&r!=="")return{token:async()=>r};let s=e.ACTIONS_ID_TOKEN_REQUEST_URL,a=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(e.GITHUB_ACTIONS==="true"&&s&&a)return f9(s,a,t,n)}function dE(e,t){return t===void 0?e:(async(n,r)=>{let s=new Headers(r?.headers);if(!s.has(Ad))return e(n,r);let a=await t.token();return a!==void 0&&s.set(o9,a),e(n,{...r,headers:s})})}var m9=1200*1e3,h9=10,g9=1e3,y9=15e3,w9=3e3,b9=6e4,lE=3e4,v9=2;function Iw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function uE(e){try{let t=await e.json();return Iw(t)?t:void 0}catch{return}}async function k9(e){return await uE(e)??{}}function cE(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(y9,Math.max(g9,e)):w9}function _w(e){let t=Iw(e.error)?e.error:void 0;return typeof t?.message=="string"?t.message:void 0}var ip=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let n=performance.now(),r=()=>performance.now()-n;for(let s=0;;s+=1){let a=await this.#e(t,r);if(a!=="interrupted")return a;if(s===v9)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:r()};this.options.onRestart?.()}}async#e(t,n){let r=(p,f)=>({kind:"failed",code:p,message:f,elapsedMs:n()}),s=At(t);if(s!==void 0)return{kind:"failed",code:"invalid-request",message:s,elapsedMs:0};let a;try{a=await this.#n("POST","/v1/jobs",b9,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(p){return r("network-error",`The model request could not reach the KwikQA service (${Ni(p)}).`)}let o=await k9(a);if(a.status!==202){let p=eu(o);return{kind:"failed",code:"http-error",message:_w(o)??"The KwikQA service refused the model request.",httpStatus:a.status,...p===void 0?{}:{providerCode:p},elapsedMs:n()}}let d=o.jobId;if(typeof d!="string"||d==="")return r("invalid-json","The KwikQA service did not name the job it started.");let l=this.options.sleep??(p=>new Promise(f=>setTimeout(f,p))),c=cE(o.pollAfterMs),u=0;for(;;){if(n()>(this.options.maxWaitMs??m9))return await this.#t(d),r("timeout","The model did not answer in time; nothing was charged.");await l(c);let p;try{p=await this.#n("GET",`/v1/jobs/${d}`,lE)}catch{p=new Response(null,{status:599})}let f=p.status>=500?void 0:await uE(p);if(p.status===404)return"interrupted";if(p.status<500&&!p.ok)return{kind:"failed",code:"http-error",message:_w(f??{})??"The KwikQA service refused to report the job.",httpStatus:p.status,elapsedMs:n()};if(f===void 0){if(u+=1,u>h9)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}if(u=0,f.status==="running"){this.options.onProgress?.(n()),c=cE(f.pollAfterMs);continue}if(f.status==="failed")return Iw(f.error)&&f.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:_w(f)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:n()};if(f.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#t(d);let m=typeof f.httpStatus=="number"?f.httpStatus:502,h=f.result,g=m>=200&&m<300;if(!g||ld(h)){let w=eu(h),y=g?w??502:m;return{kind:"failed",code:"http-error",message:Kg(y,h),httpStatus:y,...w===void 0?{}:{providerCode:w},elapsedMs:n()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:m,body:h,elapsedMs:n()}}}async#t(t){try{await this.#n("DELETE",`/v1/jobs/${t}`,lE)}catch{}}#n(t,n,r,s={}){return this.options.fetch(`${this.options.baseUrl}${n}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...s.headers},...s.body===void 0?{}:{body:s.body},redirect:"error",signal:AbortSignal.timeout(r)})}};var qi="0.8.1";var R9="https://api.kwikqa.com",Nn="https://kwikqa.com/dashboard/";function pE(e){return e.hosted??!(e.plan==="byo"||e.plan==="byo-team"||e.plan==="byo-enterprise")}function x9(e){return e?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var yt=class extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r}status;code};function cr(e,t){return(e.KWIKQA_API_URL??(t===void 0||t===""?R9:t)).replace(/\/+$/,"")}function fE(e){let t=e?.messages;if(!Array.isArray(t))return;let n=t.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(n!==void 0)try{let r=JSON.parse(n.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var _9=`kwikqa/${qi}`;function I9(e){return((t,n)=>{let r=new Headers(n?.headers);return r.set("User-Agent",_9),e(t,{...n,headers:r})})}var Ht=class{constructor(t,n,r=fetch,s,a){this.baseUrl=t;this.token=n;this.ciContext=s;this.fetchImpl=I9(dE(r,a))}baseUrl;token;ciContext;fetchImpl;async#e(t,n,r,s,a){let o=()=>this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:{Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...s===void 0?{}:{"X-KwikQA-Retry-Ticket":s},...a===void 0?{}:{"X-KwikQA-Session":a},...this.ciContext===void 0?{}:{[Ad]:this.ciContext}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),d;try{d=await o().catch(c=>{if(t==="GET")return o();throw c})}catch(c){throw new yt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${Ni(c)}).`)}let l;try{l=await d.json()}catch{l=void 0}if(!d.ok){let c=l?.error;throw new yt(d.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${d.status}.`)}return l}startDeviceLogin(){return this.#e("POST","/v1/auth/device")}pollDeviceLogin(t){return this.#e("POST","/v1/auth/token",{deviceCode:t})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(t,n){return this.#e("POST","/v1/billing/checkout",{plan:t,...n})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(t,n,r){return this.#e("POST","/v1/usage/reserve",t,n,r)}openSession(t,n="diagnosis"){return this.#e("POST","/v1/usage/session",n==="diagnosis"?{requests:t}:{requests:t,kind:n})}async claimGroups(t,n,r){let s=await this.#e("POST","/v1/ci/groups",{run:t,job:n,groups:r});return new Map((s.groups??[]).flatMap(a=>typeof a.group=="string"&&(a.diagnosedBy==="this-job"||a.diagnosedBy==="another-job")?[[a.group,a.diagnosedBy]]:[]))}async closeSession(t){let r=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,t))?.retryTicket;return typeof r=="string"&&r!==""?{retryTicket:r}:{}}reportInsights(t){return this.#e("POST","/v1/insights",{events:t})}reportResults(t){return this.#e("POST","/v1/results",{events:t})}releaseUsage(t,n){return this.#e("POST","/v1/usage/release",{id:t,status:n})}logout(){return this.#e("POST","/v1/auth/logout")}transport(t){let n=a=>{let o=fE(a),d=x9(a)?t.session?.():t.repairSession?.();return{...t.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":t.retryTicket},...d===void 0?{}:{"X-KwikQA-Session":d},...o===void 0?{}:{"X-KwikQA-Framework":o},...this.ciContext===void 0?{}:{[Ad]:this.ciContext}}},r=a=>{let o=a?.kwikqa?.retryTicket;typeof o=="string"&&o!==""&&t.onRetryTicket?.(o)},s=new Ci({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:n,onCompletionBody:r});return t.jobs!==!0||this.token===void 0?s:new ip({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:s,headers:n,onCompletionBody:r,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},sp=class{constructor(t,n,r={}){this.inner=t;this.client=n;this.options=r}inner;client;options;get routing(){return this.inner.routing??"router"}preflight(t){return this.inner.preflight(t)}async complete(t){let r=t.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",s;try{let o=fE(t.body);s=await this.client.reserveUsage({kind:r,model:t.route.modelId,provider:t.route.providerSlug,...o===void 0?{}:{framework:o}},this.options.retryTicket,r==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(o){if(!(o instanceof yt))throw o;return{kind:"failed",code:"http-error",message:o.message,elapsedMs:0,...o.status===0?{}:{httpStatus:o.status}}}s.retryTicket!==void 0&&this.options.onRetryTicket?.(s.retryTicket);let a=await this.inner.complete(t);return a.kind!=="response"&&await this.client.releaseUsage(s.id,a.httpStatus??599).catch(()=>{}),a}};var T9={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},S9={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function mE(e){let t=(e.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function wt(e){return`${T9[mE(e)]} kwikqa`}function Tw(e,t){return`${S9[mE(e)]} ${t}`}var U={ok:0,failed:1,usage:2,account:3};function Pd(e){return`Not signed in. Run \`${wt(e.env)} login\` first.`}function Lr(e,t){for(let n of t.messages)e.io.error(n);return t.exit}function hE(e){return e==="repair-failed"||e==="validation-unavailable"||e==="operation-failed"?U.failed:U.ok}async function zt(e,t){try{return await t()}catch(n){if(n instanceof yt)return e.io.error(n.message),[401,402,403,409].includes(n.status)?U.account:U.failed;throw n}}function ap(e){return e.sleep??(t=>new Promise(n=>setTimeout(n,t)))}function gE(e,t){let n=(e.env.CI??"").trim().toLowerCase();return t&&e.io.interactive&&(n===""||n==="false"||n==="0")}import{spawn as A9}from"node:child_process";function yE(e,t=process.platform){let n;try{n=new URL(e)}catch{return Promise.resolve(!1)}if(n.protocol!=="https:"&&n.protocol!=="http:")return Promise.resolve(!1);let[r,s]=t==="darwin"?["open",[n.href]]:t==="win32"?["explorer.exe",[n.href]]:["xdg-open",[n.href]];return new Promise(a=>{try{let o=A9(r,s,{stdio:"ignore",detached:!0});o.once("error",()=>a(!1)),o.once("spawn",()=>{o.unref(),a(!0)})}catch{a(!1)}})}import{mkdir as P9,readFile as E9,rm as C9,writeFile as N9}from"node:fs/promises";import{homedir as wE}from"node:os";import{join as Ed}from"node:path";function bE(e){return e.KWIKQA_CONFIG_DIR!==void 0&&e.KWIKQA_CONFIG_DIR!==""?e.KWIKQA_CONFIG_DIR:process.platform==="win32"?Ed(e.APPDATA??Ed(wE(),"AppData","Roaming"),"kwikqa"):Ed(e.XDG_CONFIG_HOME??Ed(wE(),".config"),"kwikqa")}function Sw(e){return Ed(bE(e),"credentials.json")}async function On(e){if(e.KWIKQA_TOKEN!==void 0&&e.KWIKQA_TOKEN.trim()!=="")return{token:e.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await E9(Sw(e),"utf8"));return typeof t.token!="string"||t.token===""||typeof t.login!="string"||typeof t.apiUrl!="string"?void 0:{token:t.token,login:t.login,apiUrl:t.apiUrl}}catch{return}}async function vE(e,t){await P9(bE(e),{recursive:!0,mode:448}),await N9(Sw(e),`${JSON.stringify(t)}
259
259
  `,{mode:384})}async function kE(e){await C9(Sw(e),{force:!0})}import{createHash as O9}from"node:crypto";var RE=20,M9=4,$9=/^[a-z][a-z0-9-]{0,59}$/,L9=new Set(Hs);function Aw(e){return["off","0","false","no"].includes((e.KWIKQA_RESULTS??"").trim().toLowerCase())}function Gi(e){return e!==void 0&&$9.test(e)?e:void 0}function Pw(e){if(!(Gi(e.outcome)===void 0||Gi(e.reason)===void 0))return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function D9(e){return O9("sha256").update(`kwikqa-result-run:${e.runId}`).digest("hex").slice(0,32)}function Ew(e){let t=e.diagnosis,n=e.repairProposal?.acceptedHypothesisId,r=t?.hypotheses.find(o=>o.hypothesisId===n)??[...t?.hypotheses??[]].sort((o,d)=>o.rank-d.rank)[0],s=e.clusters?.[0],a=s?.symptomCategory??s?.signals.find(o=>o.kind==="symptom-category")?.value;return{symptom:Gi(a),owner:Gi(r?.probableOwner),cause:r!==void 0&&L9.has(r.causalCategory)?r.causalCategory:void 0,evidence:Gi(r?.evidenceGrade),target:Gi(e.repairProposal?.targets[0]?.class)}}function Cw(e,t){return{run:D9(e),outcome:e.outcome,reason:e.reasonCode,framework:Gi(e.framework??e.inputs?.framework),ci:xw(t)}}function xE(e){let t=[...new Set(e??[])].filter(n=>/^[0-9a-f]{64}$/.test(n));return t.length===0?void 0:t.slice(0,M9)}function op(e,t,n){if(e!==void 0)return Pw({stage:"analysis",...Cw(e,t),...Ew(e),target:void 0,sessions:xE(n),groups:e.clusters?.length??e.symptoms?.clusters,failed:e.failingLogicalTestIds.length,flaky:e.outcomes?.filter(r=>r.status==="flaky").length})}function Dr(e,t,n,r){if(t!==void 0)return Pw({stage:e,...Cw(t,n),...Ew(t),sessions:e==="fix"?xE(r):void 0,attempt:t.repair?.attempt,changedFiles:t.repairProposal?.changedFiles,changedLines:t.repairProposal?.changedLines})}function Nw(e,t,n){return Pw({stage:"pull-request",...Cw(e,n),...Ew(e),outcome:t?"opened":"not-opened",reason:t?"pull-request-opened":"pull-request-not-opened",changedFiles:e.repairProposal?.changedFiles,changedLines:e.repairProposal?.changedLines})}function F9(e,t){return e?.results?.share===!0&&!Aw(t)}async function Cd(e,t,n,r){let s=r.filter(a=>a!==void 0);if(!(s.length===0||!F9(t,n)))for(let a=0;a<s.length;a+=RE)try{await e.reportResults(s.slice(a,a+RE))}catch{return}}async function Ow(e,t={browser:!0}){return zt(e,async()=>{let n=new Ht(cr(e.env),void 0,e.fetch),r=await n.startDeviceLogin();if(e.io.print(`Open ${r.verificationUri} and enter the code: ${r.userCode}`),gE(e,t.browser)){let d=r.verificationUriComplete??r.verificationUri;await(e.openBrowser??yE)(d)&&e.io.print("Opened that page in your browser, with the code filled in. Check it matches, then approve it.")}let s=ap(e),a=Math.max(1,r.interval),o=Date.now()+r.expiresIn*1e3;for(;Date.now()<o;){await s(a*1e3);let d=await n.pollDeviceLogin(r.deviceCode);if(d.status==="complete"){await vE(e.env,{token:d.token,login:d.login,apiUrl:n.baseUrl}),e.io.print(`Signed in as ${d.login}.`);let l=await new Ht(n.baseUrl,d.token,e.fetch).status().catch(()=>{}),c=l===void 0?void 0:$w(l,e.env);return c!==void 0&&e.io.print(c),U.ok}if(d.status==="slow_down"&&(a+=5),d.status==="expired"||d.status==="denied")return e.io.error(d.status==="denied"?"Sign-in was denied.":"The code expired."),U.account}return e.io.error("The code expired before sign-in finished."),U.account})}async function Mw(e){let t=(e.env.KWIKQA_TOKEN??"").trim()!=="",n=t?void 0:await On(e.env);if(n!==void 0)try{await new Ht(cr(e.env,n.apiUrl),n.token,e.fetch).logout()}catch{e.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Nn}account/.`)}return await kE(e.env),e.io.print("Signed out."),t&&e.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),U.ok}function _E(e){let t=[...e.seats!==void 0&&e.seats>1?[`${e.seats} seats`]:[],...e.interval===void 0?[]:[e.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${e.plan} plan${t.length===0?"":` (${t.join(", ")})`}`}function IE(e){let t=e.organization;return t.kind==="personal"?[`Signed in as ${e.login} ${_E(e)}.`,...t.insights?["Insights: on. Test names and fix outcomes from your runs are shared with your insights."]:[]]:[`${e.login==="CI"?`Signed in with a CI token of ${t.name}`:`Signed in as ${e.login}, ${t.role==="admin"?"an admin":"a member"} of ${t.name},`} ${_E(e)}.`,...t.status==="pending"?[`${t.name} has no plan yet: an admin chooses one at ${Nn}billing/.`]:[],t.team===void 0?`Team: none; usage below is ${t.name}'s shared pool.`:`Team: ${t.team.name}; usage below is ${t.name}'s shared pool, and counts toward ${t.team.name}.`,t.insights?`Insights: on. Test names and fix outcomes from your runs are shared with ${t.name}.`:"Insights: off."]}function $w(e,t){let n=e.results;if(n!==void 0)return n.off==="organization"?`Result counts: off for everyone in ${e.organization.name}, by its admins.`:n.off==="you"?`Result counts: off. Turn them on at ${Nn}account/.`:Aw(t)?"Result counts: off for this run (KWIKQA_RESULTS).":`Result counts: on. Each result is reported as codes and counts, never test names or code. Turn them off at ${Nn}account/, or for a run with KWIKQA_RESULTS=off.`}async function Lw(e){return zt(e,async()=>{let t=await On(e.env);if(t===void 0)return e.io.print(Pd(e)),U.account;let r=await new Ht(cr(e.env,t.apiUrl),t.token,e.fetch).status(),s=(o,d)=>d===void 0?`${o} (unlimited)`:`${o} of ${d}`;for(let o of IE(r))e.io.print(o);e.io.print(`Analyses this period: ${s(r.usage.analyses.used,r.usage.analyses.limit)}`),e.io.print(`Fixes this period: ${s(r.usage.repairs.used,r.usage.repairs.limit)}`),e.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`);let a=$w(r,e.env);return a!==void 0&&e.io.print(a),e.io.print(`Manage your account, team, and tokens: ${Nn}`),U.ok})}async function TE(e){let t=await On(e.env);if(t===void 0){e.io.error(Pd(e));return}return new Ht(cr(e.env,t.apiUrl),t.token,e.fetch)}function j9(e){let t=e.perSeat?"/seat":"",n=e.monthlyUsd===0?"$0":`$${e.monthlyUsd}${t}/mo or $${e.annualUsd}${t}/yr`,r=e.analyses===void 0?"unlimited analyses and fixes":`${e.analyses} analyses and ${e.repairs} fixes a month${e.perSeat?" per seat, shared":""}`,s=[...e.hosted?[]:["your OpenRouter key"],...e.perSeat?[`${e.minSeats}+ seats`]:[]];return{price:n,limits:s.length===0?r:`${r} (${s.join(", ")})`}}async function Dw(e,t,n={annual:!1}){return zt(e,async()=>{let r=await On(e.env),s=await new Ht(cr(e.env,r?.apiUrl),void 0,e.fetch).plans(),a=s.paidPlansOpen!==!1,d=s.plans.filter(g=>g.id!=="free").find(g=>g.id===t);if(d===void 0||!a){t!==void 0&&d===void 0&&e.io.error(`Unknown plan: ${t}`),e.io.print(`Plans (monthly, or yearly with ${12-s.annualMonthsCharged} months free):`);let g=Math.max(...s.plans.map(w=>w.id.length));for(let w of s.plans){let{price:y,limits:b}=j9(w);e.io.print(` ${w.id.padEnd(g)} ${y}: ${b}`)}if(a)e.io.print(`Run \`${wt(e.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else{let w=s.plans.find(y=>y.id==="free")?.name??"the free plan";if(e.io.print(`Paid plans are coming soon. Until they open, every account uses ${w}.`),d!==void 0)return U.account}return t===void 0?U.ok:U.usage}let l;if(n.seats!==void 0&&(l=Number(n.seats),!(d.perSeat?Number.isInteger(l)&&l>=d.minSeats&&l<=s.maxSeats:l===1)))return e.io.error(d.perSeat?`${d.name} needs ${d.minSeats} to ${s.maxSeats} seats.`:`${d.name} is for one person; --seats applies to team plans.`),U.usage;let c=await TE(e);if(c===void 0)return U.account;let u=await c.status();if(u.organization.kind==="company"&&u.organization.role!=="admin")return e.io.print(`${u.organization.name}'s admins manage its plan and billing.`),U.ok;if(u.plan!=="free")return e.io.print(`You're on the ${u.plan} plan. Change plans, seats, or billing period in Billing, where you see the charge before you confirm:`),e.io.print(`${Nn}billing/`),U.ok;let p=n.annual?"year":"month",f=await c.checkout(d.id,{interval:p,...l===void 0?{}:{seats:l}}),m=d.perSeat?l??d.minSeats:1,h=(n.annual?d.annualUsd:d.monthlyUsd)*m;return e.io.print(`Open this link to subscribe to ${d.name}${d.perSeat?` with ${m} seats`:""} for $${h} a ${n.annual?"year":"month"}:`),e.io.print(f.url),U.ok})}async function Fw(e){return zt(e,async()=>{let t=await TE(e);if(t===void 0)return U.account;try{let{url:n}=await t.billingPortal();return e.io.print("Open this link to update your payment method or download invoices:"),e.io.print(n),e.io.print(`To change or cancel your plan: ${Nn}billing/`),U.ok}catch(n){if(n instanceof yt&&n.code==="no-billing-account")return e.io.print("You don't have a paid subscription yet."),e.io.print(`Run \`${wt(e.env)} upgrade <plan>\` to choose one.`),U.ok;if(n instanceof yt&&n.code==="team-member")return e.io.print(n.message),U.ok;throw n}})}import{appendFile as OK,readFile as MK,realpath as $K,writeFile as LK}from"node:fs/promises";import{join as b0}from"node:path";import{createHash as Jw}from"node:crypto";import{access as _K,mkdir as IK,readdir as TK,readFile as Yw,stat as c0,writeFile as SK}from"node:fs/promises";import{isAbsolute as u0,join as Mn,relative as p0,resolve as f0}from"node:path";import{mkdir as dK,writeFile as lK}from"node:fs/promises";import{join as KE}from"node:path";import{readFile as U9,realpath as H9}from"node:fs/promises";import{createRequire as z9}from"node:module";import{delimiter as q9,dirname as NE,isAbsolute as G9,join as Ki}from"node:path";import{spawn as EE}from"node:child_process";var SE=256*1024,B9=8e3;function dp(e,t={}){let n={...e,...t};for(let r of Hp(e))delete n[r];return n}function AE(e){return e.pid===void 0||e.exitCode!==null||e.signalCode!==null}function PE(e,t){if(e.pid!==void 0)try{process.kill(-e.pid,t)}catch{e.kill(t)}}async function V9(e,t){if(!AE(e)){if(process.platform==="win32"){await new Promise(n=>{let r=EE("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>n()),r.on("error",()=>n())});return}PE(e,"SIGINT"),await Promise.race([t,new Promise(n=>setTimeout(n,B9))]),AE(e)||PE(e,"SIGKILL")}}function jw(e,t,n){let r=EE(e,[...t],{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),s="",a=d=>{s+=d.toString("utf8"),s.length>SE&&(s=s.slice(-SE))};r.stdout?.on("data",a),r.stderr?.on("data",a);let o=new Promise(d=>{r.on("exit",l=>d(l??void 0)),r.on("error",()=>d(void 0))});return{child:r,output:()=>s,exited:o,stop:async()=>{await V9(r,o),await Promise.race([o,new Promise(d=>setTimeout(d,2e3))])}}}async function lp(e,t,n){let r=jw(e,t,n),s=!1,a=setTimeout(()=>{s=!0,r.stop()},n.timeoutMs),o=await r.exited;return clearTimeout(a),{...o===void 0?{}:{exitCode:o},timedOut:s,output:r.output()}}async function CE(e,t,n){let r=Date.now()+n,s=!1;for(e.exited.then(()=>{s=!0});Date.now()<r;){let a=t.exec(e.output());if(a!==null)return a;if(s)return t.exec(e.output())??void 0;await new Promise(o=>setTimeout(o,100))}}var ME="1.0",Bw=[1,59],K9=5,W9=6e4,J9=3e4,Y9=12e4,Q9=new Set(["generic","text","list","group","none","presentation"]),X9=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function Vw(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return t>Bw[0]||t===Bw[0]&&n>=Bw[1]}async function OE(e){try{let t=JSON.parse(await U9(Ki(e,"package.json"),"utf8"));return t.name==="@playwright/cli"&&typeof t.version=="string"?t.version:void 0}catch{return}}async function $E(e,t){try{let r=z9(Ki(e,"package.json")).resolve("@playwright/cli/package.json"),s=NE(r),a=await OE(s);if(a!==void 0)return{entryPath:Ki(s,"playwright-cli.js"),version:a,source:"project"}}catch{}let n=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(t.PATH??"").split(q9).filter(Boolean))for(let s of n){let a=Ki(r,s);try{let o=process.platform==="win32"?Ki(r,"node_modules","@playwright","cli"):NE(await H9(a)),d=await OE(o);if(d!==void 0)return{entryPath:Ki(o,"playwright-cli.js"),version:d,source:"path"}}catch{}}}function Uw(e){return e.split(/\r?\n/).filter(t=>!/[║╔╚═]/.test(t)).join(`
260
260
  `)}function LE(e){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(Uw(e))?.[1]?.split(/\r?\n/)}function DE(e){let t=Uw(e).split(/\r?\n/),n=t.findIndex(r=>r.trim()==="### Result");if(!(n<0))return t.slice(n+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function Z9(e){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(e??"")?.[1]?.toLowerCase()}function FE(e){return e.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function jE(e,t,n=K9){let r=Fs(t??""),s=Z9(t);return e.map((o,d)=>{let l=/\[ref=(e\d+)\]/.exec(o)?.[1],c=FE(o),u=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(l===void 0||Q9.has(u))return;let p=c.toLowerCase(),f=r.filter(m=>p.includes(m)).length*3+(s!==void 0&&u===s?2:0);if(!(X9.has(u)&&f===0))return{ref:l,element:c,score:f,order:d}}).filter(o=>o!==void 0).sort((o,d)=>d.score-o.score||o.order-d.order).slice(0,n).map(({ref:o,element:d})=>({ref:o,element:d}))}async function BE(e){let{target:t}=e,n=[],r={logicalTestId:t.logicalTestId,title:t.title,file:t.file,line:t.line,...t.failingLine===void 0?{}:{failingLine:t.failingLine},...t.locator===void 0?{}:{locator:t.locator}};if(t.failingLine===void 0)return{...r,candidates:[],issues:["The report does not say which line failed."]};let s=dp(e.env,{PLAYWRIGHT_HTML_OPEN:"never"}),a=jw(e.playwright.executable,[...e.playwright.nodeArguments,"test",`${t.file}:${t.line}`,...t.project===void 0?[]:[`--project=${t.project}`],...e.configPath===void 0?[]:[`--config=${e.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:e.workspaceRoot,env:s}),o=(c,u=J9)=>lp(process.execPath,[e.cli.entryPath,...c],{cwd:e.scratchDirectory,env:s,timeoutMs:u}),d,l=[];try{if(d=(await CE(a,/playwright-cli attach ([\w-]+)/,W9))?.[1],d===void 0)return n.push("The test did not stop in the debugger."),{...r,candidates:l,issues:n};if((await o(["attach",d])).exitCode!==0)return n.push("Playwright CLI could not attach to the paused test."),{...r,candidates:l,issues:n};let p=G9(t.file)?t.file:Ki(e.workspaceRoot,t.file),f=await o([`-s=${d}`,"pause-at",`${p}:${t.failingLine}`],Y9);if(f.exitCode!==0||!/### Paused/.test(f.output))return n.push(`The test did not reach line ${t.failingLine}.`),{...r,candidates:l,issues:n};let m=LE((await o([`-s=${d}`,"snapshot"])).output);if(m===void 0)return n.push("Playwright CLI returned no page snapshot."),{...r,candidates:l,issues:n};for(let h of jE(m,t.locator)){let g=DE((await o([`-s=${d}`,"generate-locator",h.ref])).output);g!==void 0&&l.push({element:h.element,locator:g})}return l.length===0&&n.push("No locator could be generated for any candidate."),{...r,candidates:l,issues:n}}catch(c){return n.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...r,candidates:l,issues:n}}finally{d!==void 0&&await o([`-s=${d}`,"detach"],1e4).catch(()=>{}),await a.stop()}}import{mkdir as UE,rm as VE}from"node:fs/promises";import{dirname as eK,join as ua,relative as tK,resolve as nK}from"node:path";var HE=".kwikqa/capture",rK=10*6e4,iK={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function Hw(e){let t=tK(e.workspaceRoot,e.tool.entryPath).replaceAll("\\","/"),n=e.workspaceRoot,r=e.args.map(s=>{let a=s===n?".":s.split(`${n}/`).join("").split(`${n}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(a)?JSON.stringify(a):a});return`node ${t} ${r.join(" ")}`}async function zE(e){let t=e.targets[0];if(t===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let n=Jt(e.run);if(n===void 0)return{kind:"unavailable",message:zn(e.run)};if(!Nt(n))return{kind:"unavailable",message:"KwikQA captures pages only for Playwright, Cypress, and WebdriverIO runs. Java and Python runs can't be captured yet, so analyze them without --capture."};let r=iK[n],s=await bo({workspaceRoot:e.workspaceRoot,...e.repositoryRoot===void 0?{}:{repositoryRoot:e.repositoryRoot},ownerPath:ua(e.workspaceRoot,t.file),packageName:r});if(s.kind!=="resolved")return{kind:"unavailable",message:s.reasons[0]?.message??`The project's ${r} could not be resolved; nothing was installed.`};let a=`${HE}/${e.captureId}`,o={framework:n,tool:s.tool,workspaceRoot:e.workspaceRoot,directory:a,targets:e.targets};if(n==="playwright"){let m=[...new Set(e.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(e.targets.map(y=>y.project).filter(y=>y!==void 0))],g=ua(e.workspaceRoot,a,"report.json"),w=["test",...m,...h.map(y=>`--project=${y}`),...e.run.configFile===void 0?[]:[`--config=${e.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${a}/results`];return{kind:"ready",plan:{...o,args:w,workingDirectory:e.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:g,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:g,...e.run.configFile===void 0?{}:{configPath:e.run.configFile}}}}let d=[...new Set(e.targets.map(m=>m.file))],l=e.run.configFile??await Au(e.workspaceRoot,n,t.file),c=ua(e.workspaceRoot,a,"reports"),u=await vu(e.workspaceRoot);await UE(ua(e.workspaceRoot,a),{recursive:!0});let p=l===void 0?e.workspaceRoot:eK(nK(e.workspaceRoot,l));if(n==="cypress"){let m=await ku({workspaceRoot:e.workspaceRoot,runtime:u,...l===void 0?{}:{configFile:l},specs:d,screenshotsDirectory:`${a}/screenshots`,noRetries:!0,capture:{directory:a,supportFile:await Pu(e.workspaceRoot,l)}});return{kind:"ready",plan:{...o,args:m.args,workingDirectory:p,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,...l===void 0?{}:{configPath:l}}}}if(l===void 0)return{kind:"unavailable",message:`No wdio.conf was found for ${t.file}; nothing was run.`};let f=await Ru({workspaceRoot:e.workspaceRoot,runtime:u,configFile:l,specs:d,directory:a,noRetries:!0,reportDirectory:`${a}/reports`,capture:!0});return{kind:"ready",plan:{...o,args:f.args,workingDirectory:p,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:l}}}async function qE(e,t){let n=ua(e.workspaceRoot,e.directory);if(e.framework==="playwright")await VE(n,{recursive:!0,force:!0}),await UE(n,{recursive:!0});else for(let p of["reports","pages","screenshots"])await VE(ua(n,p),{recursive:!0,force:!0});let r=await lp(e.tool.executable,[...e.tool.nodeArguments,...e.args],{cwd:e.workingDirectory,env:dp(t.env,e.environment),timeoutMs:t.timeoutMs??rK}),s=await _t(e.reportPath,{workspaceRoot:e.workspaceRoot}),a=Su[e.framework];if(s.kind!=="parsed"){let p=r.output.trim().split(`
261
261
  `).slice(-5).join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kwikqa",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "Evidence-backed diagnoses and safe, validated repairs for failing Playwright, Cypress, and WebdriverIO tests",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -37,7 +37,7 @@
37
37
  ],
38
38
  "packageManager": "pnpm@11.22.0",
39
39
  "engines": {
40
- "node": "^22.23.5 || ^24.22.3 || >=26.13.1"
40
+ "node": "^22.0.0 || ^24.0.0 || >=26.0.0"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "node scripts/build.mjs",