werkmeister 0.82.0 → 0.82.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +3 -3
- package/dist/mcp.js +44 -44
- package/dist/werkmeister-workspaces.vsix +0 -0
- package/package.json +3 -3
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 BZ=Object.create;var z0=Object.defineProperty;var qZ=Object.getOwnPropertyDescriptor;var UZ=Object.getOwnPropertyNames;var WZ=Object.getPrototypeOf,HZ=Object.prototype.hasOwnProperty;var i=(e,t)=>z0(e,"name",{value:t,configurable:!0}),se=(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 A=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),oe=(e,t)=>{for(var r in t)z0(e,r,{get:t[r],enumerable:!0})},KZ=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of UZ(t))!HZ.call(e,s)&&s!==r&&z0(e,s,{get:()=>t[s],enumerable:!(n=qZ(t,s))||n.enumerable});return e};var _e=(e,t,r)=>(r=e!=null?BZ(WZ(e)):{},KZ(t||!e||!e.__esModule?z0(r,"default",{value:e,enumerable:!0}):r,e));var v,h=A(()=>{v={sha:"
|
|
4
|
+
var BZ=Object.create;var z0=Object.defineProperty;var qZ=Object.getOwnPropertyDescriptor;var UZ=Object.getOwnPropertyNames;var WZ=Object.getPrototypeOf,HZ=Object.prototype.hasOwnProperty;var i=(e,t)=>z0(e,"name",{value:t,configurable:!0}),se=(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 A=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),oe=(e,t)=>{for(var r in t)z0(e,r,{get:t[r],enumerable:!0})},KZ=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of UZ(t))!HZ.call(e,s)&&s!==r&&z0(e,s,{get:()=>t[s],enumerable:!(n=qZ(t,s))||n.enumerable});return e};var _e=(e,t,r)=>(r=e!=null?BZ(WZ(e)):{},KZ(t||!e||!e.__esModule?z0(r,"default",{value:e,enumerable:!0}):r,e));var v,h=A(()=>{v={sha:"73b838807c6512d586f5baa067fc774a3dc98656",dirty:!1}});var Wd=T(rS=>{h();var J0=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}},tS=class extends J0{static{i(this,"InvalidArgumentError")}constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};rS.CommanderError=J0;rS.InvalidArgumentError=tS});var X0=T(sS=>{h();var{InvalidArgumentError:VZ}=Wd(),nS=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.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:(r.push(t),r)}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 VZ(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function YZ(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}i(YZ,"humanReadableArgName");sS.Argument=nS;sS.humanReadableArgName=YZ});var aS=T(iS=>{h();var{humanReadableArgName:zZ}=X0(),oS=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=>zZ(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=[];if(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){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return 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}formatItemList(t,r,n){return r.length===0?[]:[n.styleTitle(t),...r,""]}groupItems(t,r,n){let s=new Map;return t.forEach(o=>{let a=n(o);s.has(a)||s.set(a,[])}),r.forEach(o=>{let a=n(o);s.has(a)||s.set(a,[]),s.get(a).push(o)}),s}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))));if(a=a.concat(this.formatItemList("Arguments:",l,r)),this.groupItems(t.options,r.visibleOptions(t),d=>d.helpGroupHeading??"Options:").forEach((d,p)=>{let m=d.map(w=>o(r.styleOptionTerm(r.optionTerm(w)),r.styleOptionDescription(r.optionDescription(w))));a=a.concat(this.formatItemList(p,m,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(p=>o(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));a=a.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(t.commands,r.visibleCommands(t),d=>d.helpGroup()||"Commands:").forEach((d,p)=>{let m=d.map(w=>o(r.styleSubcommandTerm(r.subcommandTerm(w)),r.styleSubcommandDescription(r.subcommandDescription(w))));a=a.concat(this.formatItemList(p,m,r))}),a.join(`
|
|
5
5
|
`)}displayWidth(t){return kI(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(`
|
|
@@ -286,7 +286,7 @@ Then output ONLY <result>{"ok":true}</result>, or <result>{"ok":false,"error":"<
|
|
|
286
286
|
`)}function HE(e={}){let t=e.project?.toUpperCase();return{id:"jira",label:"Jira",refExample:"PROJ-123",refPattern:null,issueTypes:lD,parseRef:i(r=>fie.exec(r??"")?.[0].toUpperCase()??null,"parseRef"),slug:i(r=>r.trim().toLowerCase(),"slug"),holds:i(r=>!t||r.toUpperCase().startsWith(`${t}-`),"holds"),url:Uy,async fetchIssue(r,n){let s=await QL(r,n);if(s)return iD(s);let o=await pie(r);return o||n?.push("the Atlassian MCP fallback returned no issue"),o},async fetchIssues(r){if(!r.length)return{};let n=await ZL(r)??await hie(r),s={};for(let[o,a]of Object.entries(n))s[o]={ref:o,status:a,url:Uy(o)??void 0};return s},filingGuide(r,n="<workspace>"){let s=/^([A-Z][A-Z0-9]+)-\d+$/.exec(r)?.[1]??t,o=Mj(),a=(Xo().base_url??"").trim().replace(/\/+$/,""),c=ha(a)||!a?"":` (${a})`,l=i(m=>`\`werkmeister issue create --project ${m??"<KEY>"} --type <type> --title "<title>" --body-file <file> [--relates <issue>]\`; `+(r?`pass \`--relates ${r}\` for a follow-up from this run; `:"")+"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"),u=i((m,w)=>`JQL \`${m?`project = ${m} AND `:""}text ~ "${w}"\``,"jql"),f=i(m=>`${u(m,"<keywords>")}, then ${u(m,n)}`,"both"),d=i(m=>`\`gh issue list -R ${yie} --search "${m}" --state all\``,"gh");return{row:`| app code in a worktree | ${`Jira${s?`, project \`${s}\``:" \u2014 ask the person which project"}${c}`} | ${l(s)} |`,werkmeister:o?{where:`Jira, project \`${o}\`${c}`,command:l(o)}:void 0,search:`Search first: ${f(s)}: other sessions file from the same review and exercise files, and an issue filed from this workspace names it. If it exists, comment on it instead. (Werkmeister issues: ${o?f(o):`${d("<keywords>")}, then ${d(n)}`}.)`}},async createIssue({project:r,type:n,title:s,body:o}){let a=await nD({project:r,issueType:lD[n],fallbackLabel:n,summary:s,description:aD(o)});if(!a)throw new Error(cD);return{ref:a.key,title:s,type:a.issueType,url:a.url}},async linkIssue(r,n){if(!await sD(r,n))throw new Error(cD)},async listReady(r){if(!r&&!t)throw new Error("no Jira project in scope");let n=r?await rD(r.id,r.ready):await tD(`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(iD)},async updateIssue(r,n){let s=n.comment?{...n,comment:aD(n.comment)}:n;await oD(r,s)===null&&await mie(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 XL();if(n)return{ok:!0,who:n.who,fix:""};let s=Xo();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&&ha(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 fie,wr,die,fD,dD,gie,yie,cD,lD,pD,KE=A(()=>{"use strict";h();Ye();Zp();WE();fie=/[A-Za-z][A-Za-z0-9]+-\d+/;i(Uy,"jiraBrowseUrl");i(uD,"jiraSiteRef");i(Wy,"jiraSitePhrase");wr=i(e=>typeof e=="string"&&e.trim()?e.trim():void 0,"str"),die=["new","indeterminate","done"],fD=i(e=>die.find(t=>t===wr(e)?.toLowerCase()),"category");i(iD,"fromRest");dD="Do not create, edit, transition, or comment on anything; write no prose outside the tags.";i(pie,"fetchViaMcp");i(hie,"statusesViaMcp");i(mie,"updateViaMcp");gie=i(e=>`{{${e.replace(/([-{}!*_+^~[\]|#])/g,"\\$1")}}}`,"monoEscape");i(aD,"markdownToWiki");yie="jbbz-sandbox/werkmeister",cD="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",lD={bug:"Bug",feature:"Story",task:"Task"};i(HE,"jiraTracker");pD=HE()});function po(e){return yD[e]}function eh(e){let t=(e??Pe()).overrides?.issue_tracker;return ao.includes(t)?t:"jira"}function th(e){return wie[e.tracker](e.scope)}function ga(e={}){let t=mn();if(!t.length)return null;let r=e.project?.trim();if(r){let n=t.find(s=>s.name===r);return n||(hD.has(r)||(hD.add(r),C(`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=th(n),o=s.parseRef(e.text);if(o&&s.holds(o))return n}return null}function rh(){let e=mn().filter(t=>t.default);return e.length===1?e[0]:null}function ke(e){let t=e?ga(e):null;return t?th(t):yD[eh()]}function Hy(e,t=""){let r=mn();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??ga({text:e})??rh();if(!o)throw new Error(`${e} isn't in any project's scope; pass --project (one of: ${n})`);let a=th(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 si(e){return Fc(e?.project)}function oi(e){return Fc(e?.issue_id)||Fc(e?.jira_id)||Fc(e?.github_issue)}function Uu(e){let t=oi(e);if(!t)return[];let r=e?.group,n=Array.isArray(r)?r:String(r??"").split(",");return[...new Set([t,...n.map(s=>String(s).trim()).filter(Boolean)])]}function ya(e){return Fc(e.ISSUE_ID)||Fc(e.JIRA_ID)||Fc(e.GITHUB_ISSUE)}function wD(e){let t=ya(e);return t?[t,ke().url(t)]:null}function Wu(e,t={}){let r=[`${e.ref}: ${e.title??"(no title)"}`],n=[e.status&&`Status: ${e.status}`,e.type&&`Type: ${e.type}`,e.assignee&&`Assignee: ${e.assignee}`].filter(Boolean);if(n.length&&r.push(n.join(" \xB7 ")),e.description){let o=e.description,a=t.full?0:Math.max(0,o.length-mD);r.push("","Description:",a?o.slice(0,mD):o),a&&r.push(`[cut: ${a} more characters not shown]`)}let s=e.comments??[];if(s.length){r.push("",`Comments (last ${Math.min(s.length,gD)} of ${s.length}):`);for(let o of s.slice(-gD)){let a=o.created?` ${o.created.slice(0,10)}`:"";r.push(`- [${o.author}${a}] ${o.body.slice(0,xie)}`)}}return r.join(`
|
|
287
287
|
`)}var yD,wie,hD,Fc,mD,gD,xie,Ar=A(()=>{"use strict";h();Ye();qE();KE();ay();bc();ge();qE();KE();ay();yD={jira:pD,github:zL};i(po,"trackerById");i(eh,"loadIssueTracker");wie={jira:HE,github:BE};i(th,"projectTracker");hD=new Set;i(ga,"projectFor");i(rh,"defaultProject");i(ke,"issueTracker");i(Hy,"projectForIssue");Fc=i(e=>typeof e=="string"?e.trim():"","str");i(si,"projectOf");i(oi,"issueIdOf");i(Uu,"issueRefsOf");i(ya,"issueIdOfMeta");i(wD,"issueLink");mD=4e3,gD=10,xie=1e3;i(Wu,"issueBriefing")});var xn,Ky=A(()=>{"use strict";h();xn=["icm","jit"]});import*as ls from"node:fs";import*as GE from"node:os";import*as cs from"node:path";function kie(e){try{return ls.statSync(e).isDirectory()}catch{return!1}}function bie(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]!==`
|
|
288
288
|
`;)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 Vy(e){let t=ls.readFileSync(e,"utf8"),r=cs.extname(e);return r===".yaml"||r===".yml"?kD.parse(t):JSON.parse(bie(t))}function In(e){return/^(true|1|yes|on)$/i.test(String(e??"").trim())}function Mc(e){return In(wa(e,"autonomous"))}function nh(e){let t=wa(e,"auto_stop");return t==null||t===""?Mc(e):In(t)}function bD(e){let t=wa(e,"model");return typeof t=="string"&&t.trim()?t.trim():null}function wa(e,t){let r=Ae("WORKSPACE_CONFIG"),n=[...r?[Hu(r)]:[],...Gu.map(s=>cs.join(W(e),s))];for(let s of n)if(ls.existsSync(s))try{return Vy(s)?.[t]}catch{return}}function Dt(e,t){let r=[];t&&r.push(Hu(t));let n=Ae("WORKSPACE_CONFIG");n&&r.push(Hu(n));let s=W(e);for(let o of Gu)r.push(cs.join(s,o));for(let o of r){if(!ls.existsSync(o))continue;let a;try{a=Vy(o)}catch(c){return C(`Config file ${o} unreadable: ${c.message} \u2014 skipping.`),{}}return typeof a!="object"||a===null||Array.isArray(a)?(C(`Config file ${o} must be a mapping \u2014 skipping.`),{}):(O(`Loaded workspace config from ${o}`),a)}return{}}function Hu(e){return e==="~"?GE.homedir():e.startsWith("~/")?cs.join(GE.homedir(),e.slice(2)):e}function vD(e){return/['"$#\\]/.test(e)?`"${e.replace(/[\\"$]/g,"\\$&")}"`:e}function VE(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\([\\"$])/g,"$1"):e}function vie(e){let t=cs.join(e,".env");if(!(ls.existsSync(t)&&ls.statSync(t).isFile()))return{};let r={};for(let[,,s]of Ku)r[s.toUpperCase()]=s;r.JIRA_ID=r.GITHUB_ISSUE="issue_id";let n={};for(let s of ls.readFileSync(t,"utf8").split(`
|
|
289
|
-
`)){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]]=VE(c.trim()))}return n}function Bc(e,t){let r=Dt(t,e.config_file??null),n=vie(t),s={};for(let[a,c,l]of Ku){let u=e[a]??null,f=c?Ae(c)??null:null,d=l==="issue_id"?oi(r)||null:l in r?r[l]:null,p=l in n?n[l]:null;for(let m of[u,f,d,p]){if(m==null)continue;let w;if(Array.isArray(m)?w=m.map(g=>String(g).trim()).filter(g=>g).join(","):w=String(m).trim(),w){s[l]=w;break}}}let o=i(()=>ke({project:s.project,text:s.issue_id??""}),"tracker");if(s.issue_id&&(s.issue_id=o().parseRef(s.issue_id)??s.issue_id),s.group){let a=o(),c=[...new Set(s.group.split(",").map(l=>a.parseRef(l)??l))].filter(l=>l!==s.issue_id);s.group=c.join(",")}return s.autonomous&&(s.autonomous=String(In(s.autonomous))),s.auto_stop&&(s.auto_stop=String(In(s.auto_stop))),s}function Sie(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 _ie(e){for(let t of ls.readdirSync(e).sort()){let r=cs.join(e,t);if(!kie(r)||t.startsWith("."))continue;let n;try{n=H(["git","-C",r,"branch","--show-current"],{capture:!0,timeout:5})}catch(a){if(a instanceof ne&&(a.code==="ENOENT"||a.code==="ETIMEDOUT"))continue;throw a}if(n.status!==0)continue;let s=n.stdout.trim(),o=ke({text:s}).parseRef(s);if(o)return o}return""}function qc(e){let t=e.trim().toLowerCase();return Object.hasOwn(Gy,t)?Gy[t]:YE}function Yy(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 $ie(){let e=mn();if(e.length){let r=[...new Set(e.map(n=>po(n.tracker).refExample))];return xD.map(n=>n.key==="issue_id"?{...n,placeholder:r.join(" or ")}:n)}let t=ke();return xD.flatMap(r=>r.key==="project"?[]:r.key==="issue_id"?[{...r,placeholder:t.refExample,...t.refPattern?{pattern:t.refPattern}:{}}]:[r])}function Oie(e,t,r={}){return{workspace_root:e,workspace_name:cs.basename(e),prompts:$ie().map(n=>Yy(n,e,t,r))}}function zE(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 Nn(){try{return[ae(),pn()]}catch{return[{},{}]}}function SD(e,t,r={}){return JE(t,Bc(e,t),r)}function JE(e,t,r={}){let n=Oie(e,t,r),s=Yy(Tie,"",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 kD,Ku,Gu,Gy,YE,Eie,xD,Tie,er=A(()=>{"use strict";h();kD=_e(Ve(),1);An();Q();Qp();Ar();ut();bc();ge();Ky();i(kie,"isDir");i(bie,"stripJsoncComments");i(Vy,"loadWorkspaceConfig");Ku=[["feature",null,"feature"],["work_type","WORK_TYPE","work_type"],["context_strategy","CONTEXT_STRATEGY","context_strategy"],["harness","HARNESS","harness"],["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"],["group","GROUP","group"],["autonomous","AUTONOMOUS","autonomous"],["model","MODEL","model"],["auto_stop","AUTO_STOP","auto_stop"]];i(In,"isTrue");i(Mc,"readAutonomous");i(nh,"readAutoStop");i(bD,"readModel");i(wa,"readWorkspaceField");Gu=["workspace.yml","workspace.yaml","workspace.jsonc","workspace.json"];i(Dt,"loadConfigFile");i(Hu,"expandUserPath");i(vD,"quoteEnvValue");i(VE,"unquoteEnvValue");i(vie,"loadExistingEnvMetadata");i(Bc,"resolveInputs");i(Sie,"defaultFeatureFromDir");i(_ie,"scrapeIssueId");Gy={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"}},YE={path:"architectural",phases:["research","implement","test","review","pr"],gate:null,hint:"invoke `w9r-research` first"};i(qc,"planFor");Eie=Object.keys(Gy),xD=[{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=>_ie(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(()=>mn().map(e=>e.name),"choicesFn"),defaultFn:i(()=>rh()?.name??"","defaultFn")},{key:"feature",label:"Feature name",help:`Lowercase, hyphen-separated. Drives workspace slot routing via the X-Feature cookie. No feature = no ${Te} / werkmeister-context.md.`,acceptEmpty:!1,recommended:!0,pattern:"^[a-z0-9]+(-[a-z0-9]+)*$",placeholder:"mdx-blog",defaultFn:i(e=>Sie(cs.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(Gy).join("|")+")$",default:"feature",choicesFn:i(()=>[...Eie],"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:"^("+xn.join("|")+")$",default:xn[0],choicesFn:i(()=>[...xn],"choicesFn")},{key:"harness",label:"Harness",help:"Which agent harness reads this workspace: claude (Claude Code: CLAUDE.md, .claude/, hooks), mcp (any harness with MCP and skills: AGENTS.md, .agents/skills, no hooks) or codex (Codex CLI: AGENTS.md, .agents/skills, .codex/hooks.json, .codex/config.toml).",pattern:"^("+Vr.join("|")+")$",default:Vr[0],choicesFn:i(()=>[...Vr],"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 internal session-end`, which stops this feature's containers (slot and volumes kept; `werkmeister feature 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(Nn()[0]).sort(),"choicesFn"),choiceGroupsFn:i(()=>Object.fromEntries(Object.entries(Nn()[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:"group",label:"Grouped PR members",help:"Comma-separated issue keys this workspace's PR also covers, led by its issue: one PR, one commit per ticket. Blank for a one-ticket PR.",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=>zE(cs.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(Yy,"promptEntry");i($ie,"wizardPrompts");i(Oie,"buildPromptSpec");i(zE,"slugToTask");i(Nn,"loadSandboxServiceConfigs");Tie={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(pn()).sort(),"choicesFn")};i(SD,"computePromptSpec");i(JE,"workspacePromptSpec")});var Rie,XE,Aie,xa,sh,QE=A(()=>{"use strict";h();Rie=["mcp__plugin_werkmeister_werkmeister__"],XE=i(e=>Rie.map(t=>`${t}${e}`),"pluginTool"),Aie=["werkmeister","w9r"],xa=i(e=>Aie.map(t=>`Bash(${t} ${e})`),"cli"),sh=[...["proxy-reload","down","remove","remove-workspace","clean","setup","registry","connect","intercept","notes graduate","up infra","restart infra","stop infra","infra proxy-reload","feature down","infra down","feature drop","machine clean","machine setup","infra connect","infra intercept","workspace new","ws new","infra up","infra restart","infra stop","daemon install","daemon uninstall","daemon restart"].flatMap(e=>xa(`${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(XE)]});var zy,ZE=A(()=>{"use strict";h();co();zy={id:"mcp",instructionsFile:"AGENTS.md",skillsDir:".agents/skills",hooks:{available:!1,reason:"a generic MCP harness has no hooks adapter; use harness: codex for Codex"},agents:!1,notice:i(()=>`
|
|
289
|
+
`)){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]]=VE(c.trim()))}return n}function Bc(e,t){let r=Dt(t,e.config_file??null),n=vie(t),s={};for(let[c,l,u]of Ku){let f=e[c]??null,d=l?Ae(l)??null:null,p=u==="issue_id"?oi(r)||null:u in r?r[u]:null,m=u in n?n[u]:null;for(let w of[f,d,p,m]){if(w==null)continue;let g;if(Array.isArray(w)?g=w.map(y=>String(y).trim()).filter(y=>y).join(","):g=String(w).trim(),g){s[u]=g;break}}}let o=e.services;!s.services&&o!==null&&o!==void 0&&!String(o).trim()&&(s.services="");let a=i(()=>ke({project:s.project,text:s.issue_id??""}),"tracker");if(s.issue_id&&(s.issue_id=a().parseRef(s.issue_id)??s.issue_id),s.group){let c=a(),l=[...new Set(s.group.split(",").map(u=>c.parseRef(u)??u))].filter(u=>u!==s.issue_id);s.group=l.join(",")}return s.autonomous&&(s.autonomous=String(In(s.autonomous))),s.auto_stop&&(s.auto_stop=String(In(s.auto_stop))),s}function Sie(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 _ie(e){for(let t of ls.readdirSync(e).sort()){let r=cs.join(e,t);if(!kie(r)||t.startsWith("."))continue;let n;try{n=H(["git","-C",r,"branch","--show-current"],{capture:!0,timeout:5})}catch(a){if(a instanceof ne&&(a.code==="ENOENT"||a.code==="ETIMEDOUT"))continue;throw a}if(n.status!==0)continue;let s=n.stdout.trim(),o=ke({text:s}).parseRef(s);if(o)return o}return""}function qc(e){let t=e.trim().toLowerCase();return Object.hasOwn(Gy,t)?Gy[t]:YE}function Yy(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 $ie(){let e=mn();if(e.length){let r=[...new Set(e.map(n=>po(n.tracker).refExample))];return xD.map(n=>n.key==="issue_id"?{...n,placeholder:r.join(" or ")}:n)}let t=ke();return xD.flatMap(r=>r.key==="project"?[]:r.key==="issue_id"?[{...r,placeholder:t.refExample,...t.refPattern?{pattern:t.refPattern}:{}}]:[r])}function Oie(e,t,r={}){return{workspace_root:e,workspace_name:cs.basename(e),prompts:$ie().map(n=>Yy(n,e,t,r))}}function zE(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 Nn(){try{return[ae(),pn()]}catch{return[{},{}]}}function SD(e,t,r={}){return JE(t,Bc(e,t),r)}function JE(e,t,r={}){let n=Oie(e,t,r),s=Yy(Tie,"",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 kD,Ku,Gu,Gy,YE,Eie,xD,Tie,er=A(()=>{"use strict";h();kD=_e(Ve(),1);An();Q();Qp();Ar();ut();bc();ge();Ky();i(kie,"isDir");i(bie,"stripJsoncComments");i(Vy,"loadWorkspaceConfig");Ku=[["feature",null,"feature"],["work_type","WORK_TYPE","work_type"],["context_strategy","CONTEXT_STRATEGY","context_strategy"],["harness","HARNESS","harness"],["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"],["group","GROUP","group"],["autonomous","AUTONOMOUS","autonomous"],["model","MODEL","model"],["auto_stop","AUTO_STOP","auto_stop"]];i(In,"isTrue");i(Mc,"readAutonomous");i(nh,"readAutoStop");i(bD,"readModel");i(wa,"readWorkspaceField");Gu=["workspace.yml","workspace.yaml","workspace.jsonc","workspace.json"];i(Dt,"loadConfigFile");i(Hu,"expandUserPath");i(vD,"quoteEnvValue");i(VE,"unquoteEnvValue");i(vie,"loadExistingEnvMetadata");i(Bc,"resolveInputs");i(Sie,"defaultFeatureFromDir");i(_ie,"scrapeIssueId");Gy={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"}},YE={path:"architectural",phases:["research","implement","test","review","pr"],gate:null,hint:"invoke `w9r-research` first"};i(qc,"planFor");Eie=Object.keys(Gy),xD=[{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=>_ie(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(()=>mn().map(e=>e.name),"choicesFn"),defaultFn:i(()=>rh()?.name??"","defaultFn")},{key:"feature",label:"Feature name",help:`Lowercase, hyphen-separated. Drives workspace slot routing via the X-Feature cookie. No feature = no ${Te} / werkmeister-context.md.`,acceptEmpty:!1,recommended:!0,pattern:"^[a-z0-9]+(-[a-z0-9]+)*$",placeholder:"mdx-blog",defaultFn:i(e=>Sie(cs.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(Gy).join("|")+")$",default:"feature",choicesFn:i(()=>[...Eie],"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:"^("+xn.join("|")+")$",default:xn[0],choicesFn:i(()=>[...xn],"choicesFn")},{key:"harness",label:"Harness",help:"Which agent harness reads this workspace: claude (Claude Code: CLAUDE.md, .claude/, hooks), mcp (any harness with MCP and skills: AGENTS.md, .agents/skills, no hooks) or codex (Codex CLI: AGENTS.md, .agents/skills, .codex/hooks.json, .codex/config.toml).",pattern:"^("+Vr.join("|")+")$",default:Vr[0],choicesFn:i(()=>[...Vr],"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 internal session-end`, which stops this feature's containers (slot and volumes kept; `werkmeister feature 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(Nn()[0]).sort(),"choicesFn"),choiceGroupsFn:i(()=>Object.fromEntries(Object.entries(Nn()[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:"group",label:"Grouped PR members",help:"Comma-separated issue keys this workspace's PR also covers, led by its issue: one PR, one commit per ticket. Blank for a one-ticket PR.",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=>zE(cs.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(Yy,"promptEntry");i($ie,"wizardPrompts");i(Oie,"buildPromptSpec");i(zE,"slugToTask");i(Nn,"loadSandboxServiceConfigs");Tie={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(pn()).sort(),"choicesFn")};i(SD,"computePromptSpec");i(JE,"workspacePromptSpec")});var Rie,XE,Aie,xa,sh,QE=A(()=>{"use strict";h();Rie=["mcp__plugin_werkmeister_werkmeister__"],XE=i(e=>Rie.map(t=>`${t}${e}`),"pluginTool"),Aie=["werkmeister","w9r"],xa=i(e=>Aie.map(t=>`Bash(${t} ${e})`),"cli"),sh=[...["proxy-reload","down","remove","remove-workspace","clean","setup","registry","connect","intercept","notes graduate","up infra","restart infra","stop infra","infra proxy-reload","feature down","infra down","feature drop","machine clean","machine setup","infra connect","infra intercept","workspace new","ws new","infra up","infra restart","infra stop","daemon install","daemon uninstall","daemon restart"].flatMap(e=>xa(`${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(XE)]});var zy,ZE=A(()=>{"use strict";h();co();zy={id:"mcp",instructionsFile:"AGENTS.md",skillsDir:".agents/skills",hooks:{available:!1,reason:"a generic MCP harness has no hooks adapter; use harness: codex for Codex"},agents:!1,notice:i(()=>`
|
|
290
290
|
## Harness
|
|
291
291
|
|
|
292
292
|
This workspace was generated for the \`mcp\` harness. Werkmeister's tools come from the MCP server \`werkmeister\` at ${Np()}/mcp (how to register it: docs/harnesses.md in the werkmeister repo). Hooks are unavailable on this harness: werkmeister's session-start context, standards gate, PR guard and agent state do not run here (Codex: use \`harness: codex\`). Open PRs only with \`werkmeister pr open\`.
|
|
@@ -1641,7 +1641,7 @@ If the content is unusable, output <result>{}</result> and nothing else.
|
|
|
1641
1641
|
Issue content:
|
|
1642
1642
|
\`\`\`
|
|
1643
1643
|
`+s+"\n```"}async function Cbe(e,t){let r=[...new Set(e.map(c=>ke({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=ga({text:f})?.name??"";l.set(d,[...l.get(d)??[],f])}let u={};for(let[f,d]of l){let p=ke(f?{project:f}:void 0);for(let[m,w]of Object.entries(await p.fetchIssues(d)))w.status&&(u[m]=w.status)}return u},"fetchStatuses"),s={},o=[],a=[];if(t?.refresh)o.push(...r);else for(let c of r){let l=await $O(`status:${c}`);if(!l){o.push(c);continue}s[c]=l.v,Date.now()-l.at>=Abe&&a.push(c)}if(a.length&&OO(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 xl(`status:${u}`,f)}),o.length)for(let[c,l]of Object.entries(await n(o)))s[c]=l,await xl(`status:${c}`,l);return s}function Pbe(e){let t={};for(let r of $be){let n=e[r];if(typeof n!="string")continue;let s=n.trim();s&&(r==="feature"&&!Obe.test(s)||(t[r]=s))}return t}function Ibe(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 Hm(e){try{let t=await pt.readFile(be.join(W(e),"workspace.yml"),"utf-8"),r=(0,lb.parse)(t),n=oi(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=In(r?.autonomous),l=r?.auto_stop,u=l==null||l===""?c:In(l);return{issueId:n,project:si(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 WT(e){return I$({name:be.basename(e),...await Hm(e)})}async function sd(){let e=un(),t;try{t=await pt.readdir(e,{withFileTypes:!0})}catch(s){throw new B(`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=be.join(e,s),{issueId:a,project:c,labels:l,model:u,task:f,workType:d}=await Hm(o);return{name:s,path:o,vscodeUri:`vscode://file${o.split(be.sep).map(encodeURIComponent).join("/")}`,issueId:a,issueUrl:a?ke({project:c,text:a}).url(a):null,labels:l,model:u,task:f,workType:d,lifecycle:Rl(o).state}}));return{root:e,workspaces:n}}function Nbe(){let e=[...new Set(mn().map(t=>t.tracker))];return e.length?e.length===1?po(e[0]).label:"tracker":ke().label}async function jbe(){let e;try{e=Hf(SD({},Wm.homedir(),{defaults:!1}))}catch(n){throw new B(`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:Nbe()}},{schema:e.schema,uiSchema:t,formData:e.formData,title:e.title??"Initialize workspace"}}function lK(e){return"--"+e.replace(/_/g,"-")}function kK(e){let t=String(e.feature??"").trim();if(!t)throw new B("A feature name is required (pass it as an argument, set it in ./.werkmeister/workspace.yml, or run interactively).");let r=["workspace","new",t];for(let[n,s]of Object.entries(e)){if(n==="feature"||Lbe.has(n))continue;if(s===!0){r.push(lK(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(lK(n),o)}return r}async function Fbe(){for(let e of Dbe)if(await as(e))return e;return null}async function bK(e){let t=await Fbe();if(!t)return{opened:!1,note:"VS Code CLI ('code') not found \u2014 open the workspace folder manually."};try{return xbe(t,[e],{detached:!0,stdio:"ignore"}).unref(),{opened:!0}}catch(r){return{opened:!1,note:`Could not launch VS Code: ${r.message}`}}}async function ub(e,t=r=>Pn().ask(r)){let r=Wu({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 xK(po(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 UT({},n),o={};for(let a of Mbe){let c=s[a];typeof c=="string"&&c.trim()?o[a]=a==="starting_prompt"?hh(c.trim()):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"}}function Bbe(e,t){let r=new Set(t.map(s=>s.trim()).filter(Boolean)),n=[e.title,e.body,...e.comments.map(s=>s.body)].join(`
|
|
1644
|
-
`).replace(/\\/g,"");return Object.entries(ae()).filter(([,s])=>r.has(String(s?.repo??""))).map(([s])=>s).filter(s=>new RegExp(`(?<![\\w./-])${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w/-])`).test(n)).sort()}async function vK(e,t={}){let r=Bc(e,t.cwd??Wm.homedir());try{let
|
|
1644
|
+
`).replace(/\\/g,"");return Object.entries(ae()).filter(([,s])=>r.has(String(s?.repo??""))).map(([s])=>s).filter(s=>new RegExp(`(?<![\\w./-])${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w/-])`).test(n)).sort()}async function vK(e,t={}){let r=Bc(e,t.cwd??Wm.homedir());try{let l=Hy(r.issue_id??"",r.project);l&&(r.project=l.name)}catch(l){throw new B(l.message)}if(!r.issue_id)return{resolved:r,issue:null};let n=ke({project:r.project,text:r.issue_id}),s=n.parseRef(r.issue_id);if(!s)throw new B(`${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 Yf(s,void 0,n)}catch(l){if(l instanceof kl){let u=await n.checkAuth(),f=u.ok?"run `werkmeister infra connect` to check the issue tracker":`${n.label}: ${u.reason}; run: ${u.fix}`;throw new B(`${l.message}; ${f}.`)}throw l}!r.task&&o.title&&(r.task=o.title);let a=e.services,c=a!=null&&(Array.isArray(a)?a:[a]).every(l=>!String(l).trim());if(!r.services&&r.repos&&!c){let l=Bbe(o,r.repos.split(","));l.length&&(r.services=l.join(","),O(`Services taken from the issue text: ${r.services} (pass --services "" for none)`))}if(t.distill!==!1&&(!r.description||!r.starting_prompt)){let{fields:l,warning:u}=await ub(o,t.distill??(f=>Pn().ask(f)));for(let f of["description","starting_prompt"])!r[f]&&l[f]&&(r[f]=l[f]);u&&C(`description/starting_prompt not filled from the issue: ${u}`)}return{resolved:r,issue:o}}async function HT(e,t={}){let n=`werkmeister ${kK(e).join(" ")}`,s=i(async()=>{let{resolved:f,issue:d}=await vK(e,t);return cK(f,{issue:d??void 0,readStdinTask:t.readStdinTask,force:t.force,build:t.build})},"run"),o=xu(t.onData),a;try{a=t.live?await s():await Zi(o,s)}catch(f){if(t.live)throw f instanceof tn?f:new B(f.message);let d=qe(o.text().trim())||f.message;throw new B(`${n} failed:
|
|
1645
1645
|
${d}`)}let c=qe(o.text().trim()),l=!1,u;return(t.open??!0)&&a&&await MT(a)?{opened:l,note:u}=await bK(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 ws(e){let t=(e??"").trim();if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new B(`Invalid workspace name: ${JSON.stringify(e)}`);let r=be.join(un(),t);if(!await MT(r))throw new B(`No such workspace: ${t}`);return r}function _K(e){let t=e.slice(fb.length);if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))throw new B(`Invalid reconcile session: ${JSON.stringify(e)}`);return be.join(SK(),t)}async function cd(e){if((e??"").startsWith(fb)){let t=_K(e);if(!await MT(t))throw new B(`No such reconcile session: ${e}`);return t}return ws(e)}async function KT(e){let t=await ws(e),{opened:r,note:n}=await bK(t);if(!r)throw new B(n??"Could not launch VS Code.");return{path:t}}async function ad(e,t){try{let r=await pt.readFile(be.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 qbe(e){try{let t=await pt.readFile(be.join(W(e),"workspace.yml"),"utf-8"),r=/^feature: *["']?([^"'\s#]+)/m.exec(t);return r?r[1]:null}catch{return null}}async function EK(e){let t=await pt.readdir(be.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 pt.readdir(be.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 Ube(e){let t;try{t=ef(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}function uK(e){return e.health==="healthy"?"healthy":e.health==="starting"?"starting":e.health==="unhealthy"?"unhealthy":e.state==="running"?"running":"down"}function $K(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(Fh(r,kn(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=kn(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 Wbe(){let e=await sr();return e?{containers:e,tallies:$K(e),health:await nk(e)}:null}async function Hbe(){let e=await gK(ta());if(!e)return null;try{return(0,lb.parse)(await pt.readFile(e,"utf8"))??null}catch{return null}}function Kbe(e,t){let[r,n]=ty(e,t);return`${r}-${n}`}async function OK(){let e=un(),r=(await pt.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>l.name).sort((l,u)=>l.localeCompare(u)),n=await Wbe(),s=n?.tallies??null,o=await Hbe(),a=await Promise.all(r.map(async l=>{let u=be.join(e,l),f=await ad(u,"COMPOSE_PROJECT_NAME");if(!f){let N=await qbe(u);f=N?Na(N):null}let d=ow(u),{signal:p,lastActivity:m}=await ho(u).agentSignal(l,u,await za(l).catch(()=>null)),{model:w,autonomous:g,autoStop:y}=await Hm(u),k=Pc(u),S=k?{at:k.at,containers:k.containers}:null,b={harness:d,paused:S,resumeNudge:dK(ua(u)),heldWakes:xL(u),claude:p,model:w,stage:await EK(u),phase:Ube(u),autonomous:g,autoStop:y,lastActivity:m};if(s===null)return{name:l,project:f,state:"unknown",running:0,total:0,slot:null,ports:null,services:[],...b,started:null,crashLoops:[]};let _=f?s.get(f):void 0,$=f?n?.health.get(f):void 0,E;!_||_.total===0?E="down":_.running===_.total?E="up":_.running>0?E="partial":E="stopped",S&&(E="paused");let R=_?.slot??null,P=R!==null?Kbe(R,o):null,I=(_?.services??[]).map(N=>({name:N.name,state:uK(N)}));return{name:l,project:f,state:E,running:_?.running??0,total:_?.total??0,slot:R,ports:P,services:I,...b,started:$?.started??null,crashLoops:$?.crashLoops??[]}})),c;if(s===null)c={state:"unknown",running:0,total:0,services:[]};else{let u=s.get(Jr)?.services??[],f=u.find(g=>g.name==="k8s-forwards");f&&f.state!=="running"&&!await Xx(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",w=u.map(g=>({name:g.name,state:uK(g)}));c={state:m,running:d,total:p,services:w}}return{statuses:a,infra:c}}async function Gbe(e){let t=[],r=await pt.readdir(be.join(e,"stages")).catch(()=>[]);for(let n of r.sort()){let s=be.join("stages",n,"output"),o=await pt.readdir(be.join(e,s)).catch(()=>[]);for(let a of o.sort()){if(!a.endsWith(".md"))continue;let c=await pt.readFile(be.join(e,s,a),"utf-8").catch(()=>"");(a.startsWith("pr-")?/^status: draft/m:/^status: proposed/m).test(c)&&t.push(be.join(s,a))}}return t}async function Vbe(e){let t=new Date,[{root:r,workspaces:n},{statuses:s}]=await Promise.all([sd(),OK()]),o=be.join(r,".check-in-last"),a=await pt.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 IH(f.map(m=>m.path),e);let d=await Promise.all(f.map(async m=>{let w=u.get(m.name),{updatedAt:g}=await za(m.name).catch(()=>({updatedAt:null})),y=Rl(m.path);return{name:m.name,issueId:m.issueId,labels:m.labels,containers:w?.state??"unknown",claude:w?.claude??{state:"idle",agent:"idle",at:null,question:null},gates:await Gbe(m.path),updatedAt:g,changed:a!==null&&g!==null&&Date.parse(g)>a,lifecycle:y.state,paused:w?.paused!=null,prs:y.prs.map(k=>({repo:k.dir,url:k.url,status:k.status,release:k.release}))}}));await pt.writeFile(o,"",{flag:"a"}),await pt.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 Ybe(){return TK(await Ok())}function TK(e){let 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 zbe(e){let t=null,r=await De("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null);r&&r.code===0&&(t=qe(r.stdout).trim()||null);let n={branch:t,url:null,state:null,title:null,labels:[],...LT(void 0)};if(!t||t==="HEAD")return n;let s=await De("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(qe(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,...LT(o[0].statusCheckRollup),draft:o[0].isDraft===!0}}catch{return n}}async function Jbe(){let e=un(),r=(await pt.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 Io(be.join(e,n)),o=await Promise.all(s.map(async({repo:a,dir:c})=>({repo:a,...await zbe(c)})));return{name:n,repos:o}}))}async function Xbe(e){let t=Ae("REVIEW_SLACK_TOKEN"),r=Ae("REVIEW_SLACK_CHANNEL");if(!t||!r)throw new B("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 B(`Slack request failed: ${o.message}`)})).json().catch(()=>({}));if(!s.ok)throw new B(`Slack rejected the message: ${s.error??"unknown error"}`);return r}function RK(e){return e.reviewDecision==="APPROVED"?"APPROVED":e.reviewDecision==="CHANGES_REQUESTED"?"CHANGES_REQUESTED":(e.latestReviews??[]).some(t=>t.state==="DISMISSED")?"DISMISSED":"PENDING"}function VT(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();Qbe.has(s)&&t++}return t}function LT(e){if(!Array.isArray(e)||e.length===0)return{ci:null,failingChecks:0};let t=VT(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 AK(e,t){if(!e)return!0;let r=Date.parse(e);return Number.isNaN(r)?!0:t-r<Zbe}function CK(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 DT(e,t){let{repo:r,number:n}=CK(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=ke({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:RK(e),failingChecks:VT(e.statusCheckRollup),outOfDate:e.mergeStateStatus==="BEHIND",hasApprovalLabel:s.includes(GT),issueId:u,issueUrl:u?l.url(u):null,isDraft:e.isDraft??!1}}function PK(e,t,r,n){let s=i(c=>c.filter(l=>AK("unavailable"in l?void 0:l.updatedAt,n)),"fresh"),o=s(e).map(c=>DT(c,r)),a=s(t).map(c=>DT(c,r)).filter(c=>c.author!==r);return{me:r,mine:o,others:a}}async function eve(){let e=await De("gh",["api","user","--jq",".login"]).catch(()=>null),t=e&&e.code===0?qe(e.stdout).trim():"";if(!t)throw new B("Could not resolve GitHub user (`gh api user`). Is `gh` authenticated?");return t}async function fK(e){let t=Qo();if(!t)throw new B("Could not tell which GitHub org to search. Set `overrides.github_org` in the werkmeister config.");let r=await De("gh",["search","prs",`--owner=${t}`,"--state=open",...e,"--json","url","--limit","100"]).catch(n=>{throw new B(`gh search prs failed: ${n.message}`)});if(r.code!==0)throw new B(`gh search prs failed: ${qe(r.stderr).trim()||`exit ${r.code}`}`);try{return JSON.parse(qe(r.stdout).trim()||"[]").map(s=>s.url).filter(s=>!!s)}catch{return[]}}async function FT(e){let t=await De("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(qe(t.stdout).trim())}catch{return{url:e,unavailable:!0}}}async function tve(){let e=await eve(),[t,r]=await Promise.all([fK(["--author=@me"]),fK([`--label=${GT}`])]),[n,s]=await Promise.all([Promise.all(t.map(FT)),Promise.all(r.map(FT))]);return PK(n,s,e,Date.now())}async function rve(e){let t=await De("gh",["pr","review",e,"--approve"]).catch(r=>{throw new B(`gh pr review failed: ${r.message}`)});if(t.code!==0)throw new B(`gh pr review failed: ${qe(t.stderr).trim()||`exit ${t.code}`}`);return{ok:!0}}async function IK(e){let t=ke({text:e}),r=t.parseRef(e);return r?await TO(`issue-card:${r}`,nve,async()=>await t.fetchIssue(r)??void 0)??{ref:r,url:t.url(r)??void 0}:{ref:""}}async function sve(e){let t=[e,...(await Io(e)).map(n=>n.dir)],r=[];for(let n of t)await M6(n)&&r.push(n);return r}async function Zk(e){let t=new Set;for(let r of e){let n=await De("git",["-C",r,"rev-parse","--path-format=absolute","--git-common-dir"]).catch(()=>null);if(n&&n.code===0){let s=qe(n.stdout).trim();s&&t.add(be.dirname(s))}}return[...t]}function cb(e){let t=qe(e).trim().split(`
|
|
1646
1646
|
`);return(t.find(r=>/^\s*!\s|^(error|fatal):/.test(r))??t[0]).trim().replace(/\s+/g," ")}async function eb(e,t=`chore: handoff ${be.basename(e)} before workspace teardown`,r=[],n={}){let s=be.basename(e),o=await De("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"]).catch(()=>null),a=o&&o.code===0?qe(o.stdout).trim():null;if(!a||a==="HEAD"){let y=await De("git",["-C",e,"status","--porcelain"]).catch(()=>null),k=await Dm(e),S=await Fm(e,k);if(y?.code===0&&!y.stdout.trim()&&S===0)return{ok:!0,message:`${s}: nothing to hand off (detached HEAD, already on ${k})`};let b=y?.code!==0?"can't read its status":y.stdout.trim()?"uncommitted changes":S===null?`can't tell what's on ${k}`:`${S} commit(s) not on ${k}`;return{ok:!1,message:`${s}: no branch to push (detached HEAD, ${b})`}}let c=r.length?["--",...r]:[];await De("git",["-C",e,"add",...r.length?["-A","-f",...c]:["-u"]]).catch(()=>{});let l=await De("git",["-C",e,"diff","--cached","--quiet",...c]).catch(()=>null),u=[],f=l?.code===1;if(f){let y=await De("git",["-C",e,"commit","-m",t,...c]).catch(()=>null);if(y?.code!==0)return{ok:!1,message:`${s}: commit failed \u2014 ${y?cb(y.stderr||y.stdout):"spawn error"}`};if(!r.length){let k=await De("git",["-C",e,"show","--stat","--format=","HEAD"]);u.push(` committed ${t}:`,...qe(k.stdout).trimEnd().split(`
|
|
1647
1647
|
`).map(S=>` ${S}`))}}let d=n.keepDir??be.join($t(),"handoff");if(!r.length){let y=await ove(e,be.join(d,`${s}.tgz`));if(typeof y=="string")return{ok:!1,message:`${s}: ${y}`};y.length&&u.push(` ${y.length} untracked file(s) left off the branch, kept in ${be.join(d,`${s}.tgz`)}:`,...y.map(k=>` ${k}`))}let p=i(y=>({ok:!0,message:[`${s}: ${y}`,...u].join(`
|