UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 23.3 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{l as resolveLeastPrivilegeOperatorScopesForMethod}from"./method-scopes-Dalbwzsv.mjs";import{f as withGatewayToolCallerIdentity,o as getGatewayToolCallerIdentity,t as captureGatewayToolCallerAssertion}from"./gateway-caller-context-Dw9IijqV.mjs";import{a as resolveConfiguredGitHubHost}from"./github-host-BIyVIYLv.mjs";import{c as prepareGitHubPublicationSession,d as readGitHubPublicationWorktreeOwner,n as currentGitHubPublicationConfig,t as assertExpectedSharedGitHubPublisher}from"./github-publication-availability-LlQ3BS1p.mjs";import{t as callGatewayTool}from"./gateway-Bf9f0Pcc.mjs";import{a as withInProcessGatewayDispatch}from"./server-plugin-in-process-dispatch-bWayi_W3.mjs";import{n as sessionPrAutoFixTarget}from"./session-pr-auto-fix-BHUpoNCd.mjs";import{r as projectGitHubPublicationResult}from"./github-publication-receipt-KjMQbHGW.mjs";import{r as pullRequestState,t as prepareSelectedGitHubPullRequestReader}from"./github-publication-selected-read-BsB3xNAm.mjs";import{t as GitHubPublicationReadUnavailableError}from"./github-publication-json-read-BYKGjBSc.mjs";import{r as prepareGitHubPublicationRequesterV2}from"./github-publication-requester-BoLRpUz5.mjs";import{i as readSharedGitHubPublication}from"./github-publication-inspect-BlrLFa2O.mjs";import{createHash}from"node:crypto"; //!src/gateway/github-publication-auto-fix-feedback.ts const unavailable=()=>new GitHubPublicationReadUnavailableError(`Auto-fix could not read current GitHub feedback; inspect repository access and retry.`);const fingerprint=e=>createHash(`sha256`).update(JSON.stringify(e)).digest(`hex`);const sourceNames=[`checks`,`comments`,`reviews`,`reviewThreads`];function connection(e){if(!isRecord(e)||!Array.isArray(e.nodes)||!e.nodes.every(isRecord)||!isRecord(e.pageInfo)||typeof e.pageInfo.hasNextPage!==`boolean`||e.pageInfo.hasNextPage&&typeof e.pageInfo.endCursor!==`string`)throw unavailable();return{nodes:e.nodes,next:e.pageInfo.hasNextPage?String(e.pageInfo.endCursor):null}}const commentFields=`id body updatedAt authorAssociation author { login __typename ... on Bot { databaseId } ... on User { databaseId } }`;const pageInfo=`pageInfo { hasNextPage endCursor }`;const compactFeedback=`.data.repository.pullRequest |= (if .comments then .comments.nodes |= map(. + {bodyTruncated: ((.body | length) > 2048)} | .body = .body[0:2048]) elif .reviews then .reviews.nodes |= map(. + {bodyTruncated: ((.body | length) > 2048)} | .body = .body[0:2048]) else . end) | if .data.node.comments then .data.node.comments.nodes |= map(. + {bodyTruncated: ((.body | length) > 2048)} | .body = .body[0:2048]) else . end`;function feedback(e,t,n,r){if(!isRecord(e.author)||typeof e.author.login!==`string`||typeof e.id!==`string`||typeof e.body!==`string`||typeof e.updatedAt!==`string`)throw unavailable();if(n!==void 0&&e.author.__typename===`Bot`&&e.author.databaseId===n)return;const i=[`OWNER`,`MEMBER`,`COLLABORATOR`].includes(String(e.authorAssociation));const a=r!==void 0&&e.author.__typename===`User`&&e.author.databaseId===r;const o=e.author.__typename===`Bot`&&Number.isSafeInteger(e.author.databaseId)&&t.includes(e.author.login);if(!i&&!o&&!a)return;if(!e.body.trim()||e.state===`APPROVED`||e.state===`DISMISSED`)return;return{id:e.id,revision:fingerprint([e.id,e.updatedAt]),author:e.author.login,body:e.body.slice(0,2048),truncated:e.bodyTruncated===true}}async function readPrAutoFixFeedback(e){const{previous:t,head:n,owner:r,repo:i,number:a,reader:o,pullRequest:s,producerId:c,humanAuthorId:l,retryable:u,attemptedFindings:d,dispositions:f,quietFindings:p}=e;const m=t?.version===3&&isRecord(t.scan)&&t.scan.head===n?structuredClone(t.scan):{head:n,source:0,cursor:null,digest:fingerprint([]),count:0,findings:[],checkDigest:fingerprint([]),failures:0,apps:[]};const h=/* @__PURE__ */ new Set;const observeThread=(e,t)=>{for(const n of[f,p]){const r=n.findIndex(t=>t.revision===e.revision);const i=n[r];if(i?.threadResolved===true&&!t){n.splice(r,1);h.add(e.id)}else if(i&&t)i.threadResolved=true}};const addFeedback=(e,t,n=false)=>{const r=feedback(e,m.apps,c,l);if(!r)return;if(t){r.threadId=t;observeThread(r,n)}if(f.some(e=>e.revision===r.revision))return;if(n)return;m.digest=fingerprint([m.digest,r.revision]);m.count++;if(!p.some(e=>e.revision===r.revision))m.findings.push(r)};const g=Date.now()+1e4;for(let e=0;e<32&&Date.now()<g&&m.source<sourceNames.length;e++){const e=sourceNames[m.source];let t;if(e===`checks`)t=`commits(last: 1) { nodes { commit { oid statusCheckRollup { contexts(first: 10, after: $cursor) { `+pageInfo+` nodes { ... on CheckRun { __typename id name status conclusion completedAt checkSuite { app { slug } repository { nameWithOwner } } } ... on StatusContext { __typename id context state createdAt } } } } } } }`;else if(e===`reviewThreads`)t=`reviewThreads(first: 1, after: $cursor) { `+pageInfo+` nodes { id isResolved } }`;else t=e+`(first: 3, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { id body updatedAt authorAssociation author { login __typename ... on Bot { databaseId } ... on User { databaseId } }`+(e===`reviews`?` state`:``)+` } }`;const c=m.thread?`query($id: ID!, $cursor: String) { node(id: $id) { ... on PullRequestReviewThread { id isResolved comments(first: 3, after: $cursor) { `+pageInfo+` nodes { `+commentFields+` } } } } }`:`query($owner: String!, $repo: String!, $number: Int!, $cursor: String) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { headRefOid `+t+` } } }`;const l=await o.readJson(`graphql`,{query:c,jq:compactFeedback,variables:m.thread?{id:m.thread.id,cursor:m.thread.cursor}:{owner:r,repo:i,number:a,cursor:m.cursor}});if(!isRecord(l)||l.errors||!isRecord(l.data))throw unavailable();if(m.thread){const e=l.data.node;if(!isRecord(e)||e.id!==m.thread.id||typeof e.isResolved!==`boolean`)throw unavailable();const t=connection(e.comments);for(const n of t.nodes)addFeedback(n,m.thread.id,e.isResolved);if(t.next)m.thread.cursor=t.next;else{m.cursor=m.thread.next;delete m.thread;if(!m.cursor)m.source++}if(m.findings.length)break;continue}const u=l.data.repository;if(!isRecord(u)||!isRecord(u.pullRequest))throw unavailable();const d=u.pullRequest;if(d.headRefOid!==n)throw new GitHubPublicationReadUnavailableError(`Auto-fix PR head changed during its feedback scan; retry a fresh observation.`);if(e===`checks`){const e=isRecord(d.commits)&&Array.isArray(d.commits.nodes)&&isRecord(d.commits.nodes[0])?d.commits.nodes[0].commit:void 0;if(!isRecord(e)||e.oid!==n)throw unavailable();if(e.statusCheckRollup===null){m.source++;continue}if(!isRecord(e.statusCheckRollup))throw unavailable();const t=connection(e.statusCheckRollup.contexts);for(const e of t.nodes){if(typeof e.id!==`string`||![`CheckRun`,`StatusContext`].includes(String(e.__typename)))throw unavailable();if(isRecord(e.checkSuite)&&isRecord(e.checkSuite.app)&&isRecord(e.checkSuite.repository)&&e.checkSuite.repository.nameWithOwner===s.repository&&typeof e.checkSuite.app.slug===`string`){const t=e.checkSuite.app.slug+`[bot]`;if(!m.apps.includes(t))m.apps.push(t)}if(e.__typename===`CheckRun`?e.status===`COMPLETED`&&[`FAILURE`,`TIMED_OUT`,`CANCELLED`,`ACTION_REQUIRED`,`STARTUP_FAILURE`,`STALE`].includes(String(e.conclusion)):[`ERROR`,`FAILURE`].includes(String(e.state))){m.failures++;m.checkDigest=fingerprint([m.checkDigest,e])}}m.cursor=t.next}else if(e===`reviewThreads`){const e=connection(d.reviewThreads);const t=e.nodes[0];if(t){if(typeof t.id!==`string`||typeof t.isResolved!==`boolean`)throw unavailable();m.thread={id:t.id,resolved:t.isResolved,next:e.next,cursor:null};continue}m.cursor=e.next}else{const t=connection(d[e]);for(const e of t.nodes)addFeedback(e);m.cursor=t.next}if(!m.cursor)m.source++;if(m.findings.length)break}const _=m.source===sourceNames.length;const v=_||m.findings.length>0||m.failures>0||u;const y=[...new Set([...m.findings,...d].flatMap(e=>[e.id,e.threadId]).filter(e=>typeof e===`string`))];let b=[];let x=false;if(v){const e=`number repository { nameWithOwner }`;let t=null;let f;let p;const g=[];const _=/* @__PURE__ */ new Set;const v=/* @__PURE__ */ new Set;const S=Date.now()+1e4;for(let s=0;;s++){if(s>=32||Date.now()>=S)throw unavailable();const c=await o.readJson(`graphql`,{query:`query($owner: String!, $repo: String!, $number: Int!, $ids: [ID!]!, $cursor: String) { nodes(ids: $ids) { ... on IssueComment { `+commentFields+` pullRequest { `+e+` } } `+`... on PullRequestReview { `+commentFields+` state pullRequest { `+e+` } } `+`... on PullRequestReviewComment { `+commentFields+` pullRequest { `+e+` } } `+`... on PullRequestReviewThread { id isResolved } } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { headRefOid commits(last: 1) { nodes { commit { oid statusCheckRollup { state contexts(first: 100, after: $cursor) { pageInfo { hasNextPage endCursor } totalCount nodes { ... on CheckRun { __typename id name status conclusion completedAt checkSuite { app { slug } repository { nameWithOwner } } } ... on StatusContext { __typename id context state createdAt } } } } } } } } } }`,variables:{owner:r,repo:i,number:a,ids:y,cursor:t},jq:`.data.nodes |= map(if .body then . + {bodyTruncated: ((.body | length) > 2048)} | .body = .body[0:2048] else . end)`});if(!isRecord(c)||c.errors||!isRecord(c.data)||!Array.isArray(c.data.nodes)||!c.data.nodes.every(e=>e===null||isRecord(e))||!isRecord(c.data.repository)||!isRecord(c.data.repository.pullRequest))throw unavailable();const l=c.data.nodes.filter(isRecord);if(s>0&&fingerprint(l)!==fingerprint(b))throw unavailable();b=l;const u=c.data.repository.pullRequest;const d=isRecord(u.commits)&&Array.isArray(u.commits.nodes)&&u.commits.nodes.length===1&&isRecord(u.commits.nodes[0])?u.commits.nodes[0].commit:void 0;if(u.headRefOid!==n||!isRecord(d)||d.oid!==n)throw unavailable();const m=d.statusCheckRollup;if(m===null&&s===0)break;if(!isRecord(m)||!isRecord(m.contexts))throw unavailable();const h=m.contexts.totalCount;if(typeof h!==`number`||!Number.isSafeInteger(h)||h<0||s>0&&(h!==f||m.state!==p))throw unavailable();f=h;p=m.state;const x=connection(m.contexts);if(x.nodes.length>100)throw unavailable();for(const e of x.nodes){if(typeof e.id!==`string`||_.has(e.id)||![`CheckRun`,`StatusContext`].includes(String(e.__typename)))throw unavailable();_.add(e.id);g.push(e)}if(g.length>h||!x.next&&g.length!==h)throw unavailable();if(!x.next)break;if(!x.nodes.length||g.length>=h||!x.next.trim()||v.has(x.next))throw unavailable();v.add(x.next);t=x.next}x=p===`SUCCESS`&&g.length>0&&g.every(e=>e.__typename===`CheckRun`?e.status===`COMPLETED`&&[`SUCCESS`,`NEUTRAL`,`SKIPPED`].includes(String(e.conclusion)):e.state===`SUCCESS`);m.failures=0;m.checkDigest=fingerprint([]);m.apps=[];for(const e of g){if(isRecord(e.checkSuite)&&isRecord(e.checkSuite.app)&&isRecord(e.checkSuite.repository)&&e.checkSuite.repository.nameWithOwner===s.repository&&typeof e.checkSuite.app.slug===`string`){const t=e.checkSuite.app.slug+`[bot]`;if(!m.apps.includes(t))m.apps.push(t)}if(e.__typename===`CheckRun`?e.status===`COMPLETED`&&[`FAILURE`,`TIMED_OUT`,`CANCELLED`,`ACTION_REQUIRED`,`STARTUP_FAILURE`,`STALE`].includes(String(e.conclusion)):[`ERROR`,`FAILURE`].includes(String(e.state))){m.failures++;m.checkDigest=fingerprint([m.checkDigest,e])}}const currentFinding=e=>{const t=b.find(t=>t.id===e.id);const n=t?.pullRequest??t?.issue;if(!t||!isRecord(n)||n.number!==a||!isRecord(n.repository)||n.repository.nameWithOwner!==s.repository)return;const r=feedback(t,m.apps,c,l);const i=typeof e.threadId===`string`?b.find(t=>t.id===e.threadId):void 0;if(r&&r.revision===e.revision&&typeof i?.isResolved===`boolean`)observeThread(r,i.isResolved);return r&&i?.isResolved!==true?{...r,...typeof e.threadId===`string`?{threadId:e.threadId}:{}}:void 0};const C=[...m.findings];for(const e of d){const t=currentFinding(e);if(t&&(u||h.has(t.id))&&!C.some(e=>e.id===t.id))C.push(t)}m.findings=C.flatMap(e=>currentFinding(e)??[])}return{scan:m,complete:v,inventoryComplete:_,freshNodes:b,exactHeadChecks:x,reopenedFindings:h}} //!src/gateway/github-publication-auto-fix.ts async function readSessionPrAutoFixObservation(e){try{var t=_usingCtx();const n=sessionPrAutoFixTarget(e.job);if(!n)throw new Error(`Auto-fix requires its authenticated scheduled source; recreate this automation from the owning conversation.`);const r=e.assertCurrent;const i=t.u(await prepareGitHubPublicationSession(n.sessionKey,{agentId:n.agentId,assertCurrent:r}));const a=i.readCurrent();if(!a.entry)throw new Error(`Auto-fix owning session is unavailable.`);const o={agentId:a.agentId,sessionKey:a.canonicalKey,sessionId:a.entry.sessionId};const s=a.entry.worktree?.githubPullRequest;const c=await readSharedGitHubPublication(o,{},i.readCurrent);r();const l=c?.status===`published`?c:await readSharedGitHubPublication(o,{status:`published`},i.readCurrent);r();const u=s?.url??l?.pull_request_url;const d=resolveConfiguredGitHubHost(currentGitHubPublicationConfig());const f=URL.parse(u??``);const p=f?.pathname.split(`/`);const m=p?.[1];const h=p?.[2];const g=Number(p?.[4]);const _=`session-pr:v1:`+fingerprint([n.agentId,n.sessionKey,null,m?.toLowerCase(),h?.toLowerCase(),g])+`:autoFix`;if(!u||!m||!h||!Number.isSafeInteger(g)||g<1||f?.host!==d||f.protocol!==`https:`||f.username||f.password||f.search||f.hash||p?.length!==5||p[3]!==`pull`||e.job.declarationKey!==_)throw new Error(`Auto-fix target is not this session's selected or published PR. Restore its workspace association; no other PR was adopted.`);const v=captureGatewayToolCallerAssertion();const y=getGatewayToolCallerIdentity()?.gatewayContextResolver;if(!v||!y)throw new Error(`Auto-fix requires an admitted Gateway caller.`);const b=`sessions.github.action`;const x={action:`edit`,sessionKey:o.sessionKey,agentId:o.agentId};return await withInProcessGatewayDispatch(b,x,{forceSyntheticClient:true,operatorRoleActor:{kind:`system`},syntheticScopes:resolveLeastPrivilegeOperatorScopesForMethod(b,x),syntheticScopeMode:`minimum`,resolveGatewayContext:y},async t=>{const assertRequest=()=>{r();i.readCurrent();v();t.assertContextCurrent();t.assertInvocationCurrent()};const a=await prepareGitHubPublicationRequesterV2(t,o);try{const r=s?.head?.branch??l?.branch;if(!r)throw new Error(`Auto-fix selected PR head branch is unavailable.`);const f={url:u,repository:s?.base.repository??m+`/`+h,branch:r};const p=await prepareSelectedGitHubPullRequestReader({session:o,pullRequest:f,binding:s,requester:a.requester,assertCurrent:assertRequest});if(!s&&l)assertExpectedSharedGitHubPublisher(projectGitHubPublicationResult(l).publisher,{source:p.identity.source,...p.identity.account});const _=await p.readJson(p.endpoint);const v=pullRequestState(_,f,s,p.inspection?.result.author.accountId);if(!isRecord(_)||!isRecord(_.user)||typeof _.user.login!==`string`)throw unavailable();const y=v.headCommit;const b=isRecord(e.job.state.triggerState)?e.job.state.triggerState:void 0;const x=typeof b?.pendingRequestId===`string`?b.pendingRequestId:void 0;let S=x?await readSharedGitHubPublication(o,{requestId:x},i.readCurrent):c;assertRequest();if(x&&!S)throw unavailable();let C=S?projectGitHubPublicationResult(S):void 0;let w=C?.status===`requested`||C?.status===`publishing`;if([`closed`,`merged`].includes(v.state)){try{await withGatewayToolCallerIdentity({...getGatewayToolCallerIdentity(),agentId:n.agentId,sessionKey:n.sessionKey,cronSelfManagementJobId:e.job.id},()=>callGatewayTool(`cron.remove`,{},{id:e.job.id},{requireAgentRuntimeIdentity:true}))}catch(n){if(t.context.cron.getJob(e.job.id)){assertRequest();throw new GitHubPublicationReadUnavailableError(`Terminal PR cleanup is not confirmed; retain this job for another bounded attempt`,{cause:n})}}if(t.context.cron.getJob(e.job.id))throw new GitHubPublicationReadUnavailableError(`Terminal PR cleanup is not confirmed; retain this job for another bounded attempt`);return{head:y,complete:true,terminal:true,actionable:false,fingerprint:fingerprint([y,v.state]),findings:[],publication:C,cleanupConfirmed:true}}if(S&&[`requested`,`publishing`].includes(S.status))try{var d=_usingCtx();const e=i.readCurrent().entry;if(!(`worktree_id`in S)||!e?.worktree||S.worktree_id!==e.worktree.id||S.repository!==null&&S.repository!==f.repository||S.branch!==r||S.pull_request_url&&S.pull_request_url!==u)throw new Error(`Accepted publication no longer belongs to this selected PR/workspace; no recovery was attempted`);const n=s?s.url===u&&s.base.repository===f.repository&&s.head?.branch===r:l?.pull_request_url===u&&l.repository===f.repository&&l.branch===r;if(S.repository===null&&(S.status!==`requested`||!n))throw new Error(`Accepted publication has no verified selected target; no recovery was attempted`);const a=d.u(await readGitHubPublicationWorktreeOwner({...o,allowExistingPullRequest:true,expected:{worktreeId:S.worktree_id,repositoryFingerprint:S.repository_fingerprint,branch:r}}));assertRequest();a.assertCurrent();const c=t.context.githubPublicationService;if(!c)throw new Error(`Native publication recovery owner is unavailable`);await c.resumeSessionRequests(()=>{assertRequest();a.assertCurrent();return false},void 0,S.request_id);assertRequest();S=await readSharedGitHubPublication(o,{requestId:S.request_id},i.readCurrent);assertRequest();if(!S)throw unavailable()}catch(e){d.e=e}finally{d.d()}C=S?projectGitHubPublicationResult(S):void 0;w=C?.status===`requested`||C?.status===`publishing`;if(w)return{head:y,complete:true,terminal:false,pendingPublication:true,publication:C,pendingRequestId:C?.requestId,scan:b?.scan,actionable:false,findings:[]};const T=isRecord(b?.attempt)?b.attempt:void 0;const E=Array.isArray(T?.findings)?T.findings.filter(isRecord):[];let D;const O=T?.atMs;if(typeof O===`number`){const t=await withGatewayToolCallerIdentity({...getGatewayToolCallerIdentity(),agentId:n.agentId,sessionKey:n.sessionKey,cronSelfManagementJobId:e.job.id},()=>callGatewayTool(`cron.runs`,{},{id:e.job.id,runId:`cron:${e.job.id}:${O}`,limit:1},{requireAgentRuntimeIdentity:true}));assertRequest();if(!isRecord(t)||!Array.isArray(t.entries))throw unavailable();D=t.entries.find(e=>isRecord(e)&&e.runAtMs===O&&e.triggerFired===true)}const k=Boolean(D);const ee=Boolean(T&&!k&&b?.observedAtMs!==T.atMs);const A=isRecord(D?.result)?D.result:void 0;const te=isRecord(T?.publication)?T.publication:void 0;const j=C?.status===`failed`&&C.requestId!==te?.requestId;const M=k&&(D?.status!==`ok`||A&&[`blocked`,`needs_attention`].includes(String(A.outcome))||j);const N=await t.context.cron.readScratch(e.job.id,{assertCurrent:assertRequest});assertRequest();let P;if(k&&D?.status===`ok`&&N.scratch&&N.scratch.updatedAtMs>=Number(T?.atMs)&&A&&Number(D?.ts)>=N.scratch.updatedAtMs)try{const e=JSON.parse(N.scratch.content);if(isRecord(e)&&isRecord(e.prAutoFix)&&e.prAutoFix.url===u&&e.prAutoFix.attempt===T?.fingerprint&&Array.isArray(e.prAutoFix.findings))P=e.prAutoFix}catch{}const F=Array.isArray(b?.dispositions)?b.dispositions.filter(isRecord):[];const I=Array.isArray(b?.quietFindings)?b.quietFindings.filter(isRecord):[];const L=Array.isArray(b?.quietChecks)?b.quietChecks.filter(e=>typeof e===`string`):[];if(k&&!M&&!w){for(const e of E)if(!I.some(t=>t.revision===e.revision))I.push({revision:e.revision});if(typeof T?.checks===`string`&&!L.includes(T.checks))L.push(T.checks)}const R=l?.pull_request_url===u&&_.user.type===`Bot`&&_.user.id===l.identity_account_id?l.identity_account_id:void 0;const{scan:z,complete:B,inventoryComplete:V,freshNodes:H,exactHeadChecks:U,reopenedFindings:W}=await readPrAutoFixFeedback({previous:b,head:y,owner:m,repo:h,number:g,reader:p,pullRequest:f,producerId:R,humanAuthorId:_.user.type===`User`&&typeof _.user.id===`number`&&Number.isSafeInteger(_.user.id)&&_.user.id>0?_.user.id:void 0,retryable:M,attemptedFindings:E,dispositions:F,quietFindings:I});const G=C?.status===`published`?C:void 0;const K=G&&G.url===u&&G.headCommit===y&&G.requestId!==(isRecord(T?.publication)?T.publication.requestId:void 0)&&T?.head!==y;const q=Array.isArray(P?.findings)?P.findings.filter(isRecord):[];let J=[];if(B&&K&&U&&q.some(e=>e.status===`addressed`)){if(typeof T?.head!==`string`||!/^[a-f0-9]{40}$/.test(T.head))throw unavailable();const e=await p.readJson(`repos/`+f.repository+`/compare/`+T.head+`...`+y+`?per_page=1&page=1`,{jq:`{status, base: .base_commit.sha, mergeBase: .merge_base_commit.sha, files: [.files[].filename]}`});if(!isRecord(e)||e.status!==`ahead`||e.base!==T.head||e.mergeBase!==T.head||!Array.isArray(e.files)||!e.files.every(e=>typeof e===`string`))throw unavailable();if(e.files.length<300)J=e.files}const Y=pullRequestState(await p.readJson(p.endpoint),f,s,p.inspection?.result.author.accountId);if(Y.headCommit!==y||Y.state!==v.state)throw unavailable();assertRequest();const X=[];if(B)for(const e of E){if(W.has(String(e.id)))continue;const t=H.find(t=>t.id===e.id);const n=t?.pullRequest??t?.issue;if(!t||!isRecord(n)||n.number!==g||!isRecord(n.repository)||n.repository.nameWithOwner!==f.repository||fingerprint([t.id,t.updatedAt])!==e.revision)continue;const r=q.find(t=>t.id===e.id&&t.revision===e.revision);const i=r&&typeof r.reason===`string`&&r.reason.trim()&&typeof r.quote===`string`&&r.quote.trim()&&typeof t.body===`string`&&t.body.includes(r.quote);const a=typeof e.threadId===`string`&&H.some(t=>t.id===e.threadId&&t.isResolved===true);const o=G&&K&&U&&(a||i&&r.status===`addressed`&&P?.publicationRequestId===G.requestId&&P?.head===y&&typeof r.path===`string`&&J.includes(r.path));const s=i&&r.status===`not_actionable`&&P?.head===y;if(o||s)X.push({id:e.id,revision:e.revision,threadId:e.threadId,...e.threadId?{threadResolved:a}:{},status:o?`addressed`:`not_actionable`,head:y,reason:i?String(r.reason).slice(0,240):`Native thread resolution and exact-head CI after the accepted publication`,...o?{requestId:G.requestId}:{},...i?{quote:String(r.quote).slice(0,160),...typeof r.path===`string`?{path:r.path.slice(0,160)}:{}}:{}})}for(const e of X)if(!F.some(t=>t.revision===e.revision))F.push(e);const Z=z.findings.filter(e=>!F.some(t=>t.revision===e.revision));const Q=z.failures?fingerprint([y,z.checkDigest]):null;const $=Q&&!L.includes(Q)?Q:null;const ne=E.length?{status:E.every(e=>F.some(t=>t.revision===e.revision))?`reviewed`:`blocked`,findings:E,confirmed:X.map(({id:e,revision:t,status:n})=>({id:e,revision:t,status:n})),reason:`Only fresh exact-revision judgments or native resolution with publication/CI evidence qualify`}:void 0;return{head:y,complete:B,terminal:false,inventoryComplete:V,scan:V?null:{...z,findings:[],count:0,digest:fingerprint([])},publication:C,pendingPublication:w,pendingRequestId:w?C?.requestId:null,disposition:ne,dispositions:F,quietFindings:I,quietChecks:L,settled:k,outcomeUnavailable:ee,reopened:W.size>0,retryable:M,atMs:e.job.state.runningAtMs,actionable:Z.length>0||Boolean($),checks:$,fingerprint:fingerprint([Z.map(e=>e.revision),$]),findings:Z,findingCount:z.count,unresolvedQuietCount:I.filter(e=>!F.some(t=>t.revision===e.revision)).length+(Q&&L.includes(Q)?1:0),previewIncomplete:!V||z.count>z.findings.length,failingChecks:z.failures,state:v.state}}finally{a.release()}})}catch(e){t.e=e}finally{t.d()}}export{readSessionPrAutoFixObservation};