@sma1lboy/rove 0.9.288-next.226 → 0.9.288-next.228
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/cli/{chunk-4k9kqa8t.js → chunk-14frenn5.js} +1 -1
- package/dist/cli/{chunk-38z8sgf3.js → chunk-5djyy7ar.js} +3 -2
- package/dist/cli/{chunk-cbjx2jbb.js → chunk-h80pb6sb.js} +1 -1
- package/dist/cli/{chunk-f25d5s4d.js → chunk-j48vrc9y.js} +1 -1
- package/dist/cli/{chunk-y3v3pbq7.js → chunk-jpxgdytq.js} +1 -1
- package/dist/cli/{chunk-25t74pv8.js → chunk-mg4wkarb.js} +1 -1
- package/dist/cli/{chunk-xdybj537.js → chunk-rzm12tp3.js} +1 -1
- package/dist/cli/{chunk-p1t77dtp.js → chunk-tjgf18y5.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/web/assets/{index-uZ24ArU6.js → index-CNAZqGQV.js} +32 -32
- package/dist/web/assets/{term-mount-BrPPnYX4.js → term-mount-CLr5HNlM.js} +1 -1
- package/dist/web/index.html +1 -1
- package/dist/web/relay/index.html +2 -2
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{GitWorktreeManager}from"./chunk-
|
|
2
|
+
import{GitWorktreeManager}from"./chunk-5djyy7ar.js";import"./chunk-mfmythv2.js";import"./chunk-5dkx02g8.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-xmwp6je4.js";import"./chunk-6xppe9bj.js";import"./chunk-catrr0z3.js";import"./chunk-y849hsgp.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-mg1cas61.js";import"./chunk-p84bhs57.js";import"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-w8da1czv.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{GitWorktreeManager};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-mfmythv2.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{smallIgnoredPaths}from"./chunk-xmwp6je4.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-y849hsgp.js";import{getRemoteRepoConfig}from"./chunk-bgmpczgm.js";import{loadStateFile}from"./chunk-p84bhs57.js";import path4 from"path";function parseDirtyPaths(stdout){return parsePorcelainRows(stdout).filter((row)=>(row.x+row.y).trim().length>0).map((row)=>row.path).filter((p)=>p.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var METER_RE=/(\d{1,3})% \(\d+\/\d+\)/g;function checkoutProgressReader(onPercent){let tail="",last=-1;return(chunk)=>{let text=tail+chunk,end=Math.max(text.lastIndexOf("\r"),text.lastIndexOf(`
|
|
2
|
+
import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-mfmythv2.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{smallIgnoredPaths}from"./chunk-xmwp6je4.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{REPO_CONFIG_DIRS,readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-y849hsgp.js";import{getRemoteRepoConfig}from"./chunk-bgmpczgm.js";import{loadStateFile}from"./chunk-p84bhs57.js";import path4 from"path";function parseDirtyPaths(stdout){return parsePorcelainRows(stdout).filter((row)=>(row.x+row.y).trim().length>0).map((row)=>row.path).filter((p)=>p.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var METER_RE=/(\d{1,3})% \(\d+\/\d+\)/g;function checkoutProgressReader(onPercent){let tail="",last=-1;return(chunk)=>{let text=tail+chunk,end=Math.max(text.lastIndexOf("\r"),text.lastIndexOf(`
|
|
3
3
|
`));if(end<0){tail=text;return}tail=text.slice(end+1);let percent=-1;for(let match of text.slice(0,end).matchAll(METER_RE))percent=Number(match[1]);if(percent<0||percent>100||percent===last)return;last=percent,onPercent(percent)}}class CheckpointError extends Error{code;constructor(code,reason){super(`${code}: ${reason}`);this.code=code;this.name="CheckpointError"}}function checkpointRef(taskId,n){return`refs/rove/checkpoints/${taskId}/${n}`}var FALLBACK_IDENTITY={GIT_AUTHOR_NAME:"Rove",GIT_AUTHOR_EMAIL:"rove@localhost",GIT_COMMITTER_NAME:"Rove",GIT_COMMITTER_EMAIL:"rove@localhost"};function parseSubject(subject){let parts=subject.trim().split(/\s+/).slice(3),at=parts.pop()??"";return parts[0]?{at,tabId:parts[0]}:{at}}async function listCheckpoints(deps,exec,cwd,taskId){let prefix=`refs/rove/checkpoints/${taskId}/`,out=await deps.runGit(exec,["for-each-ref","--format=%(refname)%09%(objectname)%09%(tree)%09%(subject)",prefix],{cwd,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return[];let records=[];for(let line of out.stdout.split(`
|
|
4
4
|
`)){let[ref,commit,tree,subject=""]=line.split("\t"),n=Number(ref?.slice(prefix.length));if(!ref||!commit||!tree||!Number.isInteger(n))continue;records.push({n,ref,commit,tree,...parseSubject(subject)})}return records.sort((a,b)=>a.n-b.n)}async function gitlinkPaths(exec,deps,cwd,tree){let out=await deps.runGit(exec,["ls-tree","-r",tree],{cwd,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return[];return out.stdout.split(`
|
|
5
5
|
`).filter((line)=>line.startsWith("160000 ")).map((line)=>line.slice(line.indexOf("\t")+1)).filter((p)=>p.length>0)}async function withTempIndex(deps,exec,cwd,body){let name=`rove-ckpt-index-${process.pid}-${Math.random().toString(36).slice(2,8)}`,indexPath=(await deps.runGit(exec,["rev-parse","--git-path",name],{cwd,allowFail:!0,readOnly:!0})).stdout.trim();if(!indexPath)throw new CheckpointError("CHECKPOINT_FAILED",`${cwd} is not a git work tree`);try{return await body((args,extraEnv)=>deps.runGit(exec,args,{cwd,allowFail:!0,env:{GIT_INDEX_FILE:indexPath,...extraEnv}}),indexPath)}finally{await exec.run(["rm","-f",indexPath],{cwd}).catch(()=>{return})}}async function snapshotTree(deps,exec,cwd,head){let tree=await withTempIndex(deps,exec,cwd,async(gitIdx,indexPath)=>{let real=(await deps.runGit(exec,["rev-parse","--git-path","index"],{cwd,allowFail:!0,readOnly:!0})).stdout.trim();if(!(real!==""&&(await exec.run(["cp","-p",real,indexPath],{cwd}).catch(()=>{return}))?.exitCode===0)&&head&&(await gitIdx(["read-tree",head])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","read-tree failed");if((await gitIdx(["add","-A"])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","git add -A failed");let written=(await gitIdx(["write-tree"])).stdout.trim();if(!written)throw new CheckpointError("CHECKPOINT_FAILED","write-tree failed");return written});return{tree,uncaptured:await gitlinkPaths(exec,deps,cwd,tree)}}async function headCommit(deps,exec,cwd){let out=await deps.runGit(exec,["rev-parse","--verify","-q","HEAD"],{cwd,allowFail:!0,readOnly:!0});return out.exitCode===0?out.stdout.trim():""}async function takeCheckpoint(deps,exec,worktreePath,taskId,opts={}){let head=await headCommit(deps,exec,worktreePath),{tree,uncaptured}=await snapshotTree(deps,exec,worktreePath,head),existing=await listCheckpoints(deps,exec,worktreePath,taskId),latest=existing[existing.length-1];if(latest&&latest.tree===tree)return{created:!1,checkpoint:latest};let at=(opts.now??new Date).toISOString(),hasIdentity=(await deps.runGit(exec,["var","GIT_COMMITTER_IDENT"],{cwd:worktreePath,allowFail:!0,readOnly:!0})).exitCode===0;for(let n=(latest?.n??0)+1,attempt=0;attempt<5;n++,attempt++){let message=["rove checkpoint",n,opts.tabId,at].filter((p)=>p!==void 0&&p!=="").join(" "),commitArgs=head?["commit-tree",tree,"-p",head,"-m",message]:["commit-tree",tree,"-m",message],commit=await deps.runGit(exec,commitArgs,{cwd:worktreePath,allowFail:!0,...hasIdentity?{}:{env:FALLBACK_IDENTITY}}),sha=commit.stdout.trim();if(commit.exitCode!==0||!sha)throw new CheckpointError("CHECKPOINT_FAILED",`commit-tree failed: ${commit.stderr.trim()}`);let ref=checkpointRef(taskId,n);if((await deps.runGit(exec,["update-ref",ref,sha,""],{cwd:worktreePath,allowFail:!0})).exitCode===0)return await pruneCheckpoints(deps,exec,worktreePath,taskId).catch(()=>{return}),{created:!0,checkpoint:{n,ref,commit:sha,tree,at,...opts.tabId?{tabId:opts.tabId}:{}},uncaptured}}throw new CheckpointError("CHECKPOINT_FAILED",`could not allocate a checkpoint number for ${taskId}`)}async function deleteRefs(deps,exec,cwd,refs){for(let ref of refs)await deps.runGit(exec,["update-ref","-d",ref],{cwd,allowFail:!0})}async function pruneCheckpoints(deps,exec,cwd,taskId,keep=100){let all=await listCheckpoints(deps,exec,cwd,taskId),doomed=all.slice(0,Math.max(0,all.length-keep));return await deleteRefs(deps,exec,cwd,doomed.map((c)=>c.ref)),doomed.length}async function deleteTaskCheckpoints(deps,exec,cwd,taskId){let all=await listCheckpoints(deps,exec,cwd,taskId);return await deleteRefs(deps,exec,cwd,all.map((c)=>c.ref)),all.length}async function moveTaskCheckpoints(deps,exec,cwd,fromId,toId){let moved=0;for(let c of await listCheckpoints(deps,exec,cwd,fromId)){if((await deps.runGit(exec,["update-ref",checkpointRef(toId,c.n),c.commit,""],{cwd,allowFail:!0})).exitCode!==0)continue;await deleteRefs(deps,exec,cwd,[c.ref]),moved++}return moved}async function rewindTo(deps,exec,worktreePath,taskId,n,opts={}){let target=(await listCheckpoints(deps,exec,worktreePath,taskId)).find((c)=>c.n===n);if(!target)throw new CheckpointError("CHECKPOINT_NOT_FOUND",`task ${taskId} has no checkpoint ${n}`);let taken=await takeCheckpoint(deps,exec,worktreePath,taskId,{now:opts.now}),undo=taken.checkpoint,uncaptured=taken.created?taken.uncaptured:[];await withTempIndex(deps,exec,worktreePath,async(gitIdx)=>{if((await gitIdx(["read-tree",undo.tree])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","read-tree (current) failed");let res=await gitIdx(["read-tree","--reset","-u",target.tree]);if(res.exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED",`read-tree failed: ${res.stderr.trim()}`)});let head=await headCommit(deps,exec,worktreePath);return await deps.runGit(exec,head?["reset","-q"]:["read-tree","--empty"],{cwd:worktreePath,allowFail:!0}),{target,undo,uncaptured}}import fs from"fs/promises";import path from"path";var WORKTREE_CLONE_IGNORED_KEY="worktree.cloneIgnored",DEFAULT_CLONE_DIRS=["node_modules",".venv","target",".build"];function isCloneIgnoredEnabled(){return loadStateFile()[WORKTREE_CLONE_IGNORED_KEY]!==!1}function parseCloneDirs(text){return text.split(/\r?\n/).map((line)=>line.replace(/#.*$/,"").trim()).filter((e)=>e.length>0&&e!=="."&&e!==".."&&!/[/\\]/.test(e)&&!e.startsWith("-"))}function resolveCloneDirs(worktreePath){let file=readFirstNonEmptyRepoFile(worktreePath,"clone-dirs");return file===void 0?DEFAULT_CLONE_DIRS:parseCloneDirs(file)}var CLONEFILEAT_PERL='my $r = syscall(462, -2, $ARGV[0], -2, $ARGV[1], 0); if ($r != 0) { print STDERR "clonefileat: $!\\n"; exit 1 }';function defaultCloneDeps(exec){return{platform:process.platform,statDev:async(p)=>(await fs.stat(p)).dev,isApfs:async(p)=>{let r=await exec.run(["/bin/df","-T","apfs",p]);return r.exitCode===0&&r.stdout.trim().split(`
|
|
@@ -7,5 +7,6 @@ import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedP
|
|
|
7
7
|
`).filter((line)=>line.startsWith("160000 ")).map((line)=>line.slice(line.indexOf("\t")+1)).filter((p)=>p.length>0)}function branchRefSlug(branch){return(branch??"").replace(/[\u0000-\u0020\u007f~^:?*[\\/]+/g,"-").replace(/@\{/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"detached"}function salvageRef(branch,now){let stamp=now.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");return`refs/rove/salvage/${branchRefSlug(branch)}-${stamp}`}async function createSalvageRef(git2,preferred,commit){for(let attempt=1;attempt<=50;attempt++){let ref=attempt===1?preferred:`${preferred}-${attempt}`;if((await git2(["update-ref",ref,commit,""])).exitCode===0)return ref}return null}async function salvageWorktree(deps,exec,worktreePath,now=new Date){let git2=(args)=>deps.runGit(exec,args,{cwd:worktreePath,allowFail:!0});try{let status=await git2(["status","--porcelain"]);if(status.exitCode!==0)return null;let probe=await smallIgnoredPaths(exec,worktreePath),ignored=probe==="unknown"?[]:probe;if(status.stdout.trim().length===0&&ignored.length===0)return null;let indexPath=(await git2(["rev-parse","--git-path","rove-salvage-index"])).stdout.trim();if(!indexPath)return null;let withIndex=(args)=>deps.runGit(exec,args,{cwd:worktreePath,allowFail:!0,env:{GIT_INDEX_FILE:indexPath}}),head=(await git2(["rev-parse","HEAD"])).stdout.trim(),branch=(await git2(["rev-parse","--abbrev-ref","HEAD"])).stdout.trim();try{if(head&&(await withIndex(["read-tree",head])).exitCode!==0)return null;if((await withIndex(["add","-A"])).exitCode!==0)return null;if(ignored.length>0)await withIndex(["add","-f","--",...ignored]);let tree=(await withIndex(["write-tree"])).stdout.trim();if(!tree)return null;let message=`rove salvage: force-removed worktree ${worktreePath}`,commit=(await withIndex(head?["commit-tree",tree,"-p",head,"-m",message]:["commit-tree",tree,"-m",message])).stdout.trim();if(!commit)return null;let ref=await createSalvageRef(git2,salvageRef(branch&&branch!=="HEAD"?branch:null,now),commit);if(!ref)return null;return{ref,commit,uncaptured:await gitlinkPaths2(git2,tree)}}finally{await exec.run(["rm","-f",indexPath],{cwd:worktreePath}).catch(()=>{return})}}catch{return null}}async function anchorBranchTip(deps,exec,repo,branch,now=new Date){if(!branch||branch==="HEAD")return null;let git2=(args)=>deps.runGit(exec,args,{cwd:repo,allowFail:!0});try{let tipOut=await git2(["rev-parse","--verify",`refs/heads/${branch}`]),tip=tipOut.stdout.trim();if(tipOut.exitCode!==0||!tip)return null;let holders=await git2(["for-each-ref","--contains",tip,"--format=%(refname)"]);if(holders.exitCode===0){if(holders.stdout.split(`
|
|
8
8
|
`).map((l)=>l.trim()).filter((l)=>l.length>0&&l!==`refs/heads/${branch}`).length>0)return null}let ref=salvageRef(branch,now);if((await git2(["update-ref",ref,tip])).exitCode!==0)return null;return{ref,commit:tip,uncaptured:[]}}catch{return null}}async function branchExists(deps,ctx,branch){return(await deps.runGit(ctx.exec,["show-ref","--verify","--quiet",`refs/heads/${branch}`],{cwd:ctx.dir,allowFail:!0,readOnly:!0})).exitCode===0}async function deleteBranchIn(deps,exec,repo,branch,force){if(!branch||branch==="HEAD")return{deleted:!1,reason:"no branch to delete"};let out=await deps.runGit(exec,["branch",force?"-D":"-d",branch],{cwd:repo,allowFail:!0});if(out.exitCode===0)return{deleted:!0};if(!await branchExists(deps,{exec,dir:repo,remote:exec.isRemote},branch))return{deleted:!0};return{deleted:!1,reason:out.stderr.trim()||out.stdout.trim()||`git branch exited ${out.exitCode}`}}async function deleteBranchAnchored(deps,exec,repo,branch,opts){if(opts.force)opts.onAnchor?.(await anchorBranchTip(deps,exec,repo,branch));return await deleteBranchIn(deps,exec,repo,branch,opts.force)}async function branchHasUpstream(deps,worktreePath,branch){return(await deps.runGit(deps.execAt(worktreePath),["for-each-ref","--format=%(upstream)",`refs/heads/${branch}`],{cwd:worktreePath,readOnly:!0})).stdout.trim().length>0}async function hasLocalBranch(deps,worktreePath,branch){return(await deps.runGit(deps.execAt(worktreePath),["show-ref","--verify","--quiet",`refs/heads/${branch}`],{cwd:worktreePath,allowFail:!0,readOnly:!0})).exitCode===0}async function renameBranch(deps,worktreePath,from,to){let exec=deps.execAt(worktreePath);if(from===to)return;let repo=await deps.findRepoFor(exec,worktreePath);if(!repo)throw Error(`renameBranch(): ${worktreePath} is not a git worktree`);let out=await deps.runGit(exec,["branch","-m",from,to],{cwd:repo,allowFail:!0});if(out.exitCode===0)return;let ctx={exec,dir:repo,remote:exec.isRemote};if(!await branchExists(deps,ctx,from)&&await branchExists(deps,ctx,to))return;throw new GitCommandError(["branch","-m",from,to],repo,out)}import fs2 from"fs";import path2 from"path";async function mapWithLimit(items,limit,fn){let results=Array(items.length),next=0,worker=async()=>{for(;;){let i=next++;if(i>=items.length)return;results[i]=await fn(items[i])}},width=Math.max(1,Math.min(limit,items.length));return await Promise.all(Array.from({length:width},worker)),results}var PROBE_CONCURRENCY=6;function parseWorktreeListPorcelain(out){let records=[],current=null;for(let rawLine of out.split(`
|
|
9
9
|
`)){let line=rawLine.replace(/\r$/,"");if(line===""){if(current)records.push(current);current=null;continue}if(!current)current={};if(line.startsWith("worktree "))current.path=line.slice(9);else if(line.startsWith("HEAD "))current.head=line.slice(5);else if(line.startsWith("branch ")){let ref=line.slice(7);current.branch=ref.startsWith("refs/heads/")?ref.slice(11):ref}else if(line==="detached")current.detached=!0;else if(line==="bare")current.bare=!0}if(current)records.push(current);return records}async function lastActivityMs(deps,ctx,worktreePath){try{let stdout=await deps.runGitStdoutAt(ctx,worktreePath,["log","-1","--format=%ct"]),secs=Number.parseInt(stdout.trim(),10);if(Number.isFinite(secs)&&secs>0)return secs*1000}catch{}if(!ctx.exec.isRemote)try{return fs2.statSync(worktreePath).mtimeMs}catch{}return 0}async function listBranchNames(deps,repo){let ctx=deps.ctxFor(repo);requireAbsolute("repo",ctx.dir);let stdout;try{stdout=await deps.runGitStdout(ctx,["for-each-ref","--format=%(refname)","refs/heads","refs/remotes/origin"])}catch{return[]}let names=new Set;for(let line of stdout.split(`
|
|
10
|
-
`)){let name=line.trim().replace(/^refs\/(?:heads|remotes\/origin)\//,"");if(name&&name!=="HEAD")names.add(name)}return[...names]}async function listManaged(deps,repo){let ctx=deps.ctxFor(repo);requireAbsolute("repo",ctx.dir);let all=parseWorktreeListPorcelain(await deps.runGitStdout(ctx,["worktree","list","--porcelain"])),kept=[];for(let entry of all){if(!entry.path)continue;let callerRoot=ctx.remote?remoteManagedRootForPath(ctx.dir,entry.path):managedWorktreeRootForPath(repo,entry.path);if(!callerRoot)continue;if(!entry.branch||entry.detached)continue;let rel=path2.relative(canonicalize(callerRoot),canonicalize(entry.path));kept.push({callerPath:path2.join(callerRoot,rel),probePath:entry.path,branch:entry.branch,head:entry.head??""})}return mapWithLimit(kept,PROBE_CONCURRENCY,async(e)=>({path:e.callerPath,branch:e.branch,head:e.head,dirty:await deps.isDirty(e.probePath).catch(()=>null)}))}async function listAllAdoptable(deps,repo){let ctx=deps.ctxFor(repo),adoptable=await adoptablePaths(deps,ctx),infos=await mapWithLimit(adoptable,PROBE_CONCURRENCY,async(entry)=>{let[dirty,activityMs]=await Promise.all([deps.isDirty(entry.path).catch(()=>null),lastActivityMs(deps,ctx,entry.path)]);return{path:entry.path,branch:entry.branch,head:entry.head,dirty,roveManaged:ctx.remote?remoteManagedRootForPath(ctx.dir,entry.path)!==null:isRoveManagedPath(repo,entry.path),lastActivityMs:activityMs}});return infos.sort((a,b)=>b.lastActivityMs-a.lastActivityMs),infos}async function adoptablePaths(deps,ctx){requireAbsolute("repo",ctx.dir);let all=parseWorktreeListPorcelain(await deps.runGitStdout(ctx,["worktree","list","--porcelain"])),canon=(p)=>ctx.remote?p:canonicalize(p),canonRepo=canon(ctx.dir),canonMain=all.find((entry)=>entry.path)?.path,canonMainPath=canonMain?canon(canonMain):null,kept=[];for(let entry of all){if(!entry.path)continue;if(entry.bare)continue;if(!entry.branch||entry.detached)continue;let canonEntry=canon(entry.path);if(canonMainPath!==null&&canonEntry===canonMainPath)continue;if(canonEntry===canonRepo)continue;kept.push({path:entry.path,branch:entry.branch,head:entry.head??""})}return kept}async function unreadableWorktreeNames(deps,ctx){if(ctx.remote)return[];requireAbsolute("repo",ctx.dir);let adminRoot;try{let common=(await deps.runGitStdout(ctx,["rev-parse","--git-common-dir"])).trim();if(!common)return[];adminRoot=path2.join(path2.resolve(ctx.dir,common),"worktrees")}catch{return[]}let names;try{names=fs2.readdirSync(adminRoot,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name)}catch{return[]}if(names.length===0)return[];let listed;try{listed=await deps.runGitStdout(ctx,["worktree","list","--porcelain"])}catch{return[]}let reported=new Set(parseWorktreeListPorcelain(listed).filter((entry)=>entry.path).map((entry)=>canonicalize(entry.path))),missing=[];for(let name of names){let gitdir;try{gitdir=fs2.readFileSync(path2.join(adminRoot,name,"gitdir"),"utf8").trim()}catch{missing.push(name);continue}if(gitdir&&!reported.has(canonicalize(path2.dirname(gitdir))))missing.push(name)}return missing}import path3 from"path";async function isRegisteredWorktree(deps,exec,repo,worktreePath){let out=await deps.runGit(exec,["worktree","list","--porcelain"],{cwd:repo,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return!1;let same=(a,b)=>exec.isRemote?a===b:canonicalize(a)===canonicalize(b);return parseWorktreeListPorcelain(out.stdout).some((e)=>e.path!==void 0&&same(e.path,worktreePath))}async function deregisteredWorktreeResidue(exec,worktreePath){let pointer=(await exec.readFile(`${worktreePath}/.git`))?.trim().match(/^gitdir:\s*(.+)$/)?.[1]?.trim();if(!pointer)return!1;let marker="/worktrees/",at=pointer.lastIndexOf(marker);if(at<0)return!1;return await exec.exists(pointer.slice(0,at))}function dirtyRefusal(worktreePath,ignored,dirty=[]){return`${DIRTY_WORKTREE_CODE}: ${worktreePath} has ${describeDirtyWorktreeWork(ignored,dirty)} \u2014 forcing the removal salvages it to a ref first`}async function removeWorktree(deps,worktreePath,opts){requireAbsolute("path",worktreePath);let exec=deps.execForPath(worktreePath),force=opts?.force===!0;if(!await exec.exists(worktreePath)){let goneRepo=opts?.repo??await deps.findRepoFor(exec,path3.dirname(worktreePath));if(goneRepo){if(await deps.runGit(exec,["worktree","prune"],{cwd:goneRepo,allowFail:!0}),opts?.deleteBranch===!0&&opts.branch){let outcome=await deleteBranchAnchored(deps.branchDeps(),exec,goneRepo,opts.branch,{force});if(!outcome.deleted)opts.onBranchKept?.({branch:opts.branch,reason:outcome.reason})}}return}let repo=await deps.findRepoFor(exec,worktreePath);if(repo===null||!await isRegisteredWorktree(deps,exec,repo,worktreePath)){if(await deregisteredWorktreeResidue(exec,worktreePath)){opts?.onResidue?.({path:worktreePath,reason:"a previous removal deregistered the worktree"});return}if(repo){opts?.onResidue?.({path:worktreePath,reason:"a previous removal deregistered the worktree"});return}if(!force)throw Error(`remove(): ${worktreePath} is not a git worktree`);if(!isUnderManagedWorktreesRoot(worktreePath,opts?.repo))throw Error(`remove(): ${worktreePath} has no reachable git repo and is not under a Rove worktrees root; refusing to delete it`);if(opts?.onSalvage?.(null),await exec.run(["rm","-rf",worktreePath]),await exec.exists(worktreePath))opts?.onResidue?.({path:worktreePath,reason:"the directory could not be deleted"});return}let branch=opts?.deleteBranch?await deps.currentBranch(worktreePath).catch(()=>null)??opts.branch??null:null;if(force){let salvaged=await salvageWorktree({runGit:(e,a,o)=>deps.runGit(e,a,o)},exec,worktreePath);opts?.onSalvage?.(salvaged)}else{let dirty=await deps.dirtyPaths(worktreePath);if(dirty.length>0)throw Error(dirtyRefusal(worktreePath,[],dirty));let ignored=await deps.ignoredWork(worktreePath);if(ignored==="unknown"||ignored.length>0)throw Error(dirtyRefusal(worktreePath,ignored))}let args=force?["worktree","remove","--force",worktreePath]:["worktree","remove",worktreePath],result=await deps.runGit(exec,args,{cwd:repo,allowFail:!0});if(result.exitCode!==0){if(await isRegisteredWorktree(deps,exec,repo,worktreePath))throw new GitCommandError(args,repo,result);opts?.onResidue?.({path:worktreePath,reason:result.stderr.trim()||result.stdout.trim()||"unknown"})}if(await deps.runGit(exec,["worktree","prune"],{cwd:repo,allowFail:!0}),branch){let outcome=await deleteBranchAnchored(deps.branchDeps(),exec,repo,branch,{force});if(!outcome.deleted)opts?.onBranchKept?.({branch,reason:outcome.reason})}}class GitWorktreeManager{execDeps;cloneDeps;constructor(execDeps=defaultExecDeps,cloneDeps=defaultCloneDeps){this.execDeps=execDeps;this.cloneDeps=cloneDeps}ctxFor(repoKey){let basePath=this.execDeps.remoteBasePath(repoKey);return basePath?{exec:this.execDeps.execForRepo(repoKey),dir:basePath,remote:!0}:{exec:this.execDeps.execForRepo(repoKey),dir:repoKey,remote:!1}}async runGit(exec,args,opts){if(!opts.cwd)throw Error("runGit(): cwd is required; refusing to inherit from process.cwd()");let env=opts.readOnly?{...opts.env,...READ_ONLY_GIT_ENV}:opts.env,r=await exec.run(["git",...args],{cwd:opts.cwd,env,onStderr:opts.onStderr}),result={stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode};if(result.exitCode!==0&&!opts.allowFail)throw new GitCommandError(args,opts.cwd,result);return result}async create(repo,branch,worktreePath,baseRef,onProgress){let ctx=this.ctxFor(repo);if(requireAbsolute("repo",ctx.dir),requireAbsolute("path",worktreePath),!branch)throw Error("create(): branch must be a non-empty string");if(await ctx.exec.exists(worktreePath)){let existing=await this.tryDescribe(ctx,worktreePath);if(existing){if(existing.branch!==branch)throw Error(`worktree at ${worktreePath} is on branch '${existing.branch}', refusing to hijack to '${branch}'`);return existing}throw Error(`create(): ${worktreePath} exists but is not a registered git worktree`)}await ctx.exec.mkdirp(path4.dirname(worktreePath));let args=await branchExists(this.branchDeps(),ctx,branch)?["worktree","add",worktreePath,branch]:baseRef?["worktree","add","-b",branch,worktreePath,baseRef]:["worktree","add","-b",branch,worktreePath];await this.runGit(ctx.exec,args,{cwd:ctx.dir,...onProgress?{onStderr:checkoutProgressReader(onProgress)}:{}});let info=await this.tryDescribe(ctx,worktreePath);if(!info)throw Error(`create(): git reported success but ${worktreePath} is not a worktree`);if(info.branch!==branch)throw Error(`create(): post-condition failed \u2014 expected branch '${branch}' at ${worktreePath}, got '${info.branch}'`);return info}async createForTask(args){let basePath=this.execDeps.remoteBasePath(args.repo),target=basePath?remoteWorktreePathFor(basePath,args.slug):worktreePathFor(args.repo,args.slug),ctx=this.ctxFor(args.repo),skipClone=ctx.remote||await ctx.exec.exists(target),info=await this.create(args.repo,args.branch,target,args.baseRef,args.onProgress);if(!skipClone)await cloneIgnoredDirs(ctx.exec,args.repo,info.path,this.cloneDeps(ctx.exec));return info}async remove(worktreePath,opts){await removeWorktree({runGit:(exec,args,runOpts)=>this.runGit(exec,args,runOpts),execForPath:(p)=>this.execDeps.execForPath(p),findRepoFor:(exec,p)=>this.findRepoFor(exec,p),currentBranch:(p)=>this.currentBranch(p),dirtyPaths:(p)=>this.dirtyPaths(p),ignoredWork:(p)=>this.ignoredWork(p),branchDeps:()=>this.branchDeps()},worktreePath,opts)}async deleteBranch(repo,branch,opts){let ctx=this.ctxFor(repo);return requireAbsolute("repo",ctx.dir),await deleteBranchAnchored(this.branchDeps(),ctx.exec,ctx.dir,branch,{force:opts?.force===!0,onAnchor:opts?.onAnchor})}execAt(worktreePath){return requireAbsolute("path",worktreePath),this.execDeps.execForPath(worktreePath)}branchDeps(){return{runGit:(exec,args,opts)=>this.runGit(exec,args,opts),execAt:(worktreePath)=>this.execAt(worktreePath),findRepoFor:(exec,worktreePath)=>this.findRepoFor(exec,worktreePath)}}listDeps(){return{ctxFor:(repoKey)=>this.ctxFor(repoKey),runGitStdout:async(ctx,args)=>(await this.runGit(ctx.exec,args,{cwd:ctx.dir,readOnly:!0})).stdout,runGitStdoutAt:async(ctx,cwd,args)=>(await this.runGit(ctx.exec,args,{cwd,readOnly:!0})).stdout,isDirty:(worktreePath)=>this.isDirty(worktreePath)}}list(repo){return listManaged(this.listDeps(),repo)}listAll(repo){return listAllAdoptable(this.listDeps(),repo)}listAdoptablePaths(repo){return adoptablePaths(this.listDeps(),this.ctxFor(repo))}listUnreadableWorktrees(repo){return unreadableWorktreeNames(this.listDeps(),this.ctxFor(repo))}listBranchNames(repo){return listBranchNames(this.listDeps(),repo)}async pathExists(worktreePath){return this.execAt(worktreePath).exists(worktreePath)}async pruneWorktrees(repo){let ctx=this.ctxFor(repo);requireAbsolute("repo",ctx.dir),await this.runGit(ctx.exec,["worktree","prune"],{cwd:ctx.dir,allowFail:!0})}async isDirty(worktreePath){return(await this.dirtyPaths(worktreePath)).length>0}async dirtyPaths(worktreePath){let out=await this.runGit(this.execAt(worktreePath),["status","--porcelain"],{cwd:worktreePath,readOnly:!0});return parseDirtyPaths(out.stdout)}async ignoredWork(worktreePath){let exec=this.execAt(worktreePath);return smallIgnoredPaths(exec,worktreePath,regenerableDirNames(exec,worktreePath,this.cloneDeps(exec)))}checkpointDeps(){return{runGit:(exec,args,opts)=>this.runGit(exec,args,opts)}}takeCheckpoint(worktreePath,taskId,opts){return takeCheckpoint(this.checkpointDeps(),this.execAt(worktreePath),worktreePath,taskId,opts)}listCheckpoints(worktreePath,taskId){return listCheckpoints(this.checkpointDeps(),this.execAt(worktreePath),worktreePath,taskId)}rewindToCheckpoint(worktreePath,taskId,n){return rewindTo(this.checkpointDeps(),this.execAt(worktreePath),worktreePath,taskId,n)}async deleteTaskCheckpoints(repo,taskId){let ctx=this.ctxFor(repo);return requireAbsolute("repo",ctx.dir),deleteTaskCheckpoints(this.checkpointDeps(),ctx.exec,ctx.dir,taskId)}async moveTaskCheckpoints(repo,fromId,toId){let ctx=this.ctxFor(repo);return requireAbsolute("repo",ctx.dir),moveTaskCheckpoints(this.checkpointDeps(),ctx.exec,ctx.dir,fromId,toId)}async currentBranch(worktreePath){let name=(await this.runGit(this.execAt(worktreePath),["rev-parse","--abbrev-ref","HEAD"],{cwd:worktreePath,readOnly:!0})).stdout.trim();if(!name||name==="HEAD")throw Error(`currentBranch(): ${worktreePath} is in detached-HEAD state`);return name}branchHasUpstream(worktreePath,branch){return branchHasUpstream(this.branchDeps(),worktreePath,branch)}hasLocalBranch(worktreePath,branch){return hasLocalBranch(this.branchDeps(),worktreePath,branch)}renameBranch(worktreePath,from,to){return renameBranch(this.branchDeps(),worktreePath,from,to)}async tryDescribe(ctx,worktreePath){let out=await this.runGit(ctx.exec,["worktree","list","--porcelain"],{cwd:ctx.dir,readOnly:!0}),entries=parseWorktreeListPorcelain(out.stdout),norm=(p)=>ctx.remote?p:canonicalize(p),target=norm(worktreePath),match=entries.find((e)=>e.path&&norm(e.path)===target);if(!match||!match.path||!match.branch||match.detached)return null;return{path:worktreePath,branch:match.branch,head:match.head??"",dirty:await this.isDirty(match.path)}}async findRepoFor(exec,worktreePath){try{let out=await this.runGit(exec,["rev-parse","--git-common-dir"],{cwd:worktreePath,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return null;let gitDir=out.stdout.trim();if(!gitDir)return null;let absolute=path4.isAbsolute(gitDir)?gitDir:path4.resolve(worktreePath,gitDir);return path4.basename(absolute)===".git"?path4.dirname(absolute):absolute}catch(err){if(err instanceof GitCommandError)return null;throw err}}}
|
|
10
|
+
`)){let name=line.trim().replace(/^refs\/(?:heads|remotes\/origin)\//,"");if(name&&name!=="HEAD")names.add(name)}return[...names]}async function listManaged(deps,repo){let ctx=deps.ctxFor(repo);requireAbsolute("repo",ctx.dir);let all=parseWorktreeListPorcelain(await deps.runGitStdout(ctx,["worktree","list","--porcelain"])),kept=[];for(let entry of all){if(!entry.path)continue;let callerRoot=ctx.remote?remoteManagedRootForPath(ctx.dir,entry.path):managedWorktreeRootForPath(repo,entry.path);if(!callerRoot)continue;if(!entry.branch||entry.detached)continue;let rel=path2.relative(canonicalize(callerRoot),canonicalize(entry.path));kept.push({callerPath:path2.join(callerRoot,rel),probePath:entry.path,branch:entry.branch,head:entry.head??""})}return mapWithLimit(kept,PROBE_CONCURRENCY,async(e)=>({path:e.callerPath,branch:e.branch,head:e.head,dirty:await deps.isDirty(e.probePath).catch(()=>null)}))}async function listAllAdoptable(deps,repo){let ctx=deps.ctxFor(repo),adoptable=await adoptablePaths(deps,ctx),infos=await mapWithLimit(adoptable,PROBE_CONCURRENCY,async(entry)=>{let[dirty,activityMs]=await Promise.all([deps.isDirty(entry.path).catch(()=>null),lastActivityMs(deps,ctx,entry.path)]);return{path:entry.path,branch:entry.branch,head:entry.head,dirty,roveManaged:ctx.remote?remoteManagedRootForPath(ctx.dir,entry.path)!==null:isRoveManagedPath(repo,entry.path),lastActivityMs:activityMs}});return infos.sort((a,b)=>b.lastActivityMs-a.lastActivityMs),infos}async function adoptablePaths(deps,ctx){requireAbsolute("repo",ctx.dir);let all=parseWorktreeListPorcelain(await deps.runGitStdout(ctx,["worktree","list","--porcelain"])),canon=(p)=>ctx.remote?p:canonicalize(p),canonRepo=canon(ctx.dir),canonMain=all.find((entry)=>entry.path)?.path,canonMainPath=canonMain?canon(canonMain):null,kept=[];for(let entry of all){if(!entry.path)continue;if(entry.bare)continue;if(!entry.branch||entry.detached)continue;let canonEntry=canon(entry.path);if(canonMainPath!==null&&canonEntry===canonMainPath)continue;if(canonEntry===canonRepo)continue;kept.push({path:entry.path,branch:entry.branch,head:entry.head??""})}return kept}async function unreadableWorktreeNames(deps,ctx){if(ctx.remote)return[];requireAbsolute("repo",ctx.dir);let adminRoot;try{let common=(await deps.runGitStdout(ctx,["rev-parse","--git-common-dir"])).trim();if(!common)return[];adminRoot=path2.join(path2.resolve(ctx.dir,common),"worktrees")}catch{return[]}let names;try{names=fs2.readdirSync(adminRoot,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name)}catch{return[]}if(names.length===0)return[];let listed;try{listed=await deps.runGitStdout(ctx,["worktree","list","--porcelain"])}catch{return[]}let reported=new Set(parseWorktreeListPorcelain(listed).filter((entry)=>entry.path).map((entry)=>canonicalize(entry.path))),missing=[];for(let name of names){let gitdir;try{gitdir=fs2.readFileSync(path2.join(adminRoot,name,"gitdir"),"utf8").trim()}catch{missing.push(name);continue}if(gitdir&&!reported.has(canonicalize(path2.dirname(gitdir))))missing.push(name)}return missing}import path3 from"path";var TEARDOWN_SCRIPT="teardown.sh",TEARDOWN_TIMEOUT_MS=60000;async function runRepoTeardown(exec,worktreePath,timeoutMs=TEARDOWN_TIMEOUT_MS){let script=null;for(let dir of REPO_CONFIG_DIRS){let candidate=`${dir}/${TEARDOWN_SCRIPT}`;if(await exec.exists(`${worktreePath}/${candidate}`).catch(()=>!1)){script=candidate;break}}if(!script)return{kind:"none"};let signal=AbortSignal.timeout(timeoutMs);try{let result=await exec.run(["sh",script],{cwd:worktreePath,signal});if(signal.aborted)return{kind:"failed",reason:`timed out after ${Math.round(timeoutMs/1000)}s`};if(result.exitCode===0)return{kind:"ok"};let detail=(result.stderr.trim()||result.stdout.trim()).split(`
|
|
11
|
+
`).slice(-3).join(" | ");return{kind:"failed",reason:`exit ${result.exitCode}${detail?`: ${detail}`:""}`}}catch(err){if(signal.aborted)return{kind:"failed",reason:`timed out after ${Math.round(timeoutMs/1000)}s`};return{kind:"failed",reason:err instanceof Error?err.message:String(err)}}}async function isRegisteredWorktree(deps,exec,repo,worktreePath){let out=await deps.runGit(exec,["worktree","list","--porcelain"],{cwd:repo,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return!1;let same=(a,b)=>exec.isRemote?a===b:canonicalize(a)===canonicalize(b);return parseWorktreeListPorcelain(out.stdout).some((e)=>e.path!==void 0&&same(e.path,worktreePath))}async function deregisteredWorktreeResidue(exec,worktreePath){let pointer=(await exec.readFile(`${worktreePath}/.git`))?.trim().match(/^gitdir:\s*(.+)$/)?.[1]?.trim();if(!pointer)return!1;let marker="/worktrees/",at=pointer.lastIndexOf(marker);if(at<0)return!1;return await exec.exists(pointer.slice(0,at))}function dirtyRefusal(worktreePath,ignored,dirty=[]){return`${DIRTY_WORKTREE_CODE}: ${worktreePath} has ${describeDirtyWorktreeWork(ignored,dirty)} \u2014 forcing the removal salvages it to a ref first`}async function removeWorktree(deps,worktreePath,opts){requireAbsolute("path",worktreePath);let exec=deps.execForPath(worktreePath),force=opts?.force===!0;if(!await exec.exists(worktreePath)){let goneRepo=opts?.repo??await deps.findRepoFor(exec,path3.dirname(worktreePath));if(goneRepo){if(await deps.runGit(exec,["worktree","prune"],{cwd:goneRepo,allowFail:!0}),opts?.deleteBranch===!0&&opts.branch){let outcome=await deleteBranchAnchored(deps.branchDeps(),exec,goneRepo,opts.branch,{force});if(!outcome.deleted)opts.onBranchKept?.({branch:opts.branch,reason:outcome.reason})}}return}let repo=await deps.findRepoFor(exec,worktreePath);if(repo===null||!await isRegisteredWorktree(deps,exec,repo,worktreePath)){if(await deregisteredWorktreeResidue(exec,worktreePath)){opts?.onResidue?.({path:worktreePath,reason:"a previous removal deregistered the worktree"});return}if(repo){opts?.onResidue?.({path:worktreePath,reason:"a previous removal deregistered the worktree"});return}if(!force)throw Error(`remove(): ${worktreePath} is not a git worktree`);if(!isUnderManagedWorktreesRoot(worktreePath,opts?.repo))throw Error(`remove(): ${worktreePath} has no reachable git repo and is not under a Rove worktrees root; refusing to delete it`);opts?.onSalvage?.(null);let teardown2=await runRepoTeardown(exec,worktreePath);if(teardown2.kind==="failed")console.error(`[rove] teardown.sh in ${worktreePath} failed (${teardown2.reason})`);if(await exec.run(["rm","-rf",worktreePath]),await exec.exists(worktreePath))opts?.onResidue?.({path:worktreePath,reason:"the directory could not be deleted"});return}let branch=opts?.deleteBranch?await deps.currentBranch(worktreePath).catch(()=>null)??opts.branch??null:null;if(force){let salvaged=await salvageWorktree({runGit:(e,a,o)=>deps.runGit(e,a,o)},exec,worktreePath);opts?.onSalvage?.(salvaged)}else{let dirty=await deps.dirtyPaths(worktreePath);if(dirty.length>0)throw Error(dirtyRefusal(worktreePath,[],dirty));let ignored=await deps.ignoredWork(worktreePath);if(ignored==="unknown"||ignored.length>0)throw Error(dirtyRefusal(worktreePath,ignored))}let teardown=await runRepoTeardown(exec,worktreePath);if(teardown.kind==="failed")console.error(`[rove] teardown.sh in ${worktreePath} failed (${teardown.reason})`);let args=force?["worktree","remove","--force",worktreePath]:["worktree","remove",worktreePath],result=await deps.runGit(exec,args,{cwd:repo,allowFail:!0});if(result.exitCode!==0){if(await isRegisteredWorktree(deps,exec,repo,worktreePath))throw new GitCommandError(args,repo,result);opts?.onResidue?.({path:worktreePath,reason:result.stderr.trim()||result.stdout.trim()||"unknown"})}if(await deps.runGit(exec,["worktree","prune"],{cwd:repo,allowFail:!0}),branch){let outcome=await deleteBranchAnchored(deps.branchDeps(),exec,repo,branch,{force});if(!outcome.deleted)opts?.onBranchKept?.({branch,reason:outcome.reason})}}class GitWorktreeManager{execDeps;cloneDeps;constructor(execDeps=defaultExecDeps,cloneDeps=defaultCloneDeps){this.execDeps=execDeps;this.cloneDeps=cloneDeps}ctxFor(repoKey){let basePath=this.execDeps.remoteBasePath(repoKey);return basePath?{exec:this.execDeps.execForRepo(repoKey),dir:basePath,remote:!0}:{exec:this.execDeps.execForRepo(repoKey),dir:repoKey,remote:!1}}async runGit(exec,args,opts){if(!opts.cwd)throw Error("runGit(): cwd is required; refusing to inherit from process.cwd()");let env=opts.readOnly?{...opts.env,...READ_ONLY_GIT_ENV}:opts.env,r=await exec.run(["git",...args],{cwd:opts.cwd,env,onStderr:opts.onStderr}),result={stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode};if(result.exitCode!==0&&!opts.allowFail)throw new GitCommandError(args,opts.cwd,result);return result}async create(repo,branch,worktreePath,baseRef,onProgress){let ctx=this.ctxFor(repo);if(requireAbsolute("repo",ctx.dir),requireAbsolute("path",worktreePath),!branch)throw Error("create(): branch must be a non-empty string");if(await ctx.exec.exists(worktreePath)){let existing=await this.tryDescribe(ctx,worktreePath);if(existing){if(existing.branch!==branch)throw Error(`worktree at ${worktreePath} is on branch '${existing.branch}', refusing to hijack to '${branch}'`);return existing}throw Error(`create(): ${worktreePath} exists but is not a registered git worktree`)}await ctx.exec.mkdirp(path4.dirname(worktreePath));let args=await branchExists(this.branchDeps(),ctx,branch)?["worktree","add",worktreePath,branch]:baseRef?["worktree","add","-b",branch,worktreePath,baseRef]:["worktree","add","-b",branch,worktreePath];await this.runGit(ctx.exec,args,{cwd:ctx.dir,...onProgress?{onStderr:checkoutProgressReader(onProgress)}:{}});let info=await this.tryDescribe(ctx,worktreePath);if(!info)throw Error(`create(): git reported success but ${worktreePath} is not a worktree`);if(info.branch!==branch)throw Error(`create(): post-condition failed \u2014 expected branch '${branch}' at ${worktreePath}, got '${info.branch}'`);return info}async createForTask(args){let basePath=this.execDeps.remoteBasePath(args.repo),target=basePath?remoteWorktreePathFor(basePath,args.slug):worktreePathFor(args.repo,args.slug),ctx=this.ctxFor(args.repo),skipClone=ctx.remote||await ctx.exec.exists(target),info=await this.create(args.repo,args.branch,target,args.baseRef,args.onProgress);if(!skipClone)await cloneIgnoredDirs(ctx.exec,args.repo,info.path,this.cloneDeps(ctx.exec));return info}async remove(worktreePath,opts){await removeWorktree({runGit:(exec,args,runOpts)=>this.runGit(exec,args,runOpts),execForPath:(p)=>this.execDeps.execForPath(p),findRepoFor:(exec,p)=>this.findRepoFor(exec,p),currentBranch:(p)=>this.currentBranch(p),dirtyPaths:(p)=>this.dirtyPaths(p),ignoredWork:(p)=>this.ignoredWork(p),branchDeps:()=>this.branchDeps()},worktreePath,opts)}async deleteBranch(repo,branch,opts){let ctx=this.ctxFor(repo);return requireAbsolute("repo",ctx.dir),await deleteBranchAnchored(this.branchDeps(),ctx.exec,ctx.dir,branch,{force:opts?.force===!0,onAnchor:opts?.onAnchor})}execAt(worktreePath){return requireAbsolute("path",worktreePath),this.execDeps.execForPath(worktreePath)}branchDeps(){return{runGit:(exec,args,opts)=>this.runGit(exec,args,opts),execAt:(worktreePath)=>this.execAt(worktreePath),findRepoFor:(exec,worktreePath)=>this.findRepoFor(exec,worktreePath)}}listDeps(){return{ctxFor:(repoKey)=>this.ctxFor(repoKey),runGitStdout:async(ctx,args)=>(await this.runGit(ctx.exec,args,{cwd:ctx.dir,readOnly:!0})).stdout,runGitStdoutAt:async(ctx,cwd,args)=>(await this.runGit(ctx.exec,args,{cwd,readOnly:!0})).stdout,isDirty:(worktreePath)=>this.isDirty(worktreePath)}}list(repo){return listManaged(this.listDeps(),repo)}listAll(repo){return listAllAdoptable(this.listDeps(),repo)}listAdoptablePaths(repo){return adoptablePaths(this.listDeps(),this.ctxFor(repo))}listUnreadableWorktrees(repo){return unreadableWorktreeNames(this.listDeps(),this.ctxFor(repo))}listBranchNames(repo){return listBranchNames(this.listDeps(),repo)}async pathExists(worktreePath){return this.execAt(worktreePath).exists(worktreePath)}async pruneWorktrees(repo){let ctx=this.ctxFor(repo);requireAbsolute("repo",ctx.dir),await this.runGit(ctx.exec,["worktree","prune"],{cwd:ctx.dir,allowFail:!0})}async isDirty(worktreePath){return(await this.dirtyPaths(worktreePath)).length>0}async dirtyPaths(worktreePath){let out=await this.runGit(this.execAt(worktreePath),["status","--porcelain"],{cwd:worktreePath,readOnly:!0});return parseDirtyPaths(out.stdout)}async ignoredWork(worktreePath){let exec=this.execAt(worktreePath);return smallIgnoredPaths(exec,worktreePath,regenerableDirNames(exec,worktreePath,this.cloneDeps(exec)))}checkpointDeps(){return{runGit:(exec,args,opts)=>this.runGit(exec,args,opts)}}takeCheckpoint(worktreePath,taskId,opts){return takeCheckpoint(this.checkpointDeps(),this.execAt(worktreePath),worktreePath,taskId,opts)}listCheckpoints(worktreePath,taskId){return listCheckpoints(this.checkpointDeps(),this.execAt(worktreePath),worktreePath,taskId)}rewindToCheckpoint(worktreePath,taskId,n){return rewindTo(this.checkpointDeps(),this.execAt(worktreePath),worktreePath,taskId,n)}async deleteTaskCheckpoints(repo,taskId){let ctx=this.ctxFor(repo);return requireAbsolute("repo",ctx.dir),deleteTaskCheckpoints(this.checkpointDeps(),ctx.exec,ctx.dir,taskId)}async moveTaskCheckpoints(repo,fromId,toId){let ctx=this.ctxFor(repo);return requireAbsolute("repo",ctx.dir),moveTaskCheckpoints(this.checkpointDeps(),ctx.exec,ctx.dir,fromId,toId)}async currentBranch(worktreePath){let name=(await this.runGit(this.execAt(worktreePath),["rev-parse","--abbrev-ref","HEAD"],{cwd:worktreePath,readOnly:!0})).stdout.trim();if(!name||name==="HEAD")throw Error(`currentBranch(): ${worktreePath} is in detached-HEAD state`);return name}branchHasUpstream(worktreePath,branch){return branchHasUpstream(this.branchDeps(),worktreePath,branch)}hasLocalBranch(worktreePath,branch){return hasLocalBranch(this.branchDeps(),worktreePath,branch)}renameBranch(worktreePath,from,to){return renameBranch(this.branchDeps(),worktreePath,from,to)}async tryDescribe(ctx,worktreePath){let out=await this.runGit(ctx.exec,["worktree","list","--porcelain"],{cwd:ctx.dir,readOnly:!0}),entries=parseWorktreeListPorcelain(out.stdout),norm=(p)=>ctx.remote?p:canonicalize(p),target=norm(worktreePath),match=entries.find((e)=>e.path&&norm(e.path)===target);if(!match||!match.path||!match.branch||match.detached)return null;return{path:worktreePath,branch:match.branch,head:match.head??"",dirty:await this.isDirty(match.path)}}async findRepoFor(exec,worktreePath){try{let out=await this.runGit(exec,["rev-parse","--git-common-dir"],{cwd:worktreePath,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return null;let gitDir=out.stdout.trim();if(!gitDir)return null;let absolute=path4.isAbsolute(gitDir)?gitDir:path4.resolve(worktreePath,gitDir);return path4.basename(absolute)===".git"?path4.dirname(absolute):absolute}catch(err){if(err instanceof GitCommandError)return null;throw err}}}
|
|
11
12
|
export{CLONEFILEAT_PERL,git,parseDirtyPaths,isDirtyOutput,defaultExecDeps,GitWorktreeManager};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isPathLikeArg,runOpenDirectory}from"./chunk-
|
|
2
|
+
import{isPathLikeArg,runOpenDirectory}from"./chunk-tjgf18y5.js";import"./chunk-1feav1w3.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runOpenDirectory,isPathLikeArg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Orchestrator}from"./chunk-
|
|
2
|
+
import{Orchestrator}from"./chunk-mg4wkarb.js";import"./chunk-2b6nh6z4.js";import"./chunk-n8z4nb8v.js";import"./chunk-5djyy7ar.js";import"./chunk-7f02vk0v.js";import"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-2xsxcdp6.js";import"./chunk-mfmythv2.js";import"./chunk-zj0dzjk4.js";import"./chunk-xen161q5.js";import"./chunk-5dkx02g8.js";import"./chunk-x0f8a3ez.js";import"./chunk-k6gx8sqh.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-xmwp6je4.js";import"./chunk-6xppe9bj.js";import"./chunk-mqfvzdpr.js";import"./chunk-f26r2af1.js";import"./chunk-rj5g5zv1.js";import"./chunk-b9ea827p.js";import"./chunk-han0d078.js";import"./chunk-yx4mar9e.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-0mw4pd9k.js";import"./chunk-catrr0z3.js";import"./chunk-ewdanfd9.js";import"./chunk-tn9gtf18.js";import"./chunk-y849hsgp.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-dpgaag6b.js";import"./chunk-cmp64q4j.js";import"./chunk-aagx78v1.js";import"./chunk-qbbtvxmk.js";import"./chunk-wwes4z56.js";import"./chunk-w7zv47mp.js";import"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-mg1cas61.js";import"./chunk-p84bhs57.js";import"./chunk-hkqcc1t4.js";import"./chunk-1tmmkk54.js";import"./chunk-7kysxgbq.js";import"./chunk-yfwn3fj5.js";import"./chunk-vfrxywtx.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-w8da1czv.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{PLACEHOLDER_TASK_TITLE,Orchestrator};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,stopTaskEngineTabAdapter,tearDownTaskSessionAdapter}from"./chunk-m2jh1gyh.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{Orchestrator}from"./chunk-
|
|
2
|
+
import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,stopTaskEngineTabAdapter,tearDownTaskSessionAdapter}from"./chunk-m2jh1gyh.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{Orchestrator}from"./chunk-mg4wkarb.js";import{GH_PR_VIEW_FIELDS,classifyGhFailure,mapGhPrView,nextPrPoll,samePrStatus}from"./chunk-2b6nh6z4.js";import"./chunk-n8z4nb8v.js";import{GitWorktreeManager,parseDirtyPaths}from"./chunk-5djyy7ar.js";import"./chunk-7f02vk0v.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{startChatChannels}from"./chunk-xywsd3ng.js";import{auditDeletionBranchKept,auditDeletionResidue,auditDeletionSalvaged,auditWorktreeResidue,auditWorktreeSalvaged,parseAheadBehind,startDaemonServer}from"./chunk-4fcradt8.js";import"./chunk-8qy3wkp8.js";import"./chunk-a4hsqj1b.js";import"./chunk-wwpq8gs4.js";import{refreshOutdatedSkills}from"./chunk-ctssrypp.js";import"./chunk-4dt1gfb3.js";import"./chunk-rmnm3f9n.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{preferredReleaseChannel,updateDelayHours}from"./chunk-yg076bz0.js";import{cancelAllLogins}from"./chunk-67k0f144.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-2xsxcdp6.js";import"./chunk-mfmythv2.js";import{affectsActivityState,isEngineActivityKind}from"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-4hestsjp.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-zj0dzjk4.js";import"./chunk-xen161q5.js";import"./chunk-5dkx02g8.js";import{RELAY_PREAMBLE}from"./chunk-x0f8a3ez.js";import{TaskIndexStore}from"./chunk-c0fd63tg.js";import"./chunk-qkehg2c1.js";import"./chunk-5frd2aze.js";import"./chunk-k6gx8sqh.js";import{parsePorcelain}from"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import{DEFAULT_BASE_REF_CANDIDATES,readHeadSha,readRefSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import"./chunk-xmwp6je4.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion}from"./chunk-msk54e9v.js";import{SUBCOMMAND_VERBS}from"./chunk-nbcm8d58.js";import"./chunk-60rsw6md.js";import"./chunk-e5dv15e5.js";import"./chunk-49zrnjq1.js";import"./chunk-mqfvzdpr.js";import"./chunk-afyn4v7z.js";import{installDaemonCrashHandlers,logDaemonError,logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-52y3whbh.js";import"./chunk-q30ggttf.js";import{autoStatusEnabled,protocolUpgradeFromLiveSession,protocolWriteBackFromLiveSession}from"./chunk-f26r2af1.js";import"./chunk-rj5g5zv1.js";import{engineDisplayName,engineProtocolKey,protocolEntry,roveApiInvocation,sessionProtocol}from"./chunk-b9ea827p.js";import"./chunk-han0d078.js";import"./chunk-yx4mar9e.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import{teardownScope}from"./chunk-g9ba25q5.js";import"./chunk-0mw4pd9k.js";import"./chunk-catrr0z3.js";import{stateFileTabsPersistence}from"./chunk-ewdanfd9.js";import"./chunk-tn9gtf18.js";import{execHostForWorktreePath}from"./chunk-y849hsgp.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag,switchFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-dpgaag6b.js";import"./chunk-cmp64q4j.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-aagx78v1.js";import{createEngineTurnDetector,engineEntry,engineTitleTurnHint,spawnCapture,vendorsWithQuotaProbe}from"./chunk-qbbtvxmk.js";import{availableEngineIds}from"./chunk-wwes4z56.js";import"./chunk-w7zv47mp.js";import{daemonSpawnReason,restartDaemon}from"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import{RoveDaemonClient}from"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import{backfillSavedReposFromProjects,getCustomEngineIds,getPersistedString,getRemoteRepoConfig,getSavedRepos,setPersistedString}from"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-p84bhs57.js";import"./chunk-hkqcc1t4.js";import"./chunk-1tmmkk54.js";import"./chunk-7kysxgbq.js";import"./chunk-yfwn3fj5.js";import{rotateLogIfNeeded}from"./chunk-vfrxywtx.js";import{DEFAULT_TASK_VENDOR,isTaskStatus}from"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import{migrateRoveDaemonStateLayout}from"./chunk-m5nd44st.js";import{releaseSync}from"./chunk-w8da1czv.js";import{isProcessAlive,readPidFile}from"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import{readRoveHomeDirEnv}from"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";async function latestTranscriptMtime(vendor,worktree){if(!worktree)return 0;return protocolEntry(vendor).history.latestTranscriptMtimeForWorktree(worktree)}async function maybeAutoStart(orch,taskId,enabled=autoStatusEnabled){if(!enabled())return"skipped";let task=orch.getTask(taskId);if(!task)return"skipped";if((task.kind??"task")==="main")return"skipped";if(task.status!=="backlog")return"skipped";return await orch.setStatus(taskId,"in_progress"),"moved"}var SYNC_TIMEOUT_MS=60000,SYNC_CONFLICT="SYNC_CONFLICT",SYNC_DIRTY="SYNC_WORKTREE_DIRTY";async function git(cwd,args,signal,write=!1){return spawnCapture("git",args,{cwd,env:write?process.env:readOnlyGitProcessEnv(),signal})}function parseConflictedPaths(stdout){return stdout.split(`
|
|
3
3
|
`).map((line)=>line.trim()).filter((line)=>line.length>0)}async function syncWorktreeWithBase(worktreePath,baseRef,signal){let status=await git(worktreePath,["status","--porcelain=v1"],signal);if(status.status!==0)throw Error("git status failed");let dirty=parseDirtyPaths(status.stdout);if(dirty.length>0)throw Error(`${SYNC_DIRTY}: ${dirty.join(", ")}`);let before=await git(worktreePath,["rev-parse","HEAD"],signal),merge=await git(worktreePath,["merge","--no-edit",baseRef],signal,!0);if(merge.status!==0){let conflicted=await git(worktreePath,["diff","--name-only","--diff-filter=U"],signal),paths=parseConflictedPaths(conflicted.stdout);if(paths.length>0)throw Error(`${SYNC_CONFLICT}: ${paths.join(", ")}`);let detail=merge.stderr?.trim();throw Error(detail?`git merge ${baseRef} failed \u2014 ${detail}`:`git merge ${baseRef} failed`)}let after=await git(worktreePath,["rev-parse","HEAD"],signal);return{baseRef,alreadyCurrent:before.status===0&&before.stdout.trim()===after.stdout.trim()}}import{readFileSync}from"fs";import{join}from"path";var BASE_REF_TTL_MS=300000,cache=new Map;async function git2(worktreePath,args,signal){return await spawnCapture("git",[...args],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal})}async function refExists(worktreePath,ref,signal){return(await git2(worktreePath,["rev-parse","--verify","--quiet",ref],signal)).status===0}async function sharesHistory(worktreePath,ref,signal){return(await git2(worktreePath,["merge-base",ref,"HEAD"],signal)).status===0}async function baseCheckoutBranchFromGit(worktreePath,signal){let out=await git2(worktreePath,["worktree","list","--porcelain"],signal);if(out.status!==0)return null;return(out.stdout.split(`
|
|
4
4
|
|
|
5
5
|
`,1)[0]??"").split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{canonPath,normalizeMainRepo,randomDirTaskSuffix,repoWorkingDir,samePrStatus,titleFromRepo}from"./chunk-2b6nh6z4.js";import{isUnlistedCheckout}from"./chunk-n8z4nb8v.js";import{CLONEFILEAT_PERL,GitWorktreeManager,defaultExecDeps,git,isDirtyOutput,parseDirtyPaths}from"./chunk-38z8sgf3.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-7f02vk0v.js";import{LAUNCH_PREFIX_FILE}from"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-2xsxcdp6.js";import{CannotDeleteMainTaskError,DirtyWorktreeError,EmptyBranchDirtyWorktreeError,EmptyBranchError,ExtraRepoNotGitError,ForkUnsupportedError,GitCommandFailedError,IllegalTransitionError,InvalidWorktreeNameError,LandConflictError,MainCheckoutDirtyError,MissingRefError,MoveRefusedError,NotAGitRepoError,NotALinkedRepoError,REMOTE_PARENT_UNSUPPORTED_CODE,RemoteExtraUnsupportedError,RemoteParentUnsupportedError,ReparentRefusedError,RepoDuplicateError,TaskDeletingError,TaskNotFoundError,TooManyReposError,WorktreeNameTakenError,WorktreeRemoveFailedError,canonicalize,listWorktreeDirNames,worktreePathFor}from"./chunk-mfmythv2.js";import{forwardVerb,requireMachine}from"./chunk-zj0dzjk4.js";import{resolvePreferredVendor}from"./chunk-k6gx8sqh.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{readRemoteWorkspace,removeRemoteLink}from"./chunk-rj5g5zv1.js";import{detectLanguage}from"./chunk-0mw4pd9k.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{addSavedRepo,getPersistedString,getSavedRepos,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot}from"./chunk-bgmpczgm.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{projectRejection,rejectionReason}from"./chunk-mg1cas61.js";import{MULTI_REPO_CAP,SESSION_PR_CAP,WORKSPACE_CAPABILITIES,applyTodoOps,checkNotes,childrenOf,gitRepoOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName,workspaceBackendId,workspaceCapabilities}from"./chunk-yfwn3fj5.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{pathIdentity,pathWithin,samePath}from"./chunk-pn5ygqn6.js";class WorkspaceCheckpoints{store;worktrees;workspaces;requireTask;constructor(store,worktrees,workspaces,requireTask){this.store=store;this.worktrees=worktrees;this.workspaces=workspaces;this.requireTask=requireTask}workspaceOwner(id){let task=this.requireTask(id);return(task.sharesWorkspaceOf?this.store.get(task.sharesWorkspaceOf):void 0)??task}checkpointScope(id){let owner=this.workspaceOwner(id),sharers=this.store.list().filter((t)=>t.sharesWorkspaceOf===owner.id&&!t.deletion);return{ownerId:String(owner.id),sharerIds:[String(owner.id),...sharers.map((t)=>String(t.id))]}}canCheckpoint(id){if(!this.store.get(id))return!1;let owner=this.workspaceOwner(id);return workspaceCapabilities(owner).checkpoint&&!owner.deletion&&owner.worktreePath!==""}async target(id){let owner=this.workspaceOwner(id),own=this.canCheckpoint(id)?this.workspaces.get(workspaceBackendId(owner)).checkpoints:void 0,dir=owner.worktreePath;if(!this.canCheckpoint(id)||!await this.worktrees.pathExists(own?dir:`${dir}/.git`))throw Error(`NOT_CHECKPOINTABLE: ${owner.kind==="task"?"the task has no workspace on disk":`a ${owner.kind} task works in your own checkout`}`);let ownerId=String(owner.id);return{ownerId,dir,via:own??{take:(d,opts)=>this.worktrees.takeCheckpoint(d,ownerId,opts),list:(d)=>this.worktrees.listCheckpoints(d,ownerId),rewind:(d,n)=>this.worktrees.rewindToCheckpoint(d,ownerId,n)}}}async takeCheckpoint(id,opts){let{dir,via}=await this.target(id);return via.take(dir,opts)}async listCheckpoints(id){let{dir,via}=await this.target(id);return via.list(dir)}async rewindToCheckpoint(id,n){let{dir,via}=await this.target(id);return via.rewind(dir,n)}async exportBranch(id){let owner=this.workspaceOwner(id),backend=this.workspaces.get(workspaceBackendId(owner));if(!backend.exportBranch||!owner.worktreePath)throw Error("EXPORT_UNSUPPORTED: the task's branch is already in its repo (or it has no workspace yet)");return backend.exportBranch({path:owner.worktreePath,repo:gitRepoOf(owner),branch:owner.branch})}}var TYPE_PREFIXES=new Set(["feat","feature","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","build","perf","style","revert","release"]),BRAND_TOKENS=new Set(["rove"]);function inferBranchStyle(names){let typed=new Map,bare=0;for(let raw of new Set(names)){let name=raw.trim();if(!name||name==="HEAD")continue;let slash=name.indexOf("/");if(slash===-1){bare+=1;continue}let prefix=name.slice(0,slash);if(TYPE_PREFIXES.has(prefix))typed.set(prefix,(typed.get(prefix)??0)+1)}let typedTotal=0;for(let n of typed.values())typedTotal+=n;if(typedTotal===0||typedTotal<bare)return{kind:"bare"};let best="",bestN=0;for(let[prefix,n]of typed)if(n>bestN||n===bestN&&(best===""||prefix<best))best=prefix,bestN=n;return{kind:"typed",defaultPrefix:best}}function slugTokens(title){return title.toLowerCase().replace(/[^a-z0-9]+/g,"-").split("-").filter((t)=>t.length>0&&!BRAND_TOKENS.has(t))}function capSlug(tokens){let slug="";for(let token of tokens){let candidate=slug?`${slug}-${token}`:token;if(candidate.length>32)return slug||token.slice(0,32);slug=candidate}return slug}function identitySlug(taskId){return`task-${taskId.slice(-6).toLowerCase()}`}function deriveConventionBranch(title,style,taskId){let tokens=slugTokens(title);if(style.kind==="typed"){let first=tokens[0];return`${first!==void 0&&TYPE_PREFIXES.has(first)?tokens.shift():style.defaultPrefix}/${capSlug(tokens)||identitySlug(taskId)}`}return capSlug(tokens)||identitySlug(taskId)}function uniqueBranchName(base,taken,taskId){let dirs=new Set;for(let name of taken)for(let i=name.indexOf("/");i>0;i=name.indexOf("/",i+1))dirs.add(name.slice(0,i));let isFree=(name)=>!taken.has(name)&&!dirs.has(name),segments=base.split("/"),root=segments.slice(0,-1).some((_,i)=>taken.has(segments.slice(0,i+1).join("/")))?segments.join("-"):base;if(isFree(root))return root;for(let n=2;n<=99;n+=1){let candidate=`${root}-${n}`;if(isFree(candidate))return candidate}return`${root}-${taskId.slice(-6).toLowerCase()}`}function planExtraRepos(primary,inputs){if(inputs.length===0)return[];if(1+inputs.length>MULTI_REPO_CAP)throw new TooManyReposError(1+inputs.length,MULTI_REPO_CAP);if(isRemoteRepoKey(primary))throw new RemoteExtraUnsupportedError(primary);let seen=new Set([canonPath(primary)]),names=new Set([repoNameOf(primary)]);return inputs.map((input)=>{if(isRemoteRepoKey(input.repo))throw new RemoteExtraUnsupportedError(input.repo);let{repo}=normalizeMainRepo(input.repo);if(!isGitRepo(repo))throw new ExtraRepoNotGitError(input.repo);if(seen.has(canonPath(repo)))throw new RepoDuplicateError(repo);seen.add(canonPath(repo));let name=uniqueRepoName(repoNameOf(repo),names);names.add(name);let baseRef=input.baseRef?.trim();return{name,repo,branch:"",worktreePath:"",...baseRef?{baseRef}:{}}})}async function rollbackWorktree(backend,created){try{await backend.dispose({path:created.path,...created.fresh},created.fresh?{force:!0,deleteBranch:!0}:{force:!0})}catch(err){console.error(`[rove] ensureWorktree rollback failed for ${created.path}:`,err)}}async function extrasToMaterialise(worktrees,extras){let missing=[];for(let extra of extras??[])if(!extra.worktreePath||!await worktrees.pathExists(extra.worktreePath))missing.push(extra);return missing}function scaleProgress(onProgress,step,total){return onProgress&&((percent)=>onProgress(Math.floor((step+percent/100)/total*100)))}async function materialiseExtras(opts){let{worktrees,backend,slugs,task}=opts,callerNamed=task.branch!=="",created=[],picked=[],done=new Map,missing=await extrasToMaterialise(worktrees,task.extraRepos);try{for(let[index,extra]of missing.entries()){if(extra.worktreePath)await worktrees.pruneWorktrees(extra.repo);let names=await worktrees.listBranchNames(extra.repo),branch=extra.branch||(callerNamed||!names.includes(opts.branch)?opts.branch:uniqueBranchName(opts.branch,new Set(names),task.id)),slug=await slugs.allocate(extra.repo);picked.push({repo:extra.repo,slug});let info=await backend.materialize({repo:extra.repo,slug,branch,baseRef:extra.baseRef,onProgress:opts.progressFor(index)});created.push({path:info.path,...names.includes(branch)?{}:{fresh:{repo:extra.repo,branch}}}),done.set(extra.name,{...extra,branch,worktreePath:info.path})}}catch(err){for(let wt of created.reverse())await rollbackWorktree(backend,wt);for(let{repo,slug}of picked)slugs.cancel(repo,slug);throw err}return{extraRepos:(task.extraRepos??[]).map((e)=>done.get(e.name)??e),created,slugs:picked}}function nestingParent(store,id){let parent=store.get(id);if(!parent)throw new TaskNotFoundError(id);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(isRemoteRepoKey(parent.repo))throw new RemoteParentUnsupportedError(String(parent.id));return toTaskId(lineageRootId(store.list(),parent.id))}async function createTaskRow(deps,input){if(!input.repo)throw Error("createTask: repo is required");let extraRepos=planExtraRepos(normalizeMainRepo(input.repo).repo,input.extraRepos??[]),parentTaskId=input.parentTaskId?nestingParent(deps.store,input.parentTaskId):void 0,repo=(await deps.mainTasks.ensureIfEligible(input.repo,input.projectIntent??"explicit"))?.repo??normalizeMainRepo(input.repo).repo,title=sanitizeTaskTitle(input.title??PLACEHOLDER_TASK_TITLE)||PLACEHOLDER_TASK_TITLE,worktreeName=input.worktreeName?.trim();if(worktreeName)await deps.claimWorktreeName(repo,worktreeName);return await deps.store.create({repo,title,branch:input.branch??"",worktreePath:"",status:"backlog",kind:"task",vendor:input.vendor??DEFAULT_TASK_VENDOR,...input.command?.trim()?{command:input.command.trim()}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},...input.tier?.trim()?{tier:input.tier.trim()}:{},...input.groupId?{groupId:input.groupId}:{},...input.dispatcher?{dispatcher:input.dispatcher}:{},...parentTaskId?{parentTaskId}:{},...input.worktreeOnly?{worktreeOnly:!0}:{},...input.cwdSubpath?{cwdSubpath:input.cwdSubpath}:{},...input.routine?{routine:input.routine}:{},...input.baseRef?.trim()?{baseRef:input.baseRef.trim()}:{},...extraRepos.length>0?{extraRepos}:{},...input.workspace?{workspace:input.workspace}:{},...worktreeName?{worktreeName}:{}})}async function openDirectoryTaskRow(deps,input){if(!input.dir)throw Error("openDirectoryTask: dir is required");let dir=canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:dir,status:"backlog",kind:"dir",...input.scratch?{scratch:!0}:{},...input.noProject?{noProject:!0}:{},...input.routine?{routine:input.routine}:{},...input.workspace?{workspace:input.workspace}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},vendor:input.vendor??resolvePreferredVendor()})}async function adoptScratchRepoRow(deps,id,repo){let task=deps.store.get(id);if(!task||task.kind!=="dir"||task.scratch!==!0)return;let dir=canonPath(repo);await deps.store.update(id,{repo:dir,worktreePath:dir,scratch:!1,title:titleFromRepo(dir)})}class BorrowedBackend{id="borrowed";capabilities=WORKSPACE_CAPABILITIES.borrowed;async materialize(spec){return{backend:this.id,path:spec.path??repoWorkingDir(spec.repo)}}async dispose(){}}import{execFile}from"child_process";import{promises as fs,statSync}from"fs";import path from"path";import{promisify}from"util";var run=promisify(execFile),CP_CHUNK=200;function cloneFlags(){if(process.platform==="darwin")return["-c","-R","-P"];if(process.platform==="linux")return["--reflink=always","-a"];return null}var cpClone=async(entries,to)=>{let flags=cloneFlags();if(!flags)throw new ForkUnsupportedError(`copy-on-write clones are not supported on ${process.platform}`);for(let i=0;i<entries.length;i+=CP_CHUNK)try{await run("cp",[...flags,...entries.slice(i,i+CP_CHUNK),`${to}${path.sep}`])}catch(err){let detail=err.stderr?.trim()||String(err);throw Error(`cloning the worktree failed: ${detail}`)}},probeCache=new Map;async function cloneOneFile(source,target){if(process.platform==="darwin")await run("/usr/bin/perl",["-e",CLONEFILEAT_PERL,source,target]);else if(process.platform==="linux")await run("cp",["--reflink=always",source,target]);else throw Error(`no clone primitive on ${process.platform}`)}var volumeProbe=(from,toDir)=>{let key=`${statSync(from).dev}:${statSync(toDir).dev}`,known=probeCache.get(key);if(!known)known=(async()=>{let probe=path.join(toDir,`.rove-clone-probe-${process.pid}`);try{return await cloneOneFile(path.join(from,".git"),probe),!0}catch{return!1}finally{await fs.rm(probe,{force:!0})}})(),probeCache.set(key,known);return known};async function git2(cwd,args){let{stdout}=await run("git",[...args],{cwd,maxBuffer:67108864});return stdout.trim()}class CowCloneBackend{plain;id="cow-clone";capabilities=WORKSPACE_CAPABILITIES["cow-clone"];probe;cloneEntries;constructor(plain,deps={}){this.plain=plain;this.probe=deps.probe??volumeProbe,this.cloneEntries=deps.cloneEntries??cpClone}async materialize(spec){let parent=spec.forkFrom;if(!parent)return{...await this.plain.materialize(spec),backend:this.id};if(isRemoteRepoKey(spec.repo))throw new ForkUnsupportedError("a remote project's worktree cannot be cloned");let target=worktreePathFor(spec.repo,spec.slug),root=path.dirname(target);if(await fs.mkdir(root,{recursive:!0}),!await this.probe(parent,root))throw new ForkUnsupportedError(`${parent} and ${root} are not on one volume that can clone files (APFS, btrfs, XFS with reflink); the fork would have to copy the whole tree`);let head=await git2(parent,["rev-parse","HEAD"]);await git2(spec.repo,["worktree","add","--no-checkout","-b",spec.branch,target,head]);try{let entries=(await fs.readdir(parent)).filter((name)=>name!==".git").map((name)=>path.join(parent,name));await this.cloneEntries(entries,target),await this.carryIndex(parent,target)}catch(err){throw await this.discard(spec.repo,target,spec.branch),err}return{backend:this.id,path:target}}async carryIndex(parent,target){let indexOf=(dir)=>git2(dir,["rev-parse","--path-format=absolute","--git-path","index"]);try{await fs.copyFile(await indexOf(parent),await indexOf(target)),await git2(target,["update-index","-q","--refresh"])}catch{await git2(target,["reset","-q"])}}async discard(repo,target,branch){await git2(repo,["worktree","remove","--force",target]).catch(()=>{}),await fs.rm(target,{recursive:!0,force:!0}),await git2(repo,["worktree","prune"]).catch(()=>{}),await git2(repo,["branch","-D",branch]).catch(()=>{})}dispose(target,opts){return this.plain.dispose(target,opts)}}class GitWorktreeBackend{worktrees;id="git-worktree";capabilities=WORKSPACE_CAPABILITIES["git-worktree"];constructor(worktrees){this.worktrees=worktrees}async materialize(spec){let info=await this.worktrees.createForTask({repo:spec.repo,slug:spec.slug,branch:spec.branch,baseRef:spec.baseRef,onProgress:spec.onProgress});return{backend:this.id,path:info.path}}async dispose(target,opts){await this.worktrees.remove(target.path,{...opts,repo:target.repo,branch:target.branch})}}import{execFile as execFile2}from"child_process";import{createHash}from"crypto";import{promises as fs2,readFileSync}from"fs";import os from"os";import path2 from"path";import{promisify as promisify2}from"util";var LAYERFS_CONFIG_KEY="experimental.layerfs",STATE_FILE=".rove-layerfs.json",SANDBOX_USER="501:20",SANDBOX_HOME="/tmp/rove-home",KILL_TAGGED=`for p in /proc/[0-9]*; do tr '\\0' '\\n' < $p/environ 2>/dev/null | grep -qx "$1" && kill -KILL \${p#/proc/}; done; true`,KILL_UNDER='for p in /proc/[0-9]*; do case $(readlink $p/cwd) in "$1"|"$1"/*) kill -KILL ${p#/proc/};; esac; done; sleep 0.2',execRun=async(file,args)=>{try{let{stdout}=await promisify2(execFile2)(file,[...args],{maxBuffer:67108864});return stdout}catch(err){let e=err;throw Error((e.stderr?.trim()||e.stdout?.trim()||e.message).slice(0,2000))}};function parseLayerfsEnv(text){let env={};for(let line of text.split(`
|
|
2
|
+
import{canonPath,normalizeMainRepo,randomDirTaskSuffix,repoWorkingDir,samePrStatus,titleFromRepo}from"./chunk-2b6nh6z4.js";import{isUnlistedCheckout}from"./chunk-n8z4nb8v.js";import{CLONEFILEAT_PERL,GitWorktreeManager,defaultExecDeps,git,isDirtyOutput,parseDirtyPaths}from"./chunk-5djyy7ar.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-7f02vk0v.js";import{LAUNCH_PREFIX_FILE}from"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-2xsxcdp6.js";import{CannotDeleteMainTaskError,DirtyWorktreeError,EmptyBranchDirtyWorktreeError,EmptyBranchError,ExtraRepoNotGitError,ForkUnsupportedError,GitCommandFailedError,IllegalTransitionError,InvalidWorktreeNameError,LandConflictError,MainCheckoutDirtyError,MissingRefError,MoveRefusedError,NotAGitRepoError,NotALinkedRepoError,REMOTE_PARENT_UNSUPPORTED_CODE,RemoteExtraUnsupportedError,RemoteParentUnsupportedError,ReparentRefusedError,RepoDuplicateError,TaskDeletingError,TaskNotFoundError,TooManyReposError,WorktreeNameTakenError,WorktreeRemoveFailedError,canonicalize,listWorktreeDirNames,worktreePathFor}from"./chunk-mfmythv2.js";import{forwardVerb,requireMachine}from"./chunk-zj0dzjk4.js";import{resolvePreferredVendor}from"./chunk-k6gx8sqh.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{readRemoteWorkspace,removeRemoteLink}from"./chunk-rj5g5zv1.js";import{detectLanguage}from"./chunk-0mw4pd9k.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{addSavedRepo,getPersistedString,getSavedRepos,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot}from"./chunk-bgmpczgm.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{projectRejection,rejectionReason}from"./chunk-mg1cas61.js";import{MULTI_REPO_CAP,SESSION_PR_CAP,WORKSPACE_CAPABILITIES,applyTodoOps,checkNotes,childrenOf,gitRepoOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName,workspaceBackendId,workspaceCapabilities}from"./chunk-yfwn3fj5.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{pathIdentity,pathWithin,samePath}from"./chunk-pn5ygqn6.js";class WorkspaceCheckpoints{store;worktrees;workspaces;requireTask;constructor(store,worktrees,workspaces,requireTask){this.store=store;this.worktrees=worktrees;this.workspaces=workspaces;this.requireTask=requireTask}workspaceOwner(id){let task=this.requireTask(id);return(task.sharesWorkspaceOf?this.store.get(task.sharesWorkspaceOf):void 0)??task}checkpointScope(id){let owner=this.workspaceOwner(id),sharers=this.store.list().filter((t)=>t.sharesWorkspaceOf===owner.id&&!t.deletion);return{ownerId:String(owner.id),sharerIds:[String(owner.id),...sharers.map((t)=>String(t.id))]}}canCheckpoint(id){if(!this.store.get(id))return!1;let owner=this.workspaceOwner(id);return workspaceCapabilities(owner).checkpoint&&!owner.deletion&&owner.worktreePath!==""}async target(id){let owner=this.workspaceOwner(id),own=this.canCheckpoint(id)?this.workspaces.get(workspaceBackendId(owner)).checkpoints:void 0,dir=owner.worktreePath;if(!this.canCheckpoint(id)||!await this.worktrees.pathExists(own?dir:`${dir}/.git`))throw Error(`NOT_CHECKPOINTABLE: ${owner.kind==="task"?"the task has no workspace on disk":`a ${owner.kind} task works in your own checkout`}`);let ownerId=String(owner.id);return{ownerId,dir,via:own??{take:(d,opts)=>this.worktrees.takeCheckpoint(d,ownerId,opts),list:(d)=>this.worktrees.listCheckpoints(d,ownerId),rewind:(d,n)=>this.worktrees.rewindToCheckpoint(d,ownerId,n)}}}async takeCheckpoint(id,opts){let{dir,via}=await this.target(id);return via.take(dir,opts)}async listCheckpoints(id){let{dir,via}=await this.target(id);return via.list(dir)}async rewindToCheckpoint(id,n){let{dir,via}=await this.target(id);return via.rewind(dir,n)}async exportBranch(id){let owner=this.workspaceOwner(id),backend=this.workspaces.get(workspaceBackendId(owner));if(!backend.exportBranch||!owner.worktreePath)throw Error("EXPORT_UNSUPPORTED: the task's branch is already in its repo (or it has no workspace yet)");return backend.exportBranch({path:owner.worktreePath,repo:gitRepoOf(owner),branch:owner.branch})}}var TYPE_PREFIXES=new Set(["feat","feature","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","build","perf","style","revert","release"]),BRAND_TOKENS=new Set(["rove"]);function inferBranchStyle(names){let typed=new Map,bare=0;for(let raw of new Set(names)){let name=raw.trim();if(!name||name==="HEAD")continue;let slash=name.indexOf("/");if(slash===-1){bare+=1;continue}let prefix=name.slice(0,slash);if(TYPE_PREFIXES.has(prefix))typed.set(prefix,(typed.get(prefix)??0)+1)}let typedTotal=0;for(let n of typed.values())typedTotal+=n;if(typedTotal===0||typedTotal<bare)return{kind:"bare"};let best="",bestN=0;for(let[prefix,n]of typed)if(n>bestN||n===bestN&&(best===""||prefix<best))best=prefix,bestN=n;return{kind:"typed",defaultPrefix:best}}function slugTokens(title){return title.toLowerCase().replace(/[^a-z0-9]+/g,"-").split("-").filter((t)=>t.length>0&&!BRAND_TOKENS.has(t))}function capSlug(tokens){let slug="";for(let token of tokens){let candidate=slug?`${slug}-${token}`:token;if(candidate.length>32)return slug||token.slice(0,32);slug=candidate}return slug}function identitySlug(taskId){return`task-${taskId.slice(-6).toLowerCase()}`}function deriveConventionBranch(title,style,taskId){let tokens=slugTokens(title);if(style.kind==="typed"){let first=tokens[0];return`${first!==void 0&&TYPE_PREFIXES.has(first)?tokens.shift():style.defaultPrefix}/${capSlug(tokens)||identitySlug(taskId)}`}return capSlug(tokens)||identitySlug(taskId)}function uniqueBranchName(base,taken,taskId){let dirs=new Set;for(let name of taken)for(let i=name.indexOf("/");i>0;i=name.indexOf("/",i+1))dirs.add(name.slice(0,i));let isFree=(name)=>!taken.has(name)&&!dirs.has(name),segments=base.split("/"),root=segments.slice(0,-1).some((_,i)=>taken.has(segments.slice(0,i+1).join("/")))?segments.join("-"):base;if(isFree(root))return root;for(let n=2;n<=99;n+=1){let candidate=`${root}-${n}`;if(isFree(candidate))return candidate}return`${root}-${taskId.slice(-6).toLowerCase()}`}function planExtraRepos(primary,inputs){if(inputs.length===0)return[];if(1+inputs.length>MULTI_REPO_CAP)throw new TooManyReposError(1+inputs.length,MULTI_REPO_CAP);if(isRemoteRepoKey(primary))throw new RemoteExtraUnsupportedError(primary);let seen=new Set([canonPath(primary)]),names=new Set([repoNameOf(primary)]);return inputs.map((input)=>{if(isRemoteRepoKey(input.repo))throw new RemoteExtraUnsupportedError(input.repo);let{repo}=normalizeMainRepo(input.repo);if(!isGitRepo(repo))throw new ExtraRepoNotGitError(input.repo);if(seen.has(canonPath(repo)))throw new RepoDuplicateError(repo);seen.add(canonPath(repo));let name=uniqueRepoName(repoNameOf(repo),names);names.add(name);let baseRef=input.baseRef?.trim();return{name,repo,branch:"",worktreePath:"",...baseRef?{baseRef}:{}}})}async function rollbackWorktree(backend,created){try{await backend.dispose({path:created.path,...created.fresh},created.fresh?{force:!0,deleteBranch:!0}:{force:!0})}catch(err){console.error(`[rove] ensureWorktree rollback failed for ${created.path}:`,err)}}async function extrasToMaterialise(worktrees,extras){let missing=[];for(let extra of extras??[])if(!extra.worktreePath||!await worktrees.pathExists(extra.worktreePath))missing.push(extra);return missing}function scaleProgress(onProgress,step,total){return onProgress&&((percent)=>onProgress(Math.floor((step+percent/100)/total*100)))}async function materialiseExtras(opts){let{worktrees,backend,slugs,task}=opts,callerNamed=task.branch!=="",created=[],picked=[],done=new Map,missing=await extrasToMaterialise(worktrees,task.extraRepos);try{for(let[index,extra]of missing.entries()){if(extra.worktreePath)await worktrees.pruneWorktrees(extra.repo);let names=await worktrees.listBranchNames(extra.repo),branch=extra.branch||(callerNamed||!names.includes(opts.branch)?opts.branch:uniqueBranchName(opts.branch,new Set(names),task.id)),slug=await slugs.allocate(extra.repo);picked.push({repo:extra.repo,slug});let info=await backend.materialize({repo:extra.repo,slug,branch,baseRef:extra.baseRef,onProgress:opts.progressFor(index)});created.push({path:info.path,...names.includes(branch)?{}:{fresh:{repo:extra.repo,branch}}}),done.set(extra.name,{...extra,branch,worktreePath:info.path})}}catch(err){for(let wt of created.reverse())await rollbackWorktree(backend,wt);for(let{repo,slug}of picked)slugs.cancel(repo,slug);throw err}return{extraRepos:(task.extraRepos??[]).map((e)=>done.get(e.name)??e),created,slugs:picked}}function nestingParent(store,id){let parent=store.get(id);if(!parent)throw new TaskNotFoundError(id);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(isRemoteRepoKey(parent.repo))throw new RemoteParentUnsupportedError(String(parent.id));return toTaskId(lineageRootId(store.list(),parent.id))}async function createTaskRow(deps,input){if(!input.repo)throw Error("createTask: repo is required");let extraRepos=planExtraRepos(normalizeMainRepo(input.repo).repo,input.extraRepos??[]),parentTaskId=input.parentTaskId?nestingParent(deps.store,input.parentTaskId):void 0,repo=(await deps.mainTasks.ensureIfEligible(input.repo,input.projectIntent??"explicit"))?.repo??normalizeMainRepo(input.repo).repo,title=sanitizeTaskTitle(input.title??PLACEHOLDER_TASK_TITLE)||PLACEHOLDER_TASK_TITLE,worktreeName=input.worktreeName?.trim();if(worktreeName)await deps.claimWorktreeName(repo,worktreeName);return await deps.store.create({repo,title,branch:input.branch??"",worktreePath:"",status:"backlog",kind:"task",vendor:input.vendor??DEFAULT_TASK_VENDOR,...input.command?.trim()?{command:input.command.trim()}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},...input.tier?.trim()?{tier:input.tier.trim()}:{},...input.groupId?{groupId:input.groupId}:{},...input.dispatcher?{dispatcher:input.dispatcher}:{},...parentTaskId?{parentTaskId}:{},...input.worktreeOnly?{worktreeOnly:!0}:{},...input.cwdSubpath?{cwdSubpath:input.cwdSubpath}:{},...input.routine?{routine:input.routine}:{},...input.baseRef?.trim()?{baseRef:input.baseRef.trim()}:{},...extraRepos.length>0?{extraRepos}:{},...input.workspace?{workspace:input.workspace}:{},...worktreeName?{worktreeName}:{}})}async function openDirectoryTaskRow(deps,input){if(!input.dir)throw Error("openDirectoryTask: dir is required");let dir=canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:dir,status:"backlog",kind:"dir",...input.scratch?{scratch:!0}:{},...input.noProject?{noProject:!0}:{},...input.routine?{routine:input.routine}:{},...input.workspace?{workspace:input.workspace}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},vendor:input.vendor??resolvePreferredVendor()})}async function adoptScratchRepoRow(deps,id,repo){let task=deps.store.get(id);if(!task||task.kind!=="dir"||task.scratch!==!0)return;let dir=canonPath(repo);await deps.store.update(id,{repo:dir,worktreePath:dir,scratch:!1,title:titleFromRepo(dir)})}class BorrowedBackend{id="borrowed";capabilities=WORKSPACE_CAPABILITIES.borrowed;async materialize(spec){return{backend:this.id,path:spec.path??repoWorkingDir(spec.repo)}}async dispose(){}}import{execFile}from"child_process";import{promises as fs,statSync}from"fs";import path from"path";import{promisify}from"util";var run=promisify(execFile),CP_CHUNK=200;function cloneFlags(){if(process.platform==="darwin")return["-c","-R","-P"];if(process.platform==="linux")return["--reflink=always","-a"];return null}var cpClone=async(entries,to)=>{let flags=cloneFlags();if(!flags)throw new ForkUnsupportedError(`copy-on-write clones are not supported on ${process.platform}`);for(let i=0;i<entries.length;i+=CP_CHUNK)try{await run("cp",[...flags,...entries.slice(i,i+CP_CHUNK),`${to}${path.sep}`])}catch(err){let detail=err.stderr?.trim()||String(err);throw Error(`cloning the worktree failed: ${detail}`)}},probeCache=new Map;async function cloneOneFile(source,target){if(process.platform==="darwin")await run("/usr/bin/perl",["-e",CLONEFILEAT_PERL,source,target]);else if(process.platform==="linux")await run("cp",["--reflink=always",source,target]);else throw Error(`no clone primitive on ${process.platform}`)}var volumeProbe=(from,toDir)=>{let key=`${statSync(from).dev}:${statSync(toDir).dev}`,known=probeCache.get(key);if(!known)known=(async()=>{let probe=path.join(toDir,`.rove-clone-probe-${process.pid}`);try{return await cloneOneFile(path.join(from,".git"),probe),!0}catch{return!1}finally{await fs.rm(probe,{force:!0})}})(),probeCache.set(key,known);return known};async function git2(cwd,args){let{stdout}=await run("git",[...args],{cwd,maxBuffer:67108864});return stdout.trim()}class CowCloneBackend{plain;id="cow-clone";capabilities=WORKSPACE_CAPABILITIES["cow-clone"];probe;cloneEntries;constructor(plain,deps={}){this.plain=plain;this.probe=deps.probe??volumeProbe,this.cloneEntries=deps.cloneEntries??cpClone}async materialize(spec){let parent=spec.forkFrom;if(!parent)return{...await this.plain.materialize(spec),backend:this.id};if(isRemoteRepoKey(spec.repo))throw new ForkUnsupportedError("a remote project's worktree cannot be cloned");let target=worktreePathFor(spec.repo,spec.slug),root=path.dirname(target);if(await fs.mkdir(root,{recursive:!0}),!await this.probe(parent,root))throw new ForkUnsupportedError(`${parent} and ${root} are not on one volume that can clone files (APFS, btrfs, XFS with reflink); the fork would have to copy the whole tree`);let head=await git2(parent,["rev-parse","HEAD"]);await git2(spec.repo,["worktree","add","--no-checkout","-b",spec.branch,target,head]);try{let entries=(await fs.readdir(parent)).filter((name)=>name!==".git").map((name)=>path.join(parent,name));await this.cloneEntries(entries,target),await this.carryIndex(parent,target)}catch(err){throw await this.discard(spec.repo,target,spec.branch),err}return{backend:this.id,path:target}}async carryIndex(parent,target){let indexOf=(dir)=>git2(dir,["rev-parse","--path-format=absolute","--git-path","index"]);try{await fs.copyFile(await indexOf(parent),await indexOf(target)),await git2(target,["update-index","-q","--refresh"])}catch{await git2(target,["reset","-q"])}}async discard(repo,target,branch){await git2(repo,["worktree","remove","--force",target]).catch(()=>{}),await fs.rm(target,{recursive:!0,force:!0}),await git2(repo,["worktree","prune"]).catch(()=>{}),await git2(repo,["branch","-D",branch]).catch(()=>{})}dispose(target,opts){return this.plain.dispose(target,opts)}}class GitWorktreeBackend{worktrees;id="git-worktree";capabilities=WORKSPACE_CAPABILITIES["git-worktree"];constructor(worktrees){this.worktrees=worktrees}async materialize(spec){let info=await this.worktrees.createForTask({repo:spec.repo,slug:spec.slug,branch:spec.branch,baseRef:spec.baseRef,onProgress:spec.onProgress});return{backend:this.id,path:info.path}}async dispose(target,opts){await this.worktrees.remove(target.path,{...opts,repo:target.repo,branch:target.branch})}}import{execFile as execFile2}from"child_process";import{createHash}from"crypto";import{promises as fs2,readFileSync}from"fs";import os from"os";import path2 from"path";import{promisify as promisify2}from"util";var LAYERFS_CONFIG_KEY="experimental.layerfs",STATE_FILE=".rove-layerfs.json",SANDBOX_USER="501:20",SANDBOX_HOME="/tmp/rove-home",KILL_TAGGED=`for p in /proc/[0-9]*; do tr '\\0' '\\n' < $p/environ 2>/dev/null | grep -qx "$1" && kill -KILL \${p#/proc/}; done; true`,KILL_UNDER='for p in /proc/[0-9]*; do case $(readlink $p/cwd) in "$1"|"$1"/*) kill -KILL ${p#/proc/};; esac; done; sleep 0.2',execRun=async(file,args)=>{try{let{stdout}=await promisify2(execFile2)(file,[...args],{maxBuffer:67108864});return stdout}catch(err){let e=err;throw Error((e.stderr?.trim()||e.stdout?.trim()||e.message).slice(0,2000))}};function parseLayerfsEnv(text){let env={};for(let line of text.split(`
|
|
3
3
|
`)){let m=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)=(.*)$/.exec(line);if(m)env[m[1]]=m[2].trim().replace(/^(["'])(.*)\1$/,"$2")}return env}class LayerfsBackend{id="layerfs";capabilities=WORKSPACE_CAPABILITIES.layerfs;run;configPath;platform;rootChecked=!1;constructor(deps={}){this.run=deps.run??execRun,this.configPath=deps.configPath??(()=>getPersistedString(LAYERFS_CONFIG_KEY)),this.platform=deps.platform??process.platform}async preflight(){this.env(),await this.requireRoot()}env(){if(this.platform!=="linux")throw unavailable(`it runs on Linux Runners only, not ${this.platform}`);let file=this.configPath();if(!file)throw unavailable(`set ${LAYERFS_CONFIG_KEY} in state.json to a LayerFS env file`);let env;try{env=parseLayerfsEnv(readFileSync(file,"utf8"))}catch(err){throw unavailable(`cannot read ${file}: ${err.message}`)}for(let key of["LAYERFS_CLI","LAYERFS_NODE","LAYERFS_HOME","LAYERFS_STORE_PATH","LAYERFS_IMAGE"])if(!env[key])throw unavailable(`${file} does not set ${key}`);return env}async requireRoot(){if(this.rootChecked)return;try{await this.run("sudo",["-n","true"])}catch{throw Error("LAYERFS_NEEDS_ROOT: LayerFS Store calls run as root, and `sudo -n` cannot (configure passwordless sudo for this user)")}this.rootChecked=!0}async lfs(project,...args){let env=this.env();await this.requireRoot();let pass=Object.entries(env).filter(([k])=>k!=="LAYERFS_CLI"&&k!=="LAYERFS_NODE").map(([k,v])=>`${k}=${v}`),out=await this.run("sudo",["-n","env",...pass,`LAYERFS_PROJECT=${project}`,env.LAYERFS_NODE,env.LAYERFS_CLI,...args]);return JSON.parse(out)}docker(...args){return this.run("docker",args)}inSandbox(s,dir,...argv){return this.docker("exec","-u",SANDBOX_USER,"-w",dir,"-e",`HOME=${SANDBOX_HOME}`,s.container,...argv)}async ensureProject(repo){let project=`rove-${createHash("sha1").update(repo).digest("hex").slice(0,12)}`;try{await this.lfs(project,"project","list_branches","--page-size","1")}catch{await this.lfs(project,"init",project,repo,"--timeout","1800000")}return project}async materialize(spec){if(spec.forkFrom||spec.path)throw unavailable("a layerfs task cannot be forked or borrow a directory");this.env();let dir=worktreePathFor(spec.repo,spec.slug),project=await this.ensureProject(spec.repo),branch=`${spec.slug}-${Date.now().toString(36)}`;await this.lfs(project,"branch","fork",branch);let{sandbox}=await this.lfs(project,"sandbox","create"),s={project,sandbox,ws:"",container:"",branch,gitBase:"",checkpoints:[]};try{s.container=await this.containerOf(project,sandbox),await this.mount(s,dir),await this.inSandbox(s,dir,"git","checkout","-q","-b",spec.branch,...spec.baseRef?[spec.baseRef]:[]),s.gitBase=(await this.inSandbox(s,dir,"git","rev-parse","HEAD")).trim();let reap=["docker","exec","-u",SANDBOX_USER,s.container,"sh","-c",KILL_TAGGED,"sh","ROVE_LAUNCH={launch}"];await fs2.writeFile(path2.join(dir,LAUNCH_PREFIX_FILE),JSON.stringify({prefix:this.launchPrefix(s,dir),reap})),await this.save(dir,s)}catch(err){throw await this.teardown(s,dir,!0).catch(()=>{}),err}return{backend:this.id,path:dir,ref:`${project}:${branch}`}}launchPrefix(s,dir){let env=["-e",`HOME=${SANDBOX_HOME}`,"-e","ROVE_LAUNCH={launch}","-e","TERM","-e","COLUMNS","-e","LINES"];return["docker","exec","-it","-u",SANDBOX_USER,"-w",dir,...env,s.container]}async containerOf(project,sandbox){let id=(await this.docker("ps","-q","--filter",`label=layerfs.project=${project}`,"--filter",`label=layerfs.sandbox=${sandbox}`)).trim();if(!id||id.includes(`
|
|
4
4
|
`))throw Error(`no single container for LayerFS sandbox ${project}/${sandbox}`);return id}async mount(s,dir){s.ws=(await this.lfs(s.project,"workspace","mount",s.sandbox,s.branch)).ws,await fs2.mkdir(dir,{recursive:!0}),await this.bind(s,dir)}async bind(s,dir){let mountPath=s.ws.slice(s.ws.indexOf(":")+1),script=`mkdir -p "$1" ${SANDBOX_HOME} && chown ${SANDBOX_USER} ${SANDBOX_HOME} && mount --bind "$2" "$1"`;await this.docker("exec","-u","0",s.container,"sh","-c",script,"sh",dir,mountPath)}async unbind(s,dir){try{await this.docker("exec","-u","0",s.container,"umount",dir)}catch(err){if(!/busy/i.test(err.message))throw err;throw Error(`WORKSPACE_BUSY: a process still runs in ${dir} inside the sandbox; close the task's terminals first`)}}async unmount(s,dir,discard){await this.unbind(s,dir);try{await this.lfs(s.project,"workspace","unmount",s.ws,...discard?["--discard"]:[])}catch(err){if(await this.bind(s,dir),!/"code":"Dirty"/.test(err.message))throw err;throw Error(`WORKSPACE_DIRTY: LayerFS has uncommitted changes in ${dir}; checkpoint first, or force`)}}async teardown(s,dir,discard){if(s.ws){if(s.container)await this.docker("exec","-u",SANDBOX_USER,s.container,"sh","-c",KILL_UNDER,"sh",dir);await this.unmount(s,dir,discard)}await this.lfs(s.project,"sandbox","close",s.sandbox),await fs2.rm(path2.join(dir,STATE_FILE),{force:!0}),await fs2.rm(path2.join(dir,LAUNCH_PREFIX_FILE),{force:!0}),await fs2.rmdir(dir).catch(()=>{})}async dispose(target,opts){let s=await this.load(target.path).catch(()=>{return});if(!s){await fs2.rm(path2.join(target.path,LAUNCH_PREFIX_FILE),{force:!0}),await fs2.rmdir(target.path).catch(()=>{});return}await this.teardown(s,target.path,opts.force===!0)}async dirtyPaths(dir){let s=await this.load(dir).catch(()=>{return});if(!s?.ws)return[];let{items}=await this.lfs(s.project,"sandbox","list_workspaces",s.sandbox);return items.find((w)=>`${s.sandbox}:${w.path}`===s.ws)?.changed?["(changes since the last checkpoint, inside the LayerFS sandbox)"]:[]}checkpoints={take:(dir,opts)=>this.take(dir,opts?.tabId),list:async(dir)=>(await this.load(dir)).checkpoints,rewind:async(dir,n)=>{let target=(await this.load(dir)).checkpoints.find((c)=>c.n===n);if(!target)throw Error(`CHECKPOINT_NOT_FOUND: checkpoint ${n} does not exist`);let undo=(await this.take(dir)).checkpoint,after=await this.load(dir),fork=`${after.branch.replace(/-r[0-9a-z]+$/,"")}-r${Date.now().toString(36)}`;return await this.lfs(after.project,"branch","fork",fork,target.commit),await this.unmount(after,dir,!0),after.branch=fork,await this.mount(after,dir),await this.save(dir,after),{target,undo,uncaptured:[]}}};async take(dir,tabId){let s=await this.load(dir),latest=s.checkpoints.at(-1),reply=await this.lfs(s.project,"workspace","commit",s.ws,"-m","rove checkpoint",...latest?[]:["--force"]);if(latest&&reply.kind==="UpToDate")return{created:!1,checkpoint:latest};let checkpoint={n:(latest?.n??0)+1,ref:`layerfs:${s.project}:${s.branch}`,commit:reply.head,tree:reply.commit?.root??reply.root??reply.head,at:new Date().toISOString(),...tabId?{tabId}:{}};return s.checkpoints.push(checkpoint),await this.save(dir,s),{created:!0,checkpoint,uncaptured:[]}}async exportBranch(target){let s=await this.load(target.path),inner=`/tmp/rove-export-${process.pid}.bundle`;await this.inSandbox(s,target.path,"git","bundle","create","-q",inner,target.branch,`^${s.gitBase}`);let local=path2.join(os.tmpdir(),`rove-layerfs-${process.pid}-${Date.now()}.bundle`);try{await this.docker("cp",`${s.container}:${inner}`,local),await this.run("git",["-C",target.repo,"fetch","-q",local,`${target.branch}:refs/heads/${target.branch}`]);let commit=(await this.run("git",["-C",target.repo,"rev-parse",target.branch])).trim();return{branch:target.branch,commit}}finally{await fs2.rm(local,{force:!0})}}async load(dir){return JSON.parse(await fs2.readFile(path2.join(dir,STATE_FILE),"utf8"))}save(dir,s){return fs2.writeFile(path2.join(dir,STATE_FILE),`${JSON.stringify(s,null,2)}
|
|
5
5
|
`)}}function unavailable(why){return Error(`LAYERFS_UNAVAILABLE: the layerfs workspace backend is unavailable: ${why}`)}class RemoteBackend{id="remote";capabilities=WORKSPACE_CAPABILITIES.remote;async materialize(){throw Error("a remote workspace is created by `rove api add --workspace-on <machine>`")}async dispose(target,opts){let ws=readRemoteWorkspace(target.path);if(ws){let gone=await forwardVerb(requireMachine(ws.machine),"delete",{"task-id":ws.taskId,wait:!0,...opts.force?{force:!0}:{}});if(!gone.ok&&gone.error.code!=="TASK_NOT_FOUND"&&!opts.force)throw Error(gone.error.message)}removeRemoteLink(target.path)}async dirtyPaths(){return[]}}class WorkspaceRegistry{backends=new Map;constructor(backends){for(let backend of backends)this.backends.set(backend.id,backend)}get(id){let backend=this.backends.get(id);if(!backend)throw Error(`workspace backend '${id}' is not available in this build`);return backend}}function createWorkspaceRegistry(worktrees,cowClone){let plain=new GitWorktreeBackend(worktrees);return new WorkspaceRegistry([plain,new BorrowedBackend,new CowCloneBackend(plain,cowClone),new LayerfsBackend,new RemoteBackend])}async function createOrForkTask(deps,input){if(input.workspace)await deps.workspaces.get(input.workspace.backend).preflight?.();let createRow=(row)=>createTaskRow(deps,row),{forkFrom}=input;return forkFrom?forkTaskRow({...deps,createRow},{...input,forkFrom}):createRow(input)}async function forkTaskRow(deps,input){let parent=deps.store.get(input.forkFrom);if(!parent)throw new TaskNotFoundError(input.forkFrom);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(!workspaceCapabilities(parent).ownsDirectory)throw new ForkUnsupportedError("a main or directory task has no Rove-created worktree to clone");if(isRemoteRepoKey(parent.repo))throw new ForkUnsupportedError("a remote project's worktree cannot be cloned");if(parent.extraRepos?.length)throw new ForkUnsupportedError("a multi-repo task cannot be forked: only its primary repo would be cloned");let parentPath=await deps.ensureWorktree(parent.id),baseRef=git(["rev-parse","HEAD"],{cwd:parentPath,readOnly:!0}).stdout.trim(),child=await deps.createRow({...input,repo:gitRepoOf(parent),title:input.title??`${parent.title} (fork)`,baseRef,workspace:{backend:"cow-clone",ref:String(parent.id)},...parent.cwdSubpath?{cwdSubpath:parent.cwdSubpath}:{}});if(parent.gitRepo)await deps.store.update(child.id,{repo:parent.repo,gitRepo:parent.gitRepo});try{await deps.cloneInto(child,parentPath)}catch(err){throw await discard(deps,child).catch((cleanup)=>console.error(`[rove] fork rollback failed for ${child.id}:`,cleanup)),await deps.store.remove(child.id),err}return deps.store.get(child.id)??child}async function discard(deps,child){let row=deps.store.get(child.id);if(!row?.worktreePath)return;await deps.workspaces.get(workspaceBackendId(row)).dispose({path:row.worktreePath,repo:gitRepoOf(row),branch:row.branch},{force:!0,deleteBranch:!0})}function baseRepoCtx(repo,deps){let basePath=deps.remoteBasePath(repo);return{exec:deps.execForRepo(repo),dir:basePath??repo}}async function landGit(exec,dir,args,opts){let r=await exec.run(["git",...args],{cwd:dir,env:opts?.readOnly?READ_ONLY_GIT_ENV:void 0});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}async function isDirty(exec,dir){return isDirtyOutput((await landGit(exec,dir,["status","--porcelain"],{readOnly:!0})).stdout)}async function landPreflight(task,deps=defaultExecDeps){let refuse=(pf,refusal)=>{let refused={...pf,refusal};return{...refused,message:landRefusalError(task,refused).message}},branch=task.branch.trim();if(!branch)throw Error(`landPreflight: task ${task.id} has no branch to land (never materialised)`);let{exec,dir}=baseRepoCtx(gitRepoOf(task),deps),headOut=await landGit(exec,dir,["symbolic-ref","--short","HEAD"],{readOnly:!0}),landedOn=headOut.stdout.trim();if(headOut.exitCode!==0||!landedOn){let headCommit=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0}),detached=headCommit.exitCode===0&&headCommit.stdout.trim().length>0;return refuse({branch,landedOn:"",baseDir:dir},detached?"DETACHED_HEAD":"UNREADABLE_BASE")}if(landedOn===branch)return refuse({branch,landedOn,baseDir:dir},"SAME_BRANCH");let baseDirty=await isDirty(exec,dir),aheadOut=await landGit(exec,dir,["rev-list","--count",`${landedOn}..${branch}`],{readOnly:!0});if(aheadOut.exitCode!==0){let baseHead=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0});if(baseHead.exitCode!==0||!baseHead.stdout.trim())return refuse({branch,landedOn,baseDirty,baseDir:dir},"UNBORN_BASE");return refuse({branch,landedOn,baseDirty,baseDir:dir},baseDirty?"MAIN_CHECKOUT_DIRTY":"MISSING_REF")}let parsed=Number.parseInt(aheadOut.stdout.trim(),10),base={branch,landedOn,baseDirty,baseDir:dir,...Number.isFinite(parsed)?{ahead:parsed}:{}};if(baseDirty)return refuse(base,"MAIN_CHECKOUT_DIRTY");if(base.ahead!==0)return base;let worktreePath=task.worktreePath.trim();if(worktreePath){let manager=new GitWorktreeManager(deps),dirty=!1;try{dirty=await manager.isDirty(worktreePath)}catch{dirty=!1}if(dirty){let wtExec=deps.execForPath(worktreePath),files=parseDirtyPaths((await landGit(wtExec,worktreePath,["status","--porcelain"],{readOnly:!0})).stdout);return refuse({...base,dirtyFiles:files},"EMPTY_BRANCH_DIRTY_WORKTREE")}}return refuse(base,"EMPTY_BRANCH")}function landRefusalError(task,pf){switch(pf.refusal){case"DETACHED_HEAD":return Error(`landTask: base checkout at ${pf.baseDir} is in detached-HEAD state; check out a branch first`);case"UNREADABLE_BASE":return Error(`landTask: could not read HEAD of the base checkout at ${pf.baseDir} \u2014 is it still a git repo?`);case"UNBORN_BASE":return Error(`landTask: base checkout at ${pf.baseDir} is on '${pf.landedOn}' but has no commits yet, so there is nothing to merge '${pf.branch}' into; make the first commit there (or \`git merge --ff-only ${pf.branch}\`) and land again`);case"SAME_BRANCH":return Error(`landTask: base checkout is already on '${pf.branch}' \u2014 nothing to land onto`);case"MAIN_CHECKOUT_DIRTY":return new MainCheckoutDirtyError(gitRepoOf(task),pf.baseDir);case"MISSING_REF":return new MissingRefError(pf.branch,pf.landedOn,pf.baseDir);case"EMPTY_BRANCH_DIRTY_WORKTREE":return new EmptyBranchDirtyWorktreeError(pf.branch,pf.landedOn,task.worktreePath.trim(),[...pf.dirtyFiles??[]]);case"EMPTY_BRANCH":return new EmptyBranchError(pf.branch,pf.landedOn)}}function assertOwnsBranch(task){if(workspaceCapabilities(task).ownsBranch)return;throw Error(task.kind==="main"?"landTask: a main task has no branch to land":"landTask: a directory task has no Rove-managed branch to land")}async function landTaskWithCleanup(task,opts,deps){assertOwnsBranch(task);let result=await landTask(task,{strategy:opts.strategy});return finishLanded(task,result,opts,deps)}async function finishLanded(task,result,opts,deps){let worktree=opts.removeWorktree===!1?void 0:await removeLandedWorktree(task,opts.callerCwd,deps),branchAnchor=null,branchKept,worktreeGone=!task.worktreePath.trim()||worktree?.removed===!0;if(opts.deleteBranch&&!worktreeGone)branchKept={reason:worktree?.reason??`worktree ${task.worktreePath} was kept, and still has the branch checked out`};else if(opts.deleteBranch){let outcome=await deps.worktrees.deleteBranch(gitRepoOf(task),result.branch,{force:!0,onAnchor:(record)=>{branchAnchor=record}});if(!outcome.deleted)branchKept={reason:outcome.reason}}return{...result,...worktree?{worktree}:{},...branchAnchor?{branchAnchor}:{},...branchKept?{branchKept}:{}}}async function removeLandedWorktree(task,callerCwd,deps){let worktreePath=task.worktreePath.trim();if(!worktreePath)return{removed:!1,reason:"task has no worktree on disk (never materialised)"};let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(gitRepoOf(task))))return{removed:!1,reason:"refusing to remove the base checkout"};if(deps.sharesWorktree?.(task))return{removed:!1,reason:`kept ${worktreePath}: other tasks still run in this directory`};if(callerCwd){if(pathWithin(wt,canonicalize(callerCwd))!==null)return{removed:!1,reason:`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`}}if(deps.tearDownSession)try{await deps.tearDownSession(task.id)}catch{}let residue;try{await deps.worktrees.remove(worktreePath,{onResidue:(r)=>{residue=r}})}catch(err){return{removed:!1,reason:errText(err)}}try{await deps.clearWorktreePath(task.id)}catch(err){return{removed:!0,reason:`worktree removed, but clearing the task's worktree path failed: ${errText(err)}`,...residue?{residue}:{}}}return{removed:!0,...residue?{residue}:{}}}function errText(err){return err instanceof Error?err.message:String(err)}async function conflictedFiles(exec,dir){return(await landGit(exec,dir,["diff","--name-only","--diff-filter=U"],{readOnly:!0})).stdout.split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{connectIfRunning}from"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-vfrxywtx.js";import"./chunk-pn5ygqn6.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";async function openLocalOrchestrator(){let{TaskIndexStore}=await import("./chunk-44msqtz9.js"),{GitWorktreeManager}=await import("./chunk-
|
|
2
|
+
import{connectIfRunning}from"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-vfrxywtx.js";import"./chunk-pn5ygqn6.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";async function openLocalOrchestrator(){let{TaskIndexStore}=await import("./chunk-44msqtz9.js"),{GitWorktreeManager}=await import("./chunk-14frenn5.js"),{Orchestrator}=await import("./chunk-j48vrc9y.js"),store=new TaskIndexStore;return await store.load(),new Orchestrator({store,worktrees:new GitWorktreeManager})}async function withDaemonOrLocal(bridge){let client=await connectIfRunning();if(client)try{return await bridge.daemon(client)}finally{client.close()}let orch=await openLocalOrchestrator();return bridge.local(orch)}export{withDaemonOrLocal,openLocalOrchestrator};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{expandTilde}from"./chunk-1feav1w3.js";import{pathSyntax}from"./chunk-pn5ygqn6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{statSync}from"fs";import{resolve}from"path";function isPathLikeArg(arg){return arg==="."||arg===".."||arg.startsWith("./")||arg.startsWith("../")||arg.startsWith(".\\")||arg.startsWith("..\\")||pathSyntax(arg).isAbsolute(arg)||arg.startsWith("/")||arg==="~"||arg.startsWith("~/")||arg.startsWith("~\\")}async function projectRootFor(dir){let{isGitRepo,resolveRepoRoot}=await import("./chunk-ktpdkw5c.js"),{projectRejection}=await import("./chunk-c02bw6xt.js"),top=resolveRepoRoot(dir);if(top!==dir)return null;return projectRejection(top,isGitRepo,"explicit")?null:top}async function runOpenDirectory(arg){let dir=resolve(process.cwd(),expandTilde(arg)),isDir=!1;try{isDir=statSync(dir).isDirectory()}catch{isDir=!1}if(!isDir)process.stderr.write(`${ROVE_PRODUCT_NAME}: "${arg}" is not a directory (resolved to ${dir}).
|
|
3
|
-
`),process.exit(1);let projectRoot=await projectRootFor(dir),{withDaemonOrLocal}=await import("./chunk-
|
|
3
|
+
`),process.exit(1);let projectRoot=await projectRootFor(dir),{withDaemonOrLocal}=await import("./chunk-rzm12tp3.js");await withDaemonOrLocal({daemon:async(client)=>{let taskId;if(projectRoot)taskId=(await client.request("task.ensureMain",{repo:projectRoot})).task.id;else taskId=(await client.request("task.openDir",{dir})).taskId;await client.request("task.setActive",{taskId})},local:async(orch)=>{let task=projectRoot?await orch.ensureMainTask(projectRoot):await orch.openDirectoryTask({dir}),{writeLastActiveTaskId}=await import("./chunk-gsqphkca.js");writeLastActiveTaskId(String(task.id))}});let{publishRoveTerminalTitle}=await import("./chunk-g8wrdp7n.js");publishRoveTerminalTitle();let{launchTui}=await import("./chunk-sh0rgjjq.js");await launchTui()}
|
|
4
4
|
export{isPathLikeArg,runOpenDirectory};
|
package/dist/cli/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{isPathLikeArg}from"./chunk-
|
|
4
|
-
`)}var bridge=()=>import("./chunk-
|
|
3
|
+
import{isPathLikeArg}from"./chunk-tjgf18y5.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION}from"./chunk-msk54e9v.js";import{switchFlag}from"./chunk-zsfyj36g.js";import{expandTilde}from"./chunk-1feav1w3.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{rejectionReason}from"./chunk-mg1cas61.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{resolve}from"path";var DYNAMIC_COMMANDS=new Map([["completions",async(args)=>{let{runCompletionsSubcommand}=await import("./chunk-da57rgmq.js");await runCompletionsSubcommand(args)}],["export",async(args)=>{let{runExportSubcommand}=await import("./chunk-m45b6d19.js");await runExportSubcommand(args)}],["repo",async(args)=>{let{runRepoSubcommand}=await import("./chunk-pm46jy62.js");await runRepoSubcommand(args)}],["api",async(args)=>{let{runApiSubcommand}=await import("./chunk-4x3xyvq2.js");await runApiSubcommand(args)}],["update",async(args)=>{let{runUpdateSubcommand}=await import("./chunk-48g3xxyy.js");await runUpdateSubcommand(args)}],["theme",async(args)=>{let{runThemeSubcommand}=await import("./chunk-t6nvh0y5.js");await runThemeSubcommand(args)}],["feedback",async(args)=>{let{runFeedbackSubcommand}=await import("./chunk-qx3y6rmt.js");await runFeedbackSubcommand(args)}],["daemon",async(args)=>{let{runDaemonSubcommand}=await import("./chunk-jpxgdytq.js");await runDaemonSubcommand(args)}],["machine",async(args)=>{let{runMachineSubcommand}=await import("./chunk-4wyvr74k.js");await runMachineSubcommand(args)}],["weixin",async(args)=>{let{runChannelCli}=await import("./chunk-mcpd8sw5.js");await runChannelCli("weixin",args)}],["doctor",async(args)=>{let{runDoctorSubcommand}=await import("./chunk-04dwwfgz.js");await runDoctorSubcommand(args)}],["config",async(args)=>{let{runConfigSubcommand}=await import("./chunk-f3j2vxw9.js");await runConfigSubcommand(args)}],["reset",async(args)=>{let{runResetSubcommand}=await import("./chunk-qryc8ptt.js");await runResetSubcommand(args)}],["pty-host",async(args)=>{let{runPtyHostSubcommand}=await import("./chunk-hfs4a1t8.js");await runPtyHostSubcommand(args)}],["skill",async(args)=>{let{runSkillSubcommand}=await import("./chunk-nrcpbhwd.js");await runSkillSubcommand(args)}],["plugin",async(args)=>{let{runPluginSubcommand}=await import("./chunk-g1kzwt9c.js");await runPluginSubcommand(args)}],["remote-workspace",async(args)=>{let{runRemoteWorkspaceSubcommand}=await import("./chunk-mwghc9fm.js");await runRemoteWorkspaceSubcommand(args)}],["hook",async(args)=>{let{runHookSubcommand}=await import("./chunk-9k8f281a.js");await runHookSubcommand(args)}]]);function topLevelUsage(cliName=ROVE_PRODUCT_NAME){return[`${cliName} ${CURRENT_VERSION}`,"",`Usage: ${cliName} [command] [options]`,"","Run with no command to launch PureTUI.",`Run \`${cliName} .\` (or \`${cliName} <path>\`) to open a directory as a standalone task.`,"","Commands:"," completions <shell> Generate shell completion script (bash/zsh/fish)"," add [path] Save a repo path for the new-task picker"," remove [path] Forget a saved project (inverse of add; non-destructive)"," adopt [glob] Import existing git worktrees as tasks"," export [--csv|--json] Print the task list (json/csv/table; daemon-free)"," repo <verb> Per-repo init script + first prompt (show|set|unset)",` api <verb> Scriptable RPC surface for agents (see \`${cliName} api --help\`)`," daemon <verb> Manage the daemon (start|stop|status|restart)"," machine <verb> Other computers running Rove (add|doctor|remove|list)"," weixin <verb> Talk to Rove from WeChat (login|logout|status|allow|deny|send|agent)"," doctor [--report|--fix] Diagnose daemon/PTY/engines/git; --fix walks the remedies",` config [--path] Open ${cliName}'s config file (state.json) in your editor`," reset [--hard] Stop runtimes; optionally wipe task/UI state"," theme <verb> Manage user themes (list|add|remove)",` skill <verb> Install the ${cliName} agent skill (install|status|command|print)`," plugin <verb> Install and run plugins (install|link|list|action|\u2026)"," feedback File a GitHub issue on the Rove repo",` update [version|channel|list] Self-update ${cliName}, switch channel, or list versions`,"","Options:"," -v, --version Print version"," -h, --help Print this help"," --skill Print the agent skill file and exit"," --web [bridge flags] Serve the browser client on 127.0.0.1 and print its link"].join(`
|
|
4
|
+
`)}var bridge=()=>import("./chunk-rzm12tp3.js"),CLI_NAME=ROVE_PRODUCT_NAME,ADD_USAGE=[`Usage: ${CLI_NAME} add [path]`,` ${CLI_NAME} add --remote --host <host> --user <user> --path <basePath> [--port N] [--key [path] | --password]`,"","Save a repo for the new-task picker. With --remote, register an SSH-backed","project whose worktrees live on <host>; engine launch over SSH is pending.",""].join(`
|
|
5
5
|
`);async function runAddSubcommand(rest){let arg=rest[0];if(arg==="--help"||arg==="-h"||arg==="help"){process.stdout.write(ADD_USAGE);return}if(arg==="--remote"){let{runAddRemote}=await import("./chunk-r4gspwsq.js");await runAddRemote(rest.slice(1));return}if(arg?.startsWith("-"))process.stderr.write(`${CLI_NAME} add: unknown flag "${arg}"
|
|
6
6
|
|
|
7
7
|
${ADD_USAGE}`),process.exit(2);let target=resolve(process.cwd(),expandTilde(arg&&arg.length>0?arg:".")),{addSavedRepo}=await import("./chunk-ktpdkw5c.js"),result=addSavedRepo(target);if(result.rejected)process.stderr.write(`${CLI_NAME} add: "${arg&&arg.length>0?arg:"."}" cannot be a project \u2014 ${rejectionReason(result.rejected)} (resolved to ${result.path}).
|
|
@@ -23,4 +23,4 @@ ${ADOPT_USAGE}
|
|
|
23
23
|
pass a path glob to adopt, e.g. ${CLI_NAME} adopt '${repo}/*' --yes`);return}let matched=worktrees.filter(isMatch);if(matched.length===0){console.log(`
|
|
24
24
|
no worktrees match glob ${JSON.stringify(glob)}`);return}if(!yes){console.log(`
|
|
25
25
|
${matched.length} worktree(s) match \u2014 re-run with --yes to adopt them`);return}await adoptWorktreesInto(orch,repo,matched,vendor),console.log(`done \u2014 adopted ${matched.length} worktree(s)`)}function printTopLevelUsage(out){out.write(`${topLevelUsage()}
|
|
26
|
-
`)}var COMMANDS=new Map([["add",runAddSubcommand],["remove",runRemoveSubcommand],["adopt",runAdoptSubcommand],...DYNAMIC_COMMANDS]);async function main(){let[,,...rawArgs]=process.argv,[subcommand,...rest]=rawArgs;if(subcommand==="--version"||subcommand==="-v"||subcommand==="version"){let{CURRENT_VERSION:CURRENT_VERSION2}=await import("./chunk-4nak41q0.js");console.log(`${CLI_NAME} ${CURRENT_VERSION2}`);return}if(subcommand==="--help"||subcommand==="-h"||subcommand==="help"){printTopLevelUsage(process.stdout);return}if(subcommand==="--skill"){let{runSkillSubcommand}=await import("./chunk-nrcpbhwd.js");await runSkillSubcommand(["print"]);return}if(subcommand==="--web"){let{runWebSubcommand}=await import("./chunk-7k6b6pj9.js");await runWebSubcommand(rest);return}let handler=subcommand!==void 0?COMMANDS.get(subcommand):void 0;if(handler){await handler(rest);return}if(subcommand!==void 0&&isPathLikeArg(subcommand)){let{runOpenDirectory}=await import("./chunk-
|
|
26
|
+
`)}var COMMANDS=new Map([["add",runAddSubcommand],["remove",runRemoveSubcommand],["adopt",runAdoptSubcommand],...DYNAMIC_COMMANDS]);async function main(){let[,,...rawArgs]=process.argv,[subcommand,...rest]=rawArgs;if(subcommand==="--version"||subcommand==="-v"||subcommand==="version"){let{CURRENT_VERSION:CURRENT_VERSION2}=await import("./chunk-4nak41q0.js");console.log(`${CLI_NAME} ${CURRENT_VERSION2}`);return}if(subcommand==="--help"||subcommand==="-h"||subcommand==="help"){printTopLevelUsage(process.stdout);return}if(subcommand==="--skill"){let{runSkillSubcommand}=await import("./chunk-nrcpbhwd.js");await runSkillSubcommand(["print"]);return}if(subcommand==="--web"){let{runWebSubcommand}=await import("./chunk-7k6b6pj9.js");await runWebSubcommand(rest);return}let handler=subcommand!==void 0?COMMANDS.get(subcommand):void 0;if(handler){await handler(rest);return}if(subcommand!==void 0&&isPathLikeArg(subcommand)){let{runOpenDirectory}=await import("./chunk-h80pb6sb.js");await runOpenDirectory(subcommand);return}if(subcommand!==void 0)console.error(`${CLI_NAME}: unknown command '${subcommand}'`),printTopLevelUsage(process.stderr),process.exit(2);let{publishRoveTerminalTitle}=await import("./chunk-g8wrdp7n.js");publishRoveTerminalTitle();let{launchTui}=await import("./chunk-sh0rgjjq.js");await launchTui()}var cliDone=main().catch(async(err)=>{let{formatCliFailure}=await import("./chunk-3n1d0q9b.js");console.error(formatCliFailure(err,{cliName:CLI_NAME,argv:process.argv,cwd:process.cwd(),env:process.env})),process.exit(1)});export{cliDone};
|