@buddysh/buddy 0.11.2 → 0.11.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ [Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.2...v0.11.3)
4
+
5
+ ## 🐛 Bug Fixes
6
+
7
+ - fail the run when a pull request cannot be opened, and use the PAT to open it ([4fe0f36](https://github.com/stacksjs/buddy/commit/4fe0f36)) _(by Chris <chris@stacksjs.com>)_
8
+
9
+ ## 🔧 Chores
10
+
11
+ - release v0.11.3 ([77868d3](https://github.com/stacksjs/buddy/commit/77868d3)) _(by Chris <chris@stacksjs.com>)_
12
+ - run @stacksjs/logsmith, not the unrelated npm 'logsmith' ([7185acc](https://github.com/stacksjs/buddy/commit/7185acc)) _(by Chris <chrisbreuer93@gmail.com>)_
13
+ - release through @stacksjs/bumpx, not the unrelated npm 'bumpx' ([deabeed](https://github.com/stacksjs/buddy/commit/deabeed)) _(by Chris <chrisbreuer93@gmail.com>)_
14
+
15
+ ## Contributors
16
+
17
+ - _Chris <chris@stacksjs.com>_
18
+
3
19
  [Compare changes](https://github.com/stacksjs/buddy-bot/compare/v0.11.1...v0.11.2)
4
20
 
5
21
  ## 💥 Breaking Changes
package/dist/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{Pc as C1}from"../chunk-15r904nz.js";import"../chunk-0eg3kxb5.js";import{_c as f}from"../chunk-dqbk3kcj.js";import"../chunk-phfmnnne.js";import"../chunk-r763e19p.js";import"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import"../chunk-eseshkd0.js";import"../chunk-11hdrnf6.js";import{od as g}from"../chunk-cwfkm7h9.js";import"../chunk-mkzmjg3f.js";import{Gd as Q0,yd as R1}from"../chunk-vgtmrd4c.js";import"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ke as J0,le as Q1,me as z1}from"../chunk-p8tmms5h.js";import"../chunk-ytmxd5fk.js";import"../chunk-b9escac0.js";import"../chunk-g30dr44w.js";import"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import"../chunk-8hjvthz4.js";import"../chunk-yngahb11.js";import"../chunk-08x5b93v.js";import"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import"../chunk-0hc97k0t.js";import{kg as Z0,og as $0}from"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as K0,Sg as CZ,Tg as z0,Ug as Y0,Vg as X0,Wg as j0,Xg as G0,Yg as _,Zg as h,ah as q0,bh as H0,ch as U0,dh as V0,gh as W0,hh as F0,ih as M0,jh as D0,kh as W1,lh as O0,mh as L0}from"../chunk-bymwaezh.js";import"../chunk-k26wnmzk.js";import"../chunk-193abzy6.js";import"../chunk-e68nf7cm.js";import{Ch as r,Dh as O}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import{Uk as RZ,Wk as D}from"../chunk-q4t568hv.js";import o1 from"fs";import V from"process";import{EventEmitter as w0}from"events";import c from"process";import v1 from"process";import T1 from"process";import q1 from"process";import Z1 from"process";import m1 from"tty";import GZ,{stdin as nZ,stdout as iZ}from"process";import u1,{stdin as HZ,stdout as UZ}from"process";import VZ from"readline";import{existsSync as IZ}from"fs";import D1 from"fs/promises";import c1 from"os";import O1 from"path";import n from"process";function L1(Z){return Z.replace(/[<[].+/,"").trim()}function E0(Z){let $=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Q=[],z=(j)=>{let G=!1,X=j[1];if(X.startsWith("..."))X=X.slice(3),G=!0;else if(X.endsWith("..."))X=X.slice(0,-3),G=!0;return{required:j[0].startsWith("<"),value:X.trim(),variadic:G}},Y;while(Y=$.exec(Z))Q.push(z(Y));let U;while(U=J.exec(Z))Q.push(z(U));return Q}function B0(Z){let $={alias:{},boolean:[]};for(let[J,Q]of Z.entries()){if(Q.names.length>1)$.alias[Q.names[0]]=Q.names.slice(1);if(Q.isBoolean)if(Q.negated){if(!Z.some((Y,U)=>{return U!==J&&Y.names.some((j)=>Q.names.includes(j))&&typeof Y.required==="boolean"}))$.boolean.push(Q.names[0])}else $.boolean.push(Q.names[0])}return $}function _1(Z){return Z.reduce(($,J)=>$.length>=J.length?$:J,"")}function F1(Z,$){return Z.length>=$?Z:`${Z}${" ".repeat($-Z.length)}`}function K1(Z){return Z.replace(/([a-z])-([a-z])/g,($,J,Q)=>{return J+Q.toUpperCase()})}function I0(Z,$,J){let Q=0,z=$.length,Y=Z,U;for(;Q<z;++Q)U=Y[$[Q]],Y=Y[$[Q]]=Q===z-1?J:U!=null?U:!!~$[Q+1].indexOf(".")||!(+$[Q+1]>-1)?{}:[]}function P0(Z,$){for(let J of Object.keys($)){let Q=$[J];if(Z[J]===void 0)continue;if(Q.shouldTransform){if(Z[J]=Array.prototype.concat.call([],Z[J]),typeof Q.transformFunction==="function")Z[J]=Z[J].map(Q.transformFunction)}}}function N0(Z){let $=/([^\\/]+)$/.exec(Z);return $?$[1]:""}function $1(Z){return Z.split(".").map(($,J)=>{return J===0?K1($):$}).join(".")}class J1 extends Error{exitCode=2;isUsageError=!0;usage;constructor(Z,$){super(Z);if(this.name=this.constructor.name,$!==void 0)this.usage=$;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(Z).stack}format(Z=!1){if(Z&&this.stack)return`${this.message}
3
+ import{Pc as C1}from"../chunk-tsckfwch.js";import"../chunk-cs066zt9.js";import{_c as f}from"../chunk-e2t5jq26.js";import"../chunk-phfmnnne.js";import"../chunk-r763e19p.js";import"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import"../chunk-eseshkd0.js";import"../chunk-11hdrnf6.js";import{od as g}from"../chunk-cwfkm7h9.js";import"../chunk-mkzmjg3f.js";import{Gd as Q0,yd as R1}from"../chunk-vgtmrd4c.js";import"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ke as J0,le as Q1,me as z1}from"../chunk-5av2vnvv.js";import"../chunk-ytmxd5fk.js";import"../chunk-b9escac0.js";import"../chunk-g30dr44w.js";import"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import"../chunk-8hjvthz4.js";import"../chunk-yngahb11.js";import"../chunk-08x5b93v.js";import"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import"../chunk-0hc97k0t.js";import{kg as Z0,og as $0}from"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as K0,Sg as CZ,Tg as z0,Ug as Y0,Vg as X0,Wg as j0,Xg as G0,Yg as _,Zg as h,ah as q0,bh as H0,ch as U0,dh as V0,gh as W0,hh as F0,ih as M0,jh as D0,kh as W1,lh as O0,mh as L0}from"../chunk-vbeeyhhe.js";import"../chunk-k26wnmzk.js";import"../chunk-193abzy6.js";import"../chunk-e68nf7cm.js";import{Ch as r,Dh as O}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import{Uk as RZ,Wk as D}from"../chunk-q4t568hv.js";import o1 from"fs";import V from"process";import{EventEmitter as w0}from"events";import c from"process";import v1 from"process";import T1 from"process";import q1 from"process";import Z1 from"process";import m1 from"tty";import GZ,{stdin as nZ,stdout as iZ}from"process";import u1,{stdin as HZ,stdout as UZ}from"process";import VZ from"readline";import{existsSync as IZ}from"fs";import D1 from"fs/promises";import c1 from"os";import O1 from"path";import n from"process";function L1(Z){return Z.replace(/[<[].+/,"").trim()}function E0(Z){let $=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Q=[],z=(j)=>{let G=!1,X=j[1];if(X.startsWith("..."))X=X.slice(3),G=!0;else if(X.endsWith("..."))X=X.slice(0,-3),G=!0;return{required:j[0].startsWith("<"),value:X.trim(),variadic:G}},Y;while(Y=$.exec(Z))Q.push(z(Y));let U;while(U=J.exec(Z))Q.push(z(U));return Q}function B0(Z){let $={alias:{},boolean:[]};for(let[J,Q]of Z.entries()){if(Q.names.length>1)$.alias[Q.names[0]]=Q.names.slice(1);if(Q.isBoolean)if(Q.negated){if(!Z.some((Y,U)=>{return U!==J&&Y.names.some((j)=>Q.names.includes(j))&&typeof Y.required==="boolean"}))$.boolean.push(Q.names[0])}else $.boolean.push(Q.names[0])}return $}function _1(Z){return Z.reduce(($,J)=>$.length>=J.length?$:J,"")}function F1(Z,$){return Z.length>=$?Z:`${Z}${" ".repeat($-Z.length)}`}function K1(Z){return Z.replace(/([a-z])-([a-z])/g,($,J,Q)=>{return J+Q.toUpperCase()})}function I0(Z,$,J){let Q=0,z=$.length,Y=Z,U;for(;Q<z;++Q)U=Y[$[Q]],Y=Y[$[Q]]=Q===z-1?J:U!=null?U:!!~$[Q+1].indexOf(".")||!(+$[Q+1]>-1)?{}:[]}function P0(Z,$){for(let J of Object.keys($)){let Q=$[J];if(Z[J]===void 0)continue;if(Q.shouldTransform){if(Z[J]=Array.prototype.concat.call([],Z[J]),typeof Q.transformFunction==="function")Z[J]=Z[J].map(Q.transformFunction)}}}function N0(Z){let $=/([^\\/]+)$/.exec(Z);return $?$[1]:""}function $1(Z){return Z.split(".").map(($,J)=>{return J===0?K1($):$}).join(".")}class J1 extends Error{exitCode=2;isUsageError=!0;usage;constructor(Z,$){super(Z);if(this.name=this.constructor.name,$!==void 0)this.usage=$;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(Z).stack}format(Z=!1){if(Z&&this.stack)return`${this.message}
4
4
 
5
5
  Stack trace:
6
6
  ${this.stack}`;return this.message}}function A0(Z){if(Z instanceof J1)return!0;return!!Z&&typeof Z==="object"&&Z.name==="ClappError"&&typeof Z.message==="string"}function x0(){let{env:Z}=v1,{TERM:$,TERM_PROGRAM:J}=Z;if(v1.platform!=="win32")return $!=="linux";return Boolean(Z.WT_SESSION)||Boolean(Z.TERMINUS_SUBLIME)||Z.ConEmuTask==="{cmd::Cmder}"||J==="Terminus-Sublime"||J==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||Z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var V1="\x1B",C=`${V1}[`;var u={to(Z,$){if(!$)return`${C}${Z+1}G`;return`${C}${$+1};${Z+1}H`},move(Z,$){let J="";if(Z<0)J+=`${C}${-Z}D`;else if(Z>0)J+=`${C}${Z}C`;if($<0)J+=`${C}${-$}A`;else if($>0)J+=`${C}${$}B`;return J},up:(Z=1)=>`${C}${Z}A`,down:(Z=1)=>`${C}${Z}B`,forward:(Z=1)=>`${C}${Z}C`,backward:(Z=1)=>`${C}${Z}D`,nextLine:(Z=1)=>`${C}E`.repeat(Z),prevLine:(Z=1)=>`${C}F`.repeat(Z),left:`${C}G`,hide:`${C}?25l`,show:`${C}?25h`,save:`${V1}7`,restore:`${V1}8`};var M1={screen:`${C}2J`,up:(Z=1)=>`${C}1J`.repeat(Z),down:(Z=1)=>`${C}J`.repeat(Z),line:`${C}2K`,lineEnd:`${C}K`,lineStart:`${C}1K`,lines(Z){let $="";for(let J=0;J<Z;J++)$+=this.line+(J<Z-1?u.up():"");if(Z)$+=u.left;return $}},fZ={screen:`${V1}c`};function R0(Z,$){let J=[];for(let Q=0;Q<=$.length;Q++)J[Q]=[Q];for(let Q=0;Q<=Z.length;Q++)J[0][Q]=Q;for(let Q=1;Q<=$.length;Q++)for(let z=1;z<=Z.length;z++)if($.charAt(Q-1)===Z.charAt(z-1))J[Q][z]=J[Q-1][z-1];else J[Q][z]=Math.min(J[Q-1][z-1]+1,J[Q][z-1]+1,J[Q-1][z]+1);return J[$.length][Z.length]}function l1(Z,$,J=2,Q=3){return $.map((z)=>({cmd:z,distance:R0(Z,z)})).filter(({distance:z})=>z<=J).sort((z,Y)=>z.distance-Y.distance).slice(0,Q).map(({cmd:z})=>z)}function C0(Z,$={}){let J={_:[]},Q=$.alias||{},z=new Set($.boolean||[]),Y={};for(let G of Object.keys(Q))for(let X of Q[G])Y[X]=G;for(let G of z)if(Q[G])for(let X of Q[G])z.add(X);function U(G,X){if(G===void 0)return X;if(typeof X==="boolean")return X;return Array.isArray(G)?[...G,X]:[G,X]}function j(G,X){let H=Y[G]||G,q=U(J[H],X);if(J[H]=q,Q[H])for(let K of Q[H])J[K]=q;if(Y[G]&&Q[Y[G]])for(let K of Q[Y[G]])J[K]=q;J[G]=q}for(let G=0;G<Z.length;G++){let X=Z[G];if(X==="--"){J._.push(...Z.slice(G+1));break}if(X.startsWith("--")){let H=X.indexOf("=");if(H!==-1){let q=K1(X.slice(2,H)),K=X.slice(H+1);j(q,K)}else{let q=X.slice(2);if(q.startsWith("no-")){let W=K1(q.slice(3));j(W,!1);continue}let K=K1(q),F=Y[K]||K;if(z.has(F)||z.has(K))j(K,!0);else{let W=Z[G+1];if(W!==void 0&&!W.startsWith("-"))j(K,W),G++;else j(K,!0)}}}else if(X.startsWith("-")&&X.length>1){let H=X.slice(1);for(let q=0;q<H.length;q++){let K=H[q],F=Y[K]||K;if(q===H.length-1&&!z.has(F)&&!z.has(K)){let W=Z[G+1];if(W!==void 0&&!W.startsWith("-"))j(K,W),G++;else j(K,!0)}else j(K,!0)}}else J._.push(X)}return J}class p1{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(Z,$,J){if(this.rawName=Z,this.description=$,this.config=Object.assign({},J),Z=Z.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(Z),this.names=L1(Z).split(",").map((Q)=>{let z=Q.trim().replace(/^-{1,2}/,"");if(z.startsWith("no-"))this.negated=!0,z=z.replace(/^no-/,"");return $1(z)}).sort((Q,z)=>Q.length>z.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(Z.includes("<"))this.required=!0;else if(Z.includes("["))this.required=!1;else this.isBoolean=!0}}var dZ=T1.argv,S0=`${T1.platform}-${T1.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,f1=q1.argv,k0=`${q1.platform}-${q1.arch} node-${q1.version}`;class w1{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(Z,$,J,Q){this.rawName=Z,this.description=$,this.config=J,this.cli=Q,this.options=[],this.aliasNames=[],this.name=L1(Z);let z=L1(Z),Y=z.indexOf(":");if(Y>0)this.namespace=z.substring(0,Y),this.name=z.substring(Y+1);if(this.args=E0(Z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!J)this.config={}}usage(Z){return this.usageText=Z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(Z,$="-v, --version"){return this.versionNumber=Z,this.option($,"Display version number"),this}example(Z){return this.examples.push(Z),this}option(Z,$,J){let Q=new p1(Z,$,J);return this.options.push(Q),this}alias(Z){return this.aliasNames.push(Z),this}action(Z){return this.commandAction=Z,this}before(Z){return this.beforeHooks.push(Z),this}after(Z){return this.afterHooks.push(Z),this}use(Z){return this.middleware.push(Z),this}isMatched(Z){if(this.aliasNames.includes(Z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===Z;return this.name===Z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof E1}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(Z){let $=$1(Z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Q)=>$1(Q)===$)})}outputHelp(){let{name:Z,commands:$}=this.cli,{versionNumber:J,options:Q,helpCallback:z}=this.cli.globalCommand,Y=[{body:`${Z}${J?`/${J}`:""}`}];if(Y.push({title:"Usage",body:` $ ${Z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let X=_1($.map((W)=>W.rawName)),H=new Map,q=[];for(let W of $)if(W.namespace){if(!H.has(W.namespace))H.set(W.namespace,[]);H.get(W.namespace).push(W)}else q.push(W);let K="";if(q.sort((W,T)=>W.rawName<T.rawName?-1:W.rawName>T.rawName?1:0),q.length>0)K+=q.map((W)=>{return` ${F1(W.rawName,X.length)} ${W.description}`}).join(`
@@ -29,7 +29,7 @@ Received ${J}, cleaning up...`),Z)try{await Z()}catch(Q){console.error("Error du
29
29
  `)),this.enableDidYouMean){let $=[];for(let Q of this.commands){if(Q.displayName)$.push(Q.displayName);if(Q.aliasNames)$.push(...Q.aliasNames)}let J=l1(Z,$);if(J.length>0)console.log(e.yellow("Did you mean one of these?")),J.forEach((Q)=>console.log(` ${e.dim("\u2022")} ${this.name} ${Q}`)),console.log("")}console.log(e.dim("Run"),`${this.name} --help`,e.dim("to see all available commands")),c.exit(1)}async parse(Z=f1,$={}){let{run:J=!0,exitOnError:Q=!1}=$;if(Q)try{return await this.parse(Z,{run:J})}catch(G){throw this.handleUsageError(G),G}if(this.rawArgs=Z,!this.name)this.name=Z[1]?N0(Z[1]):"cli";let z=!0,Y=Z.slice(2),U=Y[0];if(U&&!U.startsWith("-")){for(let G of this.commands)if(G.isMatched(U)){let X=this.mri(Y,G);z=!1;let H={...X,args:X.args.slice(1)};this.setParsedInfo(H,G,U),this.emit(`command:${U}`,G);break}if(z){let G=Y[1];if(G&&!G.startsWith("-")){let X=`${U}:${G}`;for(let H of this.commands)if(H.isMatched(X)){let q=this.mri(Y,H);z=!1;let K={...q,args:q.args.slice(2)};this.setParsedInfo(K,H,X),this.emit(`command:${X}`,H);break}}}}if(z){for(let G of this.commands)if(G.name===""){z=!1;let X=this.mri(Y,G);this.setParsedInfo(X,G),this.emit("command:!",G);break}}if(z){let G=this.mri(Z.slice(2));this.setParsedInfo(G)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),J=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),J=!1,this.unsetMatchedCommand();let j={args:this.args,options:this.options};if(J)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return j}mri(Z,$){let J=[...this.globalCommand.options,...$?$.options:[]],Q=B0(J),z=[],Y=Z.indexOf("--");if(Y>-1)z=Z.slice(Y+1),Z=Z.slice(0,Y);let U=C0(Z,Q),j={_:U._};for(let K of Object.keys(U))if(K!=="_")j[$1(K)]=U[K];let G=j._,X={"--":z},H=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,q=Object.create(null);for(let K of J){if(!H&&K.config.default!==void 0)for(let F of K.names)X[F]=K.config.default;if(Array.isArray(K.config.type)){if(q[K.name]===void 0)q[K.name]={shouldTransform:!0,transformFunction:K.config.type[0]}}}for(let K of Object.keys(j))if(K!=="_"){let F=K.split(".");I0(X,F,j[K]),P0(X,q)}for(let K of J){if(!K.variadic)continue;for(let F of K.names){let W=X[F];if(W===void 0||Array.isArray(W))continue;if(K.config.default!==void 0&&W===K.config.default)continue;X[F]=[W]}}return{args:G,options:X}}async run(Z=f1){return this.parse(Z,{run:!0,exitOnError:!0})}handleUsageError(Z){if(!A0(Z)||Z.isUsageError===!1)return;let $=Z.message||"command-line error",J=this.name?`${this.name}: `:"",Q=/--help/.test($)?"":Z.usage?`
30
30
  Usage: ${Z.usage}`:`
31
31
  Run \`${this.name??"cli"} --help\` for usage.`;c.stderr.write(`${J}${$}${Q}
32
- `),c.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:Z,options:$,matchedCommand:J}=this;if(!J||!J.commandAction)return;J.checkUnknownOptions(),J.checkOptionValue(),J.checkRequiredArgs();let Q=[];J.args.forEach((j,G)=>{if(j.variadic)Q.push(Z.slice(G));else Q.push(Z[G])}),Q.push($);let z={command:J,args:Q,options:$};for(let j of J.beforeHooks)await j(z);let Y,U=async()=>{let j=J.commandAction.apply(this,Q);if(j instanceof Promise)Y=await j;else Y=j;return Y};if(J.middleware.length>0){let j=0,G=async()=>{if(j<J.middleware.length){let X=J.middleware[j++];await X({...z,next:G})}else await U()};await G()}else await U();for(let j of J.afterHooks)await j(z);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return c.removeAllListeners("SIGINT"),c.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class n1{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(Z){if(!this.enabled){this.misses++;return}let $=this.cache.get(Z);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(Z),this.misses++;return}return this.hits++,$.value}set(Z,$,J=5000){if(!this.enabled)return;this.cache.set(Z,{value:$,timestamp:Date.now(),ttl:J})}has(Z){if(!this.enabled)return!1;let $=this.cache.get(Z);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(Z),!1;return!0}delete(Z){this.cache.delete(Z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let Z=Date.now();for(let[$,J]of this.cache.entries())if(Z-J.timestamp>J.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var gZ=new n1;function v0(){if("FORCE_COLOR"in Z1.env)return Z1.env.FORCE_COLOR!=="0";if("NO_COLOR"in Z1.env||Z1.env.TERM==="dumb")return!1;if(Z1.platform==="win32")return!0;return m1.isatty(1)&&m1.isatty(2)}var i1=v0();function R(Z,$){if(!i1)return(J)=>J;return(J)=>Z+J+$}var _0=R("\x1B[0m","\x1B[0m"),f0=R("\x1B[31m","\x1B[39m"),m0=R("\x1B[32m","\x1B[39m"),d0=R("\x1B[33m","\x1B[39m"),u0=R("\x1B[34m","\x1B[39m"),g0=R("\x1B[35m","\x1B[39m"),c0=R("\x1B[36m","\x1B[39m"),l0=R("\x1B[37m","\x1B[39m"),p0=R("\x1B[90m","\x1B[39m"),n0=R("\x1B[1m","\x1B[22m"),i0=R("\x1B[3m","\x1B[23m"),a0=R("\x1B[4m","\x1B[24m"),r0=R("\x1B[2m","\x1B[22m"),t0=R("\x1B[7m","\x1B[27m"),s0=R("\x1B[8m","\x1B[28m"),o0=R("\x1B[9m","\x1B[29m"),e0=R("\x1B[41m","\x1B[49m"),ZZ=R("\x1B[42m","\x1B[49m"),$Z=R("\x1B[43m","\x1B[49m"),JZ=R("\x1B[44m","\x1B[49m"),QZ=R("\x1B[45m","\x1B[49m"),zZ=R("\x1B[46m","\x1B[49m"),YZ=R("\x1B[47m","\x1B[49m"),XZ=i1,jZ={reset:_0,red:f0,green:m0,yellow:d0,blue:u0,magenta:g0,cyan:c0,white:l0,gray:p0,bold:n0,italic:i0,underline:a0,dim:r0,inverse:t0,hidden:s0,strikethrough:o0,bgRed:e0,bgGreen:ZZ,bgYellow:$Z,bgBlue:JZ,bgMagenta:QZ,bgCyan:zZ,bgWhite:YZ,isColorSupported:XZ},H1=jZ,KZ=["up","down","left","right","space","enter","cancel"],U1={actions:new Set(KZ),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function a1(Z,$){if(typeof Z==="string")return U1.aliases.get(Z)===$;for(let J of Z){if(J===void 0)continue;if(a1(J,$))return!0}return!1}function qZ(Z,$){if(Z===$)return[];let J=Z.split(`
32
+ `),c.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:Z,options:$,matchedCommand:J}=this;if(!J||!J.commandAction)return;J.checkUnknownOptions(),J.checkOptionValue(),J.checkRequiredArgs();let Q=[];J.args.forEach((j,G)=>{if(j.variadic)Q.push(Z.slice(G));else Q.push(Z[G])}),Q.push($);let z={command:J,args:Q,options:$};for(let j of J.beforeHooks)await j(z);let Y,U=async()=>{let j=J.commandAction.apply(this,Q);if(j instanceof Promise)Y=await j;else Y=j;return Y};if(J.middleware.length>0){let j=0,G=async()=>{if(j<J.middleware.length){let X=J.middleware[j++];await X({...z,next:G})}else await U()};await G()}else await U();for(let j of J.afterHooks)await j(z);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return c.removeAllListeners("SIGINT"),c.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class n1{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(Z){if(!this.enabled){this.misses++;return}let $=this.cache.get(Z);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(Z),this.misses++;return}return this.hits++,$.value}set(Z,$,J=5000){if(!this.enabled)return;this.cache.set(Z,{value:$,timestamp:Date.now(),ttl:J})}has(Z){if(!this.enabled)return!1;let $=this.cache.get(Z);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(Z),!1;return!0}delete(Z){this.cache.delete(Z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let Z=Date.now();for(let[$,J]of this.cache.entries())if(Z-J.timestamp>J.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var gZ=new n1;function v0(){if("FORCE_COLOR"in Z1.env)return Z1.env.FORCE_COLOR!=="0";if("NO_COLOR"in Z1.env||Z1.env.TERM==="dumb")return!1;if(Z1.platform==="win32")return!0;return m1.isatty(1)&&m1.isatty(2)}var i1=v0();function R(Z,$){if(!i1)return(J)=>J;return(J)=>Z+J+$}var _0=R("\x1B[0m","\x1B[0m"),f0=R("\x1B[31m","\x1B[39m"),m0=R("\x1B[32m","\x1B[39m"),d0=R("\x1B[33m","\x1B[39m"),u0=R("\x1B[34m","\x1B[39m"),g0=R("\x1B[35m","\x1B[39m"),c0=R("\x1B[36m","\x1B[39m"),l0=R("\x1B[37m","\x1B[39m"),p0=R("\x1B[90m","\x1B[39m"),n0=R("\x1B[1m","\x1B[22m"),i0=R("\x1B[3m","\x1B[23m"),a0=R("\x1B[4m","\x1B[24m"),r0=R("\x1B[2m","\x1B[22m"),s0=R("\x1B[7m","\x1B[27m"),t0=R("\x1B[8m","\x1B[28m"),o0=R("\x1B[9m","\x1B[29m"),e0=R("\x1B[41m","\x1B[49m"),ZZ=R("\x1B[42m","\x1B[49m"),$Z=R("\x1B[43m","\x1B[49m"),JZ=R("\x1B[44m","\x1B[49m"),QZ=R("\x1B[45m","\x1B[49m"),zZ=R("\x1B[46m","\x1B[49m"),YZ=R("\x1B[47m","\x1B[49m"),XZ=i1,jZ={reset:_0,red:f0,green:m0,yellow:d0,blue:u0,magenta:g0,cyan:c0,white:l0,gray:p0,bold:n0,italic:i0,underline:a0,dim:r0,inverse:s0,hidden:t0,strikethrough:o0,bgRed:e0,bgGreen:ZZ,bgYellow:$Z,bgBlue:JZ,bgMagenta:QZ,bgCyan:zZ,bgWhite:YZ,isColorSupported:XZ},H1=jZ,KZ=["up","down","left","right","space","enter","cancel"],U1={actions:new Set(KZ),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function a1(Z,$){if(typeof Z==="string")return U1.aliases.get(Z)===$;for(let J of Z){if(J===void 0)continue;if(a1(J,$))return!0}return!1}function qZ(Z,$){if(Z===$)return[];let J=Z.split(`
33
33
  `),Q=$.split(`
34
34
  `),z=[];for(let Y=0;Y<Math.max(J.length,Q.length);Y++)if(J[Y]!==Q[Y])z.push(Y);return z}var aZ=GZ.platform.startsWith("win"),d1=Symbol("clapp:cancel");function G1(Z,$){let J=Z;if(J.isTTY)J.setRawMode($)}function WZ(Z){return Z.replace(/\x1b\[[0-9;]*m/g,"")}function FZ(Z){return WZ(Z).length}function g1(Z,$,J){if(!$||$<1)return Z;let Q=J?.hard??!1,z=J?.trim??!0,Y=Z.split(`
35
35
  `),U=[];for(let j of Y){if(FZ(j)<=$){U.push(z?j.trimEnd():j);continue}if(Q){let G="",X=0,H=0;while(H<j.length){let q=j.slice(H).match(/^\x1b\[[0-9;]*m/);if(q){G+=q[0],H+=q[0].length;continue}if(X>=$)U.push(z?G.trimEnd():G),G="",X=0;G+=j[H],X++,H++}if(G)U.push(z?G.trimEnd():G)}else U.push(z?j.trimEnd():j)}return U.join(`
@@ -38,7 +38,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;c.stderr.write(`${J}${$}${Q}
38
38
  `).length-1;this.output.write(u.move(-999,Z*-1))}render(){let Z=g1(this._render(this)??"",u1.stdout.columns,{hard:!0,trim:!1});if(Z===this._prevFrame)return;if(this.state==="initial")this.output.write(u.hide);else{let $=qZ(this._prevFrame,Z);if(this.restoreCursor(),$&&$?.length===1){let J=$[0];this.output.write(u.move(0,J)),this.output.write(M1.lines(1));let Q=Z.split(`
39
39
  `);this.output.write(Q[J]),this._prevFrame=Z,this.output.write(u.move(0,Q.length-J-1));return}if($&&$?.length>1){let J=$[0];this.output.write(u.move(0,J)),this.output.write(M1.down());let z=Z.split(`
40
40
  `).slice(J);this.output.write(z.join(`
41
- `)),this._prevFrame=Z;return}this.output.write(M1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function MZ(Z,$){if(Z===void 0)return 0;if($.length===0)return 0;let Q=$.findIndex((z)=>z.value===Z);return Q!==-1?Q:0}function DZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function OZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class LZ extends I1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return H1.inverse(H1.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let Z=this.userInput.slice(0,this._cursor),[$,...J]=this.userInput.slice(this._cursor);return`${Z}${H1.inverse($)}${J.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(Z){super(Z);this.#$=Z.options;let $=this.options;this.filteredOptions=[...$],this.multiple=Z.multiple===!0,this.#Q=Z.filter??DZ;let J;if(Z.initialValue&&Array.isArray(Z.initialValue))if(this.multiple)J=Z.initialValue;else J=Z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Q of J){let z=$.findIndex((Y)=>Y.value===Q);if(z!==-1)this.toggleSelected(Q),this.#Z=z}this.focusedValue=this.options[this.#Z]?.value,this.on("key",(Q,z)=>this.#z(Q,z)),this.on("userInput",(Q)=>this.#Y(Q))}_isActionKey(Z,$){return Z==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&Z!==void 0&&Z!==""}#z(Z,$){let J=$.name==="up",Q=$.name==="down",z=$.name==="return";if(J||Q){if(this.#Z=Math.max(0,Math.min(this.#Z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(z)this.value=OZ(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(Z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(Z))this.selectedValues=this.selectedValues.filter(($)=>$!==Z);else this.selectedValues=[...this.selectedValues,Z];else this.selectedValues=[Z]}#Y(Z){if(Z!==this.#J){this.#J=Z;let $=this.options;if(Z)this.filteredOptions=$.filter((J)=>this.#Q(Z,J));else this.filteredOptions=[...$];if(this.#Z=MZ(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class TZ extends I1{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter(($)=>$.group===Z)}isGroupSelected(Z){let $=this.getGroupItems(Z),J=this.value;if(J===void 0)return!1;return $.every((Q)=>J.includes(Q.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(Z.group===!0){let $=String(Z.value),J=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((Q)=>J.findIndex((z)=>z.value===Q)===-1);else this.value=[...this.value,...J.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(Z.value);this.value=$?this.value.filter((J)=>J!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:$}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries($).flatMap(([J,Q])=>[{value:J,group:!0,label:J},...Q.map((z)=>({...z,group:J}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),this.#Z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var wZ=x0();var x=(Z,$)=>wZ?Z:$,sZ=x("\u25C6","*"),oZ=x("\u25A0","x"),eZ=x("\u25B2","x"),Z$=x("\u25C7","o"),$$=x("\u250C","T"),EZ=x("\u2502","|"),J$=x("\u2514","\u2014"),Q$=x("\u25CF",">"),z$=x("\u25CB"," "),Y$=x("\u25FB","[\u2022]"),X$=x("\u25FC","[+]"),j$=x("\u25FB","[ ]"),G$=x("\u25AA","\u2022"),K$=x("\u2500","-"),q$=x("\u256E","+"),H$=x("\u251C","+"),U$=x("\u256F","+"),V$=x("\u25CF","\u2022"),W$=x("\u25C6","*"),F$=x("\u25B2","!"),M$=x("\u25A0","x");var D$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function BZ(){return`${H1.gray(EZ)} `}var O$=BZ();class r1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=c1.homedir(),$=O1.join(Z,".config","clapp");this.configPath=O1.join($,"telemetry.json")}async isEnabled(){if(n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true")return!1;if(n.env.NO_TELEMETRY==="1"||n.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let Z=await this.loadConfig();if(Z.enabled=!0,!Z.userId)Z.userId=this.generateUserId();await this.saveConfig(Z)}async disable(){let Z=await this.loadConfig();Z.enabled=!1,await this.saveConfig(Z)}async track(Z,$){if(!await this.isEnabled())return;let Q={event:Z,...$,timestamp:Date.now(),platform:c1.platform(),nodeVersion:n.version};if(this.events.push(Q),this.events.length>=10)await this.send()}async trackCommand(Z,$){await this.track("command",{command:Z,duration:$})}async trackError(Z,$){await this.track("error",{error:Z,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(Z){return new Promise(($)=>setTimeout($,Z))}async status(){let Z=await this.loadConfig();return{enabled:Z.enabled,doNotTrack:n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(IZ(this.configPath)){let Z=await D1.readFile(this.configPath,"utf-8");return this.config=JSON.parse(Z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(Z){this.config=Z;try{let $=O1.dirname(this.configPath);await D1.mkdir($,{recursive:!0}),await D1.writeFile(this.configPath,JSON.stringify(Z,null,2),"utf-8")}catch{}}generateUserId(){let Z=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${Z}-${$}`}}var I$=new r1;var a=RZ(CZ(),1);var P1="0.11.2";var N1=String.raw`^\s*-\s*\[[xX]\]\s*`,NZ=new RegExp(`${N1}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),AZ=new RegExp(`${N1}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),xZ=new RegExp(`${N1}<!--\\s*manual job\\s*-->`,"m");function t1(Z){if(!Z)return{rebaseBranches:[],rebaseAll:!1,manualRun:!1};let $=[];for(let J of Z.matchAll(NZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:AZ.test(Z),manualRun:xZ.test(Z)}}function A1(Z){return Z.rebaseBranches.length>0||Z.rebaseAll||Z.manualRun}function s1(Z){return Z.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*(?:rebase-branch=[^>]*?|rebase-all-open-prs|manual job)\s*-->)/gm,"$1[ ]$2")}var x1=null;async function S(Z){if(Z)return await C1(Z);if(!x1)x1=await C1();return x1}async function m(Z,$,J){if(!Z.repository?.owner||!Z.repository.name)J.error(`\u274C Repository owner and name are required for ${$}`),J.info("Configure repository.owner and repository.name in buddy.config.ts"),V.exit(1);try{return await J0({provider:Z.repository.provider,owner:Z.repository.owner,name:Z.repository.name,...Z.repository.token?{token:Z.repository.token}:{},...Z.repository.apiUrl?{apiUrl:Z.repository.apiUrl}:{}},{logger:J})}catch(Q){J.error(`\u274C ${r(Q)}`),V.exit(1)}}async function e1(Z,$,J){let Q=Z.filter((U)=>U.suggestion);if(Q.length===0)return J.info("No committable suggestions in this review"),0;let z=new Map;for(let U of Q){let j=z.get(U.path);if(j)j.push(U);else z.set(U.path,[U])}let Y=0;for(let[U,j]of z){let G=Bun.file(U);if(!await G.exists()){J.warn(`\u26A0\uFE0F Skipping ${U}: not in the working tree`);continue}let X=await G.text();for(let H of[...j].sort((q,K)=>K.line-q.line)){if(!$){if(!(await a.default({type:"confirm",name:"apply",message:`${U}:${H.line} \u2014 ${H.message}
41
+ `)),this._prevFrame=Z;return}this.output.write(M1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function MZ(Z,$){if(Z===void 0)return 0;if($.length===0)return 0;let Q=$.findIndex((z)=>z.value===Z);return Q!==-1?Q:0}function DZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function OZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class LZ extends I1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return H1.inverse(H1.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let Z=this.userInput.slice(0,this._cursor),[$,...J]=this.userInput.slice(this._cursor);return`${Z}${H1.inverse($)}${J.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(Z){super(Z);this.#$=Z.options;let $=this.options;this.filteredOptions=[...$],this.multiple=Z.multiple===!0,this.#Q=Z.filter??DZ;let J;if(Z.initialValue&&Array.isArray(Z.initialValue))if(this.multiple)J=Z.initialValue;else J=Z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Q of J){let z=$.findIndex((Y)=>Y.value===Q);if(z!==-1)this.toggleSelected(Q),this.#Z=z}this.focusedValue=this.options[this.#Z]?.value,this.on("key",(Q,z)=>this.#z(Q,z)),this.on("userInput",(Q)=>this.#Y(Q))}_isActionKey(Z,$){return Z==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&Z!==void 0&&Z!==""}#z(Z,$){let J=$.name==="up",Q=$.name==="down",z=$.name==="return";if(J||Q){if(this.#Z=Math.max(0,Math.min(this.#Z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(z)this.value=OZ(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(Z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(Z))this.selectedValues=this.selectedValues.filter(($)=>$!==Z);else this.selectedValues=[...this.selectedValues,Z];else this.selectedValues=[Z]}#Y(Z){if(Z!==this.#J){this.#J=Z;let $=this.options;if(Z)this.filteredOptions=$.filter((J)=>this.#Q(Z,J));else this.filteredOptions=[...$];if(this.#Z=MZ(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class TZ extends I1{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter(($)=>$.group===Z)}isGroupSelected(Z){let $=this.getGroupItems(Z),J=this.value;if(J===void 0)return!1;return $.every((Q)=>J.includes(Q.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(Z.group===!0){let $=String(Z.value),J=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((Q)=>J.findIndex((z)=>z.value===Q)===-1);else this.value=[...this.value,...J.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(Z.value);this.value=$?this.value.filter((J)=>J!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:$}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries($).flatMap(([J,Q])=>[{value:J,group:!0,label:J},...Q.map((z)=>({...z,group:J}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),this.#Z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var wZ=x0();var x=(Z,$)=>wZ?Z:$,tZ=x("\u25C6","*"),oZ=x("\u25A0","x"),eZ=x("\u25B2","x"),Z$=x("\u25C7","o"),$$=x("\u250C","T"),EZ=x("\u2502","|"),J$=x("\u2514","\u2014"),Q$=x("\u25CF",">"),z$=x("\u25CB"," "),Y$=x("\u25FB","[\u2022]"),X$=x("\u25FC","[+]"),j$=x("\u25FB","[ ]"),G$=x("\u25AA","\u2022"),K$=x("\u2500","-"),q$=x("\u256E","+"),H$=x("\u251C","+"),U$=x("\u256F","+"),V$=x("\u25CF","\u2022"),W$=x("\u25C6","*"),F$=x("\u25B2","!"),M$=x("\u25A0","x");var D$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function BZ(){return`${H1.gray(EZ)} `}var O$=BZ();class r1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=c1.homedir(),$=O1.join(Z,".config","clapp");this.configPath=O1.join($,"telemetry.json")}async isEnabled(){if(n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true")return!1;if(n.env.NO_TELEMETRY==="1"||n.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let Z=await this.loadConfig();if(Z.enabled=!0,!Z.userId)Z.userId=this.generateUserId();await this.saveConfig(Z)}async disable(){let Z=await this.loadConfig();Z.enabled=!1,await this.saveConfig(Z)}async track(Z,$){if(!await this.isEnabled())return;let Q={event:Z,...$,timestamp:Date.now(),platform:c1.platform(),nodeVersion:n.version};if(this.events.push(Q),this.events.length>=10)await this.send()}async trackCommand(Z,$){await this.track("command",{command:Z,duration:$})}async trackError(Z,$){await this.track("error",{error:Z,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(Z){return new Promise(($)=>setTimeout($,Z))}async status(){let Z=await this.loadConfig();return{enabled:Z.enabled,doNotTrack:n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(IZ(this.configPath)){let Z=await D1.readFile(this.configPath,"utf-8");return this.config=JSON.parse(Z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(Z){this.config=Z;try{let $=O1.dirname(this.configPath);await D1.mkdir($,{recursive:!0}),await D1.writeFile(this.configPath,JSON.stringify(Z,null,2),"utf-8")}catch{}}generateUserId(){let Z=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${Z}-${$}`}}var I$=new r1;var a=RZ(CZ(),1);var P1="0.11.3";var N1=String.raw`^\s*-\s*\[[xX]\]\s*`,NZ=new RegExp(`${N1}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),AZ=new RegExp(`${N1}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),xZ=new RegExp(`${N1}<!--\\s*manual job\\s*-->`,"m");function s1(Z){if(!Z)return{rebaseBranches:[],rebaseAll:!1,manualRun:!1};let $=[];for(let J of Z.matchAll(NZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:AZ.test(Z),manualRun:xZ.test(Z)}}function A1(Z){return Z.rebaseBranches.length>0||Z.rebaseAll||Z.manualRun}function t1(Z){return Z.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*(?:rebase-branch=[^>]*?|rebase-all-open-prs|manual job)\s*-->)/gm,"$1[ ]$2")}var x1=null;async function S(Z){if(Z)return await C1(Z);if(!x1)x1=await C1();return x1}async function m(Z,$,J){if(!Z.repository?.owner||!Z.repository.name)J.error(`\u274C Repository owner and name are required for ${$}`),J.info("Configure repository.owner and repository.name in buddy.config.ts"),V.exit(1);try{return await J0({provider:Z.repository.provider,owner:Z.repository.owner,name:Z.repository.name,...Z.repository.token?{token:Z.repository.token}:{},...Z.repository.apiUrl?{apiUrl:Z.repository.apiUrl}:{}},{logger:J})}catch(Q){J.error(`\u274C ${r(Q)}`),V.exit(1)}}async function e1(Z,$,J){let Q=Z.filter((U)=>U.suggestion);if(Q.length===0)return J.info("No committable suggestions in this review"),0;let z=new Map;for(let U of Q){let j=z.get(U.path);if(j)j.push(U);else z.set(U.path,[U])}let Y=0;for(let[U,j]of z){let G=Bun.file(U);if(!await G.exists()){J.warn(`\u26A0\uFE0F Skipping ${U}: not in the working tree`);continue}let X=await G.text();for(let H of[...j].sort((q,K)=>K.line-q.line)){if(!$){if(!(await a.default({type:"confirm",name:"apply",message:`${U}:${H.line} \u2014 ${H.message}
42
42
  ${H.suggestion}
43
43
  Apply?`,initial:!1})).apply)continue}let q=Q0(X,H.line,H.suggestion);if(q===null){J.warn(`\u26A0\uFE0F Skipping ${U}:${H.line}: the file changed since the review`);continue}X=q,Y++}await Bun.write(U,X)}return Y}async function SZ(Z,$){try{let{PackageScanner:J}=await import("../chunk-fpnjpgrb.js"),Q=await new J(V.cwd(),$,Z.packages?.ignorePaths).scanProject(),z=new Map;for(let Y of Q)for(let U of Y.dependencies)if(!z.has(U.name))z.set(U.name,U.currentVersion);return[...z].map(([Y,U])=>({name:Y,declaredVersion:U}))}catch(J){return $.debug(`Could not collect dependency context: ${r(J)}`),[]}}var w=new B1("buddy");w.usage(`[command] [options]
44
44
 
@@ -138,13 +138,13 @@ Scan Results:`),$.info(`\uD83D\uDCE6 Total packages: ${j.totalPackages}`),$.info
138
138
  \uD83D\uDEA8 Major updates (${G.length}):`);for(let q of G)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(X.length>0){$.info(`
139
139
  \u2728 Minor updates (${X.length}):`);for(let q of X)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(H.length>0){$.info(`
140
140
  \uD83D\uDD27 Patch updates (${H.length}):`);for(let q of H)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(j.groups.length>0){$.info(`
141
- \uD83D\uDCCB Update groups (${j.groups.length}):`);for(let q of j.groups)$.info(` ${q.name}: ${q.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),await g(J.notifications,"run.failed",{command:"scan",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("dashboard","Create or update dependency dashboard issue").option("--verbose, -v","Enable verbose logging").option("--title <title>","Custom dashboard title").option("--issue-number <number>","Update specific issue number").option("--pin","Pin the dashboard issue to the top of the issue list").option("--no-pin","Unpin the dashboard issue").example("buddy dashboard").example('buddy dashboard --title "My Dependencies"').example("buddy dashboard --issue-number 42").example("buddy dashboard --pin").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);if(J.dashboard?.enabled===!1){$.info("\u2139\uFE0F Dashboard is disabled by config (dashboard.enabled: false)");return}try{if($.info("Creating or updating dependency dashboard..."),!J.repository)$.error("\u274C Repository configuration required for dashboard"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q={...J,verbose:Z.verbose??J.verbose,dashboard:{...J.dashboard,enabled:!0,title:Z.title??J.dashboard?.title,issueNumber:Z.issueNumber?Number.parseInt(Z.issueNumber,10):J.dashboard?.issueNumber,pin:Z.pin??J.dashboard?.pin}},Y=await new f(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),await g(J.notifications,"run.failed",{command:"dashboard",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--reviewers <names>","Comma-separated reviewers to assign (overrides pullRequest.reviewers)").option("--assignees <names>","Comma-separated assignees to assign (overrides pullRequest.assignees)").option("--labels <names>","Comma-separated labels to add (overrides pullRequest.labels)").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy update").example("buddy update --dry-run").example("buddy update --strategy patch").example("buddy update --verbose").example("buddy update --no-respect-latest").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((K)=>K.trim());let z=(K)=>K?K.split(",").map((F)=>F.trim()).filter(Boolean):void 0,Y=z(Z.reviewers),U=z(Z.assignees),j=z(Z.labels),G={...Y?{reviewers:Y}:{},...U?{assignees:U}:{},...j?{labels:j}:{}},X={...J,verbose:Z.verbose??J.verbose,...Object.keys(G).length?{pullRequest:{...J.pullRequest,...G}}:{},packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},H=new f(X),q=await H.scanForUpdates();if(q.updates.length===0){$.success("All dependencies are up to date!");return}if(Z.dryRun){$.info("\uD83D\uDD0D Dry run mode - no changes will be made"),$.info(`Would create ${q.groups.length} pull request(s):`);for(let K of q.groups)$.info(` \uD83D\uDCDD ${K.title} (${K.updates.length} updates)`);return}await H.createPullRequests(q),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),await g(J.notifications,"run.failed",{command:"update",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("rebase <pr-number>","Rebase/retry a pull request by recreating it with latest updates").option("--verbose, -v","Enable verbose logging").option("--force","Force rebase even if PR appears to be up to date").example("buddy rebase 17").example("buddy rebase 17 --verbose").example("buddy rebase 17 --force").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{if(J.info(`\uD83D\uDD04 Rebasing/retrying PR #${Z}...`),!Q.repository)J.error("\u274C Repository configuration required for PR operations"),J.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let z=await m(Q,"PR operations",J),Y=Number.parseInt(Z,10);if(Number.isNaN(Y))J.error("\u274C Invalid PR number provided"),V.exit(1);let j=(await z.getPullRequests("open")).find((M)=>M.number===Y);if(!j)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!j.head.startsWith("buddy/"))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${j.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${j.title}`),J.info(`\uD83C\uDF3F Branch: ${j.head}`);let G=await kZ(j.body);if(G.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${G.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let E=(await new f(Q).scanForUpdates()).updates.filter((N)=>G.some((b)=>b.name===N.name));if(G.every((N)=>E.some((b)=>b.name===N.name&&b.newVersion===N.newVersion))){J.success("\u2705 PR is already up to date, no rebase needed"),J.info("\uD83D\uDCA1 Use --force to rebase anyway");return}}J.info("\uD83D\uDD04 Updating PR with latest updates...");let X=new f({...Q,verbose:$.verbose??Q.verbose}),H=await X.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let q=H.groups.find((M)=>M.updates.length===G.length&&M.updates.every((L)=>G.some((E)=>E.name===L.name))&&G.every((L)=>M.updates.some((E)=>E.name===L.name)));if(!q){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${G.map((M)=>M.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((M)=>`${M.name} (${M.updates.length} packages)`).join(", ")}`),J.info("\uD83D\uDCA1 Close this PR manually and let buddy create new ones with correct grouping");return}let K=await X.generateAllFileUpdates(q.updates);if(K.length===0){J.info(`\u2139\uFE0F No file changes generated for PR #${Y} \u2014 likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`);let M=j.body||"",L=M.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(L!==M)await z.updatePullRequest(Y,{body:L}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let F=Q.repository?.baseBranch||"main";await z.commitChanges(j.head,q.title,K,F),J.info(`\u2705 Recreated branch ${j.head} from ${F} with latest changes`);let{PullRequestGenerator:W}=await import("../chunk-xznnmhyt.js"),B=(await new W({verbose:$.verbose}).generateBody(q)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:q.title,body:B}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function kZ(Z){let $=Z0(Z);if($?.truncated)return[];if($)return $0($);let J=[],Q=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g,z;while((z=Q.exec(Z))!==null){let[,Y,U,j]=z;J.push({name:Y,currentVersion:U,newVersion:j})}return J}w.command("update-check","Check all open buddy PRs for rebase checkbox and auto-rebase if checked").option("--verbose, -v","Enable verbose logging").option("--dry-run","Check but don't actually rebase").example("buddy update-check").example("buddy update-check --verbose").example("buddy update-check --dry-run").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{if(!J.repository)$.error("\u274C Repository configuration required for PR operations"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q=await m(J,"PR operations",$),z=await bZ(Q,J,$),Y=t1(z?.body);if(A1(Y))$.info(`\uD83D\uDCCB Dashboard requests: ${Y.rebaseBranches.length} branch(es)${Y.rebaseAll?", rebase all":""}${Y.manualRun?", manual run":""}`);let U=new Set(Y.rebaseBranches);$.info("\uD83D\uDD0D Checking for PRs with rebase checkbox enabled...");let j=0,G=0;try{let K=(await Q.getPullRequests("open")).filter((F)=>F.head.startsWith("buddy/"));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let F of K){G++;let W=Y.rebaseAll||U.has(F.head);if(hZ(F.body||"")||W)if($.info(`\uD83D\uDD04 PR #${F.number} has rebase ${W?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${F.number}`),j++;else{$.info(`\uD83D\uDD04 Rebasing PR #${F.number} via rebase command...`);try{let{spawn:A}=await import("child_process"),B=A("bunx",["@buddysh/buddy","rebase",F.number.toString()],{stdio:"inherit",cwd:V.cwd()});await new Promise((M,L)=>{B.on("close",(E)=>{if(E===0)j++,M(E);else L(Error(`Rebase failed with code ${E}`))})}),$.success(`\u2705 Successfully rebased PR #${F.number}`)}catch(A){$.error(`\u274C Failed to rebase PR #${F.number}:`,A)}}}if(j>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${j} PR(s)`);else if(G>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(q){$.warn("\u26A0\uFE0F Could not check for rebase requests:",q)}if(A1(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:s1(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(q){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",q)}if(Y.manualRun)if($.info("\uD83D\uDD04 Dashboard requested a full update run..."),Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would run a full scan and create PRs");else try{let q=new f(J),K=await q.scanForUpdates();if(K.updates.length>0)await q.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(q){$.error("\u274C Requested update run failed:",q)}}$.info(`
142
- \u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:q}=await import("../chunk-847g7jde.js");await new q(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",q)}$.info(`
143
- \uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:q}=await import("../chunk-847g7jde.js");await new q(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",q)}let X=0;try{if(X=(await new f(J).mergeEligiblePullRequests(!!Z.dryRun)).length,X>0)$.success(`\uD83D\uDD00 ${Z.dryRun?"Would merge":"Merged"} ${X} PR(s)`)}catch(q){$.warn("\u26A0\uFE0F Could not process auto-merge:",q)}$.info(`
141
+ \uD83D\uDCCB Update groups (${j.groups.length}):`);for(let q of j.groups)$.info(` ${q.name}: ${q.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),await g(J.notifications,"run.failed",{command:"scan",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("dashboard","Create or update dependency dashboard issue").option("--verbose, -v","Enable verbose logging").option("--title <title>","Custom dashboard title").option("--issue-number <number>","Update specific issue number").option("--pin","Pin the dashboard issue to the top of the issue list").option("--no-pin","Unpin the dashboard issue").example("buddy dashboard").example('buddy dashboard --title "My Dependencies"').example("buddy dashboard --issue-number 42").example("buddy dashboard --pin").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);if(J.dashboard?.enabled===!1){$.info("\u2139\uFE0F Dashboard is disabled by config (dashboard.enabled: false)");return}try{if($.info("Creating or updating dependency dashboard..."),!J.repository)$.error("\u274C Repository configuration required for dashboard"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q={...J,verbose:Z.verbose??J.verbose,dashboard:{...J.dashboard,enabled:!0,title:Z.title??J.dashboard?.title,issueNumber:Z.issueNumber?Number.parseInt(Z.issueNumber,10):J.dashboard?.issueNumber,pin:Z.pin??J.dashboard?.pin}},Y=await new f(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),await g(J.notifications,"run.failed",{command:"dashboard",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--reviewers <names>","Comma-separated reviewers to assign (overrides pullRequest.reviewers)").option("--assignees <names>","Comma-separated assignees to assign (overrides pullRequest.assignees)").option("--labels <names>","Comma-separated labels to add (overrides pullRequest.labels)").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy update").example("buddy update --dry-run").example("buddy update --strategy patch").example("buddy update --verbose").example("buddy update --no-respect-latest").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((K)=>K.trim());let z=(K)=>K?K.split(",").map((F)=>F.trim()).filter(Boolean):void 0,Y=z(Z.reviewers),U=z(Z.assignees),j=z(Z.labels),G={...Y?{reviewers:Y}:{},...U?{assignees:U}:{},...j?{labels:j}:{}},X={...J,verbose:Z.verbose??J.verbose,...Object.keys(G).length?{pullRequest:{...J.pullRequest,...G}}:{},packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},H=new f(X),q=await H.scanForUpdates();if(q.updates.length===0){$.success("All dependencies are up to date!");return}if(Z.dryRun){$.info("\uD83D\uDD0D Dry run mode - no changes will be made"),$.info(`Would create ${q.groups.length} pull request(s):`);for(let K of q.groups)$.info(` \uD83D\uDCDD ${K.title} (${K.updates.length} updates)`);return}await H.createPullRequests(q),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),await g(J.notifications,"run.failed",{command:"update",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("rebase <pr-number>","Rebase/retry a pull request by recreating it with latest updates").option("--verbose, -v","Enable verbose logging").option("--force","Force rebase even if PR appears to be up to date").example("buddy rebase 17").example("buddy rebase 17 --verbose").example("buddy rebase 17 --force").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{if(J.info(`\uD83D\uDD04 Rebasing/retrying PR #${Z}...`),!Q.repository)J.error("\u274C Repository configuration required for PR operations"),J.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let z=await m(Q,"PR operations",J),Y=Number.parseInt(Z,10);if(Number.isNaN(Y))J.error("\u274C Invalid PR number provided"),V.exit(1);let j=(await z.getPullRequests("open")).find((M)=>M.number===Y);if(!j)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!j.head.startsWith("buddy/"))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${j.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${j.title}`),J.info(`\uD83C\uDF3F Branch: ${j.head}`);let G=await kZ(j.body);if(G.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${G.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let E=(await new f(Q).scanForUpdates()).updates.filter((N)=>G.some((b)=>b.name===N.name));if(G.every((N)=>E.some((b)=>b.name===N.name&&b.newVersion===N.newVersion))){J.success("\u2705 PR is already up to date, no rebase needed"),J.info("\uD83D\uDCA1 Use --force to rebase anyway");return}}J.info("\uD83D\uDD04 Updating PR with latest updates...");let X=new f({...Q,verbose:$.verbose??Q.verbose}),H=await X.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let q=H.groups.find((M)=>M.updates.length===G.length&&M.updates.every((L)=>G.some((E)=>E.name===L.name))&&G.every((L)=>M.updates.some((E)=>E.name===L.name)));if(!q){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${G.map((M)=>M.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((M)=>`${M.name} (${M.updates.length} packages)`).join(", ")}`),J.info("\uD83D\uDCA1 Close this PR manually and let buddy create new ones with correct grouping");return}let K=await X.generateAllFileUpdates(q.updates);if(K.length===0){J.info(`\u2139\uFE0F No file changes generated for PR #${Y} \u2014 likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`);let M=j.body||"",L=M.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(L!==M)await z.updatePullRequest(Y,{body:L}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let F=Q.repository?.baseBranch||"main";await z.commitChanges(j.head,q.title,K,F),J.info(`\u2705 Recreated branch ${j.head} from ${F} with latest changes`);let{PullRequestGenerator:W}=await import("../chunk-xznnmhyt.js"),B=(await new W({verbose:$.verbose}).generateBody(q)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:q.title,body:B}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function kZ(Z){let $=Z0(Z);if($?.truncated)return[];if($)return $0($);let J=[],Q=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g,z;while((z=Q.exec(Z))!==null){let[,Y,U,j]=z;J.push({name:Y,currentVersion:U,newVersion:j})}return J}w.command("update-check","Check all open buddy PRs for rebase checkbox and auto-rebase if checked").option("--verbose, -v","Enable verbose logging").option("--dry-run","Check but don't actually rebase").example("buddy update-check").example("buddy update-check --verbose").example("buddy update-check --dry-run").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{if(!J.repository)$.error("\u274C Repository configuration required for PR operations"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q=await m(J,"PR operations",$),z=await bZ(Q,J,$),Y=s1(z?.body);if(A1(Y))$.info(`\uD83D\uDCCB Dashboard requests: ${Y.rebaseBranches.length} branch(es)${Y.rebaseAll?", rebase all":""}${Y.manualRun?", manual run":""}`);let U=new Set(Y.rebaseBranches);$.info("\uD83D\uDD0D Checking for PRs with rebase checkbox enabled...");let j=0,G=0;try{let K=(await Q.getPullRequests("open")).filter((F)=>F.head.startsWith("buddy/"));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let F of K){G++;let W=Y.rebaseAll||U.has(F.head);if(hZ(F.body||"")||W)if($.info(`\uD83D\uDD04 PR #${F.number} has rebase ${W?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${F.number}`),j++;else{$.info(`\uD83D\uDD04 Rebasing PR #${F.number} via rebase command...`);try{let{spawn:A}=await import("child_process"),B=A("bunx",["@buddysh/buddy","rebase",F.number.toString()],{stdio:"inherit",cwd:V.cwd()});await new Promise((M,L)=>{B.on("close",(E)=>{if(E===0)j++,M(E);else L(Error(`Rebase failed with code ${E}`))})}),$.success(`\u2705 Successfully rebased PR #${F.number}`)}catch(A){$.error(`\u274C Failed to rebase PR #${F.number}:`,A)}}}if(j>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${j} PR(s)`);else if(G>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(q){$.warn("\u26A0\uFE0F Could not check for rebase requests:",q)}if(A1(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:t1(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(q){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",q)}if(Y.manualRun)if($.info("\uD83D\uDD04 Dashboard requested a full update run..."),Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would run a full scan and create PRs");else try{let q=new f(J),K=await q.scanForUpdates();if(K.updates.length>0)await q.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(q){$.error("\u274C Requested update run failed:",q)}}$.info(`
142
+ \u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:q}=await import("../chunk-rwggcfgn.js");await new q(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",q)}$.info(`
143
+ \uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:q}=await import("../chunk-rwggcfgn.js");await new q(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",q)}let X=0;try{if(X=(await new f(J).mergeEligiblePullRequests(!!Z.dryRun)).length,X>0)$.success(`\uD83D\uDD00 ${Z.dryRun?"Would merge":"Merged"} ${X} PR(s)`)}catch(q){$.warn("\u26A0\uFE0F Could not process auto-merge:",q)}$.info(`
144
144
  \uD83E\uDDF9 Running branch cleanup...`),z1(Q,"branchHousekeeping","cleanupStaleBranches","branch cleanup");let H=await Q.cleanupStaleBranches(2,!!Z.dryRun);if(Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would delete ${H.deleted.length} stale branches`);else $.success(`\uD83C\uDF89 Cleanup complete: ${H.deleted.length} branches deleted, ${H.failed.length} failed`);if(j>0||X>0||H.deleted.length>0)$.success(`
145
- \uD83C\uDF89 Update-check complete: ${j} PR(s) rebased, ${X} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),await g(J.notifications,"run.failed",{command:"update-check",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});async function bZ(Z,$,J){try{let Q=await Z.getIssues("open"),z=$.dashboard?.issueNumber;if(z)return Q.find((U)=>U.number===z)??null;let Y=$.dashboard?.title??"Dependency Dashboard";return Q.find((U)=>U.title===Y)??Q.find((U)=>U.title.includes("Dependency Dashboard"))??null}catch(Q){return J.warn("\u26A0\uFE0F Could not load the dependency dashboard:",Q),null}}function hZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}w.command("fix-ci","Diagnose a failing workflow run and repair it when the fix is clear").option("--verbose, -v","Enable verbose logging").option("--run-id <id>","Workflow run to diagnose").option("--pr <number>","Pull request to comment on").option("--dry-run","Report the diagnosis without acting").example("buddy fix-ci --run-id 12345").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{let Q=await m(J,"this command",$),{runFixCi:z}=await import("../chunk-hbhmns7s.js"),Y=await z({config:J,provider:Q,logger:$,dryRun:Boolean(Z.dryRun),...Z.runId?{runId:Number.parseInt(Z.runId,10)}:{},...Z.pr?{prNumber:Number.parseInt(Z.pr,10)}:{}});$.success(`\u2705 ${Y}`)}catch(Q){$.error("fix-ci failed:",Q),await g(J.notifications,"run.failed",{command:"fix-ci",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("handle-comment","Handle an @buddy command from a GitHub event payload").option("--verbose, -v","Enable verbose logging").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--dry-run","Report what would run without acting").example("buddy handle-comment").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{let Q=Z.payload||V.env.GITHUB_EVENT_PATH;if(!Q)$.error("\u274C No event payload. Pass --payload or run inside GitHub Actions."),V.exit(1);let z=await Bun.file(Q).json(),Y=z.comment,U=z.issue??z.pull_request;if(!Y?.body||!U?.number){$.info("\u2139\uFE0F Event carries no comment; nothing to do");return}let{mentionsBot:j,parseCommand:G}=await import("../chunk-hd5j9e3c.js");if(!j(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let X=G(Y.body);if(!X){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await m(J,"this command",$),q=Y.user?.login??"",K=Y.user?.type==="Bot"||q.endsWith("[bot]"),F={login:q,isBot:K,canWrite:!K&&Q1(H,"permissionLookup","hasWriteAccess")?await H.hasWriteAccess(q):!1},W=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${X.name}\` from @${q} on #${U.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${X.name} (canWrite: ${F.canWrite})`);return}if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,"eyes");let{createHandlers:T,dispatchCommand:A}=await import("../chunk-hd5j9e3c.js"),{runReviewForPR:B}=await import("../chunk-ncrq3fvv.js"),M=await A({command:X,actor:F,number:U.number,isPullRequest:W,commentId:Y.id,logger:$},T({config:J,provider:H,review:async(L,E)=>await B({config:J,provider:H,prNumber:L,logger:$,...E}),rebase:async(L)=>{let{spawn:E}=await import("child_process");return await new Promise((I,N)=>{E("bunx",["@buddysh/buddy","rebase",String(L)],{stdio:"inherit"}).on("close",(k)=>k===0?I():N(Error(`rebase exited ${k}`)))}),"Rebased."},merge:async()=>await new f(J).mergeEligiblePullRequests(!1),fixCi:async(L)=>{let{runFixCi:E}=await import("../chunk-hbhmns7s.js");return await E({config:J,provider:H,prNumber:L,analysisOnly:!0,logger:$})},plan:async(L,E,I)=>{let{runPlan:N}=await import("../chunk-c3es7pgf.js");return await N({config:J,provider:H,number:L,isPullRequest:E,request:I,logger:$})},resolve:async(L)=>{let{resolveBuddyThreads:E}=await import("../chunk-t25apff9.js");return await E({provider:H,prNumber:L,logger:$})},remember:async(L,E)=>{let{addLearning:I,createLearning:N,loadLearnings:b,serializeLearnings:k,DEFAULT_LEARNINGS_FILE:d}=await import("../chunk-hsa07n7c.js"),y=J.repository?.baseBranch??"main",P=await b((t,p)=>H.getFileContent(t,p),y,d,$),v=N(L,{source:E.isPullRequest?{pr:E.number}:{issue:E.number}}),i=`buddy/learning-${v.id}`;return await H.commitChanges(i,"chore(buddy): record a learning",[{path:d,content:k(I(P,v)),type:"update"}],y),await H.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${E.number}:
145
+ \uD83C\uDF89 Update-check complete: ${j} PR(s) rebased, ${X} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),await g(J.notifications,"run.failed",{command:"update-check",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});async function bZ(Z,$,J){try{let Q=await Z.getIssues("open"),z=$.dashboard?.issueNumber;if(z)return Q.find((U)=>U.number===z)??null;let Y=$.dashboard?.title??"Dependency Dashboard";return Q.find((U)=>U.title===Y)??Q.find((U)=>U.title.includes("Dependency Dashboard"))??null}catch(Q){return J.warn("\u26A0\uFE0F Could not load the dependency dashboard:",Q),null}}function hZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}w.command("fix-ci","Diagnose a failing workflow run and repair it when the fix is clear").option("--verbose, -v","Enable verbose logging").option("--run-id <id>","Workflow run to diagnose").option("--pr <number>","Pull request to comment on").option("--dry-run","Report the diagnosis without acting").example("buddy fix-ci --run-id 12345").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{let Q=await m(J,"this command",$),{runFixCi:z}=await import("../chunk-emb5v4wv.js"),Y=await z({config:J,provider:Q,logger:$,dryRun:Boolean(Z.dryRun),...Z.runId?{runId:Number.parseInt(Z.runId,10)}:{},...Z.pr?{prNumber:Number.parseInt(Z.pr,10)}:{}});$.success(`\u2705 ${Y}`)}catch(Q){$.error("fix-ci failed:",Q),await g(J.notifications,"run.failed",{command:"fix-ci",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("handle-comment","Handle an @buddy command from a GitHub event payload").option("--verbose, -v","Enable verbose logging").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--dry-run","Report what would run without acting").example("buddy handle-comment").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);try{let Q=Z.payload||V.env.GITHUB_EVENT_PATH;if(!Q)$.error("\u274C No event payload. Pass --payload or run inside GitHub Actions."),V.exit(1);let z=await Bun.file(Q).json(),Y=z.comment,U=z.issue??z.pull_request;if(!Y?.body||!U?.number){$.info("\u2139\uFE0F Event carries no comment; nothing to do");return}let{mentionsBot:j,parseCommand:G}=await import("../chunk-hd5j9e3c.js");if(!j(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let X=G(Y.body);if(!X){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await m(J,"this command",$),q=Y.user?.login??"",K=Y.user?.type==="Bot"||q.endsWith("[bot]"),F={login:q,isBot:K,canWrite:!K&&Q1(H,"permissionLookup","hasWriteAccess")?await H.hasWriteAccess(q):!1},W=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${X.name}\` from @${q} on #${U.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${X.name} (canWrite: ${F.canWrite})`);return}if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,"eyes");let{createHandlers:T,dispatchCommand:A}=await import("../chunk-hd5j9e3c.js"),{runReviewForPR:B}=await import("../chunk-28y7eayr.js"),M=await A({command:X,actor:F,number:U.number,isPullRequest:W,commentId:Y.id,logger:$},T({config:J,provider:H,review:async(L,E)=>await B({config:J,provider:H,prNumber:L,logger:$,...E}),rebase:async(L)=>{let{spawn:E}=await import("child_process");return await new Promise((I,N)=>{E("bunx",["@buddysh/buddy","rebase",String(L)],{stdio:"inherit"}).on("close",(k)=>k===0?I():N(Error(`rebase exited ${k}`)))}),"Rebased."},merge:async()=>await new f(J).mergeEligiblePullRequests(!1),fixCi:async(L)=>{let{runFixCi:E}=await import("../chunk-emb5v4wv.js");return await E({config:J,provider:H,prNumber:L,analysisOnly:!0,logger:$})},plan:async(L,E,I)=>{let{runPlan:N}=await import("../chunk-c3es7pgf.js");return await N({config:J,provider:H,number:L,isPullRequest:E,request:I,logger:$})},resolve:async(L)=>{let{resolveBuddyThreads:E}=await import("../chunk-b1w41hfs.js");return await E({provider:H,prNumber:L,logger:$})},remember:async(L,E)=>{let{addLearning:I,createLearning:N,loadLearnings:b,serializeLearnings:k,DEFAULT_LEARNINGS_FILE:d}=await import("../chunk-hsa07n7c.js"),y=J.repository?.baseBranch??"main",P=await b((s,p)=>H.getFileContent(s,p),y,d,$),v=N(L,{source:E.isPullRequest?{pr:E.number}:{issue:E.number}}),i=`buddy/learning-${v.id}`;return await H.commitChanges(i,"chore(buddy): record a learning",[{path:d,content:k(I(P,v)),type:"update"}],y),await H.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${E.number}:
146
146
 
147
- > ${L}`,head:i,base:y,draft:!1}),`Noted. I opened a pull request adding it to \`${d}\` so it gets reviewed like any other change.`}}));if(M.reply)await H.createComment(U.number,M.reply);if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,M.handled?"rocket":"confused");$.success(M.handled?`\u2705 Handled \`${X.name}\``:`\u2139\uFE0F Did not run: ${M.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});w.command("review [pr-number]","Review a pull request, or local changes when no PR is given").option("--verbose, -v","Enable verbose logging").option("--base <branch>","Base branch to diff against for a local review").option("--staged","Review staged changes only").option("--branch","Review this branch against its base, rather than the working tree").option("--light","Analyzers only \u2014 no AI call, fast enough for a pre-commit hook").option("--format <name>","Output format: pretty|json|github|agent",{default:"pretty"}).option("--fix","Apply committable suggestions to the working tree").option("--yes","Apply fixes without confirming each one").option("--fail-on <severity>","Exit non-zero when a finding at or above this severity is found").option("--profile <name>","Review profile: chill|assertive").option("--summary-only","Post only the summary, without inline findings").option("--auto","Treat this as an automatic trigger, honouring the ai.review filters").option("--dry-run","Print the review instead of posting it").example("buddy review 42").example("buddy review --staged --light").example("buddy review --format agent | claude").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config),z=$.format??"pretty";if(!R1.includes(z))J.error(`\u274C Unknown format '${z}'. Expected one of ${R1.join(", ")}.`),V.exit(1);let Y=z!=="pretty",U=Y?O.silent():J;try{let{createAiClient:j}=await import("../chunk-hsa07n7c.js"),G=j(Q,U);if(!G&&(Z||!$.light))J.error("\u274C AI review needs an API key, or use --light for analyzers only. See https://buddy.sh/ai/providers"),V.exit(1);let{composeInstructions:X,reviewDiff:H}=await import("../chunk-t25apff9.js"),{collectLocalDiff:q,formatReview:K,shouldFail:F}=await import("../chunk-emyvrx5t.js"),{runAnalyzers:W}=await import("../chunk-a4hzzn28.js");if(Z){let I=await m(Q,"reviewing a pull request",U),{reviewPullRequest:N}=await import("../chunk-ncrq3fvv.js"),{status:b,result:k}=await N({config:Q,provider:I,prNumber:Number.parseInt(Z,10),trigger:$.auto?"automatic":"requested",...$.auto?{skipIfReviewed:!0}:{},logger:U,dryRun:Boolean($.dryRun),...$.summaryOnly?{summaryOnly:!0}:{},...$.profile?{profile:$.profile}:{}});if(J.success(`\u2705 ${b}`),await g(Q.notifications,"review.completed",{number:Number.parseInt(Z,10),findings:k?.findings.length??0}),k&&z!=="pretty")V.stdout.write(K(k,z));if(k&&$.failOn&&F(k.findings,$.failOn))V.exit(1);return}let T;{let I=$.base||Q.repository?.baseBranch||"main",N=$.staged?"staged":$.branch?"branch":"working";U.info(`\uD83D\uDD0D Reviewing ${N} changes${N==="branch"?` against ${I}`:""}...`),T=await q(N,I)}if(!T.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:A}=await import("../chunk-428c5652.js"),B=A(T).files.map((I)=>I.path),M=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await W({files:B,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:U});if($.light){let I={summary:`Static analysis of ${B.length} changed file(s).`,walkthrough:[],findings:M.findings,effort:1,omittedFiles:M.skipped.map((N)=>`${N.name} (${N.reason})`)};if(V.stdout.write(K(I,z)),$.fix){let N=await e1(I.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${N} suggestion(s)`)}if($.failOn&&F(I.findings,$.failOn))V.exit(1);return}let L=await H(G,{diff:T,profile:$.profile??Q.ai?.review?.profile,summaryOnly:$.summaryOnly??Q.ai?.review?.summaryOnly,instructions:X({global:Q.ai?.review?.instructions}),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,seenFingerprints:[],logger:U}),E={...L,findings:[...M.findings,...L.findings],omittedFiles:[...L.omittedFiles,...M.skipped.map((I)=>`${I.name} (${I.reason})`)]};if(V.stdout.write(K(E,z)),$.fix){let I=await e1(E.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${I} suggestion(s)`)}if($.failOn&&F(E.findings,$.failOn))V.exit(1)}catch(j){J.error("Review failed:",j),await g(Q.notifications,"run.failed",{command:"review",error:j instanceof Error?j.message:String(j)}),V.exit(1)}});w.command("check <packages...>","Check specific packages for updates").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy check react typescript").example("buddy check react --verbose").action(async(...Z)=>{let $=Z[Z.length-1],J=Z.slice(0,-1),Q=$.verbose?O.verbose():O.quiet(),z=await S($.config);if(!J.length)Q.error("No packages specified to check"),V.exit(1);try{Q.info(`Checking specific packages: ${J.join(", ")}`);let Y={...z,verbose:$.verbose??z.verbose,packages:{...z.packages,strategy:$.strategy??z.packages?.strategy??"all"}},j=await new f(Y).checkPackages(J);if(j.length===0)Q.success("All specified packages are up to date!");else{Q.info(`Found ${j.length} updates:`);for(let G of j)Q.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion} (${G.updateType})`)}}catch(Y){Q.error("Check failed:",Y),V.exit(1)}});w.command("schedule","Run automated dependency updates on schedule").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy schedule").example("buddy schedule --verbose").example("buddy schedule --strategy patch").action(async(Z)=>{let{Scheduler:$}=await import("../chunk-x23a6szw.js"),J=Z.verbose?O.verbose():O.quiet(),Q=await S(Z.config);try{J.info("\uD83D\uDD52 Starting Buddy Scheduler...");let z;if(Z.ignore)z=Z.ignore.split(",").map((G)=>G.trim());let Y={...Q,verbose:Z.verbose??Q.verbose,packages:{...Q.packages,strategy:Z.strategy??Q.packages?.strategy??"all",ignore:z??Q.packages?.ignore}};if(!Y.repository?.provider||!Y.repository?.owner||!Y.repository?.name)J.error("\u274C Repository configuration required for scheduling. Please configure:"),J.info(" - repository.provider (github)"),J.info(" - repository.owner"),J.info(" - repository.name"),J.info(" - repository.token (via environment variable)"),V.exit(1);let U=new $(Z.verbose),j=$.createJobFromConfig(Y,"cli-schedule");if(Z.strategy)switch(Z.strategy){case"major":j.schedule.cron=$.PRESETS.WEEKLY;break;case"minor":j.schedule.cron=$.PRESETS.TWICE_WEEKLY;break;case"patch":j.schedule.cron=$.PRESETS.DAILY;break;default:j.schedule.cron=$.PRESETS.WEEKLY}U.addJob(j),U.start(),J.success(`\u2705 Scheduler started with cron: ${j.schedule.cron}`),J.info("\uD83D\uDCC5 Next run:",j.nextRun?.toISOString()||"Unknown"),J.info("\uD83D\uDED1 Press Ctrl+C to stop the scheduler"),V.stdin.resume()}catch(z){J.error("Scheduler failed:",z),V.exit(1)}});w.command("generate-workflows",'Generate GitHub Actions workflow templates (deprecated - use "setup" instead)').option("--verbose, -v","Enable verbose logging").example("buddy generate-workflows").example("buddy generate-workflows --verbose").action(async(Z)=>{let{GitHubActionsTemplate:$}=await import("../chunk-b357cgb0.js"),{writeFileSync:J,mkdirSync:Q}=await import("fs"),{resolve:z}=await import("path"),Y=Z.verbose?O.verbose():O.quiet(),U=await S(Z.config);if(U.workflows?.enabled===!1){Y.info("\u2139\uFE0F Workflow generation is disabled by config (workflows.enabled: false)");return}console.log('\u26A0\uFE0F The "generate-workflows" command is deprecated.'),console.log(`\uD83D\uDCA1 Use "buddy setup" for a better interactive experience.
147
+ > ${L}`,head:i,base:y,draft:!1}),`Noted. I opened a pull request adding it to \`${d}\` so it gets reviewed like any other change.`}}));if(M.reply)await H.createComment(U.number,M.reply);if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,M.handled?"rocket":"confused");$.success(M.handled?`\u2705 Handled \`${X.name}\``:`\u2139\uFE0F Did not run: ${M.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});w.command("review [pr-number]","Review a pull request, or local changes when no PR is given").option("--verbose, -v","Enable verbose logging").option("--base <branch>","Base branch to diff against for a local review").option("--staged","Review staged changes only").option("--branch","Review this branch against its base, rather than the working tree").option("--light","Analyzers only \u2014 no AI call, fast enough for a pre-commit hook").option("--format <name>","Output format: pretty|json|github|agent",{default:"pretty"}).option("--fix","Apply committable suggestions to the working tree").option("--yes","Apply fixes without confirming each one").option("--fail-on <severity>","Exit non-zero when a finding at or above this severity is found").option("--profile <name>","Review profile: chill|assertive").option("--summary-only","Post only the summary, without inline findings").option("--auto","Treat this as an automatic trigger, honouring the ai.review filters").option("--dry-run","Print the review instead of posting it").example("buddy review 42").example("buddy review --staged --light").example("buddy review --format agent | claude").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config),z=$.format??"pretty";if(!R1.includes(z))J.error(`\u274C Unknown format '${z}'. Expected one of ${R1.join(", ")}.`),V.exit(1);let Y=z!=="pretty",U=Y?O.silent():J;try{let{createAiClient:j}=await import("../chunk-hsa07n7c.js"),G=j(Q,U);if(!G&&(Z||!$.light))J.error("\u274C AI review needs an API key, or use --light for analyzers only. See https://buddy.sh/ai/providers"),V.exit(1);let{composeInstructions:X,reviewDiff:H}=await import("../chunk-b1w41hfs.js"),{collectLocalDiff:q,formatReview:K,shouldFail:F}=await import("../chunk-emyvrx5t.js"),{runAnalyzers:W}=await import("../chunk-a4hzzn28.js");if(Z){let I=await m(Q,"reviewing a pull request",U),{reviewPullRequest:N}=await import("../chunk-28y7eayr.js"),{status:b,result:k}=await N({config:Q,provider:I,prNumber:Number.parseInt(Z,10),trigger:$.auto?"automatic":"requested",...$.auto?{skipIfReviewed:!0}:{},logger:U,dryRun:Boolean($.dryRun),...$.summaryOnly?{summaryOnly:!0}:{},...$.profile?{profile:$.profile}:{}});if(J.success(`\u2705 ${b}`),await g(Q.notifications,"review.completed",{number:Number.parseInt(Z,10),findings:k?.findings.length??0}),k&&z!=="pretty")V.stdout.write(K(k,z));if(k&&$.failOn&&F(k.findings,$.failOn))V.exit(1);return}let T;{let I=$.base||Q.repository?.baseBranch||"main",N=$.staged?"staged":$.branch?"branch":"working";U.info(`\uD83D\uDD0D Reviewing ${N} changes${N==="branch"?` against ${I}`:""}...`),T=await q(N,I)}if(!T.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:A}=await import("../chunk-428c5652.js"),B=A(T).files.map((I)=>I.path),M=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await W({files:B,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:U});if($.light){let I={summary:`Static analysis of ${B.length} changed file(s).`,walkthrough:[],findings:M.findings,effort:1,omittedFiles:M.skipped.map((N)=>`${N.name} (${N.reason})`)};if(V.stdout.write(K(I,z)),$.fix){let N=await e1(I.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${N} suggestion(s)`)}if($.failOn&&F(I.findings,$.failOn))V.exit(1);return}let L=await H(G,{diff:T,profile:$.profile??Q.ai?.review?.profile,summaryOnly:$.summaryOnly??Q.ai?.review?.summaryOnly,instructions:X({global:Q.ai?.review?.instructions}),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,seenFingerprints:[],logger:U}),E={...L,findings:[...M.findings,...L.findings],omittedFiles:[...L.omittedFiles,...M.skipped.map((I)=>`${I.name} (${I.reason})`)]};if(V.stdout.write(K(E,z)),$.fix){let I=await e1(E.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${I} suggestion(s)`)}if($.failOn&&F(E.findings,$.failOn))V.exit(1)}catch(j){J.error("Review failed:",j),await g(Q.notifications,"run.failed",{command:"review",error:j instanceof Error?j.message:String(j)}),V.exit(1)}});w.command("check <packages...>","Check specific packages for updates").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy check react typescript").example("buddy check react --verbose").action(async(...Z)=>{let $=Z[Z.length-1],J=Z.slice(0,-1),Q=$.verbose?O.verbose():O.quiet(),z=await S($.config);if(!J.length)Q.error("No packages specified to check"),V.exit(1);try{Q.info(`Checking specific packages: ${J.join(", ")}`);let Y={...z,verbose:$.verbose??z.verbose,packages:{...z.packages,strategy:$.strategy??z.packages?.strategy??"all"}},j=await new f(Y).checkPackages(J);if(j.length===0)Q.success("All specified packages are up to date!");else{Q.info(`Found ${j.length} updates:`);for(let G of j)Q.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion} (${G.updateType})`)}}catch(Y){Q.error("Check failed:",Y),V.exit(1)}});w.command("schedule","Run automated dependency updates on schedule").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy schedule").example("buddy schedule --verbose").example("buddy schedule --strategy patch").action(async(Z)=>{let{Scheduler:$}=await import("../chunk-e0gweha1.js"),J=Z.verbose?O.verbose():O.quiet(),Q=await S(Z.config);try{J.info("\uD83D\uDD52 Starting Buddy Scheduler...");let z;if(Z.ignore)z=Z.ignore.split(",").map((G)=>G.trim());let Y={...Q,verbose:Z.verbose??Q.verbose,packages:{...Q.packages,strategy:Z.strategy??Q.packages?.strategy??"all",ignore:z??Q.packages?.ignore}};if(!Y.repository?.provider||!Y.repository?.owner||!Y.repository?.name)J.error("\u274C Repository configuration required for scheduling. Please configure:"),J.info(" - repository.provider (github)"),J.info(" - repository.owner"),J.info(" - repository.name"),J.info(" - repository.token (via environment variable)"),V.exit(1);let U=new $(Z.verbose),j=$.createJobFromConfig(Y,"cli-schedule");if(Z.strategy)switch(Z.strategy){case"major":j.schedule.cron=$.PRESETS.WEEKLY;break;case"minor":j.schedule.cron=$.PRESETS.TWICE_WEEKLY;break;case"patch":j.schedule.cron=$.PRESETS.DAILY;break;default:j.schedule.cron=$.PRESETS.WEEKLY}U.addJob(j),U.start(),J.success(`\u2705 Scheduler started with cron: ${j.schedule.cron}`),J.info("\uD83D\uDCC5 Next run:",j.nextRun?.toISOString()||"Unknown"),J.info("\uD83D\uDED1 Press Ctrl+C to stop the scheduler"),V.stdin.resume()}catch(z){J.error("Scheduler failed:",z),V.exit(1)}});w.command("generate-workflows",'Generate GitHub Actions workflow templates (deprecated - use "setup" instead)').option("--verbose, -v","Enable verbose logging").example("buddy generate-workflows").example("buddy generate-workflows --verbose").action(async(Z)=>{let{GitHubActionsTemplate:$}=await import("../chunk-b357cgb0.js"),{writeFileSync:J,mkdirSync:Q}=await import("fs"),{resolve:z}=await import("path"),Y=Z.verbose?O.verbose():O.quiet(),U=await S(Z.config);if(U.workflows?.enabled===!1){Y.info("\u2139\uFE0F Workflow generation is disabled by config (workflows.enabled: false)");return}console.log('\u26A0\uFE0F The "generate-workflows" command is deprecated.'),console.log(`\uD83D\uDCA1 Use "buddy setup" for a better interactive experience.
148
148
  `);try{let j={...U,verbose:Z.verbose??U.verbose},G=j.workflows?.outputDir?z(V.cwd(),j.workflows.outputDir):z(V.cwd(),".github","workflows");Y.info("\uD83D\uDE80 Generating GitHub Actions workflow templates...");try{Q(G,{recursive:!0})}catch{}let X=j.workflows?.templates||{comprehensive:!0,daily:!0,weekly:!0,monthly:!0,docker:!0,monorepo:!0},H=0;if(X.daily||X.weekly||X.monthly){let q=$.generateScheduledWorkflows(j);for(let[K,F]of Object.entries(q))if(K.includes("daily")&&X.daily||K.includes("weekly")&&X.weekly||K.includes("monthly")&&X.monthly){let T=z(G,K);J(T,F),Y.success(`Generated: ${K}`),H++}}if(X.comprehensive){let q=$.generateComprehensiveWorkflow(j);J(z(G,"buddy-comprehensive.yml"),q),Y.success("Generated: buddy-comprehensive.yml"),H++}if(X.docker){let q=$.generateDockerWorkflow(j);J(z(G,"buddy-docker.yml"),q),Y.success("Generated: buddy-docker.yml"),H++}if(X.monorepo){let q=$.generateMonorepoWorkflow(j);J(z(G,"buddy-monorepo.yml"),q),Y.success("Generated: buddy-monorepo.yml"),H++}if(j.workflows?.custom?.length)for(let q of j.workflows.custom){let K=$.generateCustomWorkflow(q,j),F=`buddy-${q.name.toLowerCase().replace(/\s+/g,"-")}.yml`;J(z(G,F),K),Y.success(`Generated: ${F}`),H++}if(H===0){Y.warn("No workflows were generated. Check your configuration in buddy.config.ts"),Y.info("Set workflows.templates to enable specific templates or add custom workflows.");return}Y.success(`
149
149
  \uD83C\uDF89 ${H} GitHub Actions workflow(s) generated!`),Y.info(`\uD83D\uDCC1 Location: ${G}`),Y.info(`
150
150
  \uD83D\uDCA1 Next steps:`),Y.info(" 1. Review and customize the workflows for your project"),Y.info(" 2. Ensure GITHUB_TOKEN is available as a secret"),Y.info(" 3. Configure buddy.config.ts with your repository settings"),Y.info(" 4. Enable GitHub Actions in your repository settings"),Y.info(`
@@ -169,9 +169,9 @@ For manual setup, visit:`),$.info("\uD83D\uDD17 Repository settings: https://git
169
169
  `),V.exit(2);return}if(X)V.stdout.write(`${X}
170
170
  `);V.exit(j.failed?1:0)});w.command("touch <pr-number>","Run a finishing touch ticked on a pull request, as a stacked PR").option("--name <touch>","Run a specific touch rather than reading the checkboxes").option("--offer","Post the checkboxes on the pull request rather than running one").option("--test-command <command>","Command that verifies the change").option("--dry-run","Report what would run without acting").option("--verbose, -v","Enable verbose logging").example("buddy touch 42").example("buddy touch 42 --offer").example("buddy touch 42 --name unit-tests").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10),Y=await m(Q,"finishing touches",J),j=(await Y.getPullRequests("open")).find((M)=>M.number===z);if(!j)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let{FINISHING_TOUCHES:G,getFinishingTouch:X,hasTouchOffer:H,parseTouchSelections:q,withTouchOffer:K}=await import("../chunk-68fw3ma0.js");if($.offer){if(H(j.body)){J.info(`\u2139\uFE0F PR #${j.number} already carries the finishing-touch offer`);return}let M=K(j.body);if($.dryRun){J.info(`\uD83D\uDD0D [DRY RUN] Would offer finishing touches on PR #${j.number}`);return}await Y.updatePullRequest(j.number,{body:M}),J.success(`\u2705 Offered finishing touches on PR #${j.number}`);return}let F=$.name?[$.name]:q(j.body);if(F.length===0){J.info("\u2139\uFE0F No finishing touches are ticked on this pull request");return}let{createAiClient:W}=await import("../chunk-hsa07n7c.js"),T=W(Q,J);if(!T)J.error("\u274C Finishing touches need an API key. See https://buddy.sh/ai/providers"),V.exit(1);if($.dryRun){J.info(`\uD83D\uDD0D [DRY RUN] Would run: ${F.join(", ")}`);return}let{runStackedTouch:A}=await import("../chunk-90zmqn5k.js");for(let M of F){if(!G[M]){J.warn(`\u26A0\uFE0F Unknown finishing touch '${M}', skipping`);continue}let L=await A({provider:Y,pullRequest:j,touch:X(M),ai:T,workspace:V.cwd(),...$.testCommand?{testCommand:$.testCommand.split(" ")}:{},logger:J});await Y.createComment(z,L.comment),J.success(`\u2705 ${M}: ${L.mode}`)}let B=j.body.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*buddy:touch=)/gm,"$1[ ]$2");if(B!==j.body)await Y.updatePullRequest(z,{body:B})}catch(z){J.error("Finishing touch failed:",z),V.exit(1)}});w.command("handle-issue","Post Buddy quick-links on a new issue, or run a ticked action").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--issue <number>","Act on an issue directly rather than reading an event").option("--dry-run","Report what would happen without acting").option("--verbose, -v","Enable verbose logging").example("buddy handle-issue").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config);if(J.issues?.quickLinks!==!0){$.info("\u2139\uFE0F Issue quick-links are off (set issues.quickLinks to enable)");return}try{let Q=Z.issue?Number.parseInt(Z.issue,10):Number.NaN;if(Number.isNaN(Q)){let W=Z.payload||V.env.GITHUB_EVENT_PATH;if(!W)$.error("\u274C No event payload. Pass --issue or --payload, or run inside CI."),V.exit(1);let T=await Bun.file(W).json();if(Q=Number(T?.issue?.number),Number.isNaN(Q)){$.info("\u2139\uFE0F Event carries no issue; nothing to do");return}}let z=await m(J,"issue quick-links",$),U=(await z.getIssues("open")).find((W)=>W.number===Q);if(!U){$.info(`\u2139\uFE0F Issue #${Q} is not open`);return}let{clearQuickSelection:j,parseQuickSelection:G,QUICK_LINKS_MARKER:X,renderQuickLinks:H}=await import("../chunk-v1wfa758.js"),q=G(U.body);if(q.actions.length>0){if($.info(`\uD83E\uDD16 Requested: ${q.actions.join(", ")}`),Z.dryRun)return;let{createAiClient:W}=await import("../chunk-hsa07n7c.js"),T=W(J,$);if(!T){await z.createComment(Q,"Buddy needs an AI provider configured to act on this. See https://buddy.sh/ai/providers");return}await z.updateIssue(Q,{body:j(U.body)});for(let A of q.actions){if(A==="plan"){let{runPlan:b}=await import("../chunk-c3es7pgf.js"),k=await b({config:J,provider:z,number:Q,isPullRequest:!1,logger:$});await z.createComment(Q,k),$.success("\u2705 Ran plan");continue}let{BUILTIN_TOOLS:B,createReadIssueTool:M,getFinishingTouch:L,runAgent:E}=await import("../chunk-c3es7pgf.js"),I=L("autofix"),N=await E(T,{mode:I.mode,task:`${I.buildTask({files:[]})}
171
171
 
172
- Call \`read_issue\` to see what was asked for.`,tools:[...B,M(z,Q,!1)],context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,N.output||`I could not finish that (${N.stopReason}).`),$.success(`\u2705 Ran ${A}`)}return}if(U.body.includes(X)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await SZ(J,$):[],F=H({body:U.body,packages:K});if(Z.dryRun){$.info(F);return}await z.createComment(Q,F),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});w.command("gate <pr-number>","Run pre-merge gates on a pull request and publish the result").option("--dry-run","Print the result instead of publishing a check run").option("--verbose, -v","Enable verbose logging").example("buddy gate 42").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10);if(Number.isNaN(z))J.error("\u274C Invalid PR number"),V.exit(1);let Y=await m(Q,"running gates",J),{findLinkedIssues:U,runAiGates:j,runGates:G,gateIcon:X,summarizeGates:H}=await import("../chunk-hmskwy76.js"),{parseManifest:q}=await import("../chunk-ppmabn5h.js"),F=(await Y.getPullRequests("open")).find((P)=>P.number===z);if(!F)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},T=q(F.body),{manifestUpdates:A}=await import("../chunk-ppmabn5h.js"),B=T?await Promise.all(A(T).map(async(P)=>{let v={name:P.name,version:P.newVersion};if(W.dependencyGate?.blockEol===!1)return v;if(T.updates.find((S1)=>S1.name===P.name)?.dependencyType!=="docker-image")return v;let{checkEol:t,describeEol:p}=await import("../chunk-ds4stft2.js"),Y1=await t(P.name,P.newVersion,{logger:J}),s=p(Y1);return Y1?.eol&&s?{...v,eol:s}:v})):[],M=G({title:F.title,body:F.body,manifest:T,dependencies:B},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),L=U(F.body??""),E=L.length>0?await Y.getIssues("all"):[],I=L.map((P)=>E.find((v)=>v.number===P)).filter((P)=>Boolean(P)).map((P)=>({number:P.number,title:P.title,body:P.body})),{createAiClient:N}=await import("../chunk-hsa07n7c.js"),b=await j(N(Q,J),{title:F.title,body:F.body,diff:await Y.getPullRequestDiff(z),linkedIssues:I},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),k=[...M,...b],d=H(k);for(let P of k)J.info(`${X(P)} ${P.name}: ${P.summary}`);let y=d.conclusion==="failure";if(y)await g(Q.notifications,"gate.failed",{number:z,checks:k.filter((P)=>!P.passed).map((P)=>P.name)});if($.dryRun||!Q1(Y,"checkRuns","createCheckRun")){if(J.info(d.summary),y)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),d),y)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});w.command("post-merge <pr-number>","Run post-merge actions for a merged pull request").option("--verbose, -v","Enable verbose logging").example("buddy post-merge 42").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10),Y=await m(Q,"post-merge actions",J),j=(await Y.getPullRequests("all")).find((H)=>H.number===z);if(!j)J.error(`\u274C Pull request #${z} not found`),V.exit(1);if(j.state!=="merged"){J.info(`\u2139\uFE0F PR #${z} was closed without merging; nothing to do`);return}let{runPostMerge:G}=await import("../chunk-hmskwy76.js"),X=await G(Y,j,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??j.base,logger:J,refreshDashboard:async()=>{if(Q.dashboard?.enabled===!1)throw Error("dashboard.enabled is false");await new f(Q).createOrUpdateDashboard()}});for(let H of X.performed)J.success(`\u2705 ${H}`);for(let H of X.skipped)J.info(`\u23ED\uFE0F ${H.action}: ${H.reason}`)}catch(z){J.error("Post-merge actions failed:",z),V.exit(1)}});w.command("report","Generate a dependency-health and activity report").option("--period <window>","Reporting window: 7d|30d|90d",{default:"30d"}).option("--format <name>","Output format: markdown|json",{default:"markdown"}).option("--prompt <focus>","Focus for the AI narrative, when a provider is configured").option("--publish","Publish to the repository's report issue").option("--scheduled","This is the workflow's scheduled run; honour reports.enabled").option("--verbose, -v","Enable verbose logging").example("buddy report --period 7d").example('buddy report --prompt "focus on security posture" --publish').action(async(Z)=>{let $=Z.format==="json",J=Z.verbose?O.verbose():$?O.silent():O.quiet(),Q=await S(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:j,HISTORY_PATH:G,loadHistory:X,REPORT_MARKER:H,REPORT_PERIODS:q,renderReport:K,withNarrative:F}=await import("../chunk-zgkrhymn.js"),W=Z.period??Q.reports?.period??"30d";if(!q.includes(W))J.error(`\u274C Unknown period '${W}'. Expected one of ${q.join(", ")}.`),V.exit(1);let T=await m(Q,"reporting",J),A=new f(Q,V.cwd()),{PackageScanner:B}=await import("../chunk-fpnjpgrb.js"),M=new B(V.cwd(),J,Q.packages?.ignorePaths),[L,E,I]=await Promise.all([A.scanForUpdates(),T.getPullRequests("all"),M.scanProject()]),{ecosystemOf:N}=await import("../chunk-49znmbh8.js"),b={};for(let X1 of I)for(let j1 of X1.dependencies){let y1=N({name:j1.name,currentVersion:j1.currentVersion,newVersion:j1.currentVersion,updateType:"patch",dependencyType:j1.type,file:X1.path});b[y1]=(b[y1]??0)+1}let{DeprecatedDependenciesChecker:k}=await import("../chunk-vj1sdxpp.js"),d=await new k().checkDeprecatedDependencies(I).catch(()=>[]),y=U({period:W,now:new Date,pullRequests:E,updates:L.updates,dependenciesByEcosystem:b,deprecated:d.length}),P=Q.repository?.baseBranch||"main",v=await X(T,P,J),i=Y(y,j(v,W));if(Z.format==="json"){V.stdout.write(`${JSON.stringify({metrics:y,deltas:i},null,2)}
173
- `);return}let{createAiClient:t}=await import("../chunk-hsa07n7c.js"),p=await F(K(y,i),y,t(Q,J),Z.prompt??Q.reports?.prompt,J),{shouldPublishReport:Y1}=await import("../chunk-zgkrhymn.js"),s=Y1({scheduled:Boolean(Z.scheduled),enabled:Q.reports?.enabled});if(Z.publish&&!s.publish){J.info(`\u2139\uFE0F Not publishing: ${s.reason}`);return}if(!Z.publish){V.stdout.write(`${p}
174
- `);return}let k1=(await T.getIssues("open")).find((X1)=>X1.body.includes(H)),b1=Q.reports?.title??"Dependency Report",h1=Q.reports?.labels??["dependencies","report"],T0=k1?await T.updateIssue(k1.number,{title:b1,body:p,labels:h1}):await T.createIssue({title:b1,body:p,labels:h1});J.success(`\u2705 Report published: ${T0.url}`),await T.commitChanges(P,"chore(reports): record dependency metrics snapshot",[{path:G,content:z(v,y),type:v.length>0?"update":"create"}],P)}catch(z){J.error("Report failed:",z),V.exit(1)}});w.command("doctor","Diagnose this environment: credentials, git state and analyzer tooling").option("--verbose, -v","Enable verbose logging").example("buddy doctor").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${r(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-y3dd8v85.js"),Y=await Q(J);if(V.stdout.write(z(Y)),!Y.healthy)V.exit(1)});w.command("run","Run a prompt headlessly, with optional schema-validated output").option("--prompt <text>","The prompt to run").option("--prompt-file <path>","Read the prompt from a file").option("--output-schema <json>","JSON Schema the output must satisfy").option("--output-schema-file <path>","Read the schema from a file").option("--model <name>","Model override").option("--retries <n>","Schema retries before failing",{default:"2"}).option("--verbose, -v","Enable verbose logging").example(`buddy run --prompt "Summarize this week's dependency updates"`).example(`buddy run --prompt-file p.txt --output-schema '{"type":"object"}'`).action(async(Z)=>{let $=Z.verbose?O.verbose():O.silent(),J=await S(Z.config);try{let Q=Z.promptFile?await Bun.file(Z.promptFile).text():Z.prompt;if(!Q?.trim())V.stderr.write(`\u274C Provide --prompt or --prompt-file
172
+ Call \`read_issue\` to see what was asked for.`,tools:[...B,M(z,Q,!1)],context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,N.output||`I could not finish that (${N.stopReason}).`),$.success(`\u2705 Ran ${A}`)}return}if(U.body.includes(X)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await SZ(J,$):[],F=H({body:U.body,packages:K});if(Z.dryRun){$.info(F);return}await z.createComment(Q,F),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});w.command("gate <pr-number>","Run pre-merge gates on a pull request and publish the result").option("--dry-run","Print the result instead of publishing a check run").option("--verbose, -v","Enable verbose logging").example("buddy gate 42").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10);if(Number.isNaN(z))J.error("\u274C Invalid PR number"),V.exit(1);let Y=await m(Q,"running gates",J),{findLinkedIssues:U,runAiGates:j,runGates:G,gateIcon:X,summarizeGates:H}=await import("../chunk-hmskwy76.js"),{parseManifest:q}=await import("../chunk-ppmabn5h.js"),F=(await Y.getPullRequests("open")).find((P)=>P.number===z);if(!F)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},T=q(F.body),{manifestUpdates:A}=await import("../chunk-ppmabn5h.js"),B=T?await Promise.all(A(T).map(async(P)=>{let v={name:P.name,version:P.newVersion};if(W.dependencyGate?.blockEol===!1)return v;if(T.updates.find((S1)=>S1.name===P.name)?.dependencyType!=="docker-image")return v;let{checkEol:s,describeEol:p}=await import("../chunk-ds4stft2.js"),Y1=await s(P.name,P.newVersion,{logger:J}),t=p(Y1);return Y1?.eol&&t?{...v,eol:t}:v})):[],M=G({title:F.title,body:F.body,manifest:T,dependencies:B},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),L=U(F.body??""),E=L.length>0?await Y.getIssues("all"):[],I=L.map((P)=>E.find((v)=>v.number===P)).filter((P)=>Boolean(P)).map((P)=>({number:P.number,title:P.title,body:P.body})),{createAiClient:N}=await import("../chunk-hsa07n7c.js"),b=await j(N(Q,J),{title:F.title,body:F.body,diff:await Y.getPullRequestDiff(z),linkedIssues:I},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),k=[...M,...b],d=H(k);for(let P of k)J.info(`${X(P)} ${P.name}: ${P.summary}`);let y=d.conclusion==="failure";if(y)await g(Q.notifications,"gate.failed",{number:z,checks:k.filter((P)=>!P.passed).map((P)=>P.name)});if($.dryRun||!Q1(Y,"checkRuns","createCheckRun")){if(J.info(d.summary),y)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),d),y)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});w.command("post-merge <pr-number>","Run post-merge actions for a merged pull request").option("--verbose, -v","Enable verbose logging").example("buddy post-merge 42").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await S($.config);try{let z=Number.parseInt(Z,10),Y=await m(Q,"post-merge actions",J),j=(await Y.getPullRequests("all")).find((H)=>H.number===z);if(!j)J.error(`\u274C Pull request #${z} not found`),V.exit(1);if(j.state!=="merged"){J.info(`\u2139\uFE0F PR #${z} was closed without merging; nothing to do`);return}let{runPostMerge:G}=await import("../chunk-hmskwy76.js"),X=await G(Y,j,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??j.base,logger:J,refreshDashboard:async()=>{if(Q.dashboard?.enabled===!1)throw Error("dashboard.enabled is false");await new f(Q).createOrUpdateDashboard()}});for(let H of X.performed)J.success(`\u2705 ${H}`);for(let H of X.skipped)J.info(`\u23ED\uFE0F ${H.action}: ${H.reason}`)}catch(z){J.error("Post-merge actions failed:",z),V.exit(1)}});w.command("report","Generate a dependency-health and activity report").option("--period <window>","Reporting window: 7d|30d|90d",{default:"30d"}).option("--format <name>","Output format: markdown|json",{default:"markdown"}).option("--prompt <focus>","Focus for the AI narrative, when a provider is configured").option("--publish","Publish to the repository's report issue").option("--scheduled","This is the workflow's scheduled run; honour reports.enabled").option("--verbose, -v","Enable verbose logging").example("buddy report --period 7d").example('buddy report --prompt "focus on security posture" --publish').action(async(Z)=>{let $=Z.format==="json",J=Z.verbose?O.verbose():$?O.silent():O.quiet(),Q=await S(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:j,HISTORY_PATH:G,loadHistory:X,REPORT_MARKER:H,REPORT_PERIODS:q,renderReport:K,withNarrative:F}=await import("../chunk-zgkrhymn.js"),W=Z.period??Q.reports?.period??"30d";if(!q.includes(W))J.error(`\u274C Unknown period '${W}'. Expected one of ${q.join(", ")}.`),V.exit(1);let T=await m(Q,"reporting",J),A=new f(Q,V.cwd()),{PackageScanner:B}=await import("../chunk-fpnjpgrb.js"),M=new B(V.cwd(),J,Q.packages?.ignorePaths),[L,E,I]=await Promise.all([A.scanForUpdates(),T.getPullRequests("all"),M.scanProject()]),{ecosystemOf:N}=await import("../chunk-49znmbh8.js"),b={};for(let X1 of I)for(let j1 of X1.dependencies){let y1=N({name:j1.name,currentVersion:j1.currentVersion,newVersion:j1.currentVersion,updateType:"patch",dependencyType:j1.type,file:X1.path});b[y1]=(b[y1]??0)+1}let{DeprecatedDependenciesChecker:k}=await import("../chunk-vj1sdxpp.js"),d=await new k().checkDeprecatedDependencies(I).catch(()=>[]),y=U({period:W,now:new Date,pullRequests:E,updates:L.updates,dependenciesByEcosystem:b,deprecated:d.length}),P=Q.repository?.baseBranch||"main",v=await X(T,P,J),i=Y(y,j(v,W));if(Z.format==="json"){V.stdout.write(`${JSON.stringify({metrics:y,deltas:i},null,2)}
173
+ `);return}let{createAiClient:s}=await import("../chunk-hsa07n7c.js"),p=await F(K(y,i),y,s(Q,J),Z.prompt??Q.reports?.prompt,J),{shouldPublishReport:Y1}=await import("../chunk-zgkrhymn.js"),t=Y1({scheduled:Boolean(Z.scheduled),enabled:Q.reports?.enabled});if(Z.publish&&!t.publish){J.info(`\u2139\uFE0F Not publishing: ${t.reason}`);return}if(!Z.publish){V.stdout.write(`${p}
174
+ `);return}let k1=(await T.getIssues("open")).find((X1)=>X1.body.includes(H)),b1=Q.reports?.title??"Dependency Report",h1=Q.reports?.labels??["dependencies","report"],T0=k1?await T.updateIssue(k1.number,{title:b1,body:p,labels:h1}):await T.createIssue({title:b1,body:p,labels:h1});J.success(`\u2705 Report published: ${T0.url}`),await T.commitChanges(P,"chore(reports): record dependency metrics snapshot",[{path:G,content:z(v,y),type:v.length>0?"update":"create"}],P)}catch(z){J.error("Report failed:",z),V.exit(1)}});w.command("doctor","Diagnose this environment: credentials, git state and analyzer tooling").option("--verbose, -v","Enable verbose logging").example("buddy doctor").action(async(Z)=>{let $=Z.verbose?O.verbose():O.quiet(),J=await S(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${r(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-s25rb4t2.js"),Y=await Q(J);if(V.stdout.write(z(Y)),!Y.healthy)V.exit(1)});w.command("run","Run a prompt headlessly, with optional schema-validated output").option("--prompt <text>","The prompt to run").option("--prompt-file <path>","Read the prompt from a file").option("--output-schema <json>","JSON Schema the output must satisfy").option("--output-schema-file <path>","Read the schema from a file").option("--model <name>","Model override").option("--retries <n>","Schema retries before failing",{default:"2"}).option("--verbose, -v","Enable verbose logging").example(`buddy run --prompt "Summarize this week's dependency updates"`).example(`buddy run --prompt-file p.txt --output-schema '{"type":"object"}'`).action(async(Z)=>{let $=Z.verbose?O.verbose():O.silent(),J=await S(Z.config);try{let Q=Z.promptFile?await Bun.file(Z.promptFile).text():Z.prompt;if(!Q?.trim())V.stderr.write(`\u274C Provide --prompt or --prompt-file
175
175
  `),V.exit(1);let z=Z.outputSchemaFile?await Bun.file(Z.outputSchemaFile).text():Z.outputSchema,Y;if(z)try{Y=JSON.parse(z)}catch(F){V.stderr.write(`\u274C --output-schema is not valid JSON: ${r(F)}
176
176
  `),V.exit(1)}let{createAiClient:U}=await import("../chunk-hsa07n7c.js"),j=U(Z.model?{...J,ai:{...J.ai,model:Z.model}}:J,$);if(!j)V.stderr.write(`\u274C No AI provider configured. See https://buddy.sh/ai/providers
177
177
  `),V.exit(1);let{publishOutput:G,runHeadless:X}=await import("../chunk-gkpd5nw2.js"),H=await X({prompt:Q,ai:j,...Y?{schema:Y}:{},maxRetries:Number.parseInt(Z.retries??"2",10),logger:$});if(!H.valid)V.stderr.write(`\u274C Output did not satisfy the schema after ${H.attempts} attempt(s):
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Cb as a,Db as b}from"./chunk-1c4690h9.js";import"./chunk-q2tjkhez.js";import"./chunk-5yfaptmp.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-p8tmms5h.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{b as runReviewForPR,a as reviewPullRequest};
2
+ import{Cb as a,Db as b}from"./chunk-4jyw358y.js";import"./chunk-q2tjkhez.js";import"./chunk-5yfaptmp.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-5av2vnvv.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{b as runReviewForPR,a as reviewPullRequest};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-rc2mk5x6.js";import{fc as s}from"./chunk-tjc2vgwn.js";import{$d as i}from"./chunk-nrr8z2z7.js";import{me as S}from"./chunk-p8tmms5h.js";import{Jf as b,Kf as m}from"./chunk-1cpdz49v.js";import{Fh as Y}from"./chunk-hfjywbbc.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
2
+ import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-rc2mk5x6.js";import{fc as s}from"./chunk-tjc2vgwn.js";import{$d as i}from"./chunk-nrr8z2z7.js";import{me as S}from"./chunk-5av2vnvv.js";import{Jf as b,Kf as m}from"./chunk-1cpdz49v.js";import{Fh as Y}from"./chunk-hfjywbbc.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
3
3
 
4
4
  Report only defects you can point at in the diff. A review that invents
5
5
  findings to look thorough is worse than one that reports nothing, so say
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Wk as Z}from"./chunk-q4t568hv.js";import x from"process";var K=["github","gitlab","bitbucket"],$=["github","gitlab","bitbucket"],H={},L={pinIssues:!1,checkRuns:!1,inlineReviewComments:!1,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!1,branchHousekeeping:!1,reopenPullRequests:!1,labels:!1};class Y extends Error{provider;trackingIssue;constructor(j,z,F){super(j);this.provider=z;this.trackingIssue=F;this.name="UnsupportedProviderError"}}var B={github:["GITHUB_TOKEN","BUDDY_TOKEN"],gitlab:["CI_JOB_TOKEN","GITLAB_TOKEN","BUDDY_TOKEN"],bitbucket:["BITBUCKET_TOKEN","BUDDY_TOKEN"]};function A(j,z=x.env){for(let F of B[j]??[]){let J=z[F]?.trim();if(J)return{token:J,source:F}}return null}function C(j){if($.includes(j))return;let z=H[j];if(z)throw new Y(`'${j}' support is not implemented yet \u2014 follow ${z}. Supported today: ${$.join(", ")}.`,j,z);throw new Y(`Unknown git provider '${j}'. Supported: ${$.join(", ")}.`,j)}async function M(j,z={}){let F=j.provider??"github";C(F);let J=z.env??x.env,X=j.token??A(F,J)?.token;if(!X)throw Error(`No token for ${F}. Set one of: ${B[F].join(", ")}.`);switch(F){case"gitlab":{let{GitLabProvider:Q}=await import("./chunk-hns85dqw.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-brfyymhf.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-hwxmhkxp.js"),q=j.workflowToken??J.BUDDY_TOKEN;return new Q(X,j.owner,j.name,Boolean(q),q,j.apiUrl,z.logger)}}}function W(j,z,F){return j.capabilities()[z]===!0&&typeof j[F]==="function"}function S(j,z,F,J){if(W(j,z,F))return;throw new Y(`This provider does not support ${J} (missing capability '${z}').`,"unknown")}
2
+ import{Wk as Z}from"./chunk-q4t568hv.js";import x from"process";var K=["github","gitlab","bitbucket"],$=["github","gitlab","bitbucket"],H={},L={pinIssues:!1,checkRuns:!1,inlineReviewComments:!1,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!1,branchHousekeeping:!1,reopenPullRequests:!1,labels:!1};class Y extends Error{provider;trackingIssue;constructor(j,z,F){super(j);this.provider=z;this.trackingIssue=F;this.name="UnsupportedProviderError"}}var B={github:["GITHUB_TOKEN","BUDDY_TOKEN"],gitlab:["CI_JOB_TOKEN","GITLAB_TOKEN","BUDDY_TOKEN"],bitbucket:["BITBUCKET_TOKEN","BUDDY_TOKEN"]};function A(j,z=x.env){for(let F of B[j]??[]){let J=z[F]?.trim();if(J)return{token:J,source:F}}return null}function C(j){if($.includes(j))return;let z=H[j];if(z)throw new Y(`'${j}' support is not implemented yet \u2014 follow ${z}. Supported today: ${$.join(", ")}.`,j,z);throw new Y(`Unknown git provider '${j}'. Supported: ${$.join(", ")}.`,j)}async function M(j,z={}){let F=j.provider??"github";C(F);let J=z.env??x.env,X=j.token??A(F,J)?.token;if(!X)throw Error(`No token for ${F}. Set one of: ${B[F].join(", ")}.`);switch(F){case"gitlab":{let{GitLabProvider:Q}=await import("./chunk-hns85dqw.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-brfyymhf.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-86x1vsjw.js"),q=j.workflowToken??J.BUDDY_TOKEN;return new Q(X,j.owner,j.name,Boolean(q),q,j.apiUrl,z.logger)}}}function W(j,z,F){return j.capabilities()[z]===!0&&typeof j[F]==="function"}function S(j,z,F,J){if(W(j,z,F))return;throw new Y(`This provider does not support ${J} (missing capability '${z}').`,"unknown")}
3
3
  export{K as ce,$ as de,H as ee,L as fe,Y as ge,B as he,A as ie,C as je,M as ke,W as le,S as me};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Jc as a}from"./chunk-tws3npt7.js";import"./chunk-8fw0v7bv.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as GitHubProvider};
2
+ import{Jc as a}from"./chunk-bmnx3s41.js";import"./chunk-8fw0v7bv.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as GitHubProvider};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{mb as w}from"./chunk-cwqhxqv7.js";import{Ab as u,Bb as v,Cb as x,Db as y,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as q,xb as r,yb as s,zb as t}from"./chunk-1c4690h9.js";import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import{Lb as m,Mb as n,Nb as o,Pb as p}from"./chunk-5yfaptmp.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import{Ad as B,Bd as C,Cd as D,Dd as E,Ed as F,Fd as G,Gd as H,Hd as I,yd as z,zd as A}from"./chunk-vgtmrd4c.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-p8tmms5h.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{g as validateFindings,I as shouldFail,n as serializeReviewState,y as runReviewForPR,x as reviewPullRequest,j as reviewDiff,w as resolveBuddyThreads,u as renderFinding,b as renderDiffForReview,v as prepareReview,a as parseUnifiedDiff,o as parseReviewState,p as needsReview,s as loadGuidelines,G as formatReview,C as formatPretty,D as formatGithub,E as formatAgent,f as fingerprint,A as diffArgsFor,l as defaultIncludePath,h as dedupeFindings,F as countBySeverity,t as composeInstructions,B as collectLocalDiff,c as collectGitDiff,H as applySuggestion,k as anchorMap,d as SEVERITY_ORDER,m as REVIEW_STATE_VERSION,e as REVIEW_SCHEMA,z as REVIEW_FORMATS,r as MAX_GUIDELINE_CHARS,q as DEFAULT_GUIDELINE_FILES,i as DEFAULT_EXCLUDED_PATHS};
2
+ import{mb as w}from"./chunk-patms7t8.js";import{Ab as u,Bb as v,Cb as x,Db as y,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as q,xb as r,yb as s,zb as t}from"./chunk-4jyw358y.js";import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import{Lb as m,Mb as n,Nb as o,Pb as p}from"./chunk-5yfaptmp.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import{Ad as B,Bd as C,Cd as D,Dd as E,Ed as F,Fd as G,Gd as H,Hd as I,yd as z,zd as A}from"./chunk-vgtmrd4c.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-5av2vnvv.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{g as validateFindings,I as shouldFail,n as serializeReviewState,y as runReviewForPR,x as reviewPullRequest,j as reviewDiff,w as resolveBuddyThreads,u as renderFinding,b as renderDiffForReview,v as prepareReview,a as parseUnifiedDiff,o as parseReviewState,p as needsReview,s as loadGuidelines,G as formatReview,C as formatPretty,D as formatGithub,E as formatAgent,f as fingerprint,A as diffArgsFor,l as defaultIncludePath,h as dedupeFindings,F as countBySeverity,t as composeInstructions,B as collectLocalDiff,c as collectGitDiff,H as applySuggestion,k as anchorMap,d as SEVERITY_ORDER,m as REVIEW_STATE_VERSION,e as REVIEW_SCHEMA,z as REVIEW_FORMATS,r as MAX_GUIDELINE_CHARS,q as DEFAULT_GUIDELINE_FILES,i as DEFAULT_EXCLUDED_PATHS};
@@ -0,0 +1,38 @@
1
+ // @bun
2
+ import{Kc as T,Lc as v,Mc as y}from"./chunk-8fw0v7bv.js";import{Rf as D,Sf as R,Tf as S}from"./chunk-c8rzx3a1.js";import{oh as P}from"./chunk-193abzy6.js";import{zh as U}from"./chunk-e68nf7cm.js";import{Bh as L,Ch as x,Fh as F}from"./chunk-hfjywbbc.js";import{Buffer as W}from"buffer";import{spawn as k}from"child_process";import q from"process";var B=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function E(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function w(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function g(Q,X){let Y=Q.replace(B,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class I extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}function f(Q){let X=`${x(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class N{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,K){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):P(),this.logger=K??F()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${x(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${x(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof I||$ instanceof D)throw $;this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let C=Bun.file("README.md");if(await C.exists()){let G=`${await C.text()}
3
+
4
+ <!-- Updated by Buddy -->
5
+ `;await Bun.write("README.md",G),await this.runCommand("git",["add","README.md"]),await this.runCommand("git",["commit","-m","Update README for workflow-only PR"]),this.logger.info("\u2705 Created README update for workflow-only PR")}}catch(j){this.logger.error(`\u274C Failed to create any commit: ${j}`)}}return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);try{await this.runCommand("git",["config","user.name","github-actions[bot]"]),await this.runCommand("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"]),this.logger.info("\u2705 Git identity configured for github-actions[bot]")}catch(V){this.logger.warn("\u26A0\uFE0F Failed to configure Git identity:",V)}await this.runCommand("git",["fetch","origin"]),this.logger.info(`\uD83D\uDD04 Recreating ${Q} from origin/${Z} (Renovate-style)...`);try{await this.runCommand("git",["checkout",Q])}catch{try{await this.runCommand("git",["checkout","-b",Q,`origin/${Q}`])}catch{await this.runCommand("git",["checkout","-b",Q])}}await this.runCommand("git",["reset","--hard",`origin/${Z}`]),await this.runCommand("git",["clean","-fd"]),this.logger.info(`\u2705 Reset ${Q} to origin/${Z}`),await S(Y,async(V)=>{try{return await this.runCommand("git",["cat-file","-e",`origin/${Z}:${V}`]),!0}catch{return!1}});for(let V of Y){let j=R(V.path);if(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test"){if(["package.json","bun.lock","bun.lockb","package-lock.json","yarn.lock"].includes(j)&&V.content==='{"name":"x"}'){this.logger.warn(`\u26A0\uFE0F Skipping test file write to ${j} to prevent overwriting project files`);continue}}if(V.type==="delete")try{await this.runCommand("git",["rm",j])}catch{}else await Bun.write(j,V.content),await this.runCommand("git",["add",j])}if(!(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test")){let V=Y.map((C)=>C.path.replace(/^\.\//,"").replace(/^\/+/,"")),j=y(V);if(j.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${j.join(", ")}`);let C=q.cwd(),M=[];for(let G of j)try{let H=await v(G,C);if(H.success)for(let z of T())try{await this.runCommand("git",["add",z])}catch{}else M.push(`${G}: ${H.message}`)}catch(H){M.push(`${G}: ${H instanceof Error?H.message:String(H)}`)}if(M.length>0){let G=M.map((H)=>` - ${H}`).join(`
6
+ `);throw new I(`Lock file regeneration failed; refusing to open PR with stale lockfiles.
7
+ ${G}`)}}}if((await this.runCommand("git",["status","--porcelain"])).trim()){await this.runCommand("git",["commit","-m",X]);let V=$.length>0&&this.hasWorkflowPermissions?this.getEffectiveToken(!0):void 0;await this.runCommand("git",["push","origin",Q,"--force-with-lease"],V),this.logger.info(`\u2705 Successfully recreated ${Q} with fresh changes from ${Z}: ${X}`)}else this.logger.info(`\u2139\uFE0F No file changes after resetting to ${Z} \u2014 skipping push to prevent PR auto-close`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q} with Git CLI: ${x($)}`),$}}async commitChangesWithAPI(Q,X,Y,Z="main"){try{let $=Y.filter((z)=>z.path.includes(".github/workflows/")),J=Y.filter((z)=>!z.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((z)=>z.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. Consider using a GitHub App with workflow permissions for workflow updates."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, consider using a GitHub App with appropriate permissions.");return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);if(Y.some((z)=>z.path.endsWith("package.json")||z.path.endsWith("composer.json")))this.logger.warn("\u26A0\uFE0F Committing manifest files via API \u2014 lock files will not be updated."),this.logger.warn(" Lock file regeneration requires the Git CLI commit path (local filesystem).");this.logger.info(`\uD83D\uDD04 Recreating ${Q} from ${Z} via API (Renovate-style)...`);let V=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Z}`)).object.sha,C=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/commits/${V}`)).tree.sha;await S(Y,async(z)=>{let O=z.split("/").map((A)=>encodeURIComponent(A)).join("/");try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${O}?ref=${encodeURIComponent(Z)}`),!0}catch(A){if(A.message?.includes("404"))return!1;throw A}});let M=[];for(let z of Y){let O=R(z.path);if(z.type==="delete")M.push({path:O,mode:"100644",type:"blob",sha:null});else{let A=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/blobs`,{content:W.from(z.content).toString("base64"),encoding:"base64"});M.push({path:O,mode:"100644",type:"blob",sha:A.sha})}}let G=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/trees`,{base_tree:C,tree:M});if(G.sha===C){this.logger.info(`\u2139\uFE0F No file changes relative to ${Z} \u2014 skipping push to prevent PR auto-close`);return}let H=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/commits`,{message:X,tree:G.sha,parents:[V],author:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"},committer:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}});await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/git/refs/heads/${Q}`,{sha:H.sha,force:!0}),this.logger.info(`\u2705 Committed changes to ${Q}: ${X}`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q}: ${x($)}`),$}}async createPullRequest(Q){try{return await this.createPullRequestWithCLI(Q)}catch(X){this.logger.warn(`\u26A0\uFE0F GitHub CLI failed, falling back to API: ${X}`)}try{return await this.createPullRequestWithAPI(Q)}catch(X){if(!f(X))throw X;if(this.workflowToken&&this.workflowToken!==this.token)return this.logger.info("\uD83D\uDD11 GITHUB_TOKEN may not open pull requests in this repository, retrying with BUDDY_TOKEN"),await this.createPullRequestWithAPI(Q,this.workflowToken);throw Error('GitHub Actions may not open pull requests in this repository. Either set a BUDDY_TOKEN repository secret (a token with contents, pull requests and workflows write access), or enable Settings > Actions > General > "Allow GitHub Actions to create and approve pull requests".',{cause:X})}}async createPullRequestWithCLI(Q){try{let X=["pr","create","--title",Q.title,"--body",Q.body,"--head",Q.head,"--base",Q.base];if(Q.draft)X.push("--draft");if(Q.reviewers&&Q.reviewers.length>0)this.logger.info(`\uD83D\uDD0D Adding reviewers via CLI: ${Q.reviewers.join(", ")}`),X.push("--reviewer",Q.reviewers.join(","));if(Q.assignees&&Q.assignees.length>0)X.push("--assignee",Q.assignees.join(","));let Z=(await this.runCommand("gh",X)).match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(!Z)throw Error("Failed to parse PR number from GitHub CLI output");let $=Number.parseInt(Z[1]),J=Z[0];if(this.logger.info(`\u2705 Created PR #${$}: ${Q.title}`),Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:Q.labels}),this.logger.info(`\u2705 Added labels to PR #${$}: ${Q.labels.join(", ")}`)}catch(K){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${K}`);for(let _ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:[_]})}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to add label '${_}': ${V}`)}}return{number:$,title:Q.title,body:Q.body,head:Q.head,base:Q.base,state:"open",url:J,createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Q.draft||!1}}catch(X){throw this.logger.error(`\u274C Failed to create PR with GitHub CLI: ${Q.title}: ${x(X)}`),X}}async createPullRequestWithAPI(Q,X){try{let Y=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls`,{title:Q.title,body:Q.body,head:Q.head,base:Q.base,draft:Q.draft||!1},X);if(Q.reviewers&&Q.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to PR #${Y.number}: ${Q.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Y.number}/requested_reviewers`,{reviewers:Q.reviewers,team_reviewers:Q.teamReviewers||[]}),this.logger.info(`\u2705 Successfully added reviewers: ${Q.reviewers.join(", ")}`)}catch(Z){this.logger.error(`\u274C Failed to add reviewers: ${Z}`),this.logger.error(` Reviewers: ${Q.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`),this.logger.error(` PR: #${Y.number}`)}if(Q.assignees&&Q.assignees.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/assignees`,{assignees:Q.assignees})}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to add assignees: ${Z}`)}if(Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/labels`,{labels:Q.labels})}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${Z}`);for(let $ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/labels`,{labels:[$]})}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to add label '${$}': ${J}`)}}return this.logger.info(`\u2705 Created PR #${Y.number}: ${Q.title}`),{number:Y.number,title:Y.title,body:Y.body||"",head:Y.head.ref,base:Y.base.ref,state:Y.state,url:Y.html_url,createdAt:new Date(Y.created_at),updatedAt:new Date(Y.updated_at),author:Y.user.login,reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Y.draft}}catch(Y){throw this.logger.error(`\u274C Failed to create PR with API: ${Q.title}: ${x(Y)}`),Y}}getEffectiveToken(Q=!1){if(Q&&this.workflowToken)return this.workflowToken;return this.token}async runCommand(Q,X,Y){let Z=Y||this.token;return new Promise(($,J)=>{let K=k(Q,X,{stdio:"pipe",env:{...q.env,GITHUB_TOKEN:Z,GH_TOKEN:Z}}),_="",V="";K.stdout?.on("data",(j)=>{_+=j.toString()}),K.stderr?.on("data",(j)=>{V+=j.toString()}),K.on("close",(j)=>{if(j===0)$(_);else J(Error(`Command failed with code ${j}: ${g(V,Z)}`))}),K.on("error",(j)=>{J(j)})})}async getPullRequests(Q="open"){let X=`${Q}`,Y=this.cache.pullRequests.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached PRs (state: ${Q}, ${Y.data.length} PRs)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/pulls?state=${Q}&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let K=J.map((_)=>({number:_.number,title:_.title,body:_.body??"",head:_.head.ref,base:_.base.ref,state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),mergedAt:_.merged_at?new Date(_.merged_at):void 0,author:_.user.login,reviewers:_.requested_reviewers?.map((V)=>V.login)??[],assignees:_.assignees?.map((V)=>V.login)??[],labels:_.labels?.map((V)=>V.name)??[],draft:_.draft}));return this.cache.pullRequests.set(X,{data:K,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${K.length} PRs (state: ${Q})`),K}catch(Z){throw this.logger.error(`\u274C Failed to get PRs: ${x(Z)}`),Z}}async updatePullRequest(Q,X){this.cache.pullRequests.clear();try{let Y={};if(X.title)Y.title=X.title;if(X.body)Y.body=X.body;if(X.base)Y.base=X.base;if(X.draft!==void 0)Y.draft=X.draft;let Z=await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,Y);if(X.labels&&X.labels.length>0)try{await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:X.labels}),this.logger.info(`\u2705 Updated labels for PR #${Q}: ${X.labels.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update labels for PR #${Q}: ${$}`);for(let J of X.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:[J]})}catch(K){this.logger.warn(`\u26A0\uFE0F Failed to add label '${J}' to PR #${Q}: ${K}`)}}if(X.reviewers&&X.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to existing PR #${Q}: ${X.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/requested_reviewers`,{reviewers:X.reviewers,team_reviewers:X.teamReviewers||[]}),this.logger.info(`\u2705 Updated reviewers for PR #${Q}: ${X.reviewers.join(", ")}`)}catch($){this.logger.error(`\u274C Failed to update reviewers for PR #${Q}: ${$}`),this.logger.error(` Reviewers: ${X.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`)}if(X.assignees&&X.assignees.length>0)try{await this.runCommand("gh",["issue","edit",Q.toString(),"--add-assignee",X.assignees.join(",")]),this.logger.info(`\u2705 Updated assignees for PR #${Q}: ${X.assignees.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update assignees for PR #${Q}: ${$}`)}return this.logger.info(`\u2705 Updated PR #${Q}`),{number:Z.number,title:Z.title,body:Z.body||"",head:Z.head.ref,base:Z.base.ref,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),author:Z.user.login,reviewers:[],assignees:[],labels:X.labels||[],draft:Z.draft}}catch(Y){throw this.logger.error(`\u274C Failed to update PR #${Q}: ${x(Y)}`),Y}}async closePullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close PR #${Q}: ${x(X)}`),X}}async reopenPullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"open"}),this.logger.info(`\u2705 Reopened PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to reopen PR #${Q}: ${x(X)}`),X}}async createComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/comments`,{body:X}),this.logger.info(`\uD83D\uDCAC Added comment to PR #${Q}`)}catch(Y){throw this.logger.error(`\u274C Failed to add comment to PR #${Q}: ${x(Y)}`),Y}}async mergePullRequest(Q,X="merge"){try{let Y=X==="rebase"?"rebase":X==="squash"?"squash":"merge",$=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.ref;await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/pulls/${Q}/merge`,{merge_method:Y}),this.logger.info(`\u2705 Merged PR #${Q} using ${X}`);try{await this.deleteBranch($),this.logger.info(`\uD83E\uDDF9 Cleaned up branch ${$} after merge`)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to clean up branch ${$}:`,J)}}catch(Y){throw this.logger.error(`\u274C Failed to merge PR #${Q}: ${x(Y)}`),Y}}async getPullRequestHeadSha(Q){try{return(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`))?.head?.sha??""}catch(X){return this.logger.debug(`Could not read head SHA for PR #${Q}: ${x(X)}`),""}}async hasWriteAccess(Q){try{let X=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/collaborators/${encodeURIComponent(Q)}/permission`);return["write","maintain","admin"].includes(X?.permission)}catch(X){if(X instanceof L&&X.isNotFound)return!1;return this.logger.warn(`\u26A0\uFE0F Could not resolve permissions for @${Q}: ${x(X)}`),!1}}async reactToComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/comments/${Q}/reactions`,{content:X})}catch(Y){this.logger.debug(`Could not react to comment ${Q}: ${x(Y)}`)}}async getWorkflowRunLogs(Q){try{let X=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/logs`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!X.ok)return this.logger.debug(`Could not fetch logs for run ${Q}: ${X.status}`),null;return W.from(await X.arrayBuffer()).toString("utf-8").replace(/[^\t\n\r\x20-\x7E]+/g," ")}catch(X){return this.logger.debug(`Could not fetch logs for run ${Q}: ${x(X)}`),null}}async listWorkflowRuns(Q,X={}){let Y=new URLSearchParams({branch:Q,per_page:String(X.limit??20)});if(X.status)Y.set("status",X.status);try{return((await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/actions/runs?${Y.toString()}`))?.workflow_runs??[]).map((J)=>({id:Number(J.id),name:String(J.name??""),headSha:String(J.head_sha??""),headBranch:String(J.head_branch??Q),status:E(J.status),conclusion:w(J.conclusion),createdAt:new Date(String(J.created_at??new Date().toISOString()))}))}catch(Z){return this.logger.debug(`Could not list workflow runs for ${Q}: ${x(Z)}`),[]}}async rerunWorkflowRun(Q,X=!0){let Y=X?"rerun-failed-jobs":"rerun";try{let Z=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/${Y}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!Z.ok)return this.logger.warn(`Could not re-run workflow run ${Q}: ${Z.status} ${Z.statusText}`),!1;return!0}catch(Z){return this.logger.warn(`Could not re-run workflow run ${Q}: ${x(Z)}`),!1}}async createCheckRun(Q,X,Y){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/check-runs`,{name:Q,head_sha:X,status:"completed",conclusion:Y.conclusion,completed_at:new Date().toISOString(),output:{title:Y.title,summary:Y.summary}}),this.logger.info(`\u2705 Reported check run ${Q}: ${Y.conclusion}`)}catch(Z){this.logger.warn(`\u26A0\uFE0F Could not report check run ${Q}: ${x(Z)}`)}}async getFileContent(Q,X){try{let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodeURIComponent(Q)}?ref=${encodeURIComponent(X)}`);if(!Y?.content)return null;return W.from(Y.content,Y.encoding==="base64"?"base64":"utf-8").toString("utf-8")}catch(Y){if(Y instanceof L&&Y.isNotFound)return null;throw Y}}async getPullRequestDiff(Q){let X=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3.diff","User-Agent":"buddy"}});if(!X.ok)throw new L(`Failed to fetch diff for PR #${Q}: ${X.status} ${X.statusText}`,X.status,"GET",`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,`${this.owner}/${this.repo}`);return await X.text()}async createReview(Q,X){let Y=`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/reviews`;try{return await this.apiRequest(Y,{body:X.body,event:X.event,...X.comments?.length?{comments:X.comments}:{}}),this.logger.success(`\u2705 Posted review on PR #${Q} (${X.comments?.length??0} inline comment(s))`),{posted:!0,inlineComments:X.comments?.length??0}}catch(Z){if(!X.comments?.length)throw this.logger.error(`\u274C Failed to post review on PR #${Q}: ${x(Z)}`),Z;return this.logger.warn(`\u26A0\uFE0F Review with inline comments was rejected (${x(Z)}); posting the summary alone`),await this.apiRequest(Y,{body:X.body,event:X.event}),{posted:!0,inlineComments:0}}}async enableAutoMerge(Q,X="squash"){let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`),Z=`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
8
+ enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
9
+ pullRequest { number }
10
+ }
11
+ }`,$=await this.graphqlRequest(`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
12
+ enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
13
+ pullRequest { number }
14
+ }
15
+ }`,{pullRequestId:Y.node_id,mergeMethod:X.toUpperCase()});if($.errors?.length){let J=$.errors.map((K)=>K.message).join("; ");return this.logger.info(`\u2139\uFE0F GitHub could not queue auto-merge for PR #${Q}: ${J}`),!1}return this.logger.success(`\u2705 Auto-merge queued for PR #${Q} (${X})`),!0}async listReviewThreads(Q){try{let Y=await this.graphqlRequest(`query($owner: String!, $repo: String!, $number: Int!) {
16
+ repository(owner: $owner, name: $repo) {
17
+ pullRequest(number: $number) {
18
+ reviewThreads(first: 100) {
19
+ nodes {
20
+ id
21
+ isResolved
22
+ path
23
+ comments(first: 10) { nodes { author { login } } }
24
+ }
25
+ }
26
+ }
27
+ }
28
+ }`,{owner:this.owner,repo:this.repo,number:Q});if(Y.errors?.length)return this.logger.debug(`Could not read review threads on #${Q}: ${Y.errors.map(($)=>$.message).join("; ")}`),[];return(Y.data?.repository?.pullRequest?.reviewThreads?.nodes??[]).filter(Boolean).map(($)=>({id:String($.id),isResolved:Boolean($.isResolved),...$.path?{path:String($.path)}:{},authorLogins:($.comments?.nodes??[]).map((J)=>J?.author?.login).filter((J)=>typeof J==="string")}))}catch(Y){return this.logger.debug(`Could not read review threads on #${Q}: ${x(Y)}`),[]}}async resolveReviewThread(Q,X){try{let Z=await this.graphqlRequest(`mutation($threadId: ID!) {
29
+ resolveReviewThread(input: { threadId: $threadId }) {
30
+ thread { isResolved }
31
+ }
32
+ }`,{threadId:X});if(Z.errors?.length)return this.logger.warn(`Could not resolve review thread: ${Z.errors.map(($)=>$.message).join("; ")}`),!1;return Boolean(Z.data?.resolveReviewThread?.thread?.isResolved)}catch(Z){return this.logger.warn(`Could not resolve review thread: ${x(Z)}`),!1}}async getPullRequestChecksState(Q){try{let Y=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.sha,[Z,$]=await Promise.all([this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/status`),this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/check-runs?per_page=100`)]),J=$?.check_runs??[],K=(Z?.statuses?.length??0)>0;if(J.length===0&&!K)return"none";if(J.some((j)=>j.conclusion!==null&&["failure","cancelled","timed_out","action_required"].includes(j.conclusion))||Z?.state==="failure"||Z?.state==="error")return"failure";if(J.some((j)=>j.status!=="completed")||Z?.state==="pending")return"pending";return"success"}catch(X){return this.logger.warn(`\u26A0\uFE0F Could not read check state for PR #${Q}: ${x(X)}`),"pending"}}async graphqlRequest(Q,X){let Y=await U(`${this.apiUrl}/graphql`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({query:Q,variables:X})});if(!Y.ok)throw new L(`GraphQL request failed: ${Y.status} ${Y.statusText}`,Y.status,"POST",`${this.apiUrl}/graphql`,`${this.owner}/${this.repo}`);return await Y.json()}async deleteBranch(Q){try{await this.runCommand("git",["push","origin","--delete",Q]),this.logger.info(`\u2705 Deleted branch ${Q} via git`)}catch(X){try{await this.runCommand("git",["branch","-D",Q])}catch{}if(/remote ref does not exist|unable to delete '[^']*': remote ref/i.test(x(X))){this.logger.info(`\u2139\uFE0F Branch ${Q} was already gone`);return}throw this.logger.warn(`\u26A0\uFE0F Failed to delete remote branch ${Q}: ${x(X)}`),X}}async getBuddyBranches(){try{let Q=await this.runCommand("git",["branch","-r","--format=%(refname:short) %(objectname) %(committerdate:iso8601)"]),X=[];for(let Y of Q.split(`
33
+ `)){let Z=Y.trim();if(!Z)continue;let $=Z.split(" ");if($.length<3)continue;let J=$[0],K=$[1],_=$.slice(2).join(" "),V=J.replace(/^origin\//,"");if(!V.startsWith("buddy/"))continue;try{let j=new Date(_);X.push({name:V,sha:K,lastCommitDate:j})}catch{this.logger.warn(`\u26A0\uFE0F Failed to parse date for branch ${V}: ${_}`),X.push({name:V,sha:K,lastCommitDate:new Date(0)})}}return this.logger.info(`\uD83D\uDD0D Found ${X.length} buddy branches using local git`),X}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches via git, falling back to API:",Q),this.getBuddyBranchesViaAPI()}}async getBuddyBranchesViaAPI(){try{let Q=[],X=1,Y=100;while(!0){let J=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/branches?per_page=${Y}&page=${X}`);if(!J||J.length===0)break;if(Q=Q.concat(J),J.length<Y)break;X++}this.logger.info(`\uD83D\uDD0D Found ${Q.length} total branches in repository`);let Z=Q.filter((J)=>J.name.startsWith("buddy/"));return this.logger.info(`\uD83E\uDD16 Found ${Z.length} buddy branches`),await Promise.all(Z.map(async(J)=>{try{let K=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${J.commit.sha}`);return{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(K.commit.committer.date)}}catch(K){return this.logger.warn(`\u26A0\uFE0F Failed to get commit info for branch ${J.name}: ${x(K)}`),{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(0)}}}))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches:",Q),[]}}async getOrphanedBuddyBranches(){try{let Q=await this.getBuddyBranches(),X=await this.getOpenPRBranches();return Q.filter((Z)=>!X.has(Z.name))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to identify orphaned branches:",Q),[]}}prDetectionSuccessful=!1;async getOpenPRBranches(){this.prDetectionSuccessful=!1;try{let Q=await this.getPullRequests("open"),X=new Set(Q.map((Y)=>Y.head).filter((Y)=>Y.startsWith("buddy/")));return this.logger.info(`\uD83D\uDD0D GitHub API reports ${Q.length} open PR(s); ${X.size} are buddy branches`),this.logger.info(`\uD83D\uDEE1\uFE0F Protecting ${X.size} branches with confirmed open PRs`),this.prDetectionSuccessful=!0,X}catch(Q){this.logger.warn("\u26A0\uFE0F Failed to fetch open PRs via API, falling back to age-based protection:",Q);try{let X=await this.getBuddyBranches(),Y=new Date;Y.setDate(Y.getDate()-30);let Z=new Set;for(let $ of X)if($.lastCommitDate>Y)Z.add($.name);return this.logger.info(`\uD83D\uDEE1\uFE0F Conservative fallback: protecting ${Z.size} branches newer than 30 days`),Z}catch{return this.logger.info("\u26A0\uFE0F Could not enumerate branches for age-based fallback"),new Set}}}async cleanupStaleBranches(Q=7,X=!1){this.logger.info("\uD83D\uDD0D Looking for buddy branches without open PRs...");let Y=await this.getOrphanedBuddyBranches();this.logger.info(`\uD83D\uDD0D Found ${Y.length} orphaned buddy branches (no associated open PRs)`);let Z=Y;if(this.prDetectionSuccessful)this.logger.info(`\uD83C\uDFAF PR detection successful - cleaning up ALL ${Z.length} orphaned branches (any age)`);else{let V=new Date;V.setDate(V.getDate()-Q),Z=Y.filter((j)=>j.lastCommitDate<V),this.logger.info(`\u26A0\uFE0F PR detection failed - only deleting branches older than ${Q} days`),this.logger.info(`\uD83D\uDD0D Found ${Z.length} stale buddy branches (older than ${Q} days)`)}if(Z.length>0){if(this.logger.info("\uD83D\uDCCB Sample of branches to delete:"),Z.slice(0,5).forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old)`)}),Z.length>5)this.logger.info(` ... and ${Z.length-5} more`)}if(Z.length===0)return this.logger.info("\u2705 No branches to clean up!"),{deleted:[],failed:[]};let $=Z;if(X)return this.logger.info("\uD83D\uDD0D [DRY RUN] Would delete the following branches:"),$.forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old, last commit: ${V.lastCommitDate.toISOString()})`)}),{deleted:$.map((V)=>V.name),failed:[]};let J=[],K=[];this.logger.info(`\uD83E\uDDF9 Cleaning up ${$.length} stale branches...`);let _=5;for(let V=0;V<$.length;V+=_){let j=$.slice(V,V+_),C=Math.floor(V/_)+1,M=Math.ceil($.length/_);this.logger.info(`\uD83D\uDD04 Processing batch ${C}/${M} (${j.length} branches)`);for(let G of j){try{await this.deleteBranch(G.name),J.push(G.name),this.logger.info(`\u2705 Deleted: ${G.name}`)}catch(H){K.push(G.name),this.logger.warn(`\u274C Failed to delete ${G.name}: ${x(H)}`)}await new Promise((H)=>setTimeout(H,200))}if(V+_<$.length)this.logger.info(`\u23F3 Waiting ${3} seconds before next batch...`),await new Promise((H)=>setTimeout(H,3000))}if(this.logger.info("\uD83C\uDF89 Cleanup complete!"),this.logger.info(` \u2705 Successfully deleted: ${J.length} branches`),this.logger.info(` \u274C Failed to delete: ${K.length} branches`),K.length>0)this.logger.info("\u274C Failed branches:"),K.forEach((V)=>this.logger.info(` - ${V}`));return{deleted:J,failed:K}}async apiRequest(Q,X,Y,Z=0){let[$,J]=Q.split(" "),K=`${this.apiUrl}${J}`,_=Y||this.token,V={method:$,headers:{Authorization:`Bearer ${_}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json","User-Agent":"buddy"}};if(X&&($==="POST"||$==="PATCH"||$==="PUT"))V.body=JSON.stringify(X);let j=await U(K,{...V,retries:Z,onRetry:({delayMs:C,reason:M})=>this.logger.info(`\u23F3 ${M} on ${$} ${J}, retrying in ${Math.round(C/1000)}s...`)});if(!j.ok){let C=await j.text(),M=_?"token present ([REDACTED])":"NO TOKEN \u2014 ensure GITHUB_TOKEN or BUDDY_TOKEN is set";throw new L(`GitHub API error: ${j.status} ${j.statusText}
34
+ URL: ${$} ${K}
35
+ Auth: ${M}
36
+ Repo: ${this.owner}/${this.repo}
37
+ ${C}`,j.status,$,K,`${this.owner}/${this.repo}`,C)}if(j.headers.get("content-type")?.includes("application/json"))return j.json();return j.text()}async apiRequestWithRetry(Q,X,Y=3){return this.apiRequest(Q,X,void 0,Math.max(0,Y-1))}async createIssue(Q){this.cache.issues.clear();try{let X=await this.apiRequestWithRetry(`POST /repos/${this.owner}/${this.repo}/issues`,{title:Q.title,body:Q.body,assignees:Q.assignees||[],labels:Q.labels||[],milestone:Q.milestone});return this.logger.info(`\u2705 Created issue #${X.number}: ${Q.title}`),{number:X.number,title:X.title,body:X.body,state:X.state,url:X.html_url,createdAt:new Date(X.created_at),updatedAt:new Date(X.updated_at),closedAt:X.closed_at?new Date(X.closed_at):void 0,author:X.user.login,assignees:X.assignees?.map((Y)=>Y.login)||[],labels:X.labels?.map((Y)=>typeof Y==="string"?Y:Y.name)||[],pinned:!1}}catch(X){throw this.logger.error(`\u274C Failed to create issue: ${Q.title}: ${x(X)}`),X}}async getIssues(Q="open"){let X=`${Q}`,Y=this.cache.issues.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached issues (state: ${Q}, ${Y.data.length} issues)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/issues?state=${Q}&sort=updated&direction=desc&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let K=J.filter((_)=>!_.pull_request).map((_)=>({number:_.number,title:_.title,body:_.body||"",state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),closedAt:_.closed_at?new Date(_.closed_at):void 0,author:_.user.login,assignees:_.assignees?.map((V)=>V.login)||[],labels:_.labels?.map((V)=>typeof V==="string"?V:V.name)||[],pinned:!1}));return this.cache.issues.set(X,{data:K,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${K.length} issues (state: ${Q})`),K}catch(Z){throw this.logger.error("\u274C Failed to get issues:",Z),Z}}async updateIssue(Q,X){this.cache.issues.clear();try{let Y={};if(X.title!==void 0)Y.title=X.title;if(X.body!==void 0)Y.body=X.body;if(X.assignees!==void 0)Y.assignees=X.assignees;if(X.labels!==void 0)Y.labels=X.labels;if(X.milestone!==void 0)Y.milestone=X.milestone;let Z=await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,Y);return this.logger.info(`\u2705 Updated issue #${Q}: ${Z.title}`),{number:Z.number,title:Z.title,body:Z.body,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),closedAt:Z.closed_at?new Date(Z.closed_at):void 0,author:Z.user.login,assignees:Z.assignees?.map(($)=>$.login)||[],labels:Z.labels?.map(($)=>typeof $==="string"?$:$.name)||[],pinned:!1}}catch(Y){throw this.logger.error(`\u274C Failed to update issue #${Q}: ${x(Y)}`),Y}}async closeIssue(Q){this.cache.issues.clear();try{await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed issue #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close issue #${Q}: ${x(X)}`),X}}async pinIssue(Q){return await this.setIssuePinned(Q,!0)}async unpinIssue(Q){return await this.setIssuePinned(Q,!1)}async setIssuePinned(Q,X){let Y=X?"pin":"unpin";try{let Z=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/issues/${Q}`),$=X?"mutation($issueId: ID!) { pinIssue(input: { issueId: $issueId }) { issue { number } } }":"mutation($issueId: ID!) { unpinIssue(input: { issueId: $issueId }) { issue { number } } }",J=await this.graphqlRequest($,{issueId:Z.node_id});if(J.errors?.length){let K=J.errors.map((_)=>_.message).join("; ");return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${K}`),!1}return this.logger.info(`\uD83D\uDCCC ${X?"Pinned":"Unpinned"} issue #${Q}`),!0}catch(Z){return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${x(Z)}`),!1}}}
38
+ export{N as Jc};