werkmeister 0.28.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __sandboxCreateRequire } from "node:module";
3
3
  const require = __sandboxCreateRequire(import.meta.url);
4
- var OU=Object.create;var yp=Object.defineProperty;var TU=Object.getOwnPropertyDescriptor;var AU=Object.getOwnPropertyNames;var RU=Object.getPrototypeOf,CU=Object.prototype.hasOwnProperty;var i=(e,t)=>yp(e,"name",{value:t,configurable:!0}),J=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>(e&&(t=e(e=0)),t);var $=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ge=(e,t)=>{for(var r in t)yp(e,r,{get:t[r],enumerable:!0})},NU=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of AU(t))!CU.call(e,s)&&s!==r&&yp(e,s,{get:()=>t[s],enumerable:!(n=TU(t,s))||n.enumerable});return e};var Pe=(e,t,r)=>(r=e!=null?OU(RU(e)):{},NU(t||!e||!e.__esModule?yp(r,"default",{value:e,enumerable:!0}):r,e));var _,p=C(()=>{_={sha:"18cf7c4e3fdd69d8e78a7e309a33f72f33fc7185",dirty:!1}});var Xl=$(ay=>{p();var bp=class extends Error{static{i(this,"CommanderError")}constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},iy=class extends bp{static{i(this,"InvalidArgumentError")}constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ay.CommanderError=bp;ay.InvalidArgumentError=iy});var wp=$(ly=>{p();var{InvalidArgumentError:IU}=Xl(),cy=class{static{i(this,"Argument")}constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:r.concat(t)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new IU(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function LU(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}i(LU,"humanReadableArgName");ly.Argument=cy;ly.humanReadableArgName=LU});var dy=$(fy=>{p();var{humanReadableArgName:DU}=wp(),uy=class{static{i(this,"Help")}constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,o)=>s.name().localeCompare(o.name())),r}compareOptions(t,r){let n=i(s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,""),"getSortKey");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!s&&!o?r.push(n):n.long&&!o?r.push(t.createOption(n.long,n.description)):n.short&&!s&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>DU(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(s)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(s)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];return t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0?`${t.description} (${r.join(", ")})`:t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatHelp(t,r){let n=r.padWidth(t,r),s=r.helpWidth??80;function o(d,h){return r.formatItem(d,n,h,r)}i(o,"callFormatItem");let a=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],c=r.commandDescription(t);c.length>0&&(a=a.concat([r.boxWrap(r.styleCommandDescription(c),s),""]));let l=r.visibleArguments(t).map(d=>o(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));l.length>0&&(a=a.concat([r.styleTitle("Arguments:"),...l,""]));let u=r.visibleOptions(t).map(d=>o(r.styleOptionTerm(r.optionTerm(d)),r.styleOptionDescription(r.optionDescription(d))));if(u.length>0&&(a=a.concat([r.styleTitle("Options:"),...u,""])),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(h=>o(r.styleOptionTerm(r.optionTerm(h)),r.styleOptionDescription(r.optionDescription(h))));d.length>0&&(a=a.concat([r.styleTitle("Global Options:"),...d,""]))}let f=r.visibleCommands(t).map(d=>o(r.styleSubcommandTerm(r.subcommandTerm(d)),r.styleSubcommandDescription(r.subcommandDescription(d))));return f.length>0&&(a=a.concat([r.styleTitle("Commands:"),...f,""])),a.join(`
4
+ var OU=Object.create;var yp=Object.defineProperty;var TU=Object.getOwnPropertyDescriptor;var AU=Object.getOwnPropertyNames;var RU=Object.getPrototypeOf,CU=Object.prototype.hasOwnProperty;var i=(e,t)=>yp(e,"name",{value:t,configurable:!0}),J=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>(e&&(t=e(e=0)),t);var $=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ge=(e,t)=>{for(var r in t)yp(e,r,{get:t[r],enumerable:!0})},NU=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of AU(t))!CU.call(e,s)&&s!==r&&yp(e,s,{get:()=>t[s],enumerable:!(n=TU(t,s))||n.enumerable});return e};var Pe=(e,t,r)=>(r=e!=null?OU(RU(e)):{},NU(t||!e||!e.__esModule?yp(r,"default",{value:e,enumerable:!0}):r,e));var _,p=C(()=>{_={sha:"34a7a73865c8ede2c1a42b3a37ee3ca175b0f43b",dirty:!1}});var Xl=$(ay=>{p();var bp=class extends Error{static{i(this,"CommanderError")}constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},iy=class extends bp{static{i(this,"InvalidArgumentError")}constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ay.CommanderError=bp;ay.InvalidArgumentError=iy});var wp=$(ly=>{p();var{InvalidArgumentError:IU}=Xl(),cy=class{static{i(this,"Argument")}constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:r.concat(t)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new IU(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function LU(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}i(LU,"humanReadableArgName");ly.Argument=cy;ly.humanReadableArgName=LU});var dy=$(fy=>{p();var{humanReadableArgName:DU}=wp(),uy=class{static{i(this,"Help")}constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,o)=>s.name().localeCompare(o.name())),r}compareOptions(t,r){let n=i(s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,""),"getSortKey");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!s&&!o?r.push(n):n.long&&!o?r.push(t.createOption(n.long,n.description)):n.short&&!s&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>DU(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(s)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(s)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];return t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0?`${t.description} (${r.join(", ")})`:t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatHelp(t,r){let n=r.padWidth(t,r),s=r.helpWidth??80;function o(d,h){return r.formatItem(d,n,h,r)}i(o,"callFormatItem");let a=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],c=r.commandDescription(t);c.length>0&&(a=a.concat([r.boxWrap(r.styleCommandDescription(c),s),""]));let l=r.visibleArguments(t).map(d=>o(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));l.length>0&&(a=a.concat([r.styleTitle("Arguments:"),...l,""]));let u=r.visibleOptions(t).map(d=>o(r.styleOptionTerm(r.optionTerm(d)),r.styleOptionDescription(r.optionDescription(d))));if(u.length>0&&(a=a.concat([r.styleTitle("Options:"),...u,""])),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(h=>o(r.styleOptionTerm(r.optionTerm(h)),r.styleOptionDescription(r.optionDescription(h))));d.length>0&&(a=a.concat([r.styleTitle("Global Options:"),...d,""]))}let f=r.visibleCommands(t).map(d=>o(r.styleSubcommandTerm(r.subcommandTerm(d)),r.styleSubcommandDescription(r.subcommandDescription(d))));return f.length>0&&(a=a.concat([r.styleTitle("Commands:"),...f,""])),a.join(`
5
5
  `)}displayWidth(t){return B6(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,r){return Math.max(r.longestOptionTermLength(t,r),r.longestGlobalOptionTermLength(t,r),r.longestSubcommandTermLength(t,r),r.longestArgumentTermLength(t,r))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,r,n,s){let a=" ".repeat(2);if(!n)return a+t;let c=t.padEnd(r+t.length-s.displayWidth(t)),l=2,f=(this.helpWidth??80)-r-l-2,d;return f<this.minWidthToWrap||s.preformatted(n)?d=n:d=s.boxWrap(n,f).replace(/\n/g,`
6
6
  `+" ".repeat(r+l)),a+c+" ".repeat(l)+d.replace(/\n/g,`
7
7
  ${a}`)}boxWrap(t,r){if(r<this.minWidthToWrap)return t;let n=t.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(a=>{let c=a.match(s);if(c===null){o.push("");return}let l=[c.shift()],u=this.displayWidth(l[0]);c.forEach(f=>{let d=this.displayWidth(f);if(u+d<=r){l.push(f),u+=d;return}o.push(l.join(""));let h=f.trimStart();l=[h],u=this.displayWidth(h)}),o.push(l.join(""))}),o.join(`
@@ -1206,7 +1206,7 @@ ${$me}`}]}if(t)return[{label:n,ok:!0,detail:`configured for ${e.email} (run \`sa
1206
1206
  email: <your-atlassian-login-email>
1207
1207
  api_token: PASTE_TOKEN_HERE`;i(Ome,"defaultJiraVerifier");i(Tme,"syncJiraToken");Ame={"services-fragment.schema.json":"**/.sandbox/services.yaml","workspace.schema.json":"**/.sandbox/workspace.yml"};i(cp,"vscodeSettingsPath");i(Z$,"editorSchemaState");i(Rme,"syncEditorSchemas");i(lp,"claudeUserSettingsPath");i(e6,"claudeStandardsDirState");i(Cme,"syncClaudeStandardsDir");Ux="com.werkmeister.pr-watch",eB="# werkmeister pr watch",t6=600,Nme="Remove with: werkmeister pr watch --uninstall";i(r6,"resolvePrWatch");qx=i(e=>e.replace(/[&<>"']/g,t=>`&#${t.charCodeAt(0)};`),"xmlEscape");i(tB,"prWatchPlist");z$=i(e=>`'${e.replace(/'/g,"'\\''")}'`.replace(/%/g,"\\%"),"cronQuote");i(rB,"prWatchCronLine");ap=i(e=>e.trimEnd().endsWith(eB),"isPrWatchCronLine");i(n6,"readCrontab");i(nB,"writeCrontab");i(s6,"prWatchScheduleState");i(o6,"installPrWatchSchedule");i(sB,"uninstallPrWatchSchedule");i(Pme,"syncPrWatchSchedule");J$="jbbz.werkmeister-vscode",Ime=we.join("dist","sandbox-workspaces.vsix");i(Wx,"vscodeExtensionState");i(Lme,"syncVscodeExtension");i(Dme,"syncTelepresence");i(jme,"syncPlaywright");i(i6,"runSetup")});import*as mi from"node:fs";import*as iB from"node:path";function aB(e,t){let r=new Set;for(let n of Object.keys(e)){let s=t[n]??{};for(let o of s.mcp_servers??[])r.add(o)}return[...r].sort()}function cB(e,t){let r=[];for(let n of Object.keys(e).sort()){let s=e[n];if(!(typeof s!="object"||s===null||Array.isArray(s)))for(let o of s.mcp_servers??[])o in t||r.push(`services.yaml: archetype '${n}' lists MCP server '${o}' \u2014 no \`mcp_servers.${o}\` definition`)}return r}function a6(e,t){return typeof e=="string"?e.replace(/\$\{(\w+)\}/g,(r,n)=>Object.hasOwn(t,n)?t[n]:r):Array.isArray(e)?e.map(r=>a6(r,t)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,a6(n,t)])):e}function lB(e,t,r,n={}){let s=iB.join(e,".mcp.json"),o=mi.existsSync(s)&&mi.statSync(s).isFile(),a={};if(o)try{let f=JSON.parse(mi.readFileSync(s,"utf8"));if(typeof f=="object"&&f!==null&&!Array.isArray(f))a=f;else return s}catch{return s}let c={};for(let f of t)f in r&&(c[f]=a6(r[f],n));if(Object.keys(c).length===0&&!o)return null;"mcpServers"in a||(a.mcpServers={});let l=a.mcpServers;for(let f of Object.keys(l))f in r&&!(f in c)&&delete l[f];return l[oB]?.headers?.["X-Sandbox-Feature"]!==void 0&&delete l[oB],Object.assign(l,c),mi.writeFileSync(s,JSON.stringify(a,null,2)+`
1208
1208
  `),s}var oB,uB=C(()=>{"use strict";p();oB="sandbox";i(aB,"resolveWorkspaceMcpServers");i(cB,"validateArchetypeMcpServers");i(a6,"substituteVars");i(lB,"writeWorkspaceMcp")});import*as et from"node:fs";import*as Kl from"node:os";import*as ue from"node:path";function Rs(e){throw j(e),new kr(e)}async function Fme(e,t,r){if(r.issue)E$(e,r.issue);else if(r.refresh){if(!t)throw new kr("--refresh-issue: this workspace has no issue_id.");try{E$(e,await Fl(t))}catch(n){throw n instanceof Va?new kr(`${n.message}; run \`sandbox connect\` to check the issue tracker.`):n}}return p3(e,t)}function Mme(e){try{return et.statSync(e).isDirectory()}catch{return!1}}function Bme(){for(let e of["LOGNAME","USER","LNAME","USERNAME"]){let t=process.env[e];if(t)return t}return Kl.userInfo().username}function Ume(e){return e.split(",").map(t=>t.trim()).filter(t=>t)}function Wme(e,t){if(t&&et.existsSync(Us(t)))return!0;let r=Ye("WORKSPACE_CONFIG");if(r&&et.existsSync(Us(r)))return!0;let n=W(e);return Po.some(s=>et.existsSync(ue.join(n,s)))}function pB(e,t){if(Object.keys(t).length===0)return;let r=W(e),n=ue.join(r,Po[0]),s=Po.slice(1).map(u=>ue.join(r,u)),o={};for(let u of[n,...s])if(et.existsSync(u)&&et.statSync(u).isFile())try{let f=Ec(u);if(typeof f=="object"&&f!==null&&!Array.isArray(f)){o=f;break}}catch{}delete o._generator,delete o.$schema;let a={...o};for(let[,,u]of $c)if(u in t){let f=t[u];if(qme.has(u)&&typeof f=="string"&&(f=Ume(f)),(u==="autonomous"||u==="auto_stop")&&(f=f==="true"),u==="auto_stop"&&f===!1&&!(u in o))continue;a[u]=f}let c=dB.stringify(a,{sortMapEntries:!0,blockQuote:"literal"}),l=Vme+c;if(!(et.existsSync(n)&&et.readFileSync(n,"utf8")===l)){et.mkdirSync(r,{recursive:!0}),et.writeFileSync(n,l),F(`Persisted inputs to ${n}`);for(let u of s)et.existsSync(u)&&(et.unlinkSync(u),O(`Removed legacy ${ue.basename(u)} (superseded by workspace.yml)`))}}function Hme(e,t){let r=(e||"").trim().toLowerCase(),n=(t||"").trim().toLowerCase();return n?`${n}-${r}`:r}function Gme(e,t){return`${e}/${t}`}function Yme(){return rn()}function zme(){let e=bc().workspaces_root;return e?ue.resolve(mt(e)):ue.resolve(ue.join(Kl.homedir(),"workspace"))}function Jme(e,t,r){let n=Yme(),s=ue.join(n,Hn);if(O(`Workspace: ${e}`),O(`Branch: ${t}`),et.existsSync(ue.join(s,".git"))){try{lS(s,e,t,{force:r})}catch(o){Rs(`Failed to create workspace root worktree: ${o.message}`)}F(`Created workspace root (worktree of ${Hn}) at ${e}`)}else I(`No '${Hn}' repo at ${s} \u2014 workspace root will be a plain directory (no git history for notes/config).`),et.mkdirSync(e,{recursive:!0})}function Xme(e,t){if(et.existsSync(ue.join(e,".git")))try{if(V(["git","-C",e,"add","-A"],{capture:!0,check:!0}),V(["git","-C",e,"diff","--cached","--quiet"],{capture:!0}).status===0)return;V(["git","-C",e,"commit","-q","-m",`chore: initialize workspace ${t}`],{capture:!0,check:!0}),F("Committed initial workspace state (branch not pushed \u2014 push when ready).")}catch(r){I(`Could not commit initial workspace state: ${r.message}`)}}async function Qme(e,t){let r=pe(),[n,,s]=cS(e??null,t??null,r);return s.length&&Rs(`Unknown service(s): ${s.join(", ")}. See \`sandbox services\` / config/services.yaml.`),n.length||Rs("No repos selected. Choose at least one service or repo in the wizard, or pass --services svc1,svc2 / --repos r1,r2."),n}function fB(){let e=[],t=bc().workspaces_root;t&&e.push(ue.resolve(Us(t))),e.push(ue.join(Kl.homedir(),"workspace"));let r=new Set,n=[];for(let s of e)r.has(s)||(r.add(s),n.push(s));return n}function Zme(){let e=ue.resolve(process.cwd());for(let r of fB()){let n=ue.relative(r,e);if(!(n===".."||n.startsWith(".."+ue.sep)||ue.isAbsolute(n))&&n!=="")return ue.join(r,n.split(ue.sep)[0])}for(let r of[e,...e0e(e)])if(et.existsSync(ue.join(r,".git")))return ue.dirname(r);let t=fB().join(", ");throw new up(`${b.RED}[err] Not inside a sandbox workspace (checked: ${t}) and no parent \`.git\` directory found.
1209
- The workspaces root comes from ~/.sandbox/config.yaml \u2014 run \`sandbox config\` to set it (or \`sandbox config --check\` to verify). See docs/known-issues.md for details.${b.RESET}`)}function e0e(e){let t=[],r=e;for(;;){let n=ue.dirname(r);if(n===r)break;t.push(n),r=n}return t}function hB(e){let r=V(["git","-C",e,"branch","--show-current"],{capture:!0}).stdout.trim();return r||V(["git","-C",e,"rev-parse","--short","HEAD"],{capture:!0}).stdout.trim()||"unknown"}function mB(e){return Wi(e).map(t=>[ue.basename(t),hB(t)])}function t0e(e){if(et.existsSync(ue.join(e,".git"))){let t=hB(e);if(t&&t!=="unknown")return t}return`${Bme()}/${ue.basename(e)}`}function r0e(e,t,r){let n=rn(),s=t.filter(h=>h!==Hn),o=new Set(s),a=new Set(mB(e).map(([h])=>h)),c=s.filter(h=>!a.has(h)),l=[...a].filter(h=>!o.has(h)).sort(),u=c.filter(h=>!Mme(ue.join(n,h)));if(u.length&&Rs(`Source repo(s) not found under ${n}: ${u.join(", ")}. Clone them there (or fix \`repos\` in .sandbox/workspace.yml) and rerun.`),l.length&&!r){let h=l.filter(m=>tL(ue.join(e,m)));h.length&&Rs(`Refusing to remove worktree(s) with uncommitted changes: ${h.join(", ")}. Commit or stash them, or rerun with --force to discard them.`)}if(!c.length&&!l.length)return;let f=t0e(e);for(let h of l){let[m,y]=uS(ue.join(n,h),ue.join(e,h),f);m?(F(`Removed worktree '${h}' (no longer in workspace.yml).`),y&&I(y)):Rs(`Could not remove worktree '${h}': ${y}`)}let d=[];try{for(let h of c){let m=ue.join(n,h),y=ue.join(e,h);lS(m,y,f,{force:r}),d.push([y,m])}}catch(h){let m=`Failed to create worktree: ${h.message}`;j(m),I("Rolling back worktrees created this run...");for(let[y,g]of[...d].reverse())uS(g,y,f);throw new kr(m)}(c.length||l.length)&&F(`Worktrees reconciled (+${c.length} / -${l.length}).`)}function n0e(e,t,r){if(e)return[e.trim(),{}];let n=r?.().trim();return n?[n,{}]:[Cw(t),{}]}function s0e(e){if(!et.existsSync(e))return;et.readFileSync(e,"utf8").includes("## Layout")?I("CLAUDE.md already initialised \u2014 overwriting with fresh content."):O("Replacing stub CLAUDE.md with full workspace context.")}function o0e(e,t){O(`Task: ${e}`);for(let[r,n]of[["FEATURE","Feature"],["SERVICES","Services"],["ISSUE_ID","Issue"],["TEST_PATH","Test path"]]){let s=t[r];s&&O(` ${(n+":").padEnd(10)} ${s}`)}}async function c6(e,t,r={}){let n=t??Zme(),s=ue.basename(n);O(`Workspace root: ${n}`);let o=ji(e,n),a=h_(Vm(o.context_strategy));!Wme(n,e.config_file??null)&&!o.feature&&Rs("No .sandbox/workspace.yml found and no --feature given. Run `sandbox workspace <name>` to create and initialise a workspace, then rerun `sandbox init-workspace` from inside it to reconcile changes."),pB(n,o);let l=o.issue_id?Oe().parseRef(o.issue_id)??o.issue_id:"",u;try{u=await Fme(n,l,{issue:r.issue,refresh:!!e.refresh_issue})}catch(N){throw N instanceof kr&&Rs(N.message),N}if(o.repos){let[N]=Fr(),[P,,L]=cS(o.repos,o.services,N);L.length&&I(`Unknown service(s) in workspace.yml (no owning repo): ${L.join(", ")}`),r0e(n,P,!!e.force)}let f=ue.join(n,"CLAUDE.md");s0e(f),O("Scanning for git repos...");let d=mB(n);if(!d.length)I("No git repos found in workspace. CLAUDE.md will have an empty layout.");else{for(let[N,P]of d)O(` ${N}/ \u2192 ${P}`);eL(n,d.map(([N])=>N))}let[h,m]=n0e(o.task,s,r.readStdinTask),y={feature:"FEATURE",services:"SERVICES",issue_id:"ISSUE_ID",test_path:"TEST_PATH",description:"DESCRIPTION"};for(let[N,P]of Object.entries(y))N in o&&(m[P]=o[N]);o0e(h,m),a.init({workspaceRoot:n,workspaceName:s,repos:d,task:h,meta:m,inputs:o,configOverride:e.config??null,issue:u,isCreate:!!r.issue});for(let N of Tr)N!==a.id&&vP(n,h_(N),a,!!e.prune_context);let[g,x]=Fr(),v=Et(),S=zh(d,m,g,x,v),w=uw();for(let N of cB(v,w))I(N);let E=(m.FEATURE??"").trim(),k=lB(n,aB(S,v),w,E?{FEATURE:E}:{});k&&F(`Wrote ${k}`);for(let N of Bx())I(N);let T=ue.join(n,".env");oL(T,m),F(`Wrote ${T}`);let R=(m.FEATURE??"").trim();if(R&&await uL(R,m.SERVICES??"",n,(m.TEST_PATH??"").trim(),d.map(([P])=>P))!==null){O("Building Docker images (--no-start)...");let P=$i();w_();let L=V(y_(R,["up","--build","--no-start"]),{cwd:n,...P?{stdio:"inherit"}:{capture:!0}});P||(L.stdout&&X(L.stdout),L.stderr&&X(L.stderr,"stderr")),L.status===0?F("Docker images built successfully."):I("docker compose build exited non-zero \u2014 images may be incomplete.")}X(`
1209
+ The workspaces root comes from ~/.sandbox/config.yaml \u2014 run \`sandbox config\` to set it (or \`sandbox config --check\` to verify). See docs/known-issues.md for details.${b.RESET}`)}function e0e(e){let t=[],r=e;for(;;){let n=ue.dirname(r);if(n===r)break;t.push(n),r=n}return t}function hB(e){let r=V(["git","-C",e,"branch","--show-current"],{capture:!0}).stdout.trim();return r||V(["git","-C",e,"rev-parse","--short","HEAD"],{capture:!0}).stdout.trim()||"unknown"}function mB(e){return Wi(e).map(t=>[ue.basename(t),hB(t)])}function t0e(e){if(et.existsSync(ue.join(e,".git"))){let t=hB(e);if(t&&t!=="unknown")return t}return`${Bme()}/${ue.basename(e)}`}function r0e(e,t,r){let n=rn(),s=t.filter(h=>h!==Hn),o=new Set(s),a=new Set(mB(e).map(([h])=>h)),c=s.filter(h=>!a.has(h)),l=[...a].filter(h=>!o.has(h)).sort(),u=c.filter(h=>!Mme(ue.join(n,h)));if(u.length&&Rs(`Source repo(s) not found under ${n}: ${u.join(", ")}. Clone them there (or fix \`repos\` in .sandbox/workspace.yml) and rerun.`),l.length&&!r){let h=l.filter(m=>tL(ue.join(e,m)));h.length&&Rs(`Refusing to remove worktree(s) with uncommitted changes: ${h.join(", ")}. Commit or stash them, or rerun with --force to discard them.`)}if(!c.length&&!l.length)return;let f=t0e(e);for(let h of l){let[m,y]=uS(ue.join(n,h),ue.join(e,h),f);m?(F(`Removed worktree '${h}' (no longer in workspace.yml).`),y&&I(y)):Rs(`Could not remove worktree '${h}': ${y}`)}let d=[];try{for(let h of c){let m=ue.join(n,h),y=ue.join(e,h);lS(m,y,f,{force:r}),d.push([y,m])}}catch(h){let m=`Failed to create worktree: ${h.message}`;j(m),I("Rolling back worktrees created this run...");for(let[y,g]of[...d].reverse())uS(g,y,f);throw new kr(m)}(c.length||l.length)&&F(`Worktrees reconciled (+${c.length} / -${l.length}).`)}function n0e(e,t,r){if(e)return[e.trim(),{}];let n=r?.().trim();return n?[n,{}]:[Cw(t),{}]}function s0e(e){if(!et.existsSync(e))return;et.readFileSync(e,"utf8").includes("## Layout")?I("CLAUDE.md already initialised \u2014 overwriting with fresh content."):O("Replacing stub CLAUDE.md with full workspace context.")}function o0e(e,t){O(`Task: ${e}`);for(let[r,n]of[["FEATURE","Feature"],["SERVICES","Services"],["ISSUE_ID","Issue"],["TEST_PATH","Test path"]]){let s=t[r];s&&O(` ${(n+":").padEnd(10)} ${s}`)}}async function c6(e,t,r={}){let n=t??Zme(),s=ue.basename(n);O(`Workspace root: ${n}`);let o=ji(e,n),a=h_(Vm(o.context_strategy));!Wme(n,e.config_file??null)&&!o.feature&&Rs("No .sandbox/workspace.yml found and no --feature given. Run `sandbox workspace <name>` to create and initialise a workspace, then rerun `sandbox init-workspace` from inside it to reconcile changes."),pB(n,o);let l=o.issue_id?Oe().parseRef(o.issue_id)??o.issue_id:"",u;try{u=await Fme(n,l,{issue:r.issue,refresh:!!e.refresh_issue})}catch(N){throw N instanceof kr&&Rs(N.message),N}if(o.repos){let[N]=Fr(),[P,,L]=cS(o.repos,o.services,N);L.length&&I(`Unknown service(s) in workspace.yml (no owning repo): ${L.join(", ")}`),r0e(n,P,!!e.force)}let f=ue.join(n,"CLAUDE.md");s0e(f),O("Scanning for git repos...");let d=mB(n);if(!d.length)I("No git repos found in workspace. CLAUDE.md will have an empty layout.");else{for(let[N,P]of d)O(` ${N}/ \u2192 ${P}`);eL(n,d.map(([N])=>N))}let[h,m]=n0e(o.task,s,r.readStdinTask),y={feature:"FEATURE",services:"SERVICES",issue_id:"ISSUE_ID",test_path:"TEST_PATH",description:"DESCRIPTION"};for(let[N,P]of Object.entries(y))N in o&&(m[P]=o[N]);o0e(h,m),a.init({workspaceRoot:n,workspaceName:s,repos:d,task:h,meta:m,inputs:o,configOverride:e.config??null,issue:u,isCreate:!!r.issue});for(let N of Tr)N!==a.id&&vP(n,h_(N),a,!!e.prune_context);let[g,x]=Fr(),v=Et(),S=zh(d,m,g,x,v),w=uw();for(let N of cB(v,w))I(N);let E=(m.FEATURE??"").trim(),k=lB(n,aB(S,v),w,E?{FEATURE:E}:{});k&&F(`Wrote ${k}`);for(let N of Bx())I(N);let T=ue.join(n,".env");oL(T,m),F(`Wrote ${T}`);let R=(m.FEATURE??"").trim();if(R&&await uL(R,m.SERVICES??"",n,(m.TEST_PATH??"").trim(),d.map(([P])=>P))!==null&&r.build!==!1){O("Building Docker images (--no-start)...");let P=$i();w_();let L=V(y_(R,["up","--build","--no-start"]),{cwd:n,...P?{stdio:"inherit"}:{capture:!0}});P||(L.stdout&&X(L.stdout),L.stderr&&X(L.stderr,"stderr")),L.status===0?F("Docker images built successfully."):I("docker compose build exited non-zero \u2014 images may be incomplete.")}X(`
1210
1210
  ${b.BOLD}Workspace initialised.${b.RESET} Open a new Claude Code session from the workspace root to pick up the context.
1211
1211
 
1212
1212
  `)}async function i0e(e,t,r,n){O(`Running: sandbox init-workspace (feature: ${t})`);try{return await c6({...r,feature:t,force:n.force},e,n),0}catch(s){return s instanceof kr||j(`init-workspace failed: ${s.message}`),1}}async function gB(e,t={}){let r=(e.feature??"").trim();r||Rs("A feature name is required (pass it as an argument, set it in ./.sandbox/workspace.yml, or run interactively)."),Vm(e.context_strategy);let n=r.toLowerCase(),s=Oe();e.issue_id&&(e.issue_id=s.parseRef(e.issue_id)??e.issue_id);let o=Hme(r,e.issue_id?s.slug(e.issue_id):null);Kme.test(o)||Rs(`Workspace name '${o}' is not a valid slug (expected lowercase letters, digits, and single hyphens).`);let a=Gme(Kl.userInfo().username,o),c=ue.join(zme(),o);if(et.existsSync(c))O(`Workspace already exists: ${c} \u2014 re-running init-workspace.`);else{let u=await Qme(e.repos,e.services);e.repos=u.join(","),Jme(c,a,!!t.force),e.context_strategy||=Tr[0],pB(c,e)}let l=await i0e(c,n,e,t);if(l!==0){let u=`sandbox init-workspace exited with status ${l}. The workspace root exists at ${c}; re-run \`sandbox init-workspace\` from there once resolved.`;throw I(u),new kr(u)}return Xme(c,o),X(`
@@ -1256,7 +1256,7 @@ If the content is unusable, output <result>{}</result> and nothing else.
1256
1256
  ---
1257
1257
  Issue content:
1258
1258
  \`\`\`
1259
- `+s+"\n```"}async function v0e(e,t){let r=Oe(),n=[...new Set(e.map(l=>r.parseRef(l)).filter(l=>!!l))].sort((l,u)=>l.localeCompare(u));if(!n.length)return{};let s=i(async l=>{let u={};for(let[f,d]of Object.entries(await r.fetchIssues(l)))d.status&&(u[f]=d.status);return u},"fetchStatuses"),o={},a=[],c=[];if(t?.refresh)a.push(...n);else for(let l of n){let u=await h$(`status:${l}`);if(!u){a.push(l);continue}o[l]=u.v,Date.now()-u.at>=w0e&&c.push(l)}if(c.length&&m$(c.map(l=>`status:${l}`),async l=>{let u=await s(l.map(f=>f.slice(7)));for(let[f,d]of Object.entries(u))await Wa(`status:${f}`,d)}),a.length)for(let[l,u]of Object.entries(await s(a)))o[l]=u,await Wa(`status:${l}`,u);return o}function _0e(e){let t={};for(let r of g0e){let n=e[r];if(typeof n!="string")continue;let s=n.trim();s&&(r==="feature"&&!x0e.test(s)||(t[r]=s))}return t}function S0e(e,t){if(!Array.isArray(e)||t.length===0)return[];let r=new Set(t),n=new Set,s=[];for(let o of e){if(typeof o!="string")continue;let a=o.trim();r.has(a)&&!n.has(a)&&(n.add(a),s.push(a))}return s}async function Yx(e){try{let t=await Ne.readFile(fe.join(W(e),"workspace.yml"),"utf-8"),r=(0,mp.parse)(t),n=on(r)||null,s=Array.isArray(r?.labels)?r.labels.filter(f=>typeof f=="string"):[],o=i(f=>typeof f=="string"&&f.trim()?f.trim():null,"str"),a=o(r?.model),c=rs(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:rs(l);return{issueId:n,labels:s,model:a,autonomous:c,autoStop:u,task:o(r?.task),workType:o(r?.work_type)}}catch{return{issueId:null,labels:[],model:null,autonomous:!1,autoStop:!1,task:null,workType:null}}}async function Bl(){let e=Ms(),t;try{t=await Ne.readdir(e,{withFileTypes:!0})}catch(s){throw new K(`Could not read workspaces root ${e}: ${s.message}`)}let r=t.filter(s=>s.isDirectory()&&!s.name.startsWith(".")).map(s=>s.name).sort((s,o)=>s.localeCompare(o)),n=await Promise.all(r.map(async s=>{let o=fe.join(e,s),{issueId:a,labels:c,model:l,task:u,workType:f}=await Yx(o);return{name:s,path:o,vscodeUri:`vscode://file${o.split(fe.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?Oe().url(a):null,labels:c,model:l,task:u,workType:f,lifecycle:Ha(o).state}}));return{root:e,workspaces:n}}async function k0e(){let e;try{e=Il(LR({},Hl.homedir(),{defaults:!1}))}catch(n){throw new K(`Could not build the workspace form: ${n.message}`)}let t=e.uiSchema??{},r=t.issue_id??{};return t.issue_id={...r,"ui:options":{...r["ui:options"]??{},trackerLabel:Oe().label}},{schema:e.schema,uiSchema:t,formData:e.formData,title:e.title??"Initialize workspace"}}function xB(e){return"--"+e.replace(/_/g,"-")}function CB(e){let t=String(e.feature??"").trim();if(!t)throw new K("A feature name is required (pass it as an argument, set it in ./.sandbox/workspace.yml, or run interactively).");let r=["workspace",t];for(let[n,s]of Object.entries(e)){if(n==="feature"||E0e.has(n))continue;if(s===!0){r.push(xB(n));continue}if(s===!1)continue;let o;if(Array.isArray(s))o=s.map(a=>String(a).trim()).filter(Boolean).join(",");else{if(s==null)continue;o=String(s).trim()}o&&r.push(xB(n),o)}return r}async function O0e(){for(let e of $0e)if(await Pi(e))return e;return null}async function NB(e){let t=await O0e();if(!t)return{opened:!1,note:"VS Code CLI ('code') not found \u2014 open the workspace folder manually."};try{return _B(t,[e],{detached:!0,stdio:"ignore"}).unref(),{opened:!0}}catch(r){return{opened:!1,note:`Could not launch VS Code: ${r.message}`}}}async function zx(e,t=qu){let r=kc({ref:e.ref,title:e.title,status:e.status,description:e.body,url:e.url??void 0,comments:e.comments}),n=null;try{n=await t(await RB(e.ref,r))}catch(a){return{fields:{},warning:a.message}}if(n===null)return{fields:{},warning:"the model gave no answer"};let s=await w6({},n),o={};for(let a of T0e){let c=s[a];typeof c=="string"&&c.trim()?o[a]=c.trim():Array.isArray(c)&&c.length&&(o[a]=c.map(String).join(","))}return Object.keys(o).length?{fields:o,warning:null}:{fields:o,warning:"the answer held no usable fields"}}async function PB(e,t={}){let r=ji(e,t.cwd??Hl.homedir());if(!r.issue_id)return{resolved:r,issue:null};let n=Oe(),s=n.parseRef(r.issue_id);if(!s)throw new K(`${r.issue_id} isn't a ${n.label} issue ref (e.g. ${n.refExample})`);r.issue_id=s;let o=t.issue??null;if(!o)try{o=await Fl(s)}catch(a){if(a instanceof Va){let c=await n.checkAuth(),l=c.ok?"run `sandbox connect` to check the issue tracker":`${n.label}: ${c.reason}; run: ${c.fix}`;throw new K(`${a.message}; ${l}.`)}throw a}if(!r.task&&o.title&&(r.task=o.title),t.distill!==!1&&(!r.description||!r.starting_prompt)){let{fields:a,warning:c}=await zx(o,t.distill??qu);for(let l of["description","starting_prompt"])!r[l]&&a[l]&&(r[l]=a[l]);c&&I(`description/starting_prompt not filled from the issue: ${c}`)}return{resolved:r,issue:o}}async function v6(e,t={}){let n=`sandbox ${CB(e).join(" ")}`,s=i(async()=>{let{resolved:f,issue:d}=await PB(e,t);return gB(f,{issue:d??void 0,readStdinTask:t.readStdinTask,force:t.force})},"run"),o=dc(t.onData),a;try{a=t.live?await s():await Ao(o,s)}catch(f){if(t.live)throw f instanceof kr?f:new K(f.message);let d=De(o.text().trim())||f.message;throw new K(`${n} failed:
1259
+ `+s+"\n```"}async function v0e(e,t){let r=Oe(),n=[...new Set(e.map(l=>r.parseRef(l)).filter(l=>!!l))].sort((l,u)=>l.localeCompare(u));if(!n.length)return{};let s=i(async l=>{let u={};for(let[f,d]of Object.entries(await r.fetchIssues(l)))d.status&&(u[f]=d.status);return u},"fetchStatuses"),o={},a=[],c=[];if(t?.refresh)a.push(...n);else for(let l of n){let u=await h$(`status:${l}`);if(!u){a.push(l);continue}o[l]=u.v,Date.now()-u.at>=w0e&&c.push(l)}if(c.length&&m$(c.map(l=>`status:${l}`),async l=>{let u=await s(l.map(f=>f.slice(7)));for(let[f,d]of Object.entries(u))await Wa(`status:${f}`,d)}),a.length)for(let[l,u]of Object.entries(await s(a)))o[l]=u,await Wa(`status:${l}`,u);return o}function _0e(e){let t={};for(let r of g0e){let n=e[r];if(typeof n!="string")continue;let s=n.trim();s&&(r==="feature"&&!x0e.test(s)||(t[r]=s))}return t}function S0e(e,t){if(!Array.isArray(e)||t.length===0)return[];let r=new Set(t),n=new Set,s=[];for(let o of e){if(typeof o!="string")continue;let a=o.trim();r.has(a)&&!n.has(a)&&(n.add(a),s.push(a))}return s}async function Yx(e){try{let t=await Ne.readFile(fe.join(W(e),"workspace.yml"),"utf-8"),r=(0,mp.parse)(t),n=on(r)||null,s=Array.isArray(r?.labels)?r.labels.filter(f=>typeof f=="string"):[],o=i(f=>typeof f=="string"&&f.trim()?f.trim():null,"str"),a=o(r?.model),c=rs(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:rs(l);return{issueId:n,labels:s,model:a,autonomous:c,autoStop:u,task:o(r?.task),workType:o(r?.work_type)}}catch{return{issueId:null,labels:[],model:null,autonomous:!1,autoStop:!1,task:null,workType:null}}}async function Bl(){let e=Ms(),t;try{t=await Ne.readdir(e,{withFileTypes:!0})}catch(s){throw new K(`Could not read workspaces root ${e}: ${s.message}`)}let r=t.filter(s=>s.isDirectory()&&!s.name.startsWith(".")).map(s=>s.name).sort((s,o)=>s.localeCompare(o)),n=await Promise.all(r.map(async s=>{let o=fe.join(e,s),{issueId:a,labels:c,model:l,task:u,workType:f}=await Yx(o);return{name:s,path:o,vscodeUri:`vscode://file${o.split(fe.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?Oe().url(a):null,labels:c,model:l,task:u,workType:f,lifecycle:Ha(o).state}}));return{root:e,workspaces:n}}async function k0e(){let e;try{e=Il(LR({},Hl.homedir(),{defaults:!1}))}catch(n){throw new K(`Could not build the workspace form: ${n.message}`)}let t=e.uiSchema??{},r=t.issue_id??{};return t.issue_id={...r,"ui:options":{...r["ui:options"]??{},trackerLabel:Oe().label}},{schema:e.schema,uiSchema:t,formData:e.formData,title:e.title??"Initialize workspace"}}function xB(e){return"--"+e.replace(/_/g,"-")}function CB(e){let t=String(e.feature??"").trim();if(!t)throw new K("A feature name is required (pass it as an argument, set it in ./.sandbox/workspace.yml, or run interactively).");let r=["workspace",t];for(let[n,s]of Object.entries(e)){if(n==="feature"||E0e.has(n))continue;if(s===!0){r.push(xB(n));continue}if(s===!1)continue;let o;if(Array.isArray(s))o=s.map(a=>String(a).trim()).filter(Boolean).join(",");else{if(s==null)continue;o=String(s).trim()}o&&r.push(xB(n),o)}return r}async function O0e(){for(let e of $0e)if(await Pi(e))return e;return null}async function NB(e){let t=await O0e();if(!t)return{opened:!1,note:"VS Code CLI ('code') not found \u2014 open the workspace folder manually."};try{return _B(t,[e],{detached:!0,stdio:"ignore"}).unref(),{opened:!0}}catch(r){return{opened:!1,note:`Could not launch VS Code: ${r.message}`}}}async function zx(e,t=qu){let r=kc({ref:e.ref,title:e.title,status:e.status,description:e.body,url:e.url??void 0,comments:e.comments}),n=null;try{n=await t(await RB(e.ref,r))}catch(a){return{fields:{},warning:a.message}}if(n===null)return{fields:{},warning:"the model gave no answer"};let s=await w6({},n),o={};for(let a of T0e){let c=s[a];typeof c=="string"&&c.trim()?o[a]=c.trim():Array.isArray(c)&&c.length&&(o[a]=c.map(String).join(","))}return Object.keys(o).length?{fields:o,warning:null}:{fields:o,warning:"the answer held no usable fields"}}async function PB(e,t={}){let r=ji(e,t.cwd??Hl.homedir());if(!r.issue_id)return{resolved:r,issue:null};let n=Oe(),s=n.parseRef(r.issue_id);if(!s)throw new K(`${r.issue_id} isn't a ${n.label} issue ref (e.g. ${n.refExample})`);r.issue_id=s;let o=t.issue??null;if(!o)try{o=await Fl(s)}catch(a){if(a instanceof Va){let c=await n.checkAuth(),l=c.ok?"run `sandbox connect` to check the issue tracker":`${n.label}: ${c.reason}; run: ${c.fix}`;throw new K(`${a.message}; ${l}.`)}throw a}if(!r.task&&o.title&&(r.task=o.title),t.distill!==!1&&(!r.description||!r.starting_prompt)){let{fields:a,warning:c}=await zx(o,t.distill??qu);for(let l of["description","starting_prompt"])!r[l]&&a[l]&&(r[l]=a[l]);c&&I(`description/starting_prompt not filled from the issue: ${c}`)}return{resolved:r,issue:o}}async function v6(e,t={}){let n=`sandbox ${CB(e).join(" ")}`,s=i(async()=>{let{resolved:f,issue:d}=await PB(e,t);return gB(f,{issue:d??void 0,readStdinTask:t.readStdinTask,force:t.force,build:t.build})},"run"),o=dc(t.onData),a;try{a=t.live?await s():await Ao(o,s)}catch(f){if(t.live)throw f instanceof kr?f:new K(f.message);let d=De(o.text().trim())||f.message;throw new K(`${n} failed:
1260
1260
  ${d}`)}let c=De(o.text().trim()),l=!1,u;return(t.open??!0)&&a&&await Gx(a)?{opened:l,note:u}=await NB(a):(t.open??!0)&&(u="Could not determine the workspace path to open."),{command:n,output:c,workspacePath:a,opened:l,openNote:u}}async function Ts(e){let t=(e??"").trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new K(`Invalid workspace name: ${JSON.stringify(e)}`);let r=fe.join(Ms(),t);if(!await Gx(r))throw new K(`No such workspace: ${t}`);return r}function A0e(e){let t=e.slice(_6.length);if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new K(`Invalid reconcile session: ${JSON.stringify(e)}`);return fe.join(IB(),t)}async function gp(e){if((e??"").startsWith(_6)){let t=A0e(e);if(!await Gx(t))throw new K(`No such reconcile session: ${e}`);return t}return Ts(e)}async function S6(e){let t=await Ts(e),{opened:r,note:n}=await NB(t);if(!r)throw new K(n??"Could not launch VS Code.");return{path:t}}async function hp(e,t){try{let r=await Ne.readFile(fe.join(e,".env"),"utf-8");for(let n of r.split(/\r?\n/)){let s=n.indexOf("=");if(s>0&&n.slice(0,s).trim()===t)return n.slice(s+1).trim()}}catch{}return null}async function R0e(e){try{let t=await Ne.readFile(fe.join(W(e),"workspace.yml"),"utf-8"),r=/^feature: *["']?([^"'\s#]+)/m.exec(t);return r?r[1]:null}catch{return null}}async function LB(e){let t=await Ne.readdir(fe.join(e,"stages")).catch(()=>null);if(!t)return null;let r=t.filter(n=>/^\d+_/.test(n)).sort();for(let n=0;n<r.length;n++)if(!(await Ne.readdir(fe.join(e,"stages",r[n],"output")).catch(()=>[])).some(o=>!o.startsWith(".")))return{index:n+1,total:r.length,name:r[n].replace(/^\d+_/,"")};return null}function C0e(e){let t;try{t=Vo(e)}catch{return null}for(let r of t.reverse()){let n=r.frontmatter.phase;if(typeof n=="string"&&n.trim())return n.trim()}return null}async function P0e(e,t=131072){let r=await Ne.open(e,"r");try{let{size:n}=await r.stat(),s=Math.max(0,n-t),o=Buffer.alloc(n-s);await r.read(o,0,o.length,s);let a=o.toString("utf-8");if(s>0){let c=a.indexOf(`
1261
1261
  `);c>=0&&(a=a.slice(c+1))}return a}finally{await r.close()}}async function I0e(e,t){let r=await Ga(e).catch(()=>null),n=r?.updatedAt??null,s=O6.get(e)?.state??"idle",o=i((l,u=n,f=null)=>({signal:{state:s,agent:l,at:u,question:f},lastActivity:n}),"signal");if(s==="running")return o("working");let a=l$(t);if(a)return o(a.state,a.at,a.question??null);let c;try{r?.sessionFile&&(c=$6(await P0e(r.sessionFile)).at(-1))}catch{}return!c||!n?o("idle"):c.role==="assistant"?u$(c.text)?o("needs-you",n,f$(c.text)):o("done"):o(Date.now()-Date.parse(n)<N0e?"working":"idle")}function yB(e){return e.health==="healthy"?"healthy":e.health==="starting"?"starting":e.health==="unhealthy"?"unhealthy":e.state==="running"?"running":"down"}function DB(e){let t=new Map;for(let{service:r,state:n,health:s,labels:o,exitCode:a}of e){let c=o["com.docker.compose.project"];if(!c)continue;let l=n==="exited"&&a===0;if(vf(r,o["com.sandbox.local.role"])&&l)continue;let u=t.get(c)??{running:0,total:0,services:[],slot:null};u.total++,n==="running"&&u.running++,u.services.push({name:r,state:n,health:s});let f=o["com.sandbox.local.slot"];if(u.slot===null&&f){let d=Number.parseInt(f,10);Number.isInteger(d)&&(u.slot=d)}t.set(c,u)}return t}async function L0e(){let e=await pr();return e?{tallies:DB(e),health:await $0(e)}:null}async function D0e(){let e=await x6(Co());if(!e)return null;try{return(0,mp.parse)(await Ne.readFile(e,"utf8"))??null}catch{return null}}function j0e(e,t){let[r,n]=Sh(e,t);return`${r}-${n}`}async function jB(){let e=Ms(),r=(await Ne.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),n=await L0e(),s=n?.tallies??null,o=await D0e(),a=await Promise.all(r.map(async l=>{let u=fe.join(e,l),f=await hp(u,"COMPOSE_PROJECT_NAME");if(!f){let R=await R0e(u);f=R?`sandbox-${R}`:null}let{signal:d,lastActivity:h}=await I0e(l,u),{model:m,autonomous:y,autoStop:g}=await Yx(u),x={claude:d,model:m,stage:await LB(u),phase:C0e(u),autonomous:y,autoStop:g,lastActivity:h};if(s===null)return{name:l,project:f,state:"unknown",running:0,total:0,slot:null,ports:null,services:[],...x,started:null,crashLoops:[]};let v=f?s.get(f):void 0,S=f?n?.health.get(f):void 0,w;!v||v.total===0?w="down":v.running===v.total?w="up":v.running>0?w="partial":w="stopped";let E=v?.slot??null,k=E!==null?j0e(E,o):null,T=(v?.services??[]).map(R=>({name:R.name,state:yB(R)}));return{name:l,project:f,state:w,running:v?.running??0,total:v?.total??0,slot:E,ports:k,services:T,...x,started:S?.started??null,crashLoops:S?.crashLoops??[]}})),c;if(s===null)c={state:"unknown",running:0,total:0,services:[]};else{let l=s.get(hr),u=l?.running??0,f=l?.total??0,d=f===0?"down":u===f?"up":u>0?"partial":"down",h=(l?.services??[]).map(m=>({name:m.name,state:yB(m)}));c={state:d,running:u,total:f,services:h}}return{statuses:a,infra:c}}async function F0e(e){let t=[],r=await Ne.readdir(fe.join(e,"stages")).catch(()=>[]);for(let n of r.sort()){let s=fe.join("stages",n,"output"),o=await Ne.readdir(fe.join(e,s)).catch(()=>[]);for(let a of o.sort()){if(!a.endsWith(".md"))continue;let c=await Ne.readFile(fe.join(e,s,a),"utf-8").catch(()=>"");/^status: proposed/m.test(c)&&t.push(fe.join(s,a))}}return t}async function M0e(e){let t=new Date,[{root:r,workspaces:n},{statuses:s}]=await Promise.all([Bl(),jB()]),o=fe.join(r,".check-in-last"),a=await Ne.stat(o).then(m=>Math.round(m.mtimeMs),()=>null),c=n.some(m=>m.labels.includes("focus")),l=i(m=>!m.labels.includes("skip")&&(!c||m.labels.includes("focus")),"keep"),u=new Map(s.map(m=>[m.name,m])),f=n.filter(l);await _3(f.map(m=>m.path),e);let d=await Promise.all(f.map(async m=>{let y=u.get(m.name),{updatedAt:g}=await Ga(m.name).catch(()=>({updatedAt:null})),x=Ha(m.path);return{name:m.name,issueId:m.issueId,labels:m.labels,containers:y?.state??"unknown",claude:y?.claude??{state:"idle",agent:"idle",at:null,question:null},gates:await F0e(m.path),updatedAt:g,changed:a!==null&&g!==null&&Date.parse(g)>a,lifecycle:x.state,prs:x.prs.map(v=>({repo:v.dir,url:v.url,status:v.status,release:v.release}))}}));await Ne.writeFile(o,"",{flag:"a"}),await Ne.utimes(o,t,t);let h=d.filter(m=>(m.lifecycle==="shipped"||m.lifecycle==="abandoned")&&m.claude.agent!=="working").map(m=>m.name);return{root:r,since:a===null?null:new Date(a).toISOString(),workspaces:d,dropped:n.filter(m=>!l(m)).map(m=>m.name),candidates:d.filter(m=>m.claude.agent!=="working"&&!h.includes(m.name)&&(a===null?m.claude.agent==="needs-you"||m.claude.agent==="done":m.gates.length>0||m.changed)).map(m=>m.name),readyToClose:h}}async function B0e(){let e=await W0(),t=new Map;for(let r of e.intercepts){let n=t.get(r.feature);n||t.set(r.feature,n=new Map),n.set(r.service,r)}return{available:e.available,installed:e.installed,connectedNamespace:e.connected_namespace,byFeature:t,remoteServices:new Set(e.remote_services)}}async function FB(e){try{return await Ne.access(fe.join(e,".git")),!0}catch{return!1}}async function ql(e){let t=await Ne.readdir(e,{withFileTypes:!0}).catch(()=>[]),r=[];for(let n of t){if(!n.isDirectory()||n.name.startsWith("."))continue;let s=fe.join(e,n.name);await FB(s)&&r.push({repo:n.name,dir:s})}return r}async function q0e(e){let t=null,r=await ut("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null);r&&r.code===0&&(t=De(r.stdout).trim()||null);let n={branch:t,url:null,state:null,title:null,labels:[],...d6(void 0)};if(!t||t==="HEAD")return n;let s=await ut("gh",["pr","list","--head",t,"--state","all","--json","url,state,title,labels,statusCheckRollup,isDraft","--limit","1"],e).catch(()=>null);if(s?.code!==0)return n;try{let o=JSON.parse(De(s.stdout).trim()||"[]");if(!o.length)return n;let a=(o[0].state??"").toUpperCase(),c=a==="OPEN"||a==="MERGED"||a==="CLOSED"?a:null,l=(o[0].labels??[]).map(u=>u.name??"").filter(Boolean);return{branch:t,url:o[0].url??null,state:c,title:o[0].title??null,labels:l,...d6(o[0].statusCheckRollup),draft:o[0].isDraft===!0}}catch{return n}}async function U0e(){let e=Ms(),r=(await Ne.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort((n,s)=>n.localeCompare(s));return Promise.all(r.map(async n=>{let s=await ql(fe.join(e,n)),o=await Promise.all(s.map(async({repo:a,dir:c})=>({repo:a,...await q0e(c)})));return{name:n,repos:o}}))}async function W0e(e){let t=Ye("REVIEW_SLACK_TOKEN"),r=Ye("REVIEW_SLACK_CHANNEL");if(!t||!r)throw new K("Slack is not configured: set SANDBOX_REVIEW_SLACK_TOKEN (a bot token with chat:write) and SANDBOX_REVIEW_SLACK_CHANNEL (the review channel id).");let s=await(await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({channel:r,text:e})}).catch(o=>{throw new K(`Slack request failed: ${o.message}`)})).json().catch(()=>({}));if(!s.ok)throw new K(`Slack rejected the message: ${s.error??"unknown error"}`);return r}function MB(e){return e.reviewDecision==="APPROVED"?"APPROVED":e.reviewDecision==="CHANGES_REQUESTED"?"CHANGES_REQUESTED":(e.latestReviews??[]).some(t=>t.state==="DISMISSED")?"DISMISSED":"PENDING"}function E6(e){if(!Array.isArray(e))return 0;let t=0;for(let r of e){if(!r||typeof r!="object")continue;let n=r,s=String(n.conclusion??n.state??"").toUpperCase();V0e.has(s)&&t++}return t}function d6(e){if(!Array.isArray(e)||e.length===0)return{ci:null,failingChecks:0};let t=E6(e);return t>0?{ci:"fail",failingChecks:t}:{ci:e.some(n=>{let s=n??{},o=String(s.status??"").toUpperCase();if(o)return o!=="COMPLETED";let a=String(s.state??"").toUpperCase();return a==="PENDING"||a==="EXPECTED"})?"running":"pass",failingChecks:0}}function BB(e,t){if(!e)return!0;let r=Date.parse(e);return Number.isNaN(r)?!0:t-r<K0e}function qB(e){try{let t=new URL(e).pathname.split("/").filter(Boolean);return{repo:t[1]??"",number:Number.parseInt(t[3]??"",10)||0}}catch{return{repo:"",number:0}}}function p6(e,t){let{repo:r,number:n}=qB(e.url);if("unavailable"in e)return{url:e.url,repo:r,number:n,title:"(details unavailable)",author:"",body:"",labels:[],reviewStatus:"PENDING",failingChecks:0,outOfDate:!1,hasApprovalLabel:!1,issueId:null,issueUrl:null,isDraft:!1};let s=(e.labels??[]).map(u=>u.name??"").filter(Boolean),o=e.title??"",a=e.body??"",c=Oe(),l=c.parseRef(`${o} ${a} ${e.headRefName??""}`);return{url:e.url,repo:r,number:n,title:o,author:e.author?.login??"",body:a,labels:s,reviewStatus:MB(e),failingChecks:E6(e.statusCheckRollup),outOfDate:e.mergeStateStatus==="BEHIND",hasApprovalLabel:s.includes(k6),issueId:l,issueUrl:l?c.url(l):null,isDraft:e.isDraft??!1}}function UB(e,t,r,n){let s=i(c=>c.filter(l=>BB("unavailable"in l?void 0:l.updatedAt,n)),"fresh"),o=s(e).map(c=>p6(c,r)),a=s(t).map(c=>p6(c,r)).filter(c=>c.author!==r);return{me:r,mine:o,others:a}}async function H0e(){let e=await ut("gh",["api","user","--jq",".login"]).catch(()=>null),t=e&&e.code===0?De(e.stdout).trim():"";if(!t)throw new K("Could not resolve GitHub user (`gh api user`). Is `gh` authenticated?");return t}async function bB(e){let t=await ut("gh",["search","prs","--owner=sandbox","--state=open",...e,"--json","url","--limit","100"]).catch(r=>{throw new K(`gh search prs failed: ${r.message}`)});if(t.code!==0)throw new K(`gh search prs failed: ${De(t.stderr).trim()||`exit ${t.code}`}`);try{return JSON.parse(De(t.stdout).trim()||"[]").map(n=>n.url).filter(n=>!!n)}catch{return[]}}async function h6(e){let t=await ut("gh",["pr","view",e,"--json","reviewDecision,latestReviews,mergeStateStatus,statusCheckRollup,labels,author,number,title,body,headRefName,updatedAt,url,isDraft"]).catch(()=>null);if(t?.code!==0)return{url:e,unavailable:!0};try{return JSON.parse(De(t.stdout).trim())}catch{return{url:e,unavailable:!0}}}async function G0e(){let e=await H0e(),[t,r]=await Promise.all([bB(["--author=@me"]),bB([`--label=${k6}`])]),[n,s]=await Promise.all([Promise.all(t.map(h6)),Promise.all(r.map(h6))]);return UB(n,s,e,Date.now())}async function Y0e(e){let t=await ut("gh",["pr","review",e,"--approve"]).catch(r=>{throw new K(`gh pr review failed: ${r.message}`)});if(t.code!==0)throw new K(`gh pr review failed: ${De(t.stderr).trim()||`exit ${t.code}`}`);return{ok:!0}}async function WB(e){let t=Oe(),r=t.parseRef(e);return r?await g$(`issue-card:${r}`,z0e,async()=>await t.fetchIssue(r)??void 0)??{ref:r,url:t.url(r)??void 0}:{ref:""}}async function J0e(e){let t=[e,...(await ql(e)).map(n=>n.dir)],r=[];for(let n of t)await FB(n)&&r.push(n);return r}async function Cx(e){let t=new Set;for(let r of e){let n=await ut("git",["-C",r,"rev-parse","--path-format=absolute","--git-common-dir"]).catch(()=>null);if(n&&n.code===0){let s=De(n.stdout).trim();s&&t.add(fe.dirname(s))}}return[...t]}function wB(e){let t=De(e).trim().split(`
1262
1262
  `);return(t.find(r=>/^\s*!\s|^(error|fatal):/.test(r))??t[0]).trim().replace(/\s+/g," ")}async function Nx(e,t=`chore: handoff ${fe.basename(e)} before workspace teardown`,r=[]){let n=fe.basename(e),s=await ut("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null),o=s&&s.code===0?De(s.stdout).trim():null;if(!o||o==="HEAD")return{ok:!1,message:`${n}: no branch to push (detached HEAD)`};let a=r.length?["--",...r]:[];await ut("git",["-C",e,"add","-A",...a]).catch(()=>{});let c=await ut("git",["-C",e,"diff","--cached","--quiet",...a]).catch(()=>null);if(c&&c.code===1){let d=await ut("git",["-C",e,"commit","-m",t,...a]).catch(()=>null);if(d?.code!==0)return{ok:!1,message:`${n}: commit failed \u2014 ${d?wB(d.stderr||d.stdout):"spawn error"}`}}let l=`origin/${o}`;if((await ut("git",["-C",e,"rev-parse","--verify","--quiet",l]).catch(()=>null))?.code===0){let d=await ut("git",["-C",e,"rev-list","--count",`${l}..HEAD`]).catch(()=>null);if(d&&d.code===0&&De(d.stdout).trim()==="0")return{ok:!0,message:`${n}: nothing to hand off (${o} already on origin)`}}let f=await ut("git",["-C",e,"push","-u","origin",o]).catch(()=>null);return f?.code!==0?{ok:!1,message:`${n}: push failed \u2014 ${f?wB(f.stderr||f.stdout):"spawn error"}`}:{ok:!0,message:`${n}: pushed ${o}`}}async function tp(e,t={}){let r=await Ts(e);if(!t.closedOut){let l=await S3(r,await ql(r));if(l.length&&!t.abandon?.trim())throw new K(`Workspace '${e}' NOT removed \u2014 it holds unshipped work:
package/dist/mcp.js CHANGED
@@ -1056,7 +1056,7 @@ ${c.join(`
1056
1056
  # Format: YAML \u2014 line comments (\`#\`) are supported. The loader also
1057
1057
  # accepts legacy JSONC and JSON for back-compat.
1058
1058
  `;function Hie(e,t){if(Object.keys(t).length===0)return;let r=ee(e),i=Re.join(r,Ja[0]),n=Ja.slice(1).map(u=>Re.join(r,u)),o={};for(let u of[i,...n])if(Rt.existsSync(u)&&Rt.statSync(u).isFile())try{let p=dd(u);if(typeof p=="object"&&p!==null&&!Array.isArray(p)){o=p;break}}catch{}delete o._generator,delete o.$schema;let a={...o};for(let[,,u]of fd)if(u in t){let p=t[u];if(MMe.has(u)&&typeof p=="string"&&(p=FMe(p)),(u==="autonomous"||u==="auto_stop")&&(p=p==="true"),u==="auto_stop"&&p===!1&&!(u in o))continue;a[u]=p}let c=Zie.stringify(a,{sortMapEntries:!0,blockQuote:"literal"}),l=UMe+c;if(!(Rt.existsSync(i)&&Rt.readFileSync(i,"utf8")===l)){Rt.mkdirSync(r,{recursive:!0}),Rt.writeFileSync(i,l),X(`Persisted inputs to ${i}`);for(let u of n)Rt.existsSync(u)&&(Rt.unlinkSync(u),j(`Removed legacy ${Re.basename(u)} (superseded by workspace.yml)`))}}s(Hie,"writeWorkspaceConfig");var BMe=/^[a-z0-9]+(-[a-z0-9]+)*$/;function ZMe(e,t){let r=(e||"").trim().toLowerCase(),i=(t||"").trim().toLowerCase();return i?`${i}-${r}`:r}s(ZMe,"buildWorkspaceName");function HMe(e,t){return`${e}/${t}`}s(HMe,"buildBranchName");function VMe(){return gs()}s(VMe,"resolveReposRoot");function WMe(){let e=Hk().workspaces_root;return e?Re.resolve(kn(e)):Re.resolve(Re.join(Rd.homedir(),"workspace"))}s(WMe,"resolveWorkspacesRoot");function KMe(e,t,r){let i=VMe(),n=Re.join(i,lv);if(j(`Workspace: ${e}`),j(`Branch: ${t}`),Rt.existsSync(Re.join(n,".git"))){try{X2(n,e,t,{force:r})}catch(o){Fo(`Failed to create workspace root worktree: ${o.message}`)}X(`Created workspace root (worktree of ${lv}) at ${e}`)}else Z(`No '${lv}' repo at ${n} \u2014 workspace root will be a plain directory (no git history for notes/config).`),Rt.mkdirSync(e,{recursive:!0})}s(KMe,"createWorkspaceRoot");function GMe(e,t){if(Rt.existsSync(Re.join(e,".git")))try{if(te(["git","-C",e,"add","-A"],{capture:!0,check:!0}),te(["git","-C",e,"diff","--cached","--quiet"],{capture:!0}).status===0)return;te(["git","-C",e,"commit","-q","-m",`chore: initialize workspace ${t}`],{capture:!0,check:!0}),X("Committed initial workspace state (branch not pushed \u2014 push when ready).")}catch(r){Z(`Could not commit initial workspace state: ${r.message}`)}}s(GMe,"commitWorkspaceState");async function JMe(e,t){let r=Ye(),[i,,n]=Y2(e??null,t??null,r);return n.length&&Fo(`Unknown service(s): ${n.join(", ")}. See \`sandbox services\` / config/services.yaml.`),i.length||Fo("No repos selected. Choose at least one service or repo in the wizard, or pass --services svc1,svc2 / --repos r1,r2."),i}s(JMe,"selectRepos");function Bie(){let e=[],t=Hk().workspaces_root;t&&e.push(Re.resolve(Es(t))),e.push(Re.join(Rd.homedir(),"workspace"));let r=new Set,i=[];for(let n of e)r.has(n)||(r.add(n),i.push(n));return i}s(Bie,"candidateWorkspaceRoots");function YMe(){let e=Re.resolve(process.cwd());for(let r of Bie()){let i=Re.relative(r,e);if(!(i===".."||i.startsWith(".."+Re.sep)||Re.isAbsolute(i))&&i!=="")return Re.join(r,i.split(Re.sep)[0])}for(let r of[e,...XMe(e)])if(Rt.existsSync(Re.join(r,".git")))return Re.dirname(r);let t=Bie().join(", ");throw new LL(`${wt.RED}[err] Not inside a sandbox workspace (checked: ${t}) and no parent \`.git\` directory found.
1059
- The workspaces root comes from ~/.sandbox/config.yaml \u2014 run \`sandbox config\` to set it (or \`sandbox config --check\` to verify). See docs/known-issues.md for details.${wt.RESET}`)}s(YMe,"findWorkspaceRoot");function XMe(e){let t=[],r=e;for(;;){let i=Re.dirname(r);if(i===r)break;t.push(i),r=i}return t}s(XMe,"ancestors");function Vie(e){let r=te(["git","-C",e,"branch","--show-current"],{capture:!0}).stdout.trim();return r||te(["git","-C",e,"rev-parse","--short","HEAD"],{capture:!0}).stdout.trim()||"unknown"}s(Vie,"getBranch");function Wie(e){return ul(e).map(t=>[Re.basename(t),Vie(t)])}s(Wie,"discoverRepos");function QMe(e){if(Rt.existsSync(Re.join(e,".git"))){let t=Vie(e);if(t&&t!=="unknown")return t}return`${zMe()}/${Re.basename(e)}`}s(QMe,"workspaceBranch");function eFe(e,t,r){let i=gs(),n=t.filter(m=>m!==lv),o=new Set(n),a=new Set(Wie(e).map(([m])=>m)),c=n.filter(m=>!a.has(m)),l=[...a].filter(m=>!o.has(m)).sort(),u=c.filter(m=>!LMe(Re.join(i,m)));if(u.length&&Fo(`Source repo(s) not found under ${i}: ${u.join(", ")}. Clone them there (or fix \`repos\` in .sandbox/workspace.yml) and rerun.`),l.length&&!r){let m=l.filter(h=>Kte(Re.join(e,h)));m.length&&Fo(`Refusing to remove worktree(s) with uncommitted changes: ${m.join(", ")}. Commit or stash them, or rerun with --force to discard them.`)}if(!c.length&&!l.length)return;let p=QMe(e);for(let m of l){let[h,v]=Q2(Re.join(i,m),Re.join(e,m),p);h?(X(`Removed worktree '${m}' (no longer in workspace.yml).`),v&&Z(v)):Fo(`Could not remove worktree '${m}': ${v}`)}let d=[];try{for(let m of c){let h=Re.join(i,m),v=Re.join(e,m);X2(h,v,p,{force:r}),d.push([v,h])}}catch(m){let h=`Failed to create worktree: ${m.message}`;ue(h),Z("Rolling back worktrees created this run...");for(let[v,g]of[...d].reverse())Q2(g,v,p);throw new Hi(h)}(c.length||l.length)&&X(`Worktrees reconciled (+${c.length} / -${l.length}).`)}s(eFe,"reconcileWorktrees");function tFe(e,t,r){if(e)return[e.trim(),{}];let i=r?.().trim();return i?[i,{}]:[W2(t),{}]}s(tFe,"resolveTask");function rFe(e){if(!Rt.existsSync(e))return;Rt.readFileSync(e,"utf8").includes("## Layout")?Z("CLAUDE.md already initialised \u2014 overwriting with fresh content."):j("Replacing stub CLAUDE.md with full workspace context.")}s(rFe,"warnIfExisting");function nFe(e,t){j(`Task: ${e}`);for(let[r,i]of[["FEATURE","Feature"],["SERVICES","Services"],["ISSUE_ID","Issue"],["TEST_PATH","Test path"]]){let n=t[r];n&&j(` ${(i+":").padEnd(10)} ${n}`)}}s(nFe,"logMeta");async function zL(e,t,r={}){let i=t??YMe(),n=Re.basename(i);j(`Workspace root: ${i}`);let o=Mg(e,i),a=dL(JS(o.context_strategy));!qMe(i,e.config_file??null)&&!o.feature&&Fo("No .sandbox/workspace.yml found and no --feature given. Run `sandbox workspace <name>` to create and initialise a workspace, then rerun `sandbox init-workspace` from inside it to reconcile changes."),Hie(i,o);let l=o.issue_id?It().parseRef(o.issue_id)??o.issue_id:"",u;try{u=await DMe(i,l,{issue:r.issue,refresh:!!e.refresh_issue})}catch(P){throw P instanceof Hi&&Fo(P.message),P}if(o.repos){let[P]=Ln(),[H,,V]=Y2(o.repos,o.services,P);V.length&&Z(`Unknown service(s) in workspace.yml (no owning repo): ${V.join(", ")}`),eFe(i,H,!!e.force)}let p=Re.join(i,"CLAUDE.md");rFe(p),j("Scanning for git repos...");let d=Wie(i);if(!d.length)Z("No git repos found in workspace. CLAUDE.md will have an empty layout.");else{for(let[P,H]of d)j(` ${P}/ \u2192 ${H}`);Wte(i,d.map(([P])=>P))}let[m,h]=tFe(o.task,n,r.readStdinTask),v={feature:"FEATURE",services:"SERVICES",issue_id:"ISSUE_ID",test_path:"TEST_PATH",description:"DESCRIPTION"};for(let[P,H]of Object.entries(v))P in o&&(h[H]=o[P]);nFe(m,h),a.init({workspaceRoot:i,workspaceName:n,repos:d,task:m,meta:h,inputs:o,configOverride:e.config??null,issue:u,isCreate:!!r.issue});for(let P of On)P!==a.id&&Wne(i,dL(P),a,!!e.prune_context);let[g,y]=Ln(),w=or(),k=Bk(d,h,g,y,w),_=QG();for(let P of qie(w,_))Z(P);let $=(h.FEATURE??"").trim(),E=Uie(i,Fie(k,w),_,$?{FEATURE:$}:{});E&&X(`Wrote ${E}`);for(let P of NL())Z(P);let I=Re.join(i,".env");Xte(I,h),X(`Wrote ${I}`);let C=(h.FEATURE??"").trim();if(C&&await nre(C,h.SERVICES??"",i,(h.TEST_PATH??"").trim(),d.map(([H])=>H))!==null){j("Building Docker images (--no-start)...");let H=Dp();W4();let V=te(H4(C,["up","--build","--no-start"]),{cwd:i,...H?{stdio:"inherit"}:{capture:!0}});H||(V.stdout&&Ve(V.stdout),V.stderr&&Ve(V.stderr,"stderr")),V.status===0?X("Docker images built successfully."):Z("docker compose build exited non-zero \u2014 images may be incomplete.")}Ve(`
1059
+ The workspaces root comes from ~/.sandbox/config.yaml \u2014 run \`sandbox config\` to set it (or \`sandbox config --check\` to verify). See docs/known-issues.md for details.${wt.RESET}`)}s(YMe,"findWorkspaceRoot");function XMe(e){let t=[],r=e;for(;;){let i=Re.dirname(r);if(i===r)break;t.push(i),r=i}return t}s(XMe,"ancestors");function Vie(e){let r=te(["git","-C",e,"branch","--show-current"],{capture:!0}).stdout.trim();return r||te(["git","-C",e,"rev-parse","--short","HEAD"],{capture:!0}).stdout.trim()||"unknown"}s(Vie,"getBranch");function Wie(e){return ul(e).map(t=>[Re.basename(t),Vie(t)])}s(Wie,"discoverRepos");function QMe(e){if(Rt.existsSync(Re.join(e,".git"))){let t=Vie(e);if(t&&t!=="unknown")return t}return`${zMe()}/${Re.basename(e)}`}s(QMe,"workspaceBranch");function eFe(e,t,r){let i=gs(),n=t.filter(m=>m!==lv),o=new Set(n),a=new Set(Wie(e).map(([m])=>m)),c=n.filter(m=>!a.has(m)),l=[...a].filter(m=>!o.has(m)).sort(),u=c.filter(m=>!LMe(Re.join(i,m)));if(u.length&&Fo(`Source repo(s) not found under ${i}: ${u.join(", ")}. Clone them there (or fix \`repos\` in .sandbox/workspace.yml) and rerun.`),l.length&&!r){let m=l.filter(h=>Kte(Re.join(e,h)));m.length&&Fo(`Refusing to remove worktree(s) with uncommitted changes: ${m.join(", ")}. Commit or stash them, or rerun with --force to discard them.`)}if(!c.length&&!l.length)return;let p=QMe(e);for(let m of l){let[h,v]=Q2(Re.join(i,m),Re.join(e,m),p);h?(X(`Removed worktree '${m}' (no longer in workspace.yml).`),v&&Z(v)):Fo(`Could not remove worktree '${m}': ${v}`)}let d=[];try{for(let m of c){let h=Re.join(i,m),v=Re.join(e,m);X2(h,v,p,{force:r}),d.push([v,h])}}catch(m){let h=`Failed to create worktree: ${m.message}`;ue(h),Z("Rolling back worktrees created this run...");for(let[v,g]of[...d].reverse())Q2(g,v,p);throw new Hi(h)}(c.length||l.length)&&X(`Worktrees reconciled (+${c.length} / -${l.length}).`)}s(eFe,"reconcileWorktrees");function tFe(e,t,r){if(e)return[e.trim(),{}];let i=r?.().trim();return i?[i,{}]:[W2(t),{}]}s(tFe,"resolveTask");function rFe(e){if(!Rt.existsSync(e))return;Rt.readFileSync(e,"utf8").includes("## Layout")?Z("CLAUDE.md already initialised \u2014 overwriting with fresh content."):j("Replacing stub CLAUDE.md with full workspace context.")}s(rFe,"warnIfExisting");function nFe(e,t){j(`Task: ${e}`);for(let[r,i]of[["FEATURE","Feature"],["SERVICES","Services"],["ISSUE_ID","Issue"],["TEST_PATH","Test path"]]){let n=t[r];n&&j(` ${(i+":").padEnd(10)} ${n}`)}}s(nFe,"logMeta");async function zL(e,t,r={}){let i=t??YMe(),n=Re.basename(i);j(`Workspace root: ${i}`);let o=Mg(e,i),a=dL(JS(o.context_strategy));!qMe(i,e.config_file??null)&&!o.feature&&Fo("No .sandbox/workspace.yml found and no --feature given. Run `sandbox workspace <name>` to create and initialise a workspace, then rerun `sandbox init-workspace` from inside it to reconcile changes."),Hie(i,o);let l=o.issue_id?It().parseRef(o.issue_id)??o.issue_id:"",u;try{u=await DMe(i,l,{issue:r.issue,refresh:!!e.refresh_issue})}catch(P){throw P instanceof Hi&&Fo(P.message),P}if(o.repos){let[P]=Ln(),[H,,V]=Y2(o.repos,o.services,P);V.length&&Z(`Unknown service(s) in workspace.yml (no owning repo): ${V.join(", ")}`),eFe(i,H,!!e.force)}let p=Re.join(i,"CLAUDE.md");rFe(p),j("Scanning for git repos...");let d=Wie(i);if(!d.length)Z("No git repos found in workspace. CLAUDE.md will have an empty layout.");else{for(let[P,H]of d)j(` ${P}/ \u2192 ${H}`);Wte(i,d.map(([P])=>P))}let[m,h]=tFe(o.task,n,r.readStdinTask),v={feature:"FEATURE",services:"SERVICES",issue_id:"ISSUE_ID",test_path:"TEST_PATH",description:"DESCRIPTION"};for(let[P,H]of Object.entries(v))P in o&&(h[H]=o[P]);nFe(m,h),a.init({workspaceRoot:i,workspaceName:n,repos:d,task:m,meta:h,inputs:o,configOverride:e.config??null,issue:u,isCreate:!!r.issue});for(let P of On)P!==a.id&&Wne(i,dL(P),a,!!e.prune_context);let[g,y]=Ln(),w=or(),k=Bk(d,h,g,y,w),_=QG();for(let P of qie(w,_))Z(P);let $=(h.FEATURE??"").trim(),E=Uie(i,Fie(k,w),_,$?{FEATURE:$}:{});E&&X(`Wrote ${E}`);for(let P of NL())Z(P);let I=Re.join(i,".env");Xte(I,h),X(`Wrote ${I}`);let C=(h.FEATURE??"").trim();if(C&&await nre(C,h.SERVICES??"",i,(h.TEST_PATH??"").trim(),d.map(([H])=>H))!==null&&r.build!==!1){j("Building Docker images (--no-start)...");let H=Dp();W4();let V=te(H4(C,["up","--build","--no-start"]),{cwd:i,...H?{stdio:"inherit"}:{capture:!0}});H||(V.stdout&&Ve(V.stdout),V.stderr&&Ve(V.stderr,"stderr")),V.status===0?X("Docker images built successfully."):Z("docker compose build exited non-zero \u2014 images may be incomplete.")}Ve(`
1060
1060
  ${wt.BOLD}Workspace initialised.${wt.RESET} Open a new Claude Code session from the workspace root to pick up the context.
1061
1061
 
1062
1062
  `)}s(zL,"initWorkspace");async function iFe(e,t,r,i){j(`Running: sandbox init-workspace (feature: ${t})`);try{return await zL({...r,feature:t,force:i.force},e,i),0}catch(n){return n instanceof Hi||ue(`init-workspace failed: ${n.message}`),1}}s(iFe,"runInitWorkspace");async function Kie(e,t={}){let r=(e.feature??"").trim();r||Fo("A feature name is required (pass it as an argument, set it in ./.sandbox/workspace.yml, or run interactively)."),JS(e.context_strategy);let i=r.toLowerCase(),n=It();e.issue_id&&(e.issue_id=n.parseRef(e.issue_id)??e.issue_id);let o=ZMe(r,e.issue_id?n.slug(e.issue_id):null);BMe.test(o)||Fo(`Workspace name '${o}' is not a valid slug (expected lowercase letters, digits, and single hyphens).`);let a=HMe(Rd.userInfo().username,o),c=Re.join(WMe(),o);if(Rt.existsSync(c))j(`Workspace already exists: ${c} \u2014 re-running init-workspace.`);else{let u=await JMe(e.repos,e.services);e.repos=u.join(","),KMe(c,a,!!t.force),e.context_strategy||=On[0],Hie(c,e)}let l=await iFe(c,i,e,t);if(l!==0){let u=`sandbox init-workspace exited with status ${l}. The workspace root exists at ${c}; re-run \`sandbox init-workspace\` from there once resolved.`;throw Z(u),new Hi(u)}return GMe(c,o),Ve(`
@@ -1096,7 +1096,7 @@ If the content is unusable, output <result>{}</result> and nothing else.
1096
1096
  ---
1097
1097
  Issue content:
1098
1098
  \`\`\`
1099
- `+n+"\n```"}s(gFe,"buildIssueExtractPrompt");var vFe=5*60*1e3;async function moe(e,t){let r=It(),i=[...new Set(e.map(l=>r.parseRef(l)).filter(l=>!!l))].sort((l,u)=>l.localeCompare(u));if(!i.length)return{};let n=s(async l=>{let u={};for(let[p,d]of Object.entries(await r.fetchIssues(l)))d.status&&(u[p]=d.status);return u},"fetchStatuses"),o={},a=[],c=[];if(t?.refresh)a.push(...i);else for(let l of i){let u=await HN(`status:${l}`);if(!u){a.push(l);continue}o[l]=u.v,Date.now()-u.at>=vFe&&c.push(l)}if(c.length&&VN(c.map(l=>`status:${l}`),async l=>{let u=await n(l.map(p=>p.slice(7)));for(let[p,d]of Object.entries(u))await Qc(`status:${p}`,d)}),a.length)for(let[l,u]of Object.entries(await n(a)))o[l]=u,await Qc(`status:${l}`,u);return o}s(moe,"getIssueStatuses");function yFe(e){let t={};for(let r of fFe){let i=e[r];if(typeof i!="string")continue;let n=i.trim();n&&(r==="feature"&&!mFe.test(n)||(t[r]=n))}return t}s(yFe,"mapIssueStringFields");function bFe(e,t){if(!Array.isArray(e)||t.length===0)return[];let r=new Set(t),i=new Set,n=[];for(let o of e){if(typeof o!="string")continue;let a=o.trim();r.has(a)&&!i.has(a)&&(i.add(a),n.push(a))}return n}s(bFe,"pickValidServices");async function s$(e){try{let t=await rt.readFile(Be.join(ee(e),"workspace.yml"),"utf-8"),r=(0,fv.parse)(t),i=Ss(r)||null,n=Array.isArray(r?.labels)?r.labels.filter(p=>typeof p=="string"):[],o=s(p=>typeof p=="string"&&p.trim()?p.trim():null,"str"),a=o(r?.model),c=Po(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:Po(l);return{issueId:i,labels:n,model:a,autonomous:c,autoStop:u,task:o(r?.task),workType:o(r?.work_type)}}catch{return{issueId:null,labels:[],model:null,autonomous:!1,autoStop:!1,task:null,workType:null}}}s(s$,"readWorkspaceConfig");async function t$(){let e=hs(),t;try{t=await rt.readdir(e,{withFileTypes:!0})}catch(n){throw new ge(`Could not read workspaces root ${e}: ${n.message}`)}let r=t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort((n,o)=>n.localeCompare(o)),i=await Promise.all(r.map(async n=>{let o=Be.join(e,n),{issueId:a,labels:c,model:l,task:u,workType:p}=await s$(o);return{name:n,path:o,vscodeUri:`vscode://file${o.split(Be.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?It().url(a):null,labels:c,model:l,task:u,workType:p,lifecycle:Od(o).state}}));return{root:e,workspaces:i}}s(t$,"listWorkspaces");async function WL(){let e;try{e=YX(Fte({},dv.homedir(),{defaults:!1}))}catch(i){throw new ge(`Could not build the workspace form: ${i.message}`)}let t=e.uiSchema??{},r=t.issue_id??{};return t.issue_id={...r,"ui:options":{...r["ui:options"]??{},trackerLabel:It().label}},{schema:e.schema,uiSchema:t,formData:e.formData,title:e.title??"Initialize workspace"}}s(WL,"getFormSchema");var xFe=new Set(["open"]);function Gie(e){return"--"+e.replace(/_/g,"-")}s(Gie,"kebab");function wFe(e){let t=String(e.feature??"").trim();if(!t)throw new ge("A feature name is required (pass it as an argument, set it in ./.sandbox/workspace.yml, or run interactively).");let r=["workspace",t];for(let[i,n]of Object.entries(e)){if(i==="feature"||xFe.has(i))continue;if(n===!0){r.push(Gie(i));continue}if(n===!1)continue;let o;if(Array.isArray(n))o=n.map(a=>String(a).trim()).filter(Boolean).join(",");else{if(n==null)continue;o=String(n).trim()}o&&r.push(Gie(i),o)}return r}s(wFe,"buildWorkspaceArgs");var _Fe=[process.env.VSCODE_BIN,"/usr/local/bin/code","/opt/homebrew/bin/code","/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"].filter(e=>!!e);async function kFe(){for(let e of _Fe)if(await KN(e))return e;return null}s(kFe,"findCodeBin");async function hoe(e){let t=await kFe();if(!t)return{opened:!1,note:"VS Code CLI ('code') not found \u2014 open the workspace folder manually."};try{return ioe(t,[e],{detached:!0,stdio:"ignore"}).unref(),{opened:!0}}catch(r){return{opened:!1,note:`Could not launch VS Code: ${r.message}`}}}s(hoe,"openInVscode");var SFe=["feature","task","description","starting_prompt","services"];async function $Fe(e,t=rg){let r=Jk({ref:e.ref,title:e.title,status:e.status,description:e.body,url:e.url??void 0,comments:e.comments}),i=null;try{i=await t(await doe(e.ref,r))}catch(a){return{fields:{},warning:a.message}}if(i===null)return{fields:{},warning:"the model gave no answer"};let n=await foe({},i),o={};for(let a of SFe){let c=n[a];typeof c=="string"&&c.trim()?o[a]=c.trim():Array.isArray(c)&&c.length&&(o[a]=c.map(String).join(","))}return Object.keys(o).length?{fields:o,warning:null}:{fields:o,warning:"the answer held no usable fields"}}s($Fe,"distillIssue");async function EFe(e,t={}){let r=Mg(e,t.cwd??dv.homedir());if(!r.issue_id)return{resolved:r,issue:null};let i=It(),n=i.parseRef(r.issue_id);if(!n)throw new ge(`${r.issue_id} isn't a ${i.label} issue ref (e.g. ${i.refExample})`);r.issue_id=n;let o=t.issue??null;if(!o)try{o=await CS(n)}catch(a){if(a instanceof gl){let c=await i.checkAuth(),l=c.ok?"run `sandbox connect` to check the issue tracker":`${i.label}: ${c.reason}; run: ${c.fix}`;throw new ge(`${a.message}; ${l}.`)}throw a}if(!r.task&&o.title&&(r.task=o.title),t.distill!==!1&&(!r.description||!r.starting_prompt)){let{fields:a,warning:c}=await $Fe(o,t.distill??rg);for(let l of["description","starting_prompt"])!r[l]&&a[l]&&(r[l]=a[l]);c&&Z(`description/starting_prompt not filled from the issue: ${c}`)}return{resolved:r,issue:o}}s(EFe,"prepareCreate");async function goe(e,t={}){let i=`sandbox ${wFe(e).join(" ")}`,n=s(async()=>{let{resolved:p,issue:d}=await EFe(e,t);return Kie(p,{issue:d??void 0,readStdinTask:t.readStdinTask,force:t.force})},"run"),o=Ca(t.onData),a;try{a=t.live?await n():await ja(o,n)}catch(p){if(t.live)throw p instanceof Hi?p:new ge(p.message);let d=Tt(o.text().trim())||p.message;throw new ge(`${i} failed:
1099
+ `+n+"\n```"}s(gFe,"buildIssueExtractPrompt");var vFe=5*60*1e3;async function moe(e,t){let r=It(),i=[...new Set(e.map(l=>r.parseRef(l)).filter(l=>!!l))].sort((l,u)=>l.localeCompare(u));if(!i.length)return{};let n=s(async l=>{let u={};for(let[p,d]of Object.entries(await r.fetchIssues(l)))d.status&&(u[p]=d.status);return u},"fetchStatuses"),o={},a=[],c=[];if(t?.refresh)a.push(...i);else for(let l of i){let u=await HN(`status:${l}`);if(!u){a.push(l);continue}o[l]=u.v,Date.now()-u.at>=vFe&&c.push(l)}if(c.length&&VN(c.map(l=>`status:${l}`),async l=>{let u=await n(l.map(p=>p.slice(7)));for(let[p,d]of Object.entries(u))await Qc(`status:${p}`,d)}),a.length)for(let[l,u]of Object.entries(await n(a)))o[l]=u,await Qc(`status:${l}`,u);return o}s(moe,"getIssueStatuses");function yFe(e){let t={};for(let r of fFe){let i=e[r];if(typeof i!="string")continue;let n=i.trim();n&&(r==="feature"&&!mFe.test(n)||(t[r]=n))}return t}s(yFe,"mapIssueStringFields");function bFe(e,t){if(!Array.isArray(e)||t.length===0)return[];let r=new Set(t),i=new Set,n=[];for(let o of e){if(typeof o!="string")continue;let a=o.trim();r.has(a)&&!i.has(a)&&(i.add(a),n.push(a))}return n}s(bFe,"pickValidServices");async function s$(e){try{let t=await rt.readFile(Be.join(ee(e),"workspace.yml"),"utf-8"),r=(0,fv.parse)(t),i=Ss(r)||null,n=Array.isArray(r?.labels)?r.labels.filter(p=>typeof p=="string"):[],o=s(p=>typeof p=="string"&&p.trim()?p.trim():null,"str"),a=o(r?.model),c=Po(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:Po(l);return{issueId:i,labels:n,model:a,autonomous:c,autoStop:u,task:o(r?.task),workType:o(r?.work_type)}}catch{return{issueId:null,labels:[],model:null,autonomous:!1,autoStop:!1,task:null,workType:null}}}s(s$,"readWorkspaceConfig");async function t$(){let e=hs(),t;try{t=await rt.readdir(e,{withFileTypes:!0})}catch(n){throw new ge(`Could not read workspaces root ${e}: ${n.message}`)}let r=t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort((n,o)=>n.localeCompare(o)),i=await Promise.all(r.map(async n=>{let o=Be.join(e,n),{issueId:a,labels:c,model:l,task:u,workType:p}=await s$(o);return{name:n,path:o,vscodeUri:`vscode://file${o.split(Be.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?It().url(a):null,labels:c,model:l,task:u,workType:p,lifecycle:Od(o).state}}));return{root:e,workspaces:i}}s(t$,"listWorkspaces");async function WL(){let e;try{e=YX(Fte({},dv.homedir(),{defaults:!1}))}catch(i){throw new ge(`Could not build the workspace form: ${i.message}`)}let t=e.uiSchema??{},r=t.issue_id??{};return t.issue_id={...r,"ui:options":{...r["ui:options"]??{},trackerLabel:It().label}},{schema:e.schema,uiSchema:t,formData:e.formData,title:e.title??"Initialize workspace"}}s(WL,"getFormSchema");var xFe=new Set(["open"]);function Gie(e){return"--"+e.replace(/_/g,"-")}s(Gie,"kebab");function wFe(e){let t=String(e.feature??"").trim();if(!t)throw new ge("A feature name is required (pass it as an argument, set it in ./.sandbox/workspace.yml, or run interactively).");let r=["workspace",t];for(let[i,n]of Object.entries(e)){if(i==="feature"||xFe.has(i))continue;if(n===!0){r.push(Gie(i));continue}if(n===!1)continue;let o;if(Array.isArray(n))o=n.map(a=>String(a).trim()).filter(Boolean).join(",");else{if(n==null)continue;o=String(n).trim()}o&&r.push(Gie(i),o)}return r}s(wFe,"buildWorkspaceArgs");var _Fe=[process.env.VSCODE_BIN,"/usr/local/bin/code","/opt/homebrew/bin/code","/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"].filter(e=>!!e);async function kFe(){for(let e of _Fe)if(await KN(e))return e;return null}s(kFe,"findCodeBin");async function hoe(e){let t=await kFe();if(!t)return{opened:!1,note:"VS Code CLI ('code') not found \u2014 open the workspace folder manually."};try{return ioe(t,[e],{detached:!0,stdio:"ignore"}).unref(),{opened:!0}}catch(r){return{opened:!1,note:`Could not launch VS Code: ${r.message}`}}}s(hoe,"openInVscode");var SFe=["feature","task","description","starting_prompt","services"];async function $Fe(e,t=rg){let r=Jk({ref:e.ref,title:e.title,status:e.status,description:e.body,url:e.url??void 0,comments:e.comments}),i=null;try{i=await t(await doe(e.ref,r))}catch(a){return{fields:{},warning:a.message}}if(i===null)return{fields:{},warning:"the model gave no answer"};let n=await foe({},i),o={};for(let a of SFe){let c=n[a];typeof c=="string"&&c.trim()?o[a]=c.trim():Array.isArray(c)&&c.length&&(o[a]=c.map(String).join(","))}return Object.keys(o).length?{fields:o,warning:null}:{fields:o,warning:"the answer held no usable fields"}}s($Fe,"distillIssue");async function EFe(e,t={}){let r=Mg(e,t.cwd??dv.homedir());if(!r.issue_id)return{resolved:r,issue:null};let i=It(),n=i.parseRef(r.issue_id);if(!n)throw new ge(`${r.issue_id} isn't a ${i.label} issue ref (e.g. ${i.refExample})`);r.issue_id=n;let o=t.issue??null;if(!o)try{o=await CS(n)}catch(a){if(a instanceof gl){let c=await i.checkAuth(),l=c.ok?"run `sandbox connect` to check the issue tracker":`${i.label}: ${c.reason}; run: ${c.fix}`;throw new ge(`${a.message}; ${l}.`)}throw a}if(!r.task&&o.title&&(r.task=o.title),t.distill!==!1&&(!r.description||!r.starting_prompt)){let{fields:a,warning:c}=await $Fe(o,t.distill??rg);for(let l of["description","starting_prompt"])!r[l]&&a[l]&&(r[l]=a[l]);c&&Z(`description/starting_prompt not filled from the issue: ${c}`)}return{resolved:r,issue:o}}s(EFe,"prepareCreate");async function goe(e,t={}){let i=`sandbox ${wFe(e).join(" ")}`,n=s(async()=>{let{resolved:p,issue:d}=await EFe(e,t);return Kie(p,{issue:d??void 0,readStdinTask:t.readStdinTask,force:t.force,build:t.build})},"run"),o=Ca(t.onData),a;try{a=t.live?await n():await ja(o,n)}catch(p){if(t.live)throw p instanceof Hi?p:new ge(p.message);let d=Tt(o.text().trim())||p.message;throw new ge(`${i} failed:
1100
1100
  ${d}`)}let c=Tt(o.text().trim()),l=!1,u;return(t.open??!0)&&a&&await BL(a)?{opened:l,note:u}=await hoe(a):(t.open??!0)&&(u="Could not determine the workspace path to open."),{command:i,output:c,workspacePath:a,opened:l,openNote:u}}s(goe,"createWorkspace");async function xl(e){let t=(e??"").trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new ge(`Invalid workspace name: ${JSON.stringify(e)}`);let r=Be.join(hs(),t);if(!await BL(r))throw new ge(`No such workspace: ${t}`);return r}s(xl,"resolveWorkspaceDir");var voe=s(()=>Be.join(ee(dv.homedir()),"reconcile"),"reconcileRoot"),KL="reconcile:";function TFe(e){let t=e.slice(KL.length);if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new ge(`Invalid reconcile session: ${JSON.stringify(e)}`);return Be.join(voe(),t)}s(TFe,"reconcileDirForKey");async function mv(e){if((e??"").startsWith(KL)){let t=TFe(e);if(!await BL(t))throw new ge(`No such reconcile session: ${e}`);return t}return xl(e)}s(mv,"resolveSessionDir");async function yoe(e){let t=await xl(e),{opened:r,note:i}=await hoe(t);if(!r)throw new ge(i??"Could not launch VS Code.");return{path:t}}s(yoe,"openWorkspace");async function boe(e,t){try{let r=await rt.readFile(Be.join(e,".env"),"utf-8");for(let i of r.split(/\r?\n/)){let n=i.indexOf("=");if(n>0&&i.slice(0,n).trim()===t)return i.slice(n+1).trim()}}catch{}return null}s(boe,"readEnvValue");async function OFe(e){try{let t=await rt.readFile(Be.join(ee(e),"workspace.yml"),"utf-8"),r=/^feature: *["']?([^"'\s#]+)/m.exec(t);return r?r[1]:null}catch{return null}}s(OFe,"readWorkspaceFeature");async function IFe(e){let t=await rt.readdir(Be.join(e,"stages")).catch(()=>null);if(!t)return null;let r=t.filter(i=>/^\d+_/.test(i)).sort();for(let i=0;i<r.length;i++)if(!(await rt.readdir(Be.join(e,"stages",r[i],"output")).catch(()=>[])).some(o=>!o.startsWith(".")))return{index:i+1,total:r.length,name:r[i].replace(/^\d+_/,"")};return null}s(IFe,"icmStage");function RFe(e){let t;try{t=No(e)}catch{return null}for(let r of t.reverse()){let i=r.frontmatter.phase;if(typeof i=="string"&&i.trim())return i.trim()}return null}s(RFe,"jitPhase");var AFe=10*60*1e3;async function PFe(e,t=131072){let r=await rt.open(e,"r");try{let{size:i}=await r.stat(),n=Math.max(0,i-t),o=Buffer.alloc(i-n);await r.read(o,0,o.length,n);let a=o.toString("utf-8");if(n>0){let c=a.indexOf(`
1101
1101
  `);c>=0&&(a=a.slice(c+1))}return a}finally{await r.close()}}s(PFe,"readFileTail");async function jFe(e,t){let r=await av(e).catch(()=>null),i=r?.updatedAt??null,n=XL.get(e)?.state??"idle",o=s((l,u=i,p=null)=>({signal:{state:n,agent:l,at:u,question:p},lastActivity:i}),"signal");if(n==="running")return o("working");let a=sJ(t);if(a)return o(a.state,a.at,a.question??null);let c;try{r?.sessionFile&&(c=Loe(await PFe(r.sessionFile)).at(-1))}catch{}return!c||!i?o("idle"):c.role==="assistant"?aJ(c.text)?o("needs-you",i,cJ(c.text)):o("done"):o(Date.now()-Date.parse(i)<AFe?"working":"idle")}s(jFe,"claudeSessionSignal");function Jie(e){return e.health==="healthy"?"healthy":e.health==="starting"?"starting":e.health==="unhealthy"?"unhealthy":e.state==="running"?"running":"down"}s(Jie,"serviceHealthState");function CFe(e){let t=new Map;for(let{service:r,state:i,health:n,labels:o,exitCode:a}of e){let c=o["com.docker.compose.project"];if(!c)continue;let l=i==="exited"&&a===0;if(kg(r,o["com.sandbox.local.role"])&&l)continue;let u=t.get(c)??{running:0,total:0,services:[],slot:null};u.total++,i==="running"&&u.running++,u.services.push({name:r,state:i,health:n});let p=o["com.sandbox.local.slot"];if(u.slot===null&&p){let d=Number.parseInt(p,10);Number.isInteger(d)&&(u.slot=d)}t.set(c,u)}return t}s(CFe,"tallyComposeContainers");async function NFe(){let e=await $n();return e?{tallies:CFe(e),health:await SS(e)}:null}s(NFe,"dockerComposeProjects");async function DFe(){let e=await ZL(Yc());if(!e)return null;try{return(0,fv.parse)(await rt.readFile(e,"utf8"))??null}catch{return null}}s(DFe,"loadPortsDoc");function LFe(e,t){let[r,i]=Z0(e,t);return`${r}-${i}`}s(LFe,"slotPortLabel");async function GL(){let e=hs(),r=(await rt.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),i=await NFe(),n=i?.tallies??null,o=await DFe(),a=await Promise.all(r.map(async l=>{let u=Be.join(e,l),p=await boe(u,"COMPOSE_PROJECT_NAME");if(!p){let C=await OFe(u);p=C?`sandbox-${C}`:null}let{signal:d,lastActivity:m}=await jFe(l,u),{model:h,autonomous:v,autoStop:g}=await s$(u),y={claude:d,model:h,stage:await IFe(u),phase:RFe(u),autonomous:v,autoStop:g,lastActivity:m};if(n===null)return{name:l,project:p,state:"unknown",running:0,total:0,slot:null,ports:null,services:[],...y,started:null,crashLoops:[]};let w=p?n.get(p):void 0,k=p?i?.health.get(p):void 0,_;!w||w.total===0?_="down":w.running===w.total?_="up":w.running>0?_="partial":_="stopped";let $=w?.slot??null,E=$!==null?LFe($,o):null,I=(w?.services??[]).map(C=>({name:C.name,state:Jie(C)}));return{name:l,project:p,state:_,running:w?.running??0,total:w?.total??0,slot:$,ports:E,services:I,...y,started:k?.started??null,crashLoops:k?.crashLoops??[]}})),c;if(n===null)c={state:"unknown",running:0,total:0,services:[]};else{let l=n.get(fi),u=l?.running??0,p=l?.total??0,d=p===0?"down":u===p?"up":u>0?"partial":"down",m=(l?.services??[]).map(h=>({name:h.name,state:Jie(h)}));c={state:d,running:u,total:p,services:m}}return{statuses:a,infra:c}}s(GL,"getWorkspaceStatuses");async function zFe(e){let t=[],r=await rt.readdir(Be.join(e,"stages")).catch(()=>[]);for(let i of r.sort()){let n=Be.join("stages",i,"output"),o=await rt.readdir(Be.join(e,n)).catch(()=>[]);for(let a of o.sort()){if(!a.endsWith(".md"))continue;let c=await rt.readFile(Be.join(e,n,a),"utf-8").catch(()=>"");/^status: proposed/m.test(c)&&t.push(Be.join(n,a))}}return t}s(zFe,"proposedGates");async function xoe(e){let t=new Date,[{root:r,workspaces:i},{statuses:n}]=await Promise.all([t$(),GL()]),o=Be.join(r,".check-in-last"),a=await rt.stat(o).then(h=>Math.round(h.mtimeMs),()=>null),c=i.some(h=>h.labels.includes("focus")),l=s(h=>!h.labels.includes("skip")&&(!c||h.labels.includes("focus")),"keep"),u=new Map(n.map(h=>[h.name,h])),p=i.filter(l);await wie(p.map(h=>h.path),e);let d=await Promise.all(p.map(async h=>{let v=u.get(h.name),{updatedAt:g}=await av(h.name).catch(()=>({updatedAt:null})),y=Od(h.path);return{name:h.name,issueId:h.issueId,labels:h.labels,containers:v?.state??"unknown",claude:v?.claude??{state:"idle",agent:"idle",at:null,question:null},gates:await zFe(h.path),updatedAt:g,changed:a!==null&&g!==null&&Date.parse(g)>a,lifecycle:y.state,prs:y.prs.map(w=>({repo:w.dir,url:w.url,status:w.status,release:w.release}))}}));await rt.writeFile(o,"",{flag:"a"}),await rt.utimes(o,t,t);let m=d.filter(h=>(h.lifecycle==="shipped"||h.lifecycle==="abandoned")&&h.claude.agent!=="working").map(h=>h.name);return{root:r,since:a===null?null:new Date(a).toISOString(),workspaces:d,dropped:i.filter(h=>!l(h)).map(h=>h.name),candidates:d.filter(h=>h.claude.agent!=="working"&&!m.includes(h.name)&&(a===null?h.claude.agent==="needs-you"||h.claude.agent==="done":h.gates.length>0||h.changed)).map(h=>h.name),readyToClose:m}}s(xoe,"checkInTriage");async function woe(e){try{return await rt.access(Be.join(e,".git")),!0}catch{return!1}}s(woe,"hasGit");async function r$(e){let t=await rt.readdir(e,{withFileTypes:!0}).catch(()=>[]),r=[];for(let i of t){if(!i.isDirectory()||i.name.startsWith("."))continue;let n=Be.join(e,i.name);await woe(n)&&r.push({repo:i.name,dir:n})}return r}s(r$,"listRepoWorktrees");async function MFe(e){let t=null,r=await Mt("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null);r&&r.code===0&&(t=Tt(r.stdout).trim()||null);let i={branch:t,url:null,state:null,title:null,labels:[],...Yie(void 0)};if(!t||t==="HEAD")return i;let n=await Mt("gh",["pr","list","--head",t,"--state","all","--json","url,state,title,labels,statusCheckRollup,isDraft","--limit","1"],e).catch(()=>null);if(n?.code!==0)return i;try{let o=JSON.parse(Tt(n.stdout).trim()||"[]");if(!o.length)return i;let a=(o[0].state??"").toUpperCase(),c=a==="OPEN"||a==="MERGED"||a==="CLOSED"?a:null,l=(o[0].labels??[]).map(u=>u.name??"").filter(Boolean);return{branch:t,url:o[0].url??null,state:c,title:o[0].title??null,labels:l,...Yie(o[0].statusCheckRollup),draft:o[0].isDraft===!0}}catch{return i}}s(MFe,"ghPrForWorktree");async function _oe(){let e=hs(),r=(await rt.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(i=>i.isDirectory()&&!i.name.startsWith(".")).map(i=>i.name).sort((i,n)=>i.localeCompare(n));return Promise.all(r.map(async i=>{let n=await r$(Be.join(e,i)),o=await Promise.all(n.map(async({repo:a,dir:c})=>({repo:a,...await MFe(c)})));return{name:i,repos:o}}))}s(_oe,"getWorkspacePRs");var koe="ready-for-human-approval";async function Soe(e){let t=tr("REVIEW_SLACK_TOKEN"),r=tr("REVIEW_SLACK_CHANNEL");if(!t||!r)throw new ge("Slack is not configured: set SANDBOX_REVIEW_SLACK_TOKEN (a bot token with chat:write) and SANDBOX_REVIEW_SLACK_CHANNEL (the review channel id).");let n=await(await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({channel:r,text:e})}).catch(o=>{throw new ge(`Slack request failed: ${o.message}`)})).json().catch(()=>({}));if(!n.ok)throw new ge(`Slack rejected the message: ${n.error??"unknown error"}`);return r}s(Soe,"postSlackReviewRequest");function FFe(e){return e.reviewDecision==="APPROVED"?"APPROVED":e.reviewDecision==="CHANGES_REQUESTED"?"CHANGES_REQUESTED":(e.latestReviews??[]).some(t=>t.state==="DISMISSED")?"DISMISSED":"PENDING"}s(FFe,"reviewStatusOf");var qFe=new Set(["FAILURE","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","ERROR"]);function $oe(e){if(!Array.isArray(e))return 0;let t=0;for(let r of e){if(!r||typeof r!="object")continue;let i=r,n=String(i.conclusion??i.state??"").toUpperCase();qFe.has(n)&&t++}return t}s($oe,"countFailingChecks");function Yie(e){if(!Array.isArray(e)||e.length===0)return{ci:null,failingChecks:0};let t=$oe(e);return t>0?{ci:"fail",failingChecks:t}:{ci:e.some(i=>{let n=i??{},o=String(n.status??"").toUpperCase();if(o)return o!=="COMPLETED";let a=String(n.state??"").toUpperCase();return a==="PENDING"||a==="EXPECTED"})?"running":"pass",failingChecks:0}}s(Yie,"ciOf");var UFe=30*24*60*60*1e3;function BFe(e,t){if(!e)return!0;let r=Date.parse(e);return Number.isNaN(r)?!0:t-r<UFe}s(BFe,"isWithin30Days");function Eoe(e){try{let t=new URL(e).pathname.split("/").filter(Boolean);return{repo:t[1]??"",number:Number.parseInt(t[3]??"",10)||0}}catch{return{repo:"",number:0}}}s(Eoe,"parseRepoAndNumber");function Xie(e,t){let{repo:r,number:i}=Eoe(e.url);if("unavailable"in e)return{url:e.url,repo:r,number:i,title:"(details unavailable)",author:"",body:"",labels:[],reviewStatus:"PENDING",failingChecks:0,outOfDate:!1,hasApprovalLabel:!1,issueId:null,issueUrl:null,isDraft:!1};let n=(e.labels??[]).map(u=>u.name??"").filter(Boolean),o=e.title??"",a=e.body??"",c=It(),l=c.parseRef(`${o} ${a} ${e.headRefName??""}`);return{url:e.url,repo:r,number:i,title:o,author:e.author?.login??"",body:a,labels:n,reviewStatus:FFe(e),failingChecks:$oe(e.statusCheckRollup),outOfDate:e.mergeStateStatus==="BEHIND",hasApprovalLabel:n.includes(koe),issueId:l,issueUrl:l?c.url(l):null,isDraft:e.isDraft??!1}}s(Xie,"prFromView");function ZFe(e,t,r,i){let n=s(c=>c.filter(l=>BFe("unavailable"in l?void 0:l.updatedAt,i)),"fresh"),o=n(e).map(c=>Xie(c,r)),a=n(t).map(c=>Xie(c,r)).filter(c=>c.author!==r);return{me:r,mine:o,others:a}}s(ZFe,"assembleOpenPrs");async function HFe(){let e=await Mt("gh",["api","user","--jq",".login"]).catch(()=>null),t=e&&e.code===0?Tt(e.stdout).trim():"";if(!t)throw new ge("Could not resolve GitHub user (`gh api user`). Is `gh` authenticated?");return t}s(HFe,"resolveGithubLogin");async function Qie(e){let t=await Mt("gh",["search","prs","--owner=sandbox","--state=open",...e,"--json","url","--limit","100"]).catch(r=>{throw new ge(`gh search prs failed: ${r.message}`)});if(t.code!==0)throw new ge(`gh search prs failed: ${Tt(t.stderr).trim()||`exit ${t.code}`}`);try{return JSON.parse(Tt(t.stdout).trim()||"[]").map(i=>i.url).filter(i=>!!i)}catch{return[]}}s(Qie,"ghSearchPrUrls");async function UL(e){let t=await Mt("gh",["pr","view",e,"--json","reviewDecision,latestReviews,mergeStateStatus,statusCheckRollup,labels,author,number,title,body,headRefName,updatedAt,url,isDraft"]).catch(()=>null);if(t?.code!==0)return{url:e,unavailable:!0};try{return JSON.parse(Tt(t.stdout).trim())}catch{return{url:e,unavailable:!0}}}s(UL,"ghPrView");async function Toe(){let e=await HFe(),[t,r]=await Promise.all([Qie(["--author=@me"]),Qie([`--label=${koe}`])]),[i,n]=await Promise.all([Promise.all(t.map(UL)),Promise.all(r.map(UL))]);return ZFe(i,n,e,Date.now())}s(Toe,"getOpenPrs");async function Ooe(e){let t=await Mt("gh",["pr","review",e,"--approve"]).catch(r=>{throw new ge(`gh pr review failed: ${r.message}`)});if(t.code!==0)throw new ge(`gh pr review failed: ${Tt(t.stderr).trim()||`exit ${t.code}`}`);return{ok:!0}}s(Ooe,"approvePr");var VFe=5*60*1e3;async function JL(e){let t=It(),r=t.parseRef(e);return r?await WN(`issue-card:${r}`,VFe,async()=>await t.fetchIssue(r)??void 0)??{ref:r,url:t.url(r)??void 0}:{ref:""}}s(JL,"fetchIssueCard");async function WFe(e){let t=[e,...(await r$(e)).map(i=>i.dir)],r=[];for(let i of t)await woe(i)&&r.push(i);return r}s(WFe,"listWorkspaceWorktrees");async function AL(e){let t=new Set;for(let r of e){let i=await Mt("git",["-C",r,"rev-parse","--path-format=absolute","--git-common-dir"]).catch(()=>null);if(i&&i.code===0){let n=Tt(i.stdout).trim();n&&t.add(Be.dirname(n))}}return[...t]}s(AL,"worktreeSources");function eoe(e){let t=Tt(e).trim().split(`
1102
1102
  `);return(t.find(r=>/^\s*!\s|^(error|fatal):/.test(r))??t[0]).trim().replace(/\s+/g," ")}s(eoe,"gitErrorLine");async function PL(e,t=`chore: handoff ${Be.basename(e)} before workspace teardown`,r=[]){let i=Be.basename(e),n=await Mt("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null),o=n&&n.code===0?Tt(n.stdout).trim():null;if(!o||o==="HEAD")return{ok:!1,message:`${i}: no branch to push (detached HEAD)`};let a=r.length?["--",...r]:[];await Mt("git",["-C",e,"add","-A",...a]).catch(()=>{});let c=await Mt("git",["-C",e,"diff","--cached","--quiet",...a]).catch(()=>null);if(c&&c.code===1){let d=await Mt("git",["-C",e,"commit","-m",t,...a]).catch(()=>null);if(d?.code!==0)return{ok:!1,message:`${i}: commit failed \u2014 ${d?eoe(d.stderr||d.stdout):"spawn error"}`}}let l=`origin/${o}`;if((await Mt("git",["-C",e,"rev-parse","--verify","--quiet",l]).catch(()=>null))?.code===0){let d=await Mt("git",["-C",e,"rev-list","--count",`${l}..HEAD`]).catch(()=>null);if(d&&d.code===0&&Tt(d.stdout).trim()==="0")return{ok:!0,message:`${i}: nothing to hand off (${o} already on origin)`}}let p=await Mt("git",["-C",e,"push","-u","origin",o]).catch(()=>null);return p?.code!==0?{ok:!1,message:`${i}: push failed \u2014 ${p?eoe(p.stderr||p.stdout):"spawn error"}`}:{ok:!0,message:`${i}: pushed ${o}`}}s(PL,"commitAndPush");async function Sie(e,t={}){let r=await xl(e);if(!t.closedOut){let l=await _ie(r,await r$(r));if(l.length&&!t.abandon?.trim())throw new ge(`Workspace '${e}' NOT removed \u2014 it holds unshipped work:
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister",
3
- "version": "0.28.0",
3
+ "version": "0.28.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Multi-feature concurrent development orchestrator CLI tool",
6
6
  "type": "module",
@@ -53,7 +53,7 @@
53
53
  "typescript": "^5.7.0",
54
54
  "vitest": "^3.0.0",
55
55
  "yaml": "^2.7.0",
56
- "werkmeister-core": "0.28.0"
56
+ "werkmeister-core": "0.28.1"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "node esbuild.mjs",