werkmeister 0.44.3 → 0.44.4
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 +39 -39
- package/dist/mcp.js +2 -2
- package/dist/werkmeister-workspaces.vsix +0 -0
- package/package.json +2 -2
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 qK=Object.create;var dh=Object.defineProperty;var UK=Object.getOwnPropertyDescriptor;var WK=Object.getOwnPropertyNames;var KK=Object.getPrototypeOf,VK=Object.prototype.hasOwnProperty;var i=(e,t)=>dh(e,"name",{value:t,configurable:!0}),te=(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),pe=(e,t)=>{for(var r in t)dh(e,r,{get:t[r],enumerable:!0})},HK=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of WK(t))!VK.call(e,s)&&s!==r&&dh(e,s,{get:()=>t[s],enumerable:!(n=UK(t,s))||n.enumerable});return e};var Re=(e,t,r)=>(r=e!=null?qK(KK(e)):{},HK(t||!e||!e.__esModule?dh(r,"default",{value:e,enumerable:!0}):r,e));var _,h=C(()=>{_={sha:"
|
|
4
|
+
var qK=Object.create;var dh=Object.defineProperty;var UK=Object.getOwnPropertyDescriptor;var WK=Object.getOwnPropertyNames;var KK=Object.getPrototypeOf,VK=Object.prototype.hasOwnProperty;var i=(e,t)=>dh(e,"name",{value:t,configurable:!0}),te=(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),pe=(e,t)=>{for(var r in t)dh(e,r,{get:t[r],enumerable:!0})},HK=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of WK(t))!VK.call(e,s)&&s!==r&&dh(e,s,{get:()=>t[s],enumerable:!(n=UK(t,s))||n.enumerable});return e};var Re=(e,t,r)=>(r=e!=null?qK(KK(e)):{},HK(t||!e||!e.__esModule?dh(r,"default",{value:e,enumerable:!0}):r,e));var _,h=C(()=>{_={sha:"c344fa1f4ed00da7e589b0867728f791f79f8b57",dirty:!1}});var Lu=$(Rw=>{h();var ph=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}},Tw=class extends ph{static{i(this,"InvalidArgumentError")}constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Rw.CommanderError=ph;Rw.InvalidArgumentError=Tw});var hh=$(Cw=>{h();var{InvalidArgumentError:YK}=Lu(),Aw=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 YK(`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 zK(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}i(zK,"humanReadableArgName");Cw.Argument=Aw;Cw.humanReadableArgName=zK});var Iw=$(Nw=>{h();var{humanReadableArgName:JK}=hh(),Pw=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=>JK(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,p){return r.formatItem(d,n,p,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(p=>o(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));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 dT(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 p=f.trimStart();l=[p],u=this.displayWidth(p)}),o.push(l.join(""))}),o.join(`
|
|
@@ -188,25 +188,25 @@ if (( $+commands[werkmeister] )); then
|
|
|
188
188
|
fi
|
|
189
189
|
${EC}
|
|
190
190
|
`;return NC(t,n,s,r)}function IC(e){let t=String(e.command??""),r=e.args??[];return Et.basename(t)==="werkmeister"&&r[0]==="mcp"}function Pm(e){let t=e??ia();if(!Ue.existsSync(t))return!1;let r;try{r=JSON.parse(Ue.readFileSync(t,"utf8"))}catch(s){return N(`Could not parse ${t}: ${s}`),!1}let n=!1;for(let s of Object.values(r.mcpServers??{}))kf(s)&&IC(s)&&"env"in s&&(delete s.env,n=!0);return n&&Ue.writeFileSync(t,JSON.stringify(r,null,2)+`
|
|
191
|
-
`),n}function Nm(e){let t=[];if(!Ue.existsSync(ar()))return t.push(`config file missing: ${ar()} \u2014 run \`werkmeister config\``),t;let r=e.paths??{};for(let c of["repos_root","workspaces_root"]){let l=r[c];if(!l)t.push(`paths.${c} is not set`);else{let u=ht(String(l));Ue.existsSync(u)&&Ue.statSync(u).isDirectory()||t.push(`paths.${c} does not exist: ${l}`)}}let n=oa();n&&t.push(n),t.push(..._C(e));let s=zc();Ue.existsSync(s)?Ue.readFileSync(s,"utf8")!==Rm(e)&&t.push(`${s} is stale \u2014 run \`werkmeister config\` to regenerate`):t.push(`${s} missing \u2014 run \`werkmeister config\``);let o=ei();(!Ue.existsSync(o)||!Ue.readFileSync(o,"utf8").includes(Lv))&&t.push(`${o} does not source env.sh \u2014 run \`werkmeister config\``);let a=ia();if(Ue.existsSync(a))try{let c=JSON.parse(Ue.readFileSync(a,"utf8"));for(let l of Object.values(c.mcpServers??{}))kf(l)&&IC(l)&&"env"in l&&t.push(`${a}: werkmeister server still has a stale \`env\` block \u2014 run \`werkmeister config\``)}catch{}return t}var TC,Iv,Gz,Lv,RC,SC,EC,Yz,Jc,$C,Em,zz,AC,PC,OC,Dv,Jz,Xe=C(()=>{"use strict";h();TC=Re(rt(),1);Q();sa();Fe();Iv="^/\\S*$";i(zc,"envShPath");i(gt,"standardsDirPath");i(oa,"standardsDirProblem");i($m,"secretsPath");i(ei,"zshenvPath");i(vf,"zshrcPath");i(ia,"desktopConfigPath");Gz=[["paths","werkmeister_root","WERKMEISTER_ROOT"],["paths","repos_root","WERKMEISTER_REPOS_ROOT"],["paths","workspaces_root","WERKMEISTER_WORKSPACES_ROOT"],["overrides","mcp_port","WERKMEISTER_MCP_PORT"],["overrides","node","WERKMEISTER_NODE"],["overrides","services_yaml","WERKMEISTER_SERVICES_YAML"],["overrides","ports_yaml","WERKMEISTER_PORTS_YAML"],["overrides","model_pricing_yaml","WERKMEISTER_MODEL_PRICING_YAML"],["overrides","cache_file","WERKMEISTER_CACHE_FILE"],["ingress","certs_dir","WERKMEISTER_CERTS_DIR"]],Lv="# >>> werkmeister config >>>",RC="# <<< werkmeister config <<<",SC="# >>> werkmeister completion >>>",EC="# <<< werkmeister completion <<<",Yz=["SANDBOX_ROOT","SANDBOX_REPOS_ROOT","SANDBOX_WORKSPACES_ROOT"],Jc=[{key:"repos_root",label:"Repos root (absolute path)",help:"Directory holding the canonical source-repo clones (exported as WERKMEISTER_REPOS_ROOT).",acceptEmpty:!1,pattern:Iv,placeholder:"/Users/you/workspace"},{key:"workspaces_root",label:"Workspaces root (absolute path)",help:"Directory holding per-feature worktree workspaces (exported as WERKMEISTER_WORKSPACES_ROOT).",acceptEmpty:!1,pattern:Iv,placeholder:"/Users/you/workspace/features"}],$C={repos_root:"REPOS_ROOT",workspaces_root:"WORKSPACES_ROOT"};i(jv,"builtinPathDefault");i(Om,"pathDefault");i(kf,"isDict");i(Je,"load");i(Xc,"loadPaths");i(Dr,"candidateWorkspaceRoots");i(no,"loadJira");Em={local_domain:"local.werkmeister.io",remote_domain:"remote.werkmeister.io",certs_dir:Et.join(Zo.homedir(),".docker","certs")};i(Kt,"loadIngress");i(_f,"loadWorkspaceRepo");zz="[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?/[A-Za-z0-9._-]+$",AC={key:"workspace_repo",label:"Workspace config repo (owner/repo)",help:"GitHub repo cloned under the repos root and worktree'd as the root of every feature workspace, so .werkmeister/ configs and notes get history. Defaults to your own; point it at a shared <org>/sandbox-workspace to share workspace configs with your team.",acceptEmpty:!1,pattern:zz,placeholder:"your-org/sandbox-workspace"};i(so,"loadGithubOrg");i(CC,"loadSandboxIssuesProject");PC={key:"github_org",label:"GitHub org for service repos",help:"Owner of the repos in your services registry. Used to link the canonical examples that standards docs cite (github.com/<org>/<repo>).",acceptEmpty:!1,pattern:"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$",placeholder:"your-org"},OC="[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$",Dv=[{key:"local_domain",label:"Local ingress domain",help:"Base domain for docker features \u2014 each routed service is served at <service>.<domain> and Caddy terminates TLS for it.",acceptEmpty:!1,pattern:OC,placeholder:Em.local_domain},{key:"remote_domain",label:"Remote (K8s) ingress domain",help:"Base domain for services routed to the dev cluster instead of a local container \u2014 served at <service>.<domain>.",acceptEmpty:!1,pattern:OC,placeholder:Em.remote_domain},{key:"certs_dir",label:"Certificate directory (absolute path)",help:"Where bin/generate-certs.sh writes localhost.crt/.key; bind-mounted into the Caddy container (exported as WERKMEISTER_CERTS_DIR).",acceptEmpty:!1,pattern:Iv,placeholder:Em.certs_dir}],Jz="# Global werkmeister configuration \u2014 single source of truth.\n# Managed by `werkmeister config`; safe to hand-edit, then run `werkmeister config --check`.\n";i(Tm,"save");i(Xz,"shQuote");i(Rm,"renderEnvSh");i(Qc,"writeEnvSh");i(Qz,"managedBlock");i(Am,"stripBlock");i(Zz,"isLegacyExport");i(NC,"installBlock");i(Zc,"ensureZshenvSources");i(Cm,"ensureZshrcCompletion");i(IC,"isSandboxServer");i(Pm,"patchDesktopConfig");i(Nm,"check")});import{spawn as eJ}from"node:child_process";import LC from"node:fs/promises";import Sf from"node:os";import el from"node:path";import{stripVTControlCharacters as tJ}from"node:util";function Ie(e){return tJ(e)}async function aa(e){try{return await LC.access(e,LC.constants.X_OK),!0}catch{return!1}}function _s(){let e=[el.join(Sf.homedir(),".local","bin"),el.join(Sf.homedir(),".cargo","bin"),"/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"],t=process.env.PATH?process.env.PATH.split(el.delimiter):[],r=[...new Set([...e,...t])].join(el.delimiter);return{...process.env,PATH:r}}async function Im(){let e=[process.env.CLAUDE_BIN,el.join(Sf.homedir(),".local","bin","claude"),el.join(Sf.homedir(),".claude","local","claude"),"/opt/homebrew/bin/claude","/usr/local/bin/claude"].filter(t=>!!t);for(let t of e)if(await aa(t))return t;return"claude"}function Ze(e,t,r=Sf.homedir()){return new Promise((n,s)=>{let o=eJ(e,t,{cwd:r,env:_s(),stdio:["ignore","pipe","pipe"]}),a="",c="",l=setTimeout(()=>{o.kill("SIGKILL"),s(new z("The `claude` CLI timed out after 120s.",Gc))},12e4);o.stdout.on("data",u=>a+=u.toString()),o.stderr.on("data",u=>c+=u.toString()),o.on("error",u=>{clearTimeout(l),s(u)}),o.on("close",u=>{clearTimeout(l),n({stdout:a,stderr:c,code:u})})})}function Lm(e){let t=e.match(/<result>\s*([\s\S]*?)\s*<\/result>/i);return(t?t[1]:e).trim()}function Mv(e){let t=i(s=>{let o=s.indexOf("{"),a=s.lastIndexOf("}");return o!==-1&&a>o?s.slice(o,a+1):null},"slice"),r=t(e);if(r)try{return JSON.parse(r),r}catch{}let n=/```(?:json)?\s*([\s\S]*?)```/i.exec(e);return n?t(n[1]):r}async function Ef(e,t={}){try{let r=t.tools?["-p",e,"--dangerously-skip-permissions"]:["-p",e],n=await Ze(await Im(),r);return n.code!==0?null:Lm(Ie(n.stdout))}catch{return null}}async function jm(e,t={}){let r=await Ef(e,t),n=r===null?null:Mv(r);if(!n)return null;try{return JSON.parse(n)}catch{return null}}var tl=C(()=>{"use strict";h();Qt();i(Ie,"stripAnsi");i(aa,"isExecutable");i(_s,"childEnv");i(Im,"resolveClaudeBin");i(Ze,"runCapture");i(Lm,"extractResult");i(Mv,"extractJson");i(Ef,"askClaude");i(jm,"askClaudeJson")});function FC(e,t=so()){let r=e.trim(),n=/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/.exec(r);return n?`${n[1]}#${n[2]}`:/^[^/#]+#\d+$/.test(r)&&t?`${t}/${r}`:r}function Fm(e={}){if(e.repos?.length)return[...e.repos].sort();let t=e.org||so();if(!t)return[];let r;try{r=Object.keys(bn())}catch{r=[]}return r.sort().map(n=>`${t}/${n}`)}function MC(e){let t=Dm.exec(e);if(!t)throw new Error(`"${e}" is not a GitHub issue (owner/repo#n)`);return[t[1],t[2]]}async function oo(e){let t=await Gn([$f(),...e],{capture:!0,env:_s(),timeout:30});if(t.status!==0)throw new Error(t.stderr.trim()||`gh ${e[0]} ${e[1]} exited ${t.status}`);return t.stdout}function BC(e,t){return{ref:e,title:t.title?.trim()||void 0,status:iJ(t.state),...t.state?.toUpperCase()==="CLOSED"?{statusCategory:"done"}:{},labels:t.labels?.map(r=>r.name),type:t.labels?.map(r=>r.name).join(", ")||void 0,assignee:t.assignees?.map(r=>r.login).join(", ")||void 0,description:t.body?.trim()||void 0,url:t.url,comments:(t.comments??[]).flatMap(r=>{let n=r.body?.trim();return n?[{author:r.author?.login??"unknown",created:r.createdAt,body:n}]:[]})}}async function Bv(e,t,r){try{let[n,s]=MC(e);return BC(e,JSON.parse(await oo(["issue","view",s,"-R",n,"--json",t])))}catch(n){return r?.push(n.message),null}}function qv(e={}){let t=e.org||void 0,r=e.repos?.map(n=>n.toLowerCase());return{id:"github",label:"GitHub",refExample:"owner/repo#12",refPattern:DC,parseRef(n){let s=FC(n??"",t??so());if(Dm.test(s))return s;let o=/github\.com\/([^/\s]+\/[^/\s]+)\/issues\/(\d+)/.exec(s);return o?`${o[1]}#${o[2]}`:/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+#\d+/.exec(s)?.[0]??null},slug:i(n=>(n.split("/").pop()??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),"slug"),holds(n){let s=Dm.exec(n)?.[1].toLowerCase();return s?r?.length?r.includes(s):!t||s.startsWith(`${t.toLowerCase()}/`):!1},url(n){let s=Dm.exec(n);return s?`https://github.com/${s[1]}/issues/${s[2]}`:null},fetchIssue:i((n,s)=>Bv(n,"title,state,body,url,labels,assignees,comments",s),"fetchIssue"),async fetchIssues(n){let s=await Promise.all(n.map(o=>Bv(o,"title,state,url")));return Object.fromEntries(s.filter(o=>o!==null).map(o=>[o.ref,o]))},filingGuide(){let n=Fm(e);return{row:`| app code in a worktree | ${n.length?`the GitHub issues of the repo it belongs to \u2014 one of ${n.map(o=>`\`${o}\``).join(", ")}`:"that repo's GitHub issues \u2014 find it with `git -C <worktree> remote get-url origin`"} | \`gh issue create -R <owner>/<repo> --label <label>\` |`,search:'Search first: `gh issue list -R <owner>/<repo> --search "<keywords>" --state all`. If it exists, comment on it instead.'}},async listReady(n){if(n){let a=t||so(),c;try{c=await oo(["project","item-list",n.id,"--owner",a,"--format","json","--limit","200","--query",`status:"${n.ready}"`])}catch(u){throw new Error(`${u.message} (boards need the read:project scope: gh auth refresh -s read:project)`)}let{items:l=[]}=JSON.parse(c);return l.flatMap(({status:u,content:f})=>f?.type==="Issue"&&u?.toLowerCase()===n.ready.toLowerCase()?[{ref:`${f.repository}#${f.number}`,title:f.title,status:u,url:f.url}]:[])}let s=Fm(e);if(!s.length)throw new Error("no repos in scope");return(await Promise.all(s.map(async a=>JSON.parse(await oo(["issue","list","-R",a,"--state","open","--limit","100","--json","number,title,url,labels","--search","sort:created-asc"])).map(l=>BC(`${a}#${l.number}`,{...l,state:"OPEN"}))))).flat()},async updateIssue(n,s){let[o,a]=MC(n),c=s.status?.trim();if(c){let l=c.toLowerCase();if(rJ.has(l))await oo(["issue","close",a,"-R",o,"--reason","completed"]);else if(nJ.has(l))await oo(["issue","close",a,"-R",o,"--reason","not planned"]);else if(sJ.has(l))await oo(["issue","reopen",a,"-R",o]);else{let u=l.startsWith(jC)?((await Bv(n,"labels"))?.labels??[]).filter(f=>f.toLowerCase().startsWith(jC)&&f.toLowerCase()!==l):[];await oo(["label","create",c,"-R",o,"--color",oJ,"--force"]),await oo(["issue","edit",a,"-R",o,"--add-label",c,...u.length?["--remove-label",u.join(",")]:[]])}}s.comment&&await oo(["issue","comment",a,"-R",o,"--body",s.comment])},async checkAuth(){let n=i(a=>Gn([$f(),...a],{capture:!0,env:_s(),timeout:15}).catch(()=>null),"run"),s=await n(["auth","status","--hostname","github.com"]);if(s?.status!==0)return{ok:!1,reason:"not signed in",fix:"gh auth login"};let o=/account (\S+)/.exec(`${s.stdout}${s.stderr}`)?.[1];for(let a of Fm(e))if((await n(["repo","view",a,"--json","name"]))?.status!==0)return{ok:!1,...o?{who:o}:{},reason:`can't read ${a}`,fix:"gh auth refresh -s repo"};return{ok:!0,...o?{who:o}:{},fix:""}}}}var DC,Dm,rJ,nJ,jC,sJ,oJ,$f,iJ,qC,Uv=C(()=>{"use strict";h();tl();Q();Xe();mt();DC="^([A-Za-z0-9_.-]+/)?[A-Za-z0-9_.-]+#[0-9]+$",Dm=/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#(\d+)$/,rJ=new Set(["closed","close","done","completed"]),nJ=new Set(["not planned","abandoned"]),jC="status:",sJ=new Set(["open","reopen","reopened"]),oJ="1D76DB";i(FC,"normalizeGithubIssue");i(Fm,"githubIssueRepos");i(MC,"split");$f=i(()=>ze("GH_BIN")||"gh","ghBin");i(oo,"gh");iJ=i(e=>e?e[0]+e.slice(1).toLowerCase():void 0,"titleCase");i(BC,"fromGh");i(Bv,"view");i(qv,"githubTracker");qC=qv()});function UC(e,t,r){let n=e.trim();for(;n.endsWith("/");)n=n.slice(0,-1);return!n||!t||!r||ti(n)||ti(t)||ti(r)?null:{baseUrl:n,email:t,token:r}}async function la(){let e=UC(process.env.JIRA_BASE_URL??"",process.env.JIRA_EMAIL??"",process.env.JIRA_API_TOKEN??"");if(e)return e;try{let t=gn().jira??{};return UC(String(t.base_url??""),String(t.email??""),String(t.api_token??""))}catch{return null}}async function Of(e,t,r){let n=await fetch(`${e.baseUrl}${t}`,{method:r===void 0?"GET":"POST",headers:{Authorization:"Basic "+Buffer.from(`${e.email}:${e.token}`).toString("base64"),Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(1e4)});if(!n.ok){let s=(await n.text().catch(()=>"")).trim().slice(0,500);throw new Error(`Jira REST ${t} \u2192 HTTP ${n.status}${s?`: ${s}`:""}`)}return n}async function WC(){let e=await la();if(!e)return null;let r=await(await Of(e,"/rest/api/3/myself")).json();return{who:r.emailAddress??r.displayName??e.email}}async function ca(e,t){return await(await Of(e,t)).json()}async function KC(e,t){let r=await la();if(!r)return t?.push("no Jira REST credentials"),null;try{return await ca(r,`/rest/api/2/issue/${encodeURIComponent(e)}?fields=${aJ}`)}catch(n){return t?.push(cJ(n)),null}}function cJ(e){let t=e;if(t.message?.startsWith("Jira REST "))return t.message;let r=t.cause?.code??t.cause?.message;return`Jira REST: ${t.message}${r?` (${r})`:""}`}async function VC(e){if(!e.length)return{};let t=await la();if(!t)return null;let r=encodeURIComponent(`key in (${e.join(",")})`);try{let n=await ca(t,`/rest/api/2/search/jql?jql=${r}&fields=status&maxResults=100`),s={};for(let o of n.issues??[]){let a=o.fields?.status?.name;o.key&&a&&(s[o.key.toUpperCase()]=a)}return s}catch{return null}}async function GC(e){let t=await la();return t?(await ca(t,`/rest/api/2/search/jql?jql=${encodeURIComponent(e)}&${HC}`)).issues??[]:null}async function YC(e,t){let r=await la();if(!r)return null;let n=encodeURIComponent(e),{columnConfig:s}=await ca(r,`/rest/agile/1.0/board/${n}/configuration`),o=s?.columns??[],a=o.find(f=>f.name?.toLowerCase()===t.toLowerCase());if(!a)throw new Error(`board ${e} has no "${t}" column (it has: ${o.map(f=>f.name).join(", ")})`);let c=(a.statuses??[]).flatMap(f=>f.id?[f.id]:[]);if(!c.length)return[];let l=encodeURIComponent(`status in (${c.join(",")})`);return(await ca(r,`/rest/agile/1.0/board/${n}/issue?jql=${l}&${HC}`)).issues??[]}async function zC(e){let t=await la();if(!t)return null;let r=encodeURIComponent(e.project),{issueTypes:n=[]}=await ca(t,`/rest/api/2/issue/createmeta/${r}/issuetypes`),s=i(l=>n.some(u=>u.name?.toLowerCase()===l.toLowerCase()),"has"),o=s(e.issueType)||!s("Task")?e.issueType:"Task",a=await Of(t,"/rest/api/2/issue",{fields:{project:{key:e.project},issuetype:{name:o},summary:e.summary,description:e.description,...o===e.issueType?{}:{labels:[e.fallbackLabel]}}}),{key:c}=await a.json();return{key:c,url:`${t.baseUrl}/browse/${c}`,issueType:o}}async function JC(e,t){let r=await la();if(!r)return null;let n=`/rest/api/2/issue/${encodeURIComponent(e)}`;if(t.status){let s=t.status.trim().toLowerCase(),{transitions:o=[]}=await ca(r,`${n}/transitions`),a=o.find(c=>c.to?.name?.toLowerCase()===s)??o.find(c=>c.name?.toLowerCase()===s);if(!a){let c=o.map(l=>l.to?.name??l.name).filter(Boolean).join(", ");throw new Error(`${e} has no transition to "${t.status}" (available: ${c||"none"})`)}await Of(r,`${n}/transitions`,{transition:{id:a.id}})}return t.comment&&await Of(r,`${n}/comment`,{body:t.comment}),!0}var Wv,ti,aJ,HC,Kv=C(()=>{"use strict";h();Q();Wv=new Set(["PASTE_TOKEN_HERE","<your-atlassian-login-email>","https://your-org.atlassian.net"]),ti=i(e=>Wv.has(e.trim().replace(/\/+$/,"")),"isJiraPlaceholder");i(UC,"normalizeCreds");i(la,"jiraCreds");i(Of,"jiraFetch");i(WC,"jiraMyself");i(ca,"jiraGet");aJ="summary,description,status,issuetype,assignee,comment";i(KC,"fetchIssueRest");i(cJ,"restFailure");i(VC,"fetchStatusesRest");HC="fields=summary,status&maxResults=100";i(GC,"searchIssuesRest");i(YC,"boardColumnRest");i(zC,"createIssueRest");i(JC,"updateIssueRest")});function Mm(e){let t=(no().base_url??"").trim().replace(/\/+$/,"");return!t||ti(t)?null:`${t.includes("://")?t:`https://${t}`}/browse/${e}`}function e8(){let e=no(),t=(e.cloud_id??"").trim();if(t)return t;let r=(e.base_url??"").trim();if(!r||ti(r))return null;try{return new URL(r.includes("://")?r:`https://${r}`).hostname||null}catch{return null}}function Bm(){let e=e8();return e?`(Atlassian cloud id ${e})`:"(find the cloud id with getAccessibleAtlassianResources)"}function XC(e){let t=e.fields??{},r=(t.comment?.comments??[]).flatMap(n=>{let s=n.body?.trim();return s?[{author:n.author?.displayName??"unknown",created:n.created,body:s}]:[]});return{ref:e.key,title:Zt(t.summary),status:Zt(t.status?.name),statusCategory:t8(t.status?.statusCategory?.key),type:Zt(t.issuetype?.name),assignee:Zt(t.assignee?.displayName),description:Zt(t.description),url:Mm(e.key)??void 0,comments:r}}async function fJ(e){let t=await jm(`You are a data extractor, not an agent. Do exactly two things and nothing else:
|
|
191
|
+
`),n}function Nm(e){let t=[];if(!Ue.existsSync(ar()))return t.push(`config file missing: ${ar()} \u2014 run \`werkmeister config\``),t;let r=e.paths??{};for(let c of["repos_root","workspaces_root"]){let l=r[c];if(!l)t.push(`paths.${c} is not set`);else{let u=ht(String(l));Ue.existsSync(u)&&Ue.statSync(u).isDirectory()||t.push(`paths.${c} does not exist: ${l}`)}}let n=oa();n&&t.push(n),t.push(..._C(e));let s=zc();Ue.existsSync(s)?Ue.readFileSync(s,"utf8")!==Rm(e)&&t.push(`${s} is stale \u2014 run \`werkmeister config\` to regenerate`):t.push(`${s} missing \u2014 run \`werkmeister config\``);let o=ei();(!Ue.existsSync(o)||!Ue.readFileSync(o,"utf8").includes(Lv))&&t.push(`${o} does not source env.sh \u2014 run \`werkmeister config\``);let a=ia();if(Ue.existsSync(a))try{let c=JSON.parse(Ue.readFileSync(a,"utf8"));for(let l of Object.values(c.mcpServers??{}))kf(l)&&IC(l)&&"env"in l&&t.push(`${a}: werkmeister server still has a stale \`env\` block \u2014 run \`werkmeister config\``)}catch{}return t}var TC,Iv,Gz,Lv,RC,SC,EC,Yz,Jc,$C,Em,zz,AC,PC,OC,Dv,Jz,Xe=C(()=>{"use strict";h();TC=Re(rt(),1);Q();sa();Fe();Iv="^/\\S*$";i(zc,"envShPath");i(gt,"standardsDirPath");i(oa,"standardsDirProblem");i($m,"secretsPath");i(ei,"zshenvPath");i(vf,"zshrcPath");i(ia,"desktopConfigPath");Gz=[["paths","werkmeister_root","WERKMEISTER_ROOT"],["paths","repos_root","WERKMEISTER_REPOS_ROOT"],["paths","workspaces_root","WERKMEISTER_WORKSPACES_ROOT"],["overrides","mcp_port","WERKMEISTER_MCP_PORT"],["overrides","node","WERKMEISTER_NODE"],["overrides","services_yaml","WERKMEISTER_SERVICES_YAML"],["overrides","ports_yaml","WERKMEISTER_PORTS_YAML"],["overrides","model_pricing_yaml","WERKMEISTER_MODEL_PRICING_YAML"],["overrides","cache_file","WERKMEISTER_CACHE_FILE"],["ingress","certs_dir","WERKMEISTER_CERTS_DIR"]],Lv="# >>> werkmeister config >>>",RC="# <<< werkmeister config <<<",SC="# >>> werkmeister completion >>>",EC="# <<< werkmeister completion <<<",Yz=["SANDBOX_ROOT","SANDBOX_REPOS_ROOT","SANDBOX_WORKSPACES_ROOT"],Jc=[{key:"repos_root",label:"Repos root (absolute path)",help:"Directory holding the canonical source-repo clones (exported as WERKMEISTER_REPOS_ROOT).",acceptEmpty:!1,pattern:Iv,placeholder:"/Users/you/workspace"},{key:"workspaces_root",label:"Workspaces root (absolute path)",help:"Directory holding per-feature worktree workspaces (exported as WERKMEISTER_WORKSPACES_ROOT).",acceptEmpty:!1,pattern:Iv,placeholder:"/Users/you/workspace/features"}],$C={repos_root:"REPOS_ROOT",workspaces_root:"WORKSPACES_ROOT"};i(jv,"builtinPathDefault");i(Om,"pathDefault");i(kf,"isDict");i(Je,"load");i(Xc,"loadPaths");i(Dr,"candidateWorkspaceRoots");i(no,"loadJira");Em={local_domain:"local.werkmeister.io",remote_domain:"remote.werkmeister.io",certs_dir:Et.join(Zo.homedir(),".docker","certs")};i(Kt,"loadIngress");i(_f,"loadWorkspaceRepo");zz="[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?/[A-Za-z0-9._-]+$",AC={key:"workspace_repo",label:"Workspace config repo (owner/repo)",help:"GitHub repo cloned under the repos root and worktree'd as the root of every feature workspace, so .werkmeister/ configs and notes get history. Defaults to your own; point it at a shared <org>/sandbox-workspace to share workspace configs with your team.",acceptEmpty:!1,pattern:zz,placeholder:"your-org/sandbox-workspace"};i(so,"loadGithubOrg");i(CC,"loadSandboxIssuesProject");PC={key:"github_org",label:"GitHub org for service repos",help:"Owner of the repos in your services registry. Used to link the canonical examples that standards docs cite (github.com/<org>/<repo>).",acceptEmpty:!1,pattern:"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$",placeholder:"your-org"},OC="[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$",Dv=[{key:"local_domain",label:"Local ingress domain",help:"Base domain for docker features \u2014 each routed service is served at <service>.<domain> and Caddy terminates TLS for it.",acceptEmpty:!1,pattern:OC,placeholder:Em.local_domain},{key:"remote_domain",label:"Remote (K8s) ingress domain",help:"Base domain for services routed to the dev cluster instead of a local container \u2014 served at <service>.<domain>.",acceptEmpty:!1,pattern:OC,placeholder:Em.remote_domain},{key:"certs_dir",label:"Certificate directory (absolute path)",help:"Where bin/generate-certs.sh writes localhost.crt/.key; bind-mounted into the Caddy container (exported as WERKMEISTER_CERTS_DIR).",acceptEmpty:!1,pattern:Iv,placeholder:Em.certs_dir}],Jz="# Global werkmeister configuration \u2014 single source of truth.\n# Managed by `werkmeister config`; safe to hand-edit, then run `werkmeister config --check`.\n";i(Tm,"save");i(Xz,"shQuote");i(Rm,"renderEnvSh");i(Qc,"writeEnvSh");i(Qz,"managedBlock");i(Am,"stripBlock");i(Zz,"isLegacyExport");i(NC,"installBlock");i(Zc,"ensureZshenvSources");i(Cm,"ensureZshrcCompletion");i(IC,"isSandboxServer");i(Pm,"patchDesktopConfig");i(Nm,"check")});import{spawn as eJ}from"node:child_process";import LC from"node:fs/promises";import Sf from"node:os";import el from"node:path";import{stripVTControlCharacters as tJ}from"node:util";function Ie(e){return tJ(e)}async function aa(e){try{return await LC.access(e,LC.constants.X_OK),!0}catch{return!1}}function _s(){let e=[el.join(Sf.homedir(),".local","bin"),el.join(Sf.homedir(),".cargo","bin"),"/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"],t=process.env.PATH?process.env.PATH.split(el.delimiter):[],r=[...new Set([...e,...t])].join(el.delimiter);return{...process.env,PATH:r}}async function Im(){let e=[process.env.CLAUDE_BIN,el.join(Sf.homedir(),".local","bin","claude"),el.join(Sf.homedir(),".claude","local","claude"),"/opt/homebrew/bin/claude","/usr/local/bin/claude"].filter(t=>!!t);for(let t of e)if(await aa(t))return t;return"claude"}function Ze(e,t,r=Sf.homedir()){return new Promise((n,s)=>{let o=eJ(e,t,{cwd:r,env:_s(),stdio:["ignore","pipe","pipe"]}),a="",c="",l=setTimeout(()=>{o.kill("SIGKILL"),s(new z("The `claude` CLI timed out after 120s.",Gc))},12e4);o.stdout.on("data",u=>a+=u.toString()),o.stderr.on("data",u=>c+=u.toString()),o.on("error",u=>{clearTimeout(l),s(u)}),o.on("close",u=>{clearTimeout(l),n({stdout:a,stderr:c,code:u})})})}function Lm(e){let t=e.match(/<result>\s*([\s\S]*?)\s*<\/result>/i);return(t?t[1]:e).trim()}function Mv(e){let t=i(s=>{let o=s.indexOf("{"),a=s.lastIndexOf("}");return o!==-1&&a>o?s.slice(o,a+1):null},"slice"),r=t(e);if(r)try{return JSON.parse(r),r}catch{}let n=/```(?:json)?\s*([\s\S]*?)```/i.exec(e);return n?t(n[1]):r}async function Ef(e,t={}){try{let r=t.tools?["-p",e,"--dangerously-skip-permissions"]:["-p",e],n=await Ze(await Im(),r);return n.code!==0?null:Lm(Ie(n.stdout))}catch{return null}}async function jm(e,t={}){let r=await Ef(e,t),n=r===null?null:Mv(r);if(!n)return null;try{return JSON.parse(n)}catch{return null}}var tl=C(()=>{"use strict";h();Qt();i(Ie,"stripAnsi");i(aa,"isExecutable");i(_s,"childEnv");i(Im,"resolveClaudeBin");i(Ze,"runCapture");i(Lm,"extractResult");i(Mv,"extractJson");i(Ef,"askClaude");i(jm,"askClaudeJson")});function FC(e,t=so()){let r=e.trim(),n=/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/.exec(r);return n?`${n[1]}#${n[2]}`:/^[^/#]+#\d+$/.test(r)&&t?`${t}/${r}`:r}function Fm(e={}){if(e.repos?.length)return[...e.repos].sort();let t=e.org||so();if(!t)return[];let r;try{r=Object.keys(bn())}catch{r=[]}return r.sort().map(n=>`${t}/${n}`)}function MC(e){let t=Dm.exec(e);if(!t)throw new Error(`"${e}" is not a GitHub issue (owner/repo#n)`);return[t[1],t[2]]}async function oo(e){let t=await Gn([$f(),...e],{capture:!0,env:_s(),timeout:30});if(t.status!==0)throw new Error(t.stderr.trim()||`gh ${e[0]} ${e[1]} exited ${t.status}`);return t.stdout}function BC(e,t){return{ref:e,title:t.title?.trim()||void 0,status:iJ(t.state),...t.state?.toUpperCase()==="CLOSED"?{statusCategory:"done"}:{},labels:t.labels?.map(r=>r.name),type:t.labels?.map(r=>r.name).join(", ")||void 0,assignee:t.assignees?.map(r=>r.login).join(", ")||void 0,description:t.body?.trim()||void 0,url:t.url,comments:(t.comments??[]).flatMap(r=>{let n=r.body?.trim();return n?[{author:r.author?.login??"unknown",created:r.createdAt,body:n}]:[]})}}async function Bv(e,t,r){try{let[n,s]=MC(e);return BC(e,JSON.parse(await oo(["issue","view",s,"-R",n,"--json",t])))}catch(n){return r?.push(n.message),null}}function qv(e={}){let t=e.org||void 0,r=e.repos?.map(n=>n.toLowerCase());return{id:"github",label:"GitHub",refExample:"owner/repo#12",refPattern:DC,parseRef(n){let s=FC(n??"",t??so());if(Dm.test(s))return s;let o=/github\.com\/([^/\s]+\/[^/\s]+)\/issues\/(\d+)/.exec(s);return o?`${o[1]}#${o[2]}`:/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+#\d+/.exec(s)?.[0]??null},slug:i(n=>(n.split("/").pop()??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),"slug"),holds(n){let s=Dm.exec(n)?.[1].toLowerCase();return s?r?.length?r.includes(s):!t||s.startsWith(`${t.toLowerCase()}/`):!1},url(n){let s=Dm.exec(n);return s?`https://github.com/${s[1]}/issues/${s[2]}`:null},fetchIssue:i((n,s)=>Bv(n,"title,state,body,url,labels,assignees,comments",s),"fetchIssue"),async fetchIssues(n){let s=await Promise.all(n.map(o=>Bv(o,"title,state,url")));return Object.fromEntries(s.filter(o=>o!==null).map(o=>[o.ref,o]))},filingGuide(){let n=Fm(e);return{row:`| app code in a worktree | ${n.length?`the GitHub issues of the repo it belongs to \u2014 one of ${n.map(o=>`\`${o}\``).join(", ")}`:"that repo's GitHub issues \u2014 find it with `git -C <worktree> remote get-url origin`"} | \`gh issue create -R <owner>/<repo> --label <label>\` |`,search:'Search first: `gh issue list -R <owner>/<repo> --search "<keywords>" --state all`. If it exists, comment on it instead.'}},async listReady(n){if(n){let a=t||so(),c;try{c=await oo(["project","item-list",n.id,"--owner",a,"--format","json","--limit","200","--query",`status:"${n.ready}"`])}catch(u){throw new Error(`${u.message} (boards need the read:project scope: gh auth refresh -s read:project)`)}let{items:l=[]}=JSON.parse(c);return l.flatMap(({status:u,content:f})=>f?.type==="Issue"&&u?.toLowerCase()===n.ready.toLowerCase()?[{ref:`${f.repository}#${f.number}`,title:f.title,status:u,url:f.url}]:[])}let s=Fm(e);if(!s.length)throw new Error("no repos in scope");return(await Promise.all(s.map(async a=>JSON.parse(await oo(["issue","list","-R",a,"--state","open","--limit","100","--json","number,title,url,labels","--search","sort:created-asc"])).map(l=>BC(`${a}#${l.number}`,{...l,state:"OPEN"}))))).flat()},async updateIssue(n,s){let[o,a]=MC(n),c=s.status?.trim();if(c){let l=c.toLowerCase();if(rJ.has(l))await oo(["issue","close",a,"-R",o,"--reason","completed"]);else if(nJ.has(l))await oo(["issue","close",a,"-R",o,"--reason","not planned"]);else if(sJ.has(l))await oo(["issue","reopen",a,"-R",o]);else{let u=l.startsWith(jC)?((await Bv(n,"labels"))?.labels??[]).filter(f=>f.toLowerCase().startsWith(jC)&&f.toLowerCase()!==l):[];await oo(["label","create",c,"-R",o,"--color",oJ,"--force"]),await oo(["issue","edit",a,"-R",o,"--add-label",c,...u.length?["--remove-label",u.join(",")]:[]])}}s.comment&&await oo(["issue","comment",a,"-R",o,"--body",s.comment])},async checkAuth(){let n=i(a=>Gn([$f(),...a],{capture:!0,env:_s(),timeout:15}).catch(()=>null),"run"),s=await n(["auth","status","--hostname","github.com"]);if(s?.status!==0)return{ok:!1,reason:"not signed in",fix:"gh auth login"};let o=/account (\S+)/.exec(`${s.stdout}${s.stderr}`)?.[1];for(let a of Fm(e))if((await n(["repo","view",a,"--json","name"]))?.status!==0)return{ok:!1,...o?{who:o}:{},reason:`can't read ${a}`,fix:"gh auth refresh -s repo"};return{ok:!0,...o?{who:o}:{},fix:""}}}}var DC,Dm,rJ,nJ,jC,sJ,oJ,$f,iJ,qC,Uv=C(()=>{"use strict";h();tl();Q();Xe();mt();DC="^([A-Za-z0-9_.-]+/)?[A-Za-z0-9_.-]+#[0-9]+$",Dm=/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#(\d+)$/,rJ=new Set(["closed","close","done","completed"]),nJ=new Set(["not planned","abandoned"]),jC="status:",sJ=new Set(["open","reopen","reopened"]),oJ="1D76DB";i(FC,"normalizeGithubIssue");i(Fm,"githubIssueRepos");i(MC,"split");$f=i(()=>ze("GH_BIN")||"gh","ghBin");i(oo,"gh");iJ=i(e=>e?e[0]+e.slice(1).toLowerCase():void 0,"titleCase");i(BC,"fromGh");i(Bv,"view");i(qv,"githubTracker");qC=qv()});function UC(e,t,r){let n=e.trim();for(;n.endsWith("/");)n=n.slice(0,-1);return!n||!t||!r||ti(n)||ti(t)||ti(r)?null:{baseUrl:n,email:t,token:r}}async function la(){let e=UC(process.env.JIRA_BASE_URL??"",process.env.JIRA_EMAIL??"",process.env.JIRA_API_TOKEN??"");if(e)return e;try{let t=gn().jira??{};return UC(String(t.base_url??""),String(t.email??""),String(t.api_token??""))}catch{return null}}async function Of(e,t,r){let n=await fetch(`${e.baseUrl}${t}`,{method:r===void 0?"GET":"POST",headers:{Authorization:"Basic "+Buffer.from(`${e.email}:${e.token}`).toString("base64"),Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(1e4)});if(!n.ok){let s=(await n.text().catch(()=>"")).trim().slice(0,500);throw new Error(`Jira REST ${t} \u2192 HTTP ${n.status}${s?`: ${s}`:""}`)}return n}async function WC(){let e=await la();if(!e)return null;let r=await(await Of(e,"/rest/api/3/myself")).json();return{who:r.emailAddress??r.displayName??e.email}}async function ca(e,t){return await(await Of(e,t)).json()}async function KC(e,t){let r=await la();if(!r)return t?.push("no Jira REST credentials"),null;try{return await ca(r,`/rest/api/2/issue/${encodeURIComponent(e)}?fields=${aJ}`)}catch(n){return t?.push(cJ(n)),null}}function cJ(e){let t=e;if(t.message?.startsWith("Jira REST "))return t.message;let r=t.cause?.code??t.cause?.message;return`Jira REST: ${t.message}${r?` (${r})`:""}`}async function VC(e){if(!e.length)return{};let t=await la();if(!t)return null;let r=encodeURIComponent(`key in (${e.join(",")})`);try{let n=await ca(t,`/rest/api/2/search/jql?jql=${r}&fields=status&maxResults=100`),s={};for(let o of n.issues??[]){let a=o.fields?.status?.name;o.key&&a&&(s[o.key.toUpperCase()]=a)}return s}catch{return null}}async function GC(e){let t=await la();return t?(await ca(t,`/rest/api/2/search/jql?jql=${encodeURIComponent(e)}&${HC}`)).issues??[]:null}async function YC(e,t){let r=await la();if(!r)return null;let n=encodeURIComponent(e),{columnConfig:s}=await ca(r,`/rest/agile/1.0/board/${n}/configuration`),o=s?.columns??[],a=o.find(f=>f.name?.toLowerCase()===t.toLowerCase());if(!a)throw new Error(`board ${e} has no "${t}" column (it has: ${o.map(f=>f.name).join(", ")})`);let c=(a.statuses??[]).flatMap(f=>f.id?[f.id]:[]);if(!c.length)return[];let l=encodeURIComponent(`status in (${c.join(",")})`);return(await ca(r,`/rest/agile/1.0/board/${n}/issue?jql=${l}&${HC}`)).issues??[]}async function zC(e){let t=await la();if(!t)return null;let r=encodeURIComponent(e.project),{issueTypes:n=[]}=await ca(t,`/rest/api/2/issue/createmeta/${r}/issuetypes`),s=i(l=>n.some(u=>u.name?.toLowerCase()===l.toLowerCase()),"has"),o=s(e.issueType)||!s("Task")?e.issueType:"Task",a=await Of(t,"/rest/api/2/issue",{fields:{project:{key:e.project},issuetype:{name:o},summary:e.summary,description:e.description,...o===e.issueType?{}:{labels:[e.fallbackLabel]}}}),{key:c}=await a.json();return{key:c,url:`${t.baseUrl}/browse/${c}`,issueType:o}}async function JC(e,t){let r=await la();if(!r)return null;let n=`/rest/api/2/issue/${encodeURIComponent(e)}`;if(t.status){let s=t.status.trim().toLowerCase(),{transitions:o=[]}=await ca(r,`${n}/transitions`),a=o.find(c=>c.to?.name?.toLowerCase()===s)??o.find(c=>c.name?.toLowerCase()===s);if(!a){let c=o.map(l=>l.to?.name??l.name).filter(Boolean).join(", ");throw new Error(`${e} has no transition to "${t.status}" (available: ${c||"none"})`)}await Of(r,`${n}/transitions`,{transition:{id:a.id}})}return t.comment&&await Of(r,`${n}/comment`,{body:t.comment}),!0}var Wv,ti,aJ,HC,Kv=C(()=>{"use strict";h();Q();Wv=new Set(["PASTE_TOKEN_HERE","<your-atlassian-login-email>","https://your-org.atlassian.net"]),ti=i(e=>Wv.has(e.trim().replace(/\/+$/,"")),"isJiraPlaceholder");i(UC,"normalizeCreds");i(la,"jiraCreds");i(Of,"jiraFetch");i(WC,"jiraMyself");i(ca,"jiraGet");aJ="summary,description,status,issuetype,assignee,comment";i(KC,"fetchIssueRest");i(cJ,"restFailure");i(VC,"fetchStatusesRest");HC="fields=summary,status&maxResults=100";i(GC,"searchIssuesRest");i(YC,"boardColumnRest");i(zC,"createIssueRest");i(JC,"updateIssueRest")});function Mm(e){let t=(no().base_url??"").trim().replace(/\/+$/,"");return!t||ti(t)?null:`${t.includes("://")?t:`https://${t}`}/browse/${e}`}function eP(){let e=no(),t=(e.cloud_id??"").trim();if(t)return t;let r=(e.base_url??"").trim();if(!r||ti(r))return null;try{return new URL(r.includes("://")?r:`https://${r}`).hostname||null}catch{return null}}function Bm(){let e=eP();return e?`(Atlassian cloud id ${e})`:"(find the cloud id with getAccessibleAtlassianResources)"}function XC(e){let t=e.fields??{},r=(t.comment?.comments??[]).flatMap(n=>{let s=n.body?.trim();return s?[{author:n.author?.displayName??"unknown",created:n.created,body:s}]:[]});return{ref:e.key,title:Zt(t.summary),status:Zt(t.status?.name),statusCategory:tP(t.status?.statusCategory?.key),type:Zt(t.issuetype?.name),assignee:Zt(t.assignee?.displayName),description:Zt(t.description),url:Mm(e.key)??void 0,comments:r}}async function fJ(e){let t=await jm(`You are a data extractor, not an agent. Do exactly two things and nothing else:
|
|
192
192
|
1. Fetch Jira issue ${e} INCLUDING ITS COMMENTS using getJiraIssue ${Bm()} \u2014 request fields ["summary","status","issuetype","assignee","description","comment"].
|
|
193
|
-
2. Output ONLY a JSON object between <result> and </result> tags with keys "title","status","statusCategory" (the status category key: new, indeterminate or done), "type","assignee","description" (strings, "" when unavailable) and "comments" (an array of {"author","created","body"}, oldest first). `+
|
|
194
|
-
If you cannot fetch the issue, output <result>{}</result> and nothing else.`,{tools:!0});if(!t||!Zt(t.title))return null;let r=Array.isArray(t.comments)?t.comments.flatMap(n=>{if(typeof n!="object"||n===null)return[];let s=n,o=Zt(s.body);return o?[{author:Zt(s.author)??"unknown",created:Zt(s.created),body:o}]:[]}):[];return{ref:e,title:Zt(t.title),status:Zt(t.status),statusCategory:
|
|
193
|
+
2. Output ONLY a JSON object between <result> and </result> tags with keys "title","status","statusCategory" (the status category key: new, indeterminate or done), "type","assignee","description" (strings, "" when unavailable) and "comments" (an array of {"author","created","body"}, oldest first). `+rP+`
|
|
194
|
+
If you cannot fetch the issue, output <result>{}</result> and nothing else.`,{tools:!0});if(!t||!Zt(t.title))return null;let r=Array.isArray(t.comments)?t.comments.flatMap(n=>{if(typeof n!="object"||n===null)return[];let s=n,o=Zt(s.body);return o?[{author:Zt(s.author)??"unknown",created:Zt(s.created),body:o}]:[]}):[];return{ref:e,title:Zt(t.title),status:Zt(t.status),statusCategory:tP(t.statusCategory),type:Zt(t.type),assignee:Zt(t.assignee),description:Zt(t.description),url:Mm(e)??void 0,comments:r}}async function dJ(e){let t=await jm(`You are a data extractor, not an agent. Do exactly two things and nothing else:
|
|
195
195
|
1. Run searchJiraIssuesUsingJql ${Bm()} with jql 'key in (${e.join(",")})' and fields ["status"].
|
|
196
|
-
2. Output ONLY a JSON object between <result> and </result> tags mapping each issue key to its status name, e.g. {"PROJ-1234":"In Progress"}. Omit keys you could not fetch. `+
|
|
196
|
+
2. Output ONLY a JSON object between <result> and </result> tags mapping each issue key to its status name, e.g. {"PROJ-1234":"In Progress"}. Omit keys you could not fetch. `+rP+`
|
|
197
197
|
If the search fails entirely, output <result>{}</result> and nothing else.`,{tools:!0}),r={};for(let[n,s]of Object.entries(t??{})){let o=Zt(s);o&&(r[n.toUpperCase()]=o)}return r}async function pJ(e,t){let r=[t.status&&`Transition Jira issue ${e} to the status "${t.status}" with transitionJiraIssue.`,t.comment&&`Add this comment to Jira issue ${e} with addCommentToJiraIssue, verbatim:
|
|
198
198
|
${t.comment}`].filter(Boolean),n=await jm(`Do exactly this on the Jira site ${Bm()} and nothing else:
|
|
199
199
|
`+r.map((s,o)=>`${o+1}. ${s}`).join(`
|
|
200
200
|
`)+`
|
|
201
201
|
Then output ONLY <result>{"ok":true}</result>, or <result>{"ok":false,"error":"<why>"}</result> when any step failed. Write no prose outside the tags.`,{tools:!0});if(n?.ok!==!0)throw new Error(Zt(n?.error)??`Could not update ${e} through the Atlassian MCP`)}function QC(e){let t=null;return e.split(`
|
|
202
202
|
`).map(r=>{let n=/^\s*(```|~~~)\s*[\w-]*\s*$/.exec(r);if(n&&(!t||n[1]===t))return t=t?null:n[1],"{code}";if(t)return r;let s=i(c=>c.split(/(`[^`]+`)/).map(l=>l.startsWith("`")&&l.length>1?hJ(l.slice(1,-1)):l.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,"[$1|$2]")).join(""),"inline"),o=/^(#{1,6})\s+(.*)$/.exec(r);if(o)return`h${o[1].length}. ${s(o[2])}`;let a=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(r);if(a){let c=Math.floor(a[1].replace(/\t/g," ").length/2)+1;return`${(/\d/.test(a[2])?"#":"*").repeat(c)} ${s(a[3])}`}return s(r)}).join(`
|
|
203
|
-
`)}function Vv(e={}){let t=e.project?.toUpperCase();return{id:"jira",label:"Jira",refExample:"PROJ-123",refPattern:null,issueTypes:ZC,parseRef:i(r=>lJ.exec(r??"")?.[0].toUpperCase()??null,"parseRef"),slug:i(r=>r.trim().toLowerCase(),"slug"),holds:i(r=>!t||r.toUpperCase().startsWith(`${t}-`),"holds"),url:Mm,async fetchIssue(r,n){let s=await KC(r,n);if(s)return XC(s);let o=await fJ(r);return o||n?.push("the Atlassian MCP fallback returned no issue"),o},async fetchIssues(r){if(!r.length)return{};let n=await VC(r)??await dJ(r),s={};for(let[o,a]of Object.entries(n))s[o]={ref:o,status:a,url:Mm(o)??void 0};return s},filingGuide(r){let n=/^([A-Z][A-Z0-9]+)-\d+$/.exec(r)?.[1]??t,s=CC(),o=(no().base_url??"").trim().replace(/\/+$/,""),a=ti(o)||!o?"":` (${o})`,c=i(f=>`\`werkmeister issue create --project ${f??"<KEY>"} --type <type> --title "<title>" --body-file <file>\`; if it fails for want of a Jira API token, the Atlassian MCP tools if connected, otherwise hand the person the title, type and body to file`,"command"),l=i(f=>`JQL \`${f?`project = ${f} AND `:""}text ~ "<keywords>"\``,"jql");return{row:`| app code in a worktree | ${`Jira${n?`, project \`${n}\``:" \u2014 ask the person which project"}${a}`} | ${c(n)} |`,werkmeister:s?{where:`Jira, project \`${s}\`${a}`,command:c(s)}:void 0,search:`Search first: ${l(n)}. If it exists, comment on it instead. (Werkmeister issues: ${s?l(s):`\`gh issue list -R ${mJ} --search "<keywords>" --state all\``}.)`}},async createIssue({project:r,type:n,title:s,body:o}){let a=await zC({project:r,issueType:ZC[n],fallbackLabel:n,summary:s,description:QC(o)});if(!a)throw new Error("no Jira REST credentials: set jira.base_url, jira.email and jira.api_token (docs/jira-rest-setup.md), or file it with the Atlassian MCP tools");return{ref:a.key,title:s,type:a.issueType,url:a.url}},async listReady(r){if(!r&&!t)throw new Error("no Jira project in scope");let n=r?await YC(r.id,r.ready):await GC(`project = ${t} AND statusCategory != Done ORDER BY priority DESC, rank ASC`);if(!n)throw new Error("listing ready work needs Jira REST credentials (docs/jira-rest-setup.md)");return n.map(XC)},async updateIssue(r,n){let s=n.comment?{...n,comment:QC(n.comment)}:n;await JC(r,s)===null&&await pJ(r,n)},async checkAuth(){let r="set jira.base_url, jira.email and jira.api_token (docs/jira-rest-setup.md)";try{let n=await WC();if(n)return{ok:!0,who:n.who,fix:""};let s=no();return[process.env.JIRA_BASE_URL,process.env.JIRA_EMAIL,process.env.JIRA_API_TOKEN,s.base_url,s.email,s.api_token].some(a=>a&&ti(String(a)))?{ok:!1,reason:"Jira settings still hold the placeholder values",fix:r}:{ok:!0,who:"via Atlassian MCP (not checked)",fix:""}}catch(n){return{ok:!1,reason:n.message,fix:r}}}}}var lJ,Zt,uJ,
|
|
204
|
-
`)}var
|
|
205
|
-
`;)r+=1;continue}if(a==="*"){for(r+=2;r+1<n&&!(e[r]==="*"&&e[r+1]==="/");)r+=1;r+=2;continue}}t.push(o),r+=1}return t.join("")}function nl(e){let t=_n.readFileSync(e,"utf8"),r=kn.extname(e);return r===".yaml"||r===".yml"?
|
|
206
|
-
`)){if(s=s.trim(),!s||s.startsWith("#")||!s.includes("="))continue;let o=s.indexOf("="),a=s.slice(0,o).trim(),c=s.slice(o+1);a in r&&(n[r[a]]=c.trim())}return n}function fa(e,t){let r=$t(t,e.config_file??null),n=vJ(t),s={};for(let[o,a,c]of sl){let l=e[o]??null,u=a?ze(a)??null:null,f=c==="issue_id"?vn(r)||null:c in r?r[c]:null,d=c in n?n[c]:null;for(let p of[l,u,f,d]){if(p==null)continue;let m;if(Array.isArray(p)?m=p.map(y=>String(y).trim()).filter(y=>y).join(","):m=String(p).trim(),m){s[c]=m;break}}}return s.issue_id&&(s.issue_id=we({project:s.project,text:s.issue_id}).parseRef(s.issue_id)??s.issue_id),s.autonomous&&(s.autonomous=String(Es(s.autonomous))),s.auto_stop&&(s.auto_stop=String(Es(s.auto_stop))),s}function kJ(e){let t=e.split("-");return t.length&&t[0].length===4&&[...t[0].toLowerCase()].every(r=>"0123456789abcdef".includes(r))&&(t=t.slice(1)),t.length?t.join("-"):e}function _J(e){for(let t of _n.readdirSync(e).sort()){let r=kn.join(e,t);if(!wJ(r)||t.startsWith("."))continue;let n;try{n=H(["git","-C",r,"branch","--show-current"],{capture:!0,timeout:5})}catch(a){if(a instanceof Z&&(a.code==="ENOENT"||a.code==="ETIMEDOUT"))continue;throw a}if(n.status!==0)continue;let s=n.stdout.trim(),o=we({text:s}).parseRef(s);if(o)return o}return""}function da(e){let t=e.trim().toLowerCase();return Object.hasOwn(Wm,t)?Wm[t]:zv}function Hm(e,t,r,n={}){let s={key:e.key,label:e.label,help:e.help,accept_empty:e.acceptEmpty??!0,multi:e.multi??!1,recommended:e.recommended??!1,default:e.defaultFn&&n.defaults!==!1?e.defaultFn(t):e.default??"",resolved:e.key in r,resolved_value:e.key in r?r[e.key]:null};if(e.multiline&&(s.multiline=!0),e.boolean&&(s.boolean=!0),e.refinable&&(s.refinable=!0,e.refineInstruction&&(s.refine_instruction=e.refineInstruction)),e.pattern&&(s.pattern=e.pattern),e.placeholder&&(s.placeholder=e.placeholder),e.choicesFn&&(s.choices=e.choicesFn()),e.choiceGroupsFn){let o={},a=e.choiceGroupsFn();for(let c of s.choices??Object.keys(a))(o[a[c]??"other"]??=[]).push(c);s.choice_groups=Object.fromEntries(Object.entries(o).sort(([c],[l])=>c.localeCompare(l)))}return s}function EJ(){let e=jr();if(e.length){let r=[...new Set(e.map(n=>Ss(n.tracker).refExample))];return c8.map(n=>n.key==="issue_id"?{...n,placeholder:r.join(" or ")}:n)}let t=we();return c8.flatMap(r=>r.key==="project"?[]:r.key==="issue_id"?[{...r,placeholder:t.refExample,...t.refPattern?{pattern:t.refPattern}:{}}]:[r])}function $J(e,t,r={}){return{workspace_root:e,workspace_name:kn.basename(e),prompts:EJ().map(n=>Hm(n,e,t,r))}}function Jv(e){let t=e.split("-");return t.length&&t[0].length===4&&[...t[0].toLowerCase()].every(r=>"0123456789abcdef".includes(r))&&(t=t.slice(1)),t.length?t.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(" "):e}function zr(){try{return[de(),bn()]}catch{return[{},{}]}}function f8(e,t,r={}){return Xv(t,fa(e,t),r)}function Xv(e,t,r={}){let n=$J(e,t,r),s=Hm(OJ,"",t);if(s.choices.length){let o=n.prompts??[],a=o.findIndex(c=>c.key==="services");a===-1&&(a=o.length-1),o.splice(a+1,0,s),n.prompts=o}return n}var l8,sl,oi,Wm,zv,SJ,c8,OJ,wr=C(()=>{"use strict";h();l8=Re(rt(),1);hn();Q();yr();mt();sa();Fe();Um();i(wJ,"isDir");i(bJ,"stripJsoncComments");i(nl,"loadWorkspaceConfig");sl=[["feature",null,"feature"],["work_type","WORK_TYPE","work_type"],["context_strategy","CONTEXT_STRATEGY","context_strategy"],["repos","REPOS","repos"],["services","SERVICES","services"],["issue_id","ISSUE_ID","issue_id"],["project","PROJECT","project"],["test_path","TEST_PATH","test_path"],["description","DESCRIPTION","description"],["task","TASK","task"],["starting_prompt","STARTING_PROMPT","starting_prompt"],["labels","LABELS","labels"],["autonomous","AUTONOMOUS","autonomous"],["model","MODEL","model"],["auto_stop","AUTO_STOP","auto_stop"]];i(Es,"isTrue");i(Km,"readAutonomous");i(Vm,"readAutoStop");i(u8,"readModel");i(Yv,"readWorkspaceField");oi=["workspace.yml","workspace.yaml","workspace.jsonc","workspace.json"];i($t,"loadConfigFile");i(si,"expandUserPath");i(vJ,"loadExistingEnvMetadata");i(fa,"resolveInputs");i(kJ,"defaultFeatureFromDir");i(_J,"scrapeIssueId");Wm={feature:{path:"architectural",phases:["research","implement","test","review","pr"],gate:{note:"decision",status:"decided"},hint:"invoke `w9r-research` first \u2014 it ends in a `decision` note the user approves before any code"},bugfix:{path:"bounded",phases:["research","implement","test","pr"],gate:{note:"finding"},hint:"invoke `w9r-research` first to reproduce and write the root cause to a `finding` note before changing code"},incident:{path:"bounded",phases:["research","implement","test","pr"],gate:{note:"finding"},hint:"invoke `w9r-research` first to diagnose; the `finding` note is the incident record"},refactor:{path:"bounded",phases:["implement","test","review","pr"],gate:null,hint:"invoke `w9r-implement` first \u2014 the scope is known and standards matter most"},spike:{path:"spike",phases:["research"],gate:null,hint:"invoke `w9r-research` first to frame the questions; anything built is throwaway and there is no PR"}},zv={path:"architectural",phases:["research","implement","test","review","pr"],gate:null,hint:"invoke `w9r-research` first"};i(da,"planFor");SJ=Object.keys(Wm),c8=[{key:"issue_id",label:"Issue",help:"Issue ID in this machine's issue tracker. The issue is fetched and stored in the workspace; empty fields are filled from it.",defaultFn:i(e=>_J(e),"defaultFn")},{key:"project",label:"Project",help:"The project whose tracker holds the issue (projects: in ~/.werkmeister/config.yaml). Blank picks the one whose scope holds the issue, else the default project.",choicesFn:i(()=>jr().map(e=>e.name),"choicesFn"),defaultFn:i(()=>Af()?.name??"","defaultFn")},{key:"feature",label:"Feature name",help:`Lowercase, hyphen-separated. Drives workspace slot routing via the X-Feature cookie. No feature = no ${Oe} / werkmeister-context.md.`,acceptEmpty:!1,recommended:!0,pattern:"^[a-z0-9]+(-[a-z0-9]+)*$",placeholder:"mdx-blog",defaultFn:i(e=>kJ(kn.basename(e)),"defaultFn")},{key:"work_type",label:"Work type",help:"What kind of work this is; selects the phase sequence and the pre-implementation gate in CLAUDE.md.",acceptEmpty:!1,pattern:"^("+Object.keys(Wm).join("|")+")$",default:"feature",choicesFn:i(()=>[...SJ],"choicesFn")},{key:"context_strategy",label:"Workflow",help:"Which context layer init-workspace generates: jit (w9r-* skills, hooks, notes) or icm (staged folders the agent walks by itself).",pattern:"^("+Fr.join("|")+")$",default:Fr[0],choicesFn:i(()=>[...Fr],"choicesFn")},{key:"autonomous",label:"Autonomous run",help:"Off by default. On: an icm run goes from stage 01 to `werkmeister pr open` with no human check (each stage self-checks and the agent approves its own PR file), and .claude/settings.json allows the git, werkmeister, docker, gh, node and python3 calls a headless session needs. The person reviews the PR; `werkmeister pr gate` still applies.",boolean:!0},{key:"model",label:"Model",help:"Claude model for this workspace's sessions: an alias (opus, sonnet, haiku) or a full claude-\u2026 id; empty = Claude Code's default. Written to .claude/settings.json and passed as --model to claude-send and claude-resume. A cheaper model suits mechanical jobs (lint passes, renames).",pattern:"^[A-Za-z0-9][A-Za-z0-9._\\[\\]-]*$",placeholder:"sonnet"},{key:"auto_stop",label:"Auto-stop on session end",help:"On by default for autonomous workspaces, off otherwise. On: when a Claude session in the workspace ends and no other one is open there, a SessionEnd hook runs `werkmeister stop --if-idle`, which stops this feature's containers (slot and volumes kept; `werkmeister up` resumes). Shared infra is never stopped.",boolean:!0},{key:"services",label:"Services to run locally",help:"Services to run locally with hot-reload; the rest fall through to k8s port-forwards.",multi:!0,choicesFn:i(()=>Object.keys(zr()[0]).sort(),"choicesFn"),choiceGroupsFn:i(()=>Object.fromEntries(Object.entries(zr()[0]).map(([e,t])=>[e,String(t?.repo??"other")])),"choiceGroupsFn")},{key:"labels",label:"Labels",help:"Comma-separated free-form tags for filtering workspaces in the dashboard search.",multi:!0},{key:"test_path",label:"Feature test path",help:"URL path for the feature entry point, appended to the routed host.",pattern:"^/\\S*$",placeholder:"/products/foo"},{key:"task",label:"Task title",help:"Short title for the Current Task section. Defaults to the feature name in words.",defaultFn:i(e=>Jv(kn.basename(e)),"defaultFn")},{key:"description",label:"Description",help:"1-2 sentences on what the feature does and the user-visible outcome; rendered under Current Task in CLAUDE.md.",placeholder:"Adds an MDX-powered blog index under /blog."},{key:"starting_prompt",label:"Starting prompt",help:"The first instruction to hand the agent in this workspace; persisted to .werkmeister/workspace.yml.",multiline:!0,refinable:!0,refineInstruction:"Rewrite the user's text as a clear, specific, actionable starting instruction for a coding agent beginning a development task, preserving the user's intent. The rewritten instruction must state the goal \u2014 the desired end state and why it matters \u2014 and must include explicit acceptance criteria: a checklist of concrete, verifiable conditions that define when the task is done. Derive the goal and acceptance criteria from the user's text wherever possible; for any that cannot be confidently derived, the rewritten instruction must direct the agent to ask the user to supply them before proceeding, rather than guessing."}];i(Hm,"promptEntry");i(EJ,"wizardPrompts");i($J,"buildPromptSpec");i(Jv,"slugToTask");i(zr,"loadSandboxServiceConfigs");OJ={key:"repos",label:"Extra repos",help:"Extra repos to create worktrees for. The final set is the union of these and the repos owning the services selected above.",multi:!0,choicesFn:i(()=>Object.keys(bn()).sort(),"choicesFn")};i(f8,"computePromptSpec");i(Xv,"workspacePromptSpec")});function pa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cf(e,t){if(!pa(e))return null;let r=e.archetype;if(r!=null){t==null&&(t=vt());let s=t[r];return pa(s)?s:null}let n=e.standards;return n?.length?{standards:Array.from(n)}:null}function d8(e,t){let r=Cf(e,t);return Array.from(r?.standards??[])}function $s(e,t,r){if(!pa(t))return null;let n=t.test;if(n)return String(n);let o=Cf(t,r)?.test;return o?String(o).split("{service}").join(e):null}function Gm(e,t,r){return`docker exec ${e}-${t} sh -c '${r}'`}function Qv(e,t){if(!pa(e))return null;let r=e.validate;if(r)return String(r);let n=Cf(e,t)?.validate;return n?String(n):null}function Pf(e,t,r){return r?.length?[...r]:e.flatMap(n=>t[n]?.services??[])}function Ym(e,t,r,n=new Set){r==null&&(r=vt());let s=[];for(let o of[...new Set(e)].sort()){let a=t[o];if(!pa(a))continue;let c=Qv(a,r);s.push({service:o,repo:String(a.repo??""),path:String(a.path??"."),test:$s(o,a,r),validate:c??(n.has(o)?"URL health check (see Quick Health Checks)":"No validation guidance registered in services.yaml; say so instead of inventing one")})}return s}function TJ(e,t,r,n,s){s==null&&(s=vt());let o=Pf(e,r,n),a={};for(let l of o){let u=t[l];if(!pa(u))continue;let f=u.archetype;f&&f in s&&(a[f]??=[]).push(l)}let c={};for(let l of Object.keys(a).sort())c[l]=[...new Set(a[l])].sort();return c}function zm(e,t,r,n,s){let o=(t.SERVICES??"").split(",").map(a=>a.trim()).filter(a=>a);return TJ(e.map(([a])=>a),r,n,o,s)}function p8(e,t){let r=[];for(let[n,s]of Object.entries(e)){if(!pa(s))continue;let o=s.archetype;o!=null&&(o in t||r.push(`services.yaml: service '${n}' references unknown archetype '${o}' \u2014 no \`archetypes.${o}\` entry`),s.standards?.length&&r.push(`services.yaml: service '${n}' declares both \`archetype:\` and legacy \`standards:\` \u2014 drop \`standards:\` (the archetype wins)`))}return r}var Yn=C(()=>{"use strict";h();Q();i(pa,"isDict");i(Cf,"resolveServiceArchetype");i(d8,"serviceStandards");i($s,"serviceTestCommand");i(Gm,"containerTestCommand");i(Qv,"serviceValidation");i(Pf,"candidateServiceNames");i(Ym,"validationRows");i(TJ,"resolvePresentArchetypes");i(zm,"presentArchetypes");i(p8,"validateServiceArchetypes")});import*as Vt from"node:fs";import*as ii from"node:path";function DJ(){return{hooks:[{type:"command",command:AJ}]}}function FJ(){return{matcher:"Edit|Write",hooks:[{type:"command",command:CJ}]}}function x8(){return{matcher:"Bash|mcp__.*create_pull_request",hooks:[{type:"command",command:PJ}]}}function MJ(){return{hooks:[{type:"command",command:NJ,timeout:jJ}]}}function BJ(){return{hooks:[{type:"command",command:IJ}]}}function y8(e,t=Jm){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=e.hooks;return Array.isArray(r)?r.some(n=>typeof n=="object"&&n!==null&&!Array.isArray(n)&&qJ(String(n.command??""),t)):!1}function UJ(e,t,r,n){let s=t in e?e[t]:[];if(!Array.isArray(s))return!1;let o=s.filter(a=>!y8(a,n));return o.push(r),e[t]=o,!0}function nk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nf(e){return ii.join(e,".claude","settings.json")}function sk(e){if(!Vt.existsSync(e))return{};try{let t=JSON.parse(Vt.readFileSync(e,"utf8"));return nk(t)?t:null}catch{return null}}function Xm(e,t){if(Object.keys(t).length){Vt.mkdirSync(ii.dirname(e),{recursive:!0}),Vt.writeFileSync(e,JSON.stringify(t,null,2)+`
|
|
207
|
-
`);return}Vt.rmSync(e,{force:!0});try{Vt.rmdirSync(ii.dirname(e))}catch{}}function Qm(e,t){let r=Nf(e),n=sk(r);if(n===null)return r;"hooks"in n||(n.hooks={});let s=n.hooks;if(typeof s!="object"||s===null||Array.isArray(s))return r;for(let[o,a,c]of t)if(!UJ(s,o,a,c))return r;return Xm(r,n),r}function ok(e){return Qm(e,[["SessionStart",DJ(),Jm],["PreToolUse",FJ(),tk],["PreToolUse",
|
|
208
|
-
`)){let s=n.indexOf("=");s>0&&(r[n.slice(0,s).trim()]=n.slice(s+1).trim())}return r}function JJ(e){let t=zJ(e),r=t.FEATURE??"",n=(t.SERVICES??"").split(",").map(o=>o.trim()).filter(Boolean),s=r&&n.length?YJ(r,n,de(),vt()):[...
|
|
209
|
-
`)):Vt.rmSync(e,{force:!0}))}function QJ(e,t,r=[]){let n=Nf(e),s=sk(n);if(s===null)return n;let o=s.permissions??{};if(!nk(o))return n;let a={allow:t,deny:r},c=["allow","deny"];if(c.some(p=>!Array.isArray(o[p]??[])))return n;let l=
|
|
203
|
+
`)}function Vv(e={}){let t=e.project?.toUpperCase();return{id:"jira",label:"Jira",refExample:"PROJ-123",refPattern:null,issueTypes:ZC,parseRef:i(r=>lJ.exec(r??"")?.[0].toUpperCase()??null,"parseRef"),slug:i(r=>r.trim().toLowerCase(),"slug"),holds:i(r=>!t||r.toUpperCase().startsWith(`${t}-`),"holds"),url:Mm,async fetchIssue(r,n){let s=await KC(r,n);if(s)return XC(s);let o=await fJ(r);return o||n?.push("the Atlassian MCP fallback returned no issue"),o},async fetchIssues(r){if(!r.length)return{};let n=await VC(r)??await dJ(r),s={};for(let[o,a]of Object.entries(n))s[o]={ref:o,status:a,url:Mm(o)??void 0};return s},filingGuide(r){let n=/^([A-Z][A-Z0-9]+)-\d+$/.exec(r)?.[1]??t,s=CC(),o=(no().base_url??"").trim().replace(/\/+$/,""),a=ti(o)||!o?"":` (${o})`,c=i(f=>`\`werkmeister issue create --project ${f??"<KEY>"} --type <type> --title "<title>" --body-file <file>\`; if it fails for want of a Jira API token, the Atlassian MCP tools if connected, otherwise hand the person the title, type and body to file`,"command"),l=i(f=>`JQL \`${f?`project = ${f} AND `:""}text ~ "<keywords>"\``,"jql");return{row:`| app code in a worktree | ${`Jira${n?`, project \`${n}\``:" \u2014 ask the person which project"}${a}`} | ${c(n)} |`,werkmeister:s?{where:`Jira, project \`${s}\`${a}`,command:c(s)}:void 0,search:`Search first: ${l(n)}. If it exists, comment on it instead. (Werkmeister issues: ${s?l(s):`\`gh issue list -R ${mJ} --search "<keywords>" --state all\``}.)`}},async createIssue({project:r,type:n,title:s,body:o}){let a=await zC({project:r,issueType:ZC[n],fallbackLabel:n,summary:s,description:QC(o)});if(!a)throw new Error("no Jira REST credentials: set jira.base_url, jira.email and jira.api_token (docs/jira-rest-setup.md), or file it with the Atlassian MCP tools");return{ref:a.key,title:s,type:a.issueType,url:a.url}},async listReady(r){if(!r&&!t)throw new Error("no Jira project in scope");let n=r?await YC(r.id,r.ready):await GC(`project = ${t} AND statusCategory != Done ORDER BY priority DESC, rank ASC`);if(!n)throw new Error("listing ready work needs Jira REST credentials (docs/jira-rest-setup.md)");return n.map(XC)},async updateIssue(r,n){let s=n.comment?{...n,comment:QC(n.comment)}:n;await JC(r,s)===null&&await pJ(r,n)},async checkAuth(){let r="set jira.base_url, jira.email and jira.api_token (docs/jira-rest-setup.md)";try{let n=await WC();if(n)return{ok:!0,who:n.who,fix:""};let s=no();return[process.env.JIRA_BASE_URL,process.env.JIRA_EMAIL,process.env.JIRA_API_TOKEN,s.base_url,s.email,s.api_token].some(a=>a&&ti(String(a)))?{ok:!1,reason:"Jira settings still hold the placeholder values",fix:r}:{ok:!0,who:"via Atlassian MCP (not checked)",fix:""}}catch(n){return{ok:!1,reason:n.message,fix:r}}}}}var lJ,Zt,uJ,tP,rP,hJ,mJ,ZC,nP,Hv=C(()=>{"use strict";h();tl();Xe();Kv();lJ=/[A-Za-z][A-Za-z0-9]+-\d+/;i(Mm,"jiraBrowseUrl");i(eP,"jiraSiteRef");i(Bm,"jiraSitePhrase");Zt=i(e=>typeof e=="string"&&e.trim()?e.trim():void 0,"str"),uJ=["new","indeterminate","done"],tP=i(e=>uJ.find(t=>t===Zt(e)?.toLowerCase()),"category");i(XC,"fromRest");rP="Do not create, edit, transition, or comment on anything; write no prose outside the tags.";i(fJ,"fetchViaMcp");i(dJ,"statusesViaMcp");i(pJ,"updateViaMcp");hJ=i(e=>`{{${e.replace(/([-{}!*_+^~[\]|#])/g,"\\$1")}}}`,"monoEscape");i(QC,"markdownToWiki");mJ="jbbz-sandbox/werkmeister",ZC={bug:"Bug",feature:"Story",task:"Task"};i(Vv,"jiraTracker");nP=Vv()});function Ss(e){return iP[e]}function Tf(e){let t=(e??Je()).overrides?.issue_tracker;return ks.includes(t)?t:"jira"}function Rf(e){return gJ[e.tracker](e.scope)}function ri(e={}){let t=jr();if(!t.length)return null;let r=e.project?.trim();if(r){let n=t.find(s=>s.name===r);return n||(sP.has(r)||(sP.add(r),N(`project "${r}" is not in projects: of the config \u2014 using the machine's tracker`)),null)}if(!e.text)return null;for(let n of t){let s=Rf(n),o=s.parseRef(e.text);if(o&&s.holds(o))return n}return null}function Af(){let e=jr().filter(t=>t.default);return e.length===1?e[0]:null}function we(e){let t=e?ri(e):null;return t?Rf(t):iP[Tf()]}function qm(e,t=""){let r=jr();if(!r.length){if(t)throw new Error(`--project ${t}: this machine has no projects: in its config`);return null}let n=r.map(c=>c.name).join(", "),s=t?r.find(c=>c.name===t):void 0;if(t&&!s)throw new Error(`no project "${t}" (projects: ${n})`);if(!e)return s??null;let o=s??ri({text:e})??Af();if(!o)throw new Error(`${e} isn't in any project's scope; pass --project (one of: ${n})`);let a=Rf(o);if(!a.parseRef(e))throw new Error(`${e} isn't a ${a.label} issue in project ${o.name} (e.g. ${a.refExample})`);return o}function io(e){return ua(e?.project)}function vn(e){return ua(e?.issue_id)||ua(e?.jira_id)||ua(e?.github_issue)}function ni(e){return ua(e.ISSUE_ID)||ua(e.JIRA_ID)||ua(e.GITHUB_ISSUE)}function aP(e){let t=ni(e);return t?[t,we().url(t)]:null}function rl(e){let t=[`${e.ref}: ${e.title??"(no title)"}`],r=[e.status&&`Status: ${e.status}`,e.type&&`Type: ${e.type}`,e.assignee&&`Assignee: ${e.assignee}`].filter(Boolean);r.length&&t.push(r.join(" \xB7 ")),e.description&&t.push("","Description:",e.description.slice(0,xJ));let n=e.comments??[];if(n.length){t.push("",`Comments (last ${Math.min(n.length,oP)} of ${n.length}):`);for(let s of n.slice(-oP)){let o=s.created?` ${s.created.slice(0,10)}`:"";t.push(`- [${s.author}${o}] ${s.body.slice(0,yJ)}`)}}return t.join(`
|
|
204
|
+
`)}var iP,gJ,sP,ua,xJ,oP,yJ,yr=C(()=>{"use strict";h();Xe();Uv();Hv();Sm();sa();Fe();Uv();Hv();Sm();iP={jira:nP,github:qC};i(Ss,"trackerById");i(Tf,"loadIssueTracker");gJ={jira:Vv,github:qv};i(Rf,"projectTracker");sP=new Set;i(ri,"projectFor");i(Af,"defaultProject");i(we,"issueTracker");i(qm,"projectForIssue");ua=i(e=>typeof e=="string"?e.trim():"","str");i(io,"projectOf");i(vn,"issueIdOf");i(ni,"issueIdOfMeta");i(aP,"issueLink");xJ=4e3,oP=10,yJ=1e3;i(rl,"issueBriefing")});var Fr,Um=C(()=>{"use strict";h();Fr=["icm","jit"]});import*as _n from"node:fs";import*as Gv from"node:os";import*as kn from"node:path";function wJ(e){try{return _n.statSync(e).isDirectory()}catch{return!1}}function bJ(e){let t=[],r=0,n=e.length,s=!1;for(;r<n;){let o=e[r];if(s){if(t.push(o),o==="\\"&&r+1<n){t.push(e[r+1]),r+=2;continue}o==='"'&&(s=!1),r+=1;continue}if(o==='"'){s=!0,t.push(o),r+=1;continue}if(o==="/"&&r+1<n){let a=e[r+1];if(a==="/"){for(r+=2;r<n&&e[r]!==`
|
|
205
|
+
`;)r+=1;continue}if(a==="*"){for(r+=2;r+1<n&&!(e[r]==="*"&&e[r+1]==="/");)r+=1;r+=2;continue}}t.push(o),r+=1}return t.join("")}function nl(e){let t=_n.readFileSync(e,"utf8"),r=kn.extname(e);return r===".yaml"||r===".yml"?lP.parse(t):JSON.parse(bJ(t))}function Es(e){return/^(true|1|yes|on)$/i.test(String(e??"").trim())}function Km(e){return Es(Yv(e,"autonomous"))}function Vm(e){let t=Yv(e,"auto_stop");return t==null||t===""?Km(e):Es(t)}function uP(e){let t=Yv(e,"model");return typeof t=="string"&&t.trim()?t.trim():null}function Yv(e,t){let r=ze("WORKSPACE_CONFIG"),n=[...r?[si(r)]:[],...oi.map(s=>kn.join(K(e),s))];for(let s of n)if(_n.existsSync(s))try{return nl(s)?.[t]}catch{return}}function $t(e,t){let r=[];t&&r.push(si(t));let n=ze("WORKSPACE_CONFIG");n&&r.push(si(n));let s=K(e);for(let o of oi)r.push(kn.join(s,o));for(let o of r){if(!_n.existsSync(o))continue;let a;try{a=nl(o)}catch(c){return N(`Config file ${o} unreadable: ${c.message} \u2014 skipping.`),{}}return typeof a!="object"||a===null||Array.isArray(a)?(N(`Config file ${o} must be a mapping \u2014 skipping.`),{}):(O(`Loaded workspace config from ${o}`),a)}return{}}function si(e){return e==="~"?Gv.homedir():e.startsWith("~/")?kn.join(Gv.homedir(),e.slice(2)):e}function vJ(e){let t=kn.join(e,".env");if(!(_n.existsSync(t)&&_n.statSync(t).isFile()))return{};let r={};for(let[,,s]of sl)r[s.toUpperCase()]=s;r.JIRA_ID=r.GITHUB_ISSUE="issue_id";let n={};for(let s of _n.readFileSync(t,"utf8").split(`
|
|
206
|
+
`)){if(s=s.trim(),!s||s.startsWith("#")||!s.includes("="))continue;let o=s.indexOf("="),a=s.slice(0,o).trim(),c=s.slice(o+1);a in r&&(n[r[a]]=c.trim())}return n}function fa(e,t){let r=$t(t,e.config_file??null),n=vJ(t),s={};for(let[o,a,c]of sl){let l=e[o]??null,u=a?ze(a)??null:null,f=c==="issue_id"?vn(r)||null:c in r?r[c]:null,d=c in n?n[c]:null;for(let p of[l,u,f,d]){if(p==null)continue;let m;if(Array.isArray(p)?m=p.map(y=>String(y).trim()).filter(y=>y).join(","):m=String(p).trim(),m){s[c]=m;break}}}return s.issue_id&&(s.issue_id=we({project:s.project,text:s.issue_id}).parseRef(s.issue_id)??s.issue_id),s.autonomous&&(s.autonomous=String(Es(s.autonomous))),s.auto_stop&&(s.auto_stop=String(Es(s.auto_stop))),s}function kJ(e){let t=e.split("-");return t.length&&t[0].length===4&&[...t[0].toLowerCase()].every(r=>"0123456789abcdef".includes(r))&&(t=t.slice(1)),t.length?t.join("-"):e}function _J(e){for(let t of _n.readdirSync(e).sort()){let r=kn.join(e,t);if(!wJ(r)||t.startsWith("."))continue;let n;try{n=H(["git","-C",r,"branch","--show-current"],{capture:!0,timeout:5})}catch(a){if(a instanceof Z&&(a.code==="ENOENT"||a.code==="ETIMEDOUT"))continue;throw a}if(n.status!==0)continue;let s=n.stdout.trim(),o=we({text:s}).parseRef(s);if(o)return o}return""}function da(e){let t=e.trim().toLowerCase();return Object.hasOwn(Wm,t)?Wm[t]:zv}function Hm(e,t,r,n={}){let s={key:e.key,label:e.label,help:e.help,accept_empty:e.acceptEmpty??!0,multi:e.multi??!1,recommended:e.recommended??!1,default:e.defaultFn&&n.defaults!==!1?e.defaultFn(t):e.default??"",resolved:e.key in r,resolved_value:e.key in r?r[e.key]:null};if(e.multiline&&(s.multiline=!0),e.boolean&&(s.boolean=!0),e.refinable&&(s.refinable=!0,e.refineInstruction&&(s.refine_instruction=e.refineInstruction)),e.pattern&&(s.pattern=e.pattern),e.placeholder&&(s.placeholder=e.placeholder),e.choicesFn&&(s.choices=e.choicesFn()),e.choiceGroupsFn){let o={},a=e.choiceGroupsFn();for(let c of s.choices??Object.keys(a))(o[a[c]??"other"]??=[]).push(c);s.choice_groups=Object.fromEntries(Object.entries(o).sort(([c],[l])=>c.localeCompare(l)))}return s}function EJ(){let e=jr();if(e.length){let r=[...new Set(e.map(n=>Ss(n.tracker).refExample))];return cP.map(n=>n.key==="issue_id"?{...n,placeholder:r.join(" or ")}:n)}let t=we();return cP.flatMap(r=>r.key==="project"?[]:r.key==="issue_id"?[{...r,placeholder:t.refExample,...t.refPattern?{pattern:t.refPattern}:{}}]:[r])}function $J(e,t,r={}){return{workspace_root:e,workspace_name:kn.basename(e),prompts:EJ().map(n=>Hm(n,e,t,r))}}function Jv(e){let t=e.split("-");return t.length&&t[0].length===4&&[...t[0].toLowerCase()].every(r=>"0123456789abcdef".includes(r))&&(t=t.slice(1)),t.length?t.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(" "):e}function zr(){try{return[de(),bn()]}catch{return[{},{}]}}function fP(e,t,r={}){return Xv(t,fa(e,t),r)}function Xv(e,t,r={}){let n=$J(e,t,r),s=Hm(OJ,"",t);if(s.choices.length){let o=n.prompts??[],a=o.findIndex(c=>c.key==="services");a===-1&&(a=o.length-1),o.splice(a+1,0,s),n.prompts=o}return n}var lP,sl,oi,Wm,zv,SJ,cP,OJ,wr=C(()=>{"use strict";h();lP=Re(rt(),1);hn();Q();yr();mt();sa();Fe();Um();i(wJ,"isDir");i(bJ,"stripJsoncComments");i(nl,"loadWorkspaceConfig");sl=[["feature",null,"feature"],["work_type","WORK_TYPE","work_type"],["context_strategy","CONTEXT_STRATEGY","context_strategy"],["repos","REPOS","repos"],["services","SERVICES","services"],["issue_id","ISSUE_ID","issue_id"],["project","PROJECT","project"],["test_path","TEST_PATH","test_path"],["description","DESCRIPTION","description"],["task","TASK","task"],["starting_prompt","STARTING_PROMPT","starting_prompt"],["labels","LABELS","labels"],["autonomous","AUTONOMOUS","autonomous"],["model","MODEL","model"],["auto_stop","AUTO_STOP","auto_stop"]];i(Es,"isTrue");i(Km,"readAutonomous");i(Vm,"readAutoStop");i(uP,"readModel");i(Yv,"readWorkspaceField");oi=["workspace.yml","workspace.yaml","workspace.jsonc","workspace.json"];i($t,"loadConfigFile");i(si,"expandUserPath");i(vJ,"loadExistingEnvMetadata");i(fa,"resolveInputs");i(kJ,"defaultFeatureFromDir");i(_J,"scrapeIssueId");Wm={feature:{path:"architectural",phases:["research","implement","test","review","pr"],gate:{note:"decision",status:"decided"},hint:"invoke `w9r-research` first \u2014 it ends in a `decision` note the user approves before any code"},bugfix:{path:"bounded",phases:["research","implement","test","pr"],gate:{note:"finding"},hint:"invoke `w9r-research` first to reproduce and write the root cause to a `finding` note before changing code"},incident:{path:"bounded",phases:["research","implement","test","pr"],gate:{note:"finding"},hint:"invoke `w9r-research` first to diagnose; the `finding` note is the incident record"},refactor:{path:"bounded",phases:["implement","test","review","pr"],gate:null,hint:"invoke `w9r-implement` first \u2014 the scope is known and standards matter most"},spike:{path:"spike",phases:["research"],gate:null,hint:"invoke `w9r-research` first to frame the questions; anything built is throwaway and there is no PR"}},zv={path:"architectural",phases:["research","implement","test","review","pr"],gate:null,hint:"invoke `w9r-research` first"};i(da,"planFor");SJ=Object.keys(Wm),cP=[{key:"issue_id",label:"Issue",help:"Issue ID in this machine's issue tracker. The issue is fetched and stored in the workspace; empty fields are filled from it.",defaultFn:i(e=>_J(e),"defaultFn")},{key:"project",label:"Project",help:"The project whose tracker holds the issue (projects: in ~/.werkmeister/config.yaml). Blank picks the one whose scope holds the issue, else the default project.",choicesFn:i(()=>jr().map(e=>e.name),"choicesFn"),defaultFn:i(()=>Af()?.name??"","defaultFn")},{key:"feature",label:"Feature name",help:`Lowercase, hyphen-separated. Drives workspace slot routing via the X-Feature cookie. No feature = no ${Oe} / werkmeister-context.md.`,acceptEmpty:!1,recommended:!0,pattern:"^[a-z0-9]+(-[a-z0-9]+)*$",placeholder:"mdx-blog",defaultFn:i(e=>kJ(kn.basename(e)),"defaultFn")},{key:"work_type",label:"Work type",help:"What kind of work this is; selects the phase sequence and the pre-implementation gate in CLAUDE.md.",acceptEmpty:!1,pattern:"^("+Object.keys(Wm).join("|")+")$",default:"feature",choicesFn:i(()=>[...SJ],"choicesFn")},{key:"context_strategy",label:"Workflow",help:"Which context layer init-workspace generates: jit (w9r-* skills, hooks, notes) or icm (staged folders the agent walks by itself).",pattern:"^("+Fr.join("|")+")$",default:Fr[0],choicesFn:i(()=>[...Fr],"choicesFn")},{key:"autonomous",label:"Autonomous run",help:"Off by default. On: an icm run goes from stage 01 to `werkmeister pr open` with no human check (each stage self-checks and the agent approves its own PR file), and .claude/settings.json allows the git, werkmeister, docker, gh, node and python3 calls a headless session needs. The person reviews the PR; `werkmeister pr gate` still applies.",boolean:!0},{key:"model",label:"Model",help:"Claude model for this workspace's sessions: an alias (opus, sonnet, haiku) or a full claude-\u2026 id; empty = Claude Code's default. Written to .claude/settings.json and passed as --model to claude-send and claude-resume. A cheaper model suits mechanical jobs (lint passes, renames).",pattern:"^[A-Za-z0-9][A-Za-z0-9._\\[\\]-]*$",placeholder:"sonnet"},{key:"auto_stop",label:"Auto-stop on session end",help:"On by default for autonomous workspaces, off otherwise. On: when a Claude session in the workspace ends and no other one is open there, a SessionEnd hook runs `werkmeister stop --if-idle`, which stops this feature's containers (slot and volumes kept; `werkmeister up` resumes). Shared infra is never stopped.",boolean:!0},{key:"services",label:"Services to run locally",help:"Services to run locally with hot-reload; the rest fall through to k8s port-forwards.",multi:!0,choicesFn:i(()=>Object.keys(zr()[0]).sort(),"choicesFn"),choiceGroupsFn:i(()=>Object.fromEntries(Object.entries(zr()[0]).map(([e,t])=>[e,String(t?.repo??"other")])),"choiceGroupsFn")},{key:"labels",label:"Labels",help:"Comma-separated free-form tags for filtering workspaces in the dashboard search.",multi:!0},{key:"test_path",label:"Feature test path",help:"URL path for the feature entry point, appended to the routed host.",pattern:"^/\\S*$",placeholder:"/products/foo"},{key:"task",label:"Task title",help:"Short title for the Current Task section. Defaults to the feature name in words.",defaultFn:i(e=>Jv(kn.basename(e)),"defaultFn")},{key:"description",label:"Description",help:"1-2 sentences on what the feature does and the user-visible outcome; rendered under Current Task in CLAUDE.md.",placeholder:"Adds an MDX-powered blog index under /blog."},{key:"starting_prompt",label:"Starting prompt",help:"The first instruction to hand the agent in this workspace; persisted to .werkmeister/workspace.yml.",multiline:!0,refinable:!0,refineInstruction:"Rewrite the user's text as a clear, specific, actionable starting instruction for a coding agent beginning a development task, preserving the user's intent. The rewritten instruction must state the goal \u2014 the desired end state and why it matters \u2014 and must include explicit acceptance criteria: a checklist of concrete, verifiable conditions that define when the task is done. Derive the goal and acceptance criteria from the user's text wherever possible; for any that cannot be confidently derived, the rewritten instruction must direct the agent to ask the user to supply them before proceeding, rather than guessing."}];i(Hm,"promptEntry");i(EJ,"wizardPrompts");i($J,"buildPromptSpec");i(Jv,"slugToTask");i(zr,"loadSandboxServiceConfigs");OJ={key:"repos",label:"Extra repos",help:"Extra repos to create worktrees for. The final set is the union of these and the repos owning the services selected above.",multi:!0,choicesFn:i(()=>Object.keys(bn()).sort(),"choicesFn")};i(fP,"computePromptSpec");i(Xv,"workspacePromptSpec")});function pa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cf(e,t){if(!pa(e))return null;let r=e.archetype;if(r!=null){t==null&&(t=vt());let s=t[r];return pa(s)?s:null}let n=e.standards;return n?.length?{standards:Array.from(n)}:null}function dP(e,t){let r=Cf(e,t);return Array.from(r?.standards??[])}function $s(e,t,r){if(!pa(t))return null;let n=t.test;if(n)return String(n);let o=Cf(t,r)?.test;return o?String(o).split("{service}").join(e):null}function Gm(e,t,r){return`docker exec ${e}-${t} sh -c '${r}'`}function Qv(e,t){if(!pa(e))return null;let r=e.validate;if(r)return String(r);let n=Cf(e,t)?.validate;return n?String(n):null}function Pf(e,t,r){return r?.length?[...r]:e.flatMap(n=>t[n]?.services??[])}function Ym(e,t,r,n=new Set){r==null&&(r=vt());let s=[];for(let o of[...new Set(e)].sort()){let a=t[o];if(!pa(a))continue;let c=Qv(a,r);s.push({service:o,repo:String(a.repo??""),path:String(a.path??"."),test:$s(o,a,r),validate:c??(n.has(o)?"URL health check (see Quick Health Checks)":"No validation guidance registered in services.yaml; say so instead of inventing one")})}return s}function TJ(e,t,r,n,s){s==null&&(s=vt());let o=Pf(e,r,n),a={};for(let l of o){let u=t[l];if(!pa(u))continue;let f=u.archetype;f&&f in s&&(a[f]??=[]).push(l)}let c={};for(let l of Object.keys(a).sort())c[l]=[...new Set(a[l])].sort();return c}function zm(e,t,r,n,s){let o=(t.SERVICES??"").split(",").map(a=>a.trim()).filter(a=>a);return TJ(e.map(([a])=>a),r,n,o,s)}function pP(e,t){let r=[];for(let[n,s]of Object.entries(e)){if(!pa(s))continue;let o=s.archetype;o!=null&&(o in t||r.push(`services.yaml: service '${n}' references unknown archetype '${o}' \u2014 no \`archetypes.${o}\` entry`),s.standards?.length&&r.push(`services.yaml: service '${n}' declares both \`archetype:\` and legacy \`standards:\` \u2014 drop \`standards:\` (the archetype wins)`))}return r}var Yn=C(()=>{"use strict";h();Q();i(pa,"isDict");i(Cf,"resolveServiceArchetype");i(dP,"serviceStandards");i($s,"serviceTestCommand");i(Gm,"containerTestCommand");i(Qv,"serviceValidation");i(Pf,"candidateServiceNames");i(Ym,"validationRows");i(TJ,"resolvePresentArchetypes");i(zm,"presentArchetypes");i(pP,"validateServiceArchetypes")});import*as Vt from"node:fs";import*as ii from"node:path";function DJ(){return{hooks:[{type:"command",command:AJ}]}}function FJ(){return{matcher:"Edit|Write",hooks:[{type:"command",command:CJ}]}}function xP(){return{matcher:"Bash|mcp__.*create_pull_request",hooks:[{type:"command",command:PJ}]}}function MJ(){return{hooks:[{type:"command",command:NJ,timeout:jJ}]}}function BJ(){return{hooks:[{type:"command",command:IJ}]}}function yP(e,t=Jm){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=e.hooks;return Array.isArray(r)?r.some(n=>typeof n=="object"&&n!==null&&!Array.isArray(n)&&qJ(String(n.command??""),t)):!1}function UJ(e,t,r,n){let s=t in e?e[t]:[];if(!Array.isArray(s))return!1;let o=s.filter(a=>!yP(a,n));return o.push(r),e[t]=o,!0}function nk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nf(e){return ii.join(e,".claude","settings.json")}function sk(e){if(!Vt.existsSync(e))return{};try{let t=JSON.parse(Vt.readFileSync(e,"utf8"));return nk(t)?t:null}catch{return null}}function Xm(e,t){if(Object.keys(t).length){Vt.mkdirSync(ii.dirname(e),{recursive:!0}),Vt.writeFileSync(e,JSON.stringify(t,null,2)+`
|
|
207
|
+
`);return}Vt.rmSync(e,{force:!0});try{Vt.rmdirSync(ii.dirname(e))}catch{}}function Qm(e,t){let r=Nf(e),n=sk(r);if(n===null)return r;"hooks"in n||(n.hooks={});let s=n.hooks;if(typeof s!="object"||s===null||Array.isArray(s))return r;for(let[o,a,c]of t)if(!UJ(s,o,a,c))return r;return Xm(r,n),r}function ok(e){return Qm(e,[["SessionStart",DJ(),Jm],["PreToolUse",FJ(),tk],["PreToolUse",xP(),rk]])}function ik(e){return Qm(e,LJ.map(t=>[t,BJ(),gP]))}function wP(e){return Qm(e,[["PreToolUse",xP(),rk]])}function bP(e){return vP(e,[["SessionStart",Jm],["PreToolUse",tk]])}function WJ(e,t){return t?Qm(e,[["SessionEnd",MJ(),Zv]]):(vP(e,[["SessionEnd",Zv]]),Nf(e))}function vP(e,t){let r=Nf(e),n;try{n=JSON.parse(Vt.readFileSync(r,"utf8"))}catch{return[]}let s=n?.hooks;if(typeof s!="object"||s===null||Array.isArray(s))return[];let o=[];for(let[a,c]of t){let l=s[a];if(!Array.isArray(l))continue;let u=l.filter(f=>!yP(f,c));for(let f of l)u.includes(f)||o.push(...f.hooks.map(d=>String(d.command)));u.length?s[a]=u:delete s[a]}return o.length?(Object.keys(s).length||delete n.hooks,Xm(r,n),o):[]}function HJ(e,t){return e?[...hP,...ha(`up ${e}`),...ha(`restart ${e}`),...["logs","test","services"].flatMap(r=>ha(`${r} ${e}:*`)),...t.flatMap(r=>[`Bash(docker exec ${e}-${r}:*)`,`Bash(docker logs ${e}-${r}:*)`,`Bash(docker restart ${e}-${r})`])]:hP}function YJ(e,t,r,n){let s=[];for(let o of t){let a=$s(o,r[o],n);a&&s.push(`Bash(${Gm(e,o,a)})`,`Bash(${a}:*)`)}return[...new Set([...s,...kP])]}function zJ(e){let t;try{t=Vt.readFileSync(ii.join(e,".env"),"utf8")}catch{return{}}let r={};for(let n of t.split(`
|
|
208
|
+
`)){let s=n.indexOf("=");s>0&&(r[n.slice(0,s).trim()]=n.slice(s+1).trim())}return r}function JJ(e){let t=zJ(e),r=t.FEATURE??"",n=(t.SERVICES??"").split(",").map(o=>o.trim()).filter(Boolean),s=r&&n.length?YJ(r,n,de(),vt()):[...kP];return Km(e)?[...new Set([...s,...HJ(r,n)])]:s}function XJ(e){return Km(e)?GJ:[]}function ak(e){try{let t=JSON.parse(Vt.readFileSync(e,"utf8"));return nk(t)?{allow:mP(t.allow),deny:mP(t.deny),model:typeof t.model=="string"?t.model:null}:{allow:[],deny:[],model:null}}catch{return{allow:[],deny:[],model:null}}}function ek(e,t){let r={...t.allow.length?{allow:t.allow}:{},...t.deny.length?{deny:t.deny}:{},...t.model?{model:t.model}:{}},n=ak(e);JSON.stringify(t)!==JSON.stringify(n)&&(Object.keys(r).length?(Vt.mkdirSync(ii.dirname(e),{recursive:!0}),Vt.writeFileSync(e,`${JSON.stringify(r,null,2)}
|
|
209
|
+
`)):Vt.rmSync(e,{force:!0}))}function QJ(e,t,r=[]){let n=Nf(e),s=sk(n);if(s===null)return n;let o=s.permissions??{};if(!nk(o))return n;let a={allow:t,deny:r},c=["allow","deny"];if(c.some(p=>!Array.isArray(o[p]??[])))return n;let l=SP(e),u=ak(l),f={...u},d=!1;for(let p of c){let m=o[p]??[],y=new Set(u[p]),g=[...new Set(a[p])],x=m.filter(b=>!(typeof b=="string"&&y.has(b)&&!g.includes(b))),v=g.filter(b=>!x.includes(b));if(f[p]=g.filter(b=>y.has(b)||v.includes(b)),x.length===m.length&&!v.length)continue;d=!0;let k=[...x,...v];k.length?o[p]=k:delete o[p]}return d&&(Object.keys(o).length?s.permissions=o:delete s.permissions,Xm(n,s)),ek(l,f),n}function ZJ(e,t){let r=Nf(e),n=sk(r);if(n===null)return r;let s=SP(e),o=ak(s),a=n.model;return a!==void 0&&a!==o.model?(ek(s,{...o,model:null}),r):(a!==(t??void 0)&&(t?n.model=t:delete n.model,Xm(r,n)),ek(s,{...o,model:t}),r)}function If(e){QJ(e,JJ(e),XJ(e)),ZJ(e,uP(e)),WJ(e,Vm(e)),ik(e)}var Jm,tk,rk,Zv,gP,RJ,AJ,CJ,PJ,NJ,IJ,LJ,jJ,qJ,kP,KJ,_P,VJ,ha,hP,GJ,SP,mP,Zm=C(()=>{"use strict";h();Yn();Q();wr();Jm="werkmeister notes context",tk="werkmeister hooks gate",rk="werkmeister hooks pr-guard",Zv="werkmeister stop --if-idle",gP="werkmeister hooks agent-state",RJ="werkmeister skills check >/dev/null 2>&1 || werkmeister skills sync >/dev/null 2>&1",AJ=`command -v werkmeister >/dev/null 2>&1 && { ${RJ}; ${Jm}; } || true`,CJ=`command -v werkmeister >/dev/null 2>&1 && ${tk} || true`,PJ=`command -v werkmeister >/dev/null 2>&1 && ${rk} || true`,NJ=`command -v werkmeister >/dev/null 2>&1 && ${Zv} >/dev/null 2>&1 || true`,IJ=`command -v werkmeister >/dev/null 2>&1 && ${gP} || true`,LJ=["UserPromptSubmit","PreToolUse","PostToolUse","Notification","Stop","SessionEnd"],jJ=10;i(DJ,"buildSessionStartEntry");i(FJ,"buildPreToolUseGateEntry");i(xP,"buildPrGuardEntry");i(MJ,"buildSessionEndEntry");i(BJ,"buildAgentStateEntry");qJ=i((e,t)=>e.includes(t)||e.includes(t.replace(/^werkmeister /,"sandbox ")),"isManagedCommand");i(yP,"_isManaged");i(UJ,"_mergeEvent");i(nk,"_isDict");i(Nf,"_settingsPath");i(sk,"_readSettings");i(Xm,"_saveSettings");i(Qm,"_writeManaged");i(ok,"writeWorkspaceHooks");i(ik,"writeAgentStateHooks");i(wP,"writePrGuardHook");i(bP,"removeWorkspaceHooks");i(WJ,"writeAutoStopHook");i(vP,"_removeManaged");kP=["Bash(git diff:*)","Bash(git status:*)","Bash(git ls-files:*)"],KJ=["mcp__plugin_werkmeister_werkmeister__"],_P=i(e=>KJ.map(t=>`${t}${e}`),"pluginTool"),VJ=["werkmeister","w9r"],ha=i(e=>VJ.map(t=>`Bash(${t} ${e})`),"cli"),hP=["Bash(git:*)",...["pr view","pr checks","pr diff","pr list","issue view","run view","run list"].map(e=>`Bash(gh ${e}:*)`),...ha("up"),...ha("restart"),...["status","pr","issue view","issue start","init-workspace","skills","standards","notes context"].flatMap(e=>ha(`${e}:*`)),"Bash(docker ps:*)",...["npm ci","npm run","npm test","npx","node","python3"].map(e=>`Bash(${e}:*)`),...["install --frozen-lockfile","run","test","exec","turbo"].map(e=>`Bash(pnpm ${e}:*)`),...["ls","cat","grep","find","head","tail","sed","diff","wc","test","mkdir"].map(e=>`Bash(${e}:*)`),"Bash(claude plugin validate:*)","Bash(claude plugin test:*)",...["issue","issue-statuses","status","workspace-prs","kube-context","k8s-forwards-status"].flatMap(_P)];i(HJ,"autonomousRules");GJ=[...["proxy-reload","down","remove","remove-workspace","clean","setup","registry","connect","intercept","workspace","notes graduate","up infra","restart infra","stop infra"].flatMap(e=>ha(`${e}:*`)),...["stop","kill","rm","rmi","compose down","system prune","volume rm","network rm"].map(e=>`Bash(docker ${e}:*)`),...["npm","pnpm"].flatMap(e=>["publish","link","unlink","install -g","install --global","i -g","i --global","uninstall -g","uninstall --global"].map(t=>`Bash(${e} ${t}:*)`)),...["add -g","add --global","remove -g","remove --global"].map(e=>`Bash(pnpm ${e}:*)`),"Bash(gh pr merge:*)",...["kube-switch","up","stop","restart","down","create-workspace","create-workspace-form","pr-approve","ask-pr-review","claude-send","claude-resume","connect","proxy-reload","remove-service","intercept"].flatMap(_P)],SP=i(e=>ii.join(K(e),"claude-permissions.json"),"permissionsRecord");i(YJ,"buildAllowRules");i(zJ,"_readEnv");i(JJ,"workspaceAllowRules");i(XJ,"workspaceDenyRules");mP=i(e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],"_strings");i(ak,"_readRecord");i(ek,"_writeRecord");i(QJ,"writeWorkspacePermissions");i(ZJ,"writeWorkspaceModel");i(If,"writeWorkspaceSettings")});function e0(e,t="",r=we()){let{row:n,search:s,werkmeister:o}=r.filingGuide(t.trim()),a=o??{where:`https://github.com/${EP}/issues`,command:`\`gh issue create -R ${EP} --label <label>\``},c=!o,l=r.issueTypes,u=i(d=>l?` ${l[d]} |`:"","col"),f=i(d=>c?` ${d} |`:"","label");return`# Filing an issue
|
|
210
210
|
|
|
211
211
|
Log an issue when you find it, even if the notes are rough. Each issue must stand alone: a later agent should be able to act on it without re-running this workspace or asking follow-up questions.
|
|
212
212
|
|
|
@@ -301,7 +301,7 @@ ${n}
|
|
|
301
301
|
**Done when**
|
|
302
302
|
<the observable outcome that closes it>
|
|
303
303
|
~~~
|
|
304
|
-
`}var
|
|
304
|
+
`}var EP,ck=C(()=>{"use strict";h();hn();yr();EP="jbbz-sandbox/werkmeister";i(e0,"buildIssuesReportMd")});function t0(e,t=!1){return`# PR rules \u2014 read before opening, merging or closing out
|
|
305
305
|
|
|
306
306
|
These hold for every PR this workspace produces, whatever skill or command was asked for.
|
|
307
307
|
|
|
@@ -311,7 +311,7 @@ These hold for every PR this workspace produces, whatever skill or command was a
|
|
|
311
311
|
2. **PRs come only from code worktrees** \u2014 one per repo touched at a time, from that repo's PR file (below).
|
|
312
312
|
3. **Gate.** Before a PR opens, all of these hold: every earlier stage/phase is done; the PR file's acceptance table is all PASS; the code worktree is clean; each touched service's registry test command passes (\`.werkmeister/werkmeister-context.md\`); the exercise evidence is all PASS (or \`skip_exercise\` gives the reason); the repo's release check passes; the PR file reads \`status: approved\`.
|
|
313
313
|
4. **Only \`werkmeister pr open\` opens PRs.** \`gh pr create\`, \`/create-pr\` and \`finishing-a-development-branch\` are blocked inside a workspace.
|
|
314
|
-
5. **Auto-fix is always on.**
|
|
314
|
+
5. **Auto-fix is always on.** \`werkmeister pr open\` prints a \`<pr-created>\` line with each PR's URL; the Claude desktop app counts the session as the PR's opener from it. Right after, in the desktop app: bind the PR to this session (\`ccd_pr\` \`get_status\`; \`bind_pr\` with the PR's URL if it isn't bound), then turn on Auto-fix with \`ccd_pr\` \`set_monitor\` (\`auto_fix: true\`, \`address_comments: true\`, the PR's \`url\`). Don't ask first. If \`set_monitor\` is refused, don't retry: ask the person to turn Auto-fix on from the PR bar, and don't rely on \`get_status\` to confirm it. Never turn on auto-merge.
|
|
315
315
|
6. **Merge is the person's act.** Tooling never merges. Squash is the default. A PR whose commit SHAs must survive (e.g. a commit listed in \`.git-blame-ignore-revs\`) says "Merge with a merge commit" at the top of its body, and the person merges it that way; squash and rebase both rewrite SHAs.
|
|
316
316
|
7. **Close out only when every PR file is \`shipped\`, \`closed\` or \`abandoned\`, and after the post-mortem:** the werkmeister \`postmortem\` skill writes \`postmortem.md\` at the workspace root. \`werkmeister close-out\` refuses without it unless \`--skip-postmortem "<reason>"\`.
|
|
317
317
|
|
|
@@ -368,7 +368,7 @@ Lifecycle: \`working \u2192 ready \u2192 pr-open \u2192 merged \u2192 shipped \u
|
|
|
368
368
|
| \`werkmeister close-out\` | after ship: move the issue to done if shipping didn't, write \`closeout.md\`, remove the workspace, delete merged branches |
|
|
369
369
|
| \`werkmeister close-out --abandon "<reason>"\` | give up: record the reason, comment it on the issue, push and keep every branch with commits of its own, remove the workspace |
|
|
370
370
|
| \`werkmeister close-out --skip-postmortem "<reason>"\` | close out without a post-mortem, only when the person says to; the reason goes in \`closeout.md\` |
|
|
371
|
-
`}var lk=C(()=>{"use strict";h();i(t0,"buildPrRulesMd")});import*as n0 from"node:fs";import*as ao from"node:path";function tX(e){let t=e.trim().replace(/\.git$/,""),r=/^(?:ssh:\/\/)?git@([^:/]+)[:/](.+)$/.exec(t);return r?`https://${r[1]}/${r[2]}`:/^https?:\/\//.test(t)?t:""}function s0(){let e=gt(),t=i((...n)=>{try{let s=H(["git","-C",e,...n],{capture:!0,timeout:eX});return s.status===0?s.stdout.trim():""}catch{return""}},"git"),r=tX(t("remote","get-url","origin"));return r?{base:r,prefix:t("rev-parse","--show-prefix").replace(/\/+$/,"")}:null}function Lf(e,t,r="blob"){if(!e)return"";let n=ao.posix.normalize(ao.posix.join(e.prefix,t)).replace(/\/+$/,"");return n==="."?`${e.base}/${r}/HEAD`:`${e.base}/${r}/HEAD/${n}`}function rX(){let e=so();return e?`https://github.com/${e}`:""}function oX(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $
|
|
371
|
+
`}var lk=C(()=>{"use strict";h();i(t0,"buildPrRulesMd")});import*as n0 from"node:fs";import*as ao from"node:path";function tX(e){let t=e.trim().replace(/\.git$/,""),r=/^(?:ssh:\/\/)?git@([^:/]+)[:/](.+)$/.exec(t);return r?`https://${r[1]}/${r[2]}`:/^https?:\/\//.test(t)?t:""}function s0(){let e=gt(),t=i((...n)=>{try{let s=H(["git","-C",e,...n],{capture:!0,timeout:eX});return s.status===0?s.stdout.trim():""}catch{return""}},"git"),r=tX(t("remote","get-url","origin"));return r?{base:r,prefix:t("rev-parse","--show-prefix").replace(/\/+$/,"")}:null}function Lf(e,t,r="blob"){if(!e)return"";let n=ao.posix.normalize(ao.posix.join(e.prefix,t)).replace(/\/+$/,"");return n==="."?`${e.base}/${r}/HEAD`:`${e.base}/${r}/HEAD/${n}`}function rX(){let e=so();return e?`https://github.com/${e}`:""}function oX(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $P(e){return n0.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>ao.join(e,t)).sort()}function ma(e){return`w9r-${e}-standard`}function OP(e,t){t==null&&(t=cr(e));let r=new Set(Object.keys(t)),n=s0(),s={};for(let o of Object.keys(t).sort()){let a=t[o],c=r0(a.path),l={"SKILL.md":iX(o,a,c,r,n)},u=a.references_dir;if(u)for(let f of $P(u))l[`references/${ao.basename(f)}`]=lX(f);s[ma(o)]=l}return s}function iX(e,t,r,n,s){let o=aX(e,t),a=ao.basename(t.path)==="STANDARD.md"?`${e}/STANDARD.md`:`${e}.md`,c=nX.replace("{source}",Lf(s,a)||a);return r=cX(r,n,s),`---
|
|
372
372
|
name: ${ma(e)}
|
|
373
373
|
description: ${JSON.stringify(o)}
|
|
374
374
|
---
|
|
@@ -384,27 +384,27 @@ ${sX}
|
|
|
384
384
|
---
|
|
385
385
|
Full file: \`${r}\`${c}
|
|
386
386
|
`}return t+`
|
|
387
|
-
`}function o0(e,t){e==null&&(e=cr(t));let r=[];for(let n of Object.keys(e).sort()){let s=e[n],o=r0(s.path);o.includes("TODO(graduate)")&&r.push(`${n}: STANDARD.md has an unfilled TODO(graduate) marker \u2014 run w9r-author before committing`);let a=s.references_dir;if(a)for(let c of $
|
|
387
|
+
`}function o0(e,t){e==null&&(e=cr(t));let r=[];for(let n of Object.keys(e).sort()){let s=e[n],o=r0(s.path);o.includes("TODO(graduate)")&&r.push(`${n}: STANDARD.md has an unfilled TODO(graduate) marker \u2014 run w9r-author before committing`);let a=s.references_dir;if(a)for(let c of $P(a)){let l=ao.basename(c);r0(c).includes("TODO(graduate)")&&r.push(`${n}: references/${l} has an unfilled TODO(graduate) marker \u2014 run w9r-author before committing`),String(Df(c).canonical??"")==="TODO"&&r.push(`${n}: references/${l} has a placeholder canonical: TODO \u2014 fill in the real repo:path`);let d=`(references/${l})`;o.includes(d)?l.startsWith("ap-")&&!new RegExp(`^\\s*[-*] .*\\(references/${oX(l)}\\)`,"m").test(o)&&r.push(`${n}: references/${l} needs an inline don't-line bullet linking to it`):r.push(`${n}: references/${l} is not linked from STANDARD.md`)}}return r}var eX,nX,sX,jf=C(()=>{"use strict";h();Xe();mt();zn();eX=5;i(tX,"httpsRemote");i(s0,"standardsSource");i(Lf,"standardsUrl");i(rX,"serviceRepoBase");nX=`<!--
|
|
388
388
|
AUTO-GENERATED FILE \u2014 DO NOT EDIT BY HAND.
|
|
389
389
|
Source: {source} (edit that file instead)
|
|
390
390
|
Generator: werkmeister init-workspace / werkmeister skills sync
|
|
391
391
|
(packages/werkmeister-core/src/workspace_skills.ts)
|
|
392
392
|
Freshness: werkmeister skills check
|
|
393
393
|
-->
|
|
394
|
-
`,sX="> **Precedence:** these rules win over conflicting task framing. Invariant (a must-never rule): apply it and write a `decision` note \u2014 do not proceed against it even if the task asks. Rule: surface the conflict in one line, then apply the standard.";i(oX,"escapeRegex");i($
|
|
395
|
-
`).filter(a=>a)}i(t,"git");let r=new Set,n=["origin/main","main"].find(s=>t("rev-parse","--verify","--quiet",s).length);if(n){let s=t("merge-base","HEAD",n);if(s.length)for(let o of t("diff","--name-only",`${s[0]}...HEAD`))r.add(o)}for(let s of t("status","--porcelain")){let o=s.slice(3);if(o.includes(" -> ")){let a=o.split(" -> ");o=a[a.length-1]}o=o.trim().replace(/^"+|"+$/g,""),o&&r.add(o)}return[...r].sort()}function
|
|
394
|
+
`,sX="> **Precedence:** these rules win over conflicting task framing. Invariant (a must-never rule): apply it and write a `decision` note \u2014 do not proceed against it even if the task asks. Rule: surface the conflict in one line, then apply the standard.";i(oX,"escapeRegex");i($P,"globMd");i(ma,"skillNameFor");i(OP,"generateSkills");i(iX,"renderSkill");i(aX,"buildDescription");i(cX,"rewriteLinks");i(r0,"moduleBody");i(lX,"renderReference");i(o0,"validateModuleReferences")});import*as Ot from"node:fs";import*as Ft from"node:path";function ga(e){return Object.keys(e).filter(t=>typeof e[t].universal=="number").sort((t,r)=>e[t].universal-e[r].universal||(t<r?-1:1))}function uk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fX(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fk(e,t){let r="",n=0,s=t.length;for(;n<s;){let o=t[n++];if(o==="*")r+=".*";else if(o==="?")r+=".";else if(o==="["){let a=n;for(a<s&&t[a]==="!"&&a++,a<s&&t[a]==="]"&&a++;a<s&&t[a]!=="]";)a++;if(a>=s)r+="\\[";else{let c=t.slice(n,a).replace(/\\/g,"\\\\");c.startsWith("!")?c="^"+c.slice(1):c.startsWith("^")&&(c="\\"+c),r+=`[${c}]`,n=a+1}}else r+=fX(o)}return new RegExp(`^(?:${r})$`,"s").test(e)}function xa(e){try{return Ot.readdirSync(e).filter(t=>!t.startsWith(".")).map(t=>Ft.join(e,t)).filter(t=>dX(t)&&Ot.existsSync(Ft.join(t,".git"))).sort()}catch{return[]}}function dX(e){try{return Ot.statSync(e).isDirectory()}catch{return!1}}function pX(e){function t(...s){let o;try{o=H(["git","-C",e,...s],{capture:!0,timeout:uX})}catch{return[]}return o.status!==0?[]:o.stdout.split(`
|
|
395
|
+
`).filter(a=>a)}i(t,"git");let r=new Set,n=["origin/main","main"].find(s=>t("rev-parse","--verify","--quiet",s).length);if(n){let s=t("merge-base","HEAD",n);if(s.length)for(let o of t("diff","--name-only",`${s[0]}...HEAD`))r.add(o)}for(let s of t("status","--porcelain")){let o=s.slice(3);if(o.includes(" -> ")){let a=o.split(" -> ");o=a[a.length-1]}o=o.trim().replace(/^"+|"+$/g,""),o&&r.add(o)}return[...r].sort()}function RP(e,t){if(t==null&&(t=cr()),!Object.keys(t).length)return[];let r=new Set;for(let o of xa(e))for(let a of pX(o))r.add(a);if(!r.size)return[];let n=ga(t),s=[];for(let o of Object.keys(t).sort()){if(n.includes(o))continue;let a=t[o],c=a.applies_to??[],l=!1;for(let u of r)if(c.some(f=>fk(u,f))){l=!0;break}l&&s.push([o,String(a.summary??"").trim()])}for(let o of n)s.push([o,String(t[o].summary??"").trim()]);return s}function AP(e){let t=Ot.readdirSync(e,{withFileTypes:!0}),r=t.filter(s=>/^[a-z0-9-]+\.md$/.test(s.name)).map(s=>Ft.join(e,s.name)).sort(),n=t.filter(s=>s.isDirectory()&&Ot.existsSync(Ft.join(e,s.name,"STANDARD.md"))).map(s=>Ft.join(e,s.name,"STANDARD.md")).sort();return[...r,...n]}function cr(e){e==null&&(e=gt());let t={};if(!(Ot.existsSync(e)&&Ot.statSync(e).isDirectory()))return t;for(let r of AP(e)){let n=Df(r),s=n.domain;if(s){if(n.path=r,Ft.basename(r)==="STANDARD.md"){let o=Ft.join(Ft.dirname(r),"references");Ot.existsSync(o)&&Ot.statSync(o).isDirectory()&&Ot.readdirSync(o).some(a=>a.endsWith(".md"))&&(n.references_dir=o)}t[String(s)]=n}}return t}function Df(e){let t;try{t=Ot.readFileSync(e,"utf8")}catch{return{}}if(!t.startsWith(`---
|
|
396
396
|
`))return{};let r=t.indexOf(`
|
|
397
|
-
---`,4);if(r===-1)return{};let n;try{n=
|
|
398
|
-
`),r}var
|
|
397
|
+
---`,4);if(r===-1)return{};let n;try{n=TP.parse(t.slice(4,r))}catch{return{}}return uk(n)?n:{}}function dk(e,t,r){r==null&&(r=vt());let n=pP(e,r);for(let s of Object.keys(r).sort()){let o=r[s];if(uk(o))for(let a of o.standards??[])a in t||n.push(`services.yaml: archetype '${s}' lists unknown standard '${a}' \u2014 no docs/standards/${a}.md with \`domain: ${a}\``)}for(let[s,o]of Object.entries(e))if(!(!uk(o)||o.archetype))for(let a of o.standards??[])a in t||n.push(`services.yaml: service '${s}' lists unknown standard '${a}' \u2014 no docs/standards/${a}.md with \`domain: ${a}\``);return n}function hX(e){e==null&&(e=gt());let t=[];if(!(Ot.existsSync(e)&&Ot.statSync(e).isDirectory()))return t;for(let r of AP(e)){let n=Ft.relative(e,r),s=Df(r),o=s.domain;if(!(typeof o=="string"&&o.trim())){t.push(`${n}: unparseable frontmatter or missing \`domain:\``);continue}let a=s.summary;typeof a=="string"&&a.trim()||t.push(`${n}: missing or empty \`summary:\``);let c=s.applies_to;Array.isArray(c)&&c.length&&c.every(d=>typeof d=="string"&&d.trim())||t.push(`${n}: \`applies_to:\` must be a non-empty list of non-empty globs (empty means the standard never loads and never re-injects)`);let l=s.phase;l!=null&&!(Array.isArray(l)&&l.length&&l.every(d=>typeof d=="string"&&d.trim()))&&t.push(`${n}: \`phase:\` if present must be a non-empty list of strings (a scalar string silently breaks skill_gen's substring gate)`);let u=s.universal;u!=null&&!Number.isInteger(u)&&t.push(`${n}: \`universal:\` if present must be an integer (its load order) \u2014 \`universal: true\` reads as universal but silently is not`);let f=Ft.basename(r)==="STANDARD.md"?Ft.basename(Ft.dirname(r)):Ft.basename(r,".md");o.trim()!==f&&t.push(`${n}: \`domain: ${o}\` does not match its location (expected \`${f}\` \u2014 w9r-<domain>-standard would diverge from where the standard lives)`)}return t}function CP(){let e=gt(),t=oa();if(t)return{dir:e,moduleCount:0,errors:[t]};let r=cr(),n=Object.keys(r).length;return n?{dir:e,moduleCount:n,errors:[...hX(),...o0(r),...dk(de(),r)]}:{dir:e,moduleCount:n,errors:[`no standard modules found in ${e}`]}}function mX(e,t){if(!e)return new Set;let r=e.toLowerCase(),n=new Set;for(let[s,o]of Object.entries(t))(o.task_signatures??[]).some(c=>r.includes(String(c).toLowerCase()))&&n.add(s);return n}function ol(e,t,r,n,s,o,a){s==null&&(s=cr()),a==null&&(a=vt());let c;o?.length?c=[...o]:c=e.flatMap(x=>r[x]?.services??[]);let l=new Set;for(let x of c)for(let v of dP(t[x],a))l.add(v);let u=n??{},f=u.standards_override??{};for(let x of f.add??[])l.add(x);let d=["starting_prompt","task","description"].map(x=>u[x]?String(u[x]):"").join(" ");for(let x of mX(d,s))l.add(x);for(let x of f.remove??[])l.delete(x);let p=ga(s);for(let x of p)l.add(x);for(let x of[...l])x in s||l.delete(x);let m=i(x=>p.includes(x)?[0,p.indexOf(x),""]:[1,0,x],"sortKey"),y=[...l].sort((x,v)=>{let k=m(x),b=m(v);return k[0]!==b[0]?k[0]-b[0]:k[1]!==b[1]?k[1]-b[1]:k[2]<b[2]?-1:k[2]>b[2]?1:0}),g=Object.keys(s).filter(x=>!l.has(x)).sort();return[y,g]}function i0(e,t,r=null){let n=ga(t),s={};for(let a of e)n.includes(a)||(s[a]={applies_to:Array.from(t[a]?.applies_to??[]),summary:String(t[a]?.summary??"").trim()});let o={generated_by:"werkmeister init-workspace",universal:e.filter(a=>n.includes(a)),domains:s};return r&&(o.phase_gate={...r}),o}function a0(e,t){let r=Ft.join(K(e),"standards.json");return Ot.mkdirSync(Ft.dirname(r),{recursive:!0}),Ot.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
398
|
+
`),r}var TP,uX,zn=C(()=>{"use strict";h();TP=Re(rt(),1);Yn();Q();Xe();mt();jf();i(ga,"universalStandards");uX=5;i(uk,"isDict");i(fX,"escapeRegex");i(fk,"fnmatch");i(xa,"repoDirs");i(dX,"isDirFollowingLinks");i(pX,"changedPaths");i(RP,"standardsMatchingDiff");i(AP,"iterStandardFiles");i(cr,"loadStandardsModules");i(Df,"parseFrontmatter");i(dk,"validateServiceStandards");i(hX,"validateStandardModules");i(CP,"checkStandards");i(mX,"domainsMatchingTaskText");i(ol,"resolveActiveStandards");i(i0,"buildStandardsManifest");i(a0,"writeStandardsManifest")});import*as Os from"node:fs";import*as co from"node:path";function NP(e){return co.join(K(e),"graduations.yml")}function PP(e){try{let t=c0.parse(Os.readFileSync(NP(e),"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return{}}}function wX(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"decision"}function bX(e){let t=co.join(e,"stages"),r;try{r=Os.readdirSync(t).sort()}catch{return[]}return r.flatMap(n=>{let s=co.join(t,n,"output");try{return Os.readdirSync(s).filter(o=>o.endsWith(".md")).sort().map(o=>co.join(s,o))}catch{return[]}})}function vX(e,t){let r=e.split(`
|
|
399
399
|
`),n=0;if(r[0]==="---"){let l=r.indexOf("---",1);l!==-1&&(n=l+1)}let s=[],o=new Set,a=!1;for(let l=n;l<r.length;l++){if(yX.test(r[l])){a=!a;continue}if(a)continue;let u=xX.exec(r[l]);u?s.push({at:l,level:u[1].length,title:u[2]}):gX.test(r[l].trim())&&o.add(s.length-1)}let c=new Map;return[...o].map(l=>{let u=s[l],f=u?s.slice(l+1).find(y=>y.level<=u.level):s[0],d=wX(u?u.title:t),p=(c.get(d)??0)+1;c.set(d,p),p>1&&(d=`${d}-${p}`);let m=r.slice(u?u.at:n,f?f.at:r.length).join(`
|
|
400
|
-
`);return{slug:d,body:m}})}function pk(e,t){return co.relative(e,t.path)}var c0,gX,xX,yX,I8,L8=C(()=>{"use strict";h();c0=Re(rt(),1);Wn();gX=/^status:\s*decided$/,xX=/^(#{1,6})\s+(.+?)\s*#*$/,yX=/^\s*(```|~~~)/;i(N8,"statePath");i(P8,"readState");i(wX,"slugify");i(bX,"outputFiles");i(vX,"decidedSections");i(pk,"decisionId");I8={open(e){let t=P8(e),r=[],n=0;for(let s of bX(e)){let o=vX(Os.readFileSync(s,"utf8"),co.basename(s,".md"));for(let{slug:a,body:c}of o){n+=1;let l={path:`${s}#${a}`,number:n,type:"decision",slug:a,frontmatter:{},body:c},u=t[pk(e,l)]??{};l.frontmatter={type:"decision",status:"decided",refs:[],...u},!["graduated","superseded"].includes(l.frontmatter.status)&&r.push(l)}}return r},mark(e,t,r){let n=P8(e),s=pk(e,t);n[s]={...n[s],...r},Os.mkdirSync(K(e),{recursive:!0}),Os.writeFileSync(N8(e),c0.stringify(n))},cite:i((e,t)=>`decision ${String(t.number).padStart(3,"0")}, see ${pk(e,t)}`,"cite")}});function l0(e){let t=e.trim().toLowerCase();return Object.hasOwn(hk,t)?hk[t]:hk.feature}var mk,gk,xk,D8,yk,wk,kX,j8,_X,SX,hk,F8=C(()=>{"use strict";h();hn();mk="Never run `werkmeister up`, `werkmeister restart`, or `werkmeister init-workspace` to reload \u2014 they are slower, and init rewrites the stage contracts.",gk=["Confirm ponytail is active (see `_shared/standards.md`; invoke the skill only if it is not), then read the standards rows above. Restate the rule you are applying beside each edit."],xk="Run the test command exactly as `../../.werkmeister/werkmeister-context.md` states it. Redirect output to a file, trust the exit code, read back only the failing slice.",D8="Review `output/` once against `../../BRIEF.md` and the live issue (`werkmeister issue view`). Flip every `status: proposed` to `status: decided` yourself, and record each decision \u2014 and anything you would have asked a person \u2014 under `## Recommendations for reviewer` in the PR body. Then start the next stage without asking.",yk="a `| check | result |` table, each result `PASS` or `FAIL`, with the captured output under it",wk={name:"propose",job:"acceptance walk and PR files",writes:"one commit per code repo touched, `output/pr-<worktree>.md` per repo",check:"approve each PR file; `werkmeister pr open` opens it",standards:"none",contract:i(e=>({oneJob:`One job: prove each acceptance criterion, commit in each code worktree, and write one PR file per repo touched. ${e.autonomous?"You approve it after the self-check":"Approving is the person's act"}; opening is \`werkmeister pr open\`.`,inputs:["Working (this run): `../../BRIEF.md` \xA7 Acceptance criteria","Working (this run): `../*/output/` \u2014 every prior stage's artifacts","Working (this run): `git status` and `git diff --stat` in each repo you touched","Reference (every run): `../../_shared/pr-rules.md` \u2014 the PR file format and the gate"],doNotLoad:"`_shared/standards.md` (no code is written here), source files, `.werkmeister/`.",process:["Walk every acceptance criterion in `BRIEF.md`. For each, write PASS or FAIL with the file and line in a prior `output/` that proves it. A FAIL routes back to the owning stage \u2014 do not fix it here.","In each code worktree you touched (`git -C <repo>`), commit on its branch with a message that names the change, not the stage. For a repo with `ship: tag` and a `release_check` in the registry, add the release entry it needs (e.g. a changeset) in the same commit.","Write `output/pr-<worktree>.md` per repo touched, in the format of `_shared/pr-rules.md`, at `status: draft`. Title: `<type>(<scope>): <ISSUE-ID> <summary>`. Body: summary, the test and exercise results from prior outputs, the acceptance table from step 1, and `Fixes <issue>` when the tracker is GitHub.","Commit and push this folder's branch \u2014 the record. Never open a PR for it."],outputs:["One commit per code repo touched, on that worktree's branch","`output/pr-<worktree>.md` per repo"],humanCheck:"Read each `pr-*.md`. Set `status: approved` on each one to open \u2014 that flip is the approval. Then `werkmeister pr open` runs the gate and opens it. Merging is yours. After the release, `werkmeister pr status`, then the post-mortem (`postmortem` skill), then ask the person before `werkmeister close-out`. Code written after a PR merged (e.g. found at release) is a follow-up: `werkmeister pr new <worktree> --slug <slug>`.",selfCheck:"Review each `pr-*.md` once against `../../BRIEF.md` and the live issue. Add `## Recommendations for reviewer` to its body \u2014 every decision and question collected on the way \u2014 then set `status: approved` yourself and run `werkmeister pr open`. Stop at the PR URL. Merging is the person's."}),"contract")},kX=[{name:"research",job:"inventory the code, surface decisions",writes:"`output/inventory.md`, `output/decisions.md`",check:"answer every open question in `decisions.md`",standards:"none",contract:i(e=>({oneJob:"One job: establish what the code the brief touches does today, and turn the brief's open questions into an editable decision sheet. No code is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`",`Working (this run): the files in ${e.repos} that \`BRIEF.md\` names \u2014 grep for call sites, don't read whole trees`],doNotLoad:`\`_shared/standards.md\` (nothing is written here), other stages' contracts, \`.werkmeister/*.yml\`, \`${Oe}\`.`,process:["List what exists that the brief touches: entry points, routes or exports, data shapes, and the tests that cover them.","Find the test command in `../../.werkmeister/werkmeister-context.md` and copy it verbatim \u2014 do not restate it from memory.","Check what is already installed that could do the job before recommending anything new.","Write `output/inventory.md`: steps 1\u20133.","Write `output/decisions.md`: every open question in `BRIEF.md`, each as a heading with `status: proposed`, your recommended answer, and the evidence from steps 1\u20133. Leave the answer blank when only a person can give it (a ticket key, a preference)."],outputs:["`output/inventory.md`","`output/decisions.md`"],humanCheck:"Open `output/decisions.md`. Edit each answer as needed and change its `status: proposed` to `status: decided`. The next stage must not start while any question is still `proposed`. When every question reads `decided`, that is the approval \u2014 the next session starts the next stage without asking for confirmation."}),"contract")},{name:"spec",job:"write the spec for the change",writes:"`output/spec.md`, any checkable artifact in the repo",check:"the spec covers every acceptance criterion",enter:"every question in `stages/01_research/output/decisions.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"universal",contract:i(e=>({oneJob:"One job: turn the settled decisions into a spec precise enough that the next stage needs no judgment calls, and prove any machine-checkable part of it.",inputs:[`Working (this run): \`${e.at("research")}/output/inventory.md\``,`Working (this run): \`${e.at("research")}/output/decisions.md\` \u2014 every entry must read \`status: decided\`; if not, stop and route back to that stage's human check`,"Reference (every run): `../../BRIEF.md` \xA7 Acceptance criteria"],doNotLoad:"source files already summarised in `inventory.md` (if it looks wrong, fix `inventory.md` and tell the person), `.werkmeister/*.yml`, other stages.",process:["Write `output/spec.md`: what changes, file by file; the interfaces or schemas added; the tests that will prove it; what is explicitly out of scope.","If the change has a machine-checkable artifact (a schema, an API document, a migration), write it in the repo and validate it with a command that needs no new dependency. Record the exact command in `spec.md`.","Map each acceptance criterion in `BRIEF.md` to the step or test in `spec.md` that satisfies it. A criterion with no mapping is a defect in this stage."],outputs:["`output/spec.md`","Any artifact from step 2, in the repo"],humanCheck:"Read `output/spec.md` against the brief. Edit it directly \u2014 the next stage builds whatever is on disk."}),"contract")},{name:"implement",job:"build it and prove it",writes:"code diff, `output/exercise.md`",check:"read the diff; tests green",standards:"all",contract:i(e=>({oneJob:"One job: make the changes `spec.md` lists, add the tests it names, and prove them against the running service.",inputs:[`Working (this run): \`${e.at("spec")}/output/spec.md\` and the files it names`,`Working (this run): \`${e.at("research")}/output/decisions.md\``,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 container names, published ports, test command"],doNotLoad:`\`BRIEF.md\` (\`decisions.md\` and \`spec.md\` carry the settled scope), \`inventory.md\`, \`.werkmeister/*.yml\`, \`${Oe}\`, other stages.`,process:[...gk,"Make the changes `spec.md` lists, and only those. No new runtime dependency unless `decisions.md` justified one in a line.","Add the tests `spec.md` names. Match the style of the nearest existing test; no new test framework.",xk,`Reload the running code: ${e.restart}. ${mk} Then exercise the change as the How-to-validate section of \`werkmeister-context.md\` describes for each service touched, and capture the output. Run a CLI from a temp folder, not only with a temp HOME: it reads its workspace from the current folder.`,`Write \`output/exercise.md\`: \`git diff --stat\` for each repo you touched, the test exit code and summary line, the exercise checks as ${yk}, and any deviation from \`spec.md\` with its reason.`],outputs:["Code changes, uncommitted \u2014 the next stage commits after the person reads the diff","`output/exercise.md`"],humanCheck:"Read the diff. Run the tests yourself. Edit the code in place if something is off \u2014 the next stage commits what is on disk."}),"contract")},wk],j8=[{name:"reproduce",job:"reproduce and locate the root cause",writes:"`output/repro.md`",check:"agree the root cause",standards:"none",contract:i(e=>({oneJob:"One job: make the failure happen on demand and name its root cause. No fix is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`",`Working (this run): the files in ${e.repos} on the failing path \u2014 follow the call chain, don't read whole trees`,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 container names, published ports, logs, test command"],doNotLoad:"`_shared/standards.md` (nothing is written here), other stages' contracts, `.werkmeister/*.yml`.",process:["Reproduce the failure against the running service or with a test. Record the exact command and its output.","Write the smallest failing test that captures it, in the style of the nearest existing test. Do not commit it yet.","Trace to the root cause: the first place the code does something other than intended. A symptom site is not a root cause.","List every other caller of the function at the root cause \u2014 a fix there reaches them too.","Write `output/repro.md`: steps 1\u20134, and a proposed fix in one paragraph under a `status: proposed` line."],outputs:["`output/repro.md`","One failing test, uncommitted"],humanCheck:"Read `output/repro.md`. Correct the root cause or the proposed fix if needed, then change `status: proposed` to `status: decided`. That is the approval \u2014 the next session starts the fix without asking again."}),"contract")},{name:"fix",job:"fix it at the root cause",writes:"code diff, `output/fix.md`",check:"read the diff; the failing test now passes",enter:"`stages/01_reproduce/output/repro.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"all",contract:i(e=>({oneJob:"One job: make the failing test pass by changing the code at the root cause, and nothing else.",inputs:[`Working (this run): \`${e.at("reproduce")}/output/repro.md\` \u2014 must read \`status: decided\`; if not, stop and route back`,"Working (this run): the failing test and the files at the root cause","Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 test command"],doNotLoad:"`BRIEF.md` (`repro.md` carries the settled scope), `.werkmeister/*.yml`, other stages.",process:[...gk,"Apply the fix `repro.md` settled, at the root cause. Every caller `repro.md` lists gets the fix through the shared function \u2014 do not patch callers one by one.",xk,"Write `output/fix.md`: `git diff --stat` per repo, the failing test's name, and the test exit code and summary line."],outputs:["Code changes plus the test, uncommitted","`output/fix.md`"],humanCheck:"Read the diff. Confirm the fix sits where `repro.md` put the root cause. Edit in place if not."}),"contract")},{name:"exercise",job:"prove it against the running service",writes:"`output/exercise.md`",check:"the original reproduction no longer fails",standards:"none",contract:i(e=>({oneJob:"One job: show the original failure is gone in the running service, not just in the test.",inputs:[`Working (this run): \`${e.at("reproduce")}/output/repro.md\` \u2014 the reproduction steps`,`Working (this run): \`${e.at("fix")}/output/fix.md\``,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 container names, published ports"],doNotLoad:"`_shared/standards.md` (no code is written here), source files, `.werkmeister/*.yml`.",process:[`Reload the running code: ${e.restart}. ${mk}`,"Rerun the reproduction steps from `repro.md` exactly. Capture the output.","Exercise one neighbouring path through each caller `repro.md` listed. Capture the output.",`Write \`output/exercise.md\`: steps 2\u20133 as ${yk}.`],outputs:["`output/exercise.md`"],humanCheck:"Read `exercise.md`. A FAIL sends the run back to the fix stage."}),"contract")},wk],_X=[{name:"scope",job:"fix the boundary and the invariants",writes:"`output/scope.md`",check:"agree what must not change",standards:"none",contract:i(e=>({oneJob:"One job: pin down what the refactor may touch and what behaviour must not change. No code is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`",`Working (this run): the files in ${e.repos} that \`BRIEF.md\` names, and their callers`],doNotLoad:"`_shared/standards.md` (nothing is written here), other stages' contracts, `.werkmeister/*.yml`.",process:["List the files in scope and every caller outside it.","State the invariants: observable behaviour that must be identical after the refactor.","Name the existing tests that pin each invariant, and the gaps no test covers.","Write `output/scope.md`: steps 1\u20133, the sequence of small steps you propose, and a `status: proposed` line."],outputs:["`output/scope.md`"],humanCheck:"Read `output/scope.md`. Correct the scope or invariants, then change `status: proposed` to `status: decided`. That is the approval \u2014 the next session starts without asking again."}),"contract")},{name:"implement",job:"refactor in green steps",writes:"code diff, `output/exercise.md`",check:"read the diff; tests green at every step",enter:"`stages/01_scope/output/scope.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"all",contract:i(e=>({oneJob:"One job: carry out the steps `scope.md` settled, keeping every invariant true after each one.",inputs:[`Working (this run): \`${e.at("scope")}/output/scope.md\` \u2014 must read \`status: decided\``,"Working (this run): the files in scope","Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 test command"],doNotLoad:"`BRIEF.md` (`scope.md` carries the settled scope), `.werkmeister/*.yml`, other stages.",process:[...gk,"First add a test for each invariant gap `scope.md` named. They must pass before any code moves.",`Take the steps in order. After each one: ${xk}`,`Reload and exercise the service once at the end: ${e.restart}. ${mk}`,`Write \`output/exercise.md\`: \`git diff --stat\` per repo, the test result after each step, and the final exercise checks as ${yk}.`],outputs:["Code changes, uncommitted","`output/exercise.md`"],humanCheck:"Read the diff against `scope.md`. Anything outside scope goes back."}),"contract")},wk],SX=[{name:"questions",job:"frame what the spike must answer",writes:"`output/questions.md`",check:"agree the questions and what settles them",standards:"none",contract:i(()=>({oneJob:"One job: turn the brief into questions, each with the evidence that would settle it. No code is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`"],doNotLoad:"source trees, `_shared/standards.md`, `.werkmeister/*.yml`.",process:["List the questions the brief asks or implies, most decision-relevant first.","For each: how it will be answered (read code, measure, prototype) and what result settles it.","Write `output/questions.md`: steps 1\u20132 and a `status: proposed` line."],outputs:["`output/questions.md`"],humanCheck:"Edit the questions, then change `status: proposed` to `status: decided`. That is the approval \u2014 the next session starts without asking again."}),"contract")},{name:"findings",job:"answer them with evidence",writes:"`output/findings.md`",check:"decide the next piece of work",enter:"`stages/01_questions/output/questions.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"none",contract:i(e=>({oneJob:"One job: answer each settled question with evidence, and recommend what to build next.",inputs:[`Working (this run): \`${e.at("questions")}/output/questions.md\` \u2014 must read \`status: decided\``,`Working (this run): whatever each question's method names, in ${e.repos}`,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 ports, containers","Reference (when the brief asks for a repo deliverable): `../../_shared/pr-rules.md` \u2014 the PR file format and the gate"],doNotLoad:"`_shared/standards.md` (prototype code is throwaway), `.werkmeister/*.yml`.",process:["Answer each question by its method. Prototype code lives in `output/` or on a scratch branch, never on the workspace branch.","Write `output/findings.md`: per question, the answer, the evidence (commands and output), and confidence.","End `findings.md` with a recommendation: the next work item and its work type.","If the brief asks for a deliverable in a code repo (e.g. a doc opened as a PR): commit it on that worktree's branch, and write `output/pr-<worktree>.md` in the format of `_shared/pr-rules.md` at `status: draft`, with an acceptance table and `skip_exercise: <reason>` when there is nothing to exercise."],outputs:["`output/findings.md`","`output/pr-<worktree>.md` per repo \u2014 only when the brief asks for a repo deliverable"],humanCheck:"Read `findings.md`. The recommendation becomes the brief of the next workspace, or the spike ends here. If there is a `pr-*.md`, set `status: approved`; `werkmeister pr open` runs the gate and opens it, and close-out waits for it to ship. Otherwise, when the recommendation is recorded where it is needed, the post-mortem (`postmortem` skill), then `werkmeister close-out`."}),"contract")}],hk={feature:kX,bugfix:j8,incident:j8,refactor:_X,spike:SX};i(l0,"templateFor")});function ya(e){let t=e.url?`[${e.ref}](${e.url})`:e.ref,r=e.title?`: ${e.title}`:"",n=e.fetchedAt?`Copy taken ${e.fetchedAt.slice(0,10)}: \`.werkmeister/issue.md\`.`:"No stored copy; run `werkmeister init-workspace --refresh-issue`.";return["## Issue","",`${t}${r}. ${n}`,"Before each stage, re-read the live issue for newer direction: `werkmeister issue view`","Its status moves by itself (In Progress \u2192 In Review \u2192 Done): `docs/workspace-lifecycle.md` \xA7 Issue status in the werkmeister repo.",""].join(`
|
|
401
|
-
`)}var u0=C(()=>{"use strict";h();i(ya,"renderIssueRef")});import*as er from"node:fs";import*as Ht from"node:path";function
|
|
402
|
-
`)}function PX(e,t){if(e==="none")return"";let r=ga(t.modules);return`- Reference (every run): \`../../_shared/standards.md\` \u2014 rows ${[...e==="all"?t.active:t.active.filter(s=>r.includes(s)),"ponytail"].map(s=>`\`${s}\``).join(", ")}`}function IX(e,t,r,n=!1){let s=t.contract(r);return[`# ${e} \u2014 ${t.job}`,"",s.oneJob,"","## Inputs",...s.inputs.map(o=>`- ${o}`),...r.standards?[r.standards]:[],"",`Do NOT load: ${s.doNotLoad}`,"","## Process",...n?[`0. ${NX}`]:[],...s.process.map((o,a)=>`${a+1}. ${o}`),"","## Outputs",...s.outputs.map(o=>`- ${o}`),"",...r.autonomous?["## Self-check",s.selfCheck??
|
|
403
|
-
`)}function LX(e,t){let r=ai(t),n=
|
|
404
|
-
`)}function DX(e){return["## Stop points","","Walk every stage without stopping: each stage's self-check is its approval. Stop only at:","",
|
|
400
|
+
`);return{slug:d,body:m}})}function pk(e,t){return co.relative(e,t.path)}var c0,gX,xX,yX,IP,LP=C(()=>{"use strict";h();c0=Re(rt(),1);Wn();gX=/^status:\s*decided$/,xX=/^(#{1,6})\s+(.+?)\s*#*$/,yX=/^\s*(```|~~~)/;i(NP,"statePath");i(PP,"readState");i(wX,"slugify");i(bX,"outputFiles");i(vX,"decidedSections");i(pk,"decisionId");IP={open(e){let t=PP(e),r=[],n=0;for(let s of bX(e)){let o=vX(Os.readFileSync(s,"utf8"),co.basename(s,".md"));for(let{slug:a,body:c}of o){n+=1;let l={path:`${s}#${a}`,number:n,type:"decision",slug:a,frontmatter:{},body:c},u=t[pk(e,l)]??{};l.frontmatter={type:"decision",status:"decided",refs:[],...u},!["graduated","superseded"].includes(l.frontmatter.status)&&r.push(l)}}return r},mark(e,t,r){let n=PP(e),s=pk(e,t);n[s]={...n[s],...r},Os.mkdirSync(K(e),{recursive:!0}),Os.writeFileSync(NP(e),c0.stringify(n))},cite:i((e,t)=>`decision ${String(t.number).padStart(3,"0")}, see ${pk(e,t)}`,"cite")}});function l0(e){let t=e.trim().toLowerCase();return Object.hasOwn(hk,t)?hk[t]:hk.feature}var mk,gk,xk,DP,yk,wk,kX,jP,_X,SX,hk,FP=C(()=>{"use strict";h();hn();mk="Never run `werkmeister up`, `werkmeister restart`, or `werkmeister init-workspace` to reload \u2014 they are slower, and init rewrites the stage contracts.",gk=["Confirm ponytail is active (see `_shared/standards.md`; invoke the skill only if it is not), then read the standards rows above. Restate the rule you are applying beside each edit."],xk="Run the test command exactly as `../../.werkmeister/werkmeister-context.md` states it. Redirect output to a file, trust the exit code, read back only the failing slice.",DP="Review `output/` once against `../../BRIEF.md` and the live issue (`werkmeister issue view`). Flip every `status: proposed` to `status: decided` yourself, and record each decision \u2014 and anything you would have asked a person \u2014 under `## Recommendations for reviewer` in the PR body. Then start the next stage without asking.",yk="a `| check | result |` table, each result `PASS` or `FAIL`, with the captured output under it",wk={name:"propose",job:"acceptance walk and PR files",writes:"one commit per code repo touched, `output/pr-<worktree>.md` per repo",check:"approve each PR file; `werkmeister pr open` opens it",standards:"none",contract:i(e=>({oneJob:`One job: prove each acceptance criterion, commit in each code worktree, and write one PR file per repo touched. ${e.autonomous?"You approve it after the self-check":"Approving is the person's act"}; opening is \`werkmeister pr open\`.`,inputs:["Working (this run): `../../BRIEF.md` \xA7 Acceptance criteria","Working (this run): `../*/output/` \u2014 every prior stage's artifacts","Working (this run): `git status` and `git diff --stat` in each repo you touched","Reference (every run): `../../_shared/pr-rules.md` \u2014 the PR file format and the gate"],doNotLoad:"`_shared/standards.md` (no code is written here), source files, `.werkmeister/`.",process:["Walk every acceptance criterion in `BRIEF.md`. For each, write PASS or FAIL with the file and line in a prior `output/` that proves it. A FAIL routes back to the owning stage \u2014 do not fix it here.","In each code worktree you touched (`git -C <repo>`), commit on its branch with a message that names the change, not the stage. For a repo with `ship: tag` and a `release_check` in the registry, add the release entry it needs (e.g. a changeset) in the same commit.","Write `output/pr-<worktree>.md` per repo touched, in the format of `_shared/pr-rules.md`, at `status: draft`. Title: `<type>(<scope>): <ISSUE-ID> <summary>`. Body: summary, the test and exercise results from prior outputs, the acceptance table from step 1, and `Fixes <issue>` when the tracker is GitHub.","Commit and push this folder's branch \u2014 the record. Never open a PR for it."],outputs:["One commit per code repo touched, on that worktree's branch","`output/pr-<worktree>.md` per repo"],humanCheck:"Read each `pr-*.md`. Set `status: approved` on each one to open \u2014 that flip is the approval. Then `werkmeister pr open` runs the gate and opens it. Merging is yours. After the release, `werkmeister pr status`, then the post-mortem (`postmortem` skill), then ask the person before `werkmeister close-out`. Code written after a PR merged (e.g. found at release) is a follow-up: `werkmeister pr new <worktree> --slug <slug>`.",selfCheck:"Review each `pr-*.md` once against `../../BRIEF.md` and the live issue. Add `## Recommendations for reviewer` to its body \u2014 every decision and question collected on the way \u2014 then set `status: approved` yourself and run `werkmeister pr open`. Stop at the PR URL. Merging is the person's."}),"contract")},kX=[{name:"research",job:"inventory the code, surface decisions",writes:"`output/inventory.md`, `output/decisions.md`",check:"answer every open question in `decisions.md`",standards:"none",contract:i(e=>({oneJob:"One job: establish what the code the brief touches does today, and turn the brief's open questions into an editable decision sheet. No code is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`",`Working (this run): the files in ${e.repos} that \`BRIEF.md\` names \u2014 grep for call sites, don't read whole trees`],doNotLoad:`\`_shared/standards.md\` (nothing is written here), other stages' contracts, \`.werkmeister/*.yml\`, \`${Oe}\`.`,process:["List what exists that the brief touches: entry points, routes or exports, data shapes, and the tests that cover them.","Find the test command in `../../.werkmeister/werkmeister-context.md` and copy it verbatim \u2014 do not restate it from memory.","Check what is already installed that could do the job before recommending anything new.","Write `output/inventory.md`: steps 1\u20133.","Write `output/decisions.md`: every open question in `BRIEF.md`, each as a heading with `status: proposed`, your recommended answer, and the evidence from steps 1\u20133. Leave the answer blank when only a person can give it (a ticket key, a preference)."],outputs:["`output/inventory.md`","`output/decisions.md`"],humanCheck:"Open `output/decisions.md`. Edit each answer as needed and change its `status: proposed` to `status: decided`. The next stage must not start while any question is still `proposed`. When every question reads `decided`, that is the approval \u2014 the next session starts the next stage without asking for confirmation."}),"contract")},{name:"spec",job:"write the spec for the change",writes:"`output/spec.md`, any checkable artifact in the repo",check:"the spec covers every acceptance criterion",enter:"every question in `stages/01_research/output/decisions.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"universal",contract:i(e=>({oneJob:"One job: turn the settled decisions into a spec precise enough that the next stage needs no judgment calls, and prove any machine-checkable part of it.",inputs:[`Working (this run): \`${e.at("research")}/output/inventory.md\``,`Working (this run): \`${e.at("research")}/output/decisions.md\` \u2014 every entry must read \`status: decided\`; if not, stop and route back to that stage's human check`,"Reference (every run): `../../BRIEF.md` \xA7 Acceptance criteria"],doNotLoad:"source files already summarised in `inventory.md` (if it looks wrong, fix `inventory.md` and tell the person), `.werkmeister/*.yml`, other stages.",process:["Write `output/spec.md`: what changes, file by file; the interfaces or schemas added; the tests that will prove it; what is explicitly out of scope.","If the change has a machine-checkable artifact (a schema, an API document, a migration), write it in the repo and validate it with a command that needs no new dependency. Record the exact command in `spec.md`.","Map each acceptance criterion in `BRIEF.md` to the step or test in `spec.md` that satisfies it. A criterion with no mapping is a defect in this stage."],outputs:["`output/spec.md`","Any artifact from step 2, in the repo"],humanCheck:"Read `output/spec.md` against the brief. Edit it directly \u2014 the next stage builds whatever is on disk."}),"contract")},{name:"implement",job:"build it and prove it",writes:"code diff, `output/exercise.md`",check:"read the diff; tests green",standards:"all",contract:i(e=>({oneJob:"One job: make the changes `spec.md` lists, add the tests it names, and prove them against the running service.",inputs:[`Working (this run): \`${e.at("spec")}/output/spec.md\` and the files it names`,`Working (this run): \`${e.at("research")}/output/decisions.md\``,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 container names, published ports, test command"],doNotLoad:`\`BRIEF.md\` (\`decisions.md\` and \`spec.md\` carry the settled scope), \`inventory.md\`, \`.werkmeister/*.yml\`, \`${Oe}\`, other stages.`,process:[...gk,"Make the changes `spec.md` lists, and only those. No new runtime dependency unless `decisions.md` justified one in a line.","Add the tests `spec.md` names. Match the style of the nearest existing test; no new test framework.",xk,`Reload the running code: ${e.restart}. ${mk} Then exercise the change as the How-to-validate section of \`werkmeister-context.md\` describes for each service touched, and capture the output. Run a CLI from a temp folder, not only with a temp HOME: it reads its workspace from the current folder.`,`Write \`output/exercise.md\`: \`git diff --stat\` for each repo you touched, the test exit code and summary line, the exercise checks as ${yk}, and any deviation from \`spec.md\` with its reason.`],outputs:["Code changes, uncommitted \u2014 the next stage commits after the person reads the diff","`output/exercise.md`"],humanCheck:"Read the diff. Run the tests yourself. Edit the code in place if something is off \u2014 the next stage commits what is on disk."}),"contract")},wk],jP=[{name:"reproduce",job:"reproduce and locate the root cause",writes:"`output/repro.md`",check:"agree the root cause",standards:"none",contract:i(e=>({oneJob:"One job: make the failure happen on demand and name its root cause. No fix is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`",`Working (this run): the files in ${e.repos} on the failing path \u2014 follow the call chain, don't read whole trees`,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 container names, published ports, logs, test command"],doNotLoad:"`_shared/standards.md` (nothing is written here), other stages' contracts, `.werkmeister/*.yml`.",process:["Reproduce the failure against the running service or with a test. Record the exact command and its output.","Write the smallest failing test that captures it, in the style of the nearest existing test. Do not commit it yet.","Trace to the root cause: the first place the code does something other than intended. A symptom site is not a root cause.","List every other caller of the function at the root cause \u2014 a fix there reaches them too.","Write `output/repro.md`: steps 1\u20134, and a proposed fix in one paragraph under a `status: proposed` line."],outputs:["`output/repro.md`","One failing test, uncommitted"],humanCheck:"Read `output/repro.md`. Correct the root cause or the proposed fix if needed, then change `status: proposed` to `status: decided`. That is the approval \u2014 the next session starts the fix without asking again."}),"contract")},{name:"fix",job:"fix it at the root cause",writes:"code diff, `output/fix.md`",check:"read the diff; the failing test now passes",enter:"`stages/01_reproduce/output/repro.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"all",contract:i(e=>({oneJob:"One job: make the failing test pass by changing the code at the root cause, and nothing else.",inputs:[`Working (this run): \`${e.at("reproduce")}/output/repro.md\` \u2014 must read \`status: decided\`; if not, stop and route back`,"Working (this run): the failing test and the files at the root cause","Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 test command"],doNotLoad:"`BRIEF.md` (`repro.md` carries the settled scope), `.werkmeister/*.yml`, other stages.",process:[...gk,"Apply the fix `repro.md` settled, at the root cause. Every caller `repro.md` lists gets the fix through the shared function \u2014 do not patch callers one by one.",xk,"Write `output/fix.md`: `git diff --stat` per repo, the failing test's name, and the test exit code and summary line."],outputs:["Code changes plus the test, uncommitted","`output/fix.md`"],humanCheck:"Read the diff. Confirm the fix sits where `repro.md` put the root cause. Edit in place if not."}),"contract")},{name:"exercise",job:"prove it against the running service",writes:"`output/exercise.md`",check:"the original reproduction no longer fails",standards:"none",contract:i(e=>({oneJob:"One job: show the original failure is gone in the running service, not just in the test.",inputs:[`Working (this run): \`${e.at("reproduce")}/output/repro.md\` \u2014 the reproduction steps`,`Working (this run): \`${e.at("fix")}/output/fix.md\``,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 container names, published ports"],doNotLoad:"`_shared/standards.md` (no code is written here), source files, `.werkmeister/*.yml`.",process:[`Reload the running code: ${e.restart}. ${mk}`,"Rerun the reproduction steps from `repro.md` exactly. Capture the output.","Exercise one neighbouring path through each caller `repro.md` listed. Capture the output.",`Write \`output/exercise.md\`: steps 2\u20133 as ${yk}.`],outputs:["`output/exercise.md`"],humanCheck:"Read `exercise.md`. A FAIL sends the run back to the fix stage."}),"contract")},wk],_X=[{name:"scope",job:"fix the boundary and the invariants",writes:"`output/scope.md`",check:"agree what must not change",standards:"none",contract:i(e=>({oneJob:"One job: pin down what the refactor may touch and what behaviour must not change. No code is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`",`Working (this run): the files in ${e.repos} that \`BRIEF.md\` names, and their callers`],doNotLoad:"`_shared/standards.md` (nothing is written here), other stages' contracts, `.werkmeister/*.yml`.",process:["List the files in scope and every caller outside it.","State the invariants: observable behaviour that must be identical after the refactor.","Name the existing tests that pin each invariant, and the gaps no test covers.","Write `output/scope.md`: steps 1\u20133, the sequence of small steps you propose, and a `status: proposed` line."],outputs:["`output/scope.md`"],humanCheck:"Read `output/scope.md`. Correct the scope or invariants, then change `status: proposed` to `status: decided`. That is the approval \u2014 the next session starts without asking again."}),"contract")},{name:"implement",job:"refactor in green steps",writes:"code diff, `output/exercise.md`",check:"read the diff; tests green at every step",enter:"`stages/01_scope/output/scope.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"all",contract:i(e=>({oneJob:"One job: carry out the steps `scope.md` settled, keeping every invariant true after each one.",inputs:[`Working (this run): \`${e.at("scope")}/output/scope.md\` \u2014 must read \`status: decided\``,"Working (this run): the files in scope","Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 test command"],doNotLoad:"`BRIEF.md` (`scope.md` carries the settled scope), `.werkmeister/*.yml`, other stages.",process:[...gk,"First add a test for each invariant gap `scope.md` named. They must pass before any code moves.",`Take the steps in order. After each one: ${xk}`,`Reload and exercise the service once at the end: ${e.restart}. ${mk}`,`Write \`output/exercise.md\`: \`git diff --stat\` per repo, the test result after each step, and the final exercise checks as ${yk}.`],outputs:["Code changes, uncommitted","`output/exercise.md`"],humanCheck:"Read the diff against `scope.md`. Anything outside scope goes back."}),"contract")},wk],SX=[{name:"questions",job:"frame what the spike must answer",writes:"`output/questions.md`",check:"agree the questions and what settles them",standards:"none",contract:i(()=>({oneJob:"One job: turn the brief into questions, each with the evidence that would settle it. No code is written in this stage.",inputs:["Working (this run): `../../BRIEF.md`"],doNotLoad:"source trees, `_shared/standards.md`, `.werkmeister/*.yml`.",process:["List the questions the brief asks or implies, most decision-relevant first.","For each: how it will be answered (read code, measure, prototype) and what result settles it.","Write `output/questions.md`: steps 1\u20132 and a `status: proposed` line."],outputs:["`output/questions.md`"],humanCheck:"Edit the questions, then change `status: proposed` to `status: decided`. That is the approval \u2014 the next session starts without asking again."}),"contract")},{name:"findings",job:"answer them with evidence",writes:"`output/findings.md`",check:"decide the next piece of work",enter:"`stages/01_questions/output/questions.md` reads `status: decided` \u2014 the flip *is* the approval, do not ask again",standards:"none",contract:i(e=>({oneJob:"One job: answer each settled question with evidence, and recommend what to build next.",inputs:[`Working (this run): \`${e.at("questions")}/output/questions.md\` \u2014 must read \`status: decided\``,`Working (this run): whatever each question's method names, in ${e.repos}`,"Reference (every run): `../../.werkmeister/werkmeister-context.md` \u2014 ports, containers","Reference (when the brief asks for a repo deliverable): `../../_shared/pr-rules.md` \u2014 the PR file format and the gate"],doNotLoad:"`_shared/standards.md` (prototype code is throwaway), `.werkmeister/*.yml`.",process:["Answer each question by its method. Prototype code lives in `output/` or on a scratch branch, never on the workspace branch.","Write `output/findings.md`: per question, the answer, the evidence (commands and output), and confidence.","End `findings.md` with a recommendation: the next work item and its work type.","If the brief asks for a deliverable in a code repo (e.g. a doc opened as a PR): commit it on that worktree's branch, and write `output/pr-<worktree>.md` in the format of `_shared/pr-rules.md` at `status: draft`, with an acceptance table and `skip_exercise: <reason>` when there is nothing to exercise."],outputs:["`output/findings.md`","`output/pr-<worktree>.md` per repo \u2014 only when the brief asks for a repo deliverable"],humanCheck:"Read `findings.md`. The recommendation becomes the brief of the next workspace, or the spike ends here. If there is a `pr-*.md`, set `status: approved`; `werkmeister pr open` runs the gate and opens it, and close-out waits for it to ship. Otherwise, when the recommendation is recorded where it is needed, the post-mortem (`postmortem` skill), then `werkmeister close-out`."}),"contract")}],hk={feature:kX,bugfix:jP,incident:jP,refactor:_X,spike:SX};i(l0,"templateFor")});function ya(e){let t=e.url?`[${e.ref}](${e.url})`:e.ref,r=e.title?`: ${e.title}`:"",n=e.fetchedAt?`Copy taken ${e.fetchedAt.slice(0,10)}: \`.werkmeister/issue.md\`.`:"No stored copy; run `werkmeister init-workspace --refresh-issue`.";return["## Issue","",`${t}${r}. ${n}`,"Before each stage, re-read the live issue for newer direction: `werkmeister issue view`","Its status moves by itself (In Progress \u2192 In Review \u2192 Done): `docs/workspace-lifecycle.md` \xA7 Issue status in the werkmeister repo.",""].join(`
|
|
401
|
+
`)}var u0=C(()=>{"use strict";h();i(ya,"renderIssueRef")});import*as er from"node:fs";import*as Ht from"node:path";function BP(e){return(e??"").split(",").map(t=>t.trim()).filter(t=>t)}function ai(e){return e.map((t,r)=>`${String(r+1).padStart(2,"0")}_${t.name}`)}function qP(e,t){let r=ai(t),n;try{n=er.readdirSync(Ht.join(e,"stages")).filter(s=>/^\d+_/.test(s))}catch{return[]}return n.filter(s=>!r.includes(s)).sort()}function UP(e){let t=e.findIndex(r=>r.name==="propose");return t<0?null:ai(e)[t]}function $X(e){return UP(e)??ai(e)[e.length-1]}function OX(e,t){let[r]=zr(),n=i(c=>Kc.includes(r[c]?.type??""),"isIdle"),s=i(c=>c.map(l=>`\`${e}-${l}\``).join(", "),"names"),o=t.filter(c=>!n(c)),a=t.filter(n);return[o.length?o.map(c=>`\`docker restart ${e}-${c}\``).join(", "):"",a.length?`${s(a)} run no watcher, so a restart rebuilds nothing: build and test inside them with \`docker exec\` as \`.werkmeister/werkmeister-context.md\` \xA7 Test commands shows`:""].filter(Boolean).join("; ")}function WP(e,t){let r=ai(t),n=(e.meta.FEATURE??"").trim(),s=BP(e.meta.SERVICES),o=e.repos.map(([a])=>a);return{at:i(a=>`../${r[t.findIndex(c=>c.name===a)]}`,"at"),repos:o.length?o.map(a=>`\`../../${a}/\``).join(", "):"the code worktrees in this workspace",restart:n&&s.length?OX(n,s):"restart whatever serves the change as `.werkmeister/werkmeister-context.md` describes",standards:"",autonomous:Es(e.inputs.autonomous)}}function TX(e){let t=cr();if(!Object.keys(t).length)return N(oa()||`no standard modules found in ${gt()} \u2014 _shared/standards.md lists none`),{active:[],notActive:[],modules:t};let[r,n]=zr(),[s,o]=ol(e.repos.map(([a])=>a),r,n,$t(e.workspaceRoot,e.configOverride),t,BP(e.meta.SERVICES));return{active:s,notActive:o,modules:t}}function RX(e){let t=Array.isArray(e.applies_to)?e.applies_to.map(String):[];return!t.length||t.includes("**/*")?"any code edit":"editing "+t.map(r=>`\`${r}\``).join(", ")}function AX(e){return"<standards_dir>/"+Ht.relative(gt(),e.path).split(Ht.sep).join("/")}function CX(e){let t=["# Coding standards (factory)","","Read from their one home, not copied. Load only the rows a stage's contract names.","","| Standard | Read | Applies when |","|---|---|---|",...e.active.map(r=>`| ${r} | \`${AX(e.modules[r])}\` | ${RX(e.modules[r])} |`),EX,"","`<standards_dir>` is this machine's standards tree: `werkmeister standards check` prints its path (`overrides.standards_dir` in `werkmeister config`), and `werkmeister setup` grants Claude Code read access to it.",""];return e.notActive.length&&t.push(`Not applicable to this workspace (do not load): ${e.notActive.join(", ")}.`,""),t.push("Before writing code on a path a standard governs, restate the one rule you are applying in a line next to the edit \u2014 a rule read twenty tool calls ago no longer steers.",""),t.join(`
|
|
402
|
+
`)}function PX(e,t){if(e==="none")return"";let r=ga(t.modules);return`- Reference (every run): \`../../_shared/standards.md\` \u2014 rows ${[...e==="all"?t.active:t.active.filter(s=>r.includes(s)),"ponytail"].map(s=>`\`${s}\``).join(", ")}`}function IX(e,t,r,n=!1){let s=t.contract(r);return[`# ${e} \u2014 ${t.job}`,"",s.oneJob,"","## Inputs",...s.inputs.map(o=>`- ${o}`),...r.standards?[r.standards]:[],"",`Do NOT load: ${s.doNotLoad}`,"","## Process",...n?[`0. ${NX}`]:[],...s.process.map((o,a)=>`${a+1}. ${o}`),"","## Outputs",...s.outputs.map(o=>`- ${o}`),"",...r.autonomous?["## Self-check",s.selfCheck??DP]:["## Human check",s.humanCheck],""].join(`
|
|
403
|
+
`)}function LX(e,t){let r=ai(t),n=WP(e,t);return[`# Workspace: ${e.workspaceName}`,"",e.task,"",...e.issue?[ya(e.issue)]:[],"Read this file, then `CONTEXT.md`, then only the one stage `CONTEXT.md` the routing table sends you to. Nothing else up front.","","## Where things live","","| Path | Holds |","|---|---|","| `BRIEF.md` | the run's input: goal, acceptance criteria, open questions |",...e.issue?.fetchedAt?["| `.werkmeister/issue.md` | the issue as fetched at creation; refresh with `werkmeister init-workspace --refresh-issue` |"]:[],"| `CONTEXT.md` | the pipeline in one screen |","| `stages/NN_*/` | one stage each: `CONTEXT.md` (contract) + `output/` (this run's artifacts) |","| `_shared/` | factory: the coding standards and `issues-report.md` (fix a bug here or file an issue \u2014 bug, feature or task \u2014 and how), same every run |",...e.repos.map(([s,o])=>`| \`${s}/\` | code worktree${o?`, branch \`${o}\``:""} |`),"| this folder's git branch | the run's record (contracts + stage outputs): commit and push it; never open a PR from it or merge it |","| `.werkmeister/werkmeister-context.md` | generated infra facts: how to validate, test command, ports, container names |",`| \`.werkmeister/*.yml\`, \`${Oe}\`, \`.env\` | generated by \`werkmeister\`; do not hand-edit |`,"",`\`werkmeister up\` is safe here. Do not rerun \`werkmeister init-workspace\` unless you mean to regenerate this file and the stage contracts. To reload code after an edit, ${n.restart}.`,"","## Route by what just happened","","| If | Go to | Stop when |","|---|---|---|",...t.map((s,o)=>`| ${o===0?"starting the run":s.enter??`\`${r[o-1]}\` output ${n.autonomous?"self-checked":"approved"}`} | \`stages/${r[o]}/CONTEXT.md\` | ${n.autonomous?"`output/` written and self-checked":"a person has read `output/`"} |`),"| asked to open or create a PR \u2014 including `/create-pr` or `finishing-a-development-branch` | `_shared/pr-rules.md`, then `werkmeister pr open`, then Auto-fix on (rule 5) | PR URL is in the PR file and Auto-fix is on |","| a PR merged or released, or asked to close out | `werkmeister pr status`, then the werkmeister `postmortem` skill (writes `postmortem.md`), then ask the person before `werkmeister close-out` | `postmortem.md` written, then closed out after the person says yes |","| asked for status | `ls stages/*/output/` | report which stages hold artifacts |","| containers / ports / routing broken | `.werkmeister/werkmeister-context.md` | \u2014 |","| you hit a bug or need to log a feature/task \u2014 in the `werkmeister` tool or in a repo's code | `_shared/issues-report.md`: if this workspace's changes caused a bug, fix it here; otherwise file an issue where it belongs | fixed, or issue URL reported to the person |","",...n.autonomous?DX(t):jX,""].join(`
|
|
404
|
+
`)}function DX(e){return["## Stop points","","Walk every stage without stopping: each stage's self-check is its approval. Stop only at:","",UP(e)?"1. the PR URL from `werkmeister pr open`":"1. the last stage's `output/` written","2. a question only a person can answer","3. a gate failure outside this issue's scope","","The gate (`werkmeister pr gate`: tests, clean worktree, exercise PASS, release check) still applies; `skip_tests` only for a service this workspace doesn't run, with the reason."]}function FX(e,t){let r=ai(t);return[`# ${e.workspaceName} \u2014 the pipeline`,"",`| Stage | Job | Output | ${Es(e.inputs.autonomous)?"Self-check":"Human check"} |`,"|---|---|---|---|",...t.map((n,s)=>`| \`${r[s]}\` | ${n.job} | ${n.writes} | ${n.check} |`),"","Factory (stable, every run): `_shared/standards.md`, `_shared/issues-report.md`","Product (new each run): each stage's `output/`, plus the commits in the code worktrees","","Status is whatever exists: a stage is COMPLETE when its `output/` holds a real artifact \u2014 `.gitkeep` does not count.",""].join(`
|
|
405
405
|
`)}function UX(e){let t=(e.inputs.starting_prompt??"").trim(),r=(e.inputs.description??"").trim(),n=!!e.issue?.fetchedAt;return!e.issue||!n&&!r&&!t?["---","source: .werkmeister/workspace.yml (starting_prompt)","---","",`# Brief: ${e.task}`,"",t||MX,""].join(`
|
|
406
406
|
`):["---",`source: .werkmeister/workspace.yml (description, starting_prompt)${n?", .werkmeister/issue.md":""}`,"---","",`# Brief: ${e.task}`,"",ya(e.issue),...r?[r,""]:[],...t?[t,""]:[],...n&&!r&&!t?[BX,""]:[]].join(`
|
|
407
|
-
`)}function
|
|
407
|
+
`)}function KP(e){let t=l0(e.inputs.work_type??""),r=ai(t),n=TX(e),s=WP(e,t),o={"_shared/standards.md":CX(n),"_shared/issues-report.md":e0(e.workspaceName,ni(e.meta),we({project:e.inputs.project,text:ni(e.meta)}))};return o["_shared/pr-rules.md"]=t0(`stages/${$X(t)}/output/`,s.autonomous),t.forEach((a,c)=>{o[`stages/${r[c]}/CONTEXT.md`]=IX(r[c],a,{...s,standards:PX(a.standards,n)},c===0&&!!ni(e.meta))}),o}function WX(e){let t=$t(e,null),r={};for(let[,,n]of sl){let s=t[n];s!=null&&(r[n]=Array.isArray(s)?s.map(String).join(","):String(s))}return{workspaceRoot:e,workspaceName:Ht.basename(e),repos:xa(e).map(n=>[Ht.basename(n),""]),task:r.task??"",meta:{FEATURE:r.feature??"",SERVICES:r.services??""},inputs:r,configOverride:null}}function VP(e,t,r){let n=Ht.join(e,t);er.mkdirSync(Ht.dirname(n),{recursive:!0}),er.writeFileSync(n,r)}function MP(e){let t=WX(e);return qP(e,l0(t.inputs.work_type??"")).length?[]:Object.entries(KP(t)).filter(([r,n])=>{try{return er.readFileSync(Ht.join(e,r),"utf8")!==n}catch{return!0}})}function KX(e){let t=e.workspaceRoot,r=l0(e.inputs.work_type??""),n=qP(t,r);n.length&&N(`stages/ holds ${n.join(", ")}, which the current ${e.inputs.work_type||"feature"} template does not render \u2014 left CLAUDE.md, CONTEXT.md, _shared/ and stages/ as they are so the run keeps its pipeline. To regenerate them from the current template, move stages/ aside and rerun.`);let s=n.length?{}:{"CLAUDE.md":LX(e,r),"CONTEXT.md":FX(e,r),...KP(e)},o=Ht.join(t,"BRIEF.md"),a=er.existsSync(o)?er.readFileSync(o,"utf8"):null;(a===null||e.issue?.fetchedAt&&qX.test(a))&&(s["BRIEF.md"]=UX(e));for(let[c,l]of Object.entries(s))VP(t,c,l),D(`Wrote ${c}`);for(let c of n.length?[]:ai(r)){let l=Ht.join(t,"stages",c,"output");er.existsSync(l)||(er.mkdirSync(l,{recursive:!0}),er.writeFileSync(Ht.join(l,".gitkeep"),""))}bk.refresh(t)}var EX,NX,jX,MX,BX,qX,bk,HP=C(()=>{"use strict";h();hn();Q();Xe();Zm();yr();ck();lk();Fe();zn();wr();LP();FP();u0();EX="| ponytail | already loaded: the ponytail plugin's SessionStart hook prints `PONYTAIL MODE ACTIVE` in every session. Invoke the `ponytail` skill only if that line is missing from your session context | any code edit |";i(BP,"list");i(ai,"stageDirs");i(qP,"foreignStageDirs");i(UP,"proposeDir");i($X,"prDir");i(OX,"restartLine");i(WP,"vars");i(TX,"resolveStandards");i(RX,"appliesWhen");i(AX,"standardsPath");i(CX,"renderStandards");i(PX,"standardsRef");NX="Run `werkmeister issue start`: it moves the issue to In Progress, and does nothing when the issue is already past that or the tracker refuses.";i(IX,"renderContract");i(LX,"renderClaudeMd");jX=["## The one rule","","Nothing moves to the next stage until a person has read \u2014 and edited if needed \u2014 the previous stage's `output/`. The next stage reads whatever is there. The person's edit (a `decided` status, or a \"proceed\" after a gate) is the approval; never ask them to confirm it a second time."];i(DX,"stopPoints");i(FX,"renderPipeline");MX="_No starting prompt was given. Write the goal, acceptance criteria and open questions here before starting the first stage._",BX="_Read `.werkmeister/issue.md`, then write the goal, acceptance criteria and open questions here before starting the first stage._",qX=/^---\nsource: \.(?:sandbox|werkmeister)\/workspace\.yml \(starting_prompt\)\n---\n\n# Brief: [^\n]*\n\n_No starting prompt was given\. [^\n]*_\n$/;i(UX,"renderBrief");i(KP,"render");i(WX,"contextFromDisk");i(VP,"writeRel");i(MP,"drifted");i(KX,"init");bk={id:"icm",init:KX,refresh(e){for(let r of bP(e))O(`Removed JIT hook from .claude/settings.json: ${r}`);let t=Ht.join(K(e),".gate");er.existsSync(t)&&(er.rmSync(t,{recursive:!0,force:!0}),O(`Removed ${Ht.basename(K(e))}/.gate/`)),wP(e),If(e)},check:i(e=>MP(e).map(([t])=>t),"check"),sync(e){let t=[];for(let[r,n]of MP(e))VP(e,r,n),O(`wrote ${r}`),t.push(r);return{wrote:t}},sessionContext:i(()=>null,"sessionContext"),gate(){},ownedPaths:i(()=>["CLAUDE.md","CONTEXT.md","BRIEF.md","_shared","stages"],"ownedPaths"),decisions:IP}});import*as lo from"node:fs";import*as Ff from"node:path";function VX(){return`---
|
|
408
408
|
name: ${vk}
|
|
409
409
|
description: Research agent for this workspace. Investigates code and reports
|
|
410
410
|
findings with proposed fixes. Writes findings to .werkmeister/notes/; never
|
|
@@ -412,7 +412,7 @@ description: Research agent for this workspace. Investigates code and reports
|
|
|
412
412
|
tools: Read, Grep, Glob, Write
|
|
413
413
|
---
|
|
414
414
|
|
|
415
|
-
${
|
|
415
|
+
${GP}
|
|
416
416
|
You investigate code in this workspace and report findings. Do not modify
|
|
417
417
|
source files \u2014 the implement phase is a separate, user-invoked step. Your
|
|
418
418
|
Write tool exists solely for the note below.
|
|
@@ -475,7 +475,7 @@ workspace note:
|
|
|
475
475
|
3. Return only a 2-3 sentence summary, the note's path, and the OPEN
|
|
476
476
|
QUESTIONS / AMBIGUITIES list. The note is the durable record; your reply
|
|
477
477
|
is just the pointer.
|
|
478
|
-
`}function
|
|
478
|
+
`}function YP(e,t,r,n="",s={},o=""){let a=[];for(let[c,l]of Object.entries(e)){let u=r[c]??{},f=[];for(let d of l){let p=t[d]??{},m=s[d]?.hostname;f.push({name:d,repo:p.repo,command:$s(d,p,r),validate:Qv(p,r),url:n&&m?`https://${m}/${o.replace(/^\/+/,"")}`:null})}a.push({archetype:c,services:f,standards:[...u.standards??[]],feature:n})}return a}function HX(e){let t=e.archetype,r=e.services,n=r.map(f=>f.name).join(", "),s=[];for(let f of r)f.command?s.push(`- ${f.name} \u2014 run from \`${f.repo}/\`: \`${f.command}\``+(f.validate?`
|
|
479
479
|
validate: ${f.validate}`:"")):s.push(`- ${f.name} \u2014 no test command registered in services.yaml; say so instead of inventing one`);let o=s.join(`
|
|
480
480
|
`),a=e.feature??"",c=r.filter(f=>f.url).map(f=>`- ${f.name} \u2014 guard: \`docker ps --format '{{.Names}}' | grep -x ${a}-${f.name}\`
|
|
481
481
|
check: \`curl -sk -b "X-Feature=${a}" -o /dev/null -w "HTTP %{http_code}\\n" "${f.url}"\``),l=c.length?`
|
|
@@ -496,7 +496,7 @@ description: Runs and interprets tests for this workspace's ${t}
|
|
|
496
496
|
tools: Read, Grep, Glob, Bash, Edit
|
|
497
497
|
---
|
|
498
498
|
|
|
499
|
-
${
|
|
499
|
+
${GP}
|
|
500
500
|
You run and interpret tests for this workspace's ${t} services.
|
|
501
501
|
|
|
502
502
|
TEST COMMANDS \u2014 each runs from the named repo directory at the workspace
|
|
@@ -514,15 +514,15 @@ RETURN CONTRACT \u2014 report, per service tested:
|
|
|
514
514
|
bootstrapped) reported as BLOCKED with the error \u2014 do not "fix" the
|
|
515
515
|
environment beyond running the tests;
|
|
516
516
|
- OPEN QUESTIONS / AMBIGUITIES for the human to resolve.
|
|
517
|
-
`}function
|
|
517
|
+
`}function zP(e,t){let r=Ff.join(e,".claude","agents");lo.mkdirSync(r,{recursive:!0});let n=[Ff.join(r,`${vk}.md`)];lo.writeFileSync(n[0],VX());for(let o of t??[]){let a=Ff.join(r,`${kk}${o.archetype}.md`);lo.writeFileSync(a,HX(o)),n.push(a)}let s=new Set(n);for(let o of lo.readdirSync(r))if((o.startsWith(kk)||o.startsWith("sb-"))&&o.endsWith(".md")){let a=Ff.join(r,o);s.has(a)||lo.unlinkSync(a)}return n}var GP,vk,kk,JP=C(()=>{"use strict";h();Yn();GP=`<!--
|
|
518
518
|
AUTO-GENERATED FILE \u2014 DO NOT EDIT BY HAND.
|
|
519
519
|
Generator: werkmeister init-workspace (packages/werkmeister-core/src/agent_gen.ts)
|
|
520
520
|
Regenerated on every init-workspace run; edits will be clobbered.
|
|
521
521
|
-->
|
|
522
|
-
`,vk="w9r-researcher";i(VX,"buildResearcherAgent");kk="w9r-tester-";i(Y8,"buildTesterSpecs");i(HX,"buildTesterAgent");i(z8,"writeWorkspaceAgents")});function X8(e,t){return`${e}.${t.replace(/^\.+/,"")}`}function br(e,t){let r=e??de(),n=t??Kt(),s={};for(let[o,a]of Object.entries(r)){let c=a&&typeof a=="object"?a.feature_router:null;if(!c)continue;let l=c.remote_upstream??void 0;s[o]={hostname:c.hostname??X8(o,n.local_domain),k8s:c.k8s??void 0,remoteHostname:c.remote_hostname??(l?X8(o,n.remote_domain):void 0),remoteUpstream:l}}return s}function Mf(e,t){let r=new Set;for(let n of Object.values(br(e,t)))n.hostname&&r.add(n.hostname),n.remoteHostname&&r.add(n.remoteHostname);return[...r].sort()}function f0(e){let t;try{t=Mf()}catch{return null}return t.length?`https://${t[0]}${e.startsWith("/")?e:`/${e}`}`:null}var Ts=C(()=>{"use strict";h();Q();Xe();i(X8,"hostFor");i(br,"loadFeatureRouters");i(Mf,"ingressHostnames");i(f0,"featureUrl")});var sP=$((J2e,nP)=>{"use strict";h();var Sn=te("fs"),wa=te("path"),GX=Sn.lchown?"lchown":"chown",YX=Sn.lchownSync?"lchownSync":"chownSync",Z8=Sn.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),Q8=i((e,t,r)=>{try{return Sn[YX](e,t,r)}catch(n){if(n.code!=="ENOENT")throw n}},"lchownSync"),zX=i((e,t,r)=>{try{return Sn.chownSync(e,t,r)}catch(n){if(n.code!=="ENOENT")throw n}},"chownSync"),JX=Z8?(e,t,r,n)=>s=>{!s||s.code!=="EISDIR"?n(s):Sn.chown(e,t,r,n)}:(e,t,r,n)=>n,_k=Z8?(e,t,r)=>{try{return Q8(e,t,r)}catch(n){if(n.code!=="EISDIR")throw n;zX(e,t,r)}}:(e,t,r)=>Q8(e,t,r),XX=process.version,eP=i((e,t,r)=>Sn.readdir(e,t,r),"readdir"),QX=i((e,t)=>Sn.readdirSync(e,t),"readdirSync");/^v4\./.test(XX)&&(eP=i((e,t,r)=>Sn.readdir(e,r),"readdir"));var d0=i((e,t,r,n)=>{Sn[GX](e,t,r,JX(e,t,r,s=>{n(s&&s.code!=="ENOENT"?s:null)}))},"chown"),tP=i((e,t,r,n,s)=>{if(typeof t=="string")return Sn.lstat(wa.resolve(e,t),(o,a)=>{if(o)return s(o.code!=="ENOENT"?o:null);a.name=t,tP(e,a,r,n,s)});if(t.isDirectory())Sk(wa.resolve(e,t.name),r,n,o=>{if(o)return s(o);let a=wa.resolve(e,t.name);d0(a,r,n,s)});else{let o=wa.resolve(e,t.name);d0(o,r,n,s)}},"chownrKid"),Sk=i((e,t,r,n)=>{eP(e,{withFileTypes:!0},(s,o)=>{if(s){if(s.code==="ENOENT")return n();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return n(s)}if(s||!o.length)return d0(e,t,r,n);let a=o.length,c=null,l=i(u=>{if(!c){if(u)return n(c=u);if(--a===0)return d0(e,t,r,n)}},"then");o.forEach(u=>tP(e,u,t,r,l))})},"chownr"),ZX=i((e,t,r,n)=>{if(typeof t=="string")try{let s=Sn.lstatSync(wa.resolve(e,t));s.name=t,t=s}catch(s){if(s.code==="ENOENT")return;throw s}t.isDirectory()&&rP(wa.resolve(e,t.name),r,n),_k(wa.resolve(e,t.name),r,n)},"chownrKidSync"),rP=i((e,t,r)=>{let n;try{n=QX(e,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;if(s.code==="ENOTDIR"||s.code==="ENOTSUP")return _k(e,t,r);throw s}return n&&n.length&&n.forEach(s=>ZX(e,s,t,r)),_k(e,t,r)},"chownrSync");nP.exports=Sk;Sk.sync=rP});var Ek=$((Z2e,oP)=>{h();oP.exports=te("stream")});var fP=$((t$e,uP)=>{"use strict";h();function iP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}i(iP,"ownKeys");function aP(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?iP(Object(r),!0).forEach(function(n){eQ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):iP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}i(aP,"_objectSpread");function eQ(e,t,r){return t=lP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}i(eQ,"_defineProperty");function tQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}i(tQ,"_classCallCheck");function cP(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,lP(n.key),n)}}i(cP,"_defineProperties");function rQ(e,t,r){return t&&cP(e.prototype,t),r&&cP(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}i(rQ,"_createClass");function lP(e){var t=nQ(e,"string");return typeof t=="symbol"?t:String(t)}i(lP,"_toPropertyKey");function nQ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}i(nQ,"_toPrimitive");var sQ=te("buffer"),p0=sQ.Buffer,oQ=te("util"),$k=oQ.inspect,iQ=$k&&$k.custom||"inspect";function aQ(e,t,r){p0.prototype.copy.call(e,t,r)}i(aQ,"copyBuffer");uP.exports=function(){function e(){tQ(this,e),this.head=null,this.tail=null,this.length=0}return i(e,"BufferList"),rQ(e,[{key:"push",value:i(function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},"push")},{key:"unshift",value:i(function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},"unshift")},{key:"shift",value:i(function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},"shift")},{key:"clear",value:i(function(){this.head=this.tail=null,this.length=0},"clear")},{key:"join",value:i(function(r){if(this.length===0)return"";for(var n=this.head,s=""+n.data;n=n.next;)s+=r+n.data;return s},"join")},{key:"concat",value:i(function(r){if(this.length===0)return p0.alloc(0);for(var n=p0.allocUnsafe(r>>>0),s=this.head,o=0;s;)aQ(s.data,n,o),o+=s.data.length,s=s.next;return n},"concat")},{key:"consume",value:i(function(r,n){var s;return r<this.head.data.length?(s=this.head.data.slice(0,r),this.head.data=this.head.data.slice(r)):r===this.head.data.length?s=this.shift():s=n?this._getString(r):this._getBuffer(r),s},"consume")},{key:"first",value:i(function(){return this.head.data},"first")},{key:"_getString",value:i(function(r){var n=this.head,s=1,o=n.data;for(r-=o.length;n=n.next;){var a=n.data,c=r>a.length?a.length:r;if(c===a.length?o+=a:o+=a.slice(0,r),r-=c,r===0){c===a.length?(++s,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=a.slice(c));break}++s}return this.length-=s,o},"_getString")},{key:"_getBuffer",value:i(function(r){var n=p0.allocUnsafe(r),s=this.head,o=1;for(s.data.copy(n),r-=s.data.length;s=s.next;){var a=s.data,c=r>a.length?a.length:r;if(a.copy(n,n.length-r,0,c),r-=c,r===0){c===a.length?(++o,s.next?this.head=s.next:this.head=this.tail=null):(this.head=s,s.data=a.slice(c));break}++o}return this.length-=o,n},"_getBuffer")},{key:iQ,value:i(function(r,n){return $k(this,aP(aP({},n),{},{depth:0,customInspect:!1}))},"value")}]),e}()});var Tk=$((s$e,pP)=>{"use strict";h();function cQ(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return n||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Ok,this,e)):process.nextTick(Ok,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(o){!t&&o?r._writableState?r._writableState.errorEmitted?process.nextTick(h0,r):(r._writableState.errorEmitted=!0,process.nextTick(dP,r,o)):process.nextTick(dP,r,o):t?(process.nextTick(h0,r),t(o)):process.nextTick(h0,r)}),this)}i(cQ,"destroy");function dP(e,t){Ok(e,t),h0(e)}i(dP,"emitErrorAndCloseNT");function h0(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}i(h0,"emitCloseNT");function lQ(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}i(lQ,"undestroy");function Ok(e,t){e.emit("error",t)}i(Ok,"emitErrorNT");function uQ(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}i(uQ,"errorOrDestroy");pP.exports={destroy:cQ,undestroy:lQ,errorOrDestroy:uQ}});var ci=$((a$e,gP)=>{"use strict";h();var mP={};function En(e,t,r){r||(r=Error);function n(o,a,c){return typeof t=="string"?t:t(o,a,c)}i(n,"getMessage");class s extends r{static{i(this,"NodeError")}constructor(a,c,l){super(n(a,c,l))}}s.prototype.name=r.name,s.prototype.code=e,mP[e]=s}i(En,"createErrorType");function hP(e,t){if(Array.isArray(e)){let r=e.length;return e=e.map(n=>String(n)),r>2?`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]:r===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}i(hP,"oneOf");function fQ(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}i(fQ,"startsWith");function dQ(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}i(dQ,"endsWith");function pQ(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}i(pQ,"includes");En("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);En("ERR_INVALID_ARG_TYPE",function(e,t,r){let n;typeof t=="string"&&fQ(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";let s;if(dQ(e," argument"))s=`The ${e} ${n} ${hP(t,"type")}`;else{let o=pQ(e,".")?"property":"argument";s=`The "${e}" ${o} ${n} ${hP(t,"type")}`}return s+=`. Received type ${typeof r}`,s},TypeError);En("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");En("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});En("ERR_STREAM_PREMATURE_CLOSE","Premature close");En("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});En("ERR_MULTIPLE_CALLBACK","Callback called multiple times");En("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");En("ERR_STREAM_WRITE_AFTER_END","write after end");En("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);En("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);En("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");gP.exports.codes=mP});var Rk=$((u$e,xP)=>{"use strict";h();var hQ=ci().codes.ERR_INVALID_OPT_VALUE;function mQ(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}i(mQ,"highWaterMarkFrom");function gQ(e,t,r,n){var s=mQ(t,n,r);if(s!=null){if(!(isFinite(s)&&Math.floor(s)===s)||s<0){var o=n?r:"highWaterMark";throw new hQ(o,s)}return Math.floor(s)}return e.objectMode?16:16*1024}i(gQ,"getHighWaterMark");xP.exports={getHighWaterMark:gQ}});var yP=$((p$e,Ak)=>{h();typeof Object.create=="function"?Ak.exports=i(function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))},"inherits"):Ak.exports=i(function(t,r){if(r){t.super_=r;var n=i(function(){},"TempCtor");n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}},"inherits")});var li=$((g$e,Pk)=>{h();try{if(Ck=te("util"),typeof Ck.inherits!="function")throw"";Pk.exports=Ck.inherits}catch{Pk.exports=yP()}var Ck});var bP=$((y$e,wP)=>{h();wP.exports=te("util").deprecate});var Lk=$((b$e,$P)=>{"use strict";h();$P.exports=kt;function kP(e){var t=this;this.next=null,this.entry=null,this.finish=function(){WQ(t,e)}}i(kP,"CorkedRequest");var il;kt.WritableState=qf;var xQ={deprecate:bP()},_P=Ek(),g0=te("buffer").Buffer,yQ=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function wQ(e){return g0.from(e)}i(wQ,"_uint8ArrayToBuffer");function bQ(e){return g0.isBuffer(e)||e instanceof yQ}i(bQ,"_isUint8Array");var Ik=Tk(),vQ=Rk(),kQ=vQ.getHighWaterMark,ui=ci().codes,_Q=ui.ERR_INVALID_ARG_TYPE,SQ=ui.ERR_METHOD_NOT_IMPLEMENTED,EQ=ui.ERR_MULTIPLE_CALLBACK,$Q=ui.ERR_STREAM_CANNOT_PIPE,OQ=ui.ERR_STREAM_DESTROYED,TQ=ui.ERR_STREAM_NULL_VALUES,RQ=ui.ERR_STREAM_WRITE_AFTER_END,AQ=ui.ERR_UNKNOWN_ENCODING,al=Ik.errorOrDestroy;li()(kt,_P);function CQ(){}i(CQ,"nop");function qf(e,t,r){il=il||ba(),e=e||{},typeof r!="boolean"&&(r=t instanceof il),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=kQ(this,e,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=e.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(s){FQ(t,s)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new kP(this)}i(qf,"WritableState");qf.prototype.getBuffer=i(function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r},"getBuffer");(function(){try{Object.defineProperty(qf.prototype,"buffer",{get:xQ.deprecate(i(function(){return this.getBuffer()},"writableStateBufferGetter"),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var m0;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(m0=Function.prototype[Symbol.hasInstance],Object.defineProperty(kt,Symbol.hasInstance,{value:i(function(t){return m0.call(this,t)?!0:this!==kt?!1:t&&t._writableState instanceof qf},"value")})):m0=i(function(t){return t instanceof this},"realHasInstance");function kt(e){il=il||ba();var t=this instanceof il;if(!t&&!m0.call(kt,this))return new kt(e);this._writableState=new qf(e,this,t),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),_P.call(this)}i(kt,"Writable");kt.prototype.pipe=function(){al(this,new $Q)};function PQ(e,t){var r=new RQ;al(e,r),process.nextTick(t,r)}i(PQ,"writeAfterEnd");function NQ(e,t,r,n){var s;return r===null?s=new TQ:typeof r!="string"&&!t.objectMode&&(s=new _Q("chunk",["string","Buffer"],r)),s?(al(e,s),process.nextTick(n,s),!1):!0}i(NQ,"validChunk");kt.prototype.write=function(e,t,r){var n=this._writableState,s=!1,o=!n.objectMode&&bQ(e);return o&&!g0.isBuffer(e)&&(e=wQ(e)),typeof t=="function"&&(r=t,t=null),o?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=CQ),n.ending?PQ(this,r):(o||NQ(this,n,e,r))&&(n.pendingcb++,s=LQ(this,n,o,e,t,r)),s};kt.prototype.cork=function(){this._writableState.corked++};kt.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&SP(this,e))};kt.prototype.setDefaultEncoding=i(function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new AQ(t);return this._writableState.defaultEncoding=t,this},"setDefaultEncoding");Object.defineProperty(kt.prototype,"writableBuffer",{enumerable:!1,get:i(function(){return this._writableState&&this._writableState.getBuffer()},"get")});function IQ(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=g0.from(t,r)),t}i(IQ,"decodeChunk");Object.defineProperty(kt.prototype,"writableHighWaterMark",{enumerable:!1,get:i(function(){return this._writableState.highWaterMark},"get")});function LQ(e,t,r,n,s,o){if(!r){var a=IQ(t,n,s);n!==a&&(r=!0,s="buffer",n=a)}var c=t.objectMode?1:n.length;t.length+=c;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:s,isBuf:r,callback:o,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else Nk(e,t,!1,c,n,s,o);return l}i(LQ,"writeOrBuffer");function Nk(e,t,r,n,s,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new OQ("write")):r?e._writev(s,t.onwrite):e._write(s,o,t.onwrite),t.sync=!1}i(Nk,"doWrite");function jQ(e,t,r,n,s){--t.pendingcb,r?(process.nextTick(s,n),process.nextTick(Bf,e,t),e._writableState.errorEmitted=!0,al(e,n)):(s(n),e._writableState.errorEmitted=!0,al(e,n),Bf(e,t))}i(jQ,"onwriteError");function DQ(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}i(DQ,"onwriteStateUpdate");function FQ(e,t){var r=e._writableState,n=r.sync,s=r.writecb;if(typeof s!="function")throw new EQ;if(DQ(r),t)jQ(e,r,n,t,s);else{var o=EP(r)||e.destroyed;!o&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&SP(e,r),n?process.nextTick(vP,e,r,o,s):vP(e,r,o,s)}}i(FQ,"onwrite");function vP(e,t,r,n){r||MQ(e,t),t.pendingcb--,n(),Bf(e,t)}i(vP,"afterWrite");function MQ(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}i(MQ,"onwriteDrain");function SP(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,s=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var a=0,c=!0;r;)s[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;s.allBuffers=c,Nk(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new kP(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,f=r.callback,d=t.objectMode?1:l.length;if(Nk(e,t,!1,d,l,u,f),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}i(SP,"clearBuffer");kt.prototype._write=function(e,t,r){r(new SQ("_write()"))};kt.prototype._writev=null;kt.prototype.end=function(e,t,r){var n=this._writableState;return typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||UQ(this,n,r),this};Object.defineProperty(kt.prototype,"writableLength",{enumerable:!1,get:i(function(){return this._writableState.length},"get")});function EP(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}i(EP,"needFinish");function BQ(e,t){e._final(function(r){t.pendingcb--,r&&al(e,r),t.prefinished=!0,e.emit("prefinish"),Bf(e,t)})}i(BQ,"callFinal");function qQ(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(BQ,e,t)):(t.prefinished=!0,e.emit("prefinish")))}i(qQ,"prefinish");function Bf(e,t){var r=EP(t);if(r&&(qQ(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}i(Bf,"finishMaybe");function UQ(e,t,r){t.ending=!0,Bf(e,t),r&&(t.finished?process.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}i(UQ,"endWritable");function WQ(e,t,r){var n=e.entry;for(e.entry=null;n;){var s=n.callback;t.pendingcb--,s(r),n=n.next}t.corkedRequestsFree.next=e}i(WQ,"onCorkedFinish");Object.defineProperty(kt.prototype,"destroyed",{enumerable:!1,get:i(function(){return this._writableState===void 0?!1:this._writableState.destroyed},"get"),set:i(function(t){this._writableState&&(this._writableState.destroyed=t)},"set")});kt.prototype.destroy=Ik.destroy;kt.prototype._undestroy=Ik.undestroy;kt.prototype._destroy=function(e,t){t(e)}});var ba=$((_$e,TP)=>{"use strict";h();var KQ=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};TP.exports=Rs;var OP=Fk(),Dk=Lk();li()(Rs,OP);for(jk=KQ(Dk.prototype),x0=0;x0<jk.length;x0++)y0=jk[x0],Rs.prototype[y0]||(Rs.prototype[y0]=Dk.prototype[y0]);var jk,y0,x0;function Rs(e){if(!(this instanceof Rs))return new Rs(e);OP.call(this,e),Dk.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",VQ)))}i(Rs,"Duplex");Object.defineProperty(Rs.prototype,"writableHighWaterMark",{enumerable:!1,get:i(function(){return this._writableState.highWaterMark},"get")});Object.defineProperty(Rs.prototype,"writableBuffer",{enumerable:!1,get:i(function(){return this._writableState&&this._writableState.getBuffer()},"get")});Object.defineProperty(Rs.prototype,"writableLength",{enumerable:!1,get:i(function(){return this._writableState.length},"get")});function VQ(){this._writableState.ended||process.nextTick(HQ,this)}i(VQ,"onend");function HQ(e){e.end()}i(HQ,"onEndNT");Object.defineProperty(Rs.prototype,"destroyed",{enumerable:!1,get:i(function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},"get"),set:i(function(t){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=t,this._writableState.destroyed=t)},"set")})});var CP=$((Mk,AP)=>{h();var w0=te("buffer"),As=w0.Buffer;function RP(e,t){for(var r in e)t[r]=e[r]}i(RP,"copyProps");As.from&&As.alloc&&As.allocUnsafe&&As.allocUnsafeSlow?AP.exports=w0:(RP(w0,Mk),Mk.Buffer=va);function va(e,t,r){return As(e,t,r)}i(va,"SafeBuffer");va.prototype=Object.create(As.prototype);RP(As,va);va.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return As(e,t,r)};va.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=As(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};va.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return As(e)};va.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return w0.SlowBuffer(e)}});var Uk=$(NP=>{"use strict";h();var qk=CP().Buffer,PP=qk.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function GQ(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}i(GQ,"_normalizeEncoding");function YQ(e){var t=GQ(e);if(typeof t!="string"&&(qk.isEncoding===PP||!PP(e)))throw new Error("Unknown encoding: "+e);return t||e}i(YQ,"normalizeEncoding");NP.StringDecoder=Uf;function Uf(e){this.encoding=YQ(e);var t;switch(this.encoding){case"utf16le":this.text=eZ,this.end=tZ,t=4;break;case"utf8":this.fillLast=XQ,t=4;break;case"base64":this.text=rZ,this.end=nZ,t=3;break;default:this.write=sZ,this.end=oZ;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=qk.allocUnsafe(t)}i(Uf,"StringDecoder");Uf.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};Uf.prototype.end=ZQ;Uf.prototype.text=QQ;Uf.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function Bk(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}i(Bk,"utf8CheckByte");function zQ(e,t,r){var n=t.length-1;if(n<r)return 0;var s=Bk(t[n]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--n<r||s===-2?0:(s=Bk(t[n]),s>=0?(s>0&&(e.lastNeed=s-2),s):--n<r||s===-2?0:(s=Bk(t[n]),s>=0?(s>0&&(s===2?s=0:e.lastNeed=s-3),s):0))}i(zQ,"utf8CheckIncomplete");function JQ(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}i(JQ,"utf8CheckExtraBytes");function XQ(e){var t=this.lastTotal-this.lastNeed,r=JQ(this,e,t);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}i(XQ,"utf8FillLast");function QQ(e,t){var r=zQ(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}i(QQ,"utf8Text");function ZQ(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}i(ZQ,"utf8End");function eZ(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}i(eZ,"utf16Text");function tZ(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}i(tZ,"utf16End");function rZ(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}i(rZ,"base64Text");function nZ(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}i(nZ,"base64End");function sZ(e){return e.toString(this.encoding)}i(sZ,"simpleWrite");function oZ(e){return e&&e.length?this.write(e):""}i(oZ,"simpleEnd")});var b0=$((C$e,jP)=>{"use strict";h();var IP=ci().codes.ERR_STREAM_PREMATURE_CLOSE;function iZ(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];e.apply(this,n)}}}i(iZ,"once");function aZ(){}i(aZ,"noop");function cZ(e){return e.setHeader&&typeof e.abort=="function"}i(cZ,"isRequest");function LP(e,t,r){if(typeof t=="function")return LP(e,null,t);t||(t={}),r=iZ(r||aZ);var n=t.readable||t.readable!==!1&&e.readable,s=t.writable||t.writable!==!1&&e.writable,o=i(function(){e.writable||c()},"onlegacyfinish"),a=e._writableState&&e._writableState.finished,c=i(function(){s=!1,a=!0,n||r.call(e)},"onfinish"),l=e._readableState&&e._readableState.endEmitted,u=i(function(){n=!1,l=!0,s||r.call(e)},"onend"),f=i(function(y){r.call(e,y)},"onerror"),d=i(function(){var y;if(n&&!l)return(!e._readableState||!e._readableState.ended)&&(y=new IP),r.call(e,y);if(s&&!a)return(!e._writableState||!e._writableState.ended)&&(y=new IP),r.call(e,y)},"onclose"),p=i(function(){e.req.on("finish",c)},"onrequest");return cZ(e)?(e.on("complete",c),e.on("abort",d),e.req?p():e.on("request",p)):s&&!e._writableState&&(e.on("end",o),e.on("close",o)),e.on("end",u),e.on("finish",c),t.error!==!1&&e.on("error",f),e.on("close",d),function(){e.removeListener("complete",c),e.removeListener("abort",d),e.removeListener("request",p),e.req&&e.req.removeListener("finish",c),e.removeListener("end",o),e.removeListener("close",o),e.removeListener("finish",c),e.removeListener("end",u),e.removeListener("error",f),e.removeListener("close",d)}}i(LP,"eos");jP.exports=LP});var FP=$((I$e,DP)=>{"use strict";h();var v0;function fi(e,t,r){return t=lZ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}i(fi,"_defineProperty");function lZ(e){var t=uZ(e,"string");return typeof t=="symbol"?t:String(t)}i(lZ,"_toPropertyKey");function uZ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}i(uZ,"_toPrimitive");var fZ=b0(),di=Symbol("lastResolve"),ka=Symbol("lastReject"),Wf=Symbol("error"),k0=Symbol("ended"),_a=Symbol("lastPromise"),Wk=Symbol("handlePromise"),Sa=Symbol("stream");function pi(e,t){return{value:e,done:t}}i(pi,"createIterResult");function dZ(e){var t=e[di];if(t!==null){var r=e[Sa].read();r!==null&&(e[_a]=null,e[di]=null,e[ka]=null,t(pi(r,!1)))}}i(dZ,"readAndResolve");function pZ(e){process.nextTick(dZ,e)}i(pZ,"onReadable");function hZ(e,t){return function(r,n){e.then(function(){if(t[k0]){r(pi(void 0,!0));return}t[Wk](r,n)},n)}}i(hZ,"wrapForNext");var mZ=Object.getPrototypeOf(function(){}),gZ=Object.setPrototypeOf((v0={get stream(){return this[Sa]},next:i(function(){var t=this,r=this[Wf];if(r!==null)return Promise.reject(r);if(this[k0])return Promise.resolve(pi(void 0,!0));if(this[Sa].destroyed)return new Promise(function(a,c){process.nextTick(function(){t[Wf]?c(t[Wf]):a(pi(void 0,!0))})});var n=this[_a],s;if(n)s=new Promise(hZ(n,this));else{var o=this[Sa].read();if(o!==null)return Promise.resolve(pi(o,!1));s=new Promise(this[Wk])}return this[_a]=s,s},"next")},fi(v0,Symbol.asyncIterator,function(){return this}),fi(v0,"return",i(function(){var t=this;return new Promise(function(r,n){t[Sa].destroy(null,function(s){if(s){n(s);return}r(pi(void 0,!0))})})},"_return")),v0),mZ),xZ=i(function(t){var r,n=Object.create(gZ,(r={},fi(r,Sa,{value:t,writable:!0}),fi(r,di,{value:null,writable:!0}),fi(r,ka,{value:null,writable:!0}),fi(r,Wf,{value:null,writable:!0}),fi(r,k0,{value:t._readableState.endEmitted,writable:!0}),fi(r,Wk,{value:i(function(o,a){var c=n[Sa].read();c?(n[_a]=null,n[di]=null,n[ka]=null,o(pi(c,!1))):(n[di]=o,n[ka]=a)},"value"),writable:!0}),r));return n[_a]=null,fZ(t,function(s){if(s&&s.code!=="ERR_STREAM_PREMATURE_CLOSE"){var o=n[ka];o!==null&&(n[_a]=null,n[di]=null,n[ka]=null,o(s)),n[Wf]=s;return}var a=n[di];a!==null&&(n[_a]=null,n[di]=null,n[ka]=null,a(pi(void 0,!0))),n[k0]=!0}),t.on("readable",pZ.bind(null,n)),n},"createReadableStreamAsyncIterator");DP.exports=xZ});var UP=$((D$e,qP)=>{"use strict";h();function MP(e,t,r,n,s,o,a){try{var c=e[o](a),l=c.value}catch(u){r(u);return}c.done?t(l):Promise.resolve(l).then(n,s)}i(MP,"asyncGeneratorStep");function yZ(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var o=e.apply(t,r);function a(l){MP(o,n,s,a,c,"next",l)}i(a,"_next");function c(l){MP(o,n,s,a,c,"throw",l)}i(c,"_throw"),a(void 0)})}}i(yZ,"_asyncToGenerator");function BP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}i(BP,"ownKeys");function wZ(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?BP(Object(r),!0).forEach(function(n){bZ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):BP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}i(wZ,"_objectSpread");function bZ(e,t,r){return t=vZ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}i(bZ,"_defineProperty");function vZ(e){var t=kZ(e,"string");return typeof t=="symbol"?t:String(t)}i(vZ,"_toPropertyKey");function kZ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}i(kZ,"_toPrimitive");var _Z=ci().codes.ERR_INVALID_ARG_TYPE;function SZ(e,t,r){var n;if(t&&typeof t.next=="function")n=t;else if(t&&t[Symbol.asyncIterator])n=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])n=t[Symbol.iterator]();else throw new _Z("iterable",["Iterable"],t);var s=new e(wZ({objectMode:!0},r)),o=!1;s._read=function(){o||(o=!0,a())};function a(){return c.apply(this,arguments)}i(a,"next");function c(){return c=yZ(function*(){try{var l=yield n.next(),u=l.value,f=l.done;f?s.push(null):s.push(yield u)?a():o=!1}catch(d){s.destroy(d)}}),c.apply(this,arguments)}return i(c,"_next2"),s}i(SZ,"from");qP.exports=SZ});var Fk=$((q$e,QP)=>{"use strict";h();QP.exports=Le;var cl;Le.ReadableState=HP;var B$e=te("events").EventEmitter,VP=i(function(t,r){return t.listeners(r).length},"EElistenerCount"),Vf=Ek(),_0=te("buffer").Buffer,EZ=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function $Z(e){return _0.from(e)}i($Z,"_uint8ArrayToBuffer");function OZ(e){return _0.isBuffer(e)||e instanceof EZ}i(OZ,"_isUint8Array");var Kk=te("util"),ve;Kk&&Kk.debuglog?ve=Kk.debuglog("stream"):ve=i(function(){},"debug");var TZ=fP(),Xk=Tk(),RZ=Rk(),AZ=RZ.getHighWaterMark,S0=ci().codes,CZ=S0.ERR_INVALID_ARG_TYPE,PZ=S0.ERR_STREAM_PUSH_AFTER_EOF,NZ=S0.ERR_METHOD_NOT_IMPLEMENTED,IZ=S0.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,ll,Vk,Hk;li()(Le,Vf);var Kf=Xk.errorOrDestroy,Gk=["error","close","destroy","pause","resume"];function LZ(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}i(LZ,"prependListener");function HP(e,t,r){cl=cl||ba(),e=e||{},typeof r!="boolean"&&(r=t instanceof cl),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=AZ(this,e,"readableHighWaterMark",r),this.buffer=new TZ,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(ll||(ll=Uk().StringDecoder),this.decoder=new ll(e.encoding),this.encoding=e.encoding)}i(HP,"ReadableState");function Le(e){if(cl=cl||ba(),!(this instanceof Le))return new Le(e);var t=this instanceof cl;this._readableState=new HP(e,this,t),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),Vf.call(this)}i(Le,"Readable");Object.defineProperty(Le.prototype,"destroyed",{enumerable:!1,get:i(function(){return this._readableState===void 0?!1:this._readableState.destroyed},"get"),set:i(function(t){this._readableState&&(this._readableState.destroyed=t)},"set")});Le.prototype.destroy=Xk.destroy;Le.prototype._undestroy=Xk.undestroy;Le.prototype._destroy=function(e,t){t(e)};Le.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=!0:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=_0.from(e,t),t=""),n=!0),GP(this,e,t,!1,n)};Le.prototype.unshift=function(e){return GP(this,e,null,!0,!1)};function GP(e,t,r,n,s){ve("readableAddChunk",t);var o=e._readableState;if(t===null)o.reading=!1,FZ(e,o);else{var a;if(s||(a=jZ(o,t)),a)Kf(e,a);else if(o.objectMode||t&&t.length>0)if(typeof t!="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==_0.prototype&&(t=$Z(t)),n)o.endEmitted?Kf(e,new IZ):Yk(e,o,t,!0);else if(o.ended)Kf(e,new PZ);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||t.length!==0?Yk(e,o,t,!1):Jk(e,o)):Yk(e,o,t,!1)}else n||(o.reading=!1,Jk(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}i(GP,"readableAddChunk");function Yk(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&E0(e)),Jk(e,t)}i(Yk,"addChunk");function jZ(e,t){var r;return!OZ(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new CZ("chunk",["string","Buffer","Uint8Array"],t)),r}i(jZ,"chunkInvalid");Le.prototype.isPaused=function(){return this._readableState.flowing===!1};Le.prototype.setEncoding=function(e){ll||(ll=Uk().StringDecoder);var t=new ll(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,n="";r!==null;)n+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),n!==""&&this._readableState.buffer.push(n),this._readableState.length=n.length,this};var WP=1073741824;function DZ(e){return e>=WP?e=WP:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}i(DZ,"computeNewHighWaterMark");function KP(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=DZ(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}i(KP,"howMuchToRead");Le.prototype.read=function(e){ve("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended))return ve("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?zk(this):E0(this),null;if(e=KP(e,t),e===0&&t.ended)return t.length===0&&zk(this),null;var n=t.needReadable;ve("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=!0,ve("length less than watermark",n)),t.ended||t.reading?(n=!1,ve("reading or ended",n)):n&&(ve("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=KP(r,t)));var s;return e>0?s=JP(e,t):s=null,s===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&zk(this)),s!==null&&this.emit("data",s),s};function FZ(e,t){if(ve("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?E0(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,YP(e)))}}i(FZ,"onEofChunk");function E0(e){var t=e._readableState;ve("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(ve("emitReadable",t.flowing),t.emittedReadable=!0,process.nextTick(YP,e))}i(E0,"emitReadable");function YP(e){var t=e._readableState;ve("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Qk(e)}i(YP,"emitReadable_");function Jk(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(MZ,e,t))}i(Jk,"maybeReadMore");function MZ(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var r=t.length;if(ve("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}i(MZ,"maybeReadMore_");Le.prototype._read=function(e){Kf(this,new NZ("_read()"))};Le.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,ve("pipe count=%d opts=%j",n.pipesCount,t);var s=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr,o=s?c:g;n.endEmitted?process.nextTick(o):r.once("end",o),e.on("unpipe",a);function a(x,v){ve("onunpipe"),x===r&&v&&v.hasUnpiped===!1&&(v.hasUnpiped=!0,f())}i(a,"onunpipe");function c(){ve("onend"),e.end()}i(c,"onend");var l=BZ(r);e.on("drain",l);var u=!1;function f(){ve("cleanup"),e.removeListener("close",m),e.removeListener("finish",y),e.removeListener("drain",l),e.removeListener("error",p),e.removeListener("unpipe",a),r.removeListener("end",c),r.removeListener("end",g),r.removeListener("data",d),u=!0,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&l()}i(f,"cleanup"),r.on("data",d);function d(x){ve("ondata");var v=e.write(x);ve("dest.write",v),v===!1&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&XP(n.pipes,e)!==-1)&&!u&&(ve("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}i(d,"ondata");function p(x){ve("onerror",x),g(),e.removeListener("error",p),VP(e,"error")===0&&Kf(e,x)}i(p,"onerror"),LZ(e,"error",p);function m(){e.removeListener("finish",y),g()}i(m,"onclose"),e.once("close",m);function y(){ve("onfinish"),e.removeListener("close",m),g()}i(y,"onfinish"),e.once("finish",y);function g(){ve("unpipe"),r.unpipe(e)}return i(g,"unpipe"),e.emit("pipe",r),n.flowing||(ve("pipe resume"),r.resume()),e};function BZ(e){return i(function(){var r=e._readableState;ve("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&VP(e,"data")&&(r.flowing=!0,Qk(e))},"pipeOnDrainFunctionResult")}i(BZ,"pipeOnDrain");Le.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<s;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=XP(t.pipes,e);return a===-1?this:(t.pipes.splice(a,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};Le.prototype.on=function(e,t){var r=Vf.prototype.on.call(this,e,t),n=this._readableState;return e==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==!1&&this.resume()):e==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,ve("on readable",n.length,n.reading),n.length?E0(this):n.reading||process.nextTick(qZ,this)),r};Le.prototype.addListener=Le.prototype.on;Le.prototype.removeListener=function(e,t){var r=Vf.prototype.removeListener.call(this,e,t);return e==="readable"&&process.nextTick(zP,this),r};Le.prototype.removeAllListeners=function(e){var t=Vf.prototype.removeAllListeners.apply(this,arguments);return(e==="readable"||e===void 0)&&process.nextTick(zP,this),t};function zP(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}i(zP,"updateReadableListening");function qZ(e){ve("readable nexttick read 0"),e.read(0)}i(qZ,"nReadingNextTick");Le.prototype.resume=function(){var e=this._readableState;return e.flowing||(ve("resume"),e.flowing=!e.readableListening,UZ(this,e)),e.paused=!1,this};function UZ(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(WZ,e,t))}i(UZ,"resume");function WZ(e,t){ve("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Qk(e),t.flowing&&!t.reading&&e.read(0)}i(WZ,"resume_");Le.prototype.pause=function(){return ve("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(ve("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Qk(e){var t=e._readableState;for(ve("flow",t.flowing);t.flowing&&e.read()!==null;);}i(Qk,"flow");Le.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;e.on("end",function(){if(ve("wrapped end"),r.decoder&&!r.ended){var a=r.decoder.end();a&&a.length&&t.push(a)}t.push(null)}),e.on("data",function(a){if(ve("wrapped data"),r.decoder&&(a=r.decoder.write(a)),!(r.objectMode&&a==null)&&!(!r.objectMode&&(!a||!a.length))){var c=t.push(a);c||(n=!0,e.pause())}});for(var s in e)this[s]===void 0&&typeof e[s]=="function"&&(this[s]=i(function(c){return i(function(){return e[c].apply(e,arguments)},"methodWrapReturnFunction")},"methodWrap")(s));for(var o=0;o<Gk.length;o++)e.on(Gk[o],this.emit.bind(this,Gk[o]));return this._read=function(a){ve("wrapped _read",a),n&&(n=!1,e.resume())},this};typeof Symbol=="function"&&(Le.prototype[Symbol.asyncIterator]=function(){return Vk===void 0&&(Vk=FP()),Vk(this)});Object.defineProperty(Le.prototype,"readableHighWaterMark",{enumerable:!1,get:i(function(){return this._readableState.highWaterMark},"get")});Object.defineProperty(Le.prototype,"readableBuffer",{enumerable:!1,get:i(function(){return this._readableState&&this._readableState.buffer},"get")});Object.defineProperty(Le.prototype,"readableFlowing",{enumerable:!1,get:i(function(){return this._readableState.flowing},"get"),set:i(function(t){this._readableState&&(this._readableState.flowing=t)},"set")});Le._fromList=JP;Object.defineProperty(Le.prototype,"readableLength",{enumerable:!1,get:i(function(){return this._readableState.length},"get")});function JP(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.first():r=t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}i(JP,"fromList");function zk(e){var t=e._readableState;ve("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(KZ,t,e))}i(zk,"endReadable");function KZ(e,t){if(ve("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}i(KZ,"endReadableNT");typeof Symbol=="function"&&(Le.from=function(e,t){return Hk===void 0&&(Hk=UP()),Hk(Le,e,t)});function XP(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}i(XP,"indexOf")});var Zk=$((K$e,eN)=>{"use strict";h();eN.exports=uo;var $0=ci().codes,VZ=$0.ERR_METHOD_NOT_IMPLEMENTED,HZ=$0.ERR_MULTIPLE_CALLBACK,GZ=$0.ERR_TRANSFORM_ALREADY_TRANSFORMING,YZ=$0.ERR_TRANSFORM_WITH_LENGTH_0,O0=ba();li()(uo,O0);function zZ(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new HZ);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}i(zZ,"afterTransform");function uo(e){if(!(this instanceof uo))return new uo(e);O0.call(this,e),this._transformState={afterTransform:zZ.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",JZ)}i(uo,"Transform");function JZ(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){ZP(e,t,r)}):ZP(this,null,null)}i(JZ,"prefinish");uo.prototype.push=function(e,t){return this._transformState.needTransform=!1,O0.prototype.push.call(this,e,t)};uo.prototype._transform=function(e,t,r){r(new VZ("_transform()"))};uo.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var s=this._readableState;(n.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}};uo.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};uo.prototype._destroy=function(e,t){O0.prototype._destroy.call(this,e,function(r){t(r)})};function ZP(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new YZ;if(e._transformState.transforming)throw new GZ;return e.push(null)}i(ZP,"done")});var nN=$((G$e,rN)=>{"use strict";h();rN.exports=Hf;var tN=Zk();li()(Hf,tN);function Hf(e){if(!(this instanceof Hf))return new Hf(e);tN.call(this,e)}i(Hf,"PassThrough");Hf.prototype._transform=function(e,t,r){r(null,e)}});var cN=$((J$e,aN)=>{"use strict";h();var e_;function XZ(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}i(XZ,"once");var iN=ci().codes,QZ=iN.ERR_MISSING_ARGS,ZZ=iN.ERR_STREAM_DESTROYED;function sN(e){if(e)throw e}i(sN,"noop");function eee(e){return e.setHeader&&typeof e.abort=="function"}i(eee,"isRequest");function tee(e,t,r,n){n=XZ(n);var s=!1;e.on("close",function(){s=!0}),e_===void 0&&(e_=b0()),e_(e,{readable:t,writable:r},function(a){if(a)return n(a);s=!0,n()});var o=!1;return function(a){if(!s&&!o){if(o=!0,eee(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(a||new ZZ("pipe"))}}}i(tee,"destroyer");function oN(e){e()}i(oN,"call");function ree(e,t){return e.pipe(t)}i(ree,"pipe");function nee(e){return!e.length||typeof e[e.length-1]!="function"?sN:e.pop()}i(nee,"popCallback");function see(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=nee(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new QZ("streams");var s,o=t.map(function(a,c){var l=c<t.length-1,u=c>0;return tee(a,l,u,function(f){s||(s=f),f&&o.forEach(oN),!l&&(o.forEach(oN),n(s))})});return t.reduce(ree)}i(see,"pipeline");aN.exports=see});var ul=$(($n,Yf)=>{h();var Gf=te("stream");process.env.READABLE_STREAM==="disable"&&Gf?(Yf.exports=Gf.Readable,Object.assign(Yf.exports,Gf),Yf.exports.Stream=Gf):($n=Yf.exports=Fk(),$n.Stream=Gf||$n,$n.Readable=$n,$n.Writable=Lk(),$n.Duplex=ba(),$n.Transform=Zk(),$n.PassThrough=nN(),$n.finished=b0(),$n.pipeline=cN())});var fN=$((e6e,uN)=>{"use strict";h();var{Buffer:Jn}=te("buffer"),lN=Symbol.for("BufferList");function it(e){if(!(this instanceof it))return new it(e);it._init.call(this,e)}i(it,"BufferList");it._init=i(function(t){Object.defineProperty(this,lN,{value:!0}),this._bufs=[],this.length=0,t&&this.append(t)},"_init");it.prototype._new=i(function(t){return new it(t)},"_new");it.prototype._offset=i(function(t){if(t===0)return[0,0];let r=0;for(let n=0;n<this._bufs.length;n++){let s=r+this._bufs[n].length;if(t<s||n===this._bufs.length-1)return[n,t-r];r=s}},"_offset");it.prototype._reverseOffset=function(e){let t=e[0],r=e[1];for(let n=0;n<t;n++)r+=this._bufs[n].length;return r};it.prototype.get=i(function(t){if(t>this.length||t<0)return;let r=this._offset(t);return this._bufs[r[0]][r[1]]},"get");it.prototype.slice=i(function(t,r){return typeof t=="number"&&t<0&&(t+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,t,r)},"slice");it.prototype.copy=i(function(t,r,n,s){if((typeof n!="number"||n<0)&&(n=0),(typeof s!="number"||s>this.length)&&(s=this.length),n>=this.length||s<=0)return t||Jn.alloc(0);let o=!!t,a=this._offset(n),c=s-n,l=c,u=o&&r||0,f=a[1];if(n===0&&s===this.length){if(!o)return this._bufs.length===1?this._bufs[0]:Jn.concat(this._bufs,this.length);for(let d=0;d<this._bufs.length;d++)this._bufs[d].copy(t,u),u+=this._bufs[d].length;return t}if(l<=this._bufs[a[0]].length-f)return o?this._bufs[a[0]].copy(t,r,f,f+l):this._bufs[a[0]].slice(f,f+l);o||(t=Jn.allocUnsafe(c));for(let d=a[0];d<this._bufs.length;d++){let p=this._bufs[d].length-f;if(l>p)this._bufs[d].copy(t,u,f),u+=p;else{this._bufs[d].copy(t,u,f,f+l),u+=p;break}l-=p,f&&(f=0)}return t.length>u?t.slice(0,u):t},"copy");it.prototype.shallowSlice=i(function(t,r){if(t=t||0,r=typeof r!="number"?this.length:r,t<0&&(t+=this.length),r<0&&(r+=this.length),t===r)return this._new();let n=this._offset(t),s=this._offset(r),o=this._bufs.slice(n[0],s[0]+1);return s[1]===0?o.pop():o[o.length-1]=o[o.length-1].slice(0,s[1]),n[1]!==0&&(o[0]=o[0].slice(n[1])),this._new(o)},"shallowSlice");it.prototype.toString=i(function(t,r,n){return this.slice(r,n).toString(t)},"toString");it.prototype.consume=i(function(t){if(t=Math.trunc(t),Number.isNaN(t)||t<=0)return this;for(;this._bufs.length;)if(t>=this._bufs[0].length)t-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(t),this.length-=t;break}return this},"consume");it.prototype.duplicate=i(function(){let t=this._new();for(let r=0;r<this._bufs.length;r++)t.append(this._bufs[r]);return t},"duplicate");it.prototype.append=i(function(t){if(t==null)return this;if(t.buffer)this._appendBuffer(Jn.from(t.buffer,t.byteOffset,t.byteLength));else if(Array.isArray(t))for(let r=0;r<t.length;r++)this.append(t[r]);else if(this._isBufferList(t))for(let r=0;r<t._bufs.length;r++)this.append(t._bufs[r]);else typeof t=="number"&&(t=t.toString()),this._appendBuffer(Jn.from(t));return this},"append");it.prototype._appendBuffer=i(function(t){this._bufs.push(t),this.length+=t.length},"appendBuffer");it.prototype.indexOf=function(e,t,r){if(r===void 0&&typeof t=="string"&&(r=t,t=void 0),typeof e=="function"||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof e=="number"?e=Jn.from([e]):typeof e=="string"?e=Jn.from(e,r):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=Jn.from(e.buffer,e.byteOffset,e.byteLength):Jn.isBuffer(e)||(e=Jn.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=this._offset(t),s=n[0],o=n[1];for(;s<this._bufs.length;s++){let a=this._bufs[s];for(;o<a.length;)if(a.length-o>=e.length){let l=a.indexOf(e,o);if(l!==-1)return this._reverseOffset([s,l]);o=a.length-e.length+1}else{let l=this._reverseOffset([s,o]);if(this._match(l,e))return l;o++}o=0}return-1};it.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let r=0;r<t.length;r++)if(this.get(e+r)!==t[r])return!1;return!0};(function(){let e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let t in e)(function(r){e[r]===null?it.prototype[r]=function(n,s){return this.slice(n,n+s)[r](0,s)}:it.prototype[r]=function(n=0){return this.slice(n,n+e[r])[r](0)}})(t)})();it.prototype._isBufferList=i(function(t){return t instanceof it||it.isBufferList(t)},"_isBufferList");it.isBufferList=i(function(t){return t!=null&&t[lN]},"isBufferList");uN.exports=it});var dN=$((n6e,T0)=>{"use strict";h();var t_=ul().Duplex,oee=li(),zf=fN();function lr(e){if(!(this instanceof lr))return new lr(e);if(typeof e=="function"){this._callback=e;let t=i(function(n){this._callback&&(this._callback(n),this._callback=null)},"piper").bind(this);this.on("pipe",i(function(n){n.on("error",t)},"onPipe")),this.on("unpipe",i(function(n){n.removeListener("error",t)},"onUnpipe")),e=null}zf._init.call(this,e),t_.call(this)}i(lr,"BufferListStream");oee(lr,t_);Object.assign(lr.prototype,zf.prototype);lr.prototype._new=i(function(t){return new lr(t)},"_new");lr.prototype._write=i(function(t,r,n){this._appendBuffer(t),typeof n=="function"&&n()},"_write");lr.prototype._read=i(function(t){if(!this.length)return this.push(null);t=Math.min(t,this.length),this.push(this.slice(0,t)),this.consume(t)},"_read");lr.prototype.end=i(function(t){t_.prototype.end.call(this,t),this._callback&&(this._callback(null,this.slice()),this._callback=null)},"end");lr.prototype._destroy=i(function(t,r){this._bufs.length=0,this.length=0,r(t)},"_destroy");lr.prototype._isBufferList=i(function(t){return t instanceof lr||t instanceof zf||lr.isBufferList(t)},"_isBufferList");lr.isBufferList=zf.isBufferList;T0.exports=lr;T0.exports.BufferListStream=lr;T0.exports.BufferList=zf});var s_=$(dl=>{h();var iee=Buffer.alloc,aee="0000000000000000000",cee="7777777777777777777",pN=48,hN=Buffer.from("ustar\0","binary"),lee=Buffer.from("00","binary"),uee=Buffer.from("ustar ","binary"),fee=Buffer.from(" \0","binary"),dee=parseInt("7777",8),Jf=257,n_=263,pee=i(function(e,t,r){return typeof e!="number"?r:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)},"clamp"),hee=i(function(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null},"toType"),mee=i(function(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0},"toTypeflag"),mN=i(function(e,t,r,n){for(;r<n;r++)if(e[r]===t)return r;return n},"indexOf"),gN=i(function(e){for(var t=256,r=0;r<148;r++)t+=e[r];for(var n=156;n<512;n++)t+=e[n];return t},"cksum"),hi=i(function(e,t){return e=e.toString(8),e.length>t?cee.slice(0,t)+" ":aee.slice(0,t-e.length)+e+" "},"encodeOct");function gee(e){var t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;for(var r=[],n=e.length-1;n>0;n--){var s=e[n];t?r.push(s):r.push(255-s)}var o=0,a=r.length;for(n=0;n<a;n++)o+=r[n]*Math.pow(256,n);return t?o:-1*o}i(gee,"parse256");var mi=i(function(e,t,r){if(e=e.slice(t,t+r),t=0,e[t]&128)return gee(e);for(;t<e.length&&e[t]===32;)t++;for(var n=pee(mN(e,32,t,e.length),e.length,e.length);t<n&&e[t]===0;)t++;return n===t?0:parseInt(e.slice(t,n).toString(),8)},"decodeOct"),fl=i(function(e,t,r,n){return e.slice(t,mN(e,0,t,t+r)).toString(n)},"decodeStr"),r_=i(function(e){var t=Buffer.byteLength(e),r=Math.floor(Math.log(t)/Math.log(10))+1;return t+r>=Math.pow(10,r)&&r++,t+r+e},"addLength");dl.decodeLongPath=function(e,t){return fl(e,0,e.length,t)};dl.encodePax=function(e){var t="";e.name&&(t+=r_(" path="+e.name+`
|
|
522
|
+
`,vk="w9r-researcher";i(VX,"buildResearcherAgent");kk="w9r-tester-";i(YP,"buildTesterSpecs");i(HX,"buildTesterAgent");i(zP,"writeWorkspaceAgents")});function XP(e,t){return`${e}.${t.replace(/^\.+/,"")}`}function br(e,t){let r=e??de(),n=t??Kt(),s={};for(let[o,a]of Object.entries(r)){let c=a&&typeof a=="object"?a.feature_router:null;if(!c)continue;let l=c.remote_upstream??void 0;s[o]={hostname:c.hostname??XP(o,n.local_domain),k8s:c.k8s??void 0,remoteHostname:c.remote_hostname??(l?XP(o,n.remote_domain):void 0),remoteUpstream:l}}return s}function Mf(e,t){let r=new Set;for(let n of Object.values(br(e,t)))n.hostname&&r.add(n.hostname),n.remoteHostname&&r.add(n.remoteHostname);return[...r].sort()}function f0(e){let t;try{t=Mf()}catch{return null}return t.length?`https://${t[0]}${e.startsWith("/")?e:`/${e}`}`:null}var Ts=C(()=>{"use strict";h();Q();Xe();i(XP,"hostFor");i(br,"loadFeatureRouters");i(Mf,"ingressHostnames");i(f0,"featureUrl")});var s8=$((J2e,n8)=>{"use strict";h();var Sn=te("fs"),wa=te("path"),GX=Sn.lchown?"lchown":"chown",YX=Sn.lchownSync?"lchownSync":"chownSync",ZP=Sn.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),QP=i((e,t,r)=>{try{return Sn[YX](e,t,r)}catch(n){if(n.code!=="ENOENT")throw n}},"lchownSync"),zX=i((e,t,r)=>{try{return Sn.chownSync(e,t,r)}catch(n){if(n.code!=="ENOENT")throw n}},"chownSync"),JX=ZP?(e,t,r,n)=>s=>{!s||s.code!=="EISDIR"?n(s):Sn.chown(e,t,r,n)}:(e,t,r,n)=>n,_k=ZP?(e,t,r)=>{try{return QP(e,t,r)}catch(n){if(n.code!=="EISDIR")throw n;zX(e,t,r)}}:(e,t,r)=>QP(e,t,r),XX=process.version,e8=i((e,t,r)=>Sn.readdir(e,t,r),"readdir"),QX=i((e,t)=>Sn.readdirSync(e,t),"readdirSync");/^v4\./.test(XX)&&(e8=i((e,t,r)=>Sn.readdir(e,r),"readdir"));var d0=i((e,t,r,n)=>{Sn[GX](e,t,r,JX(e,t,r,s=>{n(s&&s.code!=="ENOENT"?s:null)}))},"chown"),t8=i((e,t,r,n,s)=>{if(typeof t=="string")return Sn.lstat(wa.resolve(e,t),(o,a)=>{if(o)return s(o.code!=="ENOENT"?o:null);a.name=t,t8(e,a,r,n,s)});if(t.isDirectory())Sk(wa.resolve(e,t.name),r,n,o=>{if(o)return s(o);let a=wa.resolve(e,t.name);d0(a,r,n,s)});else{let o=wa.resolve(e,t.name);d0(o,r,n,s)}},"chownrKid"),Sk=i((e,t,r,n)=>{e8(e,{withFileTypes:!0},(s,o)=>{if(s){if(s.code==="ENOENT")return n();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return n(s)}if(s||!o.length)return d0(e,t,r,n);let a=o.length,c=null,l=i(u=>{if(!c){if(u)return n(c=u);if(--a===0)return d0(e,t,r,n)}},"then");o.forEach(u=>t8(e,u,t,r,l))})},"chownr"),ZX=i((e,t,r,n)=>{if(typeof t=="string")try{let s=Sn.lstatSync(wa.resolve(e,t));s.name=t,t=s}catch(s){if(s.code==="ENOENT")return;throw s}t.isDirectory()&&r8(wa.resolve(e,t.name),r,n),_k(wa.resolve(e,t.name),r,n)},"chownrKidSync"),r8=i((e,t,r)=>{let n;try{n=QX(e,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;if(s.code==="ENOTDIR"||s.code==="ENOTSUP")return _k(e,t,r);throw s}return n&&n.length&&n.forEach(s=>ZX(e,s,t,r)),_k(e,t,r)},"chownrSync");n8.exports=Sk;Sk.sync=r8});var Ek=$((Z2e,o8)=>{h();o8.exports=te("stream")});var f8=$((t$e,u8)=>{"use strict";h();function i8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}i(i8,"ownKeys");function a8(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?i8(Object(r),!0).forEach(function(n){eQ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i8(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}i(a8,"_objectSpread");function eQ(e,t,r){return t=l8(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}i(eQ,"_defineProperty");function tQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}i(tQ,"_classCallCheck");function c8(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,l8(n.key),n)}}i(c8,"_defineProperties");function rQ(e,t,r){return t&&c8(e.prototype,t),r&&c8(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}i(rQ,"_createClass");function l8(e){var t=nQ(e,"string");return typeof t=="symbol"?t:String(t)}i(l8,"_toPropertyKey");function nQ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}i(nQ,"_toPrimitive");var sQ=te("buffer"),p0=sQ.Buffer,oQ=te("util"),$k=oQ.inspect,iQ=$k&&$k.custom||"inspect";function aQ(e,t,r){p0.prototype.copy.call(e,t,r)}i(aQ,"copyBuffer");u8.exports=function(){function e(){tQ(this,e),this.head=null,this.tail=null,this.length=0}return i(e,"BufferList"),rQ(e,[{key:"push",value:i(function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},"push")},{key:"unshift",value:i(function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},"unshift")},{key:"shift",value:i(function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},"shift")},{key:"clear",value:i(function(){this.head=this.tail=null,this.length=0},"clear")},{key:"join",value:i(function(r){if(this.length===0)return"";for(var n=this.head,s=""+n.data;n=n.next;)s+=r+n.data;return s},"join")},{key:"concat",value:i(function(r){if(this.length===0)return p0.alloc(0);for(var n=p0.allocUnsafe(r>>>0),s=this.head,o=0;s;)aQ(s.data,n,o),o+=s.data.length,s=s.next;return n},"concat")},{key:"consume",value:i(function(r,n){var s;return r<this.head.data.length?(s=this.head.data.slice(0,r),this.head.data=this.head.data.slice(r)):r===this.head.data.length?s=this.shift():s=n?this._getString(r):this._getBuffer(r),s},"consume")},{key:"first",value:i(function(){return this.head.data},"first")},{key:"_getString",value:i(function(r){var n=this.head,s=1,o=n.data;for(r-=o.length;n=n.next;){var a=n.data,c=r>a.length?a.length:r;if(c===a.length?o+=a:o+=a.slice(0,r),r-=c,r===0){c===a.length?(++s,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=a.slice(c));break}++s}return this.length-=s,o},"_getString")},{key:"_getBuffer",value:i(function(r){var n=p0.allocUnsafe(r),s=this.head,o=1;for(s.data.copy(n),r-=s.data.length;s=s.next;){var a=s.data,c=r>a.length?a.length:r;if(a.copy(n,n.length-r,0,c),r-=c,r===0){c===a.length?(++o,s.next?this.head=s.next:this.head=this.tail=null):(this.head=s,s.data=a.slice(c));break}++o}return this.length-=o,n},"_getBuffer")},{key:iQ,value:i(function(r,n){return $k(this,a8(a8({},n),{},{depth:0,customInspect:!1}))},"value")}]),e}()});var Tk=$((s$e,p8)=>{"use strict";h();function cQ(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return n||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Ok,this,e)):process.nextTick(Ok,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(o){!t&&o?r._writableState?r._writableState.errorEmitted?process.nextTick(h0,r):(r._writableState.errorEmitted=!0,process.nextTick(d8,r,o)):process.nextTick(d8,r,o):t?(process.nextTick(h0,r),t(o)):process.nextTick(h0,r)}),this)}i(cQ,"destroy");function d8(e,t){Ok(e,t),h0(e)}i(d8,"emitErrorAndCloseNT");function h0(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}i(h0,"emitCloseNT");function lQ(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}i(lQ,"undestroy");function Ok(e,t){e.emit("error",t)}i(Ok,"emitErrorNT");function uQ(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}i(uQ,"errorOrDestroy");p8.exports={destroy:cQ,undestroy:lQ,errorOrDestroy:uQ}});var ci=$((a$e,g8)=>{"use strict";h();var m8={};function En(e,t,r){r||(r=Error);function n(o,a,c){return typeof t=="string"?t:t(o,a,c)}i(n,"getMessage");class s extends r{static{i(this,"NodeError")}constructor(a,c,l){super(n(a,c,l))}}s.prototype.name=r.name,s.prototype.code=e,m8[e]=s}i(En,"createErrorType");function h8(e,t){if(Array.isArray(e)){let r=e.length;return e=e.map(n=>String(n)),r>2?`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]:r===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}i(h8,"oneOf");function fQ(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}i(fQ,"startsWith");function dQ(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}i(dQ,"endsWith");function pQ(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}i(pQ,"includes");En("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);En("ERR_INVALID_ARG_TYPE",function(e,t,r){let n;typeof t=="string"&&fQ(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";let s;if(dQ(e," argument"))s=`The ${e} ${n} ${h8(t,"type")}`;else{let o=pQ(e,".")?"property":"argument";s=`The "${e}" ${o} ${n} ${h8(t,"type")}`}return s+=`. Received type ${typeof r}`,s},TypeError);En("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");En("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});En("ERR_STREAM_PREMATURE_CLOSE","Premature close");En("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});En("ERR_MULTIPLE_CALLBACK","Callback called multiple times");En("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");En("ERR_STREAM_WRITE_AFTER_END","write after end");En("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);En("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);En("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");g8.exports.codes=m8});var Rk=$((u$e,x8)=>{"use strict";h();var hQ=ci().codes.ERR_INVALID_OPT_VALUE;function mQ(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}i(mQ,"highWaterMarkFrom");function gQ(e,t,r,n){var s=mQ(t,n,r);if(s!=null){if(!(isFinite(s)&&Math.floor(s)===s)||s<0){var o=n?r:"highWaterMark";throw new hQ(o,s)}return Math.floor(s)}return e.objectMode?16:16*1024}i(gQ,"getHighWaterMark");x8.exports={getHighWaterMark:gQ}});var y8=$((p$e,Ak)=>{h();typeof Object.create=="function"?Ak.exports=i(function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))},"inherits"):Ak.exports=i(function(t,r){if(r){t.super_=r;var n=i(function(){},"TempCtor");n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}},"inherits")});var li=$((g$e,Pk)=>{h();try{if(Ck=te("util"),typeof Ck.inherits!="function")throw"";Pk.exports=Ck.inherits}catch{Pk.exports=y8()}var Ck});var b8=$((y$e,w8)=>{h();w8.exports=te("util").deprecate});var Lk=$((b$e,$8)=>{"use strict";h();$8.exports=kt;function k8(e){var t=this;this.next=null,this.entry=null,this.finish=function(){WQ(t,e)}}i(k8,"CorkedRequest");var il;kt.WritableState=qf;var xQ={deprecate:b8()},_8=Ek(),g0=te("buffer").Buffer,yQ=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function wQ(e){return g0.from(e)}i(wQ,"_uint8ArrayToBuffer");function bQ(e){return g0.isBuffer(e)||e instanceof yQ}i(bQ,"_isUint8Array");var Ik=Tk(),vQ=Rk(),kQ=vQ.getHighWaterMark,ui=ci().codes,_Q=ui.ERR_INVALID_ARG_TYPE,SQ=ui.ERR_METHOD_NOT_IMPLEMENTED,EQ=ui.ERR_MULTIPLE_CALLBACK,$Q=ui.ERR_STREAM_CANNOT_PIPE,OQ=ui.ERR_STREAM_DESTROYED,TQ=ui.ERR_STREAM_NULL_VALUES,RQ=ui.ERR_STREAM_WRITE_AFTER_END,AQ=ui.ERR_UNKNOWN_ENCODING,al=Ik.errorOrDestroy;li()(kt,_8);function CQ(){}i(CQ,"nop");function qf(e,t,r){il=il||ba(),e=e||{},typeof r!="boolean"&&(r=t instanceof il),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=kQ(this,e,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=e.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(s){FQ(t,s)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new k8(this)}i(qf,"WritableState");qf.prototype.getBuffer=i(function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r},"getBuffer");(function(){try{Object.defineProperty(qf.prototype,"buffer",{get:xQ.deprecate(i(function(){return this.getBuffer()},"writableStateBufferGetter"),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var m0;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(m0=Function.prototype[Symbol.hasInstance],Object.defineProperty(kt,Symbol.hasInstance,{value:i(function(t){return m0.call(this,t)?!0:this!==kt?!1:t&&t._writableState instanceof qf},"value")})):m0=i(function(t){return t instanceof this},"realHasInstance");function kt(e){il=il||ba();var t=this instanceof il;if(!t&&!m0.call(kt,this))return new kt(e);this._writableState=new qf(e,this,t),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),_8.call(this)}i(kt,"Writable");kt.prototype.pipe=function(){al(this,new $Q)};function PQ(e,t){var r=new RQ;al(e,r),process.nextTick(t,r)}i(PQ,"writeAfterEnd");function NQ(e,t,r,n){var s;return r===null?s=new TQ:typeof r!="string"&&!t.objectMode&&(s=new _Q("chunk",["string","Buffer"],r)),s?(al(e,s),process.nextTick(n,s),!1):!0}i(NQ,"validChunk");kt.prototype.write=function(e,t,r){var n=this._writableState,s=!1,o=!n.objectMode&&bQ(e);return o&&!g0.isBuffer(e)&&(e=wQ(e)),typeof t=="function"&&(r=t,t=null),o?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=CQ),n.ending?PQ(this,r):(o||NQ(this,n,e,r))&&(n.pendingcb++,s=LQ(this,n,o,e,t,r)),s};kt.prototype.cork=function(){this._writableState.corked++};kt.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&S8(this,e))};kt.prototype.setDefaultEncoding=i(function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new AQ(t);return this._writableState.defaultEncoding=t,this},"setDefaultEncoding");Object.defineProperty(kt.prototype,"writableBuffer",{enumerable:!1,get:i(function(){return this._writableState&&this._writableState.getBuffer()},"get")});function IQ(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=g0.from(t,r)),t}i(IQ,"decodeChunk");Object.defineProperty(kt.prototype,"writableHighWaterMark",{enumerable:!1,get:i(function(){return this._writableState.highWaterMark},"get")});function LQ(e,t,r,n,s,o){if(!r){var a=IQ(t,n,s);n!==a&&(r=!0,s="buffer",n=a)}var c=t.objectMode?1:n.length;t.length+=c;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:s,isBuf:r,callback:o,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else Nk(e,t,!1,c,n,s,o);return l}i(LQ,"writeOrBuffer");function Nk(e,t,r,n,s,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new OQ("write")):r?e._writev(s,t.onwrite):e._write(s,o,t.onwrite),t.sync=!1}i(Nk,"doWrite");function jQ(e,t,r,n,s){--t.pendingcb,r?(process.nextTick(s,n),process.nextTick(Bf,e,t),e._writableState.errorEmitted=!0,al(e,n)):(s(n),e._writableState.errorEmitted=!0,al(e,n),Bf(e,t))}i(jQ,"onwriteError");function DQ(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}i(DQ,"onwriteStateUpdate");function FQ(e,t){var r=e._writableState,n=r.sync,s=r.writecb;if(typeof s!="function")throw new EQ;if(DQ(r),t)jQ(e,r,n,t,s);else{var o=E8(r)||e.destroyed;!o&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&S8(e,r),n?process.nextTick(v8,e,r,o,s):v8(e,r,o,s)}}i(FQ,"onwrite");function v8(e,t,r,n){r||MQ(e,t),t.pendingcb--,n(),Bf(e,t)}i(v8,"afterWrite");function MQ(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}i(MQ,"onwriteDrain");function S8(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,s=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var a=0,c=!0;r;)s[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;s.allBuffers=c,Nk(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new k8(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,f=r.callback,d=t.objectMode?1:l.length;if(Nk(e,t,!1,d,l,u,f),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}i(S8,"clearBuffer");kt.prototype._write=function(e,t,r){r(new SQ("_write()"))};kt.prototype._writev=null;kt.prototype.end=function(e,t,r){var n=this._writableState;return typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||UQ(this,n,r),this};Object.defineProperty(kt.prototype,"writableLength",{enumerable:!1,get:i(function(){return this._writableState.length},"get")});function E8(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}i(E8,"needFinish");function BQ(e,t){e._final(function(r){t.pendingcb--,r&&al(e,r),t.prefinished=!0,e.emit("prefinish"),Bf(e,t)})}i(BQ,"callFinal");function qQ(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(BQ,e,t)):(t.prefinished=!0,e.emit("prefinish")))}i(qQ,"prefinish");function Bf(e,t){var r=E8(t);if(r&&(qQ(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}i(Bf,"finishMaybe");function UQ(e,t,r){t.ending=!0,Bf(e,t),r&&(t.finished?process.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}i(UQ,"endWritable");function WQ(e,t,r){var n=e.entry;for(e.entry=null;n;){var s=n.callback;t.pendingcb--,s(r),n=n.next}t.corkedRequestsFree.next=e}i(WQ,"onCorkedFinish");Object.defineProperty(kt.prototype,"destroyed",{enumerable:!1,get:i(function(){return this._writableState===void 0?!1:this._writableState.destroyed},"get"),set:i(function(t){this._writableState&&(this._writableState.destroyed=t)},"set")});kt.prototype.destroy=Ik.destroy;kt.prototype._undestroy=Ik.undestroy;kt.prototype._destroy=function(e,t){t(e)}});var ba=$((_$e,T8)=>{"use strict";h();var KQ=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};T8.exports=Rs;var O8=Fk(),Dk=Lk();li()(Rs,O8);for(jk=KQ(Dk.prototype),x0=0;x0<jk.length;x0++)y0=jk[x0],Rs.prototype[y0]||(Rs.prototype[y0]=Dk.prototype[y0]);var jk,y0,x0;function Rs(e){if(!(this instanceof Rs))return new Rs(e);O8.call(this,e),Dk.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",VQ)))}i(Rs,"Duplex");Object.defineProperty(Rs.prototype,"writableHighWaterMark",{enumerable:!1,get:i(function(){return this._writableState.highWaterMark},"get")});Object.defineProperty(Rs.prototype,"writableBuffer",{enumerable:!1,get:i(function(){return this._writableState&&this._writableState.getBuffer()},"get")});Object.defineProperty(Rs.prototype,"writableLength",{enumerable:!1,get:i(function(){return this._writableState.length},"get")});function VQ(){this._writableState.ended||process.nextTick(HQ,this)}i(VQ,"onend");function HQ(e){e.end()}i(HQ,"onEndNT");Object.defineProperty(Rs.prototype,"destroyed",{enumerable:!1,get:i(function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},"get"),set:i(function(t){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=t,this._writableState.destroyed=t)},"set")})});var C8=$((Mk,A8)=>{h();var w0=te("buffer"),As=w0.Buffer;function R8(e,t){for(var r in e)t[r]=e[r]}i(R8,"copyProps");As.from&&As.alloc&&As.allocUnsafe&&As.allocUnsafeSlow?A8.exports=w0:(R8(w0,Mk),Mk.Buffer=va);function va(e,t,r){return As(e,t,r)}i(va,"SafeBuffer");va.prototype=Object.create(As.prototype);R8(As,va);va.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return As(e,t,r)};va.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=As(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};va.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return As(e)};va.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return w0.SlowBuffer(e)}});var Uk=$(N8=>{"use strict";h();var qk=C8().Buffer,P8=qk.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function GQ(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}i(GQ,"_normalizeEncoding");function YQ(e){var t=GQ(e);if(typeof t!="string"&&(qk.isEncoding===P8||!P8(e)))throw new Error("Unknown encoding: "+e);return t||e}i(YQ,"normalizeEncoding");N8.StringDecoder=Uf;function Uf(e){this.encoding=YQ(e);var t;switch(this.encoding){case"utf16le":this.text=eZ,this.end=tZ,t=4;break;case"utf8":this.fillLast=XQ,t=4;break;case"base64":this.text=rZ,this.end=nZ,t=3;break;default:this.write=sZ,this.end=oZ;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=qk.allocUnsafe(t)}i(Uf,"StringDecoder");Uf.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};Uf.prototype.end=ZQ;Uf.prototype.text=QQ;Uf.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function Bk(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}i(Bk,"utf8CheckByte");function zQ(e,t,r){var n=t.length-1;if(n<r)return 0;var s=Bk(t[n]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--n<r||s===-2?0:(s=Bk(t[n]),s>=0?(s>0&&(e.lastNeed=s-2),s):--n<r||s===-2?0:(s=Bk(t[n]),s>=0?(s>0&&(s===2?s=0:e.lastNeed=s-3),s):0))}i(zQ,"utf8CheckIncomplete");function JQ(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}i(JQ,"utf8CheckExtraBytes");function XQ(e){var t=this.lastTotal-this.lastNeed,r=JQ(this,e,t);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}i(XQ,"utf8FillLast");function QQ(e,t){var r=zQ(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}i(QQ,"utf8Text");function ZQ(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}i(ZQ,"utf8End");function eZ(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}i(eZ,"utf16Text");function tZ(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}i(tZ,"utf16End");function rZ(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}i(rZ,"base64Text");function nZ(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}i(nZ,"base64End");function sZ(e){return e.toString(this.encoding)}i(sZ,"simpleWrite");function oZ(e){return e&&e.length?this.write(e):""}i(oZ,"simpleEnd")});var b0=$((C$e,j8)=>{"use strict";h();var I8=ci().codes.ERR_STREAM_PREMATURE_CLOSE;function iZ(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];e.apply(this,n)}}}i(iZ,"once");function aZ(){}i(aZ,"noop");function cZ(e){return e.setHeader&&typeof e.abort=="function"}i(cZ,"isRequest");function L8(e,t,r){if(typeof t=="function")return L8(e,null,t);t||(t={}),r=iZ(r||aZ);var n=t.readable||t.readable!==!1&&e.readable,s=t.writable||t.writable!==!1&&e.writable,o=i(function(){e.writable||c()},"onlegacyfinish"),a=e._writableState&&e._writableState.finished,c=i(function(){s=!1,a=!0,n||r.call(e)},"onfinish"),l=e._readableState&&e._readableState.endEmitted,u=i(function(){n=!1,l=!0,s||r.call(e)},"onend"),f=i(function(y){r.call(e,y)},"onerror"),d=i(function(){var y;if(n&&!l)return(!e._readableState||!e._readableState.ended)&&(y=new I8),r.call(e,y);if(s&&!a)return(!e._writableState||!e._writableState.ended)&&(y=new I8),r.call(e,y)},"onclose"),p=i(function(){e.req.on("finish",c)},"onrequest");return cZ(e)?(e.on("complete",c),e.on("abort",d),e.req?p():e.on("request",p)):s&&!e._writableState&&(e.on("end",o),e.on("close",o)),e.on("end",u),e.on("finish",c),t.error!==!1&&e.on("error",f),e.on("close",d),function(){e.removeListener("complete",c),e.removeListener("abort",d),e.removeListener("request",p),e.req&&e.req.removeListener("finish",c),e.removeListener("end",o),e.removeListener("close",o),e.removeListener("finish",c),e.removeListener("end",u),e.removeListener("error",f),e.removeListener("close",d)}}i(L8,"eos");j8.exports=L8});var F8=$((I$e,D8)=>{"use strict";h();var v0;function fi(e,t,r){return t=lZ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}i(fi,"_defineProperty");function lZ(e){var t=uZ(e,"string");return typeof t=="symbol"?t:String(t)}i(lZ,"_toPropertyKey");function uZ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}i(uZ,"_toPrimitive");var fZ=b0(),di=Symbol("lastResolve"),ka=Symbol("lastReject"),Wf=Symbol("error"),k0=Symbol("ended"),_a=Symbol("lastPromise"),Wk=Symbol("handlePromise"),Sa=Symbol("stream");function pi(e,t){return{value:e,done:t}}i(pi,"createIterResult");function dZ(e){var t=e[di];if(t!==null){var r=e[Sa].read();r!==null&&(e[_a]=null,e[di]=null,e[ka]=null,t(pi(r,!1)))}}i(dZ,"readAndResolve");function pZ(e){process.nextTick(dZ,e)}i(pZ,"onReadable");function hZ(e,t){return function(r,n){e.then(function(){if(t[k0]){r(pi(void 0,!0));return}t[Wk](r,n)},n)}}i(hZ,"wrapForNext");var mZ=Object.getPrototypeOf(function(){}),gZ=Object.setPrototypeOf((v0={get stream(){return this[Sa]},next:i(function(){var t=this,r=this[Wf];if(r!==null)return Promise.reject(r);if(this[k0])return Promise.resolve(pi(void 0,!0));if(this[Sa].destroyed)return new Promise(function(a,c){process.nextTick(function(){t[Wf]?c(t[Wf]):a(pi(void 0,!0))})});var n=this[_a],s;if(n)s=new Promise(hZ(n,this));else{var o=this[Sa].read();if(o!==null)return Promise.resolve(pi(o,!1));s=new Promise(this[Wk])}return this[_a]=s,s},"next")},fi(v0,Symbol.asyncIterator,function(){return this}),fi(v0,"return",i(function(){var t=this;return new Promise(function(r,n){t[Sa].destroy(null,function(s){if(s){n(s);return}r(pi(void 0,!0))})})},"_return")),v0),mZ),xZ=i(function(t){var r,n=Object.create(gZ,(r={},fi(r,Sa,{value:t,writable:!0}),fi(r,di,{value:null,writable:!0}),fi(r,ka,{value:null,writable:!0}),fi(r,Wf,{value:null,writable:!0}),fi(r,k0,{value:t._readableState.endEmitted,writable:!0}),fi(r,Wk,{value:i(function(o,a){var c=n[Sa].read();c?(n[_a]=null,n[di]=null,n[ka]=null,o(pi(c,!1))):(n[di]=o,n[ka]=a)},"value"),writable:!0}),r));return n[_a]=null,fZ(t,function(s){if(s&&s.code!=="ERR_STREAM_PREMATURE_CLOSE"){var o=n[ka];o!==null&&(n[_a]=null,n[di]=null,n[ka]=null,o(s)),n[Wf]=s;return}var a=n[di];a!==null&&(n[_a]=null,n[di]=null,n[ka]=null,a(pi(void 0,!0))),n[k0]=!0}),t.on("readable",pZ.bind(null,n)),n},"createReadableStreamAsyncIterator");D8.exports=xZ});var U8=$((D$e,q8)=>{"use strict";h();function M8(e,t,r,n,s,o,a){try{var c=e[o](a),l=c.value}catch(u){r(u);return}c.done?t(l):Promise.resolve(l).then(n,s)}i(M8,"asyncGeneratorStep");function yZ(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var o=e.apply(t,r);function a(l){M8(o,n,s,a,c,"next",l)}i(a,"_next");function c(l){M8(o,n,s,a,c,"throw",l)}i(c,"_throw"),a(void 0)})}}i(yZ,"_asyncToGenerator");function B8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}i(B8,"ownKeys");function wZ(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?B8(Object(r),!0).forEach(function(n){bZ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):B8(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}i(wZ,"_objectSpread");function bZ(e,t,r){return t=vZ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}i(bZ,"_defineProperty");function vZ(e){var t=kZ(e,"string");return typeof t=="symbol"?t:String(t)}i(vZ,"_toPropertyKey");function kZ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}i(kZ,"_toPrimitive");var _Z=ci().codes.ERR_INVALID_ARG_TYPE;function SZ(e,t,r){var n;if(t&&typeof t.next=="function")n=t;else if(t&&t[Symbol.asyncIterator])n=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])n=t[Symbol.iterator]();else throw new _Z("iterable",["Iterable"],t);var s=new e(wZ({objectMode:!0},r)),o=!1;s._read=function(){o||(o=!0,a())};function a(){return c.apply(this,arguments)}i(a,"next");function c(){return c=yZ(function*(){try{var l=yield n.next(),u=l.value,f=l.done;f?s.push(null):s.push(yield u)?a():o=!1}catch(d){s.destroy(d)}}),c.apply(this,arguments)}return i(c,"_next2"),s}i(SZ,"from");q8.exports=SZ});var Fk=$((q$e,Q8)=>{"use strict";h();Q8.exports=Le;var cl;Le.ReadableState=H8;var B$e=te("events").EventEmitter,V8=i(function(t,r){return t.listeners(r).length},"EElistenerCount"),Vf=Ek(),_0=te("buffer").Buffer,EZ=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function $Z(e){return _0.from(e)}i($Z,"_uint8ArrayToBuffer");function OZ(e){return _0.isBuffer(e)||e instanceof EZ}i(OZ,"_isUint8Array");var Kk=te("util"),ve;Kk&&Kk.debuglog?ve=Kk.debuglog("stream"):ve=i(function(){},"debug");var TZ=f8(),Xk=Tk(),RZ=Rk(),AZ=RZ.getHighWaterMark,S0=ci().codes,CZ=S0.ERR_INVALID_ARG_TYPE,PZ=S0.ERR_STREAM_PUSH_AFTER_EOF,NZ=S0.ERR_METHOD_NOT_IMPLEMENTED,IZ=S0.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,ll,Vk,Hk;li()(Le,Vf);var Kf=Xk.errorOrDestroy,Gk=["error","close","destroy","pause","resume"];function LZ(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}i(LZ,"prependListener");function H8(e,t,r){cl=cl||ba(),e=e||{},typeof r!="boolean"&&(r=t instanceof cl),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=AZ(this,e,"readableHighWaterMark",r),this.buffer=new TZ,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(ll||(ll=Uk().StringDecoder),this.decoder=new ll(e.encoding),this.encoding=e.encoding)}i(H8,"ReadableState");function Le(e){if(cl=cl||ba(),!(this instanceof Le))return new Le(e);var t=this instanceof cl;this._readableState=new H8(e,this,t),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),Vf.call(this)}i(Le,"Readable");Object.defineProperty(Le.prototype,"destroyed",{enumerable:!1,get:i(function(){return this._readableState===void 0?!1:this._readableState.destroyed},"get"),set:i(function(t){this._readableState&&(this._readableState.destroyed=t)},"set")});Le.prototype.destroy=Xk.destroy;Le.prototype._undestroy=Xk.undestroy;Le.prototype._destroy=function(e,t){t(e)};Le.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=!0:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=_0.from(e,t),t=""),n=!0),G8(this,e,t,!1,n)};Le.prototype.unshift=function(e){return G8(this,e,null,!0,!1)};function G8(e,t,r,n,s){ve("readableAddChunk",t);var o=e._readableState;if(t===null)o.reading=!1,FZ(e,o);else{var a;if(s||(a=jZ(o,t)),a)Kf(e,a);else if(o.objectMode||t&&t.length>0)if(typeof t!="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==_0.prototype&&(t=$Z(t)),n)o.endEmitted?Kf(e,new IZ):Yk(e,o,t,!0);else if(o.ended)Kf(e,new PZ);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||t.length!==0?Yk(e,o,t,!1):Jk(e,o)):Yk(e,o,t,!1)}else n||(o.reading=!1,Jk(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}i(G8,"readableAddChunk");function Yk(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&E0(e)),Jk(e,t)}i(Yk,"addChunk");function jZ(e,t){var r;return!OZ(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new CZ("chunk",["string","Buffer","Uint8Array"],t)),r}i(jZ,"chunkInvalid");Le.prototype.isPaused=function(){return this._readableState.flowing===!1};Le.prototype.setEncoding=function(e){ll||(ll=Uk().StringDecoder);var t=new ll(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,n="";r!==null;)n+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),n!==""&&this._readableState.buffer.push(n),this._readableState.length=n.length,this};var W8=1073741824;function DZ(e){return e>=W8?e=W8:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}i(DZ,"computeNewHighWaterMark");function K8(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=DZ(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}i(K8,"howMuchToRead");Le.prototype.read=function(e){ve("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended))return ve("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?zk(this):E0(this),null;if(e=K8(e,t),e===0&&t.ended)return t.length===0&&zk(this),null;var n=t.needReadable;ve("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=!0,ve("length less than watermark",n)),t.ended||t.reading?(n=!1,ve("reading or ended",n)):n&&(ve("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=K8(r,t)));var s;return e>0?s=J8(e,t):s=null,s===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&zk(this)),s!==null&&this.emit("data",s),s};function FZ(e,t){if(ve("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?E0(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,Y8(e)))}}i(FZ,"onEofChunk");function E0(e){var t=e._readableState;ve("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(ve("emitReadable",t.flowing),t.emittedReadable=!0,process.nextTick(Y8,e))}i(E0,"emitReadable");function Y8(e){var t=e._readableState;ve("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Qk(e)}i(Y8,"emitReadable_");function Jk(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(MZ,e,t))}i(Jk,"maybeReadMore");function MZ(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var r=t.length;if(ve("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}i(MZ,"maybeReadMore_");Le.prototype._read=function(e){Kf(this,new NZ("_read()"))};Le.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,ve("pipe count=%d opts=%j",n.pipesCount,t);var s=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr,o=s?c:g;n.endEmitted?process.nextTick(o):r.once("end",o),e.on("unpipe",a);function a(x,v){ve("onunpipe"),x===r&&v&&v.hasUnpiped===!1&&(v.hasUnpiped=!0,f())}i(a,"onunpipe");function c(){ve("onend"),e.end()}i(c,"onend");var l=BZ(r);e.on("drain",l);var u=!1;function f(){ve("cleanup"),e.removeListener("close",m),e.removeListener("finish",y),e.removeListener("drain",l),e.removeListener("error",p),e.removeListener("unpipe",a),r.removeListener("end",c),r.removeListener("end",g),r.removeListener("data",d),u=!0,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&l()}i(f,"cleanup"),r.on("data",d);function d(x){ve("ondata");var v=e.write(x);ve("dest.write",v),v===!1&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&X8(n.pipes,e)!==-1)&&!u&&(ve("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}i(d,"ondata");function p(x){ve("onerror",x),g(),e.removeListener("error",p),V8(e,"error")===0&&Kf(e,x)}i(p,"onerror"),LZ(e,"error",p);function m(){e.removeListener("finish",y),g()}i(m,"onclose"),e.once("close",m);function y(){ve("onfinish"),e.removeListener("close",m),g()}i(y,"onfinish"),e.once("finish",y);function g(){ve("unpipe"),r.unpipe(e)}return i(g,"unpipe"),e.emit("pipe",r),n.flowing||(ve("pipe resume"),r.resume()),e};function BZ(e){return i(function(){var r=e._readableState;ve("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&V8(e,"data")&&(r.flowing=!0,Qk(e))},"pipeOnDrainFunctionResult")}i(BZ,"pipeOnDrain");Le.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<s;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=X8(t.pipes,e);return a===-1?this:(t.pipes.splice(a,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};Le.prototype.on=function(e,t){var r=Vf.prototype.on.call(this,e,t),n=this._readableState;return e==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==!1&&this.resume()):e==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,ve("on readable",n.length,n.reading),n.length?E0(this):n.reading||process.nextTick(qZ,this)),r};Le.prototype.addListener=Le.prototype.on;Le.prototype.removeListener=function(e,t){var r=Vf.prototype.removeListener.call(this,e,t);return e==="readable"&&process.nextTick(z8,this),r};Le.prototype.removeAllListeners=function(e){var t=Vf.prototype.removeAllListeners.apply(this,arguments);return(e==="readable"||e===void 0)&&process.nextTick(z8,this),t};function z8(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}i(z8,"updateReadableListening");function qZ(e){ve("readable nexttick read 0"),e.read(0)}i(qZ,"nReadingNextTick");Le.prototype.resume=function(){var e=this._readableState;return e.flowing||(ve("resume"),e.flowing=!e.readableListening,UZ(this,e)),e.paused=!1,this};function UZ(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(WZ,e,t))}i(UZ,"resume");function WZ(e,t){ve("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Qk(e),t.flowing&&!t.reading&&e.read(0)}i(WZ,"resume_");Le.prototype.pause=function(){return ve("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(ve("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Qk(e){var t=e._readableState;for(ve("flow",t.flowing);t.flowing&&e.read()!==null;);}i(Qk,"flow");Le.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;e.on("end",function(){if(ve("wrapped end"),r.decoder&&!r.ended){var a=r.decoder.end();a&&a.length&&t.push(a)}t.push(null)}),e.on("data",function(a){if(ve("wrapped data"),r.decoder&&(a=r.decoder.write(a)),!(r.objectMode&&a==null)&&!(!r.objectMode&&(!a||!a.length))){var c=t.push(a);c||(n=!0,e.pause())}});for(var s in e)this[s]===void 0&&typeof e[s]=="function"&&(this[s]=i(function(c){return i(function(){return e[c].apply(e,arguments)},"methodWrapReturnFunction")},"methodWrap")(s));for(var o=0;o<Gk.length;o++)e.on(Gk[o],this.emit.bind(this,Gk[o]));return this._read=function(a){ve("wrapped _read",a),n&&(n=!1,e.resume())},this};typeof Symbol=="function"&&(Le.prototype[Symbol.asyncIterator]=function(){return Vk===void 0&&(Vk=F8()),Vk(this)});Object.defineProperty(Le.prototype,"readableHighWaterMark",{enumerable:!1,get:i(function(){return this._readableState.highWaterMark},"get")});Object.defineProperty(Le.prototype,"readableBuffer",{enumerable:!1,get:i(function(){return this._readableState&&this._readableState.buffer},"get")});Object.defineProperty(Le.prototype,"readableFlowing",{enumerable:!1,get:i(function(){return this._readableState.flowing},"get"),set:i(function(t){this._readableState&&(this._readableState.flowing=t)},"set")});Le._fromList=J8;Object.defineProperty(Le.prototype,"readableLength",{enumerable:!1,get:i(function(){return this._readableState.length},"get")});function J8(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.first():r=t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}i(J8,"fromList");function zk(e){var t=e._readableState;ve("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(KZ,t,e))}i(zk,"endReadable");function KZ(e,t){if(ve("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}i(KZ,"endReadableNT");typeof Symbol=="function"&&(Le.from=function(e,t){return Hk===void 0&&(Hk=U8()),Hk(Le,e,t)});function X8(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}i(X8,"indexOf")});var Zk=$((K$e,eN)=>{"use strict";h();eN.exports=uo;var $0=ci().codes,VZ=$0.ERR_METHOD_NOT_IMPLEMENTED,HZ=$0.ERR_MULTIPLE_CALLBACK,GZ=$0.ERR_TRANSFORM_ALREADY_TRANSFORMING,YZ=$0.ERR_TRANSFORM_WITH_LENGTH_0,O0=ba();li()(uo,O0);function zZ(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new HZ);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}i(zZ,"afterTransform");function uo(e){if(!(this instanceof uo))return new uo(e);O0.call(this,e),this._transformState={afterTransform:zZ.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",JZ)}i(uo,"Transform");function JZ(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){Z8(e,t,r)}):Z8(this,null,null)}i(JZ,"prefinish");uo.prototype.push=function(e,t){return this._transformState.needTransform=!1,O0.prototype.push.call(this,e,t)};uo.prototype._transform=function(e,t,r){r(new VZ("_transform()"))};uo.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var s=this._readableState;(n.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}};uo.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};uo.prototype._destroy=function(e,t){O0.prototype._destroy.call(this,e,function(r){t(r)})};function Z8(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new YZ;if(e._transformState.transforming)throw new GZ;return e.push(null)}i(Z8,"done")});var nN=$((G$e,rN)=>{"use strict";h();rN.exports=Hf;var tN=Zk();li()(Hf,tN);function Hf(e){if(!(this instanceof Hf))return new Hf(e);tN.call(this,e)}i(Hf,"PassThrough");Hf.prototype._transform=function(e,t,r){r(null,e)}});var cN=$((J$e,aN)=>{"use strict";h();var e_;function XZ(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}i(XZ,"once");var iN=ci().codes,QZ=iN.ERR_MISSING_ARGS,ZZ=iN.ERR_STREAM_DESTROYED;function sN(e){if(e)throw e}i(sN,"noop");function eee(e){return e.setHeader&&typeof e.abort=="function"}i(eee,"isRequest");function tee(e,t,r,n){n=XZ(n);var s=!1;e.on("close",function(){s=!0}),e_===void 0&&(e_=b0()),e_(e,{readable:t,writable:r},function(a){if(a)return n(a);s=!0,n()});var o=!1;return function(a){if(!s&&!o){if(o=!0,eee(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(a||new ZZ("pipe"))}}}i(tee,"destroyer");function oN(e){e()}i(oN,"call");function ree(e,t){return e.pipe(t)}i(ree,"pipe");function nee(e){return!e.length||typeof e[e.length-1]!="function"?sN:e.pop()}i(nee,"popCallback");function see(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=nee(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new QZ("streams");var s,o=t.map(function(a,c){var l=c<t.length-1,u=c>0;return tee(a,l,u,function(f){s||(s=f),f&&o.forEach(oN),!l&&(o.forEach(oN),n(s))})});return t.reduce(ree)}i(see,"pipeline");aN.exports=see});var ul=$(($n,Yf)=>{h();var Gf=te("stream");process.env.READABLE_STREAM==="disable"&&Gf?(Yf.exports=Gf.Readable,Object.assign(Yf.exports,Gf),Yf.exports.Stream=Gf):($n=Yf.exports=Fk(),$n.Stream=Gf||$n,$n.Readable=$n,$n.Writable=Lk(),$n.Duplex=ba(),$n.Transform=Zk(),$n.PassThrough=nN(),$n.finished=b0(),$n.pipeline=cN())});var fN=$((e6e,uN)=>{"use strict";h();var{Buffer:Jn}=te("buffer"),lN=Symbol.for("BufferList");function it(e){if(!(this instanceof it))return new it(e);it._init.call(this,e)}i(it,"BufferList");it._init=i(function(t){Object.defineProperty(this,lN,{value:!0}),this._bufs=[],this.length=0,t&&this.append(t)},"_init");it.prototype._new=i(function(t){return new it(t)},"_new");it.prototype._offset=i(function(t){if(t===0)return[0,0];let r=0;for(let n=0;n<this._bufs.length;n++){let s=r+this._bufs[n].length;if(t<s||n===this._bufs.length-1)return[n,t-r];r=s}},"_offset");it.prototype._reverseOffset=function(e){let t=e[0],r=e[1];for(let n=0;n<t;n++)r+=this._bufs[n].length;return r};it.prototype.get=i(function(t){if(t>this.length||t<0)return;let r=this._offset(t);return this._bufs[r[0]][r[1]]},"get");it.prototype.slice=i(function(t,r){return typeof t=="number"&&t<0&&(t+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,t,r)},"slice");it.prototype.copy=i(function(t,r,n,s){if((typeof n!="number"||n<0)&&(n=0),(typeof s!="number"||s>this.length)&&(s=this.length),n>=this.length||s<=0)return t||Jn.alloc(0);let o=!!t,a=this._offset(n),c=s-n,l=c,u=o&&r||0,f=a[1];if(n===0&&s===this.length){if(!o)return this._bufs.length===1?this._bufs[0]:Jn.concat(this._bufs,this.length);for(let d=0;d<this._bufs.length;d++)this._bufs[d].copy(t,u),u+=this._bufs[d].length;return t}if(l<=this._bufs[a[0]].length-f)return o?this._bufs[a[0]].copy(t,r,f,f+l):this._bufs[a[0]].slice(f,f+l);o||(t=Jn.allocUnsafe(c));for(let d=a[0];d<this._bufs.length;d++){let p=this._bufs[d].length-f;if(l>p)this._bufs[d].copy(t,u,f),u+=p;else{this._bufs[d].copy(t,u,f,f+l),u+=p;break}l-=p,f&&(f=0)}return t.length>u?t.slice(0,u):t},"copy");it.prototype.shallowSlice=i(function(t,r){if(t=t||0,r=typeof r!="number"?this.length:r,t<0&&(t+=this.length),r<0&&(r+=this.length),t===r)return this._new();let n=this._offset(t),s=this._offset(r),o=this._bufs.slice(n[0],s[0]+1);return s[1]===0?o.pop():o[o.length-1]=o[o.length-1].slice(0,s[1]),n[1]!==0&&(o[0]=o[0].slice(n[1])),this._new(o)},"shallowSlice");it.prototype.toString=i(function(t,r,n){return this.slice(r,n).toString(t)},"toString");it.prototype.consume=i(function(t){if(t=Math.trunc(t),Number.isNaN(t)||t<=0)return this;for(;this._bufs.length;)if(t>=this._bufs[0].length)t-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(t),this.length-=t;break}return this},"consume");it.prototype.duplicate=i(function(){let t=this._new();for(let r=0;r<this._bufs.length;r++)t.append(this._bufs[r]);return t},"duplicate");it.prototype.append=i(function(t){if(t==null)return this;if(t.buffer)this._appendBuffer(Jn.from(t.buffer,t.byteOffset,t.byteLength));else if(Array.isArray(t))for(let r=0;r<t.length;r++)this.append(t[r]);else if(this._isBufferList(t))for(let r=0;r<t._bufs.length;r++)this.append(t._bufs[r]);else typeof t=="number"&&(t=t.toString()),this._appendBuffer(Jn.from(t));return this},"append");it.prototype._appendBuffer=i(function(t){this._bufs.push(t),this.length+=t.length},"appendBuffer");it.prototype.indexOf=function(e,t,r){if(r===void 0&&typeof t=="string"&&(r=t,t=void 0),typeof e=="function"||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof e=="number"?e=Jn.from([e]):typeof e=="string"?e=Jn.from(e,r):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=Jn.from(e.buffer,e.byteOffset,e.byteLength):Jn.isBuffer(e)||(e=Jn.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=this._offset(t),s=n[0],o=n[1];for(;s<this._bufs.length;s++){let a=this._bufs[s];for(;o<a.length;)if(a.length-o>=e.length){let l=a.indexOf(e,o);if(l!==-1)return this._reverseOffset([s,l]);o=a.length-e.length+1}else{let l=this._reverseOffset([s,o]);if(this._match(l,e))return l;o++}o=0}return-1};it.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let r=0;r<t.length;r++)if(this.get(e+r)!==t[r])return!1;return!0};(function(){let e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let t in e)(function(r){e[r]===null?it.prototype[r]=function(n,s){return this.slice(n,n+s)[r](0,s)}:it.prototype[r]=function(n=0){return this.slice(n,n+e[r])[r](0)}})(t)})();it.prototype._isBufferList=i(function(t){return t instanceof it||it.isBufferList(t)},"_isBufferList");it.isBufferList=i(function(t){return t!=null&&t[lN]},"isBufferList");uN.exports=it});var dN=$((n6e,T0)=>{"use strict";h();var t_=ul().Duplex,oee=li(),zf=fN();function lr(e){if(!(this instanceof lr))return new lr(e);if(typeof e=="function"){this._callback=e;let t=i(function(n){this._callback&&(this._callback(n),this._callback=null)},"piper").bind(this);this.on("pipe",i(function(n){n.on("error",t)},"onPipe")),this.on("unpipe",i(function(n){n.removeListener("error",t)},"onUnpipe")),e=null}zf._init.call(this,e),t_.call(this)}i(lr,"BufferListStream");oee(lr,t_);Object.assign(lr.prototype,zf.prototype);lr.prototype._new=i(function(t){return new lr(t)},"_new");lr.prototype._write=i(function(t,r,n){this._appendBuffer(t),typeof n=="function"&&n()},"_write");lr.prototype._read=i(function(t){if(!this.length)return this.push(null);t=Math.min(t,this.length),this.push(this.slice(0,t)),this.consume(t)},"_read");lr.prototype.end=i(function(t){t_.prototype.end.call(this,t),this._callback&&(this._callback(null,this.slice()),this._callback=null)},"end");lr.prototype._destroy=i(function(t,r){this._bufs.length=0,this.length=0,r(t)},"_destroy");lr.prototype._isBufferList=i(function(t){return t instanceof lr||t instanceof zf||lr.isBufferList(t)},"_isBufferList");lr.isBufferList=zf.isBufferList;T0.exports=lr;T0.exports.BufferListStream=lr;T0.exports.BufferList=zf});var s_=$(dl=>{h();var iee=Buffer.alloc,aee="0000000000000000000",cee="7777777777777777777",pN=48,hN=Buffer.from("ustar\0","binary"),lee=Buffer.from("00","binary"),uee=Buffer.from("ustar ","binary"),fee=Buffer.from(" \0","binary"),dee=parseInt("7777",8),Jf=257,n_=263,pee=i(function(e,t,r){return typeof e!="number"?r:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)},"clamp"),hee=i(function(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null},"toType"),mee=i(function(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0},"toTypeflag"),mN=i(function(e,t,r,n){for(;r<n;r++)if(e[r]===t)return r;return n},"indexOf"),gN=i(function(e){for(var t=256,r=0;r<148;r++)t+=e[r];for(var n=156;n<512;n++)t+=e[n];return t},"cksum"),hi=i(function(e,t){return e=e.toString(8),e.length>t?cee.slice(0,t)+" ":aee.slice(0,t-e.length)+e+" "},"encodeOct");function gee(e){var t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;for(var r=[],n=e.length-1;n>0;n--){var s=e[n];t?r.push(s):r.push(255-s)}var o=0,a=r.length;for(n=0;n<a;n++)o+=r[n]*Math.pow(256,n);return t?o:-1*o}i(gee,"parse256");var mi=i(function(e,t,r){if(e=e.slice(t,t+r),t=0,e[t]&128)return gee(e);for(;t<e.length&&e[t]===32;)t++;for(var n=pee(mN(e,32,t,e.length),e.length,e.length);t<n&&e[t]===0;)t++;return n===t?0:parseInt(e.slice(t,n).toString(),8)},"decodeOct"),fl=i(function(e,t,r,n){return e.slice(t,mN(e,0,t,t+r)).toString(n)},"decodeStr"),r_=i(function(e){var t=Buffer.byteLength(e),r=Math.floor(Math.log(t)/Math.log(10))+1;return t+r>=Math.pow(10,r)&&r++,t+r+e},"addLength");dl.decodeLongPath=function(e,t){return fl(e,0,e.length,t)};dl.encodePax=function(e){var t="";e.name&&(t+=r_(" path="+e.name+`
|
|
523
523
|
`)),e.linkname&&(t+=r_(" linkpath="+e.linkname+`
|
|
524
524
|
`));var r=e.pax;if(r)for(var n in r)t+=r_(" "+n+"="+r[n]+`
|
|
525
|
-
`);return Buffer.from(t)};dl.decodePax=function(e){for(var t={};e.length;){for(var r=0;r<e.length&&e[r]!==32;)r++;var n=parseInt(e.slice(0,r).toString(),10);if(!n)return t;var s=e.slice(r+1,n-1).toString(),o=s.indexOf("=");if(o===-1)return t;t[s.slice(0,o)]=s.slice(o+1),e=e.slice(n)}return t};dl.encode=function(e){var t=iee(512),r=e.name,n="";if(e.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),Buffer.byteLength(r)!==r.length)return null;for(;Buffer.byteLength(r)>100;){var s=r.indexOf("/");if(s===-1)return null;n+=n?"/"+r.slice(0,s):r.slice(0,s),r=r.slice(s+1)}return Buffer.byteLength(r)>100||Buffer.byteLength(n)>155||e.linkname&&Buffer.byteLength(e.linkname)>100?null:(t.write(r),t.write(hi(e.mode&dee,6),100),t.write(hi(e.uid,6),108),t.write(hi(e.gid,6),116),t.write(hi(e.size,11),124),t.write(hi(e.mtime.getTime()/1e3|0,11),136),t[156]=pN+mee(e.type),e.linkname&&t.write(e.linkname,157),hN.copy(t,Jf),lee.copy(t,n_),e.uname&&t.write(e.uname,265),e.gname&&t.write(e.gname,297),t.write(hi(e.devmajor||0,6),329),t.write(hi(e.devminor||0,6),337),n&&t.write(n,345),t.write(hi(gN(t),6),148),t)};dl.decode=function(e,t,r){var n=e[156]===0?0:e[156]-pN,s=fl(e,0,100,t),o=mi(e,100,8),a=mi(e,108,8),c=mi(e,116,8),l=mi(e,124,12),u=mi(e,136,12),f=hee(n),d=e[157]===0?null:fl(e,157,100,t),p=fl(e,265,32),m=fl(e,297,32),y=mi(e,329,8),g=mi(e,337,8),x=gN(e);if(x===8*32)return null;if(x!==mi(e,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(hN.compare(e,Jf,Jf+6)===0)e[345]&&(s=fl(e,345,155,t)+"/"+s);else if(!(uee.compare(e,Jf,Jf+6)===0&&fee.compare(e,n_,n_+2)===0)){if(!r)throw new Error("Invalid tar header: unknown format.")}return n===0&&s&&s[s.length-1]==="/"&&(n=5),{name:s,mode:o,uid:a,gid:c,size:l,mtime:new Date(1e3*u),type:f,linkname:d,uname:p,gname:m,devmajor:y,devminor:g}}});var _N=$((l6e,kN)=>{h();var yN=te("util"),xee=dN(),Xf=s_(),wN=ul().Writable,bN=ul().PassThrough,vN=i(function(){},"noop"),xN=i(function(e){return e&=511,e&&512-e},"overflow"),yee=i(function(e,t){var r=new R0(e,t);return r.end(),r},"emptyStream"),wee=i(function(e,t){return t.path&&(e.name=t.path),t.linkpath&&(e.linkname=t.linkpath),t.size&&(e.size=parseInt(t.size,10)),e.pax=t,e},"mixinPax"),R0=i(function(e,t){this._parent=e,this.offset=t,bN.call(this,{autoDestroy:!1})},"Source");yN.inherits(R0,bN);R0.prototype.destroy=function(e){this._parent.destroy(e)};var fo=i(function(e){if(!(this instanceof fo))return new fo(e);wN.call(this,e),e=e||{},this._offset=0,this._buffer=xee(),this._missing=0,this._partial=!1,this._onparse=vN,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var t=this,r=t._buffer,n=i(function(){t._continue()},"oncontinue"),s=i(function(p){if(t._locked=!1,p)return t.destroy(p);t._stream||n()},"onunlock"),o=i(function(){t._stream=null;var p=xN(t._header.size);p?t._parse(p,a):t._parse(512,d),t._locked||n()},"onstreamend"),a=i(function(){t._buffer.consume(xN(t._header.size)),t._parse(512,d),n()},"ondrain"),c=i(function(){var p=t._header.size;t._paxGlobal=Xf.decodePax(r.slice(0,p)),r.consume(p),o()},"onpaxglobalheader"),l=i(function(){var p=t._header.size;t._pax=Xf.decodePax(r.slice(0,p)),t._paxGlobal&&(t._pax=Object.assign({},t._paxGlobal,t._pax)),r.consume(p),o()},"onpaxheader"),u=i(function(){var p=t._header.size;this._gnuLongPath=Xf.decodeLongPath(r.slice(0,p),e.filenameEncoding),r.consume(p),o()},"ongnulongpath"),f=i(function(){var p=t._header.size;this._gnuLongLinkPath=Xf.decodeLongPath(r.slice(0,p),e.filenameEncoding),r.consume(p),o()},"ongnulonglinkpath"),d=i(function(){var p=t._offset,m;try{m=t._header=Xf.decode(r.slice(0,512),e.filenameEncoding,e.allowUnknownFormat)}catch(y){t.emit("error",y)}if(r.consume(512),!m){t._parse(512,d),n();return}if(m.type==="gnu-long-path"){t._parse(m.size,u),n();return}if(m.type==="gnu-long-link-path"){t._parse(m.size,f),n();return}if(m.type==="pax-global-header"){t._parse(m.size,c),n();return}if(m.type==="pax-header"){t._parse(m.size,l),n();return}if(t._gnuLongPath&&(m.name=t._gnuLongPath,t._gnuLongPath=null),t._gnuLongLinkPath&&(m.linkname=t._gnuLongLinkPath,t._gnuLongLinkPath=null),t._pax&&(t._header=m=wee(m,t._pax),t._pax=null),t._locked=!0,!m.size||m.type==="directory"){t._parse(512,d),t.emit("entry",m,yee(t,p),s);return}t._stream=new R0(t,p),t.emit("entry",m,t._stream,s),t._parse(m.size,o),n()},"onheader");this._onheader=d,this._parse(512,d)},"Extract");yN.inherits(fo,wN);fo.prototype.destroy=function(e){this._destroyed||(this._destroyed=!0,e&&this.emit("error",e),this.emit("close"),this._stream&&this._stream.emit("close"))};fo.prototype._parse=function(e,t){this._destroyed||(this._offset+=e,this._missing=e,t===this._onheader&&(this._partial=!1),this._onparse=t)};fo.prototype._continue=function(){if(!this._destroyed){var e=this._cb;this._cb=vN,this._overflow?this._write(this._overflow,void 0,e):e()}};fo.prototype._write=function(e,t,r){if(!this._destroyed){var n=this._stream,s=this._buffer,o=this._missing;if(e.length&&(this._partial=!0),e.length<o)return this._missing-=e.length,this._overflow=null,n?n.write(e,r):(s.append(e),r());this._cb=r,this._missing=0;var a=null;e.length>o&&(a=e.slice(o),e=e.slice(0,o)),n?n.end(e):s.append(e),this._overflow=a,this._onparse()}};fo.prototype._final=function(e){if(this._partial)return this.destroy(new Error("Unexpected end of data"));e()};kN.exports=fo});var EN=$((d6e,SN)=>{h();SN.exports=te("fs").constants||te("constants")});var TN=$((h6e,ON)=>{h();ON.exports=$N;function $N(e,t){if(e&&t)return $N(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){r[n]=e[n]}),r;function r(){for(var n=new Array(arguments.length),s=0;s<n.length;s++)n[s]=arguments[s];var o=e.apply(this,n),a=n[n.length-1];return typeof o=="function"&&o!==a&&Object.keys(a).forEach(function(c){o[c]=a[c]}),o}i(r,"wrapper")}i($N,"wrappy")});var i_=$((x6e,o_)=>{h();var RN=TN();o_.exports=RN(A0);o_.exports.strict=RN(AN);A0.proto=A0(function(){Object.defineProperty(Function.prototype,"once",{value:i(function(){return A0(this)},"value"),configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:i(function(){return AN(this)},"value"),configurable:!0})});function A0(e){var t=i(function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))},"f");return t.called=!1,t}i(A0,"once");function AN(e){var t=i(function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},"f"),r=e.name||"Function wrapped with `once`";return t.onceError=r+" shouldn't be called more than once",t.called=!1,t}i(AN,"onceStrict")});var a_=$((b6e,PN)=>{h();var bee=i_(),vee=i(function(){},"noop"),kee=global.Bare?queueMicrotask:process.nextTick.bind(process),_ee=i(function(e){return e.setHeader&&typeof e.abort=="function"},"isRequest"),See=i(function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},"isChildProcess"),CN=i(function(e,t,r){if(typeof t=="function")return CN(e,null,t);t||(t={}),r=bee(r||vee);var n=e._writableState,s=e._readableState,o=t.readable||t.readable!==!1&&e.readable,a=t.writable||t.writable!==!1&&e.writable,c=!1,l=i(function(){e.writable||u()},"onlegacyfinish"),u=i(function(){a=!1,o||r.call(e)},"onfinish"),f=i(function(){o=!1,a||r.call(e)},"onend"),d=i(function(x){r.call(e,x?new Error("exited with error code: "+x):null)},"onexit"),p=i(function(x){r.call(e,x)},"onerror"),m=i(function(){kee(y)},"onclose"),y=i(function(){if(!c){if(o&&!(s&&s.ended&&!s.destroyed))return r.call(e,new Error("premature close"));if(a&&!(n&&n.ended&&!n.destroyed))return r.call(e,new Error("premature close"))}},"onclosenexttick"),g=i(function(){e.req.on("finish",u)},"onrequest");return _ee(e)?(e.on("complete",u),e.on("abort",m),e.req?g():e.on("request",g)):a&&!n&&(e.on("end",l),e.on("close",l)),See(e)&&e.on("exit",d),e.on("end",f),e.on("finish",u),t.error!==!1&&e.on("error",p),e.on("close",m),function(){c=!0,e.removeListener("complete",u),e.removeListener("abort",m),e.removeListener("request",g),e.req&&e.req.removeListener("finish",u),e.removeListener("end",l),e.removeListener("close",l),e.removeListener("finish",u),e.removeListener("exit",d),e.removeListener("end",f),e.removeListener("error",p),e.removeListener("close",m)}},"eos");PN.exports=CN});var DN=$((_6e,jN)=>{h();var pl=EN(),NN=a_(),P0=li(),Eee=Buffer.alloc,IN=ul().Readable,hl=ul().Writable,$ee=te("string_decoder").StringDecoder,C0=s_(),Oee=parseInt("755",8),Tee=parseInt("644",8),LN=Eee(1024),l_=i(function(){},"noop"),c_=i(function(e,t){t&=511,t&&e.push(LN.slice(0,512-t))},"overflow");function Ree(e){switch(e&pl.S_IFMT){case pl.S_IFBLK:return"block-device";case pl.S_IFCHR:return"character-device";case pl.S_IFDIR:return"directory";case pl.S_IFIFO:return"fifo";case pl.S_IFLNK:return"symlink"}return"file"}i(Ree,"modeToType");var N0=i(function(e){hl.call(this),this.written=0,this._to=e,this._destroyed=!1},"Sink");P0(N0,hl);N0.prototype._write=function(e,t,r){if(this.written+=e.length,this._to.push(e))return r();this._to._drain=r};N0.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var I0=i(function(){hl.call(this),this.linkname="",this._decoder=new $ee("utf-8"),this._destroyed=!1},"LinkSink");P0(I0,hl);I0.prototype._write=function(e,t,r){this.linkname+=this._decoder.write(e),r()};I0.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var Qf=i(function(){hl.call(this),this._destroyed=!1},"Void");P0(Qf,hl);Qf.prototype._write=function(e,t,r){r(new Error("No body allowed for this entry"))};Qf.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var Cs=i(function(e){if(!(this instanceof Cs))return new Cs(e);IN.call(this,e),this._drain=l_,this._finalized=!1,this._finalizing=!1,this._destroyed=!1,this._stream=null},"Pack");P0(Cs,IN);Cs.prototype.entry=function(e,t,r){if(this._stream)throw new Error("already piping an entry");if(!(this._finalized||this._destroyed)){typeof t=="function"&&(r=t,t=null),r||(r=l_);var n=this;if((!e.size||e.type==="symlink")&&(e.size=0),e.type||(e.type=Ree(e.mode)),e.mode||(e.mode=e.type==="directory"?Oee:Tee),e.uid||(e.uid=0),e.gid||(e.gid=0),e.mtime||(e.mtime=new Date),typeof t=="string"&&(t=Buffer.from(t)),Buffer.isBuffer(t)){e.size=t.length,this._encode(e);var s=this.push(t);return c_(n,e.size),s?process.nextTick(r):this._drain=r,new Qf}if(e.type==="symlink"&&!e.linkname){var o=new I0;return NN(o,function(c){if(c)return n.destroy(),r(c);e.linkname=o.linkname,n._encode(e),r()}),o}if(this._encode(e),e.type!=="file"&&e.type!=="contiguous-file")return process.nextTick(r),new Qf;var a=new N0(this);return this._stream=a,NN(a,function(c){if(n._stream=null,c)return n.destroy(),r(c);if(a.written!==e.size)return n.destroy(),r(new Error("size mismatch"));c_(n,e.size),n._finalizing&&n.finalize(),r()}),a}};Cs.prototype.finalize=function(){if(this._stream){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(LN),this.push(null))};Cs.prototype.destroy=function(e){this._destroyed||(this._destroyed=!0,e&&this.emit("error",e),this.emit("close"),this._stream&&this._stream.destroy&&this._stream.destroy())};Cs.prototype._encode=function(e){if(!e.pax){var t=C0.encode(e);if(t){this.push(t);return}}this._encodePax(e)};Cs.prototype._encodePax=function(e){var t=C0.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.length,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(C0.encode(r)),this.push(t),c_(this,t.length),r.size=e.size,r.type=e.type,this.push(C0.encode(r))};Cs.prototype._read=function(e){var t=this._drain;this._drain=l_,t()};jN.exports=Cs});var FN=$(u_=>{h();u_.extract=_N();u_.pack=DN()});var qN=$((T6e,BN)=>{h();var Aee=i_(),Cee=a_(),L0;try{L0=te("fs")}catch{}var Zf=i(function(){},"noop"),Pee=typeof process>"u"?!1:/^v?\.0/.test(process.version),j0=i(function(e){return typeof e=="function"},"isFn"),Nee=i(function(e){return!Pee||!L0?!1:(e instanceof(L0.ReadStream||Zf)||e instanceof(L0.WriteStream||Zf))&&j0(e.close)},"isFS"),Iee=i(function(e){return e.setHeader&&j0(e.abort)},"isRequest"),Lee=i(function(e,t,r,n){n=Aee(n);var s=!1;e.on("close",function(){s=!0}),Cee(e,{readable:t,writable:r},function(a){if(a)return n(a);s=!0,n()});var o=!1;return function(a){if(!s&&!o){if(o=!0,Nee(e))return e.close(Zf);if(Iee(e))return e.abort();if(j0(e.destroy))return e.destroy();n(a||new Error("stream was destroyed"))}}},"destroyer"),MN=i(function(e){e()},"call"),jee=i(function(e,t){return e.pipe(t)},"pipe"),Dee=i(function(){var e=Array.prototype.slice.call(arguments),t=j0(e[e.length-1]||Zf)&&e.pop()||Zf;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw new Error("pump requires two streams per minimum");var r,n=e.map(function(s,o){var a=o<e.length-1,c=o>0;return Lee(s,a,c,function(l){r||(r=l),l&&n.forEach(MN),!a&&(n.forEach(MN),t(r))})});return e.reduce(jee)},"pump");BN.exports=Dee});var VN=$((C6e,KN)=>{h();var D0=te("path"),UN=te("fs"),WN=parseInt("0777",8);KN.exports=ml.mkdirp=ml.mkdirP=ml;function ml(e,t,r,n){typeof t=="function"?(r=t,t={}):(!t||typeof t!="object")&&(t={mode:t});var s=t.mode,o=t.fs||UN;s===void 0&&(s=WN&~process.umask()),n||(n=null);var a=r||function(){};e=D0.resolve(e),o.mkdir(e,s,function(c){if(!c)return n=n||e,a(null,n);switch(c.code){case"ENOENT":ml(D0.dirname(e),t,function(l,u){l?a(l,u):ml(e,t,a,u)});break;default:o.stat(e,function(l,u){l||!u.isDirectory()?a(c,n):a(null,n)});break}})}i(ml,"mkdirP");ml.sync=i(function e(t,r,n){(!r||typeof r!="object")&&(r={mode:r});var s=r.mode,o=r.fs||UN;s===void 0&&(s=WN&~process.umask()),n||(n=null),t=D0.resolve(t);try{o.mkdirSync(t,s),n=n||t}catch(c){switch(c.code){case"ENOENT":n=e(D0.dirname(t),r,n),e(t,r,n);break;default:var a;try{a=o.statSync(t)}catch{throw c}if(!a.isDirectory())throw c;break}}return n},"sync")});var eI=$(h_=>{h();var Fee=sP(),GN=FN(),YN=qN(),Mee=VN(),zN=te("fs"),xt=te("path"),Bee=te("os"),ed=Bee.platform()==="win32",td=i(function(){},"noop"),p_=i(function(e){return e},"echo"),f_=ed?function(e){return e.replace(/\\/g,"/").replace(/[:?<>|]/g,"_")}:p_,qee=i(function(e,t,r,n,s,o){for(var a=s||["."],c=0;c<a.length;c++)if(!d_(xt.resolve(r,a[c]),r))throw new Error(a[c]+" is not a valid path");return i(function(u){if(!a.length)return u();var f=a.shift(),d=xt.join(r,f);t.call(e,d,function(p,m){if(p)return u(p);if(!m.isDirectory())return u(null,f,m);e.readdir(d,function(y,g){if(y)return u(y);o&&g.sort();for(var x=0;x<g.length;x++)n(xt.join(r,f,g[x]))||a.push(xt.join(f,g[x]));u(null,f,m)})})},"loop")},"statAll"),JN=i(function(e,t){return function(r){r.name=r.name.split("/").slice(t).join("/");var n=r.linkname;return n&&(r.type==="link"||xt.isAbsolute(n))&&(r.linkname=n.split("/").slice(t).join("/")),e(r)}},"strip");h_.pack=function(e,t){e||(e="."),t||(t={});var r=t.fs||zN,n=t.ignore||t.filter||td,s=t.map||td,o=t.mapStream||p_,a=qee(r,t.dereference?r.stat:r.lstat,e,n,t.entries,t.sort),c=t.strict!==!1,l=typeof t.umask=="number"?~t.umask:~XN(),u=typeof t.dmode=="number"?t.dmode:0,f=typeof t.fmode=="number"?t.fmode:0,d=t.pack||GN.pack(),p=t.finish||td;t.strip&&(s=JN(s,t.strip)),t.readable&&(u|=parseInt(555,8),f|=parseInt(444,8)),t.writable&&(u|=parseInt(333,8),f|=parseInt(222,8));var m=i(function(x,v){r.readlink(xt.join(e,x),function(k,b){if(k)return d.destroy(k);v.linkname=f_(b),d.entry(v,g)})},"onsymlink"),y=i(function(x,v,k){if(x)return d.destroy(x);if(!v)return t.finalize!==!1&&d.finalize(),p(d);if(k.isSocket())return g();var b={name:f_(v),mode:(k.mode|(k.isDirectory()?u:f))&l,mtime:k.mtime,size:k.size,type:"file",uid:k.uid,gid:k.gid};if(k.isDirectory())return b.size=0,b.type="directory",b=s(b)||b,d.entry(b,g);if(k.isSymbolicLink())return b.size=0,b.type="symlink",b=s(b)||b,m(v,b);if(b=s(b)||b,!k.isFile())return c?d.destroy(new Error("unsupported type for "+v)):g();var S=d.entry(b,g);if(S){var E=o(r.createReadStream(xt.join(e,v),{start:0,end:b.size>0?b.size-1:b.size}),b);E.on("error",function(T){S.destroy(T)}),YN(E,S)}},"onstat"),g=i(function(x){if(x)return d.destroy(x);a(y)},"onnextentry");return g(),d};var Uee=i(function(e){return e.length?e[e.length-1]:null},"head"),Wee=i(function(){return process.getuid?process.getuid():-1},"processGetuid"),XN=i(function(){return process.umask?process.umask():0},"processUmask");h_.extract=function(e,t){e||(e="."),t||(t={});var r=t.fs||zN,n=t.ignore||t.filter||td,s=t.map||td,o=t.mapStream||p_,a=t.chown!==!1&&!ed&&Wee()===0,c=t.extract||GN.extract(),l=[],u=new Date,f=typeof t.umask=="number"?~t.umask:~XN(),d=typeof t.dmode=="number"?t.dmode:0,p=typeof t.fmode=="number"?t.fmode:0,m=t.strict!==!1;t.strip&&(s=JN(s,t.strip)),t.readable&&(d|=parseInt(555,8),p|=parseInt(444,8)),t.writable&&(d|=parseInt(333,8),p|=parseInt(222,8));var y=i(function(v,k){for(var b;(b=Uee(l))&&v.slice(0,b[0].length)!==b[0];)l.pop();if(!b)return k();r.utimes(b[0],u,b[1],k)},"utimesParent"),g=i(function(v,k,b){if(t.utimes===!1)return b();if(k.type==="directory")return r.utimes(v,u,k.mtime,b);if(k.type==="symlink")return y(v,b);r.utimes(v,u,k.mtime,function(S){if(S)return b(S);y(v,b)})},"utimes"),x=i(function(v,k,b){var S=k.type==="symlink",E=S?r.lchmod:r.chmod,T=S?r.lchown:r.chown;if(!E)return b();var R=(k.mode|(k.type==="directory"?d:p))&f&parseInt(777,8);T&&a?T.call(r,v,k.uid,k.gid,I):I(null);function I(P){if(P)return b(P);if(!E)return b();E.call(r,v,R,b)}i(I,"onchown")},"chperm");return c.on("entry",function(v,k,b){v=s(v)||v,v.name=f_(v.name);var S=xt.join(e,xt.join("/",v.name));if(n(S,v))return k.resume(),b();var E=i(function(j){if(j)return b(j);if(xt.join(S,".")===xt.join(e,"."))return b();g(S,v,function(M){if(M)return b(M);if(ed)return b();x(S,v,b)})},"stat"),T=i(function(){if(ed)return b();r.unlink(S,function(){var j=xt.resolve(xt.dirname(S),v.linkname);if(!d_(j,e))return b(new Error(S+" is not a valid symlink"));ZN(r,j,xt.resolve(e),function(M,A){if(M)return b(M);if(!A)return b(new Error(S+" is not a valid symlink"));r.symlink(v.linkname,S,E)})})},"onsymlink"),R=i(function(){if(ed)return b();r.unlink(S,function(){var j=xt.join(e,xt.join("/",v.linkname));r.realpath(j,function(M,A){if(M||!d_(A,e))return b(new Error(S+" is not a valid hardlink"));r.link(A,S,function(B){if(B&&B.code==="EPERM"&&t.hardlinkAsFilesFallback)return k=r.createReadStream(j),I();E(B)})})})},"onlink"),I=i(function(){r.lstat(S,function(M,A){if(!M&&A.isSymbolicLink())return r.unlink(S,j);j()});function j(M){if(M)return b(M);var A=r.createWriteStream(S),B=o(k,v);A.on("error",function(W){B.destroy(W)}),YN(B,A,function(W){if(W)return b(W);A.on("close",E)})}i(j,"onwrite")},"onfile");if(v.type==="directory")return l.push([S,v.mtime]),HN(S,{fs:r,own:a,uid:v.uid,gid:v.gid},E);var P=xt.dirname(S);QN(r,P,xt.join(e,"."),function(j,M){if(j)return b(j);if(!M)return b(new Error(P+" is not a valid path"));HN(P,{fs:r,own:a,uid:v.uid,gid:v.gid},function(A){if(A)return b(A);switch(v.type){case"file":return I();case"link":return R();case"symlink":return T()}if(m)return b(new Error("unsupported type for "+S+" ("+v.type+")"));k.resume(),b()})})}),t.finish&&c.on("finish",t.finish),c};function QN(e,t,r,n){if(t===r)return n(null,!0);e.lstat(t,function(s,o){if(s&&s.code!=="ENOENT")return n(s);if(s||o.isDirectory())return QN(e,xt.join(t,".."),r,n);n(null,!1)})}i(QN,"validate");function ZN(e,t,r,n){if(t===r)return n(null,!0);if(!t.startsWith(r+xt.sep))return n(null,!1);e.lstat(t,function(s,o){if(s&&s.code!=="ENOENT"&&s.code!=="EPERM")return n(s);if(s||!o.isSymbolicLink())return ZN(e,xt.join(t,".."),r,n);n(null,!1)})}i(ZN,"validateNotSymlink");function HN(e,t,r){Mee(e,{fs:t.fs},function(n,s){!n&&s&&t.own?Fee(s,t.uid,t.gid,r):r(n)})}i(HN,"mkdirfix");function d_(e,t){return t=xt.resolve(t),t===e||e.startsWith(t+xt.sep)}i(d_,"inCwd")});import{createHash as Kee}from"node:crypto";import{readFileSync as oI}from"node:fs";import*as iI from"node:os";import*as Ps from"node:path";import{PassThrough as tI,Readable as aI}from"node:stream";import{StringDecoder as Vee}from"node:string_decoder";import Hee from"dockerode";function Gee(){return Qee(zee()??Xee()??"")}function zee(){if(process.env.DOCKER_HOST)return process.env.DOCKER_HOST;try{let e=process.env.DOCKER_CONFIG||Ps.join(iI.homedir(),".docker"),t=process.env.DOCKER_CONTEXT||Jee(e);if(t==="default")return Yee;let r=Kee("sha256").update(t).digest("hex"),s=JSON.parse(oI(Ps.join(e,"contexts","meta",r,"meta.json"),"utf8"))?.Endpoints?.docker?.Host;return typeof s=="string"&&s?s:null}catch{return null}}function Jee(e){try{return JSON.parse(oI(Ps.join(e,"config.json"),"utf8"))?.currentContext||"default"}catch{return"default"}}function Xee(){try{let e=H(["docker","context","inspect","--format","{{.Endpoints.docker.Host}}"],{capture:!0,timeout:10});return e.status!==0?null:e.stdout.trim()||null}catch(e){if(e instanceof Z)return null;throw e}}function Qee(e){if(e.startsWith("unix://"))return{socketPath:e.slice(7)};if(/^(tcp|http|https):\/\//.test(e)){let t=new URL(e),r=t.protocol==="https:";return{host:t.hostname,port:Number(t.port)||(r?2376:2375),protocol:r?"https":"http"}}return{socketPath:"/var/run/docker.sock"}}function lt(){return Zee??=new Hee(Gee())}async function Mt(e,t,{all:r=!0}={}){let n=[e?`com.docker.compose.project=${e}`:"com.docker.compose.project","com.docker.compose.oneoff=False",...t?[`com.docker.compose.service=${t}`]:[]];try{return(await rd(10,"docker ps",lt().listContainers({all:r,filters:{label:n}}))).map(ete).sort((o,a)=>o.name<a.name?-1:o.name>a.name?1:0)}catch{return null}}function ete(e){let t=e.Labels??{},r=e.Status??"";return{name:e.Names?.[0]?.replace(/^\//,"")??e.Id.slice(0,12),state:e.State??"",health:tte(r),ports:rte(e.Ports??[]),service:t["com.docker.compose.service"]??"",labels:t,exitCode:Number(/^\s*Exited \((\d+)\)/.exec(r)?.[1]??0)}}function tte(e){let t=/\((healthy|unhealthy|health: starting)\)/.exec(e);return t?t[1]==="health: starting"?"starting":t[1]:""}function rte(e){let t=i((a,c)=>a<c?-1:a>c?1:0,"cmp"),r=[...e].sort((a,c)=>a.PrivatePort-c.PrivatePort||t(a.IP??"",c.IP??"")||(a.PublicPort??0)-(c.PublicPort??0)||t(a.Type,c.Type)),n=new Map,s=[],o=[];for(let a of r){let c=a.PrivatePort;if(a.IP&&a.PublicPort!==c){o.push(`${lI(a.IP,String(a.PublicPort))}->${c}/${a.Type}`);continue}let l=a.IP?`${a.IP}/${a.Type}`:a.Type,u=n.get(l);if(u&&c===u.last+1){u.last=c;continue}u&&s.push(rI(l,u)),n.set(l,{first:c,last:c})}for(let[a,c]of n)s.push(rI(a,c));return[...s,...o].join(", ")}function rI(e,{first:t,last:r}){let[n,s]=e.includes("/")?e.split("/"):["",e],o=t===r?`${t}`:`${t}-${r}`;return n?`${lI(n,o)}->${o}/${s}`:`${o}/${s}`}function lI(e,t){return e.includes(":")?`[${e}]:${t}`:`${e}:${t}`}async function F0(e){try{return(await lt().getContainer(e).inspect()).State.Running===!0}catch{return!1}}function nte(e){let t=e.cpu_stats.cpu_usage.total_usage-e.precpu_stats.cpu_usage.total_usage,r=e.cpu_stats.system_cpu_usage-e.precpu_stats.system_cpu_usage;if(t<=0||r<=0)return 0;let n=e.cpu_stats.online_cpus||e.cpu_stats.cpu_usage.percpu_usage?.length||1;return t/r*n*100}function ste(e){let t=e.memory_stats.stats??{},r=t.inactive_file??t.total_inactive_file??t.cache??0;return((e.memory_stats.usage??0)-r)/uI}async function gl(e){let t;try{t=await lt().listContainers({abortSignal:e})}catch{return[]}let r={stream:!1,abortSignal:e};return(await Promise.all(t.map(async s=>{try{let o=await lt().getContainer(s.Id).stats(r);return{name:s.Names[0]?.replace(/^\//,"")??s.Id.slice(0,12),cpuPercent:nte(o),memMib:ste(o),memLimitMib:(o.memory_stats.limit??0)/uI,labels:s.Labels??{}}}catch{return null}}))).filter(s=>s!==null)}async function fI(e){let t=await Promise.all(e.map(async r=>{try{let n=await rd(10,"docker inspect",lt().getContainer(r).inspect()),s={startedAt:Date.parse(n.State.StartedAt),restartCount:n.RestartCount??0,tty:n.Config.Tty};return[r,s]}catch{return null}}));return new Map(t.filter(r=>r!==null))}async function dI(e,t){try{let r=await rd(10,"docker logs",lt().getContainer(e).logs({stdout:!0,stderr:!0,tail:1,follow:!1})),n=null;return await pI(aI.from([r]),t,"",s=>{s.trim()&&(n=s.trim().slice(0,200))}),n}catch{return null}}function rd(e,t,r){let n,s=new Promise((o,a)=>{n=setTimeout(()=>a(new Error(`${t} timed out after ${e} seconds`)),e*1e3)});return Promise.race([r,s]).finally(()=>clearTimeout(n))}function m_({name:e,labels:t}){let r=t["com.docker.compose.project"],n=`${t["com.docker.compose.service"]}-${t["com.docker.compose.container-number"]}`;return e===`${r}-${n}`?n:e}function ote(e,t,r){let n=`${e.padEnd(t)} | `;if(!r)return n;let s=0;for(let o of e)s=s*31+o.charCodeAt(0)>>>0;return`${nI[s%nI.length]}${n}${xf}`}function sI(e,t,r){let n=new Vee("utf8"),s="",o=i(a=>{let c=(s+a).split(`
|
|
525
|
+
`);return Buffer.from(t)};dl.decodePax=function(e){for(var t={};e.length;){for(var r=0;r<e.length&&e[r]!==32;)r++;var n=parseInt(e.slice(0,r).toString(),10);if(!n)return t;var s=e.slice(r+1,n-1).toString(),o=s.indexOf("=");if(o===-1)return t;t[s.slice(0,o)]=s.slice(o+1),e=e.slice(n)}return t};dl.encode=function(e){var t=iee(512),r=e.name,n="";if(e.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),Buffer.byteLength(r)!==r.length)return null;for(;Buffer.byteLength(r)>100;){var s=r.indexOf("/");if(s===-1)return null;n+=n?"/"+r.slice(0,s):r.slice(0,s),r=r.slice(s+1)}return Buffer.byteLength(r)>100||Buffer.byteLength(n)>155||e.linkname&&Buffer.byteLength(e.linkname)>100?null:(t.write(r),t.write(hi(e.mode&dee,6),100),t.write(hi(e.uid,6),108),t.write(hi(e.gid,6),116),t.write(hi(e.size,11),124),t.write(hi(e.mtime.getTime()/1e3|0,11),136),t[156]=pN+mee(e.type),e.linkname&&t.write(e.linkname,157),hN.copy(t,Jf),lee.copy(t,n_),e.uname&&t.write(e.uname,265),e.gname&&t.write(e.gname,297),t.write(hi(e.devmajor||0,6),329),t.write(hi(e.devminor||0,6),337),n&&t.write(n,345),t.write(hi(gN(t),6),148),t)};dl.decode=function(e,t,r){var n=e[156]===0?0:e[156]-pN,s=fl(e,0,100,t),o=mi(e,100,8),a=mi(e,108,8),c=mi(e,116,8),l=mi(e,124,12),u=mi(e,136,12),f=hee(n),d=e[157]===0?null:fl(e,157,100,t),p=fl(e,265,32),m=fl(e,297,32),y=mi(e,329,8),g=mi(e,337,8),x=gN(e);if(x===8*32)return null;if(x!==mi(e,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(hN.compare(e,Jf,Jf+6)===0)e[345]&&(s=fl(e,345,155,t)+"/"+s);else if(!(uee.compare(e,Jf,Jf+6)===0&&fee.compare(e,n_,n_+2)===0)){if(!r)throw new Error("Invalid tar header: unknown format.")}return n===0&&s&&s[s.length-1]==="/"&&(n=5),{name:s,mode:o,uid:a,gid:c,size:l,mtime:new Date(1e3*u),type:f,linkname:d,uname:p,gname:m,devmajor:y,devminor:g}}});var _N=$((l6e,kN)=>{h();var yN=te("util"),xee=dN(),Xf=s_(),wN=ul().Writable,bN=ul().PassThrough,vN=i(function(){},"noop"),xN=i(function(e){return e&=511,e&&512-e},"overflow"),yee=i(function(e,t){var r=new R0(e,t);return r.end(),r},"emptyStream"),wee=i(function(e,t){return t.path&&(e.name=t.path),t.linkpath&&(e.linkname=t.linkpath),t.size&&(e.size=parseInt(t.size,10)),e.pax=t,e},"mixinPax"),R0=i(function(e,t){this._parent=e,this.offset=t,bN.call(this,{autoDestroy:!1})},"Source");yN.inherits(R0,bN);R0.prototype.destroy=function(e){this._parent.destroy(e)};var fo=i(function(e){if(!(this instanceof fo))return new fo(e);wN.call(this,e),e=e||{},this._offset=0,this._buffer=xee(),this._missing=0,this._partial=!1,this._onparse=vN,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var t=this,r=t._buffer,n=i(function(){t._continue()},"oncontinue"),s=i(function(p){if(t._locked=!1,p)return t.destroy(p);t._stream||n()},"onunlock"),o=i(function(){t._stream=null;var p=xN(t._header.size);p?t._parse(p,a):t._parse(512,d),t._locked||n()},"onstreamend"),a=i(function(){t._buffer.consume(xN(t._header.size)),t._parse(512,d),n()},"ondrain"),c=i(function(){var p=t._header.size;t._paxGlobal=Xf.decodePax(r.slice(0,p)),r.consume(p),o()},"onpaxglobalheader"),l=i(function(){var p=t._header.size;t._pax=Xf.decodePax(r.slice(0,p)),t._paxGlobal&&(t._pax=Object.assign({},t._paxGlobal,t._pax)),r.consume(p),o()},"onpaxheader"),u=i(function(){var p=t._header.size;this._gnuLongPath=Xf.decodeLongPath(r.slice(0,p),e.filenameEncoding),r.consume(p),o()},"ongnulongpath"),f=i(function(){var p=t._header.size;this._gnuLongLinkPath=Xf.decodeLongPath(r.slice(0,p),e.filenameEncoding),r.consume(p),o()},"ongnulonglinkpath"),d=i(function(){var p=t._offset,m;try{m=t._header=Xf.decode(r.slice(0,512),e.filenameEncoding,e.allowUnknownFormat)}catch(y){t.emit("error",y)}if(r.consume(512),!m){t._parse(512,d),n();return}if(m.type==="gnu-long-path"){t._parse(m.size,u),n();return}if(m.type==="gnu-long-link-path"){t._parse(m.size,f),n();return}if(m.type==="pax-global-header"){t._parse(m.size,c),n();return}if(m.type==="pax-header"){t._parse(m.size,l),n();return}if(t._gnuLongPath&&(m.name=t._gnuLongPath,t._gnuLongPath=null),t._gnuLongLinkPath&&(m.linkname=t._gnuLongLinkPath,t._gnuLongLinkPath=null),t._pax&&(t._header=m=wee(m,t._pax),t._pax=null),t._locked=!0,!m.size||m.type==="directory"){t._parse(512,d),t.emit("entry",m,yee(t,p),s);return}t._stream=new R0(t,p),t.emit("entry",m,t._stream,s),t._parse(m.size,o),n()},"onheader");this._onheader=d,this._parse(512,d)},"Extract");yN.inherits(fo,wN);fo.prototype.destroy=function(e){this._destroyed||(this._destroyed=!0,e&&this.emit("error",e),this.emit("close"),this._stream&&this._stream.emit("close"))};fo.prototype._parse=function(e,t){this._destroyed||(this._offset+=e,this._missing=e,t===this._onheader&&(this._partial=!1),this._onparse=t)};fo.prototype._continue=function(){if(!this._destroyed){var e=this._cb;this._cb=vN,this._overflow?this._write(this._overflow,void 0,e):e()}};fo.prototype._write=function(e,t,r){if(!this._destroyed){var n=this._stream,s=this._buffer,o=this._missing;if(e.length&&(this._partial=!0),e.length<o)return this._missing-=e.length,this._overflow=null,n?n.write(e,r):(s.append(e),r());this._cb=r,this._missing=0;var a=null;e.length>o&&(a=e.slice(o),e=e.slice(0,o)),n?n.end(e):s.append(e),this._overflow=a,this._onparse()}};fo.prototype._final=function(e){if(this._partial)return this.destroy(new Error("Unexpected end of data"));e()};kN.exports=fo});var EN=$((d6e,SN)=>{h();SN.exports=te("fs").constants||te("constants")});var TN=$((h6e,ON)=>{h();ON.exports=$N;function $N(e,t){if(e&&t)return $N(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){r[n]=e[n]}),r;function r(){for(var n=new Array(arguments.length),s=0;s<n.length;s++)n[s]=arguments[s];var o=e.apply(this,n),a=n[n.length-1];return typeof o=="function"&&o!==a&&Object.keys(a).forEach(function(c){o[c]=a[c]}),o}i(r,"wrapper")}i($N,"wrappy")});var i_=$((x6e,o_)=>{h();var RN=TN();o_.exports=RN(A0);o_.exports.strict=RN(AN);A0.proto=A0(function(){Object.defineProperty(Function.prototype,"once",{value:i(function(){return A0(this)},"value"),configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:i(function(){return AN(this)},"value"),configurable:!0})});function A0(e){var t=i(function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))},"f");return t.called=!1,t}i(A0,"once");function AN(e){var t=i(function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},"f"),r=e.name||"Function wrapped with `once`";return t.onceError=r+" shouldn't be called more than once",t.called=!1,t}i(AN,"onceStrict")});var a_=$((b6e,PN)=>{h();var bee=i_(),vee=i(function(){},"noop"),kee=global.Bare?queueMicrotask:process.nextTick.bind(process),_ee=i(function(e){return e.setHeader&&typeof e.abort=="function"},"isRequest"),See=i(function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},"isChildProcess"),CN=i(function(e,t,r){if(typeof t=="function")return CN(e,null,t);t||(t={}),r=bee(r||vee);var n=e._writableState,s=e._readableState,o=t.readable||t.readable!==!1&&e.readable,a=t.writable||t.writable!==!1&&e.writable,c=!1,l=i(function(){e.writable||u()},"onlegacyfinish"),u=i(function(){a=!1,o||r.call(e)},"onfinish"),f=i(function(){o=!1,a||r.call(e)},"onend"),d=i(function(x){r.call(e,x?new Error("exited with error code: "+x):null)},"onexit"),p=i(function(x){r.call(e,x)},"onerror"),m=i(function(){kee(y)},"onclose"),y=i(function(){if(!c){if(o&&!(s&&s.ended&&!s.destroyed))return r.call(e,new Error("premature close"));if(a&&!(n&&n.ended&&!n.destroyed))return r.call(e,new Error("premature close"))}},"onclosenexttick"),g=i(function(){e.req.on("finish",u)},"onrequest");return _ee(e)?(e.on("complete",u),e.on("abort",m),e.req?g():e.on("request",g)):a&&!n&&(e.on("end",l),e.on("close",l)),See(e)&&e.on("exit",d),e.on("end",f),e.on("finish",u),t.error!==!1&&e.on("error",p),e.on("close",m),function(){c=!0,e.removeListener("complete",u),e.removeListener("abort",m),e.removeListener("request",g),e.req&&e.req.removeListener("finish",u),e.removeListener("end",l),e.removeListener("close",l),e.removeListener("finish",u),e.removeListener("exit",d),e.removeListener("end",f),e.removeListener("error",p),e.removeListener("close",m)}},"eos");PN.exports=CN});var DN=$((_6e,jN)=>{h();var pl=EN(),NN=a_(),P0=li(),Eee=Buffer.alloc,IN=ul().Readable,hl=ul().Writable,$ee=te("string_decoder").StringDecoder,C0=s_(),Oee=parseInt("755",8),Tee=parseInt("644",8),LN=Eee(1024),l_=i(function(){},"noop"),c_=i(function(e,t){t&=511,t&&e.push(LN.slice(0,512-t))},"overflow");function Ree(e){switch(e&pl.S_IFMT){case pl.S_IFBLK:return"block-device";case pl.S_IFCHR:return"character-device";case pl.S_IFDIR:return"directory";case pl.S_IFIFO:return"fifo";case pl.S_IFLNK:return"symlink"}return"file"}i(Ree,"modeToType");var N0=i(function(e){hl.call(this),this.written=0,this._to=e,this._destroyed=!1},"Sink");P0(N0,hl);N0.prototype._write=function(e,t,r){if(this.written+=e.length,this._to.push(e))return r();this._to._drain=r};N0.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var I0=i(function(){hl.call(this),this.linkname="",this._decoder=new $ee("utf-8"),this._destroyed=!1},"LinkSink");P0(I0,hl);I0.prototype._write=function(e,t,r){this.linkname+=this._decoder.write(e),r()};I0.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var Qf=i(function(){hl.call(this),this._destroyed=!1},"Void");P0(Qf,hl);Qf.prototype._write=function(e,t,r){r(new Error("No body allowed for this entry"))};Qf.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var Cs=i(function(e){if(!(this instanceof Cs))return new Cs(e);IN.call(this,e),this._drain=l_,this._finalized=!1,this._finalizing=!1,this._destroyed=!1,this._stream=null},"Pack");P0(Cs,IN);Cs.prototype.entry=function(e,t,r){if(this._stream)throw new Error("already piping an entry");if(!(this._finalized||this._destroyed)){typeof t=="function"&&(r=t,t=null),r||(r=l_);var n=this;if((!e.size||e.type==="symlink")&&(e.size=0),e.type||(e.type=Ree(e.mode)),e.mode||(e.mode=e.type==="directory"?Oee:Tee),e.uid||(e.uid=0),e.gid||(e.gid=0),e.mtime||(e.mtime=new Date),typeof t=="string"&&(t=Buffer.from(t)),Buffer.isBuffer(t)){e.size=t.length,this._encode(e);var s=this.push(t);return c_(n,e.size),s?process.nextTick(r):this._drain=r,new Qf}if(e.type==="symlink"&&!e.linkname){var o=new I0;return NN(o,function(c){if(c)return n.destroy(),r(c);e.linkname=o.linkname,n._encode(e),r()}),o}if(this._encode(e),e.type!=="file"&&e.type!=="contiguous-file")return process.nextTick(r),new Qf;var a=new N0(this);return this._stream=a,NN(a,function(c){if(n._stream=null,c)return n.destroy(),r(c);if(a.written!==e.size)return n.destroy(),r(new Error("size mismatch"));c_(n,e.size),n._finalizing&&n.finalize(),r()}),a}};Cs.prototype.finalize=function(){if(this._stream){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(LN),this.push(null))};Cs.prototype.destroy=function(e){this._destroyed||(this._destroyed=!0,e&&this.emit("error",e),this.emit("close"),this._stream&&this._stream.destroy&&this._stream.destroy())};Cs.prototype._encode=function(e){if(!e.pax){var t=C0.encode(e);if(t){this.push(t);return}}this._encodePax(e)};Cs.prototype._encodePax=function(e){var t=C0.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.length,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(C0.encode(r)),this.push(t),c_(this,t.length),r.size=e.size,r.type=e.type,this.push(C0.encode(r))};Cs.prototype._read=function(e){var t=this._drain;this._drain=l_,t()};jN.exports=Cs});var FN=$(u_=>{h();u_.extract=_N();u_.pack=DN()});var qN=$((T6e,BN)=>{h();var Aee=i_(),Cee=a_(),L0;try{L0=te("fs")}catch{}var Zf=i(function(){},"noop"),Pee=typeof process>"u"?!1:/^v?\.0/.test(process.version),j0=i(function(e){return typeof e=="function"},"isFn"),Nee=i(function(e){return!Pee||!L0?!1:(e instanceof(L0.ReadStream||Zf)||e instanceof(L0.WriteStream||Zf))&&j0(e.close)},"isFS"),Iee=i(function(e){return e.setHeader&&j0(e.abort)},"isRequest"),Lee=i(function(e,t,r,n){n=Aee(n);var s=!1;e.on("close",function(){s=!0}),Cee(e,{readable:t,writable:r},function(a){if(a)return n(a);s=!0,n()});var o=!1;return function(a){if(!s&&!o){if(o=!0,Nee(e))return e.close(Zf);if(Iee(e))return e.abort();if(j0(e.destroy))return e.destroy();n(a||new Error("stream was destroyed"))}}},"destroyer"),MN=i(function(e){e()},"call"),jee=i(function(e,t){return e.pipe(t)},"pipe"),Dee=i(function(){var e=Array.prototype.slice.call(arguments),t=j0(e[e.length-1]||Zf)&&e.pop()||Zf;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw new Error("pump requires two streams per minimum");var r,n=e.map(function(s,o){var a=o<e.length-1,c=o>0;return Lee(s,a,c,function(l){r||(r=l),l&&n.forEach(MN),!a&&(n.forEach(MN),t(r))})});return e.reduce(jee)},"pump");BN.exports=Dee});var VN=$((C6e,KN)=>{h();var D0=te("path"),UN=te("fs"),WN=parseInt("0777",8);KN.exports=ml.mkdirp=ml.mkdirP=ml;function ml(e,t,r,n){typeof t=="function"?(r=t,t={}):(!t||typeof t!="object")&&(t={mode:t});var s=t.mode,o=t.fs||UN;s===void 0&&(s=WN&~process.umask()),n||(n=null);var a=r||function(){};e=D0.resolve(e),o.mkdir(e,s,function(c){if(!c)return n=n||e,a(null,n);switch(c.code){case"ENOENT":ml(D0.dirname(e),t,function(l,u){l?a(l,u):ml(e,t,a,u)});break;default:o.stat(e,function(l,u){l||!u.isDirectory()?a(c,n):a(null,n)});break}})}i(ml,"mkdirP");ml.sync=i(function e(t,r,n){(!r||typeof r!="object")&&(r={mode:r});var s=r.mode,o=r.fs||UN;s===void 0&&(s=WN&~process.umask()),n||(n=null),t=D0.resolve(t);try{o.mkdirSync(t,s),n=n||t}catch(c){switch(c.code){case"ENOENT":n=e(D0.dirname(t),r,n),e(t,r,n);break;default:var a;try{a=o.statSync(t)}catch{throw c}if(!a.isDirectory())throw c;break}}return n},"sync")});var eI=$(h_=>{h();var Fee=s8(),GN=FN(),YN=qN(),Mee=VN(),zN=te("fs"),xt=te("path"),Bee=te("os"),ed=Bee.platform()==="win32",td=i(function(){},"noop"),p_=i(function(e){return e},"echo"),f_=ed?function(e){return e.replace(/\\/g,"/").replace(/[:?<>|]/g,"_")}:p_,qee=i(function(e,t,r,n,s,o){for(var a=s||["."],c=0;c<a.length;c++)if(!d_(xt.resolve(r,a[c]),r))throw new Error(a[c]+" is not a valid path");return i(function(u){if(!a.length)return u();var f=a.shift(),d=xt.join(r,f);t.call(e,d,function(p,m){if(p)return u(p);if(!m.isDirectory())return u(null,f,m);e.readdir(d,function(y,g){if(y)return u(y);o&&g.sort();for(var x=0;x<g.length;x++)n(xt.join(r,f,g[x]))||a.push(xt.join(f,g[x]));u(null,f,m)})})},"loop")},"statAll"),JN=i(function(e,t){return function(r){r.name=r.name.split("/").slice(t).join("/");var n=r.linkname;return n&&(r.type==="link"||xt.isAbsolute(n))&&(r.linkname=n.split("/").slice(t).join("/")),e(r)}},"strip");h_.pack=function(e,t){e||(e="."),t||(t={});var r=t.fs||zN,n=t.ignore||t.filter||td,s=t.map||td,o=t.mapStream||p_,a=qee(r,t.dereference?r.stat:r.lstat,e,n,t.entries,t.sort),c=t.strict!==!1,l=typeof t.umask=="number"?~t.umask:~XN(),u=typeof t.dmode=="number"?t.dmode:0,f=typeof t.fmode=="number"?t.fmode:0,d=t.pack||GN.pack(),p=t.finish||td;t.strip&&(s=JN(s,t.strip)),t.readable&&(u|=parseInt(555,8),f|=parseInt(444,8)),t.writable&&(u|=parseInt(333,8),f|=parseInt(222,8));var m=i(function(x,v){r.readlink(xt.join(e,x),function(k,b){if(k)return d.destroy(k);v.linkname=f_(b),d.entry(v,g)})},"onsymlink"),y=i(function(x,v,k){if(x)return d.destroy(x);if(!v)return t.finalize!==!1&&d.finalize(),p(d);if(k.isSocket())return g();var b={name:f_(v),mode:(k.mode|(k.isDirectory()?u:f))&l,mtime:k.mtime,size:k.size,type:"file",uid:k.uid,gid:k.gid};if(k.isDirectory())return b.size=0,b.type="directory",b=s(b)||b,d.entry(b,g);if(k.isSymbolicLink())return b.size=0,b.type="symlink",b=s(b)||b,m(v,b);if(b=s(b)||b,!k.isFile())return c?d.destroy(new Error("unsupported type for "+v)):g();var S=d.entry(b,g);if(S){var E=o(r.createReadStream(xt.join(e,v),{start:0,end:b.size>0?b.size-1:b.size}),b);E.on("error",function(T){S.destroy(T)}),YN(E,S)}},"onstat"),g=i(function(x){if(x)return d.destroy(x);a(y)},"onnextentry");return g(),d};var Uee=i(function(e){return e.length?e[e.length-1]:null},"head"),Wee=i(function(){return process.getuid?process.getuid():-1},"processGetuid"),XN=i(function(){return process.umask?process.umask():0},"processUmask");h_.extract=function(e,t){e||(e="."),t||(t={});var r=t.fs||zN,n=t.ignore||t.filter||td,s=t.map||td,o=t.mapStream||p_,a=t.chown!==!1&&!ed&&Wee()===0,c=t.extract||GN.extract(),l=[],u=new Date,f=typeof t.umask=="number"?~t.umask:~XN(),d=typeof t.dmode=="number"?t.dmode:0,p=typeof t.fmode=="number"?t.fmode:0,m=t.strict!==!1;t.strip&&(s=JN(s,t.strip)),t.readable&&(d|=parseInt(555,8),p|=parseInt(444,8)),t.writable&&(d|=parseInt(333,8),p|=parseInt(222,8));var y=i(function(v,k){for(var b;(b=Uee(l))&&v.slice(0,b[0].length)!==b[0];)l.pop();if(!b)return k();r.utimes(b[0],u,b[1],k)},"utimesParent"),g=i(function(v,k,b){if(t.utimes===!1)return b();if(k.type==="directory")return r.utimes(v,u,k.mtime,b);if(k.type==="symlink")return y(v,b);r.utimes(v,u,k.mtime,function(S){if(S)return b(S);y(v,b)})},"utimes"),x=i(function(v,k,b){var S=k.type==="symlink",E=S?r.lchmod:r.chmod,T=S?r.lchown:r.chown;if(!E)return b();var R=(k.mode|(k.type==="directory"?d:p))&f&parseInt(777,8);T&&a?T.call(r,v,k.uid,k.gid,I):I(null);function I(P){if(P)return b(P);if(!E)return b();E.call(r,v,R,b)}i(I,"onchown")},"chperm");return c.on("entry",function(v,k,b){v=s(v)||v,v.name=f_(v.name);var S=xt.join(e,xt.join("/",v.name));if(n(S,v))return k.resume(),b();var E=i(function(j){if(j)return b(j);if(xt.join(S,".")===xt.join(e,"."))return b();g(S,v,function(M){if(M)return b(M);if(ed)return b();x(S,v,b)})},"stat"),T=i(function(){if(ed)return b();r.unlink(S,function(){var j=xt.resolve(xt.dirname(S),v.linkname);if(!d_(j,e))return b(new Error(S+" is not a valid symlink"));ZN(r,j,xt.resolve(e),function(M,A){if(M)return b(M);if(!A)return b(new Error(S+" is not a valid symlink"));r.symlink(v.linkname,S,E)})})},"onsymlink"),R=i(function(){if(ed)return b();r.unlink(S,function(){var j=xt.join(e,xt.join("/",v.linkname));r.realpath(j,function(M,A){if(M||!d_(A,e))return b(new Error(S+" is not a valid hardlink"));r.link(A,S,function(B){if(B&&B.code==="EPERM"&&t.hardlinkAsFilesFallback)return k=r.createReadStream(j),I();E(B)})})})},"onlink"),I=i(function(){r.lstat(S,function(M,A){if(!M&&A.isSymbolicLink())return r.unlink(S,j);j()});function j(M){if(M)return b(M);var A=r.createWriteStream(S),B=o(k,v);A.on("error",function(W){B.destroy(W)}),YN(B,A,function(W){if(W)return b(W);A.on("close",E)})}i(j,"onwrite")},"onfile");if(v.type==="directory")return l.push([S,v.mtime]),HN(S,{fs:r,own:a,uid:v.uid,gid:v.gid},E);var P=xt.dirname(S);QN(r,P,xt.join(e,"."),function(j,M){if(j)return b(j);if(!M)return b(new Error(P+" is not a valid path"));HN(P,{fs:r,own:a,uid:v.uid,gid:v.gid},function(A){if(A)return b(A);switch(v.type){case"file":return I();case"link":return R();case"symlink":return T()}if(m)return b(new Error("unsupported type for "+S+" ("+v.type+")"));k.resume(),b()})})}),t.finish&&c.on("finish",t.finish),c};function QN(e,t,r,n){if(t===r)return n(null,!0);e.lstat(t,function(s,o){if(s&&s.code!=="ENOENT")return n(s);if(s||o.isDirectory())return QN(e,xt.join(t,".."),r,n);n(null,!1)})}i(QN,"validate");function ZN(e,t,r,n){if(t===r)return n(null,!0);if(!t.startsWith(r+xt.sep))return n(null,!1);e.lstat(t,function(s,o){if(s&&s.code!=="ENOENT"&&s.code!=="EPERM")return n(s);if(s||!o.isSymbolicLink())return ZN(e,xt.join(t,".."),r,n);n(null,!1)})}i(ZN,"validateNotSymlink");function HN(e,t,r){Mee(e,{fs:t.fs},function(n,s){!n&&s&&t.own?Fee(s,t.uid,t.gid,r):r(n)})}i(HN,"mkdirfix");function d_(e,t){return t=xt.resolve(t),t===e||e.startsWith(t+xt.sep)}i(d_,"inCwd")});import{createHash as Kee}from"node:crypto";import{readFileSync as oI}from"node:fs";import*as iI from"node:os";import*as Ps from"node:path";import{PassThrough as tI,Readable as aI}from"node:stream";import{StringDecoder as Vee}from"node:string_decoder";import Hee from"dockerode";function Gee(){return Qee(zee()??Xee()??"")}function zee(){if(process.env.DOCKER_HOST)return process.env.DOCKER_HOST;try{let e=process.env.DOCKER_CONFIG||Ps.join(iI.homedir(),".docker"),t=process.env.DOCKER_CONTEXT||Jee(e);if(t==="default")return Yee;let r=Kee("sha256").update(t).digest("hex"),s=JSON.parse(oI(Ps.join(e,"contexts","meta",r,"meta.json"),"utf8"))?.Endpoints?.docker?.Host;return typeof s=="string"&&s?s:null}catch{return null}}function Jee(e){try{return JSON.parse(oI(Ps.join(e,"config.json"),"utf8"))?.currentContext||"default"}catch{return"default"}}function Xee(){try{let e=H(["docker","context","inspect","--format","{{.Endpoints.docker.Host}}"],{capture:!0,timeout:10});return e.status!==0?null:e.stdout.trim()||null}catch(e){if(e instanceof Z)return null;throw e}}function Qee(e){if(e.startsWith("unix://"))return{socketPath:e.slice(7)};if(/^(tcp|http|https):\/\//.test(e)){let t=new URL(e),r=t.protocol==="https:";return{host:t.hostname,port:Number(t.port)||(r?2376:2375),protocol:r?"https":"http"}}return{socketPath:"/var/run/docker.sock"}}function lt(){return Zee??=new Hee(Gee())}async function Mt(e,t,{all:r=!0}={}){let n=[e?`com.docker.compose.project=${e}`:"com.docker.compose.project","com.docker.compose.oneoff=False",...t?[`com.docker.compose.service=${t}`]:[]];try{return(await rd(10,"docker ps",lt().listContainers({all:r,filters:{label:n}}))).map(ete).sort((o,a)=>o.name<a.name?-1:o.name>a.name?1:0)}catch{return null}}function ete(e){let t=e.Labels??{},r=e.Status??"";return{name:e.Names?.[0]?.replace(/^\//,"")??e.Id.slice(0,12),state:e.State??"",health:tte(r),ports:rte(e.Ports??[]),service:t["com.docker.compose.service"]??"",labels:t,exitCode:Number(/^\s*Exited \((\d+)\)/.exec(r)?.[1]??0)}}function tte(e){let t=/\((healthy|unhealthy|health: starting)\)/.exec(e);return t?t[1]==="health: starting"?"starting":t[1]:""}function rte(e){let t=i((a,c)=>a<c?-1:a>c?1:0,"cmp"),r=[...e].sort((a,c)=>a.PrivatePort-c.PrivatePort||t(a.IP??"",c.IP??"")||(a.PublicPort??0)-(c.PublicPort??0)||t(a.Type,c.Type)),n=new Map,s=[],o=[];for(let a of r){let c=a.PrivatePort;if(a.IP&&a.PublicPort!==c){o.push(`${lI(a.IP,String(a.PublicPort))}->${c}/${a.Type}`);continue}let l=a.IP?`${a.IP}/${a.Type}`:a.Type,u=n.get(l);if(u&&c===u.last+1){u.last=c;continue}u&&s.push(rI(l,u)),n.set(l,{first:c,last:c})}for(let[a,c]of n)s.push(rI(a,c));return[...s,...o].join(", ")}function rI(e,{first:t,last:r}){let[n,s]=e.includes("/")?e.split("/"):["",e],o=t===r?`${t}`:`${t}-${r}`;return n?`${lI(n,o)}->${o}/${s}`:`${o}/${s}`}function lI(e,t){return e.includes(":")?`[${e}]:${t}`:`${e}:${t}`}async function F0(e){try{return(await lt().getContainer(e).inspect()).State.Running===!0}catch{return!1}}function nte(e){let t=e.cpu_stats.cpu_usage.total_usage-e.precpu_stats.cpu_usage.total_usage,r=e.cpu_stats.system_cpu_usage-e.precpu_stats.system_cpu_usage;if(t<=0||r<=0)return 0;let n=e.cpu_stats.online_cpus||e.cpu_stats.cpu_usage.percpu_usage?.length||1;return t/r*n*100}function ste(e){let t=e.memory_stats.stats??{},r=t.inactive_file??t.total_inactive_file??t.cache??0;return((e.memory_stats.usage??0)-r)/uI}async function gl(e){let t;try{t=await lt().listContainers({abortSignal:e})}catch{return[]}let r={stream:!1,abortSignal:e};return(await Promise.all(t.map(async s=>{try{let o=await lt().getContainer(s.Id).stats(r);return{name:s.Names[0]?.replace(/^\//,"")??s.Id.slice(0,12),cpuPercent:nte(o),memMib:ste(o),memLimitMib:(o.memory_stats.limit??0)/uI,labels:s.Labels??{}}}catch{return null}}))).filter(s=>s!==null)}async function fI(e){let t=await Promise.all(e.map(async r=>{try{let n=await rd(10,"docker inspect",lt().getContainer(r).inspect()),s={startedAt:Date.parse(n.State.StartedAt),restartCount:n.RestartCount??0,tty:n.Config.Tty};return[r,s]}catch{return null}}));return new Map(t.filter(r=>r!==null))}async function dI(e,t){try{let r=await rd(10,"docker logs",lt().getContainer(e).logs({stdout:!0,stderr:!0,tail:1,follow:!1})),n=null;return await pI(aI.from([r]),t,"",s=>{s.trim()&&(n=s.trim().slice(0,200))}),n}catch{return null}}function rd(e,t,r){let n,s=new Promise((o,a)=>{n=setTimeout(()=>a(new Error(`${t} timed out after ${e} seconds`)),e*1e3)});return Promise.race([r,s]).finally(()=>clearTimeout(n))}function m_({name:e,labels:t}){let r=t["com.docker.compose.project"],n=`${t["com.docker.compose.service"]}-${t["com.docker.compose.container-number"]}`;return e===`${r}-${n}`?n:e}function ote(e,t,r){let n=`${e.padEnd(t)} | `;if(!r)return n;let s=0;for(let o of e)s=s*31+o.charCodeAt(0)>>>0;return`${nI[s%nI.length]}${n}${xf}`}function sI(e,t,r){let n=new Vee("utf8"),s="",o=i(a=>{let c=(s+a).split(`
|
|
526
526
|
`);s=c.pop()??"";for(let l of c)r(e+l.replace(/\r$/,""),t)},"emit");return{write:i(a=>(o(n.write(a)),!0),"write"),flush:i(()=>{o(n.end()),s&&r(e+s,t),s=""},"flush")}}function pI(e,t,r,n){let s=sI(r,"stdout",n),o=sI(r,"stderr",n);return t?e.on("data",s.write):lt().modem.demuxStream(e,s,o),new Promise(a=>{let c=!1,l=i(()=>{c||(c=!0,s.flush(),o.flush(),a())},"end");e.once("end",l),e.once("close",l),e.once("error",l)})}async function hI(e,t,{follow:r,tail:n,signal:s,color:o},a){let c=[`com.docker.compose.project=${e}`,"com.docker.compose.oneoff=False",...t?[`com.docker.compose.service=${t}`]:[]],l=r?await lt().getEvents({filters:{type:["container"],event:["start"],label:c},abortSignal:s}).catch(()=>null):null,u=await Mt(e,t??void 0);if(u===null||u.length===0){l?.removeAllListeners(),l?.destroy(),a(u===null?"cannot reach the docker daemon":t?`no such service: ${t}`:`no containers for project ${e}`,"stderr");return}let f=Math.max(...u.map(y=>m_(y).length)),d=new Set,p=new Set,m=i((y,g,x)=>{if(d.has(y)||s?.aborted)return;d.add(y),f=Math.max(f,g.length);let v=(async()=>{let k=lt().getContainer(y),{Config:b}=await k.inspect(),E={stdout:!0,stderr:!0,...x===void 0?{tail:n}:{since:x},abortSignal:s},T=r?await k.logs({...E,follow:!0}):aI.from([await k.logs({...E,follow:!1})]);await pI(T,b.Tty,ote(g,f,o),a)})().catch(()=>{}).finally(()=>{d.delete(y),p.delete(v)});p.add(v)},"attach");for(let y of u)m(y.name,m_(y));if(r){let y="";l?.on("data",g=>{let x=(y+g.toString()).split(`
|
|
527
527
|
`);y=x.pop()??"";for(let v of x){if(!v.trim())continue;let k=JSON.parse(v),b=k.Actor?.Attributes??{};m(b.name,m_({name:b.name,labels:b}),k.time)}}),l?.on("error",()=>{}),s?.aborted||await new Promise(g=>s?.addEventListener("abort",()=>g(),{once:!0}))}for(;p.size>0;)await Promise.all(p)}async function mI(e,t,r){let n=cI.pack(Ps.dirname(t),{entries:[Ps.basename(t)],map:i(s=>({...s,name:Ps.basename(r)}),"map")});await rd(30,"docker cp",lt().getContainer(e).putArchive(n,{path:Ps.dirname(r)}))}async function g_(e,t){return rd(30,t.slice(0,2).join(" "),(async()=>{let r=await lt().getContainer(e).exec({Cmd:t,AttachStdout:!0,AttachStderr:!0}),n=await r.start({}),s=[],o=[],a=new tI().on("data",u=>s.push(u)),c=new tI().on("data",u=>o.push(u));lt().modem.demuxStream(n,a,c),await new Promise((u,f)=>{n.on("end",u),n.on("error",f)});let{ExitCode:l}=await r.inspect();return{exitCode:l??-1,stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(o).toString("utf8")}})())}async function gI(){try{let{Volumes:e}=await lt().listVolumes();return(e??[]).map(t=>t.Name)}catch{return null}}async function xI(){try{let{Volumes:e}=await lt().df();return new Map((e??[]).map(t=>[t.Name,{size:t.UsageData?.Size??-1,createdAt:t.CreatedAt}]))}catch{return null}}async function yI(e){try{return(await lt().listContainers({filters:{status:["running"]}})).filter(r=>(r.Mounts??[]).some(n=>n.Name===e||n.Source===e)).map(r=>(r.Names[0]??r.Id).replace(/^\//,""))}catch{return null}}async function wI(e){try{return await lt().getVolume(e).remove(),!0}catch{return!1}}var cI,Yee,Zee,uI,nI,Mr=C(()=>{"use strict";h();cI=Re(eI(),1);bs();mt();i(Gee,"resolveEndpoint");Yee="unix:///var/run/docker.sock";i(zee,"storeContextHost");i(Jee,"currentContextName");i(Xee,"cliContextHost");i(Qee,"endpointOptions");Zee=null;i(lt,"docker");i(Mt,"projectContainers");i(ete,"containerRecord");i(tte,"parseHealth");i(rte,"displayPorts");i(rI,"portGroup");i(lI,"hostPort");i(F0,"containerRunning");uI=1024*1024;i(nte,"cpuPercent");i(ste,"memMib");i(gl,"containerStats");i(fI,"containerRuntime");i(dI,"lastLogLine");i(rd,"withTimeout");i(m_,"logName");nI=[gf,mf,hf,Ov,$v];i(ote,"logPrefix");i(sI,"lineSink");i(pI,"pipeLogLines");i(hI,"containerLogs");i(mI,"copyFileToContainer");i(g_,"execCapture");i(gI,"listVolumeNames");i(xI,"volumeUsage");i(yI,"runningContainersMounting");i(wI,"removeVolume")});import*as Jr from"node:fs";import*as bI from"node:os";import*as x_ from"node:path";function cte(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e*1e3)}function lte(e){let t;try{t=Number.parseInt(Jr.readFileSync(e,"utf8").trim(),10)}catch{return!1}if(!Number.isInteger(t)||t<=0)return!0;try{return process.kill(t,0),!1}catch(r){return r.code==="ESRCH"}}function ute(e){try{let t=Jr.openSync(e,"wx");return Jr.writeSync(t,String(process.pid)),Jr.closeSync(t),!0}catch(t){if(t.code==="EEXIST"){if(lte(e))try{Jr.unlinkSync(e)}catch{}return!1}throw t}}function M0(e,t,{timeout:r}={}){let n=ite();Jr.mkdirSync(n,{recursive:!0});let s=x_.join(n,`${e}.lock`),o=r!==void 0?performance.now()+r*1e3:null;for(;!ute(s);){if(o!==null&&performance.now()>=o)throw new Error(`Timed out after ${r}s waiting for lock '${e}' (${s}). The previous holder may have crashed without releasing it; if no werkmeister process is running, it is safe to delete this file and retry.`);cte(ate)}let a=i(()=>{try{Jr.unlinkSync(s)}catch{}},"release"),c;try{c=t()}catch(l){throw a(),l}return c instanceof Promise?c.finally(a):(a(),c)}var ite,ate,y_=C(()=>{"use strict";h();Q();ite=i(()=>x_.join(K(bI.homedir()),"locks"),"lockDir"),ate=.1;i(cte,"sleepSync");i(lte,"holderIsDead");i(ute,"tryAcquire");i(M0,"sandboxLock")});var EI={};pe(EI,{LABEL_FEATURE:()=>Ea,LABEL_PREFIX:()=>w_,LEGACY_LABEL_FEATURE:()=>$a,LEGACY_LABEL_PREFIX:()=>b_,allocateSlot:()=>nd,classifyEndpoint:()=>SI,featureServices:()=>v_,getAllSlots:()=>Bt,getAllSlotsFromDocker:()=>B0,getPortRange:()=>Xr,getServicePort:()=>Qr,getSlot:()=>tr,labelOf:()=>Br,migrateSlotsJson:()=>gte,releaseSlot:()=>_I,slotCount:()=>yl});import*as xl from"node:fs";import*as vI from"node:os";import*as kI from"node:path";function Br(e,t){return e?.[`${w_}.${t}`]??e?.[`${b_}.${t}`]??""}async function pte(){let e;try{let t=await Promise.all([Ea,$a].map(n=>lt().listContainers({all:!0,filters:{label:[n]},abortSignal:AbortSignal.timeout(dte)}))),r=new Set;e=t.flat().filter(n=>!r.has(n.Names[0])&&r.add(n.Names[0]))}catch{return null}return e.map(t=>({name:(t.Names[0]??"").replace(/^\//,""),feature:Br(t.Labels,"feature"),slot:Br(t.Labels,"slot"),service:Br(t.Labels,"service")}))}function yl(){let e=Hn().feature_slots;return(typeof e=="object"&&e!==null&&!Array.isArray(e)?e.count:void 0)??12}function hte(){let e=de();if(typeof e!="object"||e===null)return new Set;let t=new Set;for(let[r,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&n.port_offset!==null&&n.port_offset!==void 0&&t.add(r);return t}async function B0(){let e=await pte();if(e===null)return null;let t=hte(),r={};for(let n of e){let s=n.feature,o=Number.parseInt(n.slot,10);if(Number.isNaN(o)){N(`Container '${n.name}' has unparseable slot label: '${n.slot}'`);continue}let a=n.service,c=r[s];c||(c={slot:o,services:[]},r[s]=c),c.slot!==o&&(N(`Feature '${s}' has inconsistent slot labels across containers (saw ${c.slot} and ${o}) -- using ${o}`),c.slot=o),a&&t.has(a)&&!c.services.includes(a)&&c.services.push(a)}return r}function mte(e){return!e||Object.keys(e).length===0?new Set:new Set(Object.values(e).map(t=>t.slot))}async function nd(e,t,r){let n=yl();return M0("allocate",async()=>{let s=await B0(),o=s?.[e];if(o)return o.slot;let a=mte(s);if(r!=null&&r>=1&&r<=n&&!a.has(r))return D(`Allocated slot ${r} for '${e}'`),r;for(let c=1;c<=n;c++)if(!a.has(c))return D(`Allocated slot ${c} for '${e}'`),c;throw L(`All ${n} feature slots are occupied!`),new Error("No available slots. Stop an existing feature with 'werkmeister down <feature>' first.")},{timeout:fte})}function _I(e){}async function tr(e){let t=(await Bt())[e];return t?t.slot:null}async function Bt(){let e=await B0();return e===null?{}:e}function Xr(e){return ym(e,Hn())}function Qr(e,t){let[r]=Xr(e);return r+t}function SI(e,t,r,n){let s=t.type??"unknown";if(r.includes(e)){let c=t.port_offset??0;return{service:e,source:"local",endpoint:`localhost:${Qr(n,c)}`,type:s}}let o=Jo(e,t);if(o)return{service:e,source:"baseline",endpoint:`${o.host}:${o.port}`,type:s};let a=t.k8s_forward_port;return a?{service:e,source:"k8s",endpoint:`localhost:${a}`,type:s}:{service:e,source:"none",endpoint:null,type:s}}async function v_(e){let t=await tr(e);if(t===null)throw new z(`Feature '${e}' is not running (no slot allocated)`,"NOT_RUNNING");let r=(await Bt())[e]?.services??[],n=de(),s=[];for(let o of Object.keys(n).sort()){let a=n[o]??{};typeof a!="object"||a===null||Array.isArray(a)||s.push(SI(o,a,r,t))}return{feature:e,slot:t,endpoints:s}}async function gte(){let e=kI.join(K(vI.homedir()),"slots.json");if(!xl.existsSync(e))return;let t;try{let s=JSON.parse(xl.readFileSync(e,"utf8"));t=typeof s=="object"&&s!==null?s:{}}catch{t={}}let r=await B0()??{},n=Object.keys(t).filter(s=>typeof t[s]=="object"&&t[s]!==null&&!Array.isArray(t[s])&&!(s in r));n.length>0&&(N(`~/.werkmeister/slots.json had features with no labeled containers: ${n.join(", ")}`),N("These are now forgotten \u2014 restart them with 'werkmeister up' to re-register.")),O("Migrating: removing legacy ~/.werkmeister/slots.json (labels are now authoritative)");try{xl.unlinkSync(e)}catch(s){N(`Could not remove ${e}: ${s}`)}}var w_,Ea,b_,$a,fte,dte,It=C(()=>{"use strict";h();Q();Mr();Qt();y_();Fe();w_="com.werkmeister",Ea=`${w_}.feature`,b_="com.sandbox.local",$a=`${b_}.feature`;i(Br,"labelOf");fte=30,dte=1e4;i(pte,"queryLabeledContainers");i(yl,"slotCount");i(hte,"routableServiceNames");i(B0,"getAllSlotsFromDocker");i(mte,"takenSlots");i(nd,"allocateSlot");i(_I,"releaseSlot");i(tr,"getSlot");i(Bt,"getAllSlots");i(Xr,"getPortRange");i(Qr,"getServicePort");i(SI,"classifyEndpoint");i(v_,"featureServices");i(gte,"migrateSlotsJson")});import*as $I from"node:fs";import*as OI from"node:path";function xte(e){try{let t=Kt(),r=br(void 0,t),n=e.find(o=>r[o]?.hostname),s=n?r[n].hostname:Object.values(r).map(o=>o.hostname).filter(Boolean).sort()[0];return s?{host:s,domain:t.local_domain.replace(/^\.+/,"")}:null}catch{return null}}function k_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yte(e,t,r){let n=[];for(let[s]of e){let o=!1;try{o=$I.statSync(OI.join(t,s,"CLAUDE.md")).isFile()}catch{}o&&n.push(`| Working in ${s} | ${s}/CLAUDE.md |`)}return r&&n.push("| Running or validating the change \u2014 test commands, how to validate, ports, lifecycle | .werkmeister/werkmeister-context.md |"),e.length>1&&n.push("| Cross-repo contract change | .werkmeister/notes/ (`contract` notes) |"),n.push("| Open or create a PR (including `/create-pr`), merge, close out | .werkmeister/pr-rules.md |"),n.length===0?"":`| Task | Read |
|
|
528
528
|
|------|------|
|
|
@@ -563,7 +563,7 @@ Load only what the routing table points to for your current task. Target: \u2264
|
|
|
563
563
|
Working notes live in [.werkmeister/notes/](.werkmeister/notes/) \u2014 \`NNN-<type>-<slug>.md\`. Types and rules: docs/notes-conventions.md in the werkmeister repo.
|
|
564
564
|
|
|
565
565
|
Read relevant notes first; skip \`status: superseded\`. \`decision\` notes are binding and override task-level instincts \u2014 on conflict, raise it to the user rather than picking a side.
|
|
566
|
-
${d>1?"\nRecord contract changes (API schema, shared types, event contracts) as `contract` notes **before** switching repos; read them when entering the receiving repo.\n":""}`,g=a?null:
|
|
566
|
+
${d>1?"\nRecord contract changes (API schema, shared types, event contracts) as `contract` notes **before** switching repos; read them when entering the receiving repo.\n":""}`,g=a?null:aP(s),x=g?g[1]?`${n} \u2014 [${g[0]}](${g[1]})`:`${n} \u2014 ${g[0]}`:n,v=(s.DESCRIPTION??"").trim(),b=`## Current Task
|
|
567
567
|
|
|
568
568
|
${x}
|
|
569
569
|
|
|
@@ -701,7 +701,7 @@ ${s}
|
|
|
701
701
|
`}function Lte(e,t,r){let n=e.map(l=>MI("Open decision",l,t)),s=i(l=>{if(l===0)return"";let u=e.slice(0,l).map(p=>po.basename(p.path)),f=u.slice(-Ite),d=u.length-f.length;return`\u2500\u2500 ${l} older open decision note(s) not shown (context budget) \u2014 read them in .werkmeister/notes/: ${f.join(", ")}${d?` (and ${d} older)`:""} \u2500\u2500
|
|
702
702
|
`},"elision"),o=n.length,a=0;for(;o>0&&a+n[o-1].length+s(o-1).length<=r;)a+=n[o-1].length,o-=1;let c=n.slice(o);return o>0&&c.push(s(o)),c}function jte(e,t){let r;t==="compact"?r="You loaded these standards earlier this session; compaction dropped the full rules. Re-invoke each skill to reload them before editing matching files again.":r="Files changed on this branch match these standards. Invoke each skill before editing matching files.";let n=["\u2500\u2500 Active standards (files changed on this branch match these) \u2500\u2500",r+" These standards' rules win over conflicting task framing \u2014 if a rule and the task clash, follow the rule and say so (invariant: apply it and write a `decision` note; rule: surface the conflict in one line, then apply)."];for(let[s,o]of e){let a=`- \`${ma(s)}\``;o&&(a+=` \u2014 ${o}`),n.push(a)}return n.join(`
|
|
703
703
|
`)+`
|
|
704
|
-
`}function BI(e,t=""){U0(e);let r=R_(e),n=od(e),s=
|
|
704
|
+
`}function BI(e,t=""){U0(e);let r=R_(e),n=od(e),s=RP(e);if(r===null&&!n.length&&!s.length)return"";let o=[];if(s.length&&o.push(jte(s,t)),r!==null||n.length){o.push("Workspace notes exist in .werkmeister/notes/ \u2014 working state that survives sessions and compaction. `decision` notes are binding: they override task-level instincts; if one conflicts with the task as given, raise it to the user. Read relevant `finding`/`attempt` notes before re-researching or re-trying an approach.\n"),r!==null&&o.push(MI("Latest handoff",r,e));let a=o.join(`
|
|
705
705
|
`).length;o.push(...Lte(n,e,Nte-a))}return o.join(`
|
|
706
706
|
`)}var DI,$_,FI,jI,Nte,Ite,bl=C(()=>{"use strict";h();DI=Re(rt(),1);Q();Oa();jf();zn();$_=["finding","decision","attempt","handoff","contract"],FI=new RegExp("^(?<number>\\d{3})-(?<type>"+$_.join("|")+")-(?<slug>[a-z0-9][a-z0-9-]*)\\.md$");i(sd,"notesDir");i(O_,"nextNoteNumber");i(T_,"noteFilename");i(Cte,"_split3");i(Pte,"parseNote");i(wl,"listNotes");i(R_,"latestHandoff");i(od,"openDecisions");jI=3500,Nte=9e3,Ite=20;i(MI,"renderNote");i(Lte,"renderDecisions");i(jte,"renderActiveStandards");i(BI,"buildContext")});import*as Ut from"node:fs";import*as en from"node:path";function qI(e,t){try{Ut.accessSync(Ut.existsSync(e)?e:en.dirname(e),Ut.constants.W_OK)}catch{throw new qt(`cannot write ${e} \u2014 graduation scaffolds into the standards tree (${t}), so \`overrides.standards_dir\` must name one you can write`)}}function A_(e,t,r,n=null){if(!e.includes(t)){if(n===null)throw new qt(`STANDARD.md has no '${t}' section`);return e.replace(/\n+$/,"")+`
|
|
707
707
|
|
|
@@ -742,7 +742,7 @@ ${m}
|
|
|
742
742
|
`);let S=`- Don't TODO(graduate) \u2014 [references/${v}](references/${v})`;d=A_(d,"## Don't",S)}let b=`| TODO(graduate) | [references/${v}](references/${v}) |`;d=A_(d,"## Going deeper",b,Fte),Ut.writeFileSync(f,d)}let g=en.relative(o,y);return a.mark(e,t,{status:"graduating",graduated_to:g}),{standard_path:f,scaffold_path:y,note_path:t.path,graduated_to:g}}var W0,Dte,vl,Fte,qt,K0,Oa=C(()=>{"use strict";h();W0=Re(rt(),1);Q();Qt();Xe();bl();mt();zn();Dte=5,vl=["rule","example","anti-pattern"],Fte=`## Going deeper
|
|
743
743
|
| When you're doing | Read |
|
|
744
744
|
|---|---|
|
|
745
|
-
`,qt=class extends z{static{i(this,"GraduationError")}constructor(t){super(t,"GRADUATION"),this.name="GraduationError"}};i(qI,"requireWritable");i(A_,"insertAtSectionEnd");i(C_,"eligibleDomains");i(UI,"matchDomainsForRefs");i(P_,"updateNoteStatus");K0={open:i(e=>od(e),"open"),mark:i((e,t,r)=>P_(t.path,r),"mark"),cite:i((e,t)=>`note ${String(t.number).padStart(3,"0")}, see ${en.basename(K(e))}/notes/${en.basename(t.path)}`,"cite")};i(U0,"reconcileGraduating");i(WI,"graduateNote")});import*as et from"node:fs";import*as Tt from"node:path";function Mte(){return Tt.join(na(),"skills")}function kl(e){return et.existsSync(e)&&et.statSync(e).isDirectory()}function VI(e){let t=[],r=i(n=>{for(let s of et.readdirSync(n,{withFileTypes:!0})){let o=Tt.join(n,s.name);s.isDirectory()?r(o):s.name.endsWith(".md")&&t.push(o)}},"walk");return r(e),t.sort()}function HI(e,t,r){let n={};try{let o=r?new Set(r.map(ma)):null;for(let[a,c]of Object.entries(
|
|
745
|
+
`,qt=class extends z{static{i(this,"GraduationError")}constructor(t){super(t,"GRADUATION"),this.name="GraduationError"}};i(qI,"requireWritable");i(A_,"insertAtSectionEnd");i(C_,"eligibleDomains");i(UI,"matchDomainsForRefs");i(P_,"updateNoteStatus");K0={open:i(e=>od(e),"open"),mark:i((e,t,r)=>P_(t.path,r),"mark"),cite:i((e,t)=>`note ${String(t.number).padStart(3,"0")}, see ${en.basename(K(e))}/notes/${en.basename(t.path)}`,"cite")};i(U0,"reconcileGraduating");i(WI,"graduateNote")});import*as et from"node:fs";import*as Tt from"node:path";function Mte(){return Tt.join(na(),"skills")}function kl(e){return et.existsSync(e)&&et.statSync(e).isDirectory()}function VI(e){let t=[],r=i(n=>{for(let s of et.readdirSync(n,{withFileTypes:!0})){let o=Tt.join(n,s.name);s.isDirectory()?r(o):s.name.endsWith(".md")&&t.push(o)}},"walk");return r(e),t.sort()}function HI(e,t,r){let n={};try{let o=r?new Set(r.map(ma)):null;for(let[a,c]of Object.entries(OP(e)))(!o||o.has(a))&&(n[a]=c)}catch{}let s=t??Mte();if(kl(s)){let o=et.readdirSync(s,{withFileTypes:!0}).filter(a=>a.isDirectory()&&et.existsSync(Tt.join(s,a.name,"SKILL.md"))).map(a=>a.name).sort();for(let a of o)try{n[a]={"SKILL.md":et.readFileSync(Tt.join(s,a,"SKILL.md"),"utf8")}}catch{continue}}return n}function N_(e){return Tt.join(e,".claude","skills")}function I_(e,t,r,n){let s=HI(t,r,n),o=N_(e),a=[];for(let c of Object.keys(s).sort()){let l=s[c];for(let u of Object.keys(l).sort()){let f=l[u],d=Tt.join(o,c,u);et.mkdirSync(Tt.dirname(d),{recursive:!0}),(!et.existsSync(d)||et.readFileSync(d,"utf8")!==f)&&et.writeFileSync(d,f),a.push(d)}}if(kl(o))for(let c of et.readdirSync(o).sort()){let l=Tt.join(o,c);if(!(kl(l)&&KI.some(d=>c.startsWith(d))))continue;if(!(c in s)){et.rmSync(l,{recursive:!0,force:!0});continue}let u=s[c];for(let d of VI(l))Tt.relative(l,d).split(Tt.sep).join("/")in u||et.unlinkSync(d);let f=Tt.join(l,"references");kl(f)&&et.readdirSync(f).length===0&&et.rmdirSync(f)}return a}function Bte(e,t,r,n){let s=HI(t,r,n),o=N_(e),a=[];for(let c of Object.keys(s).sort()){let l=s[c];for(let u of Object.keys(l).sort()){let f=l[u],d=Tt.join(o,c,u);et.existsSync(d)&&et.statSync(d).isFile()?et.readFileSync(d,"utf8")!==f&&a.push(`stale: ${c}/${u}`):a.push(`missing: ${c}/${u}`)}}if(kl(o))for(let c of et.readdirSync(o).sort()){let l=Tt.join(o,c);if(kl(l)&&KI.some(u=>c.startsWith(u))){if(!(c in s)){a.push(`orphaned: ${c}`);continue}for(let u of VI(l)){let f=Tt.relative(l,u).split(Tt.sep).join("/");f in s[c]||a.push(`orphaned: ${c}/${f}`)}}}return a}function V0(e){if(Array.isArray(e))return e.map(V0);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=V0(e[r]);return t}return e}function id(e){let t=cr();if(!Object.keys(t).length)return null;let r=xa(e).map(l=>Tt.basename(l)),[n,s]=zr(),o=$t(e,null),a=o.services||[];typeof a=="string"&&(a=a.split(",").map(l=>l.trim()).filter(l=>l));let[c]=ol(r,n,s,o,t,a);return{active:c,modules:t,workType:String(o.work_type??"")}}function GI(e,t=id(e)){if(t===null)return null;let n=(q0(e)?.phase_gate??null)!==null?da(t.workType).gate:null;return i0(t.active,t.modules,n)}function YI(e,t=null){return{authoring:o0(),drift:Bte(e,null,null,t)}}function zI(e,t=id(e)){let r=GI(e,t);if(r===null)return null;let n=q0(e);return JSON.stringify(V0(n))===JSON.stringify(V0(r))?null:"stale: .werkmeister/standards.json"}function JI(e){let t=id(e),r=I_(e,null,null,t?.active??null);for(let o of r)O(`wrote ${o}`);D(`Projected ${r.length} w9r-* skill(s) into ${N_(e)}`);let n=GI(e,t);if(n===null)return{written:r,manifestPath:null};let s=a0(e,n);return O(`wrote ${s}`),{written:r,manifestPath:s}}var KI,XI=C(()=>{"use strict";h();Q();xi();Fe();jf();zn();wr();KI=["w9r-","sb-"];i(Mte,"skillsSourceDir");i(kl,"isDir");i(VI,"rglobMd");i(HI,"renderWorkspaceSkills");i(N_,"workspaceSkillsDir");i(I_,"writeWorkspaceSkills");i(Bte,"checkWorkspaceSkills");i(V0,"canonical");i(id,"resolveWorkspaceActive");i(GI,"resolveWorkspaceManifest");i(YI,"checkSkills");i(zI,"checkStandardsManifest");i(JI,"syncSkills")});import*as rr from"node:fs";import*as tn from"node:path";function Ute(e,t){if(rr.existsSync(t))try{let r=rr.readFileSync(t,"utf8"),n=/^## Handoff Notes\n(?<body>[\s\S]*?)(?=^## |$(?![\s\S]))/m.exec(r);if(!n)return;let s=(n.groups?.body??"").trim();if(!s||s.includes(qte))return;let o=sd(e);rr.mkdirSync(o,{recursive:!0});let a=T_(O_(o),"contract","migrated-handoff-notes");rr.writeFileSync(tn.join(o,a),`---
|
|
746
746
|
type: contract
|
|
747
747
|
phase: implement
|
|
748
748
|
author: main
|
|
@@ -755,7 +755,7 @@ Salvaged from the legacy CLAUDE.md \`## Handoff Notes\` section on regen.
|
|
|
755
755
|
${s}
|
|
756
756
|
`),D(`Salvaged legacy Handoff Notes \u2192 ${tn.relative(e,tn.join(o,a))}`)}catch(r){N(`Could not salvage legacy Handoff Notes: ${r.message}`)}}function Wte(e){return e.type==="handoff"&&e.frontmatter.author==="workspace-creation"&&!e.body.includes("Seeded from `starting_prompt`")}function Kte(e){let t=rr.readFileSync(e.path,"utf8");rr.writeFileSync(e.path,t.replace(/^status:.*$/m,"status: superseded"))}function Vte(e,t,r,n=null){let s=t.trim();if(!s&&!n)return;let o=r.trim().toLowerCase(),a=da(o);try{let c=sd(e),l=wl(e,!0).filter(d=>d.type==="handoff");if(l.some(d=>!Wte(d)))return;for(let d of l)Kte(d);rr.mkdirSync(c,{recursive:!0});let u=T_(O_(c),"handoff","starting-prompt"),f=["---","type: handoff",`phase: ${a.phases[0]}`,"author: workspace-creation","refs: []","status: open","---","","# Handoff: workspace creation",""];n&&f.push(ya(n)),o&&f.push(`This workspace is a ${o} \u2014 ${a.hint}.`,""),s&&f.push("Seeded from `starting_prompt` in .werkmeister/workspace.yml when the","workspace was created. The task below has not begun \u2014 confirm","direction with the user before executing it.","",s),rr.writeFileSync(tn.join(c,u),f.join(`
|
|
757
757
|
`)+`
|
|
758
|
-
`),D(`Seeded starting handoff \u2192 ${tn.relative(e,tn.join(c,u))}`)}catch(c){N(`Could not seed starting handoff: ${c.message}`)}}function Hte(e){let{workspaceRoot:t,workspaceName:r,repos:n,task:s,meta:o,inputs:a,configOverride:c}=e,l=tn.join(t,"CLAUDE.md"),u=null,f=null,d=cr();if(Object.keys(d).length){let[R,I]=zr();for(let B of dk(R,d))N(B);let P=$t(t,c),j=n.map(([B])=>B),M=(o.SERVICES??"").split(",").map(B=>B.trim()).filter(B=>B),[A]=ol(j,R,I,P,d,M);f=A,u=TI(A,d,j,a.work_type??""),O(`Standards routing: active = ${A.join(", ")}`),a0(t,i0(A,d,da(a.work_type??"").gate))}else N(oa()||`no standard modules found in ${gt()} \u2014 this workspace gets no standards routing, skills, or edit-time gate`);rr.mkdirSync(sd(t),{recursive:!0}),Ute(t,l);let p=a.starting_prompt??"";Vte(t,p,a.work_type??"",e.isCreate||p.trim()?e.issue??null:null);let m=RI(r,t,n,s,o,u,e.issue??null);rr.writeFileSync(l,m),D(`Wrote ${l}`);let y=tn.join(K(t),"issues-report.md");rr.mkdirSync(tn.dirname(y),{recursive:!0}),rr.writeFileSync(y,e0(r,ni(o),we({project:a.project,text:ni(o)}))),D(`Wrote ${y}`);let g=tn.join(K(t),"pr-rules.md");rr.writeFileSync(g,t0(".werkmeister/notes/")),D(`Wrote ${g}`);for(let R of I_(t,null,null,f))D(`Wrote ${R}`);let[x,v]=zr(),k=vt(),b=zm(n,o,x,v,k),S={};try{S=br(x)}catch{S={}}let E=
|
|
758
|
+
`),D(`Seeded starting handoff \u2192 ${tn.relative(e,tn.join(c,u))}`)}catch(c){N(`Could not seed starting handoff: ${c.message}`)}}function Hte(e){let{workspaceRoot:t,workspaceName:r,repos:n,task:s,meta:o,inputs:a,configOverride:c}=e,l=tn.join(t,"CLAUDE.md"),u=null,f=null,d=cr();if(Object.keys(d).length){let[R,I]=zr();for(let B of dk(R,d))N(B);let P=$t(t,c),j=n.map(([B])=>B),M=(o.SERVICES??"").split(",").map(B=>B.trim()).filter(B=>B),[A]=ol(j,R,I,P,d,M);f=A,u=TI(A,d,j,a.work_type??""),O(`Standards routing: active = ${A.join(", ")}`),a0(t,i0(A,d,da(a.work_type??"").gate))}else N(oa()||`no standard modules found in ${gt()} \u2014 this workspace gets no standards routing, skills, or edit-time gate`);rr.mkdirSync(sd(t),{recursive:!0}),Ute(t,l);let p=a.starting_prompt??"";Vte(t,p,a.work_type??"",e.isCreate||p.trim()?e.issue??null:null);let m=RI(r,t,n,s,o,u,e.issue??null);rr.writeFileSync(l,m),D(`Wrote ${l}`);let y=tn.join(K(t),"issues-report.md");rr.mkdirSync(tn.dirname(y),{recursive:!0}),rr.writeFileSync(y,e0(r,ni(o),we({project:a.project,text:ni(o)}))),D(`Wrote ${y}`);let g=tn.join(K(t),"pr-rules.md");rr.writeFileSync(g,t0(".werkmeister/notes/")),D(`Wrote ${g}`);for(let R of I_(t,null,null,f))D(`Wrote ${R}`);let[x,v]=zr(),k=vt(),b=zm(n,o,x,v,k),S={};try{S=br(x)}catch{S={}}let E=YP(b,x,k,(o.FEATURE??"").trim(),S,(o.TEST_PATH??"").trim());for(let R of zP(t,E))D(`Wrote ${R}`);let T=ok(t);If(t),D(`Wrote ${T}`)}var qte,QI,ZI=C(()=>{"use strict";h();JP();Yn();__();Q();Ts();xi();Xe();Oa();Zm();yr();ck();bl();lk();Fe();zn();wr();XI();u0();qte="*No handoff notes yet.*";i(Ute,"salvageLegacyHandoffNotes");i(Wte,"isPlaceholderHandoff");i(Kte,"supersedeNote");i(Vte,"seedStartingHandoff");i(Hte,"init");QI={id:"jit",init:Hte,refresh(e){ok(e),If(e)},check(e){let t=id(e),{authoring:r,drift:n}=YI(e,t?.active??null),s=zI(e,t);return[...r,...n,...s===null?[]:[s]]},sync(e){let{written:t,manifestPath:r}=JI(e);return{wrote:r===null?t:[...t,r]}},sessionContext(e,t){let r=String(t.source||"");return(r==="compact"||r==="clear")&&II(e,String(t.session_id||"")),BI(e,r)||null},gate:LI,ownedPaths:i(()=>["CLAUDE.md",".claude/settings.json",".claude/skills/w9r-*",".claude/agents/w9r-*",".claude/skills/sb-*",".claude/agents/sb-*",`${Nt}/notes`,`${Nt}/standards.json`,`${Nt}/issues-report.md`,`${Nt}/pr-rules.md`,`${Nt}/.gate`],"ownedPaths"),decisions:K0}});import*as Ta from"node:fs";import*as Ns from"node:path";function L_(e){return t4[e]}function H0(e){let t=e==null?"":String(e).trim();if(!t)return"jit";if(Fr.includes(t))return t;throw new z(`Unknown context_strategy '${t}' in workspace.yml \u2014 expected one of: ${Fr.join(", ")}`,"UNKNOWN_CONTEXT_STRATEGY")}function Gte(e){let t=[],r=ze("WORKSPACE_CONFIG");r&&t.push(si(r));for(let n of oi)t.push(Ns.join(K(e),n));for(let n of t){if(!Ta.existsSync(n))continue;let s;try{s=nl(n)}catch{return"jit"}let o=typeof s=="object"&&s!==null&&!Array.isArray(s);return H0(o?s.context_strategy:void 0)}return"jit"}function Xn(e){return t4[Gte(e)]}function e4(e,t){let r=[];for(let n of t){if(!n.endsWith("*")){Ta.existsSync(Ns.join(e,n))&&r.push(n);continue}let s=Ns.dirname(n),o=Ns.basename(n).slice(0,-1),a;try{a=Ta.readdirSync(Ns.join(e,s)).sort()}catch{continue}for(let c of a)c.startsWith(o)&&r.push(Ns.join(s,c))}return r}function Yte(e,t,r){let n=new Set(e4(e,r.ownedPaths()));return e4(e,t.ownedPaths()).filter(s=>!n.has(s))}function zte(e,t){if(H(["git","-C",e,"ls-files","--error-unmatch","--",t],{capture:!0}).status!==0)return!1;let n=H(["git","-C",e,"status","--porcelain","--ignored","--untracked-files=all","--",t],{capture:!0});return n.status===0&&!n.stdout.trim()}function r4(e,t,r,n){let s=Yte(e,t,r);if(s.length){if(!n){N(`${t.id} layer still present: ${s.join(", ")}; remove by hand or run \`werkmeister init-workspace --prune-context\``);return}for(let o of s)zte(e,o)?(Ta.rmSync(Ns.join(e,o),{recursive:!0,force:!0}),D(`Pruned ${o}`)):N(`Kept ${o}: untracked, ignored or modified \u2014 git could not restore it`)}}var t4,Ra=C(()=>{"use strict";h();Q();Qt();mt();Fe();wr();HP();ZI();Um();Um();t4={jit:QI,icm:bk};i(L_,"strategyById");i(H0,"parseStrategyId");i(Gte,"readContextStrategy");i(Xn,"strategyFor");i(e4,"expandOwned");i(Yte,"leftoverPaths");i(zte,"restorable");i(r4,"reportLeftovers")});function Qte(e){return e.listenerCount("SIGINT")>1}function qr(){return j_.signal}function c4(e=process,t=()=>{},r=n=>process.exit(n)){let n=!1;j_=new AbortController,e.on("SIGINT",()=>{if(j_.abort(),Qte(e)&&!n){n=!0;return}t(),r(130)})}var j_,ho=C(()=>{"use strict";h();i(Qte,"claimed");j_=new AbortController;i(qr,"interruptSignal");i(c4,"installDefaultInterrupt")});import*as Aa from"node:fs";import*as Qn from"node:path";function yi(e){let t=Qn.resolve(e);for(;;){if(Aa.existsSync(Qn.join(K(t),"workspace.yml")))return t;let r=Qn.dirname(t);if(r===t)return null;t=r}}function Zte(e){try{let t=Aa.readdirSync(Qn.join(e,"stages")).filter(n=>/^\d+_/.test(n)).sort(),r=t.find(n=>/^\d+_propose$/.test(n))??t.find(n=>/^\d+_ship$/.test(n))??t.at(-1);return r?`stages/${r}/output/`:"the last stage's output/"}catch{return`${Qn.basename(K(e))}/notes/`}}function sre(e){return rre.test(e.replace(ere,"$3").replace(tre,"_"))}function ad(e){return["_shared/pr-rules.md",`${Nt}/pr-rules.md`].find(t=>Aa.existsSync(Qn.join(e,t)))??"docs/workspace-lifecycle.md in the werkmeister repo"}function ore(e){let t=yi(String(e.cwd||process.cwd()));if(!t)return null;let r=String(e.tool_name||""),n=String(e.tool_input?.command||"");if(!(r==="Bash"&&sre(n)||nre.test(r)))return null;let s=ad(t);return`Inside workspace \`${Qn.basename(t)}\`, PRs open only through \`werkmeister pr open\`: it runs the pre-PR gate and records the URL. Write the PR file in \`${Zte(t)}\`, have the person set \`status: approved\`, then run \`werkmeister pr open\`. Rules: \`${s}\`.`}function l4(){let e=null;try{let t=process.stdin.isTTY?"":Aa.readFileSync(0,"utf8"),r=t.trim()?JSON.parse(t):{};typeof r=="object"&&r!==null&&!Array.isArray(r)&&(e=ore(r))}catch{e=null}e&&console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}))}var ere,tre,rre,nre,_l=C(()=>{"use strict";h();Wn();i(yi,"findRecordRoot");i(Zte,"prFileDirName");ere=/(?<!<)<<(?!<)-?\s*(['"]?)(\w+)\1([^\n]*)(?:\n(?:[\s\S]*?\n)?\t*\2(?=\n|$)|[\s\S]*$)/g,tre=/'[^']*(?:'|$)|"(?:[^"\\]|\\[\s\S])*(?:"|$)/g,rre=/(?:^|[;&|({\n`])\s*(?:(?:\w+=\S*|command|exec|env|then|do|else)\s+)*gh\s+pr\s+create\b/,nre=/create_pull_request$/;i(sre,"opensPr");i(ad,"prRulesPath");i(ore,"decide");i(l4,"main")});import*as wt from"node:fs";import*as G0 from"node:path";function cd(e){try{let t=JSON.parse(wt.readFileSync(d4(e),"utf8"));if(!ire.has(t?.state)||typeof t.at!="string")return null;let r={state:t.state,at:t.at};return typeof t.question=="string"&&(r.question=t.question),t.via==="wrap_up"&&(r.via="wrap_up"),r}catch{return null}}function D_(e){return/\?[\s*_`'")\]]*$/.test(e)}function F_(e){let t=e.trim().split(/\n\s*\n/);return t[t.length-1].trim().slice(0,200)}function lre(e){let t=wt.openSync(e,"r"),r;try{let s=wt.fstatSync(t).size,o=Math.min(s,65536),a=Buffer.alloc(o);wt.readSync(t,a,0,o,s-o),r=a.toString("utf8")}finally{wt.closeSync(t)}let n=r.split(`
|
|
759
759
|
`);for(let s=n.length-1;s>=0;s--){let o;try{o=JSON.parse(n[s])}catch{continue}if(o.type!=="assistant")continue;let a=o.message?.content;if(typeof a=="string")return a;if(!Array.isArray(a))continue;let c=a.filter(l=>l?.type==="text"&&typeof l.text=="string");if(c.length)return c.map(l=>l.text).join(`
|
|
760
760
|
`)}return null}function ure(e,t){switch(e.hook_event_name){case"UserPromptSubmit":return{state:"working"};case"PostToolUse":return e.tool_name===u4&&t?.via==="wrap_up"?null:{state:"working"};case"PreToolUse":{let r=String(e.tool_name??""),n=e.tool_input?.ask;if(r===u4&&typeof n=="string"&&n.trim())return{state:"needs-you",question:n.trim(),via:"wrap_up"};if(!are.has(r))return{state:"working"};let s=e.tool_input?.questions?.[0]?.question;return{state:"needs-you",question:typeof s=="string"?s:"Approve the plan?"}}case"Notification":{let r=e.notification_type,n=String(e.message??"");return!(typeof r=="string"?cre.has(r):!/waiting for your input/i.test(n))||t?.state==="needs-you"&&t.question?null:{state:"needs-you",question:n||void 0}}case"Stop":{let r=null;return typeof e.last_assistant_message=="string"?r=e.last_assistant_message:typeof e.transcript_path=="string"&&(r=lre(e.transcript_path)),r&&D_(r)?{state:"needs-you",question:F_(r)}:t?.via==="wrap_up"?null:{state:"done"}}case"SessionEnd":return t?.state==="working"?{state:"idle"}:null;default:return null}}function B_(e,t){let r=`${e}.${process.pid}.tmp`;wt.writeFileSync(r,`${JSON.stringify(t)}
|
|
761
761
|
`),wt.renameSync(r,e)}function Sl(e){try{let t=JSON.parse(wt.readFileSync(Y0(e),"utf8"));return typeof t?.at!="string"||!Array.isArray(t.containers)?null:{at:t.at,containers:t.containers.map(String),was_working:t.was_working===!0}}catch{return null}}function p4(e,t){B_(Y0(e),t)}function q_(e){wt.rmSync(Y0(e),{force:!0})}function fre(e){try{let t=JSON.parse(wt.readFileSync(wi(e),"utf8"));return typeof t?.message=="string"?t.message:null}catch{return null}}function h4(e,t,r=new Date){B_(wi(e),{message:t,at:r.toISOString()})}function m4(e){let t=fre(e);return wt.rmSync(wi(e),{force:!0}),t}function dre(e,t){if(!wt.existsSync(Y0(t)))return null;switch(e.hook_event_name){case"PreToolUse":return{continue:!1,stopReason:f4,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:f4}};case"UserPromptSubmit":return{decision:"block",reason:"This workspace is paused. Press \u25B6 Resume on its card first."};default:return null}}function pre(e,t=new Date){let r=yi(String(e.cwd||process.cwd()));if(!r)return null;let n=cd(r),s=ure(e,n);if(!s||n&&n.state===s.state&&n.question===s.question&&n.via===s.via)return null;let o={state:s.state,at:t.toISOString()};s.question&&(o.question=s.question),s.via&&(o.via=s.via);let a=d4(r);return B_(a,o),a}function g4(){try{let e=process.stdin.isTTY?"":wt.readFileSync(0,"utf8"),t=e.trim()?JSON.parse(e):{};if(typeof t!="object"||t===null||Array.isArray(t))return;let r=yi(String(t.cwd||process.cwd())),n=r?dre(t,r):null;if(n){console.log(JSON.stringify(n));return}r&&t.hook_event_name==="UserPromptSubmit"&&wt.rmSync(wi(r),{force:!0}),pre(t)}catch{}}var ire,are,u4,cre,d4,f4,M_,Y0,wi,z0=C(()=>{"use strict";h();Wn();_l();ire=new Set(["working","needs-you","done","idle"]),are=new Set(["AskUserQuestion","ExitPlanMode"]),u4="mcp__ccd_turn__wrap_up",cre=new Set(["permission_prompt","elicitation_dialog"]),d4=i(e=>G0.join(K(e),"agent-state.json"),"stateFile");i(cd,"readAgentState");i(D_,"asksQuestion");i(F_,"questionOf");i(lre,"lastAssistantText");i(ure,"nextState");f4="Workspace paused by the person from its card. End your turn now; it continues when they press Resume.",M_="Workspace resumed by the person. Continue where you left off.",Y0=i(e=>G0.join(K(e),"paused.json"),"pausedPath"),wi=i(e=>G0.join(K(e),"resume-nudge.json"),"nudgePath");i(B_,"writeAtomic");i(Sl,"readPaused");i(p4,"writePaused");i(q_,"clearPaused");i(fre,"readNudge");i(h4,"writeNudge");i(m4,"claimNudge");i(dre,"pauseGate");i(pre,"record");i(g4,"main")});import*as Ca from"node:fs";import*as x4 from"node:os";import*as y4 from"node:path";function U_(e){let t=Zn(e);return t===null?null:yh(t)}function Zn(e){let t=mre(e);if(t!==null&&yh(t)!==null)return t;let r;try{r=Ir(e)}catch{return t}return yh(r)!==null&&hre(r,e)?r:t}function hre(e,t){let r;try{r=Ca.readFileSync(y4.join(e,".env"),"utf8")}catch{return!1}return r.split(`
|
|
@@ -1043,7 +1043,7 @@ ${(U.stdout+U.stderr).trimEnd().split(`
|
|
|
1043
1043
|
`).slice(-5).join(`
|
|
1044
1044
|
`)}`:""}`)}}return a("approved",Qe(t)==="approved",`status: ${Qe(t)}`),{ok:o.every(F=>F.ok),checks:o}}function mD(e,t){return[`${e}: gate ${t.ok?"passed":"FAILED"}`,...t.checks.map(r=>` ${r.ok?"\u2713":"\u2717"} ${r.name}: ${r.detail.replace(/\n/g,`
|
|
1045
1045
|
`)}`)]}async function bx(e,t,r=Vs()){let n=Sr(e),s=gD(e,n,t,c=>!Zce(c,n)),o=[],a=!0;for(let c of s){let l=await wx(e,c,r);a&&=l.ok,o.push(...mD(c.stem,l))}return{ok:a,lines:o}}function Zce(e,t){return Ha.has(Qe(e))&&t.some(r=>r!==e&&r.dir===e.dir&&!Ha.has(Qe(r)))}function gD(e,t,r,n){let s=t.filter(n);if(r&&(s=t.filter(o=>o.stem===r||o.dir===r),s.length>1&&(s=s.filter(n))),!s.length){let o=Kd(e)??"this workspace (no stage holds PR files)",a=`format: ${ad(e)}`;throw new q(r?`No PR file for ${r} in ${o} (${a}).`:`No matching PR file in ${o}. Write pr-<worktree>[-<slug>].md there (${a}) and have the person set status: approved.`)}return s}async function vx(e,t,r=Vs()){let n=Sr(e),s=gD(e,n,t,l=>Qe(l)==="approved"),o=[],a=!0,c=[];for(let l of s){let u=String(l.fm.branch??""),f=n.find(b=>b!==l&&b.dir===l.dir&&String(b.fm.branch??"")===u&&["merged","shipped","closed"].includes(Qe(b)));if(f){a=!1,o.push(`${l.stem}: branch ${u} was already used by ${f.stem} (${Qe(f)}) \u2014 cut a new one with \`werkmeister pr new ${l.dir} --slug <slug>\``);continue}let d=await wx(e,l,r);if(!d.ok){a=!1,o.push(...mD(l.stem,d));continue}let p=Y.join(e,l.dir),m=await r.run("git",["-C",p,"push","-u","origin",u]);if(m.code!==0){a=!1,o.push(`${l.stem}: push failed \u2014 ${m.stderr.trim()}`);continue}let y=await r.run("gh",["pr","list","--repo",l.fm.repo,"--head",u,"--state","open","--json","url","--jq",".[0].url // empty"],p),g=y.code===0?y.stdout.trim():"";if(!g){let b=Y.join(ee.mkdtempSync(Y.join(hD.tmpdir(),"werkmeister-pr-")),"body.md");ee.writeFileSync(b,l.body);let S=await r.run("gh",["pr","create","--repo",l.fm.repo,"--base",String(l.fm.base??"main"),"--head",u,"--title",l.title,"--body-file",b],p);if(ee.rmSync(Y.dirname(b),{recursive:!0,force:!0}),g=S.stdout.trim().split(`
|
|
1046
|
-
`).pop()??"",S.code!==0||!g.startsWith("http")){a=!1,o.push(`${l.stem}: gh pr create failed \u2014 ${S.stderr.trim()||S.stdout.trim()}`);continue}}_o(l,{status:"open",url:g,...await r.session(e)}),c.push(Y.relative(e,l.path)),o.push(`${l.stem}: open ${g}`);let x=await r.run("git",["-C",p,"diff",`origin/${String(l.fm.base??"main")}...HEAD`,"--",".git-blame-ignore-revs"]);/^\+[0-9a-f]{7,40}\b/m.test(x.stdout)&&o.push(" warning: this branch adds a SHA to .git-blame-ignore-revs \u2014 merge with a merge commit, not squash or rebase, and say so at the top of the PR body");let v=$t(e,null),k=vn(v);if(k){let b=n.some(R=>R!==l&&R.dir===l.dir),{tracker:S,statuses:E}=r1(v,k,r),T=await Xl(S,k,"in_review",E,{comment:`${b?"Follow-up PR":"PR"} opened: ${g}`,...b?{alwaysComment:!0}:{}});T&&o.push(` issue ${T}`)}}return c.length&&o.push((await r.commitRecord(e,"chore: record opened PR(s)",c)).message),a&&c.length&&o.push(await r.stop(e)),{ok:a,lines:o}}async function Ga(e,t=Vs(),r={}){let n=[],s=[],o={shipped:[],merged:[],closed:[],changesRequested:[],reReview:[]};for(let c of Sr(e)){let l=Qe(c),u=c.fm.review;if(r.gh!==!1&&l==="open"&&c.fm.url){let d=await t.run("gh",["pr","view",String(c.fm.url),"--json","state,mergeCommit,reviewDecision,latestReviews"]);if(d.code!==0){n.push(`${c.stem}: gh pr view failed \u2014 ${d.stderr.trim()}`);continue}let p=JSON.parse(d.stdout),m=p.reviewDecision==="CHANGES_REQUESTED"||(p.latestReviews??[]).some(g=>g.state==="CHANGES_REQUESTED"),y=String(c.fm.url);p.state==="MERGED"?(_o(c,{status:"merged",merge_sha:p.mergeCommit?.oid??""}),o.merged.push(y)):p.state==="CLOSED"?(_o(c,{status:"closed",reason:Ks(c.fm.reason)||"closed on GitHub"}),o.closed.push(y)):m?u!=="changes_requested"&&(_o(c,{review:"changes_requested"}),o.changesRequested.push(y)):u==="changes_requested"&&(_o(c,{review:void 0}),o.reReview.push(y))}if(Qe(c)==="merged"){let d=t.repos[c.dir]??{};if(d.ship!=="tag")_o(c,{status:"shipped"});else{let p=Y.join(e,c.dir);await t.run("git",["-C",p,"fetch","-q","--tags","origin"]);let m=await t.run("git",["-C",p,"tag","--contains",String(c.fm.merge_sha),"--list",String(d.release_tag),"--sort=creatordate"]),y=m.code===0?m.stdout.split(`
|
|
1046
|
+
`).pop()??"",S.code!==0||!g.startsWith("http")){a=!1,o.push(`${l.stem}: gh pr create failed \u2014 ${S.stderr.trim()||S.stdout.trim()}`);continue}}_o(l,{status:"open",url:g,...await r.session(e)}),c.push(Y.relative(e,l.path)),o.push(`${l.stem}: open ${g}`),o.push(`<pr-created>${g}</pr-created>`);let x=await r.run("git",["-C",p,"diff",`origin/${String(l.fm.base??"main")}...HEAD`,"--",".git-blame-ignore-revs"]);/^\+[0-9a-f]{7,40}\b/m.test(x.stdout)&&o.push(" warning: this branch adds a SHA to .git-blame-ignore-revs \u2014 merge with a merge commit, not squash or rebase, and say so at the top of the PR body");let v=$t(e,null),k=vn(v);if(k){let b=n.some(R=>R!==l&&R.dir===l.dir),{tracker:S,statuses:E}=r1(v,k,r),T=await Xl(S,k,"in_review",E,{comment:`${b?"Follow-up PR":"PR"} opened: ${g}`,...b?{alwaysComment:!0}:{}});T&&o.push(` issue ${T}`)}}return c.length&&o.push((await r.commitRecord(e,"chore: record opened PR(s)",c)).message),a&&c.length&&o.push(await r.stop(e)),{ok:a,lines:o}}async function Ga(e,t=Vs(),r={}){let n=[],s=[],o={shipped:[],merged:[],closed:[],changesRequested:[],reReview:[]};for(let c of Sr(e)){let l=Qe(c),u=c.fm.review;if(r.gh!==!1&&l==="open"&&c.fm.url){let d=await t.run("gh",["pr","view",String(c.fm.url),"--json","state,mergeCommit,reviewDecision,latestReviews"]);if(d.code!==0){n.push(`${c.stem}: gh pr view failed \u2014 ${d.stderr.trim()}`);continue}let p=JSON.parse(d.stdout),m=p.reviewDecision==="CHANGES_REQUESTED"||(p.latestReviews??[]).some(g=>g.state==="CHANGES_REQUESTED"),y=String(c.fm.url);p.state==="MERGED"?(_o(c,{status:"merged",merge_sha:p.mergeCommit?.oid??""}),o.merged.push(y)):p.state==="CLOSED"?(_o(c,{status:"closed",reason:Ks(c.fm.reason)||"closed on GitHub"}),o.closed.push(y)):m?u!=="changes_requested"&&(_o(c,{review:"changes_requested"}),o.changesRequested.push(y)):u==="changes_requested"&&(_o(c,{review:void 0}),o.reReview.push(y))}if(Qe(c)==="merged"){let d=t.repos[c.dir]??{};if(d.ship!=="tag")_o(c,{status:"shipped"});else{let p=Y.join(e,c.dir);await t.run("git",["-C",p,"fetch","-q","--tags","origin"]);let m=await t.run("git",["-C",p,"tag","--contains",String(c.fm.merge_sha),"--list",String(d.release_tag),"--sort=creatordate"]),y=m.code===0?m.stdout.split(`
|
|
1047
1047
|
`).map(g=>g.trim()).find(Boolean):void 0;y&&_o(c,{status:"shipped",release:y})}}let f=Qe(c);f==="shipped"&&l!=="shipped"&&o.shipped.push(c),(f!==l||c.fm.review!==u)&&s.push(Y.relative(e,c.path)),n.push(`${c.stem}: ${f}${c.fm.release?` (${c.fm.release})`:""}${c.fm.url?` ${c.fm.url}`:""}`)}let a=await ele(e,o,t);return a&&n.push(`issue ${a}`),(o.merged.length||o.shipped.length)&&n.push(await t.stop(e)),s.length&&n.push((await t.commitRecord(e,"chore: record PR status",s)).message),{lines:n,changed:s.length>0}}async function ele(e,t,r){let s=Object.values(t).some(d=>d.length)?$t(e,null):null,o=vn(s);if(!o)return"";let a=Sr(e),c=Ya(e).state,{tracker:l,statuses:u}=r1(s,o,r),f=i((d,p,m=!1)=>Xl(l,o,d,u,{comment:p,back:m}),"move");return t.shipped.length&&c==="shipped"?f("done",xD(a.filter(d=>Qe(d)==="shipped"))):t.merged.length&&a.every(d=>Ha.has(Qe(d)))?f("merged",`Merged: ${t.merged.join(", ")}`):t.changesRequested.length?f("in_progress",`Changes requested: ${t.changesRequested.join(", ")}`,!0):t.closed.length&&!a.some(d=>Qe(d)==="open")?f("in_progress",`PR closed without merging: ${t.closed.join(", ")}`,!0):t.reReview.length?f("in_review",`Back in review: ${t.reReview.join(", ")}`):""}async function rle(e,t){let r=t.CLAUDE_CODE_SESSION_ID||(await za(Y.basename(e)).catch(()=>null))?.sessionId;if(!r)return{};let n=t.CLAUDE_CODE_HOST_SESSION_ID,s=await Tx(r);return{session:r,...n&&{host_session:n},...s&&{session_cwd:s}}}function n1(e,t,r){return e==="merged"?`PR ${t} merged. Run \`werkmeister pr status\`, then follow the workspace router.`:e==="shipped"?`PR ${t} shipped${r?` in ${r}`:""}. Ask the person whether to run \`werkmeister close-out\`.`:e==="closed"?`PR ${t} was closed. Report it to the person.`:null}function kx(e){for(let t=0;t<2;t++)try{return ee.closeSync(ee.openSync(e,"wx")),!0}catch(r){if(r.code!=="EEXIST")throw r;try{if(Date.now()-ee.statSync(e).mtimeMs<tle)return!1;ee.rmSync(e,{force:!0})}catch{}}return!1}async function nle(e,t,r=Vs(),n=Y.join(St(),"pr-callbacks.lock")){if(ee.mkdirSync(Y.dirname(n),{recursive:!0}),!kx(n))return{claimed:[],lines:["another PR watch pass is running"]};let s=[],o=[];try{for(let a of e){let c=i(()=>{try{return Sr(a).filter(f=>f.fm.session&&(t.desktop||!f.fm.host_session))}catch{return[]}},"callbacks"),l=c();if(!l.length)continue;if(l.some(f=>Qe(f)==="open"||Qe(f)==="merged"))for(let f of(await Ga(a,r)).lines)o.push(`${Y.basename(a)}/${f}`);let u=[];for(let f of c()){let d=Qe(f);if(d===(Ks(f.fm.notified)||"open"))continue;let p=String(f.fm.url??""),m=n1(d,p,Ks(f.fm.release)||void 0);m&&s.push({ws:a,dir:f.dir,url:p,session:String(f.fm.session),sessionDir:Ks(f.fm.session_cwd)||null,hostSession:Ks(f.fm.host_session)||null,message:m}),_o(f,t1.has(d)?{session:void 0,session_cwd:void 0,host_session:void 0,notified:void 0}:{notified:d}),u.push(Y.relative(a,f.path))}u.length&&o.push((await r.commitRecord(a,"chore: record PR callback",u)).message)}}finally{ee.rmSync(n,{force:!0})}return{claimed:s,lines:o}}async function yD(e,t,r=Y.join(St(),"pr-callbacks.lock")){let n=e.filter(o=>{try{return Sr(o).some(a=>Qe(a)==="merged")}catch{return!1}});if(!n.length)return[];if(ee.mkdirSync(Y.dirname(r),{recursive:!0}),!kx(r))return["another PR watch pass is running"];let s=[];try{let o=t??Vs();for(let a of n)for(let c of(await Ga(a,o,{gh:!1})).lines)s.push(`${Y.basename(a)}/${c}`)}finally{ee.rmSync(r,{force:!0})}return s}async function sle(e){let t=Y.basename(e.ws),r=e.sessionDir??await Tx(e.session)??e.ws;if((await za(t,e.session,r)).sessionId!==e.session)throw new q(`session ${e.session} is gone`);await Rx(t,e.message,e.session,r)}async function _x(e,t=Vs(),r=sle,n=Y.join(St(),"idle-stop.lock")){let{workspaces:s}=await eu(),{claimed:o,lines:a}=await nle(s.map(l=>l.path),e,t),c=[];for(let l of o){if(l.hostSession){c.push(l);continue}try{await r(l),a.push(`${l.dir}: resumed session ${l.session}: ${l.message}`)}catch(u){a.push(`${l.dir}: could not resume session ${l.session}: ${u.message}`)}}if(ee.mkdirSync(Y.dirname(n),{recursive:!0}),kx(n))try{a.push(...(await t.reapIdle()).lines)}finally{ee.rmSync(n,{force:!0})}else a.push("another idle-stop pass is running");return{ok:!0,lines:a,desktop:c}}async function Sx(e,t,r=Vs()){let n=Kd(e);if(!n)throw new q("This workspace has no stage to hold a PR file.");let s=t.repo;if(!s){let f=await tu(e);if(f.length!==1)throw new q(`Name the repo \u2014 this workspace has ${f.map(d=>d.repo).join(", ")||"no code worktree"}.`);s=f[0].repo}let o=Y.join(n,`pr-${s}.md`),a=i(()=>{if(ee.existsSync(o))throw new q(`${o} already exists \u2014 remove it first to adopt.`)},"taken"),c,l;if(t.noPr!==void 0){if(!t.noPr.trim())throw new q("--no-pr needs a reason.");a(),c={status:"closed",reason:t.noPr.trim(),adopted:!0},l="No PR: the fix is already on base"}else{if(!t.pr)throw new q("Give a PR number or URL, or --no-pr <reason>.");let f=await r.run("gh",["pr","view",t.pr,"--json","url,headRefName,baseRefName,title,state,mergeCommit"],Y.join(e,s));if(f.code!==0)throw new q(`gh pr view ${t.pr} failed \u2014 ${f.stderr.trim()}`);let d=JSON.parse(f.stdout);if(d.state!=="MERGED"&&d.state!=="OPEN")throw new q(`${d.url} is ${d.state}, not merged \u2014 use --no-pr <reason> if the fix landed another way.`);let p=Sr(e).find(g=>g.fm.url===d.url);if(p)throw new q(`${d.url} is already tracked in ${Y.basename(p.path)}.`);let m=ee.existsSync(o);m&&(o=Y.join(n,`pr-${s}-${/\/pull\/(\d+)/.exec(d.url)?.[1]}.md`)),a();let y=d.state==="MERGED";c={...m?{worktree:s}:{},repo:/github\.com\/([^/]+\/[^/]+)\/pull\//.exec(d.url)?.[1]??"",branch:d.headRefName,base:d.baseRefName,status:y?"merged":"open",url:d.url,...y?{merge_sha:d.mergeCommit?.oid??""}:{},adopted:!0},l=d.title}ee.writeFileSync(o,`---
|
|
1048
1048
|
${xx.default.stringify(c)}---
|
|
1049
1049
|
# ${l}
|
|
@@ -1218,7 +1218,7 @@ If the content is unusable, output <result>{}</result> and nothing else.
|
|
|
1218
1218
|
---
|
|
1219
1219
|
Issue content:
|
|
1220
1220
|
\`\`\`
|
|
1221
|
-
`+s+"\n```"}async function jue(e,t){let r=[...new Set(e.map(c=>we({text:c}).parseRef(c)).filter(c=>!!c))].sort((c,l)=>c.localeCompare(l));if(!r.length)return{};let n=i(async c=>{let l=new Map;for(let f of c){let d=ri({text:f})?.name??"";l.set(d,[...l.get(d)??[],f])}let u={};for(let[f,d]of l){let p=we(f?{project:f}:void 0);for(let[m,y]of Object.entries(await p.fetchIssues(d)))y.status&&(u[m]=y.status)}return u},"fetchStatuses"),s={},o=[],a=[];if(t?.refresh)o.push(...r);else for(let c of r){let l=await TE(`status:${c}`);if(!l){o.push(c);continue}s[c]=l.v,Date.now()-l.at>=Lue&&a.push(c)}if(a.length&&RE(a.map(c=>`status:${c}`),async c=>{let l=await n(c.map(u=>u.slice(7)));for(let[u,f]of Object.entries(l))await Ua(`status:${u}`,f)}),o.length)for(let[c,l]of Object.entries(await n(o)))s[c]=l,await Ua(`status:${c}`,l);return s}function Due(e){let t={};for(let r of Cue){let n=e[r];if(typeof n!="string")continue;let s=n.trim();s&&(r==="feature"&&!Pue.test(s)||(t[r]=s))}return t}function Fue(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 Wx(e){try{let t=await ke.readFile(oe.join(K(e),"workspace.yml"),"utf-8"),r=(0,cp.parse)(t),n=vn(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=Es(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:Es(l);return{issueId:n,project:io(r),labels:s,model:a,autonomous:c,autoStop:u,task:o(r?.task),workType:o(r?.work_type)}}catch{return{issueId:null,project:"",labels:[],model:null,autonomous:!1,autoStop:!1,task:null,workType:null}}}async function eu(){let e=yn(),t;try{t=await ke.readdir(e,{withFileTypes:!0})}catch(s){throw new q(`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=oe.join(e,s),{issueId:a,project:c,labels:l,model:u,task:f,workType:d}=await Wx(o);return{name:s,path:o,vscodeUri:`vscode://file${o.split(oe.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?we({project:c,text:a}).url(a):null,labels:l,model:u,task:f,workType:d,lifecycle:Ya(o).state}}));return{root:e,workspaces:n}}function Mue(){let e=[...new Set(jr().map(t=>t.tracker))];return e.length?e.length===1?Ss(e[0]).label:"tracker":we().label}async function Bue(){let e;try{e=Hl(
|
|
1221
|
+
`+s+"\n```"}async function jue(e,t){let r=[...new Set(e.map(c=>we({text:c}).parseRef(c)).filter(c=>!!c))].sort((c,l)=>c.localeCompare(l));if(!r.length)return{};let n=i(async c=>{let l=new Map;for(let f of c){let d=ri({text:f})?.name??"";l.set(d,[...l.get(d)??[],f])}let u={};for(let[f,d]of l){let p=we(f?{project:f}:void 0);for(let[m,y]of Object.entries(await p.fetchIssues(d)))y.status&&(u[m]=y.status)}return u},"fetchStatuses"),s={},o=[],a=[];if(t?.refresh)o.push(...r);else for(let c of r){let l=await TE(`status:${c}`);if(!l){o.push(c);continue}s[c]=l.v,Date.now()-l.at>=Lue&&a.push(c)}if(a.length&&RE(a.map(c=>`status:${c}`),async c=>{let l=await n(c.map(u=>u.slice(7)));for(let[u,f]of Object.entries(l))await Ua(`status:${u}`,f)}),o.length)for(let[c,l]of Object.entries(await n(o)))s[c]=l,await Ua(`status:${c}`,l);return s}function Due(e){let t={};for(let r of Cue){let n=e[r];if(typeof n!="string")continue;let s=n.trim();s&&(r==="feature"&&!Pue.test(s)||(t[r]=s))}return t}function Fue(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 Wx(e){try{let t=await ke.readFile(oe.join(K(e),"workspace.yml"),"utf-8"),r=(0,cp.parse)(t),n=vn(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=Es(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:Es(l);return{issueId:n,project:io(r),labels:s,model:a,autonomous:c,autoStop:u,task:o(r?.task),workType:o(r?.work_type)}}catch{return{issueId:null,project:"",labels:[],model:null,autonomous:!1,autoStop:!1,task:null,workType:null}}}async function eu(){let e=yn(),t;try{t=await ke.readdir(e,{withFileTypes:!0})}catch(s){throw new q(`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=oe.join(e,s),{issueId:a,project:c,labels:l,model:u,task:f,workType:d}=await Wx(o);return{name:s,path:o,vscodeUri:`vscode://file${o.split(oe.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?we({project:c,text:a}).url(a):null,labels:l,model:u,task:f,workType:d,lifecycle:Ya(o).state}}));return{root:e,workspaces:n}}function Mue(){let e=[...new Set(jr().map(t=>t.tracker))];return e.length?e.length===1?Ss(e[0]).label:"tracker":we().label}async function Bue(){let e;try{e=Hl(fP({},Za.homedir(),{defaults:!1}))}catch(n){throw new q(`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:Mue()}},{schema:e.schema,uiSchema:t,formData:e.formData,title:e.title??"Initialize workspace"}}function dF(e){return"--"+e.replace(/_/g,"-")}function $F(e){let t=String(e.feature??"").trim();if(!t)throw new q("A feature name is required (pass it as an argument, set it in ./.werkmeister/workspace.yml, or run interactively).");let r=["workspace",t];for(let[n,s]of Object.entries(e)){if(n==="feature"||que.has(n))continue;if(s===!0){r.push(dF(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(dF(n),o)}return r}async function Wue(){for(let e of Uue)if(await aa(e))return e;return null}async function OF(e){let t=await Wue();if(!t)return{opened:!1,note:"VS Code CLI ('code') not found \u2014 open the workspace folder manually."};try{return gF(t,[e],{detached:!0,stdio:"ignore"}).unref(),{opened:!0}}catch(r){return{opened:!1,note:`Could not launch VS Code: ${r.message}`}}}async function Kx(e,t=Ef){let r=rl({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 EF(Ss(e.tracker).label,e.ref,r))}catch(a){return{fields:{},warning:a.message}}if(n===null)return{fields:{},warning:"the model gave no answer"};let s=await B1({},n),o={};for(let a of Kue){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 TF(e,t={}){let r=fa(e,t.cwd??Za.homedir());try{let a=qm(r.issue_id??"",r.project);a&&(r.project=a.name)}catch(a){throw new q(a.message)}if(!r.issue_id)return{resolved:r,issue:null};let n=we({project:r.project,text:r.issue_id}),s=n.parseRef(r.issue_id);if(!s)throw new q(`${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 Jl(s,void 0,n)}catch(a){if(a instanceof Wa){let c=await n.checkAuth(),l=c.ok?"run `werkmeister connect` to check the issue tracker":`${n.label}: ${c.reason}; run: ${c.fix}`;throw new q(`${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 Kx(o,t.distill??Ef);for(let l of["description","starting_prompt"])!r[l]&&a[l]&&(r[l]=a[l]);c&&N(`description/starting_prompt not filled from the issue: ${c}`)}return{resolved:r,issue:o}}async function q1(e,t={}){let n=`werkmeister ${$F(e).join(" ")}`,s=i(async()=>{let{resolved:f,issue:d}=await TF(e,t);return fF(f,{issue:d??void 0,readStdinTask:t.readStdinTask,force:t.force,build:t.build})},"run"),o=Wc(t.onData),a;try{a=t.live?await s():await Yo(o,s)}catch(f){if(t.live)throw f instanceof $r?f:new q(f.message);let d=Ie(o.text().trim())||f.message;throw new q(`${n} failed:
|
|
1222
1222
|
${d}`)}let c=Ie(o.text().trim()),l=!1,u;return(t.open??!0)&&a&&await j1(a)?{opened:l,note:u}=await OF(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 Cn(e){let t=(e??"").trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new q(`Invalid workspace name: ${JSON.stringify(e)}`);let r=oe.join(yn(),t);if(!await j1(r))throw new q(`No such workspace: ${t}`);return r}function Vue(e){let t=e.slice(U1.length);if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new q(`Invalid reconcile session: ${JSON.stringify(e)}`);return oe.join(RF(),t)}async function lp(e){if((e??"").startsWith(U1)){let t=Vue(e);if(!await j1(t))throw new q(`No such reconcile session: ${e}`);return t}return Cn(e)}async function W1(e){let t=await Cn(e),{opened:r,note:n}=await OF(t);if(!r)throw new q(n??"Could not launch VS Code.");return{path:t}}async function iu(e,t){try{let r=await ke.readFile(oe.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 Hue(e){try{let t=await ke.readFile(oe.join(K(e),"workspace.yml"),"utf-8"),r=/^feature: *["']?([^"'\s#]+)/m.exec(t);return r?r[1]:null}catch{return null}}async function AF(e){let t=await ke.readdir(oe.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 ke.readdir(oe.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 Gue(e){let t;try{t=wl(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 zue(e,t=131072){let r=await ke.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(`
|
|
1223
1223
|
`);c>=0&&(a=a.slice(c+1))}return a}finally{await r.close()}}async function Jue(e,t){let r=await za(e).catch(()=>null),n=r?.updatedAt??null,s=G1.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=cd(t);if(a)return o(a.state,a.at,a.question??null);let c;try{r?.sessionFile&&(c=H1(await zue(r.sessionFile)).at(-1))}catch{}return!c||!n?o("idle"):c.role==="assistant"?D_(c.text)?o("needs-you",n,F_(c.text)):o("done"):o(Date.now()-Date.parse(n)<Yue?"working":"idle")}function pF(e){return e.health==="healthy"?"healthy":e.health==="starting"?"starting":e.health==="unhealthy"?"unhealthy":e.state==="running"?"running":"down"}function CF(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(ld(r,Br(o,"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=Br(o,"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 Xue(){let e=await Mt();return e?{containers:e,tallies:CF(e),health:await Dg(e)}:null}async function Que(){let e=await D1(zo());if(!e)return null;try{return(0,cp.parse)(await ke.readFile(e,"utf8"))??null}catch{return null}}function Zue(e,t){let[r,n]=ym(e,t);return`${r}-${n}`}async function PF(){let e=yn(),r=(await ke.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),n=await Xue(),s=n?.tallies??null,o=await Que(),a=await Promise.all(r.map(async l=>{let u=oe.join(e,l),f=await iu(u,"COMPOSE_PROJECT_NAME");if(!f){let P=await Hue(u);f=P?bi(P):null}let{signal:d,lastActivity:p}=await Jue(l,u),{model:m,autonomous:y,autoStop:g}=await Wx(u),x=Sl(u),v=x?{at:x.at,containers:x.containers}:null,k={paused:v,resumeNudge:yF(wi(u)),claude:d,model:m,stage:await AF(u),phase:Gue(u),autonomous:y,autoStop:g,lastActivity:p};if(s===null)return{name:l,project:f,state:"unknown",running:0,total:0,slot:null,ports:null,services:[],...k,started:null,crashLoops:[]};let b=f?s.get(f):void 0,S=f?n?.health.get(f):void 0,E;!b||b.total===0?E="down":b.running===b.total?E="up":b.running>0?E="partial":E="stopped",v&&(E="paused");let T=b?.slot??null,R=T!==null?Zue(T,o):null,I=(b?.services??[]).map(P=>({name:P.name,state:pF(P)}));return{name:l,project:f,state:E,running:b?.running??0,total:b?.total??0,slot:T,ports:R,services:I,...k,started:S?.started??null,crashLoops:S?.crashLoops??[]}})),c;if(s===null)c={state:"unknown",running:0,total:0,services:[]};else{let u=s.get(vr)?.services??[],f=u.find(g=>g.name==="k8s-forwards");f&&f.state!=="running"&&!await Cg(n?.containers??null)&&(u=u.filter(g=>g!==f));let d=u.filter(g=>g.state==="running").length,p=u.length,m=p===0?"down":d===p?"up":d>0?"partial":"down",y=u.map(g=>({name:g.name,state:pF(g)}));c={state:m,running:d,total:p,services:y}}return{statuses:a,infra:c}}async function efe(e){let t=[],r=await ke.readdir(oe.join(e,"stages")).catch(()=>[]);for(let n of r.sort()){let s=oe.join("stages",n,"output"),o=await ke.readdir(oe.join(e,s)).catch(()=>[]);for(let a of o.sort()){if(!a.endsWith(".md"))continue;let c=await ke.readFile(oe.join(e,s,a),"utf-8").catch(()=>"");/^status: proposed/m.test(c)&&t.push(oe.join(s,a))}}return t}async function tfe(e){let t=new Date,[{root:r,workspaces:n},{statuses:s}]=await Promise.all([eu(),PF()]),o=oe.join(r,".check-in-last"),a=await ke.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 yD(f.map(m=>m.path),e);let d=await Promise.all(f.map(async m=>{let y=u.get(m.name),{updatedAt:g}=await za(m.name).catch(()=>({updatedAt:null})),x=Ya(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 efe(m.path),updatedAt:g,changed:a!==null&&g!==null&&Date.parse(g)>a,lifecycle:x.state,paused:y?.paused!=null,prs:x.prs.map(v=>({repo:v.dir,url:v.url,status:v.status,release:v.release}))}}));await ke.writeFile(o,"",{flag:"a"}),await ke.utimes(o,t,t);let p=d.filter(m=>!m.paused&&(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.paused&&m.claude.agent!=="working"&&!p.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:p}}async function rfe(){let e=await ax(),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 NF(e){try{return await ke.access(oe.join(e,".git")),!0}catch{return!1}}async function tu(e){let t=await ke.readdir(e,{withFileTypes:!0}).catch(()=>[]),r=[];for(let n of t){if(!n.isDirectory()||n.name.startsWith("."))continue;let s=oe.join(e,n.name);await NF(s)&&r.push({repo:n.name,dir:s})}return r}async function nfe(e){let t=null,r=await Ze("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null);r&&r.code===0&&(t=Ie(r.stdout).trim()||null);let n={branch:t,url:null,state:null,title:null,labels:[],...C1(void 0)};if(!t||t==="HEAD")return n;let s=await Ze("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(Ie(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,...C1(o[0].statusCheckRollup),draft:o[0].isDraft===!0}}catch{return n}}async function sfe(){let e=yn(),r=(await ke.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 tu(oe.join(e,n)),o=await Promise.all(s.map(async({repo:a,dir:c})=>({repo:a,...await nfe(c)})));return{name:n,repos:o}}))}async function ofe(e){let t=ze("REVIEW_SLACK_TOKEN"),r=ze("REVIEW_SLACK_CHANNEL");if(!t||!r)throw new q("Slack is not configured: set WERKMEISTER_REVIEW_SLACK_TOKEN (a bot token with chat:write) and WERKMEISTER_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 q(`Slack request failed: ${o.message}`)})).json().catch(()=>({}));if(!s.ok)throw new q(`Slack rejected the message: ${s.error??"unknown error"}`);return r}function IF(e){return e.reviewDecision==="APPROVED"?"APPROVED":e.reviewDecision==="CHANGES_REQUESTED"?"CHANGES_REQUESTED":(e.latestReviews??[]).some(t=>t.state==="DISMISSED")?"DISMISSED":"PENDING"}function V1(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();ife.has(s)&&t++}return t}function C1(e){if(!Array.isArray(e)||e.length===0)return{ci:null,failingChecks:0};let t=V1(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 LF(e,t){if(!e)return!0;let r=Date.parse(e);return Number.isNaN(r)?!0:t-r<afe}function jF(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 P1(e,t){let{repo:r,number:n}=jF(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(f=>f.name??"").filter(Boolean),o=e.title??"",a=e.body??"",c=`${o} ${a} ${e.headRefName??""}`,l=we({text:c}),u=l.parseRef(c);return{url:e.url,repo:r,number:n,title:o,author:e.author?.login??"",body:a,labels:s,reviewStatus:IF(e),failingChecks:V1(e.statusCheckRollup),outOfDate:e.mergeStateStatus==="BEHIND",hasApprovalLabel:s.includes(K1),issueId:u,issueUrl:u?l.url(u):null,isDraft:e.isDraft??!1}}function DF(e,t,r,n){let s=i(c=>c.filter(l=>LF("unavailable"in l?void 0:l.updatedAt,n)),"fresh"),o=s(e).map(c=>P1(c,r)),a=s(t).map(c=>P1(c,r)).filter(c=>c.author!==r);return{me:r,mine:o,others:a}}async function cfe(){let e=await Ze("gh",["api","user","--jq",".login"]).catch(()=>null),t=e&&e.code===0?Ie(e.stdout).trim():"";if(!t)throw new q("Could not resolve GitHub user (`gh api user`). Is `gh` authenticated?");return t}async function hF(e){let t=so();if(!t)throw new q("Could not tell which GitHub org to search. Set `overrides.github_org` in the werkmeister config.");let r=await Ze("gh",["search","prs",`--owner=${t}`,"--state=open",...e,"--json","url","--limit","100"]).catch(n=>{throw new q(`gh search prs failed: ${n.message}`)});if(r.code!==0)throw new q(`gh search prs failed: ${Ie(r.stderr).trim()||`exit ${r.code}`}`);try{return JSON.parse(Ie(r.stdout).trim()||"[]").map(s=>s.url).filter(s=>!!s)}catch{return[]}}async function N1(e){let t=await Ze("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(Ie(t.stdout).trim())}catch{return{url:e,unavailable:!0}}}async function lfe(){let e=await cfe(),[t,r]=await Promise.all([hF(["--author=@me"]),hF([`--label=${K1}`])]),[n,s]=await Promise.all([Promise.all(t.map(N1)),Promise.all(r.map(N1))]);return DF(n,s,e,Date.now())}async function ufe(e){let t=await Ze("gh",["pr","review",e,"--approve"]).catch(r=>{throw new q(`gh pr review failed: ${r.message}`)});if(t.code!==0)throw new q(`gh pr review failed: ${Ie(t.stderr).trim()||`exit ${t.code}`}`);return{ok:!0}}async function FF(e){let t=we({text:e}),r=t.parseRef(e);return r?await AE(`issue-card:${r}`,ffe,async()=>await t.fetchIssue(r)??void 0)??{ref:r,url:t.url(r)??void 0}:{ref:""}}async function dfe(e){let t=[e,...(await tu(e)).map(n=>n.dir)],r=[];for(let n of t)await NF(n)&&r.push(n);return r}async function $x(e){let t=new Set;for(let r of e){let n=await Ze("git",["-C",r,"rev-parse","--path-format=absolute","--git-common-dir"]).catch(()=>null);if(n&&n.code===0){let s=Ie(n.stdout).trim();s&&t.add(oe.dirname(s))}}return[...t]}function qx(e){let t=Ie(e).trim().split(`
|
|
1224
1224
|
`);return(t.find(r=>/^\s*!\s|^(error|fatal):/.test(r))??t[0]).trim().replace(/\s+/g," ")}async function Ox(e,t=`chore: handoff ${oe.basename(e)} before workspace teardown`,r=[],n={}){let s=oe.basename(e),o=await Ze("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null),a=o&&o.code===0?Ie(o.stdout).trim():null;if(!a||a==="HEAD")return{ok:!1,message:`${s}: no branch to push (detached HEAD)`};let c=r.length?["--",...r]:[];await Ze("git",["-C",e,"add",...r.length?["-A",...c]:["-u"]]).catch(()=>{});let l=await Ze("git",["-C",e,"diff","--cached","--quiet",...c]).catch(()=>null),u=[],f=l?.code===1;if(f){let x=await Ze("git",["-C",e,"commit","-m",t,...c]).catch(()=>null);if(x?.code!==0)return{ok:!1,message:`${s}: commit failed \u2014 ${x?qx(x.stderr||x.stdout):"spawn error"}`};if(!r.length){let v=await Ze("git",["-C",e,"show","--stat","--format=","HEAD"]);u.push(` committed ${t}:`,...Ie(v.stdout).trimEnd().split(`
|
|
@@ -1372,7 +1372,7 @@ ${w.BOLD}--- Usage vs Configured Limits ---${w.RESET}
|
|
|
1372
1372
|
`);let s=` ${w.BOLD}${"Service".padEnd(30)} ${"Max Mem".padStart(8)} ${"Limit".padStart(8)} ${"CPU Lim".padStart(7)} ${"Usage".padStart(7)} ${"Status".padEnd(20)}${w.RESET}`;console.log(s),console.log(` ${"\u2500".repeat(91)}`);for(let a of n.usage)console.log(` ${a.container.padEnd(30)} ${Ni(a.maxMemMib).padStart(8)} ${(a.limit??"n/a").padStart(8)} ${(a.cpuLimit??"n/a").padStart(7)} ${a.usagePct.toFixed(0).padStart(6)}% ${Uwe[a.status]}`);console.log();let o=n.usage.filter(a=>a.status==="risk"||a.status==="over_provisioned");if(o.length){console.log(`${w.BOLD}--- Recommendations ---${w.RESET}
|
|
1373
1373
|
`);for(let a of o)a.status==="risk"?console.log(` ${w.RED}! ${a.container}${w.RESET}: Using ${a.usagePct.toFixed(0)}% of memory limit. Consider increasing to avoid OOM kills.`):console.log(` ${w.CYAN}~ ${a.container}${w.RESET}: Only using ${a.usagePct.toFixed(0)}% of memory limit. Could reduce limit to free resources.`);console.log()}if(n.recommendations.length){console.log(`${w.BOLD}--- Data-Driven Limit Recommendations ---${w.RESET}
|
|
1374
1374
|
`),console.log(` ${w.DIM}Based on observed max usage + 50% headroom:${w.RESET}
|
|
1375
|
-
`);for(let a of n.recommendations)console.log(` ${a.name.padEnd(30)} cpus: ${a.recommended_cpus.padStart(5)} memory: ${a.recommended_memory.padStart(5)}`);console.log(),console.log(` ${w.DIM}To update: edit config/services.yaml (memory_limit, memory_reservation, cpus)${w.RESET}`),console.log(` ${w.DIM}For shared infra: edit compose/shared-infra.yml (deploy.resources)${w.RESET}`)}console.log()}var Uwe,qW=C(()=>{"use strict";h();Q1();Ee();Uwe={risk:`${w.RED}RISK - near limit${w.RESET}`,moderate:`${w.YELLOW}OK - moderate${w.RESET}`,over_provisioned:`${w.CYAN}OVER-PROVISIONED${w.RESET}`,ok:`${w.GREEN}OK${w.RESET}`,no_limit:`${w.DIM}no limit set${w.RESET}`};i(Wwe,"run")});var UW={};pe(UW,{run:()=>Vwe});function Kwe(e){console.log(`${w.RED}\u2717 ${e}${w.RESET}`)}async function Vwe(e){let t=On(process.cwd(),Dr());t===null&&(L("Not inside a workspace \u2014 run this from a workspace folder or below."),process.exit(1));let r=Xn(t);if(e.action==="sync"){r.sync(t);return}let n=r.check(t);for(let s of n)Kwe(s);n.length&&(console.log(`${w.YELLOW}Context layer lags the werkmeister repo \u2014 run \`werkmeister skills sync\` (or \`werkmeister init-workspace\`) to refresh.${w.RESET}`),process.exit(1)),D(`Context layer fresh (${r.id}).`)}var WW=C(()=>{"use strict";h();xi();Xe();Ra();Ee();i(Kwe,"printDrift");i(Vwe,"run")});var KW={};pe(KW,{run:()=>Hwe});async function Hwe(e){let{dir:t,moduleCount:r,errors:n}=
|
|
1375
|
+
`);for(let a of n.recommendations)console.log(` ${a.name.padEnd(30)} cpus: ${a.recommended_cpus.padStart(5)} memory: ${a.recommended_memory.padStart(5)}`);console.log(),console.log(` ${w.DIM}To update: edit config/services.yaml (memory_limit, memory_reservation, cpus)${w.RESET}`),console.log(` ${w.DIM}For shared infra: edit compose/shared-infra.yml (deploy.resources)${w.RESET}`)}console.log()}var Uwe,qW=C(()=>{"use strict";h();Q1();Ee();Uwe={risk:`${w.RED}RISK - near limit${w.RESET}`,moderate:`${w.YELLOW}OK - moderate${w.RESET}`,over_provisioned:`${w.CYAN}OVER-PROVISIONED${w.RESET}`,ok:`${w.GREEN}OK${w.RESET}`,no_limit:`${w.DIM}no limit set${w.RESET}`};i(Wwe,"run")});var UW={};pe(UW,{run:()=>Vwe});function Kwe(e){console.log(`${w.RED}\u2717 ${e}${w.RESET}`)}async function Vwe(e){let t=On(process.cwd(),Dr());t===null&&(L("Not inside a workspace \u2014 run this from a workspace folder or below."),process.exit(1));let r=Xn(t);if(e.action==="sync"){r.sync(t);return}let n=r.check(t);for(let s of n)Kwe(s);n.length&&(console.log(`${w.YELLOW}Context layer lags the werkmeister repo \u2014 run \`werkmeister skills sync\` (or \`werkmeister init-workspace\`) to refresh.${w.RESET}`),process.exit(1)),D(`Context layer fresh (${r.id}).`)}var WW=C(()=>{"use strict";h();xi();Xe();Ra();Ee();i(Kwe,"printDrift");i(Vwe,"run")});var KW={};pe(KW,{run:()=>Hwe});async function Hwe(e){let{dir:t,moduleCount:r,errors:n}=CP();if(n.length){if(!r)L(n[0]);else{L(`${t} has ${n.length} problem(s):`);for(let s of n)O(` - ${s}`)}process.exit(1)}D(`${t} is well-formed (${r} standard module(s) checked).`)}var VW=C(()=>{"use strict";h();zn();Ee();i(Hwe,"run")});var HW={};pe(HW,{run:()=>Gwe});async function Gwe(e){if(e.action==="pr-guard"){l4();return}if(e.action==="agent-state"){g4();return}if(e.action!=="gate")return;let t;try{t=Xn(On(process.cwd(),Dr())??process.cwd())}catch{return}t.gate()}var GW=C(()=>{"use strict";h();z0();xi();Xe();_l();Ra();i(Gwe,"run")});var zW={};pe(zW,{readStdinTask:()=>Ew,run:()=>Ywe});import*as YW from"node:fs";function Ew(){if(process.stdin.isTTY)return"";try{return YW.readFileSync(0,"utf8")}catch{return""}}async function Ywe(e){try{await O1(e,void 0,{readStdinTask:Ew})}catch(t){throw t instanceof sp&&(console.log(t.message),process.exit(1)),t instanceof $r&&process.exit(1),t}}var cT=C(()=>{"use strict";h();Bx();i(Ew,"readStdinTask");i(Ywe,"run")});var ZW={};pe(ZW,{browserFormCommand:()=>QW,resolveWorkspaceInputs:()=>XW,run:()=>ebe});import*as Gi from"node:fs";import*as xs from"node:path";function zwe(e){let t=xs.relative(yn(),xs.resolve(e));return t!==""&&!t.startsWith("..")&&!xs.isAbsolute(t)}function JW(e){let t=i(r=>(r??"").split(",").filter(n=>n.trim()),"list");return Ld({services:t(e.services),repos:t(e.repos)})}async function XW(e){let t=process.cwd(),r=fa(e,t),n,s=new Set(Object.keys(r));if(process.stdin.isTTY){let o=Hl(Xv(t,r,{defaults:zwe(t)}));r=await gW(o,r,{intro:"Interactive wizard \u2014 press Ctrl-C to abort. Defaults shown in [brackets]; leave a field blank to skip it.",afterField:i(async(c,l)=>{if(c!=="issue_id"||!l.issue_id||s.has("issue_id"))return{};let u=we({text:l.issue_id}),f=u.parseRef(l.issue_id);if(!f)throw new q(`${l.issue_id} isn't a ${u.label} issue ref (e.g. ${u.refExample})`);l.issue_id=f;try{n=await Jl(f,void 0,u)}catch{throw new q(`couldn't read ${f} from ${u.label}; run \`werkmeister connect\` to check the issue tracker.`)}let d=ri({text:f})?.name,p=d?{project:d}:{};if(e.no_distill)return{task:n.title,...p};let{fields:m,warning:y}=await Kx(n);return y&&O(`Issue read; fields not pre-filled: ${y}`),{task:n.title,...m,...p}},"afterField")});let a=kw(o).filter(c=>c.key==="services"||c.key==="repos");for(let c=JW(r);c;c=JW(r)){if(!a.length)throw new q(c);N(c);for(let l of a)await _w(l,r)}}return{resolved:r,issue:n}}function Jwe(e){let t=(process.env.PATH||"").split(xs.delimiter);for(let r of t){if(!r)continue;let n=xs.join(r,e);try{return Gi.accessSync(n,Gi.constants.X_OK),n}catch{}}return null}function QW(e,t,r){let n=Object.fromEntries(Xwe.filter(o=>r[o]!=null&&r[o]!=="").map(o=>[o,Qwe.has(o)?String(r[o]).split(",").map(a=>a.trim()).filter(Boolean):r[o]])),s=[e,t];return Object.keys(n).length&&s.push("--prefill",JSON.stringify(n)),r.issue_id&&s.push("--issue",String(r.issue_id)),r.open_vscode&&s.push("--open"),s}function Zwe(e){let t=xs.join(V7(),"apps","werkmeister-dashboard","dist","form-cli.js");Gi.existsSync(t)&&Gi.statSync(t).isFile()||(L(`Browser form not built: ${t} is missing. Run \`npm --prefix apps/werkmeister-dashboard run build\` (or \`werkmeister dashboard\` once) first.`),process.exit(1));let r=Jwe("node");r||(L("`node` not found on PATH \u2014 the browser form requires Node.js."),process.exit(1));let n=QW(r,t,e),s=H(n,{stdio:"inherit"});process.exit(s.status)}async function ebe(e){if(e.browser_form){Zwe(e);return}try{let{resolved:t,issue:r}=await XW(e);await q1(t,{live:!0,open:!!e.open_vscode,cwd:process.cwd(),issue:r,distill:e.no_distill||r?!1:void 0,readStdinTask:Ew,force:!!e.force})}catch(t){throw t instanceof $r&&process.exit(1),t instanceof q&&(L(t.message),process.exit(1)),t}}var Xwe,Qwe,eK=C(()=>{"use strict";h();os();Q();jd();dx();yr();mt();Bx();wr();Ee();Tc();cT();i(zwe,"insideWorkspacesRoot");i(JW,"wizardRepoError");i(XW,"resolveWorkspaceInputs");i(Jwe,"which");Xwe=["feature","issue_id","services","repos","labels","task","test_path","description","starting_prompt","work_type","context_strategy","autonomous","model","auto_stop"],Qwe=new Set(["services","repos"]);i(QW,"browserFormCommand");i(Zwe,"runBrowserForm");i(ebe,"run")});var tK={};pe(tK,{run:()=>tbe});async function tbe(e){let{root:t,workspaces:r}=await eu();if(console.log(`
|
|
1376
1376
|
${w.BOLD}=== Workspaces in ${t} ===${w.RESET}
|
|
1377
1377
|
`),!r.length){console.log(` ${w.DIM}No workspaces. Create one with: werkmeister workspace <feature>${w.RESET}
|
|
1378
1378
|
`);return}console.log(` ${w.BOLD}${"Workspace".padEnd(32)} ${"Issue".padEnd(12)} Labels${w.RESET}`),console.log(` ${"\u2500".repeat(70)}`);for(let{name:n,issueId:s,labels:o}of r){let a=s?s.padEnd(12):`${w.DIM}--${w.RESET}${" ".repeat(10)}`;console.log(` ${n.padEnd(32)} ${a} ${w.DIM}${o.join(", ")}${w.RESET}`)}console.log(),console.log(` ${w.DIM}End one with: werkmeister close-out <name>${w.RESET}`),console.log()}var rK=C(()=>{"use strict";h();os();Ee();i(tbe,"run")});var aK={};pe(aK,{newIssueFromArgs:()=>iK,run:()=>nbe,updateFromArgs:()=>oK});import*as sK from"node:fs";function oK(e){let t=e.status||void 0,r=e.comment||void 0;return!t&&!r?"Nothing to update: pass --status <name> and/or --comment <text>.":{status:t,comment:r}}function iK(e,t=r=>sK.readFileSync(r,"utf8")){let r=(e.project??"").trim().toUpperCase(),n=e.type??"",s=(e.title??"").trim(),o=e.bodyFile??"";if(!r)return"Pass --project <key> (the Jira project to file in).";if(!nK.includes(n))return`Pass --type ${nK.join("|")} (got '${n}').`;if(!s)return"Pass --title <text>.";if(!o)return"Pass --body-file <path> (or - for stdin).";let a;try{a=t(o==="-"?0:o)}catch(c){return`Could not read --body-file ${o}: ${c.message}`}return{project:r,type:n,title:s,body:a}}function dn(e){L(e),process.exit(1)}async function rbe(e){let t=jr();t.length||dn("no project: add one under projects: in ~/.werkmeister/config.yaml (docs/users-guide.md \xA7 Projects)");let r=On(process.cwd(),Dr()),n=e.project||(r===null?"":io($t(r,null))),s=n?t.find(c=>c.name===n):Af()??(t.length===1?t[0]:void 0),o=t.map(c=>c.name).join(", ");s||dn(n?`no project '${n}' (one of: ${o})`:`pass --project (one of: ${o})`);let a;try{a=await we({project:s.name}).listReady(s.board)}catch(c){dn(`Could not list ready work in ${s.name}: ${c.message}`)}if(e.json)console.log(JSON.stringify(a,null,2));else if(!a.length)D(`Nothing ready in ${s.name}.`);else for(let c of a)console.log(`${c.ref} ${c.status??""} ${c.title??""}`)}async function nbe(e){if(e.action==="ready")return rbe(e);if(e.action==="create"){let l=String(e.project??"").toUpperCase(),u=jr().some(d=>d.tracker==="jira"&&d.scope.project===l)?Ss("jira"):we();u.createIssue||dn(`${u.label} issues are filed with its own CLI: gh issue create -R <owner>/<repo>.`);let f=iK(e);typeof f=="string"&&dn(f);try{let d=await u.createIssue(f);D(`Created ${d.ref} (${d.type}).`),console.log(d.url??d.ref)}catch(d){dn(`Could not create the issue in ${f.project}: ${d.message}`)}return}if(e.action==="start"){let l=On(process.cwd(),Dr());l===null&&dn("Not inside a workspace \u2014 run this from a workspace folder or below.");let u=await Z5(l)||"left as is (no in_progress status configured)";(u.includes("not moved")?N:D)(`Issue: ${u}`);return}let t=e.action==="update"?oK(e):null;typeof t=="string"&&dn(t);let r=e.ref??"",n="";if(!r){let l=On(process.cwd(),Dr());l===null&&dn("No issue given and not inside a workspace.");let u=$t(l,null);r=vn(u),n=io(u),r||dn("No issue given and this workspace has no issue (issue_id in .werkmeister/workspace.yml).")}let s=we({project:n,text:r}),o=s.parseRef(r);if(o||dn(`'${r}' is not a ${s.label} issue ID (e.g. ${s.refExample}).`),t){try{await s.updateIssue(o,t)}catch(u){dn(`Could not update ${o}: ${u.message}`)}let l=[t.status&&`status \u2192 ${t.status}`,t.comment&&"comment added"].filter(Boolean);D(`Updated ${o}: ${l.join(", ")}.`);return}let a=[],c=await s.fetchIssue(o,a);c||dn(`Could not read ${o} from ${s.label}${a.length?`: ${a.join("; ")}`:""}.`),console.log(e.json?JSON.stringify(c,null,2):rl(c))}var nK,cK=C(()=>{"use strict";h();xi();Xe();zE();yr();sa();wr();Ee();i(oK,"updateFromArgs");nK=["bug","feature","task"];i(iK,"newIssueFromArgs");i(dn,"fail");i(rbe,"ready");i(nbe,"run")});var lK={};pe(lK,{run:()=>sbe});async function sbe(e){let t=e.name;if(N('werkmeister remove-workspace is deprecated \u2014 use `werkmeister close-out --abandon "<reason>"`'),console.log(`
|