kwikqa 0.3.0-rc.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/kwikqa.mjs +1 -1
- package/package.json +1 -1
package/dist/kwikqa.mjs
CHANGED
|
@@ -229,7 +229,7 @@ GitHub gives a fork's workflows a read-only token, so KwikQA can't open a fix pu
|
|
|
229
229
|
Draft pull request ${g}, into ${ge(d.branch)}, with a repair validated on this runner.
|
|
230
230
|
`).catch(()=>{})}}}}}function sv(t,n){let{projectId:e,repositoryId:r,buildId:i,jobAttempt:s,commit:a}=n;if(e===void 0||r===void 0||i===void 0||s===void 0||a===void 0)return"`kwikqa fix` in CI needs System.TeamProjectId, Build.Repository.ID, Build.BuildId, System.JobAttempt, and Build.SourceVersion as Azure Pipelines sets them.";let o={system:"Azure Pipelines",ci:{system:"azure-pipelines",repository:`${e}/${r}`,runId:i,runAttempt:s,commit:a.sha.toLowerCase()},checkout:{variable:"BUILD_SOURCESDIRECTORY",path:t.env.BUILD_SOURCESDIRECTORY||void 0}};if(n.provider!=="TfsGit")return{...o,host:Le(`the repository is on ${n.provider||"another host"}, and from Azure Pipelines KwikQA opens fix pull requests only on Azure Repos`)};let d=n.pullRequest;if(d?.fork===!0)return{...o,host:Le("the pull request comes from a fork, whose build gets no secrets by default, so no fix pull request is opened. A maintainer can check out its branch and run `npx kwikqa fix`",!1)};let c=d!==void 0?n.pullRequestHead===void 0?void 0:{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.ref?.startsWith("refs/heads/")===!0?{branch:n.ref.slice(11),commit:a.sha.toLowerCase()}:void 0;if(c===void 0)return{...o,host:d===void 0?Le("this build isn't on a branch, so there's no branch for a fix pull request",!1):Le("the build doesn't name the pull request's source branch and commit (System.PullRequest.SourceBranch, System.PullRequest.SourceCommitId)")};if(n.token===void 0)return{...o,host:Le("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env")};if(n.collectionUrl===void 0)return{...o,host:Le("System.CollectionUri isn't what Azure Pipelines sets")};let l={collectionUrl:n.collectionUrl,projectId:e,repositoryId:r,token:n.token},u=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...o,host:{fixInReview:async p=>{let f=jr(p);return ef(t,await Nu(t.fetch,l,f),f,h=>Ou(t.io,t.fetch,l,{number:h,fingerprint:f},{...u,commit:a.sha}))},publish:async(p,f)=>{let h=nf(p);if(h.length===0)return t.io.print("No fix pull request: the fix's record names no repaired file.");let m=ps(p.fix),g=await $u(t.io,t.fetch,{...l,base:c,workspaceRoot:f.root,gitRoot:f.gitRoot,targets:h,fingerprint:m,title:Bn(p.fix),description:hs({fix:p.fix,...p.validation===void 0?{}:{validation:p.validation},...p.plan===void 0?{}:{plan:p.plan},fingerprint:m,...u,commit:a.sha,host:"azure-repos"}),commitMessage:fs(p.fix,m)});tf(t,g,c.branch)}}}}function av(t,n){let{repository:e,jobId:r,commit:i}=n;if(e===void 0||r===void 0||i===void 0)return"`kwikqa fix` in CI needs CI_PROJECT_PATH, CI_JOB_ID, and CI_COMMIT_SHA as GitLab CI/CD sets them.";let s={system:"GitLab CI/CD",ci:{system:"gitlab-ci",repository:e,runId:r,runAttempt:1,commit:i.sha},checkout:{variable:"CI_PROJECT_DIR",path:t.env.CI_PROJECT_DIR||void 0}},a="A maintainer can check out its branch and run `npx kwikqa fix` on their machine";if(n.pullRequest?.fork===!0)return{...s,host:Le(`the merge request comes from a fork, whose pipeline gets none of this project's variables, so no fix merge request is opened. ${a}`,!1)};if(n.sourceInOtherProject===!0)return{...s,host:Le(`the merge request's branch is in another project, such as a fork, which this project's token can't push to. ${a}`,!1)};let o=n.pullRequestHead!==void 0?{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.commitBranch!==void 0?{branch:n.commitBranch,commit:i.sha}:void 0;if(o===void 0)return{...s,host:t.env.CI_MERGE_REQUEST_IID===void 0||t.env.CI_MERGE_REQUEST_IID===""?Le("this pipeline isn't on a branch, so there's no branch for a fix merge request",!1):Le("the pipeline doesn't name the merge request's source commit (CI_MERGE_REQUEST_SOURCE_BRANCH_SHA)")};if(n.token===void 0)return{...s,host:Le("GITLAB_TOKEN isn't set; add a token with the `api` scope and at least the Developer role as a masked CI/CD variable")};if(n.apiUrl===void 0||n.projectId===void 0)return{...s,host:Le("CI_API_V4_URL or the project isn't what GitLab sets")};let d={apiUrl:n.apiUrl,project:n.projectId,token:n.token},c=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...s,host:{fixInReview:async l=>{let u=jr(l);return ef(t,await Fu(t.fetch,d,u),u,p=>Bu(t.io,t.fetch,d,{number:p,fingerprint:u},{...c,commit:i.sha}),nv)},publish:async(l,u)=>{let p=nf(l);if(p.length===0)return t.io.print("No fix merge request: the fix's record names no repaired file.");let f=ps(l.fix),h=await Hu(t.io,t.fetch,{...d,base:o,workspaceRoot:u.root,gitRoot:u.gitRoot,targets:p,fingerprint:f,title:Bn(l.fix),description:hs({fix:l.fix,...l.validation===void 0?{}:{validation:l.validation},...l.plan===void 0?{}:{plan:l.plan},fingerprint:f,...c,commit:i.sha,host:"gitlab"}),commitMessage:fs(l.fix,f)});tf(t,h,o.branch,nv)}}}}import{createHash as lD}from"node:crypto";import{basename as uD}from"node:path";var pD=100;function ov(t){return lD("sha256").update(t).digest("hex")}function dv(t,n){let e=t.projects.find(s=>s.projectId===n.projectId)?.name??"",r=n.location.file,i=n.titlePath.filter(s=>s!==""&&s!==r&&s!==uD(r));return{key:ov([e,r,...n.titlePath].join("\0")).slice(0,32),title:(i.length===0?[n.title]:i).join(" \u203A ").slice(0,300),file:r.slice(0,300),project:e.slice(0,100)}}function cv(t){return t===void 0?void 0:ov(t).slice(0,32)}function rf(t){if(t.run===void 0)return;let n=t.run,e=n.logicalTests.filter(r=>r.status==="unexpected"||r.status==="flaky").slice(0,pD).map(r=>({...dv(n,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:t.outcome,reasonCode:t.reasonCode,framework:n.framework,tests:e}}function bd(t){let n=t.record,e=t.run===void 0||t.packet===void 0||n?.diagnosis===void 0?void 0:fd(t.run,n.diagnosis,t.packet,n.clusters?.[0]?.representativeId),r=cv(n?.repair?.repairSessionId);return{kind:"fix",outcome:t.outcome,reasonCode:t.reasonCode,...t.run===void 0?{}:{framework:t.run.framework},...r===void 0?{}:{session:r},...n?.repair?.attempt===void 0?{}:{attempt:n.repair.attempt},...e===void 0||t.run===void 0?{}:{test:dv(t.run,e)},...n?.repairProposal===void 0?{}:{changedFiles:n.repairProposal.changedFiles,changedLines:n.repairProposal.changedLines}}}function lv(t){let n=t.record?.repair,e=cv(n?.repairSessionId);if(!(e===void 0||n===void 0))return{kind:"validation",outcome:t.outcome,reasonCode:t.reasonCode,session:e,attempt:n.attempt}}async function tr(t,n,e,r){if(r===void 0||e.team?.insights!==!0)return;try{await n.reportInsights([r])}catch{t.print("Team insights: couldn't share this result; nothing else changed.");return}let i=r.kind==="analysis"?`${r.tests.length} failing or flaky test name${r.tests.length===1?"":"s"} and the result`:r.kind==="fix"?"this fix's test and outcome":"the validation result";t.print(`Team insights: shared ${i} with ${e.team.owner}'s team.`)}var fD={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},hD={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function uv(t){let n=(t.npm_config_user_agent??"").split("/")[0];return n==="pnpm"||n==="yarn"||n==="bun"?n:"npm"}function Pt(t){return`${fD[uv(t)]} kwikqa`}function sf(t,n){return`${hD[uv(t)]} ${n}`}import{basename as mD}from"node:path";function un(t,n){return`${t} ${n}${t===1?"":"s"}`}function pv(t){return`$${t.toFixed(t<.1?4:2)}`}function yD(t){let n=t.evidence.flatMap(i=>i.locator.type==="diff-hunk"?[i.locator]:[]);if(n.length===0)return[];let e=new Set(n.flatMap(i=>i.commit===void 0?[]:[i.commit])),r=[...e.size===0?[]:[un(e.size,"commit")],...n.some(i=>i.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${un(n.length,"changed hunk")} from ${r} that mention the failures (--no-changes leaves them out)`]}function Ds(t,n,e){let r=n.model.reasoningEffort===void 0?"":`, effort ${n.model.reasoningEffort}`,i=n.model.zeroDataRetention===!0?", zero data retention":"";return[`${t==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${n.model.modelId} via ${n.model.providerId}${r}${i}`,` Evidence: ${un(n.evidence.length,"redacted item")} from ${n.channels.join(", ")||"the report"}`,` ${un(n.redactionIds.length,"redaction")} applied, ${un(n.omissionIds.length,"item")} withheld by policy`,...yD(n),` Estimate: at most ${n.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${n.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${pv(n.estimate.estimatedDollars)}`,` Caps: ${pv(n.caps.request.maxDollars)} per request`,` Payload: ${n.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function af(t,n,e={}){let r=t.proposal,i=["Proposed repair",` Intent: ${r.intent.statement}`,` Preserves: ${r.intent.preservedBehavior}`,` Changes: ${un(r.changedFiles,"file")}, ${un(r.changedLines,"line")}`,"",...r.diff.trimEnd().split(`
|
|
231
231
|
`),"",e.validatedNow===!0?"Validation commands (run next, on this runner):":"Validation commands (run later by `kwikqa validate`):"],s=new Map;for(let a of n.commands.filter(o=>o.timing==="post-patch")){let o=a.args.map(c=>/\s/.test(c)?JSON.stringify(c):c),d=` ${mD(a.executable)} ${o.join(" ")}`;s.set(d,(s.get(d)??0)+1)}for(let[a,o]of s)i.push(o===1?a:`${a} (${o} runs)`);return t.checkoutPristine||i.push("","Note: this checkout has other uncommitted changes; they are not touched."),i}function fv(t,n){let e=r=>n?.logicalTests.find(i=>i.logicalTestId===r)?.title;return t.flatMap((r,i)=>{let s=r.logicalTestIds.map(d=>e(d)??d),a=s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`,o=`${s.length} test${s.length===1?"":"s"}`;return[`Failure group ${i+1} of ${t.length}: ${o} (${a})${r.escalated===!0?", answered by the stronger model":""}`,...r.diagnosis!==void 0&&r.diagnosis.hypotheses.length>0?of(r.diagnosis):[` ${r.outcome} (${r.reasonCode}): ${r.message}`],""]})}function of(t){if(t.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${t.recommendedNextAction}`];let n=[];for(let e of[...t.hypotheses].sort((r,i)=>r.rank-i.rank))n.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return n.push(` Next: ${t.recommendedNextAction}`),n}function hv(t,n,e,r,i={}){if(i.ciFix!=="running")switch(n){case"diagnosed":return r!==void 0&&Ze(r)===void 0?lt(r):t?.diagnosis?.repairEligibility!=="eligible"?void 0:i.ci===!0&&i.ciFix==="policy"?`The committed ci.fix policy lets \`${e} fix\` repair it in this job and open a draft pull request.`:i.ci===!0?`To repair it, run \`${e} analyze\` and then \`${e} fix\` on your machine.`:`Run \`${e} fix\` to propose a repair.`;case"proposal-ready":return`Run \`${e} fix\` without --propose-only to review and apply it.`;case"awaiting-validation":return`Run \`${e} validate\` to verify the patch.`;case"repair-failed":return t?.repair?.retryAvailable===!0?`Run \`${e} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}function mv(t){if(t===void 0)return;let n=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`,e=t.artifact.format===void 0?void 0:Zt[t.artifact.format],r=t.logicalTests.filter(a=>a.status==="unexpected").length,i=t.logicalTests.filter(a=>a.status==="flaky").length;return`Read a ${t.framework==="unknown"?"run from an unidentified framework":`${Rt[t.framework]}${n} run`}${e===void 0?"":` (${e})`}: ${un(t.logicalTests.length,"test")}, ${r} failing${i===0?"":`, ${i} flaky`}.`}function yv(t,n){if(t===void 0||Ze(t)===void 0)return;let e=t.framework==="playwright",r=e?"trace":"kwikqa-capture",i=0,s=0;for(let c of t.logicalTests)for(let l of Nr(c))i+=1,l.attachments.some(u=>u.name===r)&&(s+=1);if(i===0||s===i)return;let a=i-s;return[`Note: ${a===i?i===1?`The failing attempt has no ${e?"Playwright trace":"KwikQA failure capture"}`:`None of the ${i} failing attempts has ${e?"a Playwright trace":"a KwikQA failure capture"}`:`${a} of ${i} failing attempts have no ${e?"Playwright trace":"KwikQA failure capture"}`}, so browser actions, network, console, and DOM were not available to the diagnosis.`,e?` Run \`${n} analyze --capture\` to re-run them with full tracing, or set`:` Run \`${n} analyze --capture\` to re-run the failing specs and record each failure's page.`,...e?[' `use: { trace: "retain-on-failure" }` in playwright.config to keep traces of failures.']:[]].join(`
|
|
232
|
-
`)}var Ls="0.3.0
|
|
232
|
+
`)}var Ls="0.3.0";var U={ok:0,failed:1,usage:2,account:3},Ms=(()=>{let{workspaceRoot:t,...n}=Bl;return{...n,maxPacketBytes:6e5}})(),vD=.85;function Td(t){if(t===void 0)return Ms;let n=Math.min(t.diagnosis.caps.request.maxInputTokens,t.repairCaps.request.maxInputTokens);return{...Ms,maxPacketBytes:Math.min(Ms.maxPacketBytes,Math.floor(n*vD))}}var bv=["test-results/kwikqa-report.json","test-results/kwikqa","playwright-report/results.json","test-results/results.json","mochawesome-report","cypress/reports","cypress/results","results.json","report.json"],kv=He(".kwikqa","cli-state.json");function uf(t){return`Not signed in. Run \`${Pt(t.env)} login\` first.`}async function ti(t){return gD(t).then(()=>!0,()=>!1)}async function pf(t){try{return JSON.parse(await kd(He(t,kv),"utf8"))}catch{return{}}}async function ff(t,n){await bD(He(t,".kwikqa"),{recursive:!0,mode:448}),await vv(He(t,kv),`${JSON.stringify(n)}
|
|
233
233
|
`,{mode:384})}async function js(t,n,e){if(e!==void 0)return Rd(e)?e:Id(t.cwd,e);for(let r of[t.env.PLAYWRIGHT_JSON_OUTPUT_NAME,t.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let i=Rd(r)?r:Id(n,r);if(await ti(i))return i}for(let r of bv)if(await ti(He(n,r)))return He(n,r);return He(n,bv[0]??"report.json")}async function Rv(t){try{if((await wv(t)).isDirectory()){let n=gv("sha256");for(let e of(await xD(t)).sort()){let r=He(t,e);(await wv(r)).isFile()&&n.update(`${e}\0`).update(await kd(r))}return n.digest("hex")}return gv("sha256").update(await kd(t)).digest("hex")}catch{return}}async function kD(t,n,e){let r=n.capture;if(r===void 0)return;let i=He(t,r.reportPath);if(await Rv(e)!==r.sourceSha256||!await ti(i))return;let s=r.probePath===void 0?void 0:He(t,r.probePath);return{reportPath:i,...s!==void 0&&await ti(s)?{probePath:s}:{}}}async function RD(t,n,e,r){let i=await ct(e,{workspaceRoot:n,...r.framework===void 0?{}:{framework:r.framework}});if(i.kind!=="parsed"){t.io.error(`Capture skipped: ${i.diagnostic.message}`);return}let s=i.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await sp({run:i.run,workspaceRoot:n,repositoryRoot:await Os(n),captureId:s,env:t.env,probe:r.probe});if(a.kind!=="ready"){t.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)t.io.print(c);if(a.prepared.probeUnavailable!==void 0&&t.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)t.io.print("Run these tests? yes (--yes)");else if(!await t.io.confirm("Run these tests?")){t.io.print("Capture declined; analyzing the existing report.");return}let o=await ap(a.prepared,t.env);if(t.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);t.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${o.probe.results.length} failing test${o.probe.results.length===1?"":"s"}.`)}if(o.outcome.reportPath===void 0||o.outcome.reproduced===0)return;let d=await Rv(e);if(d!==void 0){let c=await pf(n);await ff(n,{...c,capture:{sourceSha256:d,reportPath:ei(n,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:ei(n,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function xv(t,n){if(t===void 0||t==="")return{...n,evaluationStatus:"unverified-model"};let[e,r]=t.split("@");if(e===void 0||r===void 0||r==="")throw new yt(0,"invalid-model",`Model routes look like author/model@provider, not ${t}.`);return{modelId:e,providerId:r,evaluationStatus:"unverified-model"}}async function _s(t,n,e){let r=await ln(t.env);if(r===void 0)return{exit:U.account,messages:[uf(t)]};let i=new Tt(cn(t.env,r.apiUrl),r.token,t.fetch),s=await i.status(),a=await i.hostedConfig(),o=Jx(s);if(!o&&(t.env.OPENROUTER_API_KEY??"").trim()==="")return{exit:U.account,messages:["The BYOK plans need OPENROUTER_API_KEY in the environment."]};let d=n==="analysis"?s.usage.analyses:s.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let v=n==="analysis"?"analyses":"fixes";return{exit:U.account,messages:[`You have used all ${d.limit} ${v} on the ${s.plan} plan until ${s.periodEnd.slice(0,10)}.`,s.team?.role==="member"?`Ask ${s.team.owner}, who manages your team's plan, to add seats.`:`Run \`${Pt(t.env)} upgrade\` to see plans with more.`]}}let c,l,u=a.sessions===!0&&e===void 0?{open:async v=>{l=(await i.openSession(v)).sessionTicket},close:async()=>{let v=l;l=void 0,v!==void 0&&await i.closeSession(v)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async v=>{p=(await i.openSession(v,"repair")).sessionTicket},close:async()=>{let v=p;if(p=void 0,v===void 0)return;let R=await i.closeSession(v);R.retryTicket!==void 0&&(c=R.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:v=>{c=v},session:()=>l,repairSession:()=>p};if(!o){let v=new wd(new Wn({readApiKey:()=>t.env.OPENROUTER_API_KEY,fetch:t.fetch}),i,h);return{diagnosis:{model:xv(t.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:v,...u===void 0?{}:{session:u}},repairModel:xv(t.env.KWIKQA_REPAIR_MODEL,a.models.repair),repairCaps:a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"OpenRouter, with your own API key (KwikQA counts the request)",ticket:()=>c,client:i,status:s}}let m=i.transport({...h,jobs:a.jobs===!0,onProgress:TD(t),onRestart:()=>t.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...t.sleep===void 0?{}:{sleep:t.sleep}}),g=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=g?a.models.escalation:void 0,w=g?a.caps.escalation:void 0,x=!g&&u!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0?{model:a.models.escalation,caps:a.caps.escalation}:void 0;return{diagnosis:{model:y??a.models.diagnosis,caps:w??a.caps.diagnosis,transport:m,...u===void 0?{}:{session:u},...x===void 0?{}:{escalation:x}},repairModel:y??a.models.repair,repairCaps:w??a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>c,client:i,status:s}}function Ad(t,n){for(let e of n.messages)t.io.error(e);return n.exit}var ID=3e4;function AD(t){let n=Math.floor(t/1e3),e=Math.floor(n/60);return e===0?`${n}s`:`${e}m ${String(n%60).padStart(2,"0")}s`}function TD(t){let n=0;return e=>{let r=Math.floor(e/ID);r<=n||(n=r,t.io.print(` The model is still working (${AD(e)})\u2026`))}}function Pd(t,n,e){let r=async(i,s)=>{for(let a of i)t.io.print(a);return e!==!1?(t.io.print(`${s} yes (${e===!0?"--yes":e})`),!0):t.io.confirm(s)};return{approveDiagnosis:i=>r(Ds("diagnosis",i,n),"Send this request?"),approveDiagnoses:i=>{let[s]=i;return i.length===1&&s!==void 0?r(Ds("diagnosis",s,n),"Send this request?"):r([`${i.length} diagnosis requests, one for each group of failures with a shared cause:`,...i.flatMap((a,o)=>["",`Request ${o+1} of ${i.length}`,...Ds("diagnosis",a,n)])],`Send these ${i.length} requests?`)},approveRepairRequest:i=>r(Ds("repair proposal",i,n),"Send this request?"),approveApplication:async(i,s)=>{for(let a of af(i,s))t.io.print(a);return t.io.confirm("Apply this patch?")}}}async function Sd(t,n,e,r,i){let s=new Set(r),a=await sp({run:{...e,logicalTests:e.logicalTests.filter(d=>s.has(d.logicalTestId))},workspaceRoot:n,repositoryRoot:await Os(n),captureId:`${i.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:t.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};t.io.print(""),t.io.print(i.intro);for(let d of a.prepared.description)t.io.print(d);if(i.approvedBy!==void 0)t.io.print(`${i.question} yes (${i.approvedBy})`);else if(!await t.io.confirm(i.question))return{kind:"declined"};let o=await ap(a.prepared,t.env);return t.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function PD(t){return t==="repair-failed"||t==="validation-unavailable"||t==="operation-failed"?U.failed:U.ok}function pn(t,n,e={}){t.io.print("");let r=mv("run"in n?n.run:void 0);r!==void 0&&n.record?.command!=="validate"&&t.io.print(r);let i=n.record?.clusters??[];if(i.length>1&&n.record?.command!=="validate")for(let d of fv(i,"run"in n?n.run:void 0))t.io.print(d);else if(n.record?.diagnosis!==void 0&&n.record.command!=="validate"){for(let d of of(n.record.diagnosis))t.io.print(d);t.io.print("")}t.io.print(`Result: ${n.outcome} (${n.reasonCode})`),t.io.print(n.message);let s=Pt(t.env),a=yv("run"in n?n.run:void 0,s);a!==void 0&&t.io.print(a);let o=hv(n.record,n.outcome,s,"run"in n?n.run:void 0,e);return o!==void 0&&t.io.print(o),n.recordPath!==void 0&&t.io.print(`Record: ${n.recordPath}`),PD(n.outcome)}async function fn(t,n){try{return await n()}catch(e){if(e instanceof yt)return t.io.error(e.message),[401,402,403,409].includes(e.status)?U.account:U.failed;throw e}}function Iv(t){return t.sleep??(n=>new Promise(e=>setTimeout(e,n)))}async function Av(t){return fn(t,async()=>{let n=new Tt(cn(t.env),void 0,t.fetch),e=await n.startDeviceLogin();t.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let r=Iv(t),i=Math.max(1,e.interval),s=Date.now()+e.expiresIn*1e3;for(;Date.now()<s;){await r(i*1e3);let a=await n.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await Zx(t.env,{token:a.token,login:a.login,apiUrl:n.baseUrl}),t.io.print(`Signed in as ${a.login}.`),U.ok;if(a.status==="slow_down"&&(i+=5),a.status==="expired"||a.status==="denied")return t.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),U.account}return t.io.error("The code expired before sign-in finished."),U.account})}async function Tv(t){let n=(t.env.KWIKQA_TOKEN??"").trim()!=="",e=n?void 0:await ln(t.env);if(e!==void 0)try{await new Tt(cn(t.env,e.apiUrl),e.token,t.fetch).logout()}catch{t.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Zr}account/.`)}return await ev(t.env),t.io.print("Signed out."),n&&t.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),U.ok}function SD(t){let n=[...t.seats!==void 0&&t.seats>1?[`${t.seats} seats`]:[],...t.interval===void 0?[]:[t.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${t.plan} plan${n.length===0?"":` (${n.join(", ")})`}`}async function Pv(t){return fn(t,async()=>{let n=await ln(t.env);if(n===void 0)return t.io.print(uf(t)),U.account;let r=await new Tt(cn(t.env,n.apiUrl),n.token,t.fetch).status(),i=(s,a)=>a===void 0?`${s} (unlimited)`:`${s} of ${a}`;return t.io.print(`Signed in as ${r.login} ${SD(r)}.`),r.team!==void 0&&(t.io.print(r.team.role==="member"?`Team: ${r.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${r.team.members} member${r.team.members===1?"":"s"}; usage below is the shared pool.`),t.io.print(r.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),t.io.print(`Analyses this period: ${i(r.usage.analyses.used,r.usage.analyses.limit)}`),t.io.print(`Fixes this period: ${i(r.usage.repairs.used,r.usage.repairs.limit)}`),t.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`),t.io.print(`Manage your account, team, and tokens: ${Zr}`),U.ok})}async function Sv(t){let n=await ln(t.env);if(n===void 0){t.io.error(uf(t));return}return new Tt(cn(t.env,n.apiUrl),n.token,t.fetch)}function ED(t){let n=t.perSeat?"/seat":"",e=t.monthlyUsd===0?"$0":`$${t.monthlyUsd}${n}/mo or $${t.annualUsd}${n}/yr`,r=t.analyses===void 0?"unlimited analyses and fixes":`${t.analyses} analyses and ${t.repairs} fixes a month${t.perSeat?" per seat, shared":""}`,i=[...t.hosted?[]:["your OpenRouter key"],...t.perSeat?[`${t.minSeats}+ seats`]:[]];return{price:e,limits:i.length===0?r:`${r} (${i.join(", ")})`}}async function Ev(t,n,e={annual:!1}){return fn(t,async()=>{let r=await ln(t.env),i=await new Tt(cn(t.env,r?.apiUrl),void 0,t.fetch).plans(),s=i.paidPlansOpen!==!1,o=i.plans.filter(m=>m.id!=="free").find(m=>m.id===n);if(o===void 0||!s){n!==void 0&&o===void 0&&t.io.error(`Unknown plan: ${n}`),t.io.print(`Plans (monthly, or yearly with ${12-i.annualMonthsCharged} months free):`);let m=Math.max(...i.plans.map(g=>g.id.length));for(let g of i.plans){let{price:y,limits:w}=ED(g);t.io.print(` ${g.id.padEnd(m)} ${y}: ${w}`)}if(s)t.io.print(`Run \`${Pt(t.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else if(t.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return U.account;return n===void 0?U.ok:U.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=i.maxSeats:d===1)))return t.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${i.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),U.usage;let c=await Sv(t);if(c===void 0)return U.account;let l=await c.status();if(l.team?.role==="member")return t.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),U.ok;if(l.plan!=="free")return t.io.print(`You're on the ${l.plan} plan. Change plans, seats, or billing period in Billing, where you see the charge before you confirm:`),t.io.print(`${Zr}billing/`),U.ok;let u=e.annual?"year":"month",p=await c.checkout(o.id,{interval:u,...d===void 0?{}:{seats:d}}),f=o.perSeat?d??o.minSeats:1,h=(e.annual?o.annualUsd:o.monthlyUsd)*f;return t.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),t.io.print(p.url),U.ok})}async function Cv(t){return fn(t,async()=>{let n=await Sv(t);if(n===void 0)return U.account;try{let{url:e}=await n.billingPortal();return t.io.print("Open this link to update your payment method or download invoices:"),t.io.print(e),t.io.print(`To change or cancel your plan: ${Zr}billing/`),U.ok}catch(e){if(e instanceof yt&&e.code==="no-billing-account")return t.io.print("You don't have a paid subscription yet."),t.io.print(`Run \`${Pt(t.env)} upgrade <plan>\` to choose one.`),U.ok;if(e instanceof yt&&e.code==="team-member")return t.io.print(e.message),U.ok;throw e}})}async function Nv(t){let n=await Ut(t.cwd),e=He(n,"kwikqa.config.json");if(await ti(e))t.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let p=Op({repositoryPaths:await Wp(n)});t.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let f of p.canonicalContents.trimEnd().split(`
|
|
234
234
|
`))t.io.print(` ${f}`);for(let f of[...p.reasons,...p.ambiguities])t.io.print(` - ${f}`);await t.io.confirm("Write kwikqa.config.json?")&&(await vv(e,p.canonicalContents,{flag:"wx"}),t.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let r=He(n,".gitignore"),i=await ti(r)?await kd(r,"utf8"):"",s=p=>p.trim().replace(/^\//,"").replace(/\/$/,""),a=new Set(i.split(/\r?\n/).map(s)),o=[{entry:".kwikqa/",what:"local run records"},{entry:Ya,what:"the failure report"}].filter(p=>!a.has(s(p.entry))),d=o.map(p=>`${p.entry} (${p.what})`).join(" and ");o.length>0&&await t.io.confirm(`Add ${d} to .gitignore?`)&&await wD(r,`
|
|
235
235
|
${o.map(p=>p.entry).join(`
|
package/package.json
CHANGED