opencode-forgekeeper 3.1.0 → 3.3.0

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/README.md CHANGED
@@ -22,8 +22,8 @@ OpenCode server's `PATH`; only the CLI for your forge is required.
22
22
  opencode plugin add opencode-forgekeeper
23
23
  ```
24
24
 
25
- OpenCode loads the server and terminal parts automatically. Forgekeeper uses your forge CLI's
26
- credentials and has none of its own. Without a forge CLI, session naming still works, and
25
+ OpenCode loads the server, terminal, and desktop parts automatically. Forgekeeper uses your
26
+ forge CLI's credentials and has none of its own. Without a forge CLI, session naming still works, and
27
27
  `/forge-status` explains what's missing.
28
28
 
29
29
  For self-managed hosts, configure `hosts` for GitLab hosts not named `gitlab.*`, or
@@ -64,6 +64,22 @@ For example, this footer tracks four MRs, with one conflict and two already merg
64
64
  | `/forge-open` | Open the PR/MR in your browser. Aliases: `/mr-open`, `/pr-open`. |
65
65
  | `/forge-feedback` | Browse pending review feedback and PR/MR updates. |
66
66
 
67
+ In OpenCode Desktop, a pill above the composer shows the same status, and the commands
68
+ above open side panels for the status and the inbox. Server notices appear as toasts and
69
+ system notifications.
70
+
71
+ The OpenCode web app loads neither the terminal nor the desktop part, but it offers two
72
+ commands that answer in the conversation:
73
+
74
+ | Command | Action |
75
+ | --- | --- |
76
+ | `/forge-report` | Show the PR/MR status of the session. |
77
+ | `/forge-inbox` | List the session's pending updates. `ack <number>` or `ack all` acknowledges them, and `summarize <number>` summarizes one. |
78
+
79
+ Each answer is a short tool-free model turn that shows a report written from forge data.
80
+ Those apps don't display the text of messages that plugins add, so the model shows it.
81
+ The report stays out of the session's history.
82
+
67
83
  Status normally refreshes every 2 minutes, or every 30 seconds during automated reviews and
68
84
  while new review feedback settles.
69
85
  Explicit PR/MR targets take precedence over title references and branch discovery. Issue
@@ -107,7 +123,7 @@ before a typical 5-minute prompt cache expires. Monitoring records an initial ba
107
123
  than announcing existing feedback. Pending updates survive reloads and clear when acknowledged
108
124
  or no longer relevant; merge updates remain until acknowledged.
109
125
 
110
- Forgekeeper reports failed jobs but doesn't retry or fix them. For tracked stacks, it can
126
+ Forgekeeper reports failed jobs but never retries or fixes them. For tracked stacks, it can
111
127
  also propose retargeting dependents after a parent merges, but never retargets or rebases itself.
112
128
 
113
129
  Optionally, `automation.rules` lets exact reviewers on exact projects, such as GitLab Duo, start
@@ -117,6 +133,12 @@ you trust with code changes. The turn uses the session's instructions and permis
117
133
  leaves changes uncommitted. In `/forge-feedback`, **Act on feedback** (Ctrl+A) starts the same
118
134
  turn on request, and **Retry feedback work** (Ctrl+T) retries one after you inspect it.
119
135
 
136
+ A `job-failed` rule investigates failed jobs on exact projects instead. Once a pipeline's
137
+ failures go quiet for four minutes, or the pipeline finishes, one turn reads the failed jobs'
138
+ logs and reports each failure's cause and a recommended fix, without changing anything. It runs
139
+ on PRs/MRs you wrote or review, with the checkout at the head commit the pipeline tested. See
140
+ [Investigate failed jobs](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#investigate-failed-jobs).
141
+
120
142
  See [review detection and summaries](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#review-notifications),
121
143
  [monitoring eligibility](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#which-sessions-the-server-watches),
122
144
  [stacked PRs/MRs](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#stacked-prsmrs), and
@@ -141,7 +163,7 @@ Only specify values you want to change. The terminal part has no separate option
141
163
  | `delivery.reviews` | `"inbox"` | Review delivery: `inbox`, `passive`, or `summary`. |
142
164
  | `delivery.lifecycle` | `"inbox"` | Conflict, job-failure, and merge delivery. |
143
165
  | `lifecycleExecution.parentMerged` | `{ "mode": "notify" }` | Optionally prepare retarget proposals for tracked dependents. |
144
- | `automation.rules` | No rules | Reviewers whose feedback starts a coding turn that prepares fixes, optionally limited to allowed models. |
166
+ | `automation.rules` | No rules | Reviewers whose feedback starts a coding turn that prepares fixes, or projects whose failed jobs start an investigation, optionally limited to allowed models. |
145
167
  | `automation.modelGroups` | No groups | Named lists of `provider/model` IDs that rules reference in `allowedModelGroup`. |
146
168
 
147
169
  See the [configuration reference](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#options) for validation behavior and
@@ -154,7 +176,8 @@ edit files, commit, push, reply to comments, or resolve discussions. Only an
154
176
  [automation rule](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#prepare-fixes-from-review-feedback)
155
177
  or **Act on feedback** starts a coding turn that edits files, with the session's permissions.
156
178
  That turn sends reviewer text to the model as untrusted data, keeps it in the session's
157
- history, and leaves changes uncommitted.
179
+ history, and leaves changes uncommitted. A failed-job investigation sends job names and
180
+ links the same way, and the agent reads job logs with the session's tools.
158
181
 
159
182
  Optional review summaries send review text to the session's model, isolated from conversation
160
183
  history and ordinary tools. On GitLab, a restricted tool can read notes directly linked by
@@ -0,0 +1,131 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js/web"),j=require("@opencode/plugin/gui"),P=require("solid-js"),Pe=require("solid-js/store"),ct=require("node:crypto"),ze=e=>t=>t.forge===e,lt=e=>e?.match(/^\[[^\]]*\]/)?.[0]??"";function We(e,t){return lt(e).slice(1,-1).split(/[\s,]+/).flatMap(r=>r.startsWith(t)&&/^[1-9]\d*$/.test(r.slice(t.length))?[r.slice(t.length)]:[])}function fe(e,t,r){let s;try{s=new URL(t)}catch{return}if(!["https:","http:"].includes(s.protocol))return;const n=s.pathname.match(r);if(n)return{forge:e,host:s.hostname.toLowerCase(),project:decodeURIComponent(n[1]),iid:n[2]}}const W=e=>e?"yes":"no",he=e=>e.toLowerCase().replace(/_/g," ");class x extends Error{constructor(t,r){super(r),this.kind=t}kind}const N=e=>e,B=e=>async(t,r,s)=>await e(t,r,s),_e=10,ut=10,Ne=300,dt=5,De=300;function pt(e,t){const r=e.split(`
2
+ `);if(t<1||t>r.length)return;const s=Math.max(1,t-_e),n=Math.min(r.length,t+_e);return r.slice(s-1,n).map((o,i)=>{const a=s+i,c=o.length>Ne?`${o.slice(0,Ne)}…`:o;return`${a===t?">":" "}${a}: ${c}`}).join(`
3
+ `)}const ee=100,ie=20,Je=200,be="author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } }",ve="pageInfo { hasPreviousPage startCursor }",Qe=`id url state createdAt publishedAt lastEditedAt isMinimized ${be}`,$e=(e,t)=>N(`query($owner: String!, $repo: String!, $number: Int!, $before: String) {
4
+ viewer { id }
5
+ repository(owner: $owner, name: $repo) {
6
+ pullRequest(number: $number) {
7
+ ${e}(last: ${ee}, before: $before) { ${ve} nodes { ${t} } }
8
+ }
9
+ }
10
+ }`),ft=$e("comments",`id url createdAt publishedAt lastEditedAt isMinimized ${be}`),ht=$e("reviews",`id url state body submittedAt lastEditedAt isMinimized ${be}`),mt=$e("reviewThreads",`id isResolved comments(last: ${ee}) { ${ve} nodes { ${Qe} } }`),gt=N(`query($id: ID!, $before: String) {
11
+ node(id: $id) {
12
+ ... on PullRequestReviewThread {
13
+ comments(last: ${ee}, before: $before) { ${ve} nodes { ${Qe} } }
14
+ }
15
+ }
16
+ }`),wt=new Set(["COMMENTED","CHANGES_REQUESTED","APPROVED"]),ye=(...e)=>{const t=e.find(r=>r);return t?Date.parse(t):NaN},Se=(e,t)=>{const r=e?Date.parse(e):NaN;return Number.isFinite(r)?Math.max(r,t):t};function Ce({node:e,postedAt:t,editedAt:r,resolved:s}){if(e.isMinimized||!e.author?.id||!Number.isFinite(t)||!Number.isFinite(r))return;const{__typename:n,login:o}=e.author;return{id:e.id,order:t,url:e.url??"",editedAt:r,resolved:s,bot:n==="Bot"||o.endsWith("[bot]"),authorID:e.author.id,username:o}}function bt(e){const t=ye(e.publishedAt,e.createdAt);return Ce({node:e,postedAt:t,editedAt:Se(e.lastEditedAt,t),resolved:!1})}function vt(e){if(!wt.has(e.state)||!e.body.trim())return;const t=ye(e.submittedAt);return Ce({node:e,postedAt:t,editedAt:Se(e.lastEditedAt,t),resolved:!1})}function $t(e,t){if(e.state==="PENDING")return;const r=ye(e.publishedAt,e.createdAt);return Ce({node:e,postedAt:r,editedAt:Se(e.lastEditedAt,r),resolved:t})}const yt={pages:ie,completeAtLimit:!0},St={pages:Je,completeAtLimit:!1};async function ue(e,t,r,s,n,o=yt){const i=[];let a,c;const d=m=>({items:i.toReversed().flat(),viewer:a,complete:m});for(let m=0;m<o.pages;m++){const f=c?{...r,before:c}:r,g=await e(t,s,f);a??=g.viewer?.id??void 0;const S=g.repository?.pullRequest?.[n];if(!S)return m===0?{viewer:a,complete:!1}:d(!1);if(i.push(S.nodes),!S.pageInfo.hasPreviousPage)return d(!0);if(c=S.pageInfo.startCursor??void 0,!c)return d(!1)}return d(o.completeAtLimit)}async function Ct(e,t,r){if(!r.comments)return{comments:[],complete:!1};const s=[];let n=r.comments?.pageInfo.hasPreviousPage?r.comments.pageInfo.startCursor??void 0:void 0;if(r.comments?.pageInfo.hasPreviousPage&&!n)return{comments:[],complete:!1};for(let o=1;n&&o<ie;o++){const a=(await e(t,gt,{id:r.id,before:n})).node?.comments;if(!a)return{comments:s.toReversed().flat(),complete:!1};if(s.push(a.nodes),n=a.pageInfo.hasPreviousPage?a.pageInfo.startCursor??void 0:void 0,a.pageInfo.hasPreviousPage&&!n)return{comments:s.toReversed().flat(),complete:!1}}return{comments:s.toReversed().flat(),complete:!0}}const Rt=e=>N(`query {
17
+ nodes(ids: ${JSON.stringify(e)}) {
18
+ __typename
19
+ ... on IssueComment { id url body author { login ... on User { id } ... on Bot { id } } }
20
+ ... on PullRequestReview { id url body author { login ... on User { id } ... on Bot { id } } }
21
+ ... on PullRequestReviewComment {
22
+ id url body path line originalLine diffHunk author { login ... on User { id } ... on Bot { id } }
23
+ replyTo { body author { login } }
24
+ }
25
+ }
26
+ }`),Et=/^[A-Za-z0-9_=-]+$/,Ae=50;async function It(e,t,r){const s=B(e),n=[],o=r.filter(i=>Et.test(i));for(let i=0;i<o.length;i+=Ae){const a=await s(t,Rt(o.slice(i,i+Ae)),{});for(const c of a.nodes??[]){if(!c?.id||!c.url||!c.author||c.body===void 0)continue;const d=c.line??c.originalLine??void 0,m=c.diffHunk?.split(`
27
+ `).slice(-21).join(`
28
+ `),f=c.replyTo?.author?[{username:c.replyTo.author.login,body:c.replyTo.body}]:[];n.push({id:c.id,url:c.url,username:c.author.login,...c.author.id?{authorID:c.author.id}:{},body:c.body,...c.path?{path:c.path}:{},...d!==void 0?{line:d}:{},...c.path&&m?{code:{path:c.path,text:m}}:{},...f.length?{replies:f}:{}})}}return n}async function kt(e,t,r,s){let n=0;const o=B(async(..._)=>n++>=Je?{}:e(..._)),[i,a]=r.split("/"),c={owner:i,repo:a,number:Number(s)},[d,m,f]=await Promise.all([ue(o,t,c,ft,"comments"),ue(o,t,c,ht,"reviews"),ue(o,t,c,mt,"reviewThreads",St)]);if(!d.items||!m.items||!f.items)return;const g=d.viewer??m.viewer??f.viewer;let S=f.complete;const v=[];for(const _ of f.items){const L=await Ct(o,t,_);S&&=L.complete;for(const O of[...L.comments,..._.comments?.nodes??[]]){const p=$t(O,_.isResolved);p&&v.push(p)}v.sort((O,p)=>p.order-O.order),v.splice(ee*ie)}const q=[...d.items.map(bt),...m.items.map(vt),...v.sort((_,L)=>_.order-L.order).slice(-ee*ie)].flatMap(_=>_??[]);return{complete:d.complete&&m.complete&&S&&g!==void 0,viewerID:g,comments:q.sort((_,L)=>_.order-L.order)}}const Pt=100,_t=20,me=N(`query($project: ID!, $iid: String!, $before: String) {
29
+ currentUser { id }
30
+ project(fullPath: $project) {
31
+ mergeRequest(iid: $iid) {
32
+ notes(last: ${Pt}, before: $before, filter: ONLY_COMMENTS) {
33
+ pageInfo { hasPreviousPage startCursor }
34
+ nodes {
35
+ id url createdAt updatedAt lastEditedAt system
36
+ position { newPath }
37
+ discussion { resolved }
38
+ author { id username bot }
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }`),Nt=N(String(me).replace("position { newPath }","position { newPath } duoCreatedSession { id status workflowDefinition }")),se=e=>e.slice(e.lastIndexOf("/")+1),Dt=e=>Date.parse(e.lastEditedAt??e.updatedAt??e.createdAt);function At(e){const t=Dt(e),r=se(e.id);if(!(e.system||!e.author||!Number.isFinite(t)||!/^\d+$/.test(r)))return{id:r,order:Number(r),url:e.url??"",editedAt:t,resolved:e.discussion?.resolved===!0,bot:e.author.bot,authorID:e.author.id,username:e.author.username,...e.author.bot&&e.author.username.toLowerCase()==="gitlabduo"?{automated:{reviewer:"GitLab Duo",finding:!!e.position,...e.duoCreatedSession?.workflowDefinition==="code_review/v1"?{runID:e.duoCreatedSession.id,status:e.duoCreatedSession.status}:{}}}:{}}}async function Tt(e,t,r,s){const n=B(e),o=[];let i,a,c=!0;const d=m=>({complete:m&&i!==void 0,viewerID:i,comments:o.toReversed().flat()});for(let m=0;m<_t;m++){const f={project:r,iid:s};a&&(f.before=a);let g;try{g=await n(t,c?Nt:me,f)}catch(v){if(!c||!/duoCreatedSession.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*duoCreatedSession/i.test(v instanceof Error?v.message:String(v)))throw v;c=!1,g=await n(t,me,f)}i??=g.currentUser?.id??void 0;const S=g.project?.mergeRequest?.notes;if(!S)return m===0?void 0:d(!1);if(o.push(S.nodes.flatMap(v=>At(v)??[])),!S.pageInfo.hasPreviousPage)return d(!0);if(a=S.pageInfo.startCursor??void 0,!a)return d(!1)}return d(!0)}const Te=25,qt=20,Lt=/^[0-9a-f]{40}$/;function Ke(e){const t=e?.diffRefs;if(t){if(e.newLine&&e.newPath)return{sha:t.headSha,path:e.newPath,line:e.newLine};if(e.oldLine&&e.oldPath)return{sha:t.baseSha,path:e.oldPath,line:e.oldLine}}}async function Ot(e,t,r,s){const n=B(e),o=[],i=s.filter(c=>/^\d+$/.test(c));for(let c=0;c<i.length;c+=Te){const d=i.slice(c,c+Te).map((f,g)=>`n${g}: note(id: "gid://gitlab/Note/${f}") { id url body author { id username }
44
+ position { diffRefs { baseSha headSha } newPath newLine oldPath oldLine }
45
+ discussion { notes(first: ${qt}) { nodes { id body author { username } } } } }`).join(`
46
+ `),m=await n(t,N(`query { ${d} }`),{});for(const f of Object.values(m))f?.author&&f.url&&o.push(f)}const a=await xt(n,t,r,o).catch(()=>new Map);return o.map(c=>{const d=Ke(c.position),m=d&&a.get(JSON.stringify([d.sha,d.path])),f=m!==void 0&&d?pt(m,d.line):void 0,g=c.discussion?.notes?.nodes??[],S=g.findIndex(q=>se(q.id)===se(c.id)),v=(S>0?g.slice(0,S):[]).flatMap(q=>q.author?[{username:q.author.username,body:q.body}]:[]);return{id:se(c.id),url:c.url??"",username:c.author?.username??"",...c.author?.id?{authorID:c.author.id}:{},body:c.body,...d?{path:d.path,line:d.line}:{},...f&&d?{code:{path:d.path,text:f}}:{},...v.length?{replies:v}:{}}})}async function xt(e,t,r,s){const n=new Map;let o=0;for(const m of s){const f=Ke(m.position);if(!f||!Lt.test(f.sha))continue;const g=n.get(f.sha)??new Set;!g.has(f.path)&&o>=ut||(g.has(f.path)||o++,n.set(f.sha,g.add(f.path)))}const i=new Map;if(!n.size)return i;const a=[...n.keys()],c=a.map((m,f)=>`b${f}: project(fullPath: ${JSON.stringify(r)}) { repository { blobs(paths: ${JSON.stringify([...n.get(m)])}, ref: ${JSON.stringify(m)}) { nodes { path rawTextBlob } } } }`).join(`
47
+ `),d=await e(t,N(`query { ${c} }`),{});return a.forEach((m,f)=>{for(const g of d[`b${f}`]?.repository?.blobs?.nodes??[])g.rawTextBlob!==null&&i.set(JSON.stringify([m,g.path]),g.rawTextBlob)}),i}const Ut=/^\/(.+?)\/-\/(issues|work_items|merge_requests)\/(\d+)(\/diffs)?\/?$/,Mt=/^#note_(\d+)$/,jt=/https:\/\/[^\s<>()[\]"'`]+/g,Bt=/^gid:\/\/gitlab\/[A-Za-z]*Note\/(\d+)$/;function ge(e,t){if(e.length>De*2)return;let r;try{r=new URL(e)}catch{return}if(r.protocol!=="https:"||r.hostname.toLowerCase()!==t||r.port||r.username||r.password)return;const s=r.hash.match(Mt)?.[1],n=r.pathname.match(Ut);if(!s||!n)return;const[,o,i,a,c]=n;if(c&&i!=="merge_requests"||o.split("/").some(m=>!m||m==="."||m===".."))return;const d=`https://${t}/${o}/-/${i}/${a}#note_${s}`;if(!(d.length>De))return{url:d,project:o,resource:i==="merge_requests"?"merge_request":"issue",iid:a,noteID:s}}const Ve=(e,t)=>e.project.toLowerCase()===t.project.toLowerCase()&&e.resource===t.resource&&e.iid===t.iid&&e.noteID===t.noteID;function Ft(e,t){const r=new Set(t.map(n=>n.id)),s=[];for(const n of t)for(const[o]of n.body.matchAll(jt)){const i=ge(o.replace(/[.,;:!?*_~]+$/,""),e);if(!(!i||r.has(i.noteID))&&!s.some(a=>Ve(a,i))&&(s.push(i),s.length===dt))return s.map(a=>a.url)}return s.map(n=>n.url)}async function Gt(e,t,r){const s=ge(r,t);if(!s||s.url!==r)return;const o=(await B(e)(t,N("query($id: NoteID!) { note(id: $id) { id url body author { username } } }"),{id:`gid://gitlab/Note/${s.noteID}`})).note;if(!o?.author||!o.url||o.id.match(Bt)?.[1]!==s.noteID)return;const i=ge(o.url,t);if(!(!i||!Ve(i,s)))return{url:s.url,username:o.author.username,body:o.body}}const Ht=4*6e4;function zt(e){return{...e,comments:e.comments.filter(t=>t.automated?.reviewer==="GitLab Duo"&&t.automated.finding).map(t=>({...t,bot:!1}))}}function Wt(e,t){return e.comments.filter(s=>!s.resolved).every(s=>t-s.editedAt>=Ht&&(!s.automated?.status||["FINISHED","FAILED","STOPPED"].includes(s.automated.status)))}function Jt(e,t,r){const s={Authorization:`Bearer ${t}`,Origin:r},n=new WebSocket(e,{protocols:["actioncable-v1-json"],headers:s}),o=new AbortController;let i=!1,a=!1;const c={send:d=>n.send(d),close:()=>{o.abort(),n.close()},onmessage:null,onerror:null,onclose:null,onresponse:null};return n.onopen=()=>{i=!0},n.onmessage=({data:d})=>c.onmessage?.(String(d)),n.onclose=()=>{a||c.onclose?.()},n.onerror=async()=>{if(o.signal.aborted||a)return;if(i){c.onerror?.();return}a=!0;const d=new URL(e);d.protocol=d.protocol==="wss:"?"https:":"http:";try{const m=await fetch(d,{redirect:"manual",signal:AbortSignal.any([o.signal,AbortSignal.timeout(1e4)]),headers:{...s,Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":ct.randomBytes(16).toString("base64"),"Sec-WebSocket-Protocol":"actioncable-v1-json"}});try{o.signal.aborted||c.onresponse?.(m.status,m.headers)}finally{await m.body?.cancel()}}catch{o.signal.aborted||c.onerror?.()}},c}class Qt extends Error{constructor(t){super("Feedback subscription rate limited"),this.retryAt=t}retryAt}function Kt(e,t=Date.now()){const r=Date.parse(e.get("date")??""),s=Number.isFinite(r)?r:t,n=[],o=e.get("retry-after")?.trim();o&&(/^\d+$/.test(o)?n.push(Number(o)*1e3):/^[+-]?[\d.]+$/.test(o)||n.push(Date.parse(o)-s));for(const d of["ratelimit-reset","x-ratelimit-reset"]){const m=e.get(d)?.trim();m&&/^\d+$/.test(m)&&n.push(Number(m)*1e3-s)}const i=e.get("ratelimit-resettime");i&&n.push(Date.parse(i)-s);const a=n.filter(d=>Number.isFinite(d)&&d>=0);if(!a.length)return;const c=t+Math.max(...a);return Number.isSafeInteger(c)?c:void 0}async function Vt(e,t,r,s,n,o=Jt){const i=new URL(r.url);if(i.protocol!=="https:"||i.username||i.password||i.port)return;const a=i.pathname.match(/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);if(!a||n.aborted)return;const c=await e("glab",["config","get","token","--host",i.hostname],t);if(n.aborted)return;if(c.code!==0||!c.stdout.trim())throw new Error("Subscription credentials unavailable");const d=await e("glab",["api",`projects/${encodeURIComponent(decodeURIComponent(a[1]))}/merge_requests/${a[2]}`,"--hostname",i.hostname],t);if(n.aborted)return;if(d.code!==0)throw new Error("Subscription target lookup failed");const m=JSON.parse(d.stdout);if(!Number.isSafeInteger(m.id)||!Number.isSafeInteger(m.project_id))throw new Error("Invalid subscription target");const f=JSON.stringify({channel:"Noteable::NotesChannel",project_id:m.project_id,noteable_type:"MergeRequest",noteable_id:m.id});await new Promise((g,S)=>{const v=o(`wss://${i.host}/-/cable`,c.stdout.trim(),i.origin);let q=!1,_=!1,L,O;const p=()=>{q||(q=!0,clearTimeout(O),n.removeEventListener("abort",p),v.onmessage=null,v.onerror=null,v.onclose=null,v.onresponse=null,v.close(),L?S(L):g())},$=()=>{clearTimeout(O),O=setTimeout(p,_?45e3:15e3)};$(),n.addEventListener("abort",p,{once:!0}),v.onerror=p,v.onclose=p,v.onresponse=(E,A)=>{E===429&&(L=new Qt(Kt(A)??Date.now()+6e4)),p()},v.onmessage=E=>{if(!q)try{const A=JSON.parse(String(E));if(_&&$(),A.type==="welcome"&&v.send(JSON.stringify({command:"subscribe",identifier:f})),A.type==="disconnect"&&p(),A.identifier!==f)return;A.type==="reject_subscription"&&p(),A.type==="confirm_subscription"&&!_&&(_=!0,$(),s.connected()),_&&A.message?.event==="updated"&&s.changed()}catch{p()}},n.aborted&&p()})}const Xe="pageInfo { hasNextPage endCursor } nodes { resolvable resolved }",Ye=100,Xt=50,Yt=10,Zt="pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }",er=new Set(["CHECKING","UNCHECKED","PREPARING"]),qe="CANNOT_BE_MERGED_RECHECK",Ze=`
48
+ iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
49
+ approvedBy(first: 100) { nodes { id bot } }
50
+ sourceProject { fullPath }
51
+ targetProject { fullPath }
52
+ author { id }
53
+ headPipeline {
54
+ id status path detailedStatus { label }
55
+ jobs(statuses: [FAILED], retried: false, first: ${Yt}) { ${Zt} }
56
+ }
57
+ reviewers(first: 100) { nodes { id type username bot mergeRequestInteraction { reviewState approved } } }
58
+ discussions(first: ${Ye}) { ${Xe} }
59
+ `;function tr(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) {
60
+ mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${Ze} } }
61
+ }`).join(`
62
+ `);return N(`query($branch: String!, ${t}) {
63
+ ${r}
64
+ }`)}function rr(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) { mergeRequest(iid: $iid) { ${Ze} } }`).join(`
65
+ `);return N(`query($iid: String!, ${t}) {
66
+ ${r}
67
+ }`)}function nr(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) {
68
+ mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { iid updatedAt sourceProject { fullPath } } }
69
+ }`).join(`
70
+ `);return N(`query($branch: String!, ${t}) {
71
+ ${r}
72
+ }`)}const sr=N(`query($project: ID!, $iid: String!) {
73
+ project(fullPath: $project) { mergeRequest(iid: $iid) { sourceBranch } }
74
+ }`),or=N(`query($project: ID!, $iid: String!, $after: String) {
75
+ project(fullPath: $project) {
76
+ mergeRequest(iid: $iid) { discussions(first: ${Ye}, after: $after) { ${Xe} } }
77
+ }
78
+ }`);function K(e,t){const r=e.trim().replace(/^glab:\s*/,"")||`glab exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new x("missing-glab","glab is not installed"):/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(r)?new x("auth","GitLab authentication failed. Run `glab auth status`."):/\b429\b|rate limit|too many requests/i.test(r)?new x("rate-limit","GitLab rate limit reached"):new x("request",r.split(`
79
+ `)[0])}const ir=e=>typeof e=="object"&&e!==null&&(!("errors"in e)||Array.isArray(e.errors))&&(!("data"in e)||typeof e.data=="object");function z(e,t){return async(r,s,n)=>{const o=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[c,d]of Object.entries(n))o.push("-f",`${c}=${d}`);const i=await e("glab",o,t);let a;try{a=JSON.parse(i.stdout)}catch{throw K(i.stderr,i.code)}if(!ir(a))throw K(i.stderr||"Unexpected GitLab response",i.code);if(a.errors?.length)throw K(String(a.errors[0]?.message??""),i.code);if(i.code!==0)throw K(i.stderr,i.code);if(!a.data)throw K("GitLab returned no data",i.code);return a.data}}const Le=e=>e.nodes.filter(t=>t.resolvable&&!t.resolved).length,G={kind:"gitlab",noun:"MR",ci:"pipeline",recognizes:e=>/(^|\.)gitlab\./.test(e),open:(e,t)=>new dr(z(e,t)),owns:ze("gitlab"),parseUrl:e=>fe("gitlab",e,/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/),parseIssueUrl:e=>fe("gitlab",e,/^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),reference:e=>`!${e}`,issueReference:e=>`#${e}`,titleReferences:e=>We(e,"!"),indicators:()=>[],details(e){const t=e.approvalRequirementsSatisfied===null?"unknown":W(e.approvalRequirementsSatisfied),r=[`Human approvals: ${W(e.hasApprovals)} · Approval requirements satisfied: ${t}`];return e.mergeStatus&&r.push(`Merge status: ${he(e.mergeStatus)}`),r},automatedReview:{publishedFeedback:{storageKey:"duo",select:zt,ready:Wt},name:"GitLab Duo",status(e){const t=e.duoReviewState;if(t)return{state:ur(t),label:he(t)}}},feedback:{async viewerID(e,t,r){return(await B(z(e,t))(r,N("query { currentUser { id } }"),{})).currentUser?.id},async reviewerID(e,t,r,s){const n=await B(z(e,t))(r,N("query($username: String!) { user(username: $username) { id username } }"),{username:s});return n.user?.username.toLowerCase()===s.toLowerCase()?n.user.id:void 0},subscribe:Vt,async fetch(e,t,r){const s=G.parseUrl(r.url);return s?Tt(z(e,t),s.host,s.project,s.iid):void 0},async details(e,t,r,s){const n=G.parseUrl(r.url);return n?Ot(z(e,t),n.host,n.project,s):[]},commentID:e=>e.match(/#note_(\d+)$/)?.[1],linkedNotes(e,t){const r=G.parseUrl(e.url);return r?Ft(r.host,t):[]},async linkedNote(e,t,r,s){const n=G.parseUrl(r.url);return n?Gt(z(e,t),n.host,s):void 0}}},ar=new Set(["REVIEWED","REQUESTED_CHANGES"]);function cr(e,t){return!t.id||!t.jobs?{}:{id:t.id,failedJobs:lr(e,t.jobs.nodes),failedJobsComplete:!t.jobs.pageInfo?.hasNextPage}}function lr(e,t){return t.flatMap(r=>!r.allowFailure&&r.name?[{...r.id?{id:r.id}:{},name:r.name,...r.webPath?{url:`https://${e}${r.webPath}`}:{},...r.stage?.name?{stage:r.stage.name}:{}}]:[])}function ur(e){return e==="REVIEW_STARTED"?"running":ar.has(e)?"feedback":"settled"}class dr{traits=G;graphql;constructor(t){this.graphql=B(t)}async findByBranch(t){const{source:r,targets:s,sourceBranch:n}=t,o={branch:n};s.forEach((f,g)=>o[`p${g}`]=f.path);const i=await this.graphql(r.host,tr(s.length),o),a=r.path.toLowerCase(),c=new Set,d=[];return s.forEach((f,g)=>{for(const S of i[`p${g}`]?.mergeRequests?.nodes??[]){if(S.sourceProject?.fullPath.toLowerCase()!==a)continue;const v=`${S.targetProject.fullPath}!${S.iid}`;c.has(v)||(c.add(v),d.push(S))}}),(await Promise.all(d.map(f=>this.normalize(r.host,f)))).sort((f,g)=>(g.updatedAt??"").localeCompare(f.updatedAt??""))}async findNumberByBranch(t){const{source:r,targets:s,sourceBranch:n}=t,o={branch:n};s.forEach((d,m)=>o[`p${m}`]=d.path);const i=await this.graphql(r.host,nr(s.length),o),a=r.path.toLowerCase();return s.flatMap((d,m)=>i[`p${m}`]?.mergeRequests?.nodes??[]).filter(d=>d.sourceProject?.fullPath.toLowerCase()===a).sort((d,m)=>(m.updatedAt??"").localeCompare(d.updatedAt??""))[0]?.iid}async sourceBranch(t){const s=(await this.graphql(t.host,sr,{project:t.project,iid:t.iid})).project?.mergeRequest?.sourceBranch;return typeof s=="string"&&s?s:void 0}async findByNumber(t,r){if(t.length===0)return;const s=t[0].host,n={iid:r};t.forEach((i,a)=>n[`p${a}`]=i.path);const o=await this.graphql(s,rr(t.length),n);for(let i=0;i<t.length;i++){const a=o[`p${i}`]?.mergeRequest;if(a)return this.normalize(s,a)}}async unresolvedThreads(t,r){let s=Le(r.discussions),n=r.discussions.pageInfo,o=1;for(;n.hasNextPage&&n.endCursor&&o<Xt;){const a=(await this.graphql(t,or,{project:r.targetProject.fullPath,iid:r.iid,after:n.endCursor})).project?.mergeRequest?.discussions;if(!a)break;s+=Le(a),n=a.pageInfo,o++}return{count:s,complete:!n.hasNextPage}}async normalize(t,r){const s=await this.unresolvedThreads(t,r),n=r.headPipeline,o=(r.approvedBy?.nodes??[]).some(a=>a.bot!==!0),i=(r.reviewers?.nodes??[]).filter(a=>a.bot!==!0&&a.username&&a.mergeRequestInteraction?.approved!==!0).map(a=>a.username);return{forge:"gitlab",iid:r.iid,title:r.title,url:r.webUrl,state:r.state.toLowerCase(),draft:r.draft,conflicts:r.conflicts||r.mergeStatusEnum===qe,conflictsKnown:r.mergeStatusEnum!==qe&&!er.has(r.detailedMergeStatus??""),approved:r.approved===!0&&o&&i.length===0,hasApprovals:o,approvalRequirementsSatisfied:r.approved,awaitingReviewers:i,reviewersComplete:!0,reviewerIDs:(r.reviewers?.nodes??[]).flatMap(a=>a.id??[]),mergeStatus:r.detailedMergeStatus??void 0,targetProject:r.targetProject.fullPath,targetBranch:r.targetBranch,...r.sourceProject?{sourceProject:r.sourceProject.fullPath}:{},sourceBranch:r.sourceBranch,headSha:r.diffHeadSha??void 0,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt??void 0,pipeline:n?{status:n.status,label:n.detailedStatus?.label??n.status.toLowerCase().replace(/_/g," "),url:n.path?`https://${t}${n.path}`:void 0,...cr(t,n)}:void 0,unresolvedThreads:s.count,threadsComplete:s.complete,duoReviewState:r.reviewers?.nodes.find(a=>a.type==="DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState??void 0}}}const pr="copilot-pull-request-reviewer[bot]",Oe=`number title url state isDraft mergeable reviewDecision headRefOid headRefName
80
+ headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
81
+ author { ... on User { id } ... on Bot { id } }
82
+ reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
83
+ reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
84
+ latestReviews(first:100) { nodes { author { ... on User { id } } } }
85
+ copilotReviews: reviews(last:1, author:"${pr}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } } }
86
+ commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
87
+ nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } }
88
+ pageInfo { hasNextPage endCursor }
89
+ } } } } }`,te=50;function re(e,t){return async(r,s,n)=>{const o=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[d,m]of Object.entries(n))o.push(typeof m=="number"?"-F":"-f",`${d}=${m}`);const i=await e("gh",o,t);let a;try{a=JSON.parse(i.stdout)}catch{throw xe(i.stderr,i.code)}const c=(a.errors??[]).filter(d=>d.type!=="NOT_FOUND");if(!a.data||c.length||i.code!==0&&!a.errors?.length)throw xe(c[0]?.message??i.stderr,i.code);return a.data}}function xe(e,t){const r=e.trim()||`gh exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new x("missing-gh","gh is not installed"):/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(r)?new x("auth","GitHub authentication failed. Run `gh auth status`."):/429|rate limit|too many requests/i.test(r)?new x("rate-limit","GitHub rate limit reached"):new x("request",r.split(`
90
+ `)[0])}const fr=["FAILURE","ERROR","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","STALE"],hr=["SUCCESS","NEUTRAL","SKIPPED","FAILURE","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","STALE"],mr=["SUCCESS","FAILURE","ERROR","PENDING","EXPECTED"];function gr(e,t,r,s){const n=f=>`${f} check${f===1?"":"s"}`,o=e.filter(f=>fr.includes(f.conclusion??f.state??"")),i=o.length,a=s?{id:s,failedJobs:o.flatMap(f=>{const g=f.name??f.context,S=f.detailsUrl??f.targetUrl;return g?[{...f.id?{id:f.id}:{},name:g,...S?{url:S}:{}}]:[]}),failedJobsComplete:t}:{},c=e.filter(f=>f.status?f.status!=="COMPLETED":["PENDING","EXPECTED"].includes(f.state??"")).length,d=e.some(f=>f.status==="COMPLETED"?!hr.includes(f.conclusion??""):!f.status&&!mr.includes(f.state??""));return i?{status:"FAILED",label:`${n(i)} failed${c?`, ${n(c)} pending`:""}${t?"":" (partial)"}`,url:r,...a,running:c>0}:c||!t||d?{status:"PENDING",label:`${c?`${n(c)} pending`:"unknown"}${t?"":" (partial)"}`,url:r,...a}:{status:"SUCCESS",label:[["SUCCESS","passed"],["SKIPPED","skipped"],["NEUTRAL","neutral"]].flatMap(([f,g])=>{const S=e.filter(v=>(v.conclusion??v.state)===f).length;return S?[`${n(S)} ${g}`]:[]}).join(", ")||"0 checks",url:r,...a}}function Ue(e,t){const r=fe("github",e,t);return r&&!G.recognizes(r.host)?r:void 0}const ae={kind:"github",noun:"PR",ci:"checks",recognizes:()=>!1,open:(e,t)=>new $r(re(e,t)),owns:ze("github"),parseUrl:e=>Ue(e,/^\/([^/]+\/[^/]+)\/pull\/([1-9]\d*)\/?$/),parseIssueUrl:e=>Ue(e,/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/),reference:e=>`#${e}`,issueReference:e=>`#${e}`,titleReferences:e=>We(e,"#"),indicators:e=>e.reviewDecision==="CHANGES_REQUESTED"?[{text:"changes requested",tone:"warning",essential:!0}]:[],details:e=>[`Review decision: ${e.reviewDecision?he(e.reviewDecision):"not reported"}`],automatedReview:{name:"GitHub Copilot",status:e=>wr(e.copilotReview)},feedback:{async viewerID(e,t,r){return(await B(re(e,t))(r,N("query { viewer { id } }"),{})).viewer?.id},async reviewerID(e,t,r,s){const n=await e("gh",["api","--hostname",r,`users/${encodeURIComponent(s)}`],t);if(n.code!==0)throw new Error("Could not resolve the GitHub reviewer account");const o=JSON.parse(n.stdout);return o.login?.toLowerCase()===s.toLowerCase()?o.node_id:void 0},async fetch(e,t,r){const s=ae.parseUrl(r.url);return s?kt(re(e,t),s.host,s.project,s.iid):void 0},async details(e,t,r,s){const n=ae.parseUrl(r.url);return n?It(re(e,t),n.host,s):[]}}};function wr(e){if(!e)return;const t=e.comments>0&&!e.dismissed,r=e.dismissed?"dismissed":t?"commented":"no comments",s=e.reviewID?{id:e.reviewID,feedback:t,label:r}:void 0;if(e.requested)return{state:"running",label:"reviewing",completed:s};if(s)return{state:t?"feedback":"settled",label:r,completed:s}}const br=e=>/^copilot-pull-request-reviewer(\[bot\])?$/i.test(e??"");function vr(e){const t=e.reviewRequests.nodes.some(s=>br(s.requestedReviewer?.login)),r=e.copilotReviews?.nodes?.find(s=>s);if(!(!t&&!r))return{requested:t,reviewID:r?.id,comments:r?.comments.totalCount??0,...r?.state==="DISMISSED"?{dismissed:!0}:{}}}class $r{traits=ae;graphql;constructor(t){this.graphql=B(t)}async findByNumber(t,r){for(const s of t){const[n,o]=s.path.split("/"),a=(await this.graphql(s.host,N(`query($owner:String!,$repo:String!,$number:Int!) {
91
+ repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${Oe} } }
92
+ }`),{owner:n,repo:o,number:Number(r)})).repository?.pullRequest;if(a)return this.normalize(s.host,a)}}async findNumberByBranch(t){let r;for(const s of t.targets){const[n,o]=s.path.split("/"),a=(await this.graphql(s.host,N(`query($owner:String!,$repo:String!,$branch:String!) {
93
+ repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch,orderBy:{field:UPDATED_AT,direction:DESC}) {
94
+ nodes { number updatedAt headRepository { nameWithOwner } }
95
+ } } }`),{owner:n,repo:o,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const c of a)c.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||c.updatedAt>r.updatedAt)&&(r=c)}return r?String(r.number):void 0}async sourceBranch(t){const[r,s]=t.project.split("/");return(await this.graphql(t.host,N(`query($owner:String!,$repo:String!,$number:Int!) {
96
+ repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefName } }
97
+ }`),{owner:r,repo:s,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async findByBranch(t){const r=new Map;for(const s of t.targets){const[n,o]=s.path.split("/");let i,a=!1;for(let c=0;c<te;c++){const m=(await this.graphql(s.host,N(`query($owner:String!,$repo:String!,$branch:String!${i?",$after:String!":""}) {
98
+ repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${i?",after:$after":""}) {
99
+ nodes { ${Oe} } pageInfo { hasNextPage endCursor }
100
+ } } }`),{owner:n,repo:o,branch:t.sourceBranch,...i?{after:i}:{}})).repository?.pullRequests;if(!m)throw new x("request","GitHub repository unavailable");for(const f of m.nodes)f.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(r.has(f.url)||r.set(f.url,await this.normalize(s.host,f)));if(!m.pageInfo?.hasNextPage){a=!0;break}if(i=m.pageInfo.endCursor,!i)break}if(!a)throw new x("request","GitHub PR discovery exceeded its pagination limit")}return[...r.values()].sort((s,n)=>(n.updatedAt??"").localeCompare(s.updatedAt??""))}async threads(t,r){const[s,n]=r.baseRepository.nameWithOwner.split("/"),o=[...r.reviewThreads.nodes];let i=r.reviewThreads.pageInfo;for(let a=1;i?.hasNextPage&&i.endCursor&&a<te;a++){const d=(await this.graphql(t,N(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
101
+ repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
102
+ reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
103
+ } } }`),{owner:s,repo:n,number:r.number,after:i.endCursor})).repository?.pullRequest?.reviewThreads;if(!d)break;o.push(...d.nodes),i=d.pageInfo}return{unresolved:o.filter(a=>!a.isResolved).length,complete:!i?.hasNextPage}}async contexts(t,r){const[s,n]=r.baseRepository.nameWithOwner.split("/"),o=r.commits.nodes[0]?.commit.statusCheckRollup?.contexts,i=[...o?.nodes??[]];let a=o?.pageInfo;for(let c=1;a?.hasNextPage&&a.endCursor&&c<te;c++){const m=(await this.graphql(t,N(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
104
+ repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
105
+ contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
106
+ } } } } }`),{owner:s,repo:n,oid:r.headRefOid,after:a.endCursor})).repository?.object?.statusCheckRollup?.contexts;if(!m)break;i.push(...m.nodes),a=m.pageInfo}return{nodes:i,complete:!a?.hasNextPage}}async reviewers(t,r){const s=[...r.reviewRequests.nodes];let n=r.reviewRequests.pageInfo;for(let o=1;n?.hasNextPage&&o<te;o++){if(!n.endCursor)throw new x("request","GitHub reviewer pagination cursor missing");const[i,a]=r.baseRepository.nameWithOwner.split("/"),d=(await this.graphql(t,N(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
107
+ repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
108
+ reviewRequests(first:100,after:$after) {
109
+ nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } }
110
+ pageInfo { hasNextPage endCursor }
111
+ }
112
+ } }
113
+ }`),{owner:i,repo:a,number:r.number,after:n.endCursor})).repository?.pullRequest?.reviewRequests;if(!d)throw new x("request","GitHub reviewers unavailable");s.push(...d.nodes),n=d.pageInfo}if(n?.hasNextPage)throw new x("request","GitHub reviewers exceeded the pagination limit");return{nodes:s,pageInfo:n}}async normalize(t,r){const s=await this.reviewers(t,r),[n,o]=[await this.threads(t,r),await this.contexts(t,r)];return{forge:"github",iid:String(r.number),title:r.title,url:r.url,state:r.state==="OPEN"?"opened":r.state.toLowerCase(),draft:r.isDraft,conflicts:r.mergeable==="CONFLICTING",conflictsKnown:r.mergeable!=="UNKNOWN",approved:r.reviewDecision==="APPROVED",reviewDecision:r.reviewDecision??void 0,copilotReview:vr({...r,reviewRequests:s}),awaitingReviewers:s.nodes.flatMap(i=>{const a=i.requestedReviewer;return a?.__typename==="Bot"?[]:a?.login?[a.login]:a?.name?[a.name]:[]}),reviewersComplete:!s.pageInfo?.hasNextPage,reviewerIDs:[...new Set([...s.nodes.flatMap(i=>i.requestedReviewer?.__typename==="User"?i.requestedReviewer.id??[]:[]),...(r.latestReviews?.nodes??[]).flatMap(i=>i?.author?.id??[])])],targetProject:r.baseRepository.nameWithOwner,targetBranch:r.baseRefName,...r.headRepository?{sourceProject:r.headRepository.nameWithOwner}:{},sourceBranch:r.headRefName,headSha:r.headRefOid,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt,pipeline:o.nodes.length||!o.complete?gr(o.nodes,o.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:n.unresolved,threadsComplete:n.complete}}}const yr={gitlab:G,github:ae},F=e=>yr[e.forge],ce=e=>F(e).reference(e.iid);function le(e){const t=F(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const Me={url:{type:"string"},issueUrl:{type:"string"}},je={type:"object",properties:{...Me,targets:{type:"array",items:{type:"object",properties:Me,required:["url"],additionalProperties:!1}}},additionalProperties:!1},ne={type:"string"},we={type:"object",title:"Snapshot"},V={type:"object",title:"InboxState"},Sr={type:"object",properties:{enabled:{type:"boolean"},snapshot:we},required:["enabled","snapshot"],additionalProperties:!1},Cr={id:"opencode-forgekeeper",methods:{monitoringStatus:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:{type:"object",title:"MonitoringStatus"}},feedback:{input:{type:"object",additionalProperties:!1},output:V},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:V},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:V},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:V},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:V},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:je},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:ne},visible:ne},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:we}},required:["enabled","statuses"],additionalProperties:!1}},release:{input:{type:"object",properties:{clientID:{type:"string"}},required:["clientID"],additionalProperties:!1},output:{type:"object",additionalProperties:!1}},refresh:{input:{type:"object",properties:{key:ne},required:["key"],additionalProperties:!1},output:Sr}},events:{feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...je.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:ne,snapshot:we},required:["directory","key","snapshot"],additionalProperties:!1}},notice:{schema:{type:"object",properties:{sessionID:{type:"string"},title:{type:"string"},message:{type:"string"},variant:{type:"string",enum:["info","error"]}},required:["message","variant"],additionalProperties:!1}}}},Rr="",et=6e4,Be=(e,t)=>e.directory===t.directory&&e.key===t.key,X=e=>JSON.stringify([e.directory,e.key]);function Er(e){const t=e.now??Date.now,r=e.setTimer??((p,$)=>setTimeout(p,$)),s=e.clearTimer??(p=>clearTimeout(p)),n=e.defer??queueMicrotask,o=new Map,i=new Map,a=new Map;let c,d=!1;const m=p=>i.get(p.directory)?.has(p.key)===!0;function f(p,$){const E=X(p);($.revision??-1)>=(o.get(E)?.revision??-1)&&o.set(E,$)}function g(p,$){const A={kind:"request",message:`PR/MR status service unavailable: ${$ instanceof Error?$.message:String($)}`,at:t()};for(const H of i.get(p)??[]){const U=X({directory:p,key:H});o.set(U,{...o.get(U)??{},loading:!1,error:A})}e.onChange()}const S=new Map,v=new Map;function q(p){const $=(S.get(p)??0)+1;S.set(p,$);const E=v.get(p);E!==void 0&&s(E),v.set(p,r(()=>{_(p)},Math.min(et,1e3*2**$)))}async function _(p){if(d)return;const $=v.get(p);$!==void 0&&s($),v.delete(p);const E=[...i.get(p)??[]];try{const A=await e.watch(p,{clientID:e.clientID,keys:E,...c?.directory===p?{visible:c.key}:{}});if(d)return;S.delete(p),a.set(p,A.enabled);for(const[H,U]of Object.entries(A.statuses))m({directory:p,key:H})&&f({directory:p,key:H},U);e.onChange()}catch(A){if(d)return;g(p,A),q(p)}}const L=new Set;function O(p){L.has(p)||(L.add(p),n(()=>{L.delete(p),_(p)}))}return{snapshot:p=>o.get(X(p))??{loading:!1},enabled:p=>a.get(p)??!0,show(p){if(p.key!==Rr)for(const[E,A]of i)E===p.directory||!A.delete(p.key)||(o.delete(X({directory:E,key:p.key})),c&&Be(c,{directory:E,key:p.key})&&(c=void 0),O(E));const $=i.get(p.directory)??new Set;i.set(p.directory,$),$.add(p.key),c=p,O(p.directory)},hide(p){c&&Be(c,p)&&(c=void 0),O(p.directory)},async refresh(p){const $=X(p);o.set($,{...o.get($)??{},loading:!0}),e.onChange();try{const E=await e.refresh(p.directory,p.key);if(d)return;a.set(p.directory,E.enabled),f(p,E.snapshot),e.onChange()}catch(E){if(d)return;g(p.directory,E)}},heartbeat(){for(const p of i.keys())_(p)},receive(p,$,E){m({directory:p,key:$})&&(f({directory:p,key:$},E),e.onChange())},hasShown:p=>[...i.values()].some($=>$.has(p)),dispose(){d=!0;for(const p of v.values())s(p);for(const p of i.keys())e.release(p,e.clientID).catch(()=>{})}}}const oe=e=>({location:{directory:e}}),Ir=async(e,t)=>await e.feedback({},oe(t));function kr(e){let t,r=0;const s=new Map;let n;return{get client(){return t?.client},connect(o){t?.dispose(),t=_r(o,{...e,clientID:`${e.clientID}:${++r}`});for(const i of s.values())t.client.show(i),t.client.hide(i);n&&t.client.show(n),e.onChange()},show(o){s.set(o.key,o),n=o,t?.client.show(o)},hide(o){n?.key===o.key&&n.directory===o.directory&&(n=void 0),t?.client.hide(o)},dispose(){t?.dispose(),t=void 0}}}function Pr(e){const t=new Map;let r=0;const s=async n=>{const o=(t.get(n)??0)+1;t.set(n,o);const i=r,a=()=>i===r&&t.get(n)===o;try{const c=await e.load(n);a()&&e.changed(n,c)}catch(c){a()&&e.failed(n,c instanceof Error?c.message:String(c))}};return{reload:s,has:n=>t.has(n),refresh:()=>Promise.all([...t.keys()].map(s)),invalidate(){r++}}}function _r(e,t){const r=e,s=Er({clientID:t.clientID,watch:async(i,a)=>await r.watch(a,oe(i)),refresh:async(i,a)=>await r.refresh({key:a},oe(i)),release:(i,a)=>r.release({clientID:a},oe(i)),onChange:t.onChange}),n=setInterval(()=>{s.heartbeat(),t.heartbeat?.()},et),o=e.events.on("status",i=>{const{directory:a,key:c,snapshot:d}=i.data;s.receive(a,c,d)});return{client:s,dispose(){clearInterval(n),o(),s.dispose()}}}const Nr=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,Fe=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),Dr=e=>e.postedAt!==void 0?`Latest comment: ${Fe(e.postedAt)}`:`Detected: ${Fe(e.at)}`;function Ar(e,t){const r=e.items.filter(s=>s.sessionID===t).length;if(!(!t||r===0))return`${r} review update${r===1?"":"s"}${e.paused?" (paused)":""}`}function Tr(e){return[...new Set([e.url,...e.links])].filter(t=>{try{const r=new URL(t);return r.protocol==="https:"&&r.origin===new URL(e.url).origin&&!r.username&&!r.password}catch{return!1}})}function qr(e){const t=Tr(e),r=t.filter(n=>n!==e.url),s=e.kind==="ci-failed";return[...r.map((n,o)=>({title:`${s?"Failed job":"Comment"} ${r.length>1?`${o+1} of ${r.length} `:""}(${s?new URL(n).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(n).hash||"no anchor"})`,description:n,value:n})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Lr=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Re(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Lr.has(e.status)?"warning":"muted":"muted"}const tt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Or=e=>e.charAt(0).toUpperCase()+e.slice(1),xr={success:"CI ✓",error:"CI ✗",warning:"CI …"};function Ur(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}function Mr(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const de=e=>({text:ce(e),tone:"muted",url:e.url,essential:!0});function jr(e){const t=Re(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:xr[t],tone:t,url:e.pipeline.url}:{text:`no ${F(e).ci}`,compact:"no CI",tone:t}}function Br(e){const t=new Set(e.map(g=>F(g).noun)),r=t.size===1?[...t][0]:"PR/MR",s=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,n=e.filter(g=>g.state==="opened"),o=[{text:s,tone:"muted",essential:!0}],i=n.filter(g=>le(g)?.state==="running").length;i&&o.push({text:`🤖 ${i} reviewing`,compact:`🤖 ${i}`,tone:"warning",essential:!0});const a=n.filter(g=>Re(g.pipeline)==="error").length;a&&o.push({text:`${a} CI failed`,compact:`CI ✗ ${a}`,tone:"error"});const c=n.filter(g=>g.conflicts).length;c&&o.push({text:tt(c,"conflict"),tone:"error",essential:!0});const d=n.filter(g=>g.approved&&g.awaitingReviewers.length===0).length;d&&o.push({text:`${d} approved`,tone:"success"});const m=e.filter(g=>g.state==="merged").length;m&&o.push({text:`${m} merged`,tone:"success"});const f=e.length-n.length-m;return f&&o.push({text:`${f} closed`,tone:"muted"}),o}function Fr(e){const{lookup:t,error:r}=e,s=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&s.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const n=t.requests;if(t.explicitTarget&&n.length>1)return[...Br(n),...s];if(n.length>1){const a=F(n[0]).noun;return[...n.map(de),{text:`${tt(n.length,`open ${a}`)}, run /${a.toLowerCase()}-status`,tone:"warning"},...s]}const[o]=n;if(o.state!=="opened")return[de(o),{text:o.state,tone:o.state==="merged"?"success":"muted",essential:!0},...s];const i=[de(o),jr(o)];if(o.unresolvedThreads>0||!o.threadsComplete){const a=Mr(o);i.push({text:a,compact:a.replace("unresolved ",""),tone:"warning"})}return le(o)?.state==="running"&&i.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),i.push(...F(o).indicators(o)),o.conflicts&&i.push({text:"conflicts",tone:"error",essential:!0}),o.conflictsKnown||i.push({text:"mergeability unknown",tone:"muted"}),o.awaitingReviewers.length?i.push({text:Ur(o.awaitingReviewers),tone:"muted"}):o.approved&&i.push({text:"approved",tone:"success"}),[...i,...s]}const Ge=e=>new Date(e).toLocaleTimeString();function Gr(e,t){const r=F(e),s=[`${ce(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} → ${e.targetBranch}`,`${Or(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${W(e.draft)} · Conflicts: ${e.conflictsKnown?W(e.conflicts):"unknown"}`,...r.details(e)],n=le(e);return n&&s.push(`${n.name} review: ${n.label}`),e.awaitingReviewers.length&&s.push(`Awaiting review: ${e.awaitingReviewers.map(o=>`@${o}`).join(", ")}`),e.reviewersComplete||s.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&s.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),s.push(e.url),s}function Hr(e){const{lookup:t,error:r,fetchedAt:s}=e,n=[];if(!t)n.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")n.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:o,sessionTarget:i,requests:a}=t;if(o){const c=o.branch===o.sourceBranch?o.branch:`${o.branch} (pushes to ${o.sourceBranch})`;n.push(`Branch: ${c} in ${o.source.path}`),a.length===0&&n.push("","No open PR/MR for this branch.")}else i&&n.push(`Session target: ${i}`);for(const{url:c,reason:d}of t.failed??[])n.push(`Unavailable: ${c} (${d})`);for(const c of a)n.push("",...Gr(c,o?.head??""))}return r&&n.push("",`Last refresh failed at ${Ge(r.at)}: ${r.message}`),s!==void 0&&n.push("",`Last fetched: ${Ge(s)}`),n.join(`
114
+ `)}function zr(e,t){const{sessionID:r}=e;r&&!t.hasShown(r)||(r&&e.variant==="info"&&t.openTab(r),t.toast({...e.title?{title:e.title}:{},message:e.message,variant:e.variant}))}var Wr=l.template("<a><b>"),Jr=l.template("<div><span class=fk-label>: "),Qr=l.template("<b>"),Kr=l.template("<div class=fk-warning>Reviewer list is partial"),Vr=l.template("<div class=fk-warning>Local HEAD differs from the <!> head commit (unpushed or not fetched)"),Xr=l.template("<div class=fk-card><a><b> </b></a><section></section><section><b>Review and approval"),pe=l.template("<div>"),Yr=l.template("<div class=forgekeeper-panel><header><h2>PR/MR status"),Zr=l.template("<div>PR/MR status is off."),en=l.template("<div class=fk-muted>No PR/MR status available."),tn=l.template("<div class=fk-muted>Last fetched: "),rn=l.template("<section>"),nn=l.template('<div class="fk-warning fk-pre"><b>Unavailable'),sn=l.template('<div class="fk-error fk-pre"><b>Last refresh failed at '),on=l.template("<div class=fk-card><b></b><div class=fk-muted></div><section></section><div class=fk-actions>"),an=l.template("<a>"),cn=l.template("<div class=forgekeeper-panel><header><h2>Review updates"),ln=l.template("<div class=fk-error>Could not load review updates: <!>. Retrying automatically."),un=l.template("<div class=fk-muted>");const dn=`
115
+ .forgekeeper-panel { display: flex; flex-direction: column; gap: 12px; padding: 12px 16px; overflow-y: auto; height: 100%; font-size: 13px; line-height: 1.5; color: var(--v2-text-text-base); }
116
+ .forgekeeper-panel header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
117
+ .forgekeeper-panel h2 { font-size: 13px; font-weight: 600; margin: 0; }
118
+ .forgekeeper-panel section { display: flex; flex-direction: column; gap: 2px; }
119
+ .forgekeeper-panel .fk-card { border: 1px solid var(--v2-border-border-muted); border-radius: 8px; padding: 8px 10px; display: flex; flex-direction: column; gap: 6px; }
120
+ .forgekeeper-panel .fk-actions { display: flex; flex-wrap: wrap; gap: 6px; }
121
+ .forgekeeper-panel .fk-muted { color: var(--v2-text-text-muted); }
122
+ .forgekeeper-panel .fk-label { color: var(--v2-text-text-muted); }
123
+ .forgekeeper-panel .fk-success { color: var(--v2-state-fg-success); }
124
+ .forgekeeper-panel .fk-warning { color: var(--v2-state-fg-warning); }
125
+ .forgekeeper-panel .fk-error { color: var(--v2-state-fg-danger); }
126
+ .forgekeeper-panel a { color: var(--v2-text-text-accent); cursor: pointer; text-decoration: underline; }
127
+ .forgekeeper-panel .fk-pre { white-space: pre-wrap; }
128
+ `,Y="status",Z="feedback",pn={items:[],paused:!1},He=e=>e==="success"?"fk-success":e==="warning"?"fk-warning":e==="error"?"fk-error":e==="muted"?"fk-muted":void 0;function fn(e){if(e.includes("error"))return"danger";if(e.includes("warning"))return"warning";if(e.includes("success"))return"success"}const hn=j.Plugin.define({setup(e){e.add(j.Style,dn);const t=()=>e.client.rpc(Cr),r=u=>({location:{directory:u}}),[s,n]=P.createSignal(0),[o,i]=Pe.createStore({}),[a,c]=Pe.createStore({}),d=Pr({load:u=>Ir(t(),u),changed:(u,h)=>{i(u,h),c(u,void 0)},failed:(u,h)=>c(u,h)}),m=d.reload,f=kr({clientID:Nr(),onChange:()=>n(u=>u+1),heartbeat:()=>{d.refresh()}}),g=()=>f.client,S=u=>u.server.builtin,v=u=>u.location?.directory??u.directory,q=u=>({directory:v(u),key:u.id}),_=u=>(s(),g()?.snapshot(u)??{loading:!1}),L=u=>(s(),g()?.enabled(u)??!0),O=u=>o[u]??pn,p=u=>{const h=_(u).lookup;return h?.kind==="found"?h.requests:[]},$=()=>{const u=e.sessions.current();return u&&S(u)?u:void 0};j.createKeyed(()=>{const u=$();return u?JSON.stringify([v(u),u.id]):void 0},u=>{const[h,b]=JSON.parse(u),y={directory:h,key:b};f.show(y),m(h),P.onCleanup(()=>f.hide(y))});const E=(u,h=$())=>{h&&e.layout.open(`${e.id}:${u}`,h,{tab:"select"})},A=u=>L(u)?!1:(e.toast.show({title:"PR/MR status is off in the plugin's options (status: false)"}),!0);e.add(j.ComposerPill,{id:"status",show:u=>H(u.session)});function H(u){if(!S(u))return;const h=q(u);if(!L(h.directory))return;const b=Fr(_(h)),y=Ar(O(h.directory),u.id);if(!(!b.length&&!y))return{icon:"review",label:[...b.map(w=>w.compact??w.text),y].filter(Boolean).join(" · "),tone:fn(b.map(w=>w.tone)),title:"PR/MR status",rows:[...b.map((w,I)=>({id:`segment-${I}`,label:w.text,...w.url?{icon:"outline-arrow-up-right"}:{},...w.tone==="success"||w.tone==="warning"?{tone:w.tone}:w.tone==="error"?{tone:"danger"}:{},...w.url?{run:()=>e.system.openExternal(w.url)}:{}})),{id:"details",label:"Show PR/MR status",icon:"status",run:()=>E(Y,u)},...y?[{id:"feedback",label:y,icon:"comment",run:()=>E(Z,u)}]:[]]}}const U=e.ui;function M(u){return(()=>{var h=Jr(),b=h.firstChild,y=b.firstChild;return l.insert(b,()=>u.label,y),l.insert(h,l.createComponent(P.Show,{get when(){return u.url},get fallback(){return(()=>{var w=Qr();return l.insert(w,()=>u.value),l.effect(()=>l.className(w,He(u.tone))),w})()},get children(){var w=Wr(),I=w.firstChild;return w.$$click=()=>e.system.openExternal(u.url),l.insert(I,()=>u.value),l.effect(()=>l.className(w,He(u.tone))),w}}),null),h})()}function rt(u){const h=()=>u.request,b=()=>F(h()),y=()=>le(h());return(()=>{var w=Xr(),I=w.firstChild,k=I.firstChild,C=k.firstChild,R=I.nextSibling,T=R.nextSibling;return T.firstChild,I.$$click=()=>e.system.openExternal(h().url),l.insert(k,()=>ce(h()),C),l.insert(k,()=>h().title,null),l.insert(R,l.createComponent(M,{label:"State",get value(){return h().state},get tone(){return h().state==="merged"?"success":void 0}}),null),l.insert(R,l.createComponent(M,{label:"Target",get value(){return`${h().targetProject} → ${h().targetBranch}`}}),null),l.insert(R,l.createComponent(M,{get label(){return b().ci.charAt(0).toUpperCase()+b().ci.slice(1)},get value(){return h().pipeline?.label??"none"},get tone(){return Re(h().pipeline)},get url(){return h().pipeline?.url}}),null),l.insert(R,l.createComponent(M,{label:"Unresolved threads",get value(){return`${h().unresolvedThreads}${h().threadsComplete?"":"+"}`},get tone(){return h().unresolvedThreads||!h().threadsComplete?"warning":void 0}}),null),l.insert(R,l.createComponent(M,{label:"Draft",get value(){return W(h().draft)},get tone(){return h().draft?"warning":void 0}}),null),l.insert(R,l.createComponent(M,{label:"Conflicts",get value(){return l.memo(()=>!!h().conflictsKnown)()?W(h().conflicts):"unknown"},get tone(){return h().conflicts?"error":void 0}}),null),l.insert(T,l.createComponent(P.For,{get each(){return b().details(h())},children:D=>{const J=D.indexOf(": ");return J<0?(()=>{var Q=pe();return l.insert(Q,D),Q})():l.createComponent(M,{get label(){return D.slice(0,J)},get value(){return D.slice(J+2)}})}}),null),l.insert(T,l.createComponent(P.Show,{get when(){return y()},children:D=>l.createComponent(M,{get label(){return`${D().name} review`},get value(){return D().label},get tone(){return D().state==="running"?"warning":void 0}})}),null),l.insert(T,l.createComponent(P.Show,{get when(){return h().awaitingReviewers.length},get children(){return l.createComponent(M,{label:"Awaiting review",get value(){return h().awaitingReviewers.map(D=>`@${D}`).join(", ")}})}}),null),l.insert(w,l.createComponent(P.Show,{get when(){return!h().reviewersComplete},get children(){return Kr()}}),null),l.insert(w,l.createComponent(P.Show,{get when(){return l.memo(()=>!!(u.head&&h().headSha))()&&u.head!==h().headSha},get children(){var D=Vr(),J=D.firstChild,Q=J.nextSibling;return Q.nextSibling,l.insert(D,()=>b().noun,Q),D}}),null),w})()}function nt(u){const h=P.createMemo(()=>q(u.session),void 0,{equals:(w,I)=>w.directory===I.directory&&w.key===I.key}),b=P.createMemo(()=>_(h())),y=()=>{const w=b().lookup;return w?.kind==="found"?w:void 0};return(()=>{var w=Yr(),I=w.firstChild;return I.firstChild,l.insert(I,l.createComponent(U.Button,{size:"small",icon:"refresh",get busy(){return b().loading},onClick:()=>{g()?.refresh(h())},children:"Refresh"}),null),l.insert(w,l.createComponent(P.Show,{get when(){return L(h().directory)},get fallback(){return Zr()},get children(){return l.createComponent(P.Show,{get when(){return y()},get fallback(){return(()=>{var k=pe();return l.insert(k,()=>Hr(b())),l.effect(()=>l.className(k,`fk-pre ${b().error?"fk-error":"fk-muted"}`)),k})()},children:k=>[l.createComponent(P.Show,{get when(){return k().repository},children:C=>(()=>{var R=rn();return l.insert(R,l.createComponent(M,{label:"Repository",get value(){return C().source.path}}),null),l.insert(R,l.createComponent(M,{label:"Branch",get value(){return l.memo(()=>C().branch===C().sourceBranch)()?C().branch:`${C().branch} (pushes to ${C().sourceBranch})`}}),null),R})()}),l.createComponent(P.Show,{get when(){return l.memo(()=>!k().repository)()&&k().sessionTarget},get children(){return l.createComponent(M,{label:"Session target",get value(){return k().sessionTarget}})}}),l.createComponent(P.For,{get each(){return k().failed??[]},children:C=>(()=>{var R=nn();return R.firstChild,l.insert(R,()=>`
129
+ ${C.url}
130
+ ${C.reason}`,null),R})()}),l.createComponent(P.Show,{get when(){return k().requests.length===0},get children(){return en()}}),l.createComponent(P.For,{get each(){return k().requests},children:C=>l.createComponent(rt,{request:C,get head(){return k().repository?.head}})}),l.createComponent(P.Show,{get when(){return b().error},children:C=>(()=>{var R=sn(),T=R.firstChild;return T.firstChild,l.insert(T,()=>new Date(C().at).toLocaleTimeString(),null),l.insert(R,()=>`
131
+ ${C().message}`,null),R})()}),l.createComponent(P.Show,{get when(){return b().fetchedAt!==void 0},get children(){var C=tn();return C.firstChild,l.insert(C,()=>new Date(b().fetchedAt).toLocaleTimeString(),null),C}})]})}}),null),w})()}async function Ee(u,h,b){try{await t()[h](b,r(u)),await m(u)}catch(y){e.toast.show({title:y instanceof Error?y.message:String(y),variant:"error"})}}function st(u){const h=()=>u.item,b=()=>[h().sessionID===u.current?"This session":void 0,Dr(h()),h().automation?`${h().automation.state}${h().automation.reason?`: ${h().automation.reason}`:""}`:void 0].filter(Boolean).join(" · "),y=(w,I={})=>Ee(u.directory,w,{id:h().id,...I});return(()=>{var w=on(),I=w.firstChild,k=I.nextSibling,C=k.nextSibling,R=C.nextSibling;return l.insert(I,()=>h().title),l.insert(k,b),l.insert(w,l.createComponent(P.For,{get each(){return h().details??[]},children:T=>(()=>{var D=pe();return l.insert(D,T),D})()}),C),l.insert(C,l.createComponent(P.For,{get each(){return qr(h())},children:T=>(()=>{var D=an();return D.$$click=()=>e.system.openExternal(T.value),l.insert(D,()=>T.title),D})()})),l.insert(R,l.createComponent(P.Show,{get when(){return h().sessionID!==u.current},get children(){return l.createComponent(U.Button,{size:"small",onClick:()=>{const T=$()?.server.id;T&&e.tabs.open({server:T,id:h().sessionID},{focus:!0})},children:"Open session"})}}),null),l.insert(R,l.createComponent(U.Button,{size:"small",onClick:()=>{y("summarizeFeedback")},children:"Summarize in session"}),null),l.insert(R,l.createComponent(U.Button,{size:"small",onClick:()=>{y("actOnFeedback")},children:"Act on feedback"}),null),l.insert(R,l.createComponent(U.Button,{size:"small",onClick:async()=>{await e.dialogs.confirm({title:"Retry feedback work?",description:"Retry may repeat earlier changes. Inspect the session first.",confirm:"Retry",danger:!0})&&await y("actOnFeedback",{retry:!0})},children:"Retry"}),null),l.insert(R,l.createComponent(U.Button,{size:"small",onClick:()=>{y("acknowledgeFeedback")},children:"Acknowledge"}),null),w})()}function ot(u){const h=()=>v(u.session),b=()=>O(h());return(()=>{var y=cn(),w=y.firstChild,I=w.firstChild;return I.firstChild,l.insert(I,()=>b().paused?" (monitoring paused)":"",null),l.insert(w,l.createComponent(U.Button,{size:"small",onClick:()=>{Ee(h(),"pauseFeedback",{paused:!b().paused})},get children(){return b().paused?"Resume monitoring":"Pause monitoring"}}),null),l.insert(y,l.createComponent(P.Show,{get when(){return a[h()]},children:k=>(()=>{var C=ln(),R=C.firstChild,T=R.nextSibling;return T.nextSibling,l.insert(C,k,T),C})()}),null),l.insert(y,l.createComponent(P.Show,{get when(){return b().items.length},get fallback(){return l.createComponent(P.Show,{get when(){return!a[h()]},get children(){var k=un();return l.insert(k,()=>o[h()]?"No pending review updates in this checkout.":"Loading review updates…"),k}})},get children(){return l.createComponent(P.For,{get each(){return b().items},children:k=>l.createComponent(st,{item:k,get directory(){return h()},get current(){return u.session.id}})})}}),null),y})()}const Ie=(u,h)=>({id:u,title:h,closable:"hover"}),it=Ie(Y,"PR/MR status"),at=Ie(Z,"Review updates");e.add(j.Panel,{id:Y,region:"side",width:420,list:u=>u.open.includes(Y)?[it]:[],render:u=>l.createComponent(nt,{get session(){return u.session}})}),e.add(j.Panel,{id:Z,region:"side",width:420,list:u=>u.open.includes(Z)?[at]:[],render:u=>l.createComponent(ot,{get session(){return u.session}})}),e.add(j.Command,()=>({id:"status",title:"Show PR/MR status",group:"Forge",slash:{name:"forge-status"},enabled:!!$(),run:()=>{const u=$();!u||A(v(u))||(g()?.refresh(q(u)),E(Y,u))}})),e.add(j.Command,()=>({id:"feedback",title:"Show pending review feedback",group:"Forge",slash:{name:"forge-feedback"},enabled:!!$(),run:()=>{const u=$();u&&(m(v(u)),E(Z,u))}})),e.add(j.Command,()=>({id:"open",title:"Open PR/MR in browser",group:"Forge",slash:{name:"forge-open"},enabled:!!$(),run:async()=>{const u=$();if(!u||A(v(u)))return;const h=q(u);let b=p(h);if(b.length===0&&(await g()?.refresh(h),b=p(h)),b.length===0){e.toast.show({title:"No PR/MR for this session or branch"});return}const y=b.length===1?b[0].url:await e.dialogs.select({title:"Open PR/MR",options:b.map(w=>({title:`${ce(w)} ${w.title}`,description:w.targetProject,value:w.url}))});y&&e.system.openExternal(y)}}));const ke=()=>e.servers.list().map(u=>e.servers.get(u)).find(u=>u?.builtin);return j.createKeyed(()=>e.client,()=>{const u=t();d.invalidate(),f.connect(u),d.refresh();const h=[u.events.on("feedbackChanged",b=>{const{directory:y}=b.data;d.has(y)&&m(y)}),u.events.on("notice",b=>{const y=b.data;zr(y,{hasShown:w=>!!g()?.hasShown(w)||!!b.location?.directory&&d.has(b.location.directory),openTab:w=>{const I=ke()?.id;I&&e.tabs.open({server:I,id:w})},toast:({title:w,message:I,variant:k})=>{const C=ke()?.id,R=y.sessionID;e.toast.show({title:w??I,...w?{description:I}:{},variant:k==="error"?"error":"default",...C&&R?{actions:[{label:"Open session",run:()=>e.tabs.open({server:C,id:R},{focus:!0})}]}:{}}),e.attention.notify({title:w??"Forgekeeper",message:I,variant:k==="error"?"error":"default",...C&&R?{session:{server:C,id:R}}:{},id:`forgekeeper:${R??""}:${w??""}:${I}`})}})})];P.onCleanup(()=>{for(const b of h)b();d.invalidate(),f.dispose()})}),()=>{d.invalidate(),f.dispose()}}});l.delegateEvents(["click"]);exports.default=hn;