import{spawn as T}from"child_process";import{existsSync as p,mkdirSync as O,readdirSync as $,statSync as j,readFileSync as R}from"fs";import{resolve as v,join as l,basename as C}from"path";var x=".zibby/repos";function w(u,n,r={}){return new Promise((o,i)=>{let e=T(u,{cwd:n,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...r}}),c="",f="";e.stdout.on("data",s=>{c+=s.toString()}),e.stderr.on("data",s=>{f+=s.toString()}),e.on("close",s=>{s!==0?i(new Error(`Exit ${s}: ${f.trim()||c.trim()}`)):o(c.trim())}),e.on("error",s=>i(s))})}var A={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
You can clone and explore git repositories locally for codebase analysis:
- git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
- git_list_repos: List locally cloned repos
- git_explore: Quick overview of a cloned repo's structure (key files, package.json, routes, etc.)

When a test ticket lacks context, use this workflow:
1. Clone the relevant repo with git_checkout
2. Use git_explore to understand the project structure
3. Use shell commands (grep, cat) to read specific files for deeper understanding
4. Use GitHub/GitLab skills to read related PRs and commits
5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(u,n,r){let o=r?.options?.workspace||process.cwd();try{switch(u){case"git_checkout":return await N(n,o);case"git_list_repos":return L(n,o);case"git_explore":return D(n,o);default:return JSON.stringify({error:`Unknown tool: ${u}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function N(u,n){let{url:r,branch:o,shallow:i=!0,name:e}=u;!r.includes("://")&&!r.startsWith("git@")&&(r=`https://github.com/${r}`);let c=e||C(r.replace(/\.git$/,"")),f=v(n,x);O(f,{recursive:!0});let s=l(f,c),h=r,g=process.env.GITHUB_TOKEN,m=process.env.GITLAB_TOKEN,k=process.env.GITLAB_URL;if(r.includes("github.com")&&g)h=r.replace("https://github.com",`https://x-access-token:${g}@github.com`);else if(m&&k)try{let d=new URL(k).host;r.includes(d)&&(h=r.replace(`https://${d}`,`https://oauth2:${m}@${d}`))}catch{}if(p(l(s,".git"))){let d=o?`git -C "${s}" fetch origin ${o} && git -C "${s}" checkout ${o} && git -C "${s}" pull origin ${o}`:`git -C "${s}" pull`;await w(d,n);let b=await w(`git -C "${s}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"updated",repo:c,path:s,branch:o||"default",head:b})}let t=["git","clone"];i&&t.push("--depth","1"),o&&t.push("--branch",o),t.push(`"${h}"`,`"${s}"`),await w(t.join(" "),n);let _=await w(`git -C "${s}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"cloned",repo:c,path:s,branch:o||"default",shallow:i,head:_})}function L(u,n){let r=v(n,x);if(!p(r))return JSON.stringify({repos:[],message:"No repos cloned yet"});let o=[];for(let i of $(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let e=l(r,i.name);if(!p(l(e,".git")))continue;let c=j(e);o.push({name:i.name,path:e,lastModified:c.mtime.toISOString()})}return JSON.stringify({repos:o,total:o.length,directory:r})}function D(u,n){let{repo:r,depth:o=2}=u,i=v(n,x,r);if(!p(i))return JSON.stringify({error:`Repo not found: ${r}. Run git_checkout first.`});let e={repo:r,path:i},c=l(i,"package.json");if(p(c))try{let t=JSON.parse(R(c,"utf-8"));e.packageJson={name:t.name,version:t.version,scripts:t.scripts?Object.keys(t.scripts):[],dependencies:t.dependencies?Object.keys(t.dependencies).slice(0,30):[],devDependencies:t.devDependencies?Object.keys(t.devDependencies).slice(0,20):[]},t.dependencies?.react?e.framework="React":t.dependencies?.next?e.framework="Next.js":t.dependencies?.vue?e.framework="Vue":t.dependencies?.angular?e.framework="Angular":t.dependencies?.express?e.framework="Express":t.dependencies?.fastify&&(e.framework="Fastify")}catch{}let f=l(i,"pyproject.toml");p(f)&&(e.language="Python");let s=l(i,"go.mod");p(s)&&(e.language="Go");let h=l(i,"Cargo.toml");p(h)&&(e.language="Rust"),p(c)&&(e.language=e.language||"JavaScript/TypeScript");let g=[];function m(t,_,d){if(d>o)return;let b;try{b=$(t,{withFileTypes:!0})}catch{return}let S=b.filter(a=>!a.name.startsWith(".")&&a.name!=="node_modules"&&a.name!=="__pycache__"&&a.name!=="dist"&&a.name!=="build"&&a.name!==".git").sort((a,y)=>a.isDirectory()!==y.isDirectory()?a.isDirectory()?-1:1:a.name.localeCompare(y.name));for(let a of S){let y=a.isDirectory();g.push(`${_}${y?"\u{1F4C1}":"\u{1F4C4}"} ${a.name}`),y&&d<o&&m(l(t,a.name),`${_}  `,d+1)}}m(i,"",1),e.tree=g.slice(0,80),g.length>80&&(e.treeTruncated=!0);let k=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return e.keyFilesFound=k.filter(t=>p(l(i,t))),JSON.stringify(e)}export{A as gitSkill};
