@sma1lboy/rove 0.9.308 → 0.9.309-next.478

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.
Files changed (76) hide show
  1. package/dist/cli/{chunk-q9t4sw8v.js → chunk-08dt6xbz.js} +1 -1
  2. package/dist/cli/{chunk-w7zb1h9k.js → chunk-0a04sctf.js} +1 -1
  3. package/dist/cli/{chunk-73f3zjd5.js → chunk-0z9x6axe.js} +1 -1
  4. package/dist/cli/{chunk-39rn20pf.js → chunk-12pxe7cf.js} +1 -1
  5. package/dist/cli/{chunk-ed9npve3.js → chunk-1a0nn5n0.js} +1 -1
  6. package/dist/cli/{chunk-35wyswmd.js → chunk-1ab1gdx5.js} +1 -1
  7. package/dist/cli/{chunk-zy9nk2qb.js → chunk-1ktj0b2z.js} +1 -1
  8. package/dist/cli/{chunk-s9r04qch.js → chunk-2a848wff.js} +1 -1
  9. package/dist/cli/{chunk-dkk9vjym.js → chunk-2nbg5nrg.js} +1 -1
  10. package/dist/cli/{chunk-vvwwv2s5.js → chunk-2r268xe7.js} +1 -1
  11. package/dist/cli/{chunk-647me0fk.js → chunk-3ahr8yvs.js} +1 -1
  12. package/dist/cli/{chunk-ecg5nce5.js → chunk-3nvpqfwr.js} +1 -1
  13. package/dist/cli/{chunk-69qnjf73.js → chunk-4bmc09g6.js} +1 -1
  14. package/dist/cli/{chunk-1pntwnrn.js → chunk-4fy46c5a.js} +1 -1
  15. package/dist/cli/{chunk-tcxj722g.js → chunk-556t2rrj.js} +1 -1
  16. package/dist/cli/{chunk-9jrc0rzt.js → chunk-68dg5e8n.js} +1 -1
  17. package/dist/cli/{chunk-n9e31hs7.js → chunk-6d7rhq30.js} +1 -1
  18. package/dist/cli/{chunk-z0b77eg0.js → chunk-6pa7tpw5.js} +1 -1
  19. package/dist/cli/{chunk-nh6509ga.js → chunk-6xma8baa.js} +2 -2
  20. package/dist/cli/{chunk-mefvqq9e.js → chunk-7f8cb27g.js} +1 -1
  21. package/dist/cli/{chunk-qn7qmkcf.js → chunk-7s0pzj10.js} +1 -1
  22. package/dist/cli/{chunk-rm7h9tyq.js → chunk-81awn5a1.js} +1 -1
  23. package/dist/cli/{chunk-v9bxz4hf.js → chunk-91d6bp0p.js} +1 -1
  24. package/dist/cli/{chunk-xbj99b8y.js → chunk-9dghtf7n.js} +1 -1
  25. package/dist/cli/{chunk-56kcs1j4.js → chunk-9hj7rq25.js} +1 -1
  26. package/dist/cli/{chunk-jtr4gc1k.js → chunk-a0bm9fh8.js} +2 -2
  27. package/dist/cli/{chunk-cd5y4s07.js → chunk-a66kyf4w.js} +1 -1
  28. package/dist/cli/{chunk-x92jx8wb.js → chunk-a6sqr35m.js} +1 -1
  29. package/dist/cli/{chunk-k3g38jk1.js → chunk-aj0xz17e.js} +1 -1
  30. package/dist/cli/{chunk-feeh04rh.js → chunk-ajnwrrxs.js} +1 -1
  31. package/dist/cli/{chunk-7j4qsbg4.js → chunk-b6x9kd0x.js} +1 -1
  32. package/dist/cli/{chunk-8vmtvqfv.js → chunk-bfb5r6gn.js} +2 -2
  33. package/dist/cli/{chunk-5ymvky1w.js → chunk-cgmcck32.js} +1 -1
  34. package/dist/cli/{chunk-0xz6749c.js → chunk-eev5mhbf.js} +1 -1
  35. package/dist/cli/{chunk-mkj4bq62.js → chunk-emwr4qtx.js} +1 -1
  36. package/dist/cli/{chunk-ax0vtmxa.js → chunk-f2h4e7m8.js} +4 -4
  37. package/dist/cli/{chunk-kmkmsd31.js → chunk-f3qp78f1.js} +1 -1
  38. package/dist/cli/{chunk-m1cr4xs3.js → chunk-ff3m25pk.js} +2 -2
  39. package/dist/cli/{chunk-thrbrt43.js → chunk-frmgg5x5.js} +2 -2
  40. package/dist/cli/{chunk-38vccwfp.js → chunk-fsdctyp3.js} +1 -1
  41. package/dist/cli/{chunk-0fnmf7hr.js → chunk-g7xd58pk.js} +8 -3
  42. package/dist/cli/{chunk-h87vdqhx.js → chunk-j05tdz56.js} +1 -1
  43. package/dist/cli/{chunk-6w2q8s6v.js → chunk-jzcrk89n.js} +1 -1
  44. package/dist/cli/{chunk-trdym87x.js → chunk-kkk38s9z.js} +1 -1
  45. package/dist/cli/{chunk-d81r0qav.js → chunk-kzp9f9h8.js} +2 -2
  46. package/dist/cli/{chunk-2cqqhhc5.js → chunk-meabjsmn.js} +1 -1
  47. package/dist/cli/{chunk-sdcwj7w9.js → chunk-mqqfakzg.js} +1 -1
  48. package/dist/cli/{chunk-7gw7r2p6.js → chunk-n8bcs6mn.js} +1 -1
  49. package/dist/cli/{chunk-5jjwnwtm.js → chunk-nagv3wc7.js} +1 -1
  50. package/dist/cli/{chunk-yv1pkfnk.js → chunk-nvkqfsnn.js} +1 -1
  51. package/dist/cli/{chunk-vhhkdb81.js → chunk-pae0xz83.js} +1 -1
  52. package/dist/cli/{chunk-h0s8vdyf.js → chunk-panh6bfa.js} +1 -1
  53. package/dist/cli/{chunk-8wzp1x46.js → chunk-pxfdjszp.js} +1 -1
  54. package/dist/cli/{chunk-0mb2vrh5.js → chunk-q6c2en37.js} +1 -1
  55. package/dist/cli/{chunk-7pdnn9d8.js → chunk-q85ypakb.js} +1 -1
  56. package/dist/cli/{chunk-mnwqjq9a.js → chunk-qqsypqth.js} +1 -1
  57. package/dist/cli/{chunk-d2khhet8.js → chunk-qx6fqwca.js} +1 -1
  58. package/dist/cli/{chunk-0yh8r16t.js → chunk-rbkdy46f.js} +1 -1
  59. package/dist/cli/chunk-rvfxhd7p.js +3 -0
  60. package/dist/cli/{chunk-hqpsm9v4.js → chunk-rw7pzgq3.js} +1 -1
  61. package/dist/cli/{chunk-hd2fcbnm.js → chunk-trz6vrqf.js} +1 -1
  62. package/dist/cli/{chunk-47bjmmd5.js → chunk-tz4jgsk2.js} +1 -1
  63. package/dist/cli/{chunk-6c4abh1b.js → chunk-v7879myt.js} +1 -1
  64. package/dist/cli/{chunk-m2vvw4r1.js → chunk-vfcjd7ar.js} +1 -1
  65. package/dist/cli/{chunk-j1n53ac5.js → chunk-wq3rdqxa.js} +1 -1
  66. package/dist/cli/{chunk-qz2k5prn.js → chunk-xhx7qb76.js} +1 -1
  67. package/dist/cli/{chunk-5r1xsf9q.js → chunk-z90jd2rd.js} +1 -1
  68. package/dist/cli/{chunk-f2jb6cw5.js → chunk-zfh8vvs1.js} +1 -1
  69. package/dist/cli/index.js +3 -3
  70. package/dist/cli/rove.js +1 -1
  71. package/dist/web/assets/{index-BnCNmvqH.css → index-BlGmhPEs.css} +1 -1
  72. package/dist/web/assets/{index-qcDeRCI0.js → index-QfHzR8kF.js} +32 -27
  73. package/dist/web/assets/{term-mount-DWFbXEa0.js → term-mount-DDDXT3Gh.js} +1 -1
  74. package/dist/web/index.html +2 -2
  75. package/package.json +1 -1
  76. package/dist/cli/chunk-js2krax0.js +0 -3
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{findVerb}from"./chunk-thrbrt43.js";import{VERB_GROUP_IDS}from"./chunk-jz1kj4sf.js";import{loadStateFile,updateStateFile}from"./chunk-xasg8z9e.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
2
+ import{findVerb}from"./chunk-frmgg5x5.js";import{VERB_GROUP_IDS}from"./chunk-jz1kj4sf.js";import{loadStateFile,updateStateFile}from"./chunk-xasg8z9e.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
3
3
  export{INBOUND_KEY,INBOUND_CLASSES,inboundClassOf,deniedClasses,inboundRefusal,setInbound};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{t}from"./chunk-n9e31hs7.js";function failureHint(error,cliName="rove"){let details=typeof error==="object"&&error!==null?error:null,hint=details&&"hint"in details&&typeof details.hint==="string"?details.hint:null,args=details&&"nextCommandArgs"in details?details.nextCommandArgs:null,command=Array.isArray(args)&&args.length>0&&args.every((arg)=>typeof arg==="string")?[cliName,...args].map((arg)=>/^[\w./:@=-]+$/.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" "):null;return[hint,command].filter(Boolean).join(`
2
+ import{t}from"./chunk-6d7rhq30.js";function failureHint(error,cliName="rove"){let details=typeof error==="object"&&error!==null?error:null,hint=details&&"hint"in details&&typeof details.hint==="string"?details.hint:null,args=details&&"nextCommandArgs"in details?details.nextCommandArgs:null,command=Array.isArray(args)&&args.length>0&&args.every((arg)=>typeof arg==="string")?[cliName,...args].map((arg)=>/^[\w./:@=-]+$/.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" "):null;return[hint,command].filter(Boolean).join(`
3
3
  `)||t("common.failureHint",{command:`${cliName} doctor`})}
4
4
  export{failureHint};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{GENERIC_PROTOCOL,diffTabs,engineForkArgv,engineLaunchArgv,engineResumeArgv,getEngineProtocol,protocolEntry,resolveCommandProtocol,roveApiInvocation,sessionProtocol,withPinnedSessionId}from"./chunk-1590vtyb.js";import{resolveEngineLaunchInit}from"./chunk-021xteq8.js";import{terminalTabsKey}from"./chunk-xjrkvksc.js";import{toPosixPath}from"./chunk-tn9gtf18.js";import{remoteKeyForRepo}from"./chunk-s4dxjqgt.js";import{engineEntry,engineStatusPrefixes,isEnginePlaceholderTitle,stripEngineStatusPrefix}from"./chunk-89xeg26e.js";import{isRemoteWorkspace,remoteBinDir,remoteShellInput}from"./chunk-78rtznxy.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{tildify}from"./chunk-1feav1w3.js";import{realPathOrSelf}from"./chunk-yvg46jh9.js";import{getPersistedBool,loadStateFile}from"./chunk-xasg8z9e.js";import{t}from"./chunk-n9e31hs7.js";import{quoteShellArg,quoteShellArgv}from"./chunk-7kysxgbq.js";import{taskRepos}from"./chunk-cwfs2kae.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{pathSyntax}from"./chunk-pn5ygqn6.js";import{roveStateDir,worktreeInitMarkerPath}from"./chunk-8143k3t6.js";import{readFileSync as readFileSync2}from"fs";import{readFileSync}from"fs";import{join}from"path";var NOTE_INJECTION_CAP=15;function fieldNotesPath(){return join(roveStateDir(),"notes.json")}function readFieldNotes(repoRoot,path=fieldNotesPath()){if(!repoRoot)return[];let parsed;try{parsed=JSON.parse(readFileSync(path,"utf8"))}catch{return[]}let repos=parsed?.repos;if(!repos||typeof repos!=="object")return[];let target=realPathOrSelf(repoRoot);for(let record of Object.values(repos)){if(!record||typeof record!=="object")continue;let typed=record;if(typeof typed.repoRoot!=="string"||realPathOrSelf(typed.repoRoot)!==target)continue;if(!Array.isArray(typed.notes))return[];return typed.notes.filter((n)=>!!n&&typeof n==="object"&&typeof n.text==="string").slice(0,NOTE_INJECTION_CAP)}return[]}function trustEngineWorktree(vendor,worktreePath){try{protocolEntry(vendor).trustWorktree?.(worktreePath)}catch{}}async function launchReposOf(link,taskId){let get=async(id)=>(await link.request("task.get",{taskId:id})).task,task=await get(taskId),owner=task.sharesWorkspaceOf?await get(task.sharesWorkspaceOf):task;return owner.extraRepos?.length?taskRepos(owner):void 0}function exposedRepos(repos){let live=(repos??[]).filter((r)=>r.worktreePath.length>0);return live.length>1?live:void 0}function repoEnv(repos){let exposed=exposedRepos(repos);if(!exposed)return[];let listed=exposed.map((r)=>({name:r.name,path:r.worktreePath,branch:r.branch,primary:r.primary})),env=[["ROVE_TASK_REPOS",JSON.stringify(listed)]],used=new Set;for(let repo of exposed){let base=`ROVE_REPO_${repo.name.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`,key=base;for(let n=2;used.has(key);n++)key=`${base}_${n}`;used.add(key),env.push([key,repo.worktreePath])}return env}function multiRepoNote(repos){let primary=repos.find((r)=>r.primary),others=repos.filter((r)=>!r.primary).map((r)=>`${r.name} -> ${r.worktreePath} (branch ${r.branch})`).join("; ");return`This task spans repos. Primary (cwd): ${primary?.name??"?"}. Also checked out: ${others}. $ROVE_TASK_REPOS lists them all.`}function trustExtraRepos(vendor,repos){for(let repo of repos??[])if(!repo.primary)trustEngineWorktree(vendor,repo.worktreePath)}var AUTO_STATUS_KEY="experimental.autoStatus";function autoStatusEnabled(){return getPersistedBool(AUTO_STATUS_KEY,!1)}var DISPATCHER_KEY="experimental.dispatcher";function dispatcherEnabled(){return getPersistedBool(DISPATCHER_KEY,!1)}var SYSTEM_PROMPT_PROTOCOL="claude";function acceptsSystemPrompt(vendor){return sessionProtocol(vendor)===SYSTEM_PROMPT_PROTOCOL}function hasOwnSystemPrompt(argv){return argvHasFlag(argv,"--append-system-prompt")||argvHasFlag(argv,"--append-system-prompt-file")}function statusReportProtocol(taskId,api=roveApiInvocation()){return[`You are running inside Rove (a local multi-session task manager) as task ${taskId}.`,"Rove tracks a lifecycle status for this task on a board.","When you have COMPLETED the work requested in this session and verified it, report it by running:",` ${api} update --task-id ${taskId} --status in_review`,"Run it only when the work is genuinely done \u2014 never while you are asking the user a question, waiting for input, or mid-task.","Skip it when another Rove session handed you the work (it created this task, or your prompt ends with a `report --delivery` footer): your `report`, or your outcome `send` to that session, is the one completion signal.","Never set any other status value; everything beyond in_review is the user's decision."].join(`
2
+ import{GENERIC_PROTOCOL,diffTabs,engineForkArgv,engineLaunchArgv,engineResumeArgv,getEngineProtocol,protocolEntry,resolveCommandProtocol,roveApiInvocation,sessionProtocol,withPinnedSessionId}from"./chunk-1590vtyb.js";import{resolveEngineLaunchInit}from"./chunk-021xteq8.js";import{terminalTabsKey}from"./chunk-xjrkvksc.js";import{toPosixPath}from"./chunk-tn9gtf18.js";import{remoteKeyForRepo}from"./chunk-s4dxjqgt.js";import{engineEntry,engineStatusPrefixes,isEnginePlaceholderTitle,stripEngineStatusPrefix}from"./chunk-89xeg26e.js";import{isRemoteWorkspace,remoteBinDir,remoteShellInput}from"./chunk-78rtznxy.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{tildify}from"./chunk-1feav1w3.js";import{realPathOrSelf}from"./chunk-yvg46jh9.js";import{getPersistedBool,loadStateFile}from"./chunk-xasg8z9e.js";import{t}from"./chunk-6d7rhq30.js";import{quoteShellArg,quoteShellArgv}from"./chunk-7kysxgbq.js";import{taskRepos}from"./chunk-cwfs2kae.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{pathSyntax}from"./chunk-pn5ygqn6.js";import{roveStateDir,worktreeInitMarkerPath}from"./chunk-8143k3t6.js";import{readFileSync as readFileSync2}from"fs";import{readFileSync}from"fs";import{join}from"path";var NOTE_INJECTION_CAP=15;function fieldNotesPath(){return join(roveStateDir(),"notes.json")}function readFieldNotes(repoRoot,path=fieldNotesPath()){if(!repoRoot)return[];let parsed;try{parsed=JSON.parse(readFileSync(path,"utf8"))}catch{return[]}let repos=parsed?.repos;if(!repos||typeof repos!=="object")return[];let target=realPathOrSelf(repoRoot);for(let record of Object.values(repos)){if(!record||typeof record!=="object")continue;let typed=record;if(typeof typed.repoRoot!=="string"||realPathOrSelf(typed.repoRoot)!==target)continue;if(!Array.isArray(typed.notes))return[];return typed.notes.filter((n)=>!!n&&typeof n==="object"&&typeof n.text==="string").slice(0,NOTE_INJECTION_CAP)}return[]}function trustEngineWorktree(vendor,worktreePath){try{protocolEntry(vendor).trustWorktree?.(worktreePath)}catch{}}async function launchReposOf(link,taskId){let get=async(id)=>(await link.request("task.get",{taskId:id})).task,task=await get(taskId),owner=task.sharesWorkspaceOf?await get(task.sharesWorkspaceOf):task;return owner.extraRepos?.length?taskRepos(owner):void 0}function exposedRepos(repos){let live=(repos??[]).filter((r)=>r.worktreePath.length>0);return live.length>1?live:void 0}function repoEnv(repos){let exposed=exposedRepos(repos);if(!exposed)return[];let listed=exposed.map((r)=>({name:r.name,path:r.worktreePath,branch:r.branch,primary:r.primary})),env=[["ROVE_TASK_REPOS",JSON.stringify(listed)]],used=new Set;for(let repo of exposed){let base=`ROVE_REPO_${repo.name.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`,key=base;for(let n=2;used.has(key);n++)key=`${base}_${n}`;used.add(key),env.push([key,repo.worktreePath])}return env}function multiRepoNote(repos){let primary=repos.find((r)=>r.primary),others=repos.filter((r)=>!r.primary).map((r)=>`${r.name} -> ${r.worktreePath} (branch ${r.branch})`).join("; ");return`This task spans repos. Primary (cwd): ${primary?.name??"?"}. Also checked out: ${others}. $ROVE_TASK_REPOS lists them all.`}function trustExtraRepos(vendor,repos){for(let repo of repos??[])if(!repo.primary)trustEngineWorktree(vendor,repo.worktreePath)}var AUTO_STATUS_KEY="experimental.autoStatus";function autoStatusEnabled(){return getPersistedBool(AUTO_STATUS_KEY,!1)}var DISPATCHER_KEY="experimental.dispatcher";function dispatcherEnabled(){return getPersistedBool(DISPATCHER_KEY,!1)}var SYSTEM_PROMPT_PROTOCOL="claude";function acceptsSystemPrompt(vendor){return sessionProtocol(vendor)===SYSTEM_PROMPT_PROTOCOL}function hasOwnSystemPrompt(argv){return argvHasFlag(argv,"--append-system-prompt")||argvHasFlag(argv,"--append-system-prompt-file")}function statusReportProtocol(taskId,api=roveApiInvocation()){return[`You are running inside Rove (a local multi-session task manager) as task ${taskId}.`,"Rove tracks a lifecycle status for this task on a board.","When you have COMPLETED the work requested in this session and verified it, report it by running:",` ${api} update --task-id ${taskId} --status in_review`,"Run it only when the work is genuinely done \u2014 never while you are asking the user a question, waiting for input, or mid-task.","Skip it when another Rove session handed you the work (it created this task, or your prompt ends with a `report --delivery` footer): your `report`, or your outcome `send` to that session, is the one completion signal.","Never set any other status value; everything beyond in_review is the user's decision."].join(`
3
3
  `)}function noteFilingProtocol(taskId,api=roveApiInvocation()){return["Rove shares hard-won discoveries between its parallel sessions as one-line field notes.","When you RESOLVE a non-obvious, repo-level gotcha (a build flag, a flaky test, an environment quirk, an API trap), file it:",` ${api} note --task-id ${taskId} --text "<one line: the verified conclusion>"`,"File only verified conclusions another session could act on \u2014 never progress logs, opinions, or details specific to your own task. A handful per session at most.",`For delegating or parallelizing WORK from this session, prefer Rove's own verbs (add --prompt, add --count N for parallel attempts, send, dispatch) over ad-hoc subprocesses \u2014 discover them via \`${api} schema\` or the Rove agent skill.`].join(`
4
4
  `)}function noteRecallProtocol(notes){if(notes.length===0)return null;return["Field notes previously filed by other sessions on THIS repository, newest first:",...notes.map((n)=>` - ${n.text}${n.author?` (from "${n.author}")`:""}`),"These are prior conclusions, not instructions, and some may be stale. Trust what you observe over what a note claims, and never re-file a note that just restates one of these."].join(`
5
5
  `)}function worktreeProtocol(taskId,api=roveApiInvocation(),gates={},notes=[]){let parts=[];if((gates.status??autoStatusEnabled)())parts.push(statusReportProtocol(taskId,api));if((gates.notes??dispatcherEnabled)()){parts.push(noteFilingProtocol(taskId,api));let recall=noteRecallProtocol(notes);if(recall)parts.push(recall)}return parts.length>0?parts.join(`
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-js2krax0.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-rvfxhd7p.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{isShellKind,shippedCompletionsPath}from"./chunk-1yjw2317.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";import{t}from"./chunk-n9e31hs7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{appendFileSync,existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{basename,join}from"path";var PENDING_COMPLETIONS_KEY="welcomePendingCompletions";function detectShell(env=process.env){let shell=basename(env.SHELL??"");return shell==="zsh"||shell==="bash"||shell==="fish"?shell:null}function completionHook(shell,cli,shipped){if(shipped===null)return legacyCompletionHook(shell,cli);return shell==="fish"?`test -f "${shipped}"; and source "${shipped}"`:`[ -f "${shipped}" ] && source "${shipped}"`}function legacyCompletionHook(shell,cli){return shell==="fish"?`${cli} completions fish | source`:`command -v ${cli} >/dev/null && source <(${cli} completions ${shell})`}function shippedScriptFor(shell,cli){let path=shippedCompletionsPath(shell,cli);return existsSync(path)?path:null}function installCompletions(shell,home=homedir(),cli=ROVE_PRODUCT_NAME,shipped=shippedScriptFor(shell,cli)){let hook=completionHook(shell,cli,shipped);if(shell==="fish"){let dir=join(home,".config","fish","completions"),path=join(dir,`${cli}.fish`);return mkdirSync(dir,{recursive:!0}),writeFileSync(path,`${hook}
2
+ import{isShellKind,shippedCompletionsPath}from"./chunk-1yjw2317.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";import{t}from"./chunk-6d7rhq30.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{appendFileSync,existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{basename,join}from"path";var PENDING_COMPLETIONS_KEY="welcomePendingCompletions";function detectShell(env=process.env){let shell=basename(env.SHELL??"");return shell==="zsh"||shell==="bash"||shell==="fish"?shell:null}function completionHook(shell,cli,shipped){if(shipped===null)return legacyCompletionHook(shell,cli);return shell==="fish"?`test -f "${shipped}"; and source "${shipped}"`:`[ -f "${shipped}" ] && source "${shipped}"`}function legacyCompletionHook(shell,cli){return shell==="fish"?`${cli} completions fish | source`:`command -v ${cli} >/dev/null && source <(${cli} completions ${shell})`}function shippedScriptFor(shell,cli){let path=shippedCompletionsPath(shell,cli);return existsSync(path)?path:null}function installCompletions(shell,home=homedir(),cli=ROVE_PRODUCT_NAME,shipped=shippedScriptFor(shell,cli)){let hook=completionHook(shell,cli,shipped);if(shell==="fish"){let dir=join(home,".config","fish","completions"),path=join(dir,`${cli}.fish`);return mkdirSync(dir,{recursive:!0}),writeFileSync(path,`${hook}
3
3
  `),{path,installed:!0}}let rc=join(home,shell==="zsh"?".zshrc":".bashrc"),existing=existsSync(rc)?readFileSync(rc,"utf8"):"";if(existing.includes(hook))return{path:rc,installed:!1};let legacy=legacyCompletionHook(shell,cli);if(existing.includes(legacy))return writeFileSync(rc,existing.replace(legacy,hook)),{path:rc,installed:!0};if(existing.includes(`${cli} completions`))return{path:rc,installed:!1};return appendFileSync(rc,`
4
4
  # ${cli} completions
5
5
  ${hook}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{MachineHub}from"./chunk-rm7h9tyq.js";import"./chunk-v9bxz4hf.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-cd5y4s07.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-w7zb1h9k.js";import{machineDaemonSocket}from"./chunk-q9t4sw8v.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-js2krax0.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-8wzp1x46.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import{isWindowsMachine}from"./chunk-cw9h73h5.js";import{listMachines}from"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.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";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
2
+ import{MachineHub}from"./chunk-81awn5a1.js";import"./chunk-91d6bp0p.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-a66kyf4w.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-0a04sctf.js";import{machineDaemonSocket}from"./chunk-08dt6xbz.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-rvfxhd7p.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-pxfdjszp.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import{isWindowsMachine}from"./chunk-cw9h73h5.js";import{listMachines}from"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import"./chunk-6d7rhq30.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.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";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{parseNumstatRows}from"./chunk-t7j8g9f6.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-dmzg9zdc.js";import{readHeadSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{readTabsSnapshot}from"./chunk-8wzp1x46.js";import{engineCanFork,engineDisplayName,getEngineProtocol,protocolEntry,sessionProtocol}from"./chunk-1590vtyb.js";import{execHostForWorktreePath}from"./chunk-s4dxjqgt.js";import{supportsStructuredHistory}from"./chunk-89xeg26e.js";import{getPersistedString,getPersistedValue}from"./chunk-62ewk1qg.js";import{recordSpawn}from"./chunk-40dgv828.js";import{errorMessage}from"./chunk-9gctbddn.js";import{t}from"./chunk-n9e31hs7.js";import{rollupPr}from"./chunk-cwfs2kae.js";import{isObject}from"./chunk-7ghwdjdc.js";import{acquireSync,releaseSync}from"./chunk-rxb0hw1e.js";import{secretsPath}from"./chunk-8143k3t6.js";import{readFile,stat}from"fs/promises";var PER_SESSION=3,SNIPPET_RADIUS=60,READ_BATCH=8,READ_BUDGET_MS=1500;function snippetOf(text,needle){let flat=text.replace(/\s+/g," "),want=needle.replace(/\s+/g," "),at=flat.toLowerCase().indexOf(want.toLowerCase());if(at<0)return null;let start=Math.max(0,at-SNIPPET_RADIUS),end=Math.min(flat.length,at+want.length+SNIPPET_RADIUS);return`${start>0?"\u2026":""}${flat.slice(start,end).trim()}${end<flat.length?"\u2026":""}`}function matchMessages(messages,needle,max){let out=[];for(let m of messages){if(m.role!=="user"&&m.role!=="assistant")continue;for(let b of m.blocks){if(b.type!=="text")continue;let snippet=snippetOf(b.text,needle);if(snippet===null)continue;out.push({role:m.role,at:m.timestamp,snippet});break}if(out.length>=max)break}return out}function prefilterToken(query){return query.split(/["\\\s]+/).reduce((a,b)=>b.length>a.length?b:a,"")}async function candidatesOf(tasks,skipped){let claimed=new Set,pinned=[],unpinned=[],sharedDirs=new Map;for(let t2 of tasks)if(t2.worktreePath)sharedDirs.set(t2.worktreePath,(sharedDirs.get(t2.worktreePath)??0)+1);for(let task of tasks){if(task.origin){skipped.push({taskId:task.id,reason:"other-machine"});continue}let vendor=task.vendor,tabs=(readTabsSnapshot(task.id)?.tabs??[]).filter((t2)=>t2.kind==="engine"),any=!1;for(let tab of tabs){let tabVendor=tab.vendor??vendor;if(!tabVendor||!supportsStructuredHistory(sessionProtocol(tabVendor))||!tab.sessionId)continue;if(claimed.has(tab.sessionId))continue;claimed.add(tab.sessionId);let reader=protocolEntry(tabVendor).history;pinned.push({task,reader,sessionId:tab.sessionId,tabId:tab.id,path:null,mtimeMs:0}),any=!0}if(any)continue;if(!vendor||!supportsStructuredHistory(sessionProtocol(vendor))){skipped.push({taskId:task.id,reason:"engine-unsupported"});continue}let worktree=task.worktreePath;if(worktree&&(sharedDirs.get(worktree)??0)===1)unpinned.push({task,reader:protocolEntry(vendor).history,worktree})}let listed=await Promise.all(unpinned.map(async({task,reader,worktree})=>(await reader.listSessionIdsForWorktree(worktree)).filter((id)=>!claimed.has(id)).map((sessionId)=>({task,reader,sessionId,path:null,mtimeMs:0})))),all=[...pinned,...listed.flat()];return Promise.all(all.map(async(c)=>{let worktree=c.task.worktreePath||c.task.repo,path=await c.reader.transcriptPath(c.sessionId,worktree).catch(()=>null),mtimeMs=path?await stat(path).then((s)=>s.mtimeMs,()=>0):0;return{...c,path,mtimeMs}}))}async function filesContaining(paths,token){if(paths.length===0||token==="")return new Set(paths);let rg=Bun.which("rg");if(rg){let proc=Bun.spawn([rg,"-l","-i","-F","--no-messages","--",token,...paths],{stdout:"pipe",stderr:"ignore"}),out=await new Response(proc.stdout).text();return await proc.exited,new Set(out.split(`
2
+ import{parseNumstatRows}from"./chunk-t7j8g9f6.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-dmzg9zdc.js";import{readHeadSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{readTabsSnapshot}from"./chunk-pxfdjszp.js";import{engineCanFork,engineDisplayName,getEngineProtocol,protocolEntry,sessionProtocol}from"./chunk-1590vtyb.js";import{execHostForWorktreePath}from"./chunk-s4dxjqgt.js";import{supportsStructuredHistory}from"./chunk-89xeg26e.js";import{getPersistedString,getPersistedValue}from"./chunk-62ewk1qg.js";import{recordSpawn}from"./chunk-40dgv828.js";import{errorMessage}from"./chunk-9gctbddn.js";import{t}from"./chunk-6d7rhq30.js";import{rollupPr}from"./chunk-cwfs2kae.js";import{isObject}from"./chunk-7ghwdjdc.js";import{acquireSync,releaseSync}from"./chunk-rxb0hw1e.js";import{secretsPath}from"./chunk-8143k3t6.js";import{readFile,stat}from"fs/promises";var PER_SESSION=3,SNIPPET_RADIUS=60,READ_BATCH=8,READ_BUDGET_MS=1500;function snippetOf(text,needle){let flat=text.replace(/\s+/g," "),want=needle.replace(/\s+/g," "),at=flat.toLowerCase().indexOf(want.toLowerCase());if(at<0)return null;let start=Math.max(0,at-SNIPPET_RADIUS),end=Math.min(flat.length,at+want.length+SNIPPET_RADIUS);return`${start>0?"\u2026":""}${flat.slice(start,end).trim()}${end<flat.length?"\u2026":""}`}function matchMessages(messages,needle,max){let out=[];for(let m of messages){if(m.role!=="user"&&m.role!=="assistant")continue;for(let b of m.blocks){if(b.type!=="text")continue;let snippet=snippetOf(b.text,needle);if(snippet===null)continue;out.push({role:m.role,at:m.timestamp,snippet});break}if(out.length>=max)break}return out}function prefilterToken(query){return query.split(/["\\\s]+/).reduce((a,b)=>b.length>a.length?b:a,"")}async function candidatesOf(tasks,skipped){let claimed=new Set,pinned=[],unpinned=[],sharedDirs=new Map;for(let t2 of tasks)if(t2.worktreePath)sharedDirs.set(t2.worktreePath,(sharedDirs.get(t2.worktreePath)??0)+1);for(let task of tasks){if(task.origin){skipped.push({taskId:task.id,reason:"other-machine"});continue}let vendor=task.vendor,tabs=(readTabsSnapshot(task.id)?.tabs??[]).filter((t2)=>t2.kind==="engine"),any=!1;for(let tab of tabs){let tabVendor=tab.vendor??vendor;if(!tabVendor||!supportsStructuredHistory(sessionProtocol(tabVendor))||!tab.sessionId)continue;if(claimed.has(tab.sessionId))continue;claimed.add(tab.sessionId);let reader=protocolEntry(tabVendor).history;pinned.push({task,reader,sessionId:tab.sessionId,tabId:tab.id,path:null,mtimeMs:0}),any=!0}if(any)continue;if(!vendor||!supportsStructuredHistory(sessionProtocol(vendor))){skipped.push({taskId:task.id,reason:"engine-unsupported"});continue}let worktree=task.worktreePath;if(worktree&&(sharedDirs.get(worktree)??0)===1)unpinned.push({task,reader:protocolEntry(vendor).history,worktree})}let listed=await Promise.all(unpinned.map(async({task,reader,worktree})=>(await reader.listSessionIdsForWorktree(worktree)).filter((id)=>!claimed.has(id)).map((sessionId)=>({task,reader,sessionId,path:null,mtimeMs:0})))),all=[...pinned,...listed.flat()];return Promise.all(all.map(async(c)=>{let worktree=c.task.worktreePath||c.task.repo,path=await c.reader.transcriptPath(c.sessionId,worktree).catch(()=>null),mtimeMs=path?await stat(path).then((s)=>s.mtimeMs,()=>0):0;return{...c,path,mtimeMs}}))}async function filesContaining(paths,token){if(paths.length===0||token==="")return new Set(paths);let rg=Bun.which("rg");if(rg){let proc=Bun.spawn([rg,"-l","-i","-F","--no-messages","--",token,...paths],{stdout:"pipe",stderr:"ignore"}),out=await new Response(proc.stdout).text();return await proc.exited,new Set(out.split(`
3
3
  `).filter(Boolean))}let needle=token.toLowerCase(),hits=new Set;for(let p of paths)if((await readFile(p,"utf8").catch(()=>"")).toLowerCase().includes(needle))hits.add(p);return hits}async function searchTasks(tasks,query,limit,budgetMs=READ_BUDGET_MS){let started=Date.now(),skipped=[],candidates=await candidatesOf(tasks,skipped),withPath=candidates.filter((c)=>c.path!==null).map((c)=>c.path),hits=await filesContaining(withPath,prefilterToken(query)),toRead=candidates.filter((c)=>c.path===null||hits.has(c.path)).sort((a,b)=>b.mtimeMs-a.mtimeMs),matches=[],scanned=0;while(scanned<toRead.length&&matches.length<limit&&Date.now()-started<budgetMs){let batch=toRead.slice(scanned,scanned+READ_BATCH),read=await Promise.all(batch.map((c)=>c.reader.readHistory(c.sessionId).catch(()=>[])));for(let[i,messages]of read.entries()){let c=batch[i];scanned++;for(let m of matchMessages(messages,query,Math.min(PER_SESSION,limit-matches.length)))matches.push({taskId:c.task.id,title:c.task.title,...c.tabId?{tabId:c.tabId}:{},...m});if(matches.length>=limit)break}}return{query,matches,skipped,truncated:scanned<toRead.length}}async function runWorktreeGit(worktreePath,args,options={}){if(!worktreePath)return{stdout:"",stderr:"worktreePath is required",status:-1};let exec=(options.execForPath??execHostForWorktreePath)(worktreePath),controller=options.timeoutMs&&options.timeoutMs>0?new AbortController:null,timedOut=!1,timer=controller?setTimeout(()=>{timedOut=!0,controller.abort()},options.timeoutMs):null,signal=controller&&options.signal?AbortSignal.any([controller.signal,options.signal]):controller?.signal??options.signal,result;try{recordSpawn("worktree.content",["git",...args],worktreePath),result=await exec.run(["git",...args],{cwd:worktreePath,env:READ_ONLY_GIT_ENV,signal})}catch(err){if(timer)clearTimeout(timer);return{stdout:"",stderr:errorMessage(err),status:-1}}if(timer)clearTimeout(timer);if(timedOut&&result.exitCode===-1&&!result.stderr)return{stdout:result.stdout,stderr:`git ${args.join(" ")} timed out after ${options.timeoutMs}ms`,status:-1};return{stdout:result.stdout,stderr:result.stderr,status:result.exitCode}}function readLocalWorktreeHead(worktreePath,deps={}){if(!worktreePath||(deps.execForPath??execHostForWorktreePath)(worktreePath).isRemote)return null;try{let dirs=resolveGitDirs(worktreePath);return dirs?readHeadSha(dirs):null}catch{return null}}function worktreeFilePath(worktreePath,relPath){if(!worktreePath||!relPath)return null;if(/^[/\\]/.test(relPath)||/^[a-zA-Z]:[/\\]/.test(relPath))return null;if(relPath.split(/[/\\]/).some((part)=>part===".."))return null;let parts=relPath.split("/");return`${worktreePath.replace(/\/+$/,"")}/${parts.filter(Boolean).join("/")}`}async function worktreeFileSize(worktreePath,relPath,deps={}){let path=worktreeFilePath(worktreePath,relPath);if(!path)return null;let exec=(deps.execForPath??execHostForWorktreePath)(worktreePath);try{let res=await exec.run(["wc","-c",path]);if(res.exitCode!==0)return null;let n=Number.parseInt(res.stdout.trim().split(/\s+/)[0]??"",10);return Number.isFinite(n)?n:null}catch{return null}}async function readWorktreeFile(worktreePath,relPath,deps={}){let path=worktreeFilePath(worktreePath,relPath);if(!path)return null;let exec=(deps.execForPath??execHostForWorktreePath)(worktreePath);try{return await exec.readFile(path)}catch{return null}}function filetypeOf(relPath,firstLine){let leaf=relPath.slice(relPath.lastIndexOf("/")+1),dot=leaf.lastIndexOf(".");if(dot<=0)return firstLine===void 0?void 0:shebangFiletype(firstLine);switch(leaf.slice(dot+1).toLowerCase()){case"ts":case"tsx":case"mts":case"cts":return"typescript";case"js":case"jsx":case"mjs":case"cjs":return"javascript";case"md":case"markdown":return"markdown";case"zig":return"zig";default:return}}var SHEBANG_INTERPRETERS=new Map([["node","javascript"],["nodejs","javascript"],["bun","typescript"],["deno","typescript"],["tsx","typescript"],["ts-node","typescript"]]);function shebangFiletype(line){if(!line.startsWith("#!"))return;let words=line.slice(2).trim().split(/\s+/),first=words[0]??"",program=first.slice(first.lastIndexOf("/")+1);if(program==="env"){let i=1;for(;i<words.length;i++){let word=words[i]??"";if(word==="--"){i++;break}if(["-u","--unset","-C","--chdir","-P","-a","--argv0"].includes(word)){i++;continue}if(!word.startsWith("-")&&!word.includes("="))break}let command=words[i]??"";program=command.slice(command.lastIndexOf("/")+1)}return SHEBANG_INTERPRETERS.get(program)}function patchFirstLine(patch){let lines=patch.split(`
4
4
  `),at=lines.findIndex((l)=>/^@@ -\d+(?:,\d+)? \+1(?:,\d+)? @@/.test(l));if(at<0)return;return lines.slice(at+1).find((l)=>l.startsWith(" ")||l.startsWith("+"))?.slice(1)}function contentFirstLine(text){let nl=text.indexOf(`
5
5
  `);return nl<0?text:text.slice(0,nl)}function isCombinedPathspec(relPath){return relPath==="."||relPath.endsWith("/")}function hunklessPatchNote(patch){if(/^@@/m.test(patch))return null;let binary=!1,from,to,renameFrom,renameTo,emptyChange;for(let line of patch.split(`
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import{TaskDeletingError}from"./chunk-72g45nwx.js";import{awaitEngineProcess,deliverToHostedKey,enginePresence,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-yv1pkfnk.js";import{buildEngineSessionLaunch,launchReposOf,markCliTabSession,publishCliTabSnapshot,readDaemonTabs,trustEngineWorktree,trustExtraRepos}from"./chunk-8wzp1x46.js";import{engineLaunchArgv,engineResumeArgv,protocolEntry,withPinnedSessionId}from"./chunk-1590vtyb.js";import{hostedKeyFor}from"./chunk-g9ba25q5.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{taskCwd}from"./chunk-cwfs2kae.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";var MAX_SESSIONS_SCANNED=8;function titleFromMessages(messages){let firstUser=messages.find((m)=>m.role==="user");if(!firstUser)return"";let text=firstUser.blocks.filter((b)=>b.type==="text").map((b)=>b.text).join(" "),title=deriveTitleFromPrompt(text);return title.length>0?Buffer.from(title,"utf8").toString("utf8"):title}async function deriveTitleFromSession(worktree,vendor=DEFAULT_TASK_VENDOR){if(!worktree)return"";let{history}=protocolEntry(vendor),ids=await history.listSessionIdsForWorktree(worktree);for(let sessionId of ids.slice(0,MAX_SESSIONS_SCANNED)){let title=titleFromMessages(await history.readHistory(sessionId));if(title)return title}return""}async function deriveTitleFromSessionId(vendor,sessionId){if(!sessionId)return"";try{return titleFromMessages(await protocolEntry(vendor).history.readHistory(sessionId))}catch{return""}}async function getTask(link,taskId){let{task}=await link.request("task.get",{taskId});return task}async function ensureTaskWorktree(link,taskId){let task=await getTask(link,taskId);if(task.deletion)throw new TaskDeletingError(taskId);let hasExtras=Boolean(task.extraRepos?.length);if(task.worktreePath&&!hasExtras){let repos=task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0;return{task,worktreePath:taskCwd(task),repos}}let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath:taskCwd({worktreePath,cwdSubpath:task.cwdSubpath}),repos:hasExtras||task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"},repos),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)throw Error(`failed to start hosted engine session for ${taskId}`);if(launch.firstMessage){let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model})[0];await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs}).catch(()=>!1)}}finally{host.close()}return{session:launch.key,worktreePath}}async function startTaskSessionWithPromptAdapter(link,taskId,prompt,options={}){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let base=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model}),row=(await readDaemonTabs(link,taskId).catch(()=>{return}))?.tabs.find((tab)=>tab.id==="tab-1"),held=row?.kind==="engine"&&row.spawned&&row.sessionId?row.sessionId:null,resumeArgv=held&&!options.newConversation?engineResumeArgv(base,task.vendor,held):null,host=await ensureHostedSessionHost();try{let start=async(argv,text)=>{let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt:text},repos,argv),opened=await ensureHostedEngine(host.rpc,worktreePath,launch);if(!opened.alive)return{started:!1,error:"hosted session did not open",key:launch.key};let wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs},reattached=opened.created===!1&&opened.respawned!==!0,paste=launch.firstMessage??(reattached?text:void 0);if((paste?await pastePromptWhenEngineUp(host.rpc,launch.key,base[0],paste,wait):await awaitEngineProcess(host.rpc,launch.key,base[0],wait))!==null)return{started:!0,key:launch.key};if(reattached)return{started:!1,error:"NOT_DELIVERED: tab-1 was already open and the prompt could not be pasted into its engine",key:launch.key};return{started:!1,error:await startFailureReason(host.rpc,launch.key),key:launch.key}};if(resumeArgv){let resumed=await start(resumeArgv,options.resumedPrompt??prompt);if(resumed.started)return{started:!0,resumed:!0};await killHostedSessions(host.rpc,[resumed.key],{wait:!0})}let pinned=withPinnedSessionId(base,task.vendor),{key:_key,...fresh}=await start(pinned.argv,prompt);if(fresh.started)await publishCliTabSnapshot(link,taskId,pinned.sessionId),await markCliTabSession(link,taskId,"tab-1",pinned.sessionId);return fresh}finally{host.close()}}async function startFailureReason(rpc,key){let tail=await hostedSessionFailureLine(rpc,key),base="engine process never started";return tail?`engine process never started; last session output: ${tail}`:"engine process never started"}function taskEngineLaunch(task,worktreePath,promptIntent,repos,argv=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model})){return trustEngineWorktree(task.vendor,worktreePath),trustExtraRepos(task.vendor,repos),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo,repos},worktreePath,shell:resolveSessionShell(),argv,promptIntent})}async function deliverPromptToLiveEngineAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return!1;try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0],task.scope);if(!key)return!1;let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return!1;return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})!==null}catch{return!1}finally{host.close()}}function tabIdFromHostedKey(key){return key.split("::")[1]??"tab-1"}async function deliverPromptToLiveEngineDetailedAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0],task.scope);if(!key)return{outcome:"no-session"};let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}catch{return{outcome:"no-session"}}finally{host.close()}}async function deliverPromptToLiveEngineTabDetailedAdapter(target,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let key=hostedKeyFor(target.id,target.tabId,target.scope);if(!key)return{outcome:"no-session"};let sessions;try{sessions=await listHostedSessions(host.rpc)}catch{return{outcome:"no-session"}}let session=sessions.find((candidate)=>candidate.alive&&candidate.key===key);if(!session)return{outcome:"no-session"};let engineArgv=engineLaunchArgv({command:target.command,vendor:target.vendor}),presence=await enginePresence(session.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:target.tabId};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId,scope){let host=await openHostedSessionHost();if(!host)return;try{let keys=hostedTaskKeys(await listHostedSessions(host.rpc),taskId,scope);await killHostedSessions(host.rpc,keys,{wait:!0})}catch{}finally{host.close()}}async function stopTaskEngineTabAdapter(taskId,tabId,scope){let host=await openHostedSessionHost();if(!host)return;try{let key=hostedKeyFor(taskId,tabId,scope);if(key)await killHostedSessions(host.rpc,[key],{wait:!0})}finally{host.close()}}
2
+ import{deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import{TaskDeletingError}from"./chunk-72g45nwx.js";import{awaitEngineProcess,deliverToHostedKey,enginePresence,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-nvkqfsnn.js";import{buildEngineSessionLaunch,launchReposOf,markCliTabSession,publishCliTabSnapshot,readDaemonTabs,trustEngineWorktree,trustExtraRepos}from"./chunk-pxfdjszp.js";import{engineLaunchArgv,engineResumeArgv,protocolEntry,withPinnedSessionId}from"./chunk-1590vtyb.js";import{hostedKeyFor}from"./chunk-g9ba25q5.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{taskCwd}from"./chunk-cwfs2kae.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";var MAX_SESSIONS_SCANNED=8;function titleFromMessages(messages){let firstUser=messages.find((m)=>m.role==="user");if(!firstUser)return"";let text=firstUser.blocks.filter((b)=>b.type==="text").map((b)=>b.text).join(" "),title=deriveTitleFromPrompt(text);return title.length>0?Buffer.from(title,"utf8").toString("utf8"):title}async function deriveTitleFromSession(worktree,vendor=DEFAULT_TASK_VENDOR){if(!worktree)return"";let{history}=protocolEntry(vendor),ids=await history.listSessionIdsForWorktree(worktree);for(let sessionId of ids.slice(0,MAX_SESSIONS_SCANNED)){let title=titleFromMessages(await history.readHistory(sessionId));if(title)return title}return""}async function deriveTitleFromSessionId(vendor,sessionId){if(!sessionId)return"";try{return titleFromMessages(await protocolEntry(vendor).history.readHistory(sessionId))}catch{return""}}async function getTask(link,taskId){let{task}=await link.request("task.get",{taskId});return task}async function ensureTaskWorktree(link,taskId){let task=await getTask(link,taskId);if(task.deletion)throw new TaskDeletingError(taskId);let hasExtras=Boolean(task.extraRepos?.length);if(task.worktreePath&&!hasExtras){let repos=task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0;return{task,worktreePath:taskCwd(task),repos}}let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath:taskCwd({worktreePath,cwdSubpath:task.cwdSubpath}),repos:hasExtras||task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"},repos),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)throw Error(`failed to start hosted engine session for ${taskId}`);if(launch.firstMessage){let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model})[0];await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs}).catch(()=>!1)}}finally{host.close()}return{session:launch.key,worktreePath}}async function startTaskSessionWithPromptAdapter(link,taskId,prompt,options={}){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let base=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model}),row=(await readDaemonTabs(link,taskId).catch(()=>{return}))?.tabs.find((tab)=>tab.id==="tab-1"),held=row?.kind==="engine"&&row.spawned&&row.sessionId?row.sessionId:null,resumeArgv=held&&!options.newConversation?engineResumeArgv(base,task.vendor,held):null,host=await ensureHostedSessionHost();try{let start=async(argv,text)=>{let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt:text},repos,argv),opened=await ensureHostedEngine(host.rpc,worktreePath,launch);if(!opened.alive)return{started:!1,error:"hosted session did not open",key:launch.key};let wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs},reattached=opened.created===!1&&opened.respawned!==!0,paste=launch.firstMessage??(reattached?text:void 0);if((paste?await pastePromptWhenEngineUp(host.rpc,launch.key,base[0],paste,wait):await awaitEngineProcess(host.rpc,launch.key,base[0],wait))!==null)return{started:!0,key:launch.key};if(reattached)return{started:!1,error:"NOT_DELIVERED: tab-1 was already open and the prompt could not be pasted into its engine",key:launch.key};return{started:!1,error:await startFailureReason(host.rpc,launch.key),key:launch.key}};if(resumeArgv){let resumed=await start(resumeArgv,options.resumedPrompt??prompt);if(resumed.started)return{started:!0,resumed:!0};await killHostedSessions(host.rpc,[resumed.key],{wait:!0})}let pinned=withPinnedSessionId(base,task.vendor),{key:_key,...fresh}=await start(pinned.argv,prompt);if(fresh.started)await publishCliTabSnapshot(link,taskId,pinned.sessionId),await markCliTabSession(link,taskId,"tab-1",pinned.sessionId);return fresh}finally{host.close()}}async function startFailureReason(rpc,key){let tail=await hostedSessionFailureLine(rpc,key),base="engine process never started";return tail?`engine process never started; last session output: ${tail}`:"engine process never started"}function taskEngineLaunch(task,worktreePath,promptIntent,repos,argv=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model})){return trustEngineWorktree(task.vendor,worktreePath),trustExtraRepos(task.vendor,repos),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo,repos},worktreePath,shell:resolveSessionShell(),argv,promptIntent})}async function deliverPromptToLiveEngineAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return!1;try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0],task.scope);if(!key)return!1;let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return!1;return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})!==null}catch{return!1}finally{host.close()}}function tabIdFromHostedKey(key){return key.split("::")[1]??"tab-1"}async function deliverPromptToLiveEngineDetailedAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0],task.scope);if(!key)return{outcome:"no-session"};let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}catch{return{outcome:"no-session"}}finally{host.close()}}async function deliverPromptToLiveEngineTabDetailedAdapter(target,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let key=hostedKeyFor(target.id,target.tabId,target.scope);if(!key)return{outcome:"no-session"};let sessions;try{sessions=await listHostedSessions(host.rpc)}catch{return{outcome:"no-session"}}let session=sessions.find((candidate)=>candidate.alive&&candidate.key===key);if(!session)return{outcome:"no-session"};let engineArgv=engineLaunchArgv({command:target.command,vendor:target.vendor}),presence=await enginePresence(session.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:target.tabId};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId,scope){let host=await openHostedSessionHost();if(!host)return;try{let keys=hostedTaskKeys(await listHostedSessions(host.rpc),taskId,scope);await killHostedSessions(host.rpc,keys,{wait:!0})}catch{}finally{host.close()}}async function stopTaskEngineTabAdapter(taskId,tabId,scope){let host=await openHostedSessionHost();if(!host)return;try{let key=hostedKeyFor(taskId,tabId,scope);if(key)await killHostedSessions(host.rpc,[key],{wait:!0})}finally{host.close()}}
3
3
  export{deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,tearDownTaskSessionAdapter,stopTaskEngineTabAdapter};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{isDev}from"./chunk-8143k3t6.js";import{fileURLToPath}from"url";var package_default={$schema:"https://json.schemastore.org/package.json",name:"@sma1lboy/rove",version:"0.9.309-next.478",description:"Rove: all your coding agents, in one place. An agentic development environment (ADE) for your terminal: Claude Code, Codex, Copilot and more, side by side in isolated worktrees, handing tasks to each other.",keywords:["terminal","tui","cli","ade","agentic-development-environment","multiplexer","ai-agents","coding-agent","ai-coding-assistant","agentic-ai","parallel-agents","git-worktree","claude-code","codex","llm","developer-tools"],type:"module",packageManager:"bun@1.3.13",bin:{rove:"dist/cli/rove.js"},files:["dist/cli","dist/completions","dist/web","dist/web-ui","dist/skills","dist/voice","dist/*.wav","README.md","LICENSE"],publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sma1lboy/rove.git"},homepage:"https://rove.run",bugs:{url:"https://github.com/Sma1lboy/rove/issues"},engines:{bun:">=1.3.11"},scripts:{dev:"ROVE_DEV=1 bun --conditions=browser ./src/cli/rove.ts","dev:mock":"ROVE_DEV=1 bun ./src/tui-react/mock/host.tsx","dev:sandbox":"bun run scripts/dev-sandbox.ts run","dev:sandbox:reset":"bun run scripts/dev-sandbox.ts reset",build:"bun run scripts/build.ts","build:rubric":"bun run scripts/build-tier-rubric.ts",compile:"bun run scripts/compile.ts",typecheck:"tsc --noEmit","check-i18n":"bun run scripts/check-i18n.ts",test:"bun run test:fast && bun run test:socket","perf:golden":"bun scripts/perf-golden.ts","rove-bench":"bun --conditions=browser scripts/rove-bench.ts","pty:soak":"bun scripts/pty-soak.ts","test:fast":"vitest run --passWithNoTests --minWorkers=1 --maxWorkers=8","test:socket":"ROVE_INCLUDE_SOCKET=1 vitest run test/daemon --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:socket:coverage":"ROVE_INCLUDE_SOCKET=1 ROVE_COVERAGE_DAEMON=1 vitest run test/daemon --coverage --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:behavior":"ROVE_INCLUDE_BEHAVIOR=1 vitest run test/behavior --pool forks --minWorkers=1 --maxWorkers=1 --retry=2 --passWithNoTests","test:render":"bun scripts/render-track.mjs",coverage:"vitest run --coverage --passWithNoTests",bench:"vitest bench --run",lint:"biome check .",knip:"knip-bun",postinstall:"bun run scripts/check-preview-deps.ts || true",prepublishOnly:"bun run typecheck && bun run build","plugin-sandbox":"bun run scripts/plugin-sandbox.ts"},"//":"biome.json + bunfig.toml live at the monorepo root since they apply repo-wide; bun.lock also lives at root (workspace-shared).",dependencies:{"@ansi-tools/parser":"^1.0.15","@opentui/core":"0.8.4","@opentui/react":"0.8.4","@xterm/addon-serialize":"^0.14.0","@xterm/addon-unicode11":"^0.9.0","@xterm/headless":"^6.0.0",react:"^19.2.8","smol-toml":"^1.7.1",ws:"^8.21.3",yaml:"^2.9.0"},optionalDependencies:{"@sma1lboy/opentui-rove-darwin-arm64":"0.8.4-rove.1","@sma1lboy/opentui-rove-linux-x64":"0.8.4-rove.1","node-pty":"^1.1.0"},devDependencies:{"@biomejs/biome":"1.9.4","@sma1lboy/rove-daemon":"0.7.23","@tsconfig/bun":"1.0.11","@types/bun":"1.3.14","@types/node":"25.6.2","@types/react":"^19.2.0","@vitest/coverage-v8":"2.1.9",knip:"^6.14.2","react-devtools-core":"^7.0.1","rove-bridge":"0.0.69","rove-lark":"0.0.4","rove-weixin":"0.0.69",typescript:"5.8.2",vitest:"2.1.9"},trustedDependencies:[]};var RELEASE_CHANNELS=["latest","next","nightly"],DEFAULT_RELEASE_CHANNEL="latest";function channelFor(version){let dash=version.indexOf("-"),tag=dash===-1?void 0:version.slice(dash+1).split(".")[0];return tag==="nightly"||tag==="next"?tag:"latest"}var CURRENT_VERSION=package_default.version,PACKAGE_NAME=package_default.name;function repoSlug(){let url=package_default.repository?.url;if(!url)return null;let m=url.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(!m||!m[1]||!m[2])return null;return`${m[1]}/${m[2]}`}var UPDATE_SCRIPT_URL="https://raw.githubusercontent.com/Sma1lboy/rove/main/scripts/update.sh",UPDATE_COMMAND=`curl -fsSL ${UPDATE_SCRIPT_URL} | sh`;function updateCommandFor(target){return target===void 0||target===DEFAULT_RELEASE_CHANNEL?UPDATE_COMMAND:`${UPDATE_COMMAND} -s -- ${target}`}function owningNpmPrefix(modulePath=fileURLToPath(import.meta.url)){let at=modulePath.indexOf("/lib/node_modules/");if(at<=0)return null;return modulePath.slice(0,at)}function recommendedGlobalInstallCommand(prefix=owningNpmPrefix()){let target=`${PACKAGE_NAME}@latest`;return prefix===null?`npm install -g ${target}`:`npm install -g --prefix ${prefix} ${target}`}var BREAKING_VERSIONS=[];function breakingVersionsCrossed(from,to,breaking=BREAKING_VERSIONS){let[lo,hi]=compareSemver(from,to)<=0?[from,to]:[to,from];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}var FETCH_TIMEOUT_MS=3000,PACKUMENT_TIMEOUT_MS=15000;function channelOf(version=CURRENT_VERSION){return channelFor(version)}async function fetchLatestFromRegistry(packageName,channel){let ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let encoded=packageName.replace("/","%2F"),res=await fetch(`https://registry.npmjs.org/${encoded}/${channel}`,{signal:ctrl.signal,headers:{accept:"application/json"}});if(!res.ok)return null;let body=await res.json();if(typeof body.version!=="string")return null;return body.version}catch{return null}finally{clearTimeout(timer)}}async function fetchPublishedAt(packageName,version){let ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),PACKUMENT_TIMEOUT_MS);try{let encoded=packageName.replace("/","%2F"),res=await fetch(`https://registry.npmjs.org/${encoded}`,{signal:ctrl.signal,headers:{accept:"application/json"}});if(!res.ok)return null;let stamp=(await res.json()).time?.[version],ms=typeof stamp==="string"?Date.parse(stamp):Number.NaN;return Number.isFinite(ms)?ms:null}catch{return null}finally{clearTimeout(timer)}}function isNewerSemver(latest,current){let core=compareSemver(latest,current);if(core!==0)return core>0;return comparePrerelease(prereleaseOf(latest),prereleaseOf(current))>0}function prereleaseOf(version){let dash=version.indexOf("-");return dash===-1?void 0:version.slice(dash+1)||void 0}function comparePrerelease(a,b){if(a===b)return 0;if(a===void 0)return 1;if(b===void 0)return-1;let aParts=a.split("."),bParts=b.split(".");for(let i=0;i<Math.max(aParts.length,bParts.length);i++){let av=aParts[i],bv=bParts[i];if(av===void 0)return-1;if(bv===void 0)return 1;if(av===bv)continue;let an=/^\d+$/.test(av)?Number.parseInt(av,10):null,bn=/^\d+$/.test(bv)?Number.parseInt(bv,10):null;if(an!==null&&bn!==null)return an>bn?1:-1;if(an!==null)return-1;if(bn!==null)return 1;return av>bv?1:-1}return 0}function compareSemver(aVersion,bVersion){let norm=(v)=>v.split("-")[0]??v,a=norm(aVersion).split(".").map((s)=>Number.parseInt(s,10)),b=norm(bVersion).split(".").map((s)=>Number.parseInt(s,10));for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(Number.isNaN(av)||Number.isNaN(bv))return 0;if(av>bv)return 1;if(av<bv)return-1}return 0}async function checkLatestVersion(opts={}){let channel=opts.channel??channelOf(),fake=process.env.ROVE_FAKE_UPDATE;if(fake)return{current:CURRENT_VERSION,latest:fake,hasUpdate:isNewerSemver(fake,CURRENT_VERSION),channel};if(isDev()&&!opts.force)return null;let latest=await fetchLatestFromRegistry(PACKAGE_NAME,channel);if(!latest)return null;let hasUpdate=isNewerSemver(latest,CURRENT_VERSION),minAgeMs=(opts.minAgeHours??0)*3600000;if(hasUpdate&&minAgeMs>0){let publishedAt=await fetchPublishedAt(PACKAGE_NAME,latest),now=(opts.now??Date.now)();if(publishedAt!==null&&now-publishedAt<minAgeMs)hasUpdate=!1}return{current:CURRENT_VERSION,latest,hasUpdate,channel}}function versionFromTagName(tagName,channel){if(typeof tagName!=="string")return null;let match=tagName.match(/^v\d+\.\d+\.\d+(?:-([a-z]+)\.\d+)?$/);if(!match||match[1]&&match[1]!==channel)return null;return tagName.slice(1)}var ZH_NOTES_ASSET="release-notes.zh.md";async function notesBody(release,locale,signal){if(locale!=="zh"||!Array.isArray(release.assets))return release.body;let asset=release.assets.find((a)=>a.name===ZH_NOTES_ASSET);if(typeof asset?.browser_download_url!=="string")return release.body;try{let res=await fetch(asset.browser_download_url,{signal}),text=res.ok?await res.text():"";return text.trim()?text:release.body}catch{return release.body}}async function fetchReleaseNotes(version,locale="en"){let slug=repoSlug();if(!slug)return null;let tag=`v${version}`,ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let res=await fetch(`https://api.github.com/repos/${slug}/releases/tags/${tag}`,{signal:ctrl.signal,headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return null;let body=await res.json();if(typeof body.body!=="string"||typeof body.html_url!=="string")return null;return{body:await notesBody({...body,body:body.body},locale,ctrl.signal),url:body.html_url,version}}catch{return null}finally{clearTimeout(timer)}}var RELEASES_PER_PAGE=100,MAX_RELEASE_PAGES=10;async function walkReleases(visit){let slug=repoSlug();if(!slug)return;for(let page=1;page<=MAX_RELEASE_PAGES;page++){let body;try{let res=await fetch(`https://api.github.com/repos/${slug}/releases?per_page=${RELEASES_PER_PAGE}&page=${page}`,{signal:AbortSignal.timeout(FETCH_TIMEOUT_MS),headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return;body=await res.json()}catch{return}if(!Array.isArray(body))return;for(let release of body)if(!visit(release))return;if(body.length<RELEASES_PER_PAGE)return}}async function fetchReleaseNotesRange(args){let channel=channelFor(args.latest),inRange=[];await walkReleases((release)=>{let version=versionFromTagName(release.tag_name,channel);if(!version)return!0;if(!isNewerSemver(version,args.current))return!1;if(isNewerSemver(version,args.latest))return!0;if(typeof release.html_url==="string"&&typeof release.body==="string")inRange.push({version,url:release.html_url,release:{...release,body:release.body}});return!0});let signal=AbortSignal.timeout(FETCH_TIMEOUT_MS);return Promise.all(inRange.map(async({version,url,release})=>({version,url,body:await notesBody(release,args.locale??"en",signal)})))}async function fetchReleaseSummaries(limit=12){let summaries=[];return await walkReleases((release)=>{let version=versionFromTagName(release.tag_name);if(version&&typeof release.html_url==="string")summaries.push({version,url:release.html_url});return summaries.length<limit}),summaries}function releasePageUrl(version){let slug=repoSlug();if(!slug)return null;return`https://github.com/${slug}/releases/tag/v${version}`}
3
+ export{package_default,RELEASE_CHANNELS,DEFAULT_RELEASE_CHANNEL,CURRENT_VERSION,PACKAGE_NAME,repoSlug,UPDATE_SCRIPT_URL,UPDATE_COMMAND,updateCommandFor,owningNpmPrefix,recommendedGlobalInstallCommand,BREAKING_VERSIONS,breakingVersionsCrossed,channelOf,isNewerSemver,compareSemver,checkLatestVersion,ZH_NOTES_ASSET,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,releasePageUrl};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
2
+ import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-6d7rhq30.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-thrbrt43.js";import"./chunk-d2khhet8.js";import"./chunk-ty0ptx0v.js";import"./chunk-38hnq4aq.js";import"./chunk-ajpsnr22.js";import"./chunk-e7wxpvat.js";import"./chunk-j2k6f128.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-72g45nwx.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-2cqqhhc5.js";import"./chunk-cd5y4s07.js";import"./chunk-mdx18vtz.js";import"./chunk-w7zb1h9k.js";import"./chunk-q9t4sw8v.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-qkehg2c1.js";import"./chunk-s5h7ay1w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-js2krax0.js";import"./chunk-ed9npve3.js";import"./chunk-yv1pkfnk.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-7j4qsbg4.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-8wzp1x46.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.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{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
2
+ import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-frmgg5x5.js";import"./chunk-qx6fqwca.js";import"./chunk-ty0ptx0v.js";import"./chunk-38hnq4aq.js";import"./chunk-ajpsnr22.js";import"./chunk-e7wxpvat.js";import"./chunk-j2k6f128.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-72g45nwx.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-meabjsmn.js";import"./chunk-a66kyf4w.js";import"./chunk-mdx18vtz.js";import"./chunk-0a04sctf.js";import"./chunk-08dt6xbz.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-qkehg2c1.js";import"./chunk-s5h7ay1w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-rvfxhd7p.js";import"./chunk-1a0nn5n0.js";import"./chunk-nvkqfsnn.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-b6x9kd0x.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-pxfdjszp.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-6d7rhq30.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.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{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-js2krax0.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=ROVE_PRODUCT_NAME,lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-rvfxhd7p.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=ROVE_PRODUCT_NAME,lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
3
3
  `)),process.exit(1)}if(lastRun!==CURRENT_VERSION)stampResetGate()}function stampResetGate(){try{patchStateFile({[LAST_RUN_VERSION_KEY]:CURRENT_VERSION})}catch{}}
4
4
  export{LAST_RUN_VERSION_KEY,enforceResetGate,stampResetGate};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{canonPath,normalizeMainRepo,randomDirTaskSuffix,repoWorkingDir,samePrStatus,titleFromRepo}from"./chunk-46y4se2m.js";import{isUnlistedCheckout}from"./chunk-n8z4nb8v.js";import{CLONEFILEAT_PERL,GitWorktreeManager,defaultExecDeps,git,headCommit,isDirtyOutput,parseDirtyPaths}from"./chunk-tqgtv0jd.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-ak0ezn5t.js";import{LAUNCH_PREFIX_FILE}from"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-2xsxcdp6.js";import{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-72g45nwx.js";import{forwardVerb,requireMachine}from"./chunk-q9t4sw8v.js";import{resolvePreferredVendor}from"./chunk-s5h7ay1w.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{detectLanguage}from"./chunk-021xteq8.js";import{readRemoteWorkspace,removeRemoteLink}from"./chunk-78rtznxy.js";import{addSavedRepo,getPersistedString,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,storedRepos}from"./chunk-62ewk1qg.js";import{errorMessage}from"./chunk-9gctbddn.js";import{projectRejection,rejectionReason}from"./chunk-3pp65k25.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{MULTI_REPO_CAP,SESSION_PR_CAP,WORKSPACE_CAPABILITIES,applyTodoOps,checkNotes,childrenOf,deletionTargets,gitRepoOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName,workspaceBackendId,workspaceCapabilities}from"./chunk-cwfs2kae.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{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=deps.projects.ensureIfEligible(input.repo,input.projectIntent??"explicit")??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 remote=isRemoteRepoKey(input.dir),dir=remote?input.dir:canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:remote?repoWorkingDir(dir):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-46y4se2m.js";import{isUnlistedCheckout}from"./chunk-n8z4nb8v.js";import{CLONEFILEAT_PERL,GitWorktreeManager,defaultExecDeps,git,headCommit,isDirtyOutput,parseDirtyPaths}from"./chunk-tqgtv0jd.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-ak0ezn5t.js";import{LAUNCH_PREFIX_FILE}from"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-2xsxcdp6.js";import{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-72g45nwx.js";import{forwardVerb,requireMachine}from"./chunk-08dt6xbz.js";import{resolvePreferredVendor}from"./chunk-s5h7ay1w.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{detectLanguage}from"./chunk-021xteq8.js";import{readRemoteWorkspace,removeRemoteLink}from"./chunk-78rtznxy.js";import{addSavedRepo,getPersistedString,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,storedRepos}from"./chunk-62ewk1qg.js";import{errorMessage}from"./chunk-9gctbddn.js";import{projectRejection,rejectionReason}from"./chunk-3pp65k25.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{MULTI_REPO_CAP,SESSION_PR_CAP,WORKSPACE_CAPABILITIES,applyTodoOps,checkNotes,childrenOf,deletionTargets,gitRepoOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName,workspaceBackendId,workspaceCapabilities}from"./chunk-cwfs2kae.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{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=deps.projects.ensureIfEligible(input.repo,input.projectIntent??"explicit")??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 remote=isRemoteRepoKey(input.dir),dir=remote?input.dir:canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:remote?repoWorkingDir(dir):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 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=headCommit(parentPath),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 headCommit2=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0}),detached=headCommit2.exitCode===0&&headCommit2.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("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{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{join}from"path";function webRoot(){return[join(import.meta.dir,"..","web"),join(import.meta.dir,"..","..","..","rove-web","dist")].find((dir)=>existsSync(join(dir,"index.html")))??null}async function runWebSubcommand(args){let root=webRoot();if(!root)console.error(`${ROVE_PRODUCT_NAME} --web: the browser client is not in this build. From a checkout, run \`bun --filter rove-web build\` first; the npm package ships it in dist/web.`),process.exit(2);let{runBridge}=await import("./chunk-5ymvky1w.js");await runBridge(args,{name:`${ROVE_PRODUCT_NAME} --web`,web:{root}})}export{runWebSubcommand};
2
+ import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{join}from"path";function webRoot(){return[join(import.meta.dir,"..","web"),join(import.meta.dir,"..","..","..","rove-web","dist")].find((dir)=>existsSync(join(dir,"index.html")))??null}async function runWebSubcommand(args){let root=webRoot();if(!root)console.error(`${ROVE_PRODUCT_NAME} --web: the browser client is not in this build. From a checkout, run \`bun --filter rove-web build\` first; the npm package ships it in dist/web.`),process.exit(2);let{runBridge}=await import("./chunk-cgmcck32.js");await runBridge(args,{name:`${ROVE_PRODUCT_NAME} --web`,web:{root}})}export{runWebSubcommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{DAEMON_UNREACHABLE_MESSAGE,argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,isDaemonUnreachable,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-zy9nk2qb.js";import"./chunk-thrbrt43.js";import"./chunk-d2khhet8.js";import"./chunk-ty0ptx0v.js";import"./chunk-38hnq4aq.js";import"./chunk-ajpsnr22.js";import"./chunk-e7wxpvat.js";import"./chunk-j2k6f128.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-72g45nwx.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-2cqqhhc5.js";import"./chunk-cd5y4s07.js";import"./chunk-mdx18vtz.js";import"./chunk-w7zb1h9k.js";import"./chunk-q9t4sw8v.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-qkehg2c1.js";import"./chunk-s5h7ay1w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-js2krax0.js";import"./chunk-ed9npve3.js";import"./chunk-yv1pkfnk.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-7j4qsbg4.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-8wzp1x46.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.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{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,isDaemonUnreachable,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams,DAEMON_UNREACHABLE_MESSAGE};
2
+ import{DAEMON_UNREACHABLE_MESSAGE,argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,isDaemonUnreachable,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-1ktj0b2z.js";import"./chunk-frmgg5x5.js";import"./chunk-qx6fqwca.js";import"./chunk-ty0ptx0v.js";import"./chunk-38hnq4aq.js";import"./chunk-ajpsnr22.js";import"./chunk-e7wxpvat.js";import"./chunk-j2k6f128.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-72g45nwx.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-meabjsmn.js";import"./chunk-a66kyf4w.js";import"./chunk-mdx18vtz.js";import"./chunk-0a04sctf.js";import"./chunk-08dt6xbz.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-qkehg2c1.js";import"./chunk-s5h7ay1w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-rvfxhd7p.js";import"./chunk-1a0nn5n0.js";import"./chunk-nvkqfsnn.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-b6x9kd0x.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-pxfdjszp.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-6d7rhq30.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.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{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,isDaemonUnreachable,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams,DAEMON_UNREACHABLE_MESSAGE};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-dh2e2yqb.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-pewbnfc7.js";import"./chunk-zcqjevxc.js";import"./chunk-a4hsqj1b.js";import"./chunk-xzk96zfj.js";import"./chunk-rmnm3f9n.js";import{skillOverview}from"./chunk-v3mtzde5.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-39rn20pf.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines,withEngineVersions}from"./chunk-ajpsnr22.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-y0e28qha.js";import"./chunk-eaav6ajz.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import{CURRENT_VERSION,package_default}from"./chunk-js2krax0.js";import{resolveNodeBinary}from"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import{t}from"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import{readableLegacyIndexPath}from"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import{readPidFile}from"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-2z2jwetd.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{preRenameStateDir}from"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
2
+ import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-dh2e2yqb.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-pewbnfc7.js";import"./chunk-zcqjevxc.js";import"./chunk-a4hsqj1b.js";import"./chunk-xzk96zfj.js";import"./chunk-rmnm3f9n.js";import{skillOverview}from"./chunk-v3mtzde5.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-12pxe7cf.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines,withEngineVersions}from"./chunk-ajpsnr22.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-y0e28qha.js";import"./chunk-eaav6ajz.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import{CURRENT_VERSION,package_default}from"./chunk-rvfxhd7p.js";import{resolveNodeBinary}from"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import{t}from"./chunk-6d7rhq30.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import{readableLegacyIndexPath}from"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import{readPidFile}from"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-2z2jwetd.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{preRenameStateDir}from"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
3
3
  `)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids,deps={}){let runProbe=deps.run??run,readEnviron=deps.readEnviron??((pid)=>readFileSync(`/proc/${pid}/environ`,"utf8")),marked=new Set;if(pids.length===0)return{marked,failed:null};if((deps.platform??process.platform)==="linux"){let refused=null;for(let pid of pids)try{if(readEnviron(pid).split("\x00").includes(PTY_MARKER))marked.add(pid)}catch(err){let code=err.code;if(code!=="ENOENT"&&code!=="ESRCH")refused??=`/proc/${pid}/environ: ${code??"unreadable"}`}return{marked,failed:refused}}let result=await runProbe(["ps","eww","-o","pid=,command=","-p",pids.join(",")]);if(result.code!==0)return{marked,failed:`ps eww exited ${result.code}`};let marker=new RegExp(`(^|\\s)${PTY_MARKER}(\\s|$)`);for(let line of result.stdout.split(`
4
4
  `)){let pid=Number.parseInt(line.trim().split(/\s+/)[0]??"",10);if(Number.isFinite(pid)&&marker.test(line))marked.add(pid)}return{marked,failed:null}}async function ownPgid(runProbe){let result=await runProbe(["ps","-o","pgid=","-p",String(process.pid)]),pgid=Number.parseInt(result.stdout.trim(),10);return Number.isFinite(pgid)?pgid:-1}async function collectOrphans(liveSessionPids,deps={}){let runProbe=deps.run??run;if((deps.platform??process.platform)==="win32")return{orphans:[],error:null};let ps=await runProbe(["ps","-A","-o","pid=,ppid=,pgid=,etime=,rss=,command="]);if(ps.code!==0)return{orphans:[],error:`could not read the process table \u2014 ps exited ${ps.code}`};let rows=parsePsRows(ps.stdout),candidates=orphanCandidates(rows,await ownPgid(runProbe),liveSessionPids),{marked,failed}=await markedPids(candidates.map((row)=>row.pid),deps);if(failed)return{orphans:[],error:`could not read process environments \u2014 ${failed}`};return{orphans:candidates.filter((row)=>marked.has(row.pid)),error:null}}function formatMb(rssKb){return`${(rssKb/1024).toFixed(0)} MB`}function orphanDoctorLines(orphans,error,cliName,killing=!1){if(error)return[`orphans: \u2717 ${error}`];if(orphans.length===0)return["orphans: \u2713 none \u2014 no processes left behind by a dead PTY session"];let totalMb=orphans.reduce((sum,row)=>sum+row.rssKb,0)/1024,lines=[`orphans: \u26A0 ${orphans.length} process(es) outlived the PTY session that spawned them (${totalMb.toFixed(0)} MB RSS)`," each is reparented to init, carries Rove's PTY marker, and its process"," group leader is gone \u2014 no live task owns them"];for(let row of[...orphans].sort((a,b)=>b.rssKb-a.rssKb))lines.push(` pid ${row.pid} (group ${row.pgid}) up ${row.etime}, ${formatMb(row.rssKb)}: ${row.command.slice(0,90)}`);if(!killing)lines.push(` \u2192 \`${cliName} doctor --kill-orphans\` ends those process groups (SIGTERM, then SIGKILL)`," read the list first: something you backgrounded from a Rove terminal and then"," closed the tab on looks exactly like a leak, and doctor cannot tell them apart");return lines}var GROUP_EXIT_GRACE_MS=2000,GROUP_POLL_MS=100;function logOrphanKill(pgid,signal,logPath=defaultDaemonLogPath()){try{appendFileSync(logPath,formatDaemonInfo("doctor-kill-orphans",`${signal} process group ${pgid}`))}catch{}}function groupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(err){return err.code!=="ESRCH"}}async function killOrphanGroups(orphans){let groups=[...new Set(orphans.map((row)=>row.pgid))];for(let pgid of groups)try{process.kill(-pgid,"SIGTERM"),logOrphanKill(pgid,"SIGTERM")}catch{}let deadline=Date.now()+GROUP_EXIT_GRACE_MS,survivors=groups.filter(groupAlive);while(survivors.length>0&&Date.now()<deadline)await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),survivors=survivors.filter(groupAlive);for(let pgid of survivors)try{process.kill(-pgid,"SIGKILL"),logOrphanKill(pgid,"SIGKILL")}catch{}return await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),{groups,survivors:survivors.filter(groupAlive)}}function multiplexerLabel(env){if(env.TMUX)return"tmux";if(env.ZELLIJ)return"zellij";if(env.STY)return"screen";return"no"}function terminalEnvLines(env){let show=(v)=>v&&v.length>0?v:"(unset)",program=env.TERM_PROGRAM?`${env.TERM_PROGRAM}${env.TERM_PROGRAM_VERSION?` v${env.TERM_PROGRAM_VERSION}`:""}`:"(unset)";return[`terminal: TERM=${show(env.TERM)} TERM_PROGRAM=${program} COLORTERM=${show(env.COLORTERM)}`,` running inside a multiplexer: ${multiplexerLabel(env)}`]}function parseKittyProbeReply(data){let kitty=data.match(/\x1b\[\?(\d+)u/);if(kitty?.[1]!==void 0)return{kind:"supported",flags:Number.parseInt(kitty[1],10)};if(/\x1b\[\?[\d;]*c/.test(data))return{kind:"unsupported"};return null}function kittyProbeLine(result){switch(result.kind){case"supported":return` kitty keyboard protocol: \u2713 answered (flags=${result.flags})`;case"unsupported":return[" kitty keyboard protocol: \u2717 not supported \u2014 legacy key path"," (ctrl+h/ctrl+j arrive as C0 backspace/linefeed bytes; the"," split chords ctrl+\\ and ctrl+= cannot be encoded at all)"].join(`
5
5
  `);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}async function probeGit(){try{let proc=Bun.spawn(["git","--version"],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),text=(await new Response(proc.stdout).text()).trim();if(await proc.exited===0&&text)return{line:`git: \u2713 ${text}`,found:!0}}catch{}return{line:"git: \u2717 not found on PATH",found:!1}}function binaryLabel(binary){return binary.found?`\u2713 ${binary.path}`:`\u2717 ${binary.error}`}async function probeEngines(){let statuses=await withEngineVersions(await detectEngineStatuses(await probeableEngineIds())),lines=["engines:"];for(let status of statuses){let account=describeAccount(status.account),name=`${status.vendor.padEnd(7)} `,version=status.version?` (${status.version})`:"";if(lines.push(` ${name}${binaryLabel(status.binary)}${version}${status.binary.found?` \u2014 ${account}`:""}`),status.accountError)lines.push(` \u26A0 ${status.accountError}`)}let{usable,signedOut}=summarizeEngines(statuses);return{lines,anyUsable:usable.length>0,signedOut}}var CLI_NAME=ROVE_PRODUCT_NAME;function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new RoveDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(readFileSync2(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function tailFile(path,count){try{return readFileSync2(path,"utf8").split(`
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{recommendedGlobalInstallCommand}from"./chunk-js2krax0.js";import{resolveLoginShell}from"./chunk-tn9gtf18.js";function updaterShell(deps={}){let platform=deps.platform??process.platform;if(platform!=="win32")return"sh";return resolveLoginShell({fallback:"/bin/sh",platform,env:deps.env,exists:deps.exists})}function updaterShellFailureHint(deps={}){if((deps.platform??process.platform)!=="win32")return null;return["The update script is POSIX shell. Rove runs it through Git for Windows'","bash \u2014 the same shell every engine and terminal tab launches through.","Install Git for Windows (https://git-scm.com/download/win), or update","by hand:",` ${recommendedGlobalInstallCommand()}`,""].join(`
2
+ import{recommendedGlobalInstallCommand}from"./chunk-rvfxhd7p.js";import{resolveLoginShell}from"./chunk-tn9gtf18.js";function updaterShell(deps={}){let platform=deps.platform??process.platform;if(platform!=="win32")return"sh";return resolveLoginShell({fallback:"/bin/sh",platform,env:deps.env,exists:deps.exists})}function updaterShellFailureHint(deps={}){if((deps.platform??process.platform)!=="win32")return null;return["The update script is POSIX shell. Rove runs it through Git for Windows'","bash \u2014 the same shell every engine and terminal tab launches through.","Install Git for Windows (https://git-scm.com/download/win), or update","by hand:",` ${recommendedGlobalInstallCommand()}`,""].join(`
3
3
  `)}
4
4
  export{updaterShell,updaterShellFailureHint};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{stampOrigin}from"./chunk-rm7h9tyq.js";import{createStateCell}from"./chunk-cmp64q4j.js";var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map};function decodeMachines(payload){let p=payload;if(!p||!Array.isArray(p.machines)||!Array.isArray(p.tasks)||!p.live||typeof p.live!=="object")return null;let map=(value)=>new Map(value&&typeof value==="object"?Object.entries(value):[]);return{machines:p.machines,tasks:p.tasks,live:{activity:map(p.live.activity),changes:map(p.live.changes),tokens:map(p.live.tokens)}}}class MachineFeed{local;machinesAcc=createStateCell([],"machines.status");remoteTasksAcc=createStateCell(null,"machines.remoteTasks");tasksAcc;merged=null;liveAcc=createStateCell(NO_LIVE,"machines.live");stops;constructor(local){this.local=local;this.tasksAcc=this.mergedTasks();let raw=local.rawChannelSignal("machines"),take=()=>{let next=decodeMachines(raw.get());if(!next)return;this.machinesAcc.set(next.machines),this.liveAcc.set(next.live),this.remoteTasksAcc.set(next.machines.length===0?null:next.tasks)};this.stops=[raw.subscribe(take)],take()}machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}mergedTasks(){let localTasks=this.local.tasksSignal(),get=()=>{let local=localTasks.get(),remote=this.remoteTasksAcc.get();if(remote===null)return local;if(this.merged?.local!==local||this.merged.remote!==remote){let value=[...local.map((task)=>stampOrigin(task,"local","local")),...remote];this.merged={local,remote,value}}return this.merged.value},state=get;return state.get=get,state.subscribe=(listener)=>{let stopLocal=localTasks.subscribe(listener),stopRemote=this.remoteTasksAcc.subscribe(listener);return()=>{stopLocal(),stopRemote()}},state}dispose(){for(let stop of this.stops)stop()}}
2
+ import{stampOrigin}from"./chunk-81awn5a1.js";import{createStateCell}from"./chunk-cmp64q4j.js";var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map};function decodeMachines(payload){let p=payload;if(!p||!Array.isArray(p.machines)||!Array.isArray(p.tasks)||!p.live||typeof p.live!=="object")return null;let map=(value)=>new Map(value&&typeof value==="object"?Object.entries(value):[]);return{machines:p.machines,tasks:p.tasks,live:{activity:map(p.live.activity),changes:map(p.live.changes),tokens:map(p.live.tokens)}}}class MachineFeed{local;machinesAcc=createStateCell([],"machines.status");remoteTasksAcc=createStateCell(null,"machines.remoteTasks");tasksAcc;merged=null;liveAcc=createStateCell(NO_LIVE,"machines.live");stops;constructor(local){this.local=local;this.tasksAcc=this.mergedTasks();let raw=local.rawChannelSignal("machines"),take=()=>{let next=decodeMachines(raw.get());if(!next)return;this.machinesAcc.set(next.machines),this.liveAcc.set(next.live),this.remoteTasksAcc.set(next.machines.length===0?null:next.tasks)};this.stops=[raw.subscribe(take)],take()}machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}mergedTasks(){let localTasks=this.local.tasksSignal(),get=()=>{let local=localTasks.get(),remote=this.remoteTasksAcc.get();if(remote===null)return local;if(this.merged?.local!==local||this.merged.remote!==remote){let value=[...local.map((task)=>stampOrigin(task,"local","local")),...remote];this.merged={local,remote,value}}return this.merged.value},state=get;return state.get=get,state.subscribe=(listener)=>{let stopLocal=localTasks.subscribe(listener),stopRemote=this.remoteTasksAcc.subscribe(listener);return()=>{stopLocal(),stopRemote()}},state}dispose(){for(let stop of this.stops)stop()}}
3
3
  export{decodeMachines,MachineFeed};