@oss-autopilot/core 3.4.0 → 3.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.bundle.cjs
CHANGED
|
@@ -103,7 +103,7 @@ Could not preserve the rejected content; do not push without inspecting the Gist
|
|
|
103
103
|
onRateLimit: (retryAfter, options) => {/* ... */}
|
|
104
104
|
}
|
|
105
105
|
})
|
|
106
|
-
`);let l={},d=new o.Events(l);return l.on("secondary-limit",c.onSecondaryRateLimit),l.on("rate-limit",c.onRateLimit),l.on("error",p=>t.log.warn("Error in throttling-plugin limit handler",p)),c.retryLimiter.on("failed",async function(p,m){let[g,h,_]=m.args,{pathname:$}=new URL(_.url,"http://github.test");if(!($.startsWith("/graphql")&&p.status!==401||p.status===403||p.status===429))return;let T=~~h.retryCount;h.retryCount=T,_.request.retryCount=T;let{wantRetry:j,retryAfter:F=0}=await(async function(){if(/\bsecondary rate\b/i.test(p.message)){let U=Number(p.response.headers["retry-after"])||g.fallbackSecondaryRateRetryAfter;return{wantRetry:await d.trigger("secondary-limit",U,_,t,T),retryAfter:U}}if(p.response.headers!=null&&p.response.headers["x-ratelimit-remaining"]==="0"||(p.response.data?.errors??[]).some(U=>U.type==="RATE_LIMITED")){let U=new Date(~~p.response.headers["x-ratelimit-reset"]*1e3).getTime(),J=Math.max(Math.ceil((U-Date.now())/1e3)+1,0);return{wantRetry:await d.trigger("rate-limit",J,_,t,T),retryAfter:J}}return{}})();if(j)return h.retryCount++,F*g.retryAfterBaseValue}),t.hook.wrap("request",KO.bind(null,c)),{}}var J$,JO,uh,QO,q$,K$,dn,tA,lh=v(()=>{J$=K(W$(),1),JO="0.0.0-development",uh=()=>Promise.resolve();QO=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];q$=eA(QO),K$=q$.test.bind(q$),dn={},tA=function(t,e){dn.global=new t.Group({id:"octokit-global",maxConcurrent:10,...e}),dn.auth=new t.Group({id:"octokit-auth",maxConcurrent:1,...e}),dn.search=new t.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...e}),dn.write=new t.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...e}),dn.notifications=new t.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...e})};$o.VERSION=JO;$o.triggersNotification=K$});var Q$={};ie(Q$,{checkRateLimit:()=>dh,getOctokit:()=>Ie,getRateLimitCallbacks:()=>Y$});function Mc(t){return t.toLocaleTimeString("en-US",{hour12:!1})}function Y$(){return{onRateLimit:(t,e,n,o)=>{let r=e,i=new Date(Date.now()+t*1e3);return o<2?(b(Lc,`Rate limit hit (retry ${o+1}/2, waiting ${t}s, resets at ${Mc(i)}) \u2014 ${r.method} ${r.url}`),!0):(b(Lc,`Rate limit exceeded, not retrying \u2014 ${r.method} ${r.url} (resets at ${Mc(i)})`),!1)},onSecondaryRateLimit:(t,e,n,o)=>{let r=e,i=new Date(Date.now()+t*1e3);return o<3?(b(Lc,`Secondary rate limit hit (retry ${o+1}/3, waiting ${t}s, resets at ${Mc(i)}) \u2014 ${r.method} ${r.url}`),!0):(b(Lc,`Secondary rate limit exceeded, not retrying \u2014 ${r.method} ${r.url} (resets at ${Mc(i)})`),!1)}}}function Ie(t){if(Nc&&X$===t)return Nc;let e=Y$();return Nc=new rA({auth:t,throttle:e}),X$=t,Nc}async function dh(t){let e=Ie(t),{data:n}=await e.rateLimit.get(),o=n.resources.search;return{remaining:o.remaining,limit:o.limit,resetAt:new Date(o.reset*1e3).toISOString()}}var Lc,rA,Nc,X$,ko=v(()=>{"use strict";sh();lh();we();Lc="github",rA=zc.plugin($o),Nc=null,X$=null});function ek(t,e){let n=[],o=0;for(let r of t){if(xe(r.url)===null){b(Fe,`Dropping ${e} PR with invalid URL: ${r.url}`),o++;continue}n.push(r)}return{valid:n,dropped:o}}async function Ge(t,e){if(t.isGistMode())try{await t.checkpoint()}catch(n){b(e,`Gist checkpoint failed (local mutation succeeded, will retry on next push): ${I(n)}`)}}function L(){return mn||(mn=new Ro),mn}async function ph(t){return mn||pn||(t?(pn=Ro.createWithGist(t).then(e=>(mn=e,pn=null,e)).catch(e=>{if(pn=null,e instanceof ot||!bw(e))throw e;return b(Fe,`Gist initialization failed (transient network error), falling back to local-only mode: ${e}`),L()}),pn):L())}async function tk(t){if(!t)return;let e;try{let n=Eo.readFileSync(nt(),"utf8");e=JSON.parse(n)?.config?.persistence}catch{return}e==="gist"&&await ph(t)}function Hc(){mn=null,pn=null}var Eo,Fe,Ro,mn,pn,To=v(()=>{"use strict";Eo=K(require("node:fs"),1);uo();Xi();Gw();we();he();Nf();Zf();rn();It();Xi();Fe="state";Ro=class t{state;inMemoryOnly;lastLoadedMtimeMs=0;_batching=!1;_batchDirty=!1;gistStore=null;gistDegraded=!1;staleness=null;lastSuccessfulRefreshAt=null;constructor(e=!1){if(this.inMemoryOnly=e,e)this.state=Ar();else{let n=Ic();this.state=n.state,this.lastLoadedMtimeMs=n.mtimeMs,this.tryReconcilePRCounts()}}static async createWithGist(e){let{getOctokit:n}=await Promise.resolve().then(()=>(ko(),Q$)),o=n(e),r=new yo(o),i=nt(),s;if(Eo.existsSync(i)){let c=Ic(),l=await r.bootstrapWithMigration(c.state);if(s=l,l.migrated)try{let d=i+".pre-gist-migration";Eo.renameSync(i,d),E(Fe,`Renamed ${i} to ${d} after Gist migration`)}catch(d){b(Fe,`Failed to rename state.json after Gist migration: ${d}`)}}else s=await r.bootstrap();let a=new t(!0);return a.state=s.state,s.gistId&&(a.state.gistId=s.gistId),a.gistStore=r,a.gistDegraded=s.degraded??!1,a.inMemoryOnly=!1,s.degraded&&(a.staleness={source:"cache",reason:"initial Gist bootstrap fell back to local cache",lastSuccessfulRefresh:null,detectedAt:new Date().toISOString()}),a}tryReconcilePRCounts(){try{this.reconcilePRCounts()}catch(e){b(Fe,`PR count reconciliation failed (will retry on next load): ${I(e)}`),E(Fe,`Reconciliation error details: ${e instanceof Error?e.stack:String(e)}`)}}batch(e){if(this._batching){e();return}this._batching=!0,this._batchDirty=!1;try{e(),this._batchDirty&&this.save()}finally{this._batching=!1,this._batchDirty=!1}}autoSave(){if(this._batching){this._batchDirty=!0;return}this.save()}isSetupComplete(){return this.state.config.setupComplete===!0}markSetupComplete(){this.state.config.setupComplete=!0,this.state.config.setupCompletedAt=new Date().toISOString(),this.autoSave()}initializeWithDefaults(e){if(this.state.config.setupComplete){E(Fe,`Setup already complete, skipping initializeWithDefaults for "${e}"`);return}this.batch(()=>{this.updateConfig({githubUsername:e}),this.markSetupComplete(),E(Fe,`Initialized with defaults for user "${e}"`)})}save(e={}){if(this.state.lastRunAt=new Date().toISOString(),!this.inMemoryOnly){if(this.gistStore){try{Ct(tn(),JSON.stringify(this.state,null,2),384)}catch(n){b(Fe,`Failed to write Gist local cache: ${I(n)}`)}return}try{this.lastLoadedMtimeMs=$w(this.state,this.lastLoadedMtimeMs)}catch(n){if(n instanceof nn&&e.allowReloadAndLoseMutation){b(Fe,`Concurrent external write detected; reloading and discarding in-memory mutation. ${n.message}`),this.reloadIfChanged();return}throw n}}}async checkpoint(){return this.gistStore?(this.gistStore.setState(JSON.stringify(this.state,null,2)),this.gistStore.push()):!0}isGistMode(){return this.gistStore!==null}isGistDegraded(){return this.gistDegraded}isGuidelinesAvailable(){return this.gistStore!==null}getGuidelines(e){return Lw(this.gistStore,e)}setGuidelines(e,n){Nw(this.gistStore,e,n),this.autoSave()}deleteGuidelines(e){Mw(this.gistStore,e),this.autoSave()}listGuidelinesRepos(){return Hw(this.gistStore)}getState(){return this.state}reloadIfChanged(){if(this.inMemoryOnly||this.gistStore)return!1;let e=kw(this.lastLoadedMtimeMs);return e?(this.state=e.state,this.lastLoadedMtimeMs=e.mtimeMs,this.tryReconcilePRCounts(),!0):!1}async refreshFromGist(){if(!this.gistStore)return!1;let n=(await this.gistStore.refreshFromGist()).status==="refreshed";if(n){let o=this.gistStore.cachedFiles.get("state.json");if(!o)return b(Fe,"Gist refreshed but state.json missing from cache"),this.staleness={source:"cache",reason:"Gist refresh returned no state.json file",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;try{this.state=lt.parse(JSON.parse(o)),this.tryReconcilePRCounts()}catch(r){return b(Fe,`Failed to parse refreshed Gist state: ${I(r)}`),this.staleness={source:"cache",reason:`Gist refresh succeeded but payload was invalid: ${I(r)}`,lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1}this.lastSuccessfulRefreshAt=new Date().toISOString(),this.staleness=null}else this.gistStore.lastRefreshError&&(this.staleness={source:"cache",reason:I(this.gistStore.lastRefreshError),lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()});return n}getStateStaleness(){return this.staleness}setLastDigest(e){this.state.lastDigest=e,this.state.lastDigestAt=e.generatedAt,this.autoSave()}setMonthlyMergedCounts(e){this.state.monthlyMergedCounts=e,this.autoSave()}setMonthlyClosedCounts(e){this.state.monthlyClosedCounts=e,this.autoSave()}setMonthlyOpenedCounts(e){this.state.monthlyOpenedCounts=e,this.autoSave()}setLocalRepoCache(e){this.state.localRepoCache=e,this.autoSave()}getMergedPRs(){return this.state.mergedPRs??[]}addMergedPRs(e){if(e.length===0)return{added:0,dropped:0};let{valid:n,dropped:o}=ek(e,"merged");if(n.length===0)return{added:0,dropped:o};this.state.mergedPRs||(this.state.mergedPRs=[]);let r=new Set(this.state.mergedPRs.map(s=>s.url)),i=n.filter(s=>!r.has(s.url));return i.length===0?{added:0,dropped:o}:(this.state.mergedPRs.push(...i),this.state.mergedPRs.sort((s,a)=>a.mergedAt.localeCompare(s.mergedAt)),E(Fe,`Added ${i.length} merged PRs (total: ${this.state.mergedPRs.length})`),this.autoSave(),{added:i.length,dropped:o})}getMergedPRWatermark(){return this.state.mergedPRs?.[0]?.mergedAt||void 0}getClosedPRs(){return this.state.closedPRs??[]}addClosedPRs(e){if(e.length===0)return{added:0,dropped:0};let{valid:n,dropped:o}=ek(e,"closed");if(n.length===0)return{added:0,dropped:o};this.state.closedPRs||(this.state.closedPRs=[]);let r=new Set(this.state.closedPRs.map(s=>s.url)),i=n.filter(s=>!r.has(s.url));return i.length===0?{added:0,dropped:o}:(this.state.closedPRs.push(...i),this.state.closedPRs.sort((s,a)=>a.closedAt.localeCompare(s.closedAt)),E(Fe,`Added ${i.length} closed PRs (total: ${this.state.closedPRs.length})`),this.autoSave(),{added:i.length,dropped:o})}getClosedPRWatermark(){return this.state.closedPRs?.[0]?.closedAt||void 0}markPRCommentsFetched(e,n){let o=this.state.mergedPRs?.find(i=>i.url===e);if(o){o.commentsFetchedAt=n,this.autoSave();return}let r=this.state.closedPRs?.find(i=>i.url===e);r&&(r.commentsFetchedAt=n,this.autoSave())}markPRLearningsExtracted(e,n){let o=this.state.mergedPRs?.find(i=>i.url===e);if(o){o.learningsExtractedAt=n,this.autoSave();return}let r=this.state.closedPRs?.find(i=>i.url===e);r&&(r.learningsExtractedAt=n,this.autoSave())}updateConfig(e){this.state.config={...this.state.config,...e},this.autoSave()}addIssue(e){if(this.state.activeIssues.find(o=>o.url===e.url)){E(Fe,`Issue ${e.url} already tracked`);return}this.state.activeIssues.push(e),E(Fe,`Added issue: ${e.repo}#${e.number}`),this.autoSave()}addTrustedProject(e){this.state.config.trustedProjects.includes(e)||(this.state.config.trustedProjects.push(e),E(Fe,`Added trusted project: ${e}`),this.autoSave())}static matchesExclusion(e,n,o){let r=e.toLowerCase();return!!(n.some(i=>i.toLowerCase()===r)||o?.some(i=>i.toLowerCase()===r.split("/")[0]))}cleanupExcludedData(e,n){let o=s=>t.matchesExclusion(s,e,n),r=this.state.config.trustedProjects.length;this.state.config.trustedProjects=this.state.config.trustedProjects.filter(s=>!o(s));let i=r-this.state.config.trustedProjects.length;i>0&&(E(Fe,`Removed ${i} trusted project(s) for excluded repos/orgs`),this.autoSave())}getStarredRepos(){return this.state.config.starredRepos||[]}setStarredRepos(e){this.state.config.starredRepos=e,this.state.config.starredReposLastFetched=new Date().toISOString(),E(Fe,`Updated starred repos: ${e.length} repositories`),this.autoSave()}isStarredReposStale(){let e=this.state.config.starredReposLastFetched;if(!e)return!0;let n=1440*60*1e3,o=new Date(e);return new Date().getTime()-o.getTime()>n}shelvePR(e){return this.state.config.shelvedPRUrls||(this.state.config.shelvedPRUrls=[]),this.state.config.shelvedPRUrls.includes(e)?!1:(this.state.config.shelvedPRUrls.push(e),this.autoSave(),!0)}unshelvePR(e){if(!this.state.config.shelvedPRUrls)return!1;let n=this.state.config.shelvedPRUrls.indexOf(e);return n===-1?!1:(this.state.config.shelvedPRUrls.splice(n,1),this.autoSave(),!0)}isPRShelved(e){return this.state.config.shelvedPRUrls?.includes(e)??!1}dismissIssue(e,n){return this.state.config.dismissedIssues||(this.state.config.dismissedIssues={}),e in this.state.config.dismissedIssues?!1:(this.state.config.dismissedIssues[e]=n,this.autoSave(),!0)}undismissIssue(e){return!this.state.config.dismissedIssues||!(e in this.state.config.dismissedIssues)?!1:(delete this.state.config.dismissedIssues[e],this.autoSave(),!0)}getIssueDismissedAt(e){return this.state.config.dismissedIssues?.[e]}setStatusOverride(e,n,o){this.state.config.statusOverrides||(this.state.config.statusOverrides={}),this.state.config.statusOverrides[e]={status:n,setAt:new Date().toISOString(),lastActivityAt:o},this.autoSave()}clearStatusOverride(e){return!this.state.config.statusOverrides||!(e in this.state.config.statusOverrides)?!1:(delete this.state.config.statusOverrides[e],this.autoSave(),!0)}getStatusOverride(e,n){let o=this.state.config.statusOverrides?.[e];if(o){if(n&&n>o.lastActivityAt){this.clearStatusOverride(e);return}return o}}getRepoScore(e){return xw(this.state,e)}updateRepoScore(e,n){vo(this.state,e,n),this.autoSave()}incrementMergedCount(e){Pw(this.state,e),this.autoSave()}incrementClosedCount(e){Cw(this.state,e),this.autoSave()}markRepoHostile(e){Iw(this.state,e),this.autoSave()}getReposWithMergedPRs(){return Ow(this.state)}getReposWithOpenPRs(){return Aw(this.state)}getHighScoringRepos(e){return Dw(this.state,e)}getLowScoringRepos(e){return Uw(this.state,e)}getStats(){return jw(this.state)}reconcilePRCounts(){let e=this.state.mergedPRs??[],n=this.state.closedPRs??[];if(e.length===0&&n.length===0)return;Fw(this.state,e,n)&&this.autoSave()}},mn=null,pn=null});var rk={};ie(rk,{byDateDescending:()=>mh,daysBetween:()=>gn,formatRelativeTime:()=>is});function gn(t,e=new Date){return Math.max(0,Math.floor((e.getTime()-t.getTime())/(1e3*60*60*24)))}function is(t){let e=new Date(t),n=Date.now()-e.getTime();if(n<0)return"just now";let o=Math.floor(n/6e4),r=Math.floor(n/36e5),i=Math.floor(n/864e5);return o<60?`${o}m ago`:r<24?`${r}h ago`:i<30?`${i}d ago`:e.toLocaleDateString()}function mh(t){return(e,n)=>{let o=new Date(t(e)||0).getTime();return new Date(t(n)||0).getTime()-o}}var xo=v(()=>{"use strict"});async function Zc(t,e,n){let o=0,r=!1,i=async()=>{for(;o<t.length&&!r;){let a=t[o++];try{await e(a)}catch(c){throw r=!0,c}}},s=Math.min(n,t.length);await Promise.all(Array.from({length:s},()=>i()))}var Po,Vc=v(()=>{"use strict";Po=5});function iA(t,e){if(!t||!e)return!0;let n=t.toLowerCase();return nA.has(n)?!0:n===e.toLowerCase()}function Co(t){return t?new Date(t).getTime():Number.NaN}function sA(t,e){let n=Co(t),o=Co(e);return!Number.isFinite(n)||!Number.isFinite(o)?!1:n-o>=oA}function nk(t){let{latestCommitDate:e,latestCommitAuthor:n,contributorUsername:o}=t;if(e)return iA(n,o)?e:void 0}function ok(t,e,n){if(!t||!e||!sA(t,e))return!1;if(n){let o=Co(t),r=Co(n);if(!Number.isFinite(o)||!Number.isFinite(r)||o<r)return!1}return!0}function ik(t,e){if(!t||!e)return!1;let n=Co(t),o=Co(e);return!Number.isFinite(n)||!Number.isFinite(o)?!1:n>=o}function aA(t){let{ciStatus:e,hasMergeConflict:n,hasUnrespondedComment:o,hasIncompleteChecklist:r,reviewDecision:i,lastMaintainerCommentDate:s,latestChangesRequestedDate:a,hasActionableCIFailure:c=!0}=t,l=nk(t),d=[];return o&&!ok(l,s,a)&&d.push("needs_response"),i==="changes_requested"&&a&&!ik(l,a)&&d.push("needs_changes"),e==="failing"&&c&&d.push("failing_ci"),n&&d.push("merge_conflict"),r&&d.push("incomplete_checklist"),d.length>0?d:void 0}function gh(t){let e=cA(t),n=aA(t);return n?{...e,actionReasons:n}:e}function cA(t){let{ciStatus:e,hasMergeConflict:n,hasUnrespondedComment:o,hasIncompleteChecklist:r,reviewDecision:i,daysSinceActivity:s,dormantThreshold:a,approachingThreshold:c,lastMaintainerCommentDate:l,latestChangesRequestedDate:d,hasActionableCIFailure:p=!0}=t,m="active";s>=a?m="dormant":s>=c&&(m="approaching_dormant");let g=nk(t);return o?ok(g,l,d)?e==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_response",stalenessTier:m}:i==="changes_requested"&&d?ik(g,d)?e==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_changes",stalenessTier:m}:e==="failing"?p?s>=5?{status:"waiting_on_maintainer",waitReason:"stale_ci_failure",stalenessTier:m}:{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"ci_blocked",stalenessTier:m}:n?{status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:m}:r?{status:"needs_addressing",actionReason:"incomplete_checklist",stalenessTier:m}:i==="approved"&&(e==="passing"||e==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"pending_review",stalenessTier:m}}var nA,oA,fh=v(()=>{"use strict";nA=new Set(["autofix-ci[bot]","prettier-ci[bot]","pre-commit-ci[bot]"]),oA=120*1e3});async function _t(t,e=100,n=10){let o=[];for(let r=1;r<=n;r++){let{data:i}=await t(r);if(o.push(...i),i.length<e)break}return o}var ss=v(()=>{"use strict"});function Io(){return hh||(hh=new cs),hh}async function Bc(t,e,n){let o=t.getInflight(e);if(o)return E(fr,`Dedup hit for ${e}`),await o;let i=(async()=>{let a={},c=t.get(e);c&&(a["if-none-match"]=c.etag);try{let l=await n(a),d=l.headers?.etag;return d&&t.set(e,d,l.data),l.data}catch(l){if(dA(l)){let d=t.get(e);if(d)return E(fr,`304 cache hit for ${e}`),d.body}throw l}})(),s=t.setInflight(e,i);try{return await i}finally{s()}}function dA(t){return Ke(t)===304}var Ve,as,sk,fr,uA,lA,cs,hh,Wc=v(()=>{"use strict";Ve=K(require("node:fs"),1),as=K(require("node:path"),1),sk=K(require("node:crypto"),1);rn();we();he();fr="http-cache",uA=1440*60*1e3,lA=2e3,cs=class{cacheDir;maxEntries;inflightRequests=new Map;constructor(e,n=lA){this.cacheDir=e??$c(),this.maxEntries=n}keyFor(e){return sk.createHash("sha256").update(e).digest("hex")}pathFor(e){return as.join(this.cacheDir,`${this.keyFor(e)}.json`)}getIfFresh(e,n){let o=this.get(e);if(!o)return null;let r=Date.now()-new Date(o.cachedAt).getTime();return!Number.isFinite(r)||r<0||r>n?null:o.body}get(e){let n=this.pathFor(e);try{let o=Ve.readFileSync(n,"utf8"),r=JSON.parse(o);return r.url!==e?(E(fr,`Cache collision detected for ${e}, ignoring`),null):r}catch(o){if(o&&typeof o=="object"&&o.code!=="ENOENT"){let r=o instanceof Error?o.message:"unknown error";E(fr,`Cache read failed for ${e} (treating as miss): ${r}`)}return null}}set(e,n,o){let r={etag:n,url:e,body:o,cachedAt:new Date().toISOString()};try{Ve.writeFileSync(this.pathFor(e),JSON.stringify(r),{encoding:"utf8",mode:384}),E(fr,`Cached response for ${e}`),this.evictIfExceeds(this.maxEntries)}catch(i){E(fr,`Failed to write cache for ${e}`,i)}}evictIfExceeds(e){if(!(e<=0))try{let n=Ve.readdirSync(this.cacheDir).filter(s=>s.endsWith(".json"));if(n.length<=e)return;let o=n.map(s=>{let a=as.join(this.cacheDir,s);try{return{fullPath:a,mtimeMs:Ve.statSync(a).mtimeMs}}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.mtimeMs-a.mtimeMs),r=o.length-e,i=0;for(let s=0;s<r;s++)try{Ve.unlinkSync(o[s].fullPath),i++}catch{}i>0&&E(fr,`Capped cache at ${e} entries: evicted ${i} oldest`)}catch{}}hasInflight(e){return this.inflightRequests.has(e)}getInflight(e){return this.inflightRequests.get(e)}setInflight(e,n){return this.inflightRequests.set(e,n),()=>{this.inflightRequests.delete(e)}}evictStale(e=uA){let n=0;try{let o=Ve.readdirSync(this.cacheDir),r=Date.now();for(let i of o){if(!i.endsWith(".json"))continue;let s=as.join(this.cacheDir,i);try{let a=Ve.readFileSync(s,"utf8"),c=JSON.parse(a);r-new Date(c.cachedAt).getTime()>e&&(Ve.unlinkSync(s),n++)}catch{try{Ve.unlinkSync(s),n++}catch{}}}}catch{}return n>0&&E(fr,`Evicted ${n} stale cache entries`),n}clear(){try{let e=Ve.readdirSync(this.cacheDir);for(let n of e)n.endsWith(".json")&&Ve.unlinkSync(as.join(this.cacheDir,n));E(fr,"Cache cleared")}catch{}}size(){try{return Ve.readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).length}catch{return 0}}},hh=null});function qc(){return{status:"unknown",failingCheckNames:[],failingCheckConclusions:new Map}}function Jc(t,e,n){if(n==="cancelled"||n==="timed_out")return"infrastructure";if(n==="action_required")return"auth_gate";let o=t.toLowerCase();if(ck.some(r=>r.test(o)))return"auth_gate";if(ak.some(r=>r.test(o)))return"fork_limitation";if(uk.some(r=>r.test(o)))return"infrastructure";if(e){let r=e.toLowerCase();if(ck.some(i=>i.test(r)))return"auth_gate";if(ak.some(i=>i.test(r)))return"fork_limitation";if(uk.some(i=>i.test(r)))return"infrastructure"}return"actionable"}function us(t,e){return t.map(n=>{let o=e?.get(n);return{name:n,category:Jc(n,void 0,o),conclusion:o}})}function pA(t){let e=!1,n=!1,o=!1,r=[],i=new Map;for(let s of t)s.conclusion==="failure"||s.conclusion==="cancelled"||s.conclusion==="timed_out"||s.conclusion==="action_required"?(e=!0,r.push(s.name),i.set(s.name,s.conclusion)):s.status==="in_progress"||s.status==="queued"?n=!0:s.conclusion==="success"&&(o=!0);return{hasFailingChecks:e,hasPendingChecks:n,hasSuccessfulChecks:o,failingCheckNames:r,failingCheckConclusions:i}}function mA(t){let e=t.statuses.filter(c=>{let l=(c.description||"").toLowerCase();return!(c.state==="failure"&&(l.includes("authorization required")||l.includes("authorize")))}),n=e.some(c=>c.state==="failure"||c.state==="error"),o=e.some(c=>c.state==="pending"),r=e.some(c=>c.state==="success"),i;n?i="failure":o?i="pending":r||e.length===0?i="success":i=t.state;let s=t.statuses.length>0,a=[];for(let c of e)(c.state==="failure"||c.state==="error")&&a.push(c.context);return{effectiveCombinedState:i,hasStatuses:s,failingStatusNames:a}}function gA(t,e,n){let{hasFailingChecks:o,hasPendingChecks:r,hasSuccessfulChecks:i,failingCheckNames:s,failingCheckConclusions:a}=t,{effectiveCombinedState:c,hasStatuses:l,failingStatusNames:d}=e,p=[...s,...d];return o||c==="failure"||c==="error"?{status:"failing",failingCheckNames:p,failingCheckConclusions:a}:r||c==="pending"?{status:"pending",failingCheckNames:[],failingCheckConclusions:new Map}:i||c==="success"?{status:"passing",failingCheckNames:[],failingCheckConclusions:new Map}:qc()}async function vh(t,e,n,o){if(!o)return qc();try{let[r,i]=await Promise.all([t.repos.getCombinedStatusForRef({owner:e,repo:n,ref:o}),t.checks.listForRef({owner:e,repo:n,ref:o}).catch(m=>{let g=Ke(m);if(g===429)throw m;if(g===403){let h=I(m).toLowerCase();if(h.includes("rate limit")||h.includes("abuse detection"))throw m}return g===404?E("pr-monitor",`Check runs 404 for ${e}/${n}@${o.slice(0,7)} (no checks configured)`):b("pr-monitor",`Non-404 error fetching check runs for ${e}/${n}@${o.slice(0,7)}: ${g??m}`),null})]),s=r.data,a=i?.data?.check_runs||[],c=new Map;for(let m of a){let g=c.get(m.name);(!g||new Date(m.started_at??0)>new Date(g.started_at??0))&&c.set(m.name,m)}let l=[...c.values()],d=pA(l),p=mA(s);return gA(d,p,l.length)}catch(r){let i=Ke(r);if(i===401||i===403||i===429)throw r;return i===404?E("pr-monitor",`CI check 404 for ${e}/${n} (no CI configured)`):b("pr-monitor",`Failed to check CI for ${e}/${n}@${o.slice(0,7)}: ${I(r)}`),qc()}}var ak,ck,uk,bh=v(()=>{"use strict";he();we();ak=[/vercel/i,/netlify/i,/\bpreview\s*deploy/i,/\bdeploy\s*preview/i,/storybook/i,/chromatic/i,/percy/i,/cloudflare pages/i,/\binternal\b(?!\s+(?:api|test|integration|smoke|unit|e2e|regression|functional))/i],ck=[/authoriz/i,/approval/i,/\bcla\b/i,/license\/cla/i],uk=[/\binstall\s*(os\s*)?dep(endenc|s\b)/i,/\bsetup\s+fail(ed|ure)?\b/i,/\bservice\s*unavailable/i,/\binfrastructure/i,/\bblacksmith\b/i,/\breadthedocs\b/i]});function hr(t){return t.includes("[bot]")||fA.has(t.toLowerCase())}function Oo(t){if(!t||t.length>100||t.includes("?"))return!1;let e=t.toLowerCase();return["thanks","thank you","lgtm","looks good","will review","we'll review","we'll get to this","noted","got it","will look","will check"].some(o=>e.includes(o))}var fA,ls=v(()=>{"use strict";fA=new Set(["allcontributors","changeset-bot","claassistant","codecov-commenter","greenkeeper","imgbot","netlify","renovate","snyk-bot","sonarcloud","stale","vercel"])});function lk(t){if(t.length===0)return"review_required";let e=new Map;for(let o of t){let r=o.user?.login,i=o.state;r&&i&&e.set(r,i)}let n=Array.from(e.values());return n.includes("CHANGES_REQUESTED")?"changes_requested":n.includes("APPROVED")?"approved":"review_required"}function dk(t){let e;for(let n of t)n.state==="CHANGES_REQUESTED"&&n.submitted_at&&(!e||n.submitted_at>e)&&(e=n.submitted_at);return e}function hA(t,e){let n=e.filter(r=>r.pull_request_review_id===t);if(n.length===0)return!1;let o=new Map;for(let r of e)r.user?.login&&o.set(r.id,r.user.login.toLowerCase());return n.every(r=>{if(!r.in_reply_to_id)return!1;let i=o.get(r.in_reply_to_id),s=r.user?.login?.toLowerCase();return!(i==null||s==null||i!==s||!r.body||r.body.includes("?"))})}function vA(t,e){return e.find(n=>n.pull_request_review_id===t&&n.body?.trim())?.body?.trim()}function bA(t,e){return e.some(n=>n.pull_request_review_id===t)}function pk(t,e,n,o){let r=[],i=o.toLowerCase();for(let d of t){let p=d.user?.login||"unknown";r.push({author:p,body:d.body||"",createdAt:d.created_at,isUser:p.toLowerCase()===i})}for(let d of e){if(!d.submitted_at)continue;let p=(d.body||"").trim();if(!p&&d.state!=="COMMENTED"&&d.state!=="CHANGES_REQUESTED")continue;let m=d.user?.login||"unknown";if(!p&&d.state==="COMMENTED"&&d.id!=null&&hA(d.id,n))continue;let g=p||(d.id!=null?vA(d.id,n):void 0)||(d.state==="CHANGES_REQUESTED"?"(requested changes via inline review comments)":"(posted inline review comments)");r.push({author:m,body:g,createdAt:d.submitted_at,isUser:m.toLowerCase()===i,reviewId:d.id})}r.sort((d,p)=>new Date(d.createdAt).getTime()-new Date(p.createdAt).getTime());let s=null;for(let d of r)d.isUser&&(s=new Date(d.createdAt));let a,c;for(let d of r){if(d.isUser||d.author==="unknown"||hr(d.author))continue;let p=new Date(d.createdAt);(!s||p>s)&&(a={author:d.author,body:d.body.slice(0,200)+(d.body.length>200?"...":""),createdAt:d.createdAt},c=d.reviewId)}let l=c!=null&&bA(c,n);return a&&Oo(a.body)&&!l&&(a=void 0),{hasUnrespondedComment:!!a,lastMaintainerComment:a}}var mk=v(()=>{"use strict";ls()});function gk(t){return yA.test(t.toLowerCase())}function fk(t){if(!t)return{hasIncompleteChecklist:!1};let e=/- \[x\]/gi,n=/^.*- \[ \].*$/gm,o=t.match(e)||[],r=t.match(n)||[],i=o.length;if(i+r.length===0)return{hasIncompleteChecklist:!1};let a=r.filter(l=>!gk(l)),c=i+a.length;return{hasIncompleteChecklist:a.length>0,checklistStats:{checked:i,total:c}}}var yA,yh=v(()=>{"use strict";yA=/\(if\s|\bif applicable\b|\bif needed\b|\bif relevant\b|\bonly if\b|\bwhen applicable\b|\(optional\)|- \[ \]\s*optional\b|\bn\/a\b|\bnot applicable\b|\bif required\b|\bif necessary\b/});function hk(t,e){let n=[];if(e==="changes_requested"&&n.push("changes_requested"),!t)return n;let o=t.toLowerCase();["screenshot","demo","recording","screen recording","before/after","before and after","gif","video","screencast","show me","can you show"].some(l=>o.includes(l))&&n.push("demo_requested"),["add test","test coverage","unit test","missing test","add a test","write test","needs test","need test"].some(l=>o.includes(l))&&n.push("tests_requested"),["documentation","readme","jsdoc","docstring","add docs","update docs","document this"].some(l=>o.includes(l))&&n.push("docs_requested");let a=["merge conflict","out of date","behind main","behind master"];return(/\brebase\b/i.test(t)||a.some(l=>o.includes(l)))&&n.push("rebase_requested"),n}var vk=v(()=>{"use strict"});function SA(t){let e=bk[t]?.label;return e?e.replace(/[[\]]/g,"").toLowerCase():t}function ds(t){if(t.status==="needs_addressing"&&t.actionReason){let e=bk[t.actionReason];if(e){let n=e.description(t);if(t.actionReasons&&t.actionReasons.length>1){let o=t.actionReasons.filter(r=>r!==t.actionReason).map(SA);o.length>0&&(n+=` (also: ${o.join(", ")})`)}return{displayLabel:e.label,displayDescription:n}}}if(t.status==="waiting_on_maintainer"&&t.waitReason){let e=_A[t.waitReason];if(e)return{displayLabel:e.label,displayDescription:e.description(t)}}return b("display-utils",`PR ${t.url} has status "${t.status}" but no matching reason (actionReason=${t.actionReason}, waitReason=${t.waitReason})`),t.status==="needs_addressing"?{displayLabel:"[Needs Addressing]",displayDescription:"Action required"}:{displayLabel:"[Waiting on Maintainer]",displayDescription:"Awaiting maintainer action"}}var bk,_A,_h=v(()=>{"use strict";we();bk={needs_response:{label:"[Needs Response]",description:t=>t.lastMaintainerComment?`@${t.lastMaintainerComment.author} commented`:"Maintainer awaiting response"},needs_changes:{label:"[Needs Changes]",description:()=>"Review requested changes \u2014 push commits to address"},failing_ci:{label:"[CI Failing]",description:t=>{let e=t.classifiedChecks||[],n=e.filter(i=>i.category==="actionable");if(n.length>0)return`${n.length} check${n.length===1?"":"s"} failed: ${n.map(i=>i.name).join(", ")}`;let o=e.filter(i=>i.category==="infrastructure");if(o.length>0)return`${o.length} check${o.length===1?"":"s"} cancelled/timed out (infrastructure)`;let r=t.failingCheckNames||[];return r.length>0?`${r.length} check${r.length===1?"":"s"} failed`:"One or more CI checks are failing"}},merge_conflict:{label:"[Merge Conflict]",description:()=>"PR has merge conflicts with the base branch"},incomplete_checklist:{label:"[Incomplete Checklist]",description:t=>t.checklistStats?`${t.checklistStats.checked}/${t.checklistStats.total} items checked`:"PR body has unchecked required checkboxes"},ci_not_running:{label:"[CI Not Running]",description:()=>"No CI checks have been triggered"},needs_rebase:{label:"[Needs Rebase]",description:()=>"PR branch is significantly behind upstream"},missing_required_files:{label:"[Missing Files]",description:t=>t.missingRequiredFiles?`Missing: ${t.missingRequiredFiles.join(", ")}`:"Required files are missing"}},_A={pending_review:{label:"[Waiting on Maintainer]",description:()=>"Awaiting review"},pending_merge:{label:"[Waiting on Maintainer]",description:()=>"Approved and CI passes \u2014 waiting for merge"},changes_addressed:{label:"[Waiting on Maintainer]",description:t=>t.hasUnrespondedComment&&t.lastMaintainerComment?`Changes addressed \u2014 waiting for @${t.lastMaintainerComment.author} to re-review`:"Changes addressed \u2014 awaiting re-review"},ci_blocked:{label:"[CI Blocked]",description:t=>{let e=t.classifiedChecks||[];return e.length>0&&e.every(n=>n.category!=="actionable")?`All failing checks are non-actionable (${[...new Set(e.map(o=>o.category))].join(", ")})`:"CI checks are failing but no action is needed from you"}},stale_ci_failure:{label:"[Stale CI Failure]",description:t=>`CI failing for ${t.daysSinceActivity}+ days \u2014 likely pre-existing or non-actionable`}}});function fn(){return{repos:new Map,monthlyCounts:{},monthlyOpenedCounts:{},dailyActivityCounts:{}}}function $A(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.reposEntries)&&typeof e.monthlyCounts=="object"&&e.monthlyCounts!==null&&typeof e.monthlyOpenedCounts=="object"&&e.monthlyOpenedCounts!==null&&typeof e.dailyActivityCounts=="object"&&e.dailyActivityCounts!==null}async function yk(t,e,n,o,r,i){if(!e)return fn();let s=Io(),a=i?`:stars${i.minStars}`:"",c=`pr-counts:v3:${o}:${e}${a}`,l=s.getIfFresh(c,wA);if(l&&$A(l))return E(Be,`Using cached ${o} PR counts for @${e}`),{repos:new Map(l.reposEntries),monthlyCounts:l.monthlyCounts,monthlyOpenedCounts:l.monthlyOpenedCounts,dailyActivityCounts:l.dailyActivityCounts};E(Be,`Fetching ${o} PR counts for @${e}...`);let d=new Map,p={},m={},g={},h=1,_=0,$;for(;;){let{data:S}=await t.search.issuesAndPullRequests({q:`is:pr ${n} author:${e} -user:${e}`,sort:"updated",order:"desc",per_page:100,page:h});$=S.total_count;for(let T of S.items){let j=fo(T.html_url);if(!j){b(Be,`Skipping ${o} PR with unparseable URL: ${T.html_url}`);continue}let{owner:F}=j,U=`${F}/${j.repo}`;if(er(F,e)||i&&Qt(i.knownStarCounts.get(U),i.minStars))continue;let J=r(d,U,T);if(J){let Y=J.slice(0,7);p[Y]=(p[Y]||0)+1;let ue=J.slice(0,10);ue.length===10&&(g[ue]=(g[ue]||0)+1)}if(T.created_at){let Y=T.created_at.slice(0,7);m[Y]=(m[Y]||0)+1;let ue=T.created_at.slice(0,10);ue.length===10&&(g[ue]=(g[ue]||0)+1)}}if(_+=S.items.length,_>=S.total_count||_>=1e3||S.items.length===0||h>=Ao)break;h++}return _<$&&h>=Ao&&b(Be,`Pagination capped at ${Ao} pages: fetched ${_} of ${$} ${o} PRs. Stats may be incomplete for prolific contributors.`),E(Be,`Found ${_} ${o} PRs across ${d.size} repos`),s.set(c,"",{reposEntries:Array.from(d.entries()),monthlyCounts:p,monthlyOpenedCounts:m,dailyActivityCounts:g}),{repos:d,monthlyCounts:p,monthlyOpenedCounts:m,dailyActivityCounts:g}}function _k(t,e,n){return yk(t,e,"is:merged","merged",(o,r,i)=>{i.pull_request?.merged_at||b(Be,`merged_at missing for merged PR ${i.html_url}${i.closed_at?", falling back to closed_at":", no date available"}`);let s=i.pull_request?.merged_at||i.closed_at||"",a=o.get(r);return a?(a.count+=1,s&&s>a.lastMergedAt&&(a.lastMergedAt=s)):o.set(r,{count:1,lastMergedAt:s}),s},n)}function Sk(t,e,n){return yk(t,e,"is:closed is:unmerged","closed",(o,r,i)=>(o.set(r,(o.get(r)||0)+1),i.closed_at||""),n)}async function wk(t,e,n,o,r,i){if(!e.githubUsername)return b(Be,`Skipping recently ${o} PRs fetch: no githubUsername configured. Run /setup-oss to configure.`),[];let s=new Date;s.setDate(s.getDate()-r);let a=s.toISOString().split("T")[0];E(Be,`Fetching recently ${o} PRs for @${e.githubUsername} (since ${a})...`);let{data:c}=await t.search.issuesAndPullRequests({q:n.replace("{username}",e.githubUsername).replace("{since}",a),sort:"updated",order:"desc",per_page:100}),l=[];for(let d of c.items){let p=xe(d.html_url);if(!p){b(Be,`Could not parse GitHub URL from API response: ${d.html_url}`);continue}if(er(p.owner,e.githubUsername))continue;let m=`${p.owner}/${p.repo}`;l.push(i(d,{owner:p.owner,repo:m,number:p.number}))}return E(Be,`Found ${l.length} recently ${o} PRs`),l}async function $k(t,e,n=7){return wk(t,e,"is:pr is:closed is:unmerged is:public author:{username} closed:>={since}","closed",n,(o,{repo:r,number:i})=>({url:o.html_url,repo:r,number:i,title:o.title,closedAt:o.closed_at||""}))}async function kk(t,e,n=7){return wk(t,e,"is:pr is:merged is:public author:{username} merged:>={since}","merged",n,(o,{repo:r,number:i})=>{let s=o.pull_request?.merged_at;return s||b(Be,`merged_at missing for merged PR ${o.html_url}${o.closed_at?", falling back to closed_at":", no date available"}`),{url:o.html_url,repo:r,number:i,title:o.title,mergedAt:s||o.closed_at||""}})}async function Rk(t,e,n,o){if(!e.githubUsername)return b(Be,`Skipping ${n.kind} PRs fetch: no githubUsername configured.`),[];let r=n.buildQuery(e.githubUsername,o);E(Be,`Fetching ${n.kind} PRs${o?` since ${o}`:" (all time)"}...`);let i=[],s=1,a=0,c;for(;;){let{data:l}=await t.search.issuesAndPullRequests({q:r,sort:"updated",order:"desc",per_page:100,page:s});c=l.total_count;for(let d of l.items){let p=xe(d.html_url);if(!p){b(Be,`Skipping ${n.kind} PR with unparseable URL: ${d.html_url}`);continue}if(er(p.owner,e.githubUsername))continue;let m=n.extractDate(d);if(!m){b(Be,`Skipping ${n.kind} PR with no ${n.dateNoun} date: ${d.html_url}`);continue}i.push(n.buildRecord(d,m))}if(a+=l.items.length,a>=c||a>=1e3||l.items.length===0||s>=Ao)break;s++}return a<c&&s>=Ao&&b(Be,`Pagination capped at ${Ao} pages: fetched ${a} of ${c} ${n.kind} PRs. Oldest PRs may be missing.`),E(Be,`Fetched ${i.length} ${n.kind} PRs${o?" (incremental)":" (initial)"}`),i}async function Ek(t,e,n){return Rk(t,e,{kind:"merged",dateNoun:"merge",buildQuery:(o,r)=>`is:pr is:merged author:${o} -user:${o}${r?` merged:>${r}`:""}`,extractDate:o=>o.pull_request?.merged_at||o.closed_at||"",buildRecord:(o,r)=>({url:o.html_url,title:o.title,mergedAt:r})},n)}async function Tk(t,e,n){return Rk(t,e,{kind:"closed",dateNoun:"close",buildQuery:(o,r)=>`is:pr is:closed is:unmerged author:${o} -user:${o}${r?` closed:>${r}`:""}`,extractDate:o=>o.closed_at||"",buildRecord:(o,r)=>({url:o.html_url,title:o.title,closedAt:r})},n)}var Be,wA,Ao,Kc=v(()=>{"use strict";It();Dr();we();Wc();Be="github-stats",wA=1440*60*1e3,Ao=3});function ps(t){return RA.has(t.toLowerCase())}var kA,RA,Sh=v(()=>{"use strict";kA=["example-user","your-username","your-github-username"],RA=new Set(kA)});function EA(t,e){return t===!1||e==="dirty"}var Lt,TA,jr,xk=v(()=>{"use strict";ko();To();xo();It();Vc();fh();he();ss();we();Wc();bh();mk();yh();vk();_h();Kc();Sh();_h();bh();yh();fh();Lt="pr-monitor",TA=5,jr=class{octokit;stateManager;constructor(e){this.octokit=Ie(e),this.stateManager=L()}async fetchUserOpenPRs(){let e=this.stateManager.getState().config;if(!e.githubUsername)throw new ot("No GitHub username configured. Run setup first.");let n=[],o=e.githubUsername,r=!1;if(ps(o))try{let{data:$}=await this.octokit.users.getAuthenticated(),S=$.login?.trim();if(!S||ps(S)){let T=`Placeholder username "${o}" detected but authenticated viewer returned an unusable login (${JSON.stringify($.login)}); skipping auto-repair.`;n.push(T),b(Lt,T)}else{this.stateManager.updateConfig({githubUsername:S}),o=S,r=!0;let T=`Configured GitHub username "${e.githubUsername}" looks like a placeholder. Auto-repaired to "${S}" using the authenticated viewer.`;n.push(T),b(Lt,T)}}catch($){if(dt($))throw $;let S=`Could not auto-repair placeholder username "${o}": ${I($)}`;n.push(S),b(Lt,S)}E("pr-monitor",`Fetching open PRs for @${o}...`);let i=[],s=1,a=100,c=await this.octokit.search.issuesAndPullRequests({q:`is:pr is:open is:public author:${o}`,sort:"updated",order:"desc",per_page:a,page:1});i.push(...c.data.items);let l=c.data.total_count;E(Lt,`Found ${l} open PRs`);let d=1e3,p=Math.ceil(d/a),m=Math.min(Math.ceil(l/a),p);if(l===0&&!r)try{let{data:$}=await this.octokit.users.getAuthenticated();if($.login.toLowerCase()!==o.toLowerCase()){let S=`Configured GitHub username @${o} does not match authenticated user @${$.login}. Did you mean to run \`oss-autopilot config username ${$.login}\`? Zero PRs returned.`;n.push(S),b(Lt,S)}}catch($){if(dt($))throw $;E(Lt,`Could not cross-check viewer login: ${I($)}`)}for(l>d&&(n.push(`GitHub Search API returned ${l} PRs for @${o}, but results are capped at ${d}. Showing the ${d} most recently updated PRs.`),b(Lt,n[n.length-1]));s<m;){s++;let $=await this.octokit.search.issuesAndPullRequests({q:`is:pr is:open is:public author:${o}`,sort:"updated",order:"desc",per_page:a,page:s});i.push(...$.data.items)}let g=[],h=[],_=i.filter($=>{if(!$.pull_request)return!1;let S=fo($.html_url);return S?!er(S.owner,o):(b("pr-monitor",`Skipping PR with unparseable URL: ${$.html_url}`),!1)});return E("pr-monitor",`Filtered to ${_.length} PRs after excluding own repos`),await Tc("pr-monitor",`Fetch details for ${_.length} PRs`,async()=>{await Zc(_,async $=>{try{E("pr-monitor",`Fetching details for ${$.html_url}`);let S=await this.fetchPRDetails($.html_url);S&&g.push(S)}catch(S){let T=I(S);b("pr-monitor",`Error fetching ${$.html_url}: ${T}`),h.push({prUrl:$.html_url,error:T})}},TA)}),g.sort(($,S)=>$.status===S.status?0:$.status==="needs_addressing"?-1:1),n.length>0?{prs:g,failures:h,warnings:n}:{prs:g,failures:h}}async fetchPRDetails(e){let n=xe(e);if(!n||n.type!=="pull")throw new ne(`Invalid PR URL format: ${e}`);let{owner:o,repo:r,number:i}=n,s=this.stateManager.getState().config,[a,c,l,d]=await Promise.all([this.octokit.pulls.get({owner:o,repo:r,pull_number:i}),_t(pe=>this.octokit.issues.listComments({owner:o,repo:r,issue_number:i,per_page:100,page:pe})),this.octokit.pulls.listReviews({owner:o,repo:r,pull_number:i}),_t(pe=>this.octokit.pulls.listReviewComments({owner:o,repo:r,pull_number:i,per_page:100,page:pe})).catch(pe=>{let je=Ke(pe);if(je===429)throw pe;if(je===403){let Ye=I(pe).toLowerCase();if(Ye.includes("rate limit")||Ye.includes("abuse detection"))throw pe;return b("pr-monitor",`403 fetching review comments for ${o}/${r}#${i}: ${Ye}`),[]}return je===404?E("pr-monitor",`Review comments 404 for ${o}/${r}#${i} (likely no inline comments)`):b("pr-monitor",`Failed to fetch review comments for ${o}/${r}#${i} (status ${je??"unknown"}): self-reply detection will be skipped`),[]})]),p=a.data,m=l.data,g=lk(m),h=EA(p.mergeable,p.mergeable_state),{hasUnrespondedComment:_,lastMaintainerComment:$}=pk(c,m,d,s.githubUsername),S=vh(this.octokit,o,r,p.head.sha),j=_||g==="changes_requested"?this.octokit.repos.getCommit({owner:o,repo:r,ref:p.head.sha}).then(pe=>({date:pe.data.commit.author?.date,author:pe.data.author?.login})).catch(pe=>{let je=Ke(pe);if(je===429)throw pe;if(je===403){let Ye=I(pe).toLowerCase();if(Ye.includes("rate limit")||Ye.includes("abuse detection"))throw pe;b("pr-monitor",`403 fetching commit date for ${o}/${r}@${p.head.sha.slice(0,7)}: ${I(pe)}`);return}b("pr-monitor",`Failed to fetch commit date for ${o}/${r}@${p.head.sha.slice(0,7)}: ${I(pe)}`)}):Promise.resolve(void 0),[{status:F,failingCheckNames:U,failingCheckConclusions:J},Y]=await Promise.all([S,j]),ue=Y?.date,M=Y?.author,{hasIncompleteChecklist:z,checklistStats:W}=fk(p.body||""),de=hk($?.body,g),q=gn(new Date(p.updated_at),new Date),Ae=dk(m),Ue=us(U,J),ce=F==="failing"&&Ue.some(pe=>pe.category==="actionable"),{status:ht,actionReason:Et,waitReason:ur,stalenessTier:re,actionReasons:fe}=gh({ciStatus:F,hasMergeConflict:h,hasUnrespondedComment:_,hasIncompleteChecklist:z,reviewDecision:g,daysSinceActivity:q,dormantThreshold:s.dormantThresholdDays,approachingThreshold:s.approachingDormantDays,latestCommitDate:ue,latestCommitAuthor:M,contributorUsername:s.githubUsername,lastMaintainerCommentDate:$?.createdAt,latestChangesRequestedDate:Ae,hasActionableCIFailure:ce});return this.buildFetchedPR({id:p.id,url:e,repo:`${o}/${r}`,number:i,title:p.title,status:ht,actionReason:Et,waitReason:ur,stalenessTier:re,actionReasons:fe,createdAt:p.created_at,updatedAt:p.updated_at,daysSinceActivity:q,ciStatus:F,failingCheckNames:U,classifiedChecks:Ue,hasMergeConflict:h,reviewDecision:g,hasUnrespondedComment:_,lastMaintainerComment:$,latestCommitDate:ue,hasIncompleteChecklist:z,checklistStats:W,maintainerActionHints:de})}buildFetchedPR(e){let n={...e,displayLabel:"",displayDescription:""},{displayLabel:o,displayDescription:r}=ds(n);return n.displayLabel=o,n.displayDescription=r,n}async fetchUserMergedPRCounts(e){let n=this.stateManager.getState().config;return _k(this.octokit,n.githubUsername,e)}async fetchUserClosedPRCounts(e){let n=this.stateManager.getState().config;return Sk(this.octokit,n.githubUsername,e)}async fetchRepoMetadata(e){if(e.length===0)return new Map;E(Lt,`Fetching repo metadata for ${e.length} repos...`);let n=new Map,o=Io(),r=[...new Set(e)],i=10;for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i),c=await Promise.allSettled(a.map(async d=>{let p=d.split("/");if(p.length!==2||!p[0]||!p[1])throw new ne(`Malformed repo identifier: "${d}"`);let[m,g]=p,h=`/repos/${m}/${g}`,_=await Bc(o,h,S=>this.octokit.repos.get({owner:m,repo:g,headers:S})),$={stars:_.stargazers_count,language:_.language??null};return{repo:d,metadata:$}})),l=0;for(let d=0;d<c.length;d++){let p=c[d];p.status==="fulfilled"?n.set(p.value.repo,p.value.metadata):(l++,b(Lt,`Failed to fetch metadata for ${a[d]}: ${I(p.reason)}`))}if(l===a.length&&a.length>0){let d=r.length-s-i;d>0&&b(Lt,`Entire chunk failed, aborting remaining ${d} repos`);break}}return E(Lt,`Fetched repo metadata for ${n.size}/${e.length} repos`),n}async fetchRecentlyClosedPRs(e=7){let n=this.stateManager.getState().config;return $k(this.octokit,n,e)}async fetchRecentlyMergedPRs(e=7){let n=this.stateManager.getState().config;return kk(this.octokit,n,e)}generateDigest(e,n=[],o=[]){let r=new Date().toISOString(),i=e.filter(c=>c.status==="needs_addressing"),s=e.filter(c=>c.status==="waiting_on_maintainer"),a=this.stateManager.getStats();return{generatedAt:r,openPRs:e,needsAddressingPRs:i,waitingOnMaintainerPRs:s,recentlyClosedPRs:n,recentlyMergedPRs:o,shelvedPRs:[],autoUnshelvedPRs:[],summary:{totalActivePRs:e.length,totalNeedingAttention:i.length,totalMergedAllTime:a.mergedPRs,mergeRate:parseFloat(a.mergeRate)}}}async updateRepoScoreFromObservedPR(e,n){n?this.stateManager.incrementMergedCount(e):this.stateManager.incrementClosedCount(e)}}});var vr,xA,Pk,Gr,Ck=v(()=>{"use strict";ko();ls();ss();To();xo();It();Vc();he();we();vr="issue-conversation",xA=5,Pk=new Set(["OWNER","MEMBER","COLLABORATOR"]),Gr=class{octokit;stateManager;constructor(e){this.octokit=Ie(e),this.stateManager=L()}async fetchCommentedIssues(e=30){let n=this.stateManager.getState().config;if(!n.githubUsername)throw new ot("No GitHub username configured. Run setup first.");let o=n.githubUsername,r=new Date;r.setDate(r.getDate()-e);let i=r.toISOString().split("T")[0];E(vr,`Fetching commented issues for @${o} (last ${e} days)...`);let{data:s}=await this.octokit.search.issuesAndPullRequests({q:`commenter:${o} type:issue state:open updated:>=${i}`,sort:"updated",order:"desc",per_page:100});s.total_count>100&&b(vr,`Search returned ${s.total_count} results but only first 100 were fetched. Some commented issues may be missing.`);let a=this.stateManager.getState().activeIssues||[],c=new Set(a.filter(h=>h.status==="claimed"||h.status==="in_progress"||h.status==="pr_submitted").map(h=>`${h.repo}#${h.number}`)),l=new Set((n.aiPolicyBlocklist||[]).map(h=>h.toLowerCase())),d=[];for(let h of s.items){if(h.pull_request)continue;let _=fo(h.html_url);if(!_){b(vr,`Skipping issue with unparseable URL: ${h.html_url}`);continue}let{owner:$,repo:S}=_,T=`${$}/${S}`;er($,o)||h.user?.login?.toLowerCase()!==o.toLowerCase()&&(n.excludeRepos.includes(T)||n.excludeOrgs?.some(j=>$.toLowerCase()===j.toLowerCase())||l.has(T.toLowerCase())||c.has(`${T}#${h.number}`)||d.push({item:h,repoFullName:T}))}E(vr,`Found ${d.length} commented issues to check`);let p=[],m=[];await Zc(d,async({item:h,repoFullName:_})=>{try{let $=await this.analyzeIssueConversation(h,_,o);$?p.push($):m.push({issueUrl:h.html_url,error:"No user comment found despite commenter: search match (possible pagination or eventual consistency)"})}catch($){let S=I($);m.push({issueUrl:h.html_url,error:S}),b(vr,`Error analyzing issue ${h.html_url}: ${S}`)}},xA),m.length>0&&b(vr,`${m.length}/${d.length} issue analysis call(s) failed`),m.length===d.length&&d.length>0&&b(vr,`All ${d.length} issue analysis call(s) failed. Possible systemic issue (rate limit, auth, network).`);let g={new_response:0,waiting:1,acknowledged:2};return p.sort((h,_)=>g[h.status]-g[_.status]),E(vr,`Analyzed ${p.length} issue conversations (${p.filter(h=>h.status==="new_response").length} with new responses)`),{issues:p,failures:m}}async analyzeIssueConversation(e,n,o){let{owner:r,repo:i}=ho(n),s=await _t(S=>this.octokit.issues.listComments({owner:r,repo:i,issue_number:e.number,per_page:100,page:S})),a=[];for(let S of s){if(!S.user?.login)continue;let T=S.user.login;a.push({author:T,body:S.body||"",createdAt:S.created_at,isUser:T.toLowerCase()===o.toLowerCase(),authorAssociation:typeof S.author_association=="string"?S.author_association:""})}a.sort((S,T)=>new Date(S.createdAt).getTime()-new Date(T.createdAt).getTime());let c;for(let S of a)S.isUser&&(c=S);if(!c)return b(vr,`No user comment found for ${e.html_url} despite commenter: search match`),null;let l=new Date(c.createdAt),d=`@${o.toLowerCase()}`;function p(S){return Pk.has(S.authorAssociation)||S.body.toLowerCase().includes(d)}let m;for(let S of a){if(S.isUser||hr(S.author))continue;if(new Date(S.createdAt)>l){if(Oo(S.body)||!p(S))continue;m={author:S.author,body:S.body.slice(0,200)+(S.body.length>200?"...":""),createdAt:S.createdAt,authorAssociation:S.authorAssociation}}}let g=(e.labels||[]).map(S=>S.name||"").filter(Boolean),h={repo:n,number:e.number,title:e.title,url:e.html_url,userLastCommentedAt:c.createdAt,labels:g,daysSinceUserComment:gn(l,new Date)};if(m)return{...h,status:"new_response",lastResponseAuthor:m.author,lastResponseBody:m.body,lastResponseAt:m.createdAt,isFromMaintainer:Pk.has(m.authorAssociation)};let $=[...a].reverse().find(S=>hr(S.author)?!1:S.isUser?!0:p(S))?.isUser?"acknowledged":"waiting";return{...h,status:$}}}});function Xc(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ").replace(/\r/g," ")}function Dk(t,e,n={}){let o=t.split("&").join(Ik).split(zr).join(Ok).replace(PA,Ak),r=[`label="${Xc(e)}"`];return n.author!==void 0&&r.push(`author="${Xc(n.author)}"`),n.association!==void 0&&r.push(`association="${Xc(n.association)}"`),n.source!==void 0&&r.push(`source="${Xc(n.source)}"`),`<${br} ${r.join(" ")}>${o}${zr}`}function Uk(t){let e=t.match(new RegExp(`^<${br}\\b[^>]*>`));if(!e)throw new Error("extractFromFence: input does not start with a <github-content> open tag");if(!t.endsWith(zr))throw new Error("extractFromFence: input does not end with </github-content>");let n=t.slice(e[0].length,t.length-zr.length);if(n.includes(zr))throw new Error("extractFromFence: nested </github-content> found in body \u2014 fence escaping is broken");return n.split(Ok).join(zr).split(Ak).join(`<${br}`).split(Ik).join("&")}var br,zr,Ik,Ok,PA,Ak,Fk=v(()=>{"use strict";br="github-content",zr=`</${br}>`,Ik="&",Ok=`</${br}>`,PA=new RegExp(`<${br}\\b`,"g"),Ak=`<${br}`});function vn(){if(St)return St;if(ms)return null;if(ms=!0,process.env.GITHUB_TOKEN)return St=process.env.GITHUB_TOKEN,St;try{let t=(0,gs.execFileSync)("gh",["auth","token"],{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:2e3}).trim();if(t&&t.length>0)return St=t,E(hn,"Using GitHub token from gh CLI"),St}catch(t){b(hn,`gh auth token failed (CLI unavailable or not authenticated): ${t instanceof Error?t.message:String(t)}`)}return null}function We(){let t=vn();if(!t)throw new ot(`GitHub authentication required.
|
|
106
|
+
`);let l={},d=new o.Events(l);return l.on("secondary-limit",c.onSecondaryRateLimit),l.on("rate-limit",c.onRateLimit),l.on("error",p=>t.log.warn("Error in throttling-plugin limit handler",p)),c.retryLimiter.on("failed",async function(p,m){let[g,h,_]=m.args,{pathname:$}=new URL(_.url,"http://github.test");if(!($.startsWith("/graphql")&&p.status!==401||p.status===403||p.status===429))return;let T=~~h.retryCount;h.retryCount=T,_.request.retryCount=T;let{wantRetry:j,retryAfter:F=0}=await(async function(){if(/\bsecondary rate\b/i.test(p.message)){let U=Number(p.response.headers["retry-after"])||g.fallbackSecondaryRateRetryAfter;return{wantRetry:await d.trigger("secondary-limit",U,_,t,T),retryAfter:U}}if(p.response.headers!=null&&p.response.headers["x-ratelimit-remaining"]==="0"||(p.response.data?.errors??[]).some(U=>U.type==="RATE_LIMITED")){let U=new Date(~~p.response.headers["x-ratelimit-reset"]*1e3).getTime(),J=Math.max(Math.ceil((U-Date.now())/1e3)+1,0);return{wantRetry:await d.trigger("rate-limit",J,_,t,T),retryAfter:J}}return{}})();if(j)return h.retryCount++,F*g.retryAfterBaseValue}),t.hook.wrap("request",KO.bind(null,c)),{}}var J$,JO,uh,QO,q$,K$,dn,tA,lh=v(()=>{J$=K(W$(),1),JO="0.0.0-development",uh=()=>Promise.resolve();QO=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];q$=eA(QO),K$=q$.test.bind(q$),dn={},tA=function(t,e){dn.global=new t.Group({id:"octokit-global",maxConcurrent:10,...e}),dn.auth=new t.Group({id:"octokit-auth",maxConcurrent:1,...e}),dn.search=new t.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...e}),dn.write=new t.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...e}),dn.notifications=new t.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...e})};$o.VERSION=JO;$o.triggersNotification=K$});var Q$={};ie(Q$,{checkRateLimit:()=>dh,getOctokit:()=>Ie,getRateLimitCallbacks:()=>Y$});function Mc(t){return t.toLocaleTimeString("en-US",{hour12:!1})}function Y$(){return{onRateLimit:(t,e,n,o)=>{let r=e,i=new Date(Date.now()+t*1e3);return o<2?(b(Lc,`Rate limit hit (retry ${o+1}/2, waiting ${t}s, resets at ${Mc(i)}) \u2014 ${r.method} ${r.url}`),!0):(b(Lc,`Rate limit exceeded, not retrying \u2014 ${r.method} ${r.url} (resets at ${Mc(i)})`),!1)},onSecondaryRateLimit:(t,e,n,o)=>{let r=e,i=new Date(Date.now()+t*1e3);return o<3?(b(Lc,`Secondary rate limit hit (retry ${o+1}/3, waiting ${t}s, resets at ${Mc(i)}) \u2014 ${r.method} ${r.url}`),!0):(b(Lc,`Secondary rate limit exceeded, not retrying \u2014 ${r.method} ${r.url} (resets at ${Mc(i)})`),!1)}}}function Ie(t){if(Nc&&X$===t)return Nc;let e=Y$();return Nc=new rA({auth:t,throttle:e}),X$=t,Nc}async function dh(t){let e=Ie(t),{data:n}=await e.rateLimit.get(),o=n.resources.search;return{remaining:o.remaining,limit:o.limit,resetAt:new Date(o.reset*1e3).toISOString()}}var Lc,rA,Nc,X$,ko=v(()=>{"use strict";sh();lh();we();Lc="github",rA=zc.plugin($o),Nc=null,X$=null});function ek(t,e){let n=[],o=0;for(let r of t){if(xe(r.url)===null){b(Fe,`Dropping ${e} PR with invalid URL: ${r.url}`),o++;continue}n.push(r)}return{valid:n,dropped:o}}async function Ge(t,e){if(t.isGistMode())try{await t.checkpoint()}catch(n){b(e,`Gist checkpoint failed (local mutation succeeded, will retry on next push): ${I(n)}`)}}function L(){return mn||(mn=new Ro),mn}async function ph(t){return mn||pn||(t?(pn=Ro.createWithGist(t).then(e=>(mn=e,pn=null,e)).catch(e=>{if(pn=null,e instanceof ot||!bw(e))throw e;return b(Fe,`Gist initialization failed (transient network error), falling back to local-only mode: ${e}`),L()}),pn):L())}async function tk(t){if(!t)return;let e;try{let n=Eo.readFileSync(nt(),"utf8");e=JSON.parse(n)?.config?.persistence}catch{return}e==="gist"&&await ph(t)}function Hc(){mn=null,pn=null}var Eo,Fe,Ro,mn,pn,To=v(()=>{"use strict";Eo=K(require("node:fs"),1);uo();Xi();Gw();we();he();Nf();Zf();rn();It();Xi();Fe="state";Ro=class t{state;inMemoryOnly;lastLoadedMtimeMs=0;_batching=!1;_batchDirty=!1;gistStore=null;gistDegraded=!1;staleness=null;lastSuccessfulRefreshAt=null;constructor(e=!1){if(this.inMemoryOnly=e,e)this.state=Ar();else{let n=Ic();this.state=n.state,this.lastLoadedMtimeMs=n.mtimeMs,this.tryReconcilePRCounts()}}static async createWithGist(e){let{getOctokit:n}=await Promise.resolve().then(()=>(ko(),Q$)),o=n(e),r=new yo(o),i=nt(),s;if(Eo.existsSync(i)){let c=Ic(),l=await r.bootstrapWithMigration(c.state);if(s=l,l.migrated)try{let d=i+".pre-gist-migration";Eo.renameSync(i,d),E(Fe,`Renamed ${i} to ${d} after Gist migration`)}catch(d){b(Fe,`Failed to rename state.json after Gist migration: ${d}`)}}else s=await r.bootstrap();let a=new t(!0);return a.state=s.state,s.gistId&&(a.state.gistId=s.gistId),a.gistStore=r,a.gistDegraded=s.degraded??!1,a.inMemoryOnly=!1,s.degraded&&(a.staleness={source:"cache",reason:"initial Gist bootstrap fell back to local cache",lastSuccessfulRefresh:null,detectedAt:new Date().toISOString()}),a}tryReconcilePRCounts(){try{this.reconcilePRCounts()}catch(e){b(Fe,`PR count reconciliation failed (will retry on next load): ${I(e)}`),E(Fe,`Reconciliation error details: ${e instanceof Error?e.stack:String(e)}`)}}batch(e){if(this._batching){e();return}this._batching=!0,this._batchDirty=!1;try{e(),this._batchDirty&&this.save()}finally{this._batching=!1,this._batchDirty=!1}}autoSave(){if(this._batching){this._batchDirty=!0;return}this.save()}isSetupComplete(){return this.state.config.setupComplete===!0}markSetupComplete(){this.state.config.setupComplete=!0,this.state.config.setupCompletedAt=new Date().toISOString(),this.autoSave()}initializeWithDefaults(e){if(this.state.config.setupComplete){E(Fe,`Setup already complete, skipping initializeWithDefaults for "${e}"`);return}this.batch(()=>{this.updateConfig({githubUsername:e}),this.markSetupComplete(),E(Fe,`Initialized with defaults for user "${e}"`)})}save(e={}){if(this.state.lastRunAt=new Date().toISOString(),!this.inMemoryOnly){if(this.gistStore){try{Ct(tn(),JSON.stringify(this.state,null,2),384)}catch(n){b(Fe,`Failed to write Gist local cache: ${I(n)}`)}return}try{this.lastLoadedMtimeMs=$w(this.state,this.lastLoadedMtimeMs)}catch(n){if(n instanceof nn&&e.allowReloadAndLoseMutation){b(Fe,`Concurrent external write detected; reloading and discarding in-memory mutation. ${n.message}`),this.reloadIfChanged();return}throw n}}}async checkpoint(){return this.gistStore?(this.gistStore.setState(JSON.stringify(this.state,null,2)),this.gistStore.push()):!0}isGistMode(){return this.gistStore!==null}isGistDegraded(){return this.gistDegraded}isGuidelinesAvailable(){return this.gistStore!==null}getGuidelines(e){return Lw(this.gistStore,e)}setGuidelines(e,n){Nw(this.gistStore,e,n),this.autoSave()}deleteGuidelines(e){Mw(this.gistStore,e),this.autoSave()}listGuidelinesRepos(){return Hw(this.gistStore)}getState(){return this.state}reloadIfChanged(){if(this.inMemoryOnly||this.gistStore)return!1;let e=kw(this.lastLoadedMtimeMs);return e?(this.state=e.state,this.lastLoadedMtimeMs=e.mtimeMs,this.tryReconcilePRCounts(),!0):!1}async refreshFromGist(){if(!this.gistStore)return!1;let n=(await this.gistStore.refreshFromGist()).status==="refreshed";if(n){let o=this.gistStore.cachedFiles.get("state.json");if(!o)return b(Fe,"Gist refreshed but state.json missing from cache"),this.staleness={source:"cache",reason:"Gist refresh returned no state.json file",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;try{this.state=lt.parse(JSON.parse(o)),this.tryReconcilePRCounts()}catch(r){return b(Fe,`Failed to parse refreshed Gist state: ${I(r)}`),this.staleness={source:"cache",reason:`Gist refresh succeeded but payload was invalid: ${I(r)}`,lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1}this.lastSuccessfulRefreshAt=new Date().toISOString(),this.staleness=null}else this.gistStore.lastRefreshError&&(this.staleness={source:"cache",reason:I(this.gistStore.lastRefreshError),lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()});return n}getStateStaleness(){return this.staleness}setLastDigest(e){this.state.lastDigest=e,this.state.lastDigestAt=e.generatedAt,this.autoSave()}setMonthlyMergedCounts(e){this.state.monthlyMergedCounts=e,this.autoSave()}setMonthlyClosedCounts(e){this.state.monthlyClosedCounts=e,this.autoSave()}setMonthlyOpenedCounts(e){this.state.monthlyOpenedCounts=e,this.autoSave()}setLocalRepoCache(e){this.state.localRepoCache=e,this.autoSave()}getMergedPRs(){return this.state.mergedPRs??[]}addMergedPRs(e){if(e.length===0)return{added:0,dropped:0};let{valid:n,dropped:o}=ek(e,"merged");if(n.length===0)return{added:0,dropped:o};this.state.mergedPRs||(this.state.mergedPRs=[]);let r=new Set(this.state.mergedPRs.map(s=>s.url)),i=n.filter(s=>!r.has(s.url));return i.length===0?{added:0,dropped:o}:(this.state.mergedPRs.push(...i),this.state.mergedPRs.sort((s,a)=>a.mergedAt.localeCompare(s.mergedAt)),E(Fe,`Added ${i.length} merged PRs (total: ${this.state.mergedPRs.length})`),this.autoSave(),{added:i.length,dropped:o})}getMergedPRWatermark(){return this.state.mergedPRs?.[0]?.mergedAt||void 0}getClosedPRs(){return this.state.closedPRs??[]}addClosedPRs(e){if(e.length===0)return{added:0,dropped:0};let{valid:n,dropped:o}=ek(e,"closed");if(n.length===0)return{added:0,dropped:o};this.state.closedPRs||(this.state.closedPRs=[]);let r=new Set(this.state.closedPRs.map(s=>s.url)),i=n.filter(s=>!r.has(s.url));return i.length===0?{added:0,dropped:o}:(this.state.closedPRs.push(...i),this.state.closedPRs.sort((s,a)=>a.closedAt.localeCompare(s.closedAt)),E(Fe,`Added ${i.length} closed PRs (total: ${this.state.closedPRs.length})`),this.autoSave(),{added:i.length,dropped:o})}getClosedPRWatermark(){return this.state.closedPRs?.[0]?.closedAt||void 0}markPRCommentsFetched(e,n){let o=this.state.mergedPRs?.find(i=>i.url===e);if(o){o.commentsFetchedAt=n,this.autoSave();return}let r=this.state.closedPRs?.find(i=>i.url===e);r&&(r.commentsFetchedAt=n,this.autoSave())}markPRLearningsExtracted(e,n){let o=this.state.mergedPRs?.find(i=>i.url===e);if(o){o.learningsExtractedAt=n,this.autoSave();return}let r=this.state.closedPRs?.find(i=>i.url===e);r&&(r.learningsExtractedAt=n,this.autoSave())}updateConfig(e){this.state.config={...this.state.config,...e},this.autoSave()}addIssue(e){if(this.state.activeIssues.find(o=>o.url===e.url)){E(Fe,`Issue ${e.url} already tracked`);return}this.state.activeIssues.push(e),E(Fe,`Added issue: ${e.repo}#${e.number}`),this.autoSave()}addTrustedProject(e){this.state.config.trustedProjects.includes(e)||(this.state.config.trustedProjects.push(e),E(Fe,`Added trusted project: ${e}`),this.autoSave())}static matchesExclusion(e,n,o){let r=e.toLowerCase();return!!(n.some(i=>i.toLowerCase()===r)||o?.some(i=>i.toLowerCase()===r.split("/")[0]))}cleanupExcludedData(e,n){let o=s=>t.matchesExclusion(s,e,n),r=this.state.config.trustedProjects.length;this.state.config.trustedProjects=this.state.config.trustedProjects.filter(s=>!o(s));let i=r-this.state.config.trustedProjects.length;i>0&&(E(Fe,`Removed ${i} trusted project(s) for excluded repos/orgs`),this.autoSave())}getStarredRepos(){return this.state.config.starredRepos||[]}setStarredRepos(e){this.state.config.starredRepos=e,this.state.config.starredReposLastFetched=new Date().toISOString(),E(Fe,`Updated starred repos: ${e.length} repositories`),this.autoSave()}isStarredReposStale(){let e=this.state.config.starredReposLastFetched;if(!e)return!0;let n=1440*60*1e3,o=new Date(e);return new Date().getTime()-o.getTime()>n}shelvePR(e){return this.state.config.shelvedPRUrls||(this.state.config.shelvedPRUrls=[]),this.state.config.shelvedPRUrls.includes(e)?!1:(this.state.config.shelvedPRUrls.push(e),this.autoSave(),!0)}unshelvePR(e){if(!this.state.config.shelvedPRUrls)return!1;let n=this.state.config.shelvedPRUrls.indexOf(e);return n===-1?!1:(this.state.config.shelvedPRUrls.splice(n,1),this.autoSave(),!0)}isPRShelved(e){return this.state.config.shelvedPRUrls?.includes(e)??!1}dismissIssue(e,n){return this.state.config.dismissedIssues||(this.state.config.dismissedIssues={}),e in this.state.config.dismissedIssues?!1:(this.state.config.dismissedIssues[e]=n,this.autoSave(),!0)}undismissIssue(e){return!this.state.config.dismissedIssues||!(e in this.state.config.dismissedIssues)?!1:(delete this.state.config.dismissedIssues[e],this.autoSave(),!0)}getIssueDismissedAt(e){return this.state.config.dismissedIssues?.[e]}setStatusOverride(e,n,o){this.state.config.statusOverrides||(this.state.config.statusOverrides={}),this.state.config.statusOverrides[e]={status:n,setAt:new Date().toISOString(),lastActivityAt:o},this.autoSave()}clearStatusOverride(e){return!this.state.config.statusOverrides||!(e in this.state.config.statusOverrides)?!1:(delete this.state.config.statusOverrides[e],this.autoSave(),!0)}getStatusOverride(e,n){let o=this.state.config.statusOverrides?.[e];if(o){if(n&&n>o.lastActivityAt){this.clearStatusOverride(e);return}return o}}getRepoScore(e){return xw(this.state,e)}updateRepoScore(e,n){vo(this.state,e,n),this.autoSave()}incrementMergedCount(e){Pw(this.state,e),this.autoSave()}incrementClosedCount(e){Cw(this.state,e),this.autoSave()}markRepoHostile(e){Iw(this.state,e),this.autoSave()}getReposWithMergedPRs(){return Ow(this.state)}getReposWithOpenPRs(){return Aw(this.state)}getHighScoringRepos(e){return Dw(this.state,e)}getLowScoringRepos(e){return Uw(this.state,e)}getStats(){return jw(this.state)}reconcilePRCounts(){let e=this.state.mergedPRs??[],n=this.state.closedPRs??[];if(e.length===0&&n.length===0)return;Fw(this.state,e,n)&&this.autoSave()}},mn=null,pn=null});var rk={};ie(rk,{byDateDescending:()=>mh,daysBetween:()=>gn,formatRelativeTime:()=>is});function gn(t,e=new Date){return Math.max(0,Math.floor((e.getTime()-t.getTime())/(1e3*60*60*24)))}function is(t){let e=new Date(t),n=Date.now()-e.getTime();if(n<0)return"just now";let o=Math.floor(n/6e4),r=Math.floor(n/36e5),i=Math.floor(n/864e5);return o<60?`${o}m ago`:r<24?`${r}h ago`:i<30?`${i}d ago`:e.toLocaleDateString()}function mh(t){return(e,n)=>{let o=new Date(t(e)||0).getTime();return new Date(t(n)||0).getTime()-o}}var xo=v(()=>{"use strict"});async function Zc(t,e,n){let o=0,r=!1,i=async()=>{for(;o<t.length&&!r;){let a=t[o++];try{await e(a)}catch(c){throw r=!0,c}}},s=Math.min(n,t.length);await Promise.all(Array.from({length:s},()=>i()))}var Po,Vc=v(()=>{"use strict";Po=5});function iA(t,e){if(!t||!e)return!0;let n=t.toLowerCase();return nA.has(n)?!0:n===e.toLowerCase()}function Co(t){return t?new Date(t).getTime():Number.NaN}function sA(t,e){let n=Co(t),o=Co(e);return!Number.isFinite(n)||!Number.isFinite(o)?!1:n-o>=oA}function nk(t){let{latestCommitDate:e,latestCommitAuthor:n,contributorUsername:o}=t;if(e)return iA(n,o)?e:void 0}function ok(t,e,n){if(!t||!e||!sA(t,e))return!1;if(n){let o=Co(t),r=Co(n);if(!Number.isFinite(o)||!Number.isFinite(r)||o<r)return!1}return!0}function ik(t,e){if(!t||!e)return!1;let n=Co(t),o=Co(e);return!Number.isFinite(n)||!Number.isFinite(o)?!1:n>=o}function aA(t){let{ciStatus:e,hasMergeConflict:n,hasUnrespondedComment:o,hasIncompleteChecklist:r,reviewDecision:i,lastMaintainerCommentDate:s,latestChangesRequestedDate:a,hasActionableCIFailure:c=!0}=t,l=nk(t),d=[];return o&&!ok(l,s,a)&&d.push("needs_response"),i==="changes_requested"&&a&&!ik(l,a)&&d.push("needs_changes"),e==="failing"&&c&&d.push("failing_ci"),n&&d.push("merge_conflict"),r&&d.push("incomplete_checklist"),d.length>0?d:void 0}function gh(t){let e=cA(t),n=aA(t);return n?{...e,actionReasons:n}:e}function cA(t){let{ciStatus:e,hasMergeConflict:n,hasUnrespondedComment:o,hasIncompleteChecklist:r,reviewDecision:i,daysSinceActivity:s,dormantThreshold:a,approachingThreshold:c,lastMaintainerCommentDate:l,latestChangesRequestedDate:d,hasActionableCIFailure:p=!0}=t,m="active";s>=a?m="dormant":s>=c&&(m="approaching_dormant");let g=nk(t);return o?ok(g,l,d)?e==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_response",stalenessTier:m}:i==="changes_requested"&&d?ik(g,d)?e==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_changes",stalenessTier:m}:e==="failing"?p?s>=5?{status:"waiting_on_maintainer",waitReason:"stale_ci_failure",stalenessTier:m}:{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"ci_blocked",stalenessTier:m}:n?{status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:m}:r?{status:"needs_addressing",actionReason:"incomplete_checklist",stalenessTier:m}:i==="approved"&&(e==="passing"||e==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"pending_review",stalenessTier:m}}var nA,oA,fh=v(()=>{"use strict";nA=new Set(["autofix-ci[bot]","prettier-ci[bot]","pre-commit-ci[bot]"]),oA=120*1e3});async function _t(t,e=100,n=10){let o=[];for(let r=1;r<=n;r++){let{data:i}=await t(r);if(o.push(...i),i.length<e)break}return o}var ss=v(()=>{"use strict"});function Io(){return hh||(hh=new cs),hh}async function Bc(t,e,n){let o=t.getInflight(e);if(o)return E(fr,`Dedup hit for ${e}`),await o;let i=(async()=>{let a={},c=t.get(e);c&&(a["if-none-match"]=c.etag);try{let l=await n(a),d=l.headers?.etag;return d&&t.set(e,d,l.data),l.data}catch(l){if(dA(l)){let d=t.get(e);if(d)return E(fr,`304 cache hit for ${e}`),d.body}throw l}})(),s=t.setInflight(e,i);try{return await i}finally{s()}}function dA(t){return Ke(t)===304}var Ve,as,sk,fr,uA,lA,cs,hh,Wc=v(()=>{"use strict";Ve=K(require("node:fs"),1),as=K(require("node:path"),1),sk=K(require("node:crypto"),1);rn();we();he();fr="http-cache",uA=1440*60*1e3,lA=2e3,cs=class{cacheDir;maxEntries;inflightRequests=new Map;constructor(e,n=lA){this.cacheDir=e??$c(),this.maxEntries=n}keyFor(e){return sk.createHash("sha256").update(e).digest("hex")}pathFor(e){return as.join(this.cacheDir,`${this.keyFor(e)}.json`)}getIfFresh(e,n){let o=this.get(e);if(!o)return null;let r=Date.now()-new Date(o.cachedAt).getTime();return!Number.isFinite(r)||r<0||r>n?null:o.body}get(e){let n=this.pathFor(e);try{let o=Ve.readFileSync(n,"utf8"),r=JSON.parse(o);return r.url!==e?(E(fr,`Cache collision detected for ${e}, ignoring`),null):r}catch(o){if(o&&typeof o=="object"&&o.code!=="ENOENT"){let r=o instanceof Error?o.message:"unknown error";E(fr,`Cache read failed for ${e} (treating as miss): ${r}`)}return null}}set(e,n,o){let r={etag:n,url:e,body:o,cachedAt:new Date().toISOString()};try{Ve.writeFileSync(this.pathFor(e),JSON.stringify(r),{encoding:"utf8",mode:384}),E(fr,`Cached response for ${e}`),this.evictIfExceeds(this.maxEntries)}catch(i){E(fr,`Failed to write cache for ${e}`,i)}}evictIfExceeds(e){if(!(e<=0))try{let n=Ve.readdirSync(this.cacheDir).filter(s=>s.endsWith(".json"));if(n.length<=e)return;let o=n.map(s=>{let a=as.join(this.cacheDir,s);try{return{fullPath:a,mtimeMs:Ve.statSync(a).mtimeMs}}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.mtimeMs-a.mtimeMs),r=o.length-e,i=0;for(let s=0;s<r;s++)try{Ve.unlinkSync(o[s].fullPath),i++}catch{}i>0&&E(fr,`Capped cache at ${e} entries: evicted ${i} oldest`)}catch{}}hasInflight(e){return this.inflightRequests.has(e)}getInflight(e){return this.inflightRequests.get(e)}setInflight(e,n){return this.inflightRequests.set(e,n),()=>{this.inflightRequests.delete(e)}}evictStale(e=uA){let n=0;try{let o=Ve.readdirSync(this.cacheDir),r=Date.now();for(let i of o){if(!i.endsWith(".json"))continue;let s=as.join(this.cacheDir,i);try{let a=Ve.readFileSync(s,"utf8"),c=JSON.parse(a);r-new Date(c.cachedAt).getTime()>e&&(Ve.unlinkSync(s),n++)}catch{try{Ve.unlinkSync(s),n++}catch{}}}}catch{}return n>0&&E(fr,`Evicted ${n} stale cache entries`),n}clear(){try{let e=Ve.readdirSync(this.cacheDir);for(let n of e)n.endsWith(".json")&&Ve.unlinkSync(as.join(this.cacheDir,n));E(fr,"Cache cleared")}catch{}}size(){try{return Ve.readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).length}catch{return 0}}},hh=null});function qc(){return{status:"unknown",failingCheckNames:[],failingCheckConclusions:new Map}}function Jc(t,e,n){if(n==="cancelled"||n==="timed_out")return"infrastructure";if(n==="action_required")return"auth_gate";let o=t.toLowerCase();if(ck.some(r=>r.test(o)))return"auth_gate";if(ak.some(r=>r.test(o)))return"fork_limitation";if(uk.some(r=>r.test(o)))return"infrastructure";if(e){let r=e.toLowerCase();if(ck.some(i=>i.test(r)))return"auth_gate";if(ak.some(i=>i.test(r)))return"fork_limitation";if(uk.some(i=>i.test(r)))return"infrastructure"}return"actionable"}function us(t,e){return t.map(n=>{let o=e?.get(n);return{name:n,category:Jc(n,void 0,o),conclusion:o}})}function pA(t){let e=!1,n=!1,o=!1,r=[],i=new Map;for(let s of t)s.conclusion==="failure"||s.conclusion==="cancelled"||s.conclusion==="timed_out"||s.conclusion==="action_required"?(e=!0,r.push(s.name),i.set(s.name,s.conclusion)):s.status==="in_progress"||s.status==="queued"?n=!0:s.conclusion==="success"&&(o=!0);return{hasFailingChecks:e,hasPendingChecks:n,hasSuccessfulChecks:o,failingCheckNames:r,failingCheckConclusions:i}}function mA(t){let e=t.statuses.filter(c=>{let l=(c.description||"").toLowerCase();return!(c.state==="failure"&&(l.includes("authorization required")||l.includes("authorize")))}),n=e.some(c=>c.state==="failure"||c.state==="error"),o=e.some(c=>c.state==="pending"),r=e.some(c=>c.state==="success"),i;n?i="failure":o?i="pending":r||e.length===0?i="success":i=t.state;let s=t.statuses.length>0,a=[];for(let c of e)(c.state==="failure"||c.state==="error")&&a.push(c.context);return{effectiveCombinedState:i,hasStatuses:s,failingStatusNames:a}}function gA(t,e,n){let{hasFailingChecks:o,hasPendingChecks:r,hasSuccessfulChecks:i,failingCheckNames:s,failingCheckConclusions:a}=t,{effectiveCombinedState:c,hasStatuses:l,failingStatusNames:d}=e,p=[...s,...d];return o||c==="failure"||c==="error"?{status:"failing",failingCheckNames:p,failingCheckConclusions:a}:r||c==="pending"?{status:"pending",failingCheckNames:[],failingCheckConclusions:new Map}:i||c==="success"?{status:"passing",failingCheckNames:[],failingCheckConclusions:new Map}:qc()}async function vh(t,e,n,o){if(!o)return qc();try{let[r,i]=await Promise.all([t.repos.getCombinedStatusForRef({owner:e,repo:n,ref:o}),t.checks.listForRef({owner:e,repo:n,ref:o}).catch(m=>{let g=Ke(m);if(g===429)throw m;if(g===403){let h=I(m).toLowerCase();if(h.includes("rate limit")||h.includes("abuse detection"))throw m}return g===404?E("pr-monitor",`Check runs 404 for ${e}/${n}@${o.slice(0,7)} (no checks configured)`):b("pr-monitor",`Non-404 error fetching check runs for ${e}/${n}@${o.slice(0,7)}: ${g??m}`),null})]),s=r.data,a=i?.data?.check_runs||[],c=new Map;for(let m of a){let g=c.get(m.name);(!g||new Date(m.started_at??0)>new Date(g.started_at??0))&&c.set(m.name,m)}let l=[...c.values()],d=pA(l),p=mA(s);return gA(d,p,l.length)}catch(r){let i=Ke(r);if(i===401||i===403||i===429)throw r;return i===404?E("pr-monitor",`CI check 404 for ${e}/${n} (no CI configured)`):b("pr-monitor",`Failed to check CI for ${e}/${n}@${o.slice(0,7)}: ${I(r)}`),qc()}}var ak,ck,uk,bh=v(()=>{"use strict";he();we();ak=[/vercel/i,/netlify/i,/\bpreview\s*deploy/i,/\bdeploy\s*preview/i,/storybook/i,/chromatic/i,/percy/i,/cloudflare pages/i,/\binternal\b(?!\s+(?:api|test|integration|smoke|unit|e2e|regression|functional))/i],ck=[/authoriz/i,/approval/i,/\bcla\b/i,/license\/cla/i],uk=[/\binstall\s*(os\s*)?dep(endenc|s\b)/i,/\bsetup\s+fail(ed|ure)?\b/i,/\bservice\s*unavailable/i,/\binfrastructure/i,/\bblacksmith\b/i,/\breadthedocs\b/i]});function hr(t){return t.includes("[bot]")||fA.has(t.toLowerCase())}function Oo(t){if(!t||t.length>100||t.includes("?"))return!1;let e=t.toLowerCase();return["thanks","thank you","lgtm","looks good","will review","we'll review","we'll get to this","noted","got it","will look","will check"].some(o=>e.includes(o))}var fA,ls=v(()=>{"use strict";fA=new Set(["allcontributors","changeset-bot","claassistant","codecov-commenter","greenkeeper","imgbot","netlify","renovate","snyk-bot","sonarcloud","stale","vercel"])});function lk(t){if(t.length===0)return"review_required";let e=new Map;for(let o of t){let r=o.user?.login,i=o.state;r&&i&&e.set(r,i)}let n=Array.from(e.values());return n.includes("CHANGES_REQUESTED")?"changes_requested":n.includes("APPROVED")?"approved":"review_required"}function dk(t){let e;for(let n of t)n.state==="CHANGES_REQUESTED"&&n.submitted_at&&(!e||n.submitted_at>e)&&(e=n.submitted_at);return e}function hA(t,e){let n=e.filter(r=>r.pull_request_review_id===t);if(n.length===0)return!1;let o=new Map;for(let r of e)r.user?.login&&o.set(r.id,r.user.login.toLowerCase());return n.every(r=>{if(!r.in_reply_to_id)return!1;let i=o.get(r.in_reply_to_id),s=r.user?.login?.toLowerCase();return!(i==null||s==null||i!==s||!r.body||r.body.includes("?"))})}function vA(t,e){return e.find(n=>n.pull_request_review_id===t&&n.body?.trim())?.body?.trim()}function bA(t,e){return e.some(n=>n.pull_request_review_id===t)}function pk(t,e,n,o){let r=[],i=o.toLowerCase();for(let d of t){let p=d.user?.login||"unknown";r.push({author:p,body:d.body||"",createdAt:d.created_at,isUser:p.toLowerCase()===i})}for(let d of e){if(!d.submitted_at)continue;let p=(d.body||"").trim();if(!p&&d.state!=="COMMENTED"&&d.state!=="CHANGES_REQUESTED")continue;let m=d.user?.login||"unknown";if(!p&&d.state==="COMMENTED"&&d.id!=null&&hA(d.id,n))continue;let g=p||(d.id!=null?vA(d.id,n):void 0)||(d.state==="CHANGES_REQUESTED"?"(requested changes via inline review comments)":"(posted inline review comments)");r.push({author:m,body:g,createdAt:d.submitted_at,isUser:m.toLowerCase()===i,reviewId:d.id})}r.sort((d,p)=>new Date(d.createdAt).getTime()-new Date(p.createdAt).getTime());let s=null;for(let d of r)d.isUser&&(s=new Date(d.createdAt));let a,c;for(let d of r){if(d.isUser||d.author==="unknown"||hr(d.author))continue;let p=new Date(d.createdAt);(!s||p>s)&&(a={author:d.author,body:d.body.slice(0,200)+(d.body.length>200?"...":""),createdAt:d.createdAt},c=d.reviewId)}let l=c!=null&&bA(c,n);return a&&Oo(a.body)&&!l&&(a=void 0),{hasUnrespondedComment:!!a,lastMaintainerComment:a}}var mk=v(()=>{"use strict";ls()});function gk(t){return yA.test(t.toLowerCase())}function fk(t){if(!t)return{hasIncompleteChecklist:!1};let e=/- \[x\]/gi,n=/^.*- \[ \].*$/gm,o=t.match(e)||[],r=t.match(n)||[],i=o.length;if(i+r.length===0)return{hasIncompleteChecklist:!1};let a=r.filter(l=>!gk(l)),c=i+a.length;return{hasIncompleteChecklist:a.length>0,checklistStats:{checked:i,total:c}}}var yA,yh=v(()=>{"use strict";yA=/\(if\s|\bif applicable\b|\bif needed\b|\bif relevant\b|\bonly if\b|\bwhen applicable\b|\(optional\)|- \[ \]\s*optional\b|\bn\/a\b|\bnot applicable\b|\bif required\b|\bif necessary\b/});function hk(t,e){let n=[];if(e==="changes_requested"&&n.push("changes_requested"),!t)return n;let o=t.toLowerCase();["screenshot","demo","recording","screen recording","before/after","before and after","gif","video","screencast","show me","can you show"].some(l=>o.includes(l))&&n.push("demo_requested"),["add test","test coverage","unit test","missing test","add a test","write test","needs test","need test"].some(l=>o.includes(l))&&n.push("tests_requested"),["documentation","readme","jsdoc","docstring","add docs","update docs","document this"].some(l=>o.includes(l))&&n.push("docs_requested");let a=["merge conflict","out of date","behind main","behind master"];return(/\brebase\b/i.test(t)||a.some(l=>o.includes(l)))&&n.push("rebase_requested"),n}var vk=v(()=>{"use strict"});function SA(t){let e=bk[t]?.label;return e?e.replace(/[[\]]/g,"").toLowerCase():t}function ds(t){if(t.status==="needs_addressing"&&t.actionReason){let e=bk[t.actionReason];if(e){let n=e.description(t);if(t.actionReasons&&t.actionReasons.length>1){let o=t.actionReasons.filter(r=>r!==t.actionReason).map(SA);o.length>0&&(n+=` (also: ${o.join(", ")})`)}return{displayLabel:e.label,displayDescription:n}}}if(t.status==="waiting_on_maintainer"&&t.waitReason){let e=_A[t.waitReason];if(e)return{displayLabel:e.label,displayDescription:e.description(t)}}return b("display-utils",`PR ${t.url} has status "${t.status}" but no matching reason (actionReason=${t.actionReason}, waitReason=${t.waitReason})`),t.status==="needs_addressing"?{displayLabel:"[Needs Addressing]",displayDescription:"Action required"}:{displayLabel:"[Waiting on Maintainer]",displayDescription:"Awaiting maintainer action"}}var bk,_A,_h=v(()=>{"use strict";we();bk={needs_response:{label:"[Needs Response]",description:t=>t.lastMaintainerComment?`@${t.lastMaintainerComment.author} commented`:"Maintainer awaiting response"},needs_changes:{label:"[Needs Changes]",description:()=>"Review requested changes \u2014 push commits to address"},failing_ci:{label:"[CI Failing]",description:t=>{let e=t.classifiedChecks||[],n=e.filter(i=>i.category==="actionable");if(n.length>0)return`${n.length} check${n.length===1?"":"s"} failed: ${n.map(i=>i.name).join(", ")}`;let o=e.filter(i=>i.category==="infrastructure");if(o.length>0)return`${o.length} check${o.length===1?"":"s"} cancelled/timed out (infrastructure)`;let r=t.failingCheckNames||[];return r.length>0?`${r.length} check${r.length===1?"":"s"} failed`:"One or more CI checks are failing"}},merge_conflict:{label:"[Merge Conflict]",description:()=>"PR has merge conflicts with the base branch"},incomplete_checklist:{label:"[Incomplete Checklist]",description:t=>t.checklistStats?`${t.checklistStats.checked}/${t.checklistStats.total} items checked`:"PR body has unchecked required checkboxes"},ci_not_running:{label:"[CI Not Running]",description:()=>"No CI checks have been triggered"},needs_rebase:{label:"[Needs Rebase]",description:()=>"PR branch is significantly behind upstream"},missing_required_files:{label:"[Missing Files]",description:t=>t.missingRequiredFiles?`Missing: ${t.missingRequiredFiles.join(", ")}`:"Required files are missing"}},_A={pending_review:{label:"[Waiting on Maintainer]",description:()=>"Awaiting review"},pending_merge:{label:"[Waiting on Maintainer]",description:()=>"Approved and CI passes \u2014 waiting for merge"},changes_addressed:{label:"[Waiting on Maintainer]",description:t=>t.hasUnrespondedComment&&t.lastMaintainerComment?`Changes addressed \u2014 waiting for @${t.lastMaintainerComment.author} to re-review`:"Changes addressed \u2014 awaiting re-review"},ci_blocked:{label:"[CI Blocked]",description:t=>{let e=t.classifiedChecks||[];return e.length>0&&e.every(n=>n.category!=="actionable")?`All failing checks are non-actionable (${[...new Set(e.map(o=>o.category))].join(", ")})`:"CI checks are failing but no action is needed from you"}},stale_ci_failure:{label:"[Stale CI Failure]",description:t=>`CI failing for ${t.daysSinceActivity}+ days \u2014 likely pre-existing or non-actionable`}}});function fn(){return{repos:new Map,monthlyCounts:{},monthlyOpenedCounts:{},dailyActivityCounts:{}}}function $A(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.reposEntries)&&typeof e.monthlyCounts=="object"&&e.monthlyCounts!==null&&typeof e.monthlyOpenedCounts=="object"&&e.monthlyOpenedCounts!==null&&typeof e.dailyActivityCounts=="object"&&e.dailyActivityCounts!==null}async function yk(t,e,n,o,r,i){if(!e)return fn();let s=Io(),a=i?`:stars${i.minStars}`:"",c=`pr-counts:v3:${o}:${e}${a}`,l=s.getIfFresh(c,wA);if(l&&$A(l))return E(Be,`Using cached ${o} PR counts for @${e}`),{repos:new Map(l.reposEntries),monthlyCounts:l.monthlyCounts,monthlyOpenedCounts:l.monthlyOpenedCounts,dailyActivityCounts:l.dailyActivityCounts};E(Be,`Fetching ${o} PR counts for @${e}...`);let d=new Map,p={},m={},g={},h=1,_=0,$;for(;;){let{data:S}=await t.search.issuesAndPullRequests({q:`is:pr ${n} author:${e} -user:${e}`,sort:"updated",order:"desc",per_page:100,page:h});$=S.total_count;for(let T of S.items){let j=fo(T.html_url);if(!j){b(Be,`Skipping ${o} PR with unparseable URL: ${T.html_url}`);continue}let{owner:F}=j,U=`${F}/${j.repo}`;if(er(F,e)||i&&Qt(i.knownStarCounts.get(U),i.minStars))continue;let J=r(d,U,T);if(J){let Y=J.slice(0,7);p[Y]=(p[Y]||0)+1;let ue=J.slice(0,10);ue.length===10&&(g[ue]=(g[ue]||0)+1)}if(T.created_at){let Y=T.created_at.slice(0,7);m[Y]=(m[Y]||0)+1;let ue=T.created_at.slice(0,10);ue.length===10&&(g[ue]=(g[ue]||0)+1)}}if(_+=S.items.length,_>=S.total_count||_>=1e3||S.items.length===0||h>=Ao)break;h++}return _<$&&h>=Ao&&b(Be,`Pagination capped at ${Ao} pages: fetched ${_} of ${$} ${o} PRs. Stats may be incomplete for prolific contributors.`),E(Be,`Found ${_} ${o} PRs across ${d.size} repos`),s.set(c,"",{reposEntries:Array.from(d.entries()),monthlyCounts:p,monthlyOpenedCounts:m,dailyActivityCounts:g}),{repos:d,monthlyCounts:p,monthlyOpenedCounts:m,dailyActivityCounts:g}}function _k(t,e,n){return yk(t,e,"is:merged","merged",(o,r,i)=>{i.pull_request?.merged_at||b(Be,`merged_at missing for merged PR ${i.html_url}${i.closed_at?", falling back to closed_at":", no date available"}`);let s=i.pull_request?.merged_at||i.closed_at||"",a=o.get(r);return a?(a.count+=1,s&&s>a.lastMergedAt&&(a.lastMergedAt=s)):o.set(r,{count:1,lastMergedAt:s}),s},n)}function Sk(t,e,n){return yk(t,e,"is:closed is:unmerged","closed",(o,r,i)=>(o.set(r,(o.get(r)||0)+1),i.closed_at||""),n)}async function wk(t,e,n,o,r,i){if(!e.githubUsername)return b(Be,`Skipping recently ${o} PRs fetch: no githubUsername configured. Run /setup-oss to configure.`),[];let s=new Date;s.setDate(s.getDate()-r);let a=s.toISOString().split("T")[0];E(Be,`Fetching recently ${o} PRs for @${e.githubUsername} (since ${a})...`);let{data:c}=await t.search.issuesAndPullRequests({q:n.replace("{username}",e.githubUsername).replace("{since}",a),sort:"updated",order:"desc",per_page:100}),l=[];for(let d of c.items){let p=xe(d.html_url);if(!p){b(Be,`Could not parse GitHub URL from API response: ${d.html_url}`);continue}if(er(p.owner,e.githubUsername))continue;let m=`${p.owner}/${p.repo}`;l.push(i(d,{owner:p.owner,repo:m,number:p.number}))}return E(Be,`Found ${l.length} recently ${o} PRs`),l}async function $k(t,e,n=7){return wk(t,e,"is:pr is:closed is:unmerged is:public author:{username} closed:>={since}","closed",n,(o,{repo:r,number:i})=>({url:o.html_url,repo:r,number:i,title:o.title,closedAt:o.closed_at||""}))}async function kk(t,e,n=7){return wk(t,e,"is:pr is:merged is:public author:{username} merged:>={since}","merged",n,(o,{repo:r,number:i})=>{let s=o.pull_request?.merged_at;return s||b(Be,`merged_at missing for merged PR ${o.html_url}${o.closed_at?", falling back to closed_at":", no date available"}`),{url:o.html_url,repo:r,number:i,title:o.title,mergedAt:s||o.closed_at||""}})}async function Rk(t,e,n,o){if(!e.githubUsername)return b(Be,`Skipping ${n.kind} PRs fetch: no githubUsername configured.`),[];let r=n.buildQuery(e.githubUsername,o);E(Be,`Fetching ${n.kind} PRs${o?` since ${o}`:" (all time)"}...`);let i=[],s=1,a=0,c;for(;;){let{data:l}=await t.search.issuesAndPullRequests({q:r,sort:"updated",order:"desc",per_page:100,page:s});c=l.total_count;for(let d of l.items){let p=xe(d.html_url);if(!p){b(Be,`Skipping ${n.kind} PR with unparseable URL: ${d.html_url}`);continue}if(er(p.owner,e.githubUsername))continue;let m=n.extractDate(d);if(!m){b(Be,`Skipping ${n.kind} PR with no ${n.dateNoun} date: ${d.html_url}`);continue}i.push(n.buildRecord(d,m))}if(a+=l.items.length,a>=c||a>=1e3||l.items.length===0||s>=Ao)break;s++}return a<c&&s>=Ao&&b(Be,`Pagination capped at ${Ao} pages: fetched ${a} of ${c} ${n.kind} PRs. Oldest PRs may be missing.`),E(Be,`Fetched ${i.length} ${n.kind} PRs${o?" (incremental)":" (initial)"}`),i}async function Ek(t,e,n){return Rk(t,e,{kind:"merged",dateNoun:"merge",buildQuery:(o,r)=>`is:pr is:merged author:${o} -user:${o}${r?` merged:>${r}`:""}`,extractDate:o=>o.pull_request?.merged_at||o.closed_at||"",buildRecord:(o,r)=>({url:o.html_url,title:o.title,mergedAt:r})},n)}async function Tk(t,e,n){return Rk(t,e,{kind:"closed",dateNoun:"close",buildQuery:(o,r)=>`is:pr is:closed is:unmerged author:${o} -user:${o}${r?` closed:>${r}`:""}`,extractDate:o=>o.closed_at||"",buildRecord:(o,r)=>({url:o.html_url,title:o.title,closedAt:r})},n)}var Be,wA,Ao,Kc=v(()=>{"use strict";It();Dr();we();Wc();Be="github-stats",wA=1440*60*1e3,Ao=3});function ps(t){return RA.has(t.toLowerCase())}var kA,RA,Sh=v(()=>{"use strict";kA=["example-user","your-username","your-github-username","octocat","monalisa"],RA=new Set(kA)});function EA(t,e){return t===!1||e==="dirty"}var Lt,TA,jr,xk=v(()=>{"use strict";ko();To();xo();It();Vc();fh();he();ss();we();Wc();bh();mk();yh();vk();_h();Kc();Sh();_h();bh();yh();fh();Lt="pr-monitor",TA=5,jr=class{octokit;stateManager;constructor(e){this.octokit=Ie(e),this.stateManager=L()}async fetchUserOpenPRs(){let e=this.stateManager.getState().config;if(!e.githubUsername)throw new ot("No GitHub username configured. Run setup first.");let n=[],o=e.githubUsername,r=!1;if(ps(o))try{let{data:$}=await this.octokit.users.getAuthenticated(),S=$.login?.trim();if(!S||ps(S)){let T=`Placeholder username "${o}" detected but authenticated viewer returned an unusable login (${JSON.stringify($.login)}); skipping auto-repair.`;n.push(T),b(Lt,T)}else{this.stateManager.updateConfig({githubUsername:S}),o=S,r=!0;let T=`Configured GitHub username "${e.githubUsername}" looks like a placeholder. Auto-repaired to "${S}" using the authenticated viewer.`;n.push(T),b(Lt,T)}}catch($){if(dt($))throw $;let S=`Could not auto-repair placeholder username "${o}": ${I($)}`;n.push(S),b(Lt,S)}E("pr-monitor",`Fetching open PRs for @${o}...`);let i=[],s=1,a=100,c=await this.octokit.search.issuesAndPullRequests({q:`is:pr is:open is:public author:${o}`,sort:"updated",order:"desc",per_page:a,page:1});i.push(...c.data.items);let l=c.data.total_count;E(Lt,`Found ${l} open PRs`);let d=1e3,p=Math.ceil(d/a),m=Math.min(Math.ceil(l/a),p);if(l===0&&!r)try{let{data:$}=await this.octokit.users.getAuthenticated();if($.login.toLowerCase()!==o.toLowerCase()){let S=`Configured GitHub username @${o} does not match authenticated user @${$.login}. Did you mean to run \`oss-autopilot config username ${$.login}\`? Zero PRs returned.`;n.push(S),b(Lt,S)}}catch($){if(dt($))throw $;E(Lt,`Could not cross-check viewer login: ${I($)}`)}for(l>d&&(n.push(`GitHub Search API returned ${l} PRs for @${o}, but results are capped at ${d}. Showing the ${d} most recently updated PRs.`),b(Lt,n[n.length-1]));s<m;){s++;let $=await this.octokit.search.issuesAndPullRequests({q:`is:pr is:open is:public author:${o}`,sort:"updated",order:"desc",per_page:a,page:s});i.push(...$.data.items)}let g=[],h=[],_=i.filter($=>{if(!$.pull_request)return!1;let S=fo($.html_url);return S?!er(S.owner,o):(b("pr-monitor",`Skipping PR with unparseable URL: ${$.html_url}`),!1)});return E("pr-monitor",`Filtered to ${_.length} PRs after excluding own repos`),await Tc("pr-monitor",`Fetch details for ${_.length} PRs`,async()=>{await Zc(_,async $=>{try{E("pr-monitor",`Fetching details for ${$.html_url}`);let S=await this.fetchPRDetails($.html_url);S&&g.push(S)}catch(S){let T=I(S);b("pr-monitor",`Error fetching ${$.html_url}: ${T}`),h.push({prUrl:$.html_url,error:T})}},TA)}),g.sort(($,S)=>$.status===S.status?0:$.status==="needs_addressing"?-1:1),n.length>0?{prs:g,failures:h,warnings:n}:{prs:g,failures:h}}async fetchPRDetails(e){let n=xe(e);if(!n||n.type!=="pull")throw new ne(`Invalid PR URL format: ${e}`);let{owner:o,repo:r,number:i}=n,s=this.stateManager.getState().config,[a,c,l,d]=await Promise.all([this.octokit.pulls.get({owner:o,repo:r,pull_number:i}),_t(pe=>this.octokit.issues.listComments({owner:o,repo:r,issue_number:i,per_page:100,page:pe})),this.octokit.pulls.listReviews({owner:o,repo:r,pull_number:i}),_t(pe=>this.octokit.pulls.listReviewComments({owner:o,repo:r,pull_number:i,per_page:100,page:pe})).catch(pe=>{let je=Ke(pe);if(je===429)throw pe;if(je===403){let Ye=I(pe).toLowerCase();if(Ye.includes("rate limit")||Ye.includes("abuse detection"))throw pe;return b("pr-monitor",`403 fetching review comments for ${o}/${r}#${i}: ${Ye}`),[]}return je===404?E("pr-monitor",`Review comments 404 for ${o}/${r}#${i} (likely no inline comments)`):b("pr-monitor",`Failed to fetch review comments for ${o}/${r}#${i} (status ${je??"unknown"}): self-reply detection will be skipped`),[]})]),p=a.data,m=l.data,g=lk(m),h=EA(p.mergeable,p.mergeable_state),{hasUnrespondedComment:_,lastMaintainerComment:$}=pk(c,m,d,s.githubUsername),S=vh(this.octokit,o,r,p.head.sha),j=_||g==="changes_requested"?this.octokit.repos.getCommit({owner:o,repo:r,ref:p.head.sha}).then(pe=>({date:pe.data.commit.author?.date,author:pe.data.author?.login})).catch(pe=>{let je=Ke(pe);if(je===429)throw pe;if(je===403){let Ye=I(pe).toLowerCase();if(Ye.includes("rate limit")||Ye.includes("abuse detection"))throw pe;b("pr-monitor",`403 fetching commit date for ${o}/${r}@${p.head.sha.slice(0,7)}: ${I(pe)}`);return}b("pr-monitor",`Failed to fetch commit date for ${o}/${r}@${p.head.sha.slice(0,7)}: ${I(pe)}`)}):Promise.resolve(void 0),[{status:F,failingCheckNames:U,failingCheckConclusions:J},Y]=await Promise.all([S,j]),ue=Y?.date,M=Y?.author,{hasIncompleteChecklist:z,checklistStats:W}=fk(p.body||""),de=hk($?.body,g),q=gn(new Date(p.updated_at),new Date),Ae=dk(m),Ue=us(U,J),ce=F==="failing"&&Ue.some(pe=>pe.category==="actionable"),{status:ht,actionReason:Et,waitReason:ur,stalenessTier:re,actionReasons:fe}=gh({ciStatus:F,hasMergeConflict:h,hasUnrespondedComment:_,hasIncompleteChecklist:z,reviewDecision:g,daysSinceActivity:q,dormantThreshold:s.dormantThresholdDays,approachingThreshold:s.approachingDormantDays,latestCommitDate:ue,latestCommitAuthor:M,contributorUsername:s.githubUsername,lastMaintainerCommentDate:$?.createdAt,latestChangesRequestedDate:Ae,hasActionableCIFailure:ce});return this.buildFetchedPR({id:p.id,url:e,repo:`${o}/${r}`,number:i,title:p.title,status:ht,actionReason:Et,waitReason:ur,stalenessTier:re,actionReasons:fe,createdAt:p.created_at,updatedAt:p.updated_at,daysSinceActivity:q,ciStatus:F,failingCheckNames:U,classifiedChecks:Ue,hasMergeConflict:h,reviewDecision:g,hasUnrespondedComment:_,lastMaintainerComment:$,latestCommitDate:ue,hasIncompleteChecklist:z,checklistStats:W,maintainerActionHints:de})}buildFetchedPR(e){let n={...e,displayLabel:"",displayDescription:""},{displayLabel:o,displayDescription:r}=ds(n);return n.displayLabel=o,n.displayDescription=r,n}async fetchUserMergedPRCounts(e){let n=this.stateManager.getState().config;return _k(this.octokit,n.githubUsername,e)}async fetchUserClosedPRCounts(e){let n=this.stateManager.getState().config;return Sk(this.octokit,n.githubUsername,e)}async fetchRepoMetadata(e){if(e.length===0)return new Map;E(Lt,`Fetching repo metadata for ${e.length} repos...`);let n=new Map,o=Io(),r=[...new Set(e)],i=10;for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i),c=await Promise.allSettled(a.map(async d=>{let p=d.split("/");if(p.length!==2||!p[0]||!p[1])throw new ne(`Malformed repo identifier: "${d}"`);let[m,g]=p,h=`/repos/${m}/${g}`,_=await Bc(o,h,S=>this.octokit.repos.get({owner:m,repo:g,headers:S})),$={stars:_.stargazers_count,language:_.language??null};return{repo:d,metadata:$}})),l=0;for(let d=0;d<c.length;d++){let p=c[d];p.status==="fulfilled"?n.set(p.value.repo,p.value.metadata):(l++,b(Lt,`Failed to fetch metadata for ${a[d]}: ${I(p.reason)}`))}if(l===a.length&&a.length>0){let d=r.length-s-i;d>0&&b(Lt,`Entire chunk failed, aborting remaining ${d} repos`);break}}return E(Lt,`Fetched repo metadata for ${n.size}/${e.length} repos`),n}async fetchRecentlyClosedPRs(e=7){let n=this.stateManager.getState().config;return $k(this.octokit,n,e)}async fetchRecentlyMergedPRs(e=7){let n=this.stateManager.getState().config;return kk(this.octokit,n,e)}generateDigest(e,n=[],o=[]){let r=new Date().toISOString(),i=e.filter(c=>c.status==="needs_addressing"),s=e.filter(c=>c.status==="waiting_on_maintainer"),a=this.stateManager.getStats();return{generatedAt:r,openPRs:e,needsAddressingPRs:i,waitingOnMaintainerPRs:s,recentlyClosedPRs:n,recentlyMergedPRs:o,shelvedPRs:[],autoUnshelvedPRs:[],summary:{totalActivePRs:e.length,totalNeedingAttention:i.length,totalMergedAllTime:a.mergedPRs,mergeRate:parseFloat(a.mergeRate)}}}async updateRepoScoreFromObservedPR(e,n){n?this.stateManager.incrementMergedCount(e):this.stateManager.incrementClosedCount(e)}}});var vr,xA,Pk,Gr,Ck=v(()=>{"use strict";ko();ls();ss();To();xo();It();Vc();he();we();vr="issue-conversation",xA=5,Pk=new Set(["OWNER","MEMBER","COLLABORATOR"]),Gr=class{octokit;stateManager;constructor(e){this.octokit=Ie(e),this.stateManager=L()}async fetchCommentedIssues(e=30){let n=this.stateManager.getState().config;if(!n.githubUsername)throw new ot("No GitHub username configured. Run setup first.");let o=n.githubUsername,r=new Date;r.setDate(r.getDate()-e);let i=r.toISOString().split("T")[0];E(vr,`Fetching commented issues for @${o} (last ${e} days)...`);let{data:s}=await this.octokit.search.issuesAndPullRequests({q:`commenter:${o} type:issue state:open updated:>=${i}`,sort:"updated",order:"desc",per_page:100});s.total_count>100&&b(vr,`Search returned ${s.total_count} results but only first 100 were fetched. Some commented issues may be missing.`);let a=this.stateManager.getState().activeIssues||[],c=new Set(a.filter(h=>h.status==="claimed"||h.status==="in_progress"||h.status==="pr_submitted").map(h=>`${h.repo}#${h.number}`)),l=new Set((n.aiPolicyBlocklist||[]).map(h=>h.toLowerCase())),d=[];for(let h of s.items){if(h.pull_request)continue;let _=fo(h.html_url);if(!_){b(vr,`Skipping issue with unparseable URL: ${h.html_url}`);continue}let{owner:$,repo:S}=_,T=`${$}/${S}`;er($,o)||h.user?.login?.toLowerCase()!==o.toLowerCase()&&(n.excludeRepos.includes(T)||n.excludeOrgs?.some(j=>$.toLowerCase()===j.toLowerCase())||l.has(T.toLowerCase())||c.has(`${T}#${h.number}`)||d.push({item:h,repoFullName:T}))}E(vr,`Found ${d.length} commented issues to check`);let p=[],m=[];await Zc(d,async({item:h,repoFullName:_})=>{try{let $=await this.analyzeIssueConversation(h,_,o);$?p.push($):m.push({issueUrl:h.html_url,error:"No user comment found despite commenter: search match (possible pagination or eventual consistency)"})}catch($){let S=I($);m.push({issueUrl:h.html_url,error:S}),b(vr,`Error analyzing issue ${h.html_url}: ${S}`)}},xA),m.length>0&&b(vr,`${m.length}/${d.length} issue analysis call(s) failed`),m.length===d.length&&d.length>0&&b(vr,`All ${d.length} issue analysis call(s) failed. Possible systemic issue (rate limit, auth, network).`);let g={new_response:0,waiting:1,acknowledged:2};return p.sort((h,_)=>g[h.status]-g[_.status]),E(vr,`Analyzed ${p.length} issue conversations (${p.filter(h=>h.status==="new_response").length} with new responses)`),{issues:p,failures:m}}async analyzeIssueConversation(e,n,o){let{owner:r,repo:i}=ho(n),s=await _t(S=>this.octokit.issues.listComments({owner:r,repo:i,issue_number:e.number,per_page:100,page:S})),a=[];for(let S of s){if(!S.user?.login)continue;let T=S.user.login;a.push({author:T,body:S.body||"",createdAt:S.created_at,isUser:T.toLowerCase()===o.toLowerCase(),authorAssociation:typeof S.author_association=="string"?S.author_association:""})}a.sort((S,T)=>new Date(S.createdAt).getTime()-new Date(T.createdAt).getTime());let c;for(let S of a)S.isUser&&(c=S);if(!c)return b(vr,`No user comment found for ${e.html_url} despite commenter: search match`),null;let l=new Date(c.createdAt),d=`@${o.toLowerCase()}`;function p(S){return Pk.has(S.authorAssociation)||S.body.toLowerCase().includes(d)}let m;for(let S of a){if(S.isUser||hr(S.author))continue;if(new Date(S.createdAt)>l){if(Oo(S.body)||!p(S))continue;m={author:S.author,body:S.body.slice(0,200)+(S.body.length>200?"...":""),createdAt:S.createdAt,authorAssociation:S.authorAssociation}}}let g=(e.labels||[]).map(S=>S.name||"").filter(Boolean),h={repo:n,number:e.number,title:e.title,url:e.html_url,userLastCommentedAt:c.createdAt,labels:g,daysSinceUserComment:gn(l,new Date)};if(m)return{...h,status:"new_response",lastResponseAuthor:m.author,lastResponseBody:m.body,lastResponseAt:m.createdAt,isFromMaintainer:Pk.has(m.authorAssociation)};let $=[...a].reverse().find(S=>hr(S.author)?!1:S.isUser?!0:p(S))?.isUser?"acknowledged":"waiting";return{...h,status:$}}}});function Xc(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ").replace(/\r/g," ")}function Dk(t,e,n={}){let o=t.split("&").join(Ik).split(zr).join(Ok).replace(PA,Ak),r=[`label="${Xc(e)}"`];return n.author!==void 0&&r.push(`author="${Xc(n.author)}"`),n.association!==void 0&&r.push(`association="${Xc(n.association)}"`),n.source!==void 0&&r.push(`source="${Xc(n.source)}"`),`<${br} ${r.join(" ")}>${o}${zr}`}function Uk(t){let e=t.match(new RegExp(`^<${br}\\b[^>]*>`));if(!e)throw new Error("extractFromFence: input does not start with a <github-content> open tag");if(!t.endsWith(zr))throw new Error("extractFromFence: input does not end with </github-content>");let n=t.slice(e[0].length,t.length-zr.length);if(n.includes(zr))throw new Error("extractFromFence: nested </github-content> found in body \u2014 fence escaping is broken");return n.split(Ok).join(zr).split(Ak).join(`<${br}`).split(Ik).join("&")}var br,zr,Ik,Ok,PA,Ak,Fk=v(()=>{"use strict";br="github-content",zr=`</${br}>`,Ik="&",Ok=`</${br}>`,PA=new RegExp(`<${br}\\b`,"g"),Ak=`<${br}`});function vn(){if(St)return St;if(ms)return null;if(ms=!0,process.env.GITHUB_TOKEN)return St=process.env.GITHUB_TOKEN,St;try{let t=(0,gs.execFileSync)("gh",["auth","token"],{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:2e3}).trim();if(t&&t.length>0)return St=t,E(hn,"Using GitHub token from gh CLI"),St}catch(t){b(hn,`gh auth token failed (CLI unavailable or not authenticated): ${t instanceof Error?t.message:String(t)}`)}return null}function We(){let t=vn();if(!t)throw new ot(`GitHub authentication required.
|
|
107
107
|
|
|
108
108
|
Options:
|
|
109
109
|
1. Use gh CLI: gh auth login
|
|
@@ -20,6 +20,13 @@ const PLACEHOLDER_USERNAMES = [
|
|
|
20
20
|
'example-user',
|
|
21
21
|
'your-username',
|
|
22
22
|
'your-github-username',
|
|
23
|
+
// GitHub's mascot accounts. Real users on github.com but seeded into countless
|
|
24
|
+
// example configs, READMEs, and SDK docs (Octokit's quickstarts use `octocat`
|
|
25
|
+
// as the canonical login). Treating them as placeholders keeps a stale example
|
|
26
|
+
// value from silently swapping a real user's PR feed with the mascot's open
|
|
27
|
+
// PRs in violet-org/boysenberry-repo (octocat's public test fixtures).
|
|
28
|
+
'octocat',
|
|
29
|
+
'monalisa',
|
|
23
30
|
];
|
|
24
31
|
const KNOWN_PLACEHOLDER_USERNAMES = new Set(PLACEHOLDER_USERNAMES);
|
|
25
32
|
export function isPlaceholderUsername(username) {
|