@counterfact-labs/cli 0.2.3 → 0.2.4

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.
Files changed (58) hide show
  1. package/bundle/client-release.json +1 -1
  2. package/dist/adapters/files.js +5 -1
  3. package/dist/adapters/relay-plan.js +2 -2
  4. package/dist/adapters/release.js +8 -3
  5. package/dist/adapters/settings.js +2 -1
  6. package/dist/analysis-core/analysis/finding-quality/config.js +1 -1
  7. package/dist/analysis-core/analysis/finding-quality/policy.js +1 -1
  8. package/dist/analysis-core/analysis/headlines/attachment.js +1 -1
  9. package/dist/analysis-core/analysis/headlines/input.js +1 -1
  10. package/dist/analysis-core/analysis/schemas.js +1 -1
  11. package/dist/analysis-core/chunks/3CKW5JIF.js +1 -0
  12. package/dist/analysis-core/chunks/3GUKUEEJ.js +1 -0
  13. package/dist/analysis-core/chunks/7OYIBWX3.js +1 -0
  14. package/dist/analysis-core/chunks/{Y5AUKKYG.js → D6AWHLRI.js} +1 -1
  15. package/dist/analysis-core/chunks/{G322LST6.js → DRGDIIFA.js} +1 -1
  16. package/dist/analysis-core/chunks/{ZMUBMYWN.js → FTODBFQW.js} +1 -1
  17. package/dist/analysis-core/chunks/{EQTIRIMU.js → HPIAEQHE.js} +25 -25
  18. package/dist/analysis-core/chunks/{YVDCJN7D.js → IVDDV6CU.js} +1 -1
  19. package/dist/analysis-core/chunks/JKWTHRUR.js +1 -0
  20. package/dist/analysis-core/chunks/K5OTWBTT.js +22 -0
  21. package/dist/analysis-core/chunks/{VFENG4MR.js → MJGB25S5.js} +1 -1
  22. package/dist/analysis-core/chunks/{DTMHXKP6.js → MXXNED6N.js} +1 -1
  23. package/dist/analysis-core/chunks/NCWEOJVJ.js +6 -0
  24. package/dist/analysis-core/chunks/{M7MMAUAK.js → O652FQQH.js} +1 -1
  25. package/dist/analysis-core/chunks/{QPXNXMLC.js → QMIXCT62.js} +1 -1
  26. package/dist/analysis-core/chunks/QV2EOS7U.js +1 -0
  27. package/dist/analysis-core/chunks/T2SAP7OV.js +60 -0
  28. package/dist/analysis-core/chunks/{VER355VN.js → T66VDFXF.js} +1 -1
  29. package/dist/analysis-core/chunks/{IL2KRP3T.js → V7BFUTM7.js} +1 -1
  30. package/dist/analysis-core/contracts/requests.js +1 -1
  31. package/dist/analysis-core/conventions/analysis-fit.js +1 -0
  32. package/dist/analysis-core/conventions/file-admission.js +1 -1
  33. package/dist/analysis-core/errors.js +1 -1
  34. package/dist/analysis-core/import/outside-loader-sources.js +1 -1
  35. package/dist/analysis-core/index.js +3 -3
  36. package/dist/analysis-core/llm/cache-policy.js +1 -1
  37. package/dist/analysis-core/llm/cost.js +1 -1
  38. package/dist/analysis-core/requests/local-plan.js +1 -1
  39. package/dist/analysis-core/requests/registry.js +1 -1
  40. package/dist/analysis-core/requests/template-version.js +1 -1
  41. package/dist/analysis-core/requests/tools.js +1 -1
  42. package/dist/analysis-core/settings.js +1 -1
  43. package/dist/bundle/seal/signature.js +2 -2
  44. package/dist/cli/commands/analyze.js +4 -2
  45. package/dist/cli/development-relay.js +34 -0
  46. package/dist/cli/relay-check.js +2 -2
  47. package/dist/cli/relay-preparation.js +3 -1
  48. package/dist/contract/cli-refusals.js +2 -0
  49. package/dist/contract/cli-version.js +1 -1
  50. package/dist/contract/console.js +20 -0
  51. package/dist/gatekeeper/connection-exchange.js +2 -1
  52. package/dist/gatekeeper/console.js +11 -4
  53. package/package.json +2 -2
  54. package/dist/analysis-core/chunks/7QDOHWSY.js +0 -27
  55. package/dist/analysis-core/chunks/BZNHHLNP.js +0 -1
  56. package/dist/analysis-core/chunks/KEKTZDIK.js +0 -1
  57. package/dist/analysis-core/chunks/ORCYIIHB.js +0 -60
  58. package/dist/analysis-core/chunks/PVPEY7NF.js +0 -1
@@ -1,6 +1,6 @@
1
- import{$ as Wt,A as Tt,B as _t,C as ge,D as Lt,E as ke,F as Nt,G as Ae,H as Me,I as Fr,J as Rr,K as vr,L as Cr,M as we,N as V,O as jt,P as Kt,Q as Se,R as Ht,S as Pe,T as zt,U as Be,V as Dt,W as Ut,X as qt,Y as $t,Z as Vt,_ as Gt,a as kt,aa as Or,b as Y,ba as Xt,c as wt,ca as Jt,d as he,da as Yt,e as $,ea as Qt,f as St,g as Q,ga as Ir,h as Pt,i as Z,ia as Ar,j as ee,ja as Mr,k as bt,l as yt,la as Br,m as xt,n as Et,na as Tr,o as Ft,p as Rt,q as vt,r as Ct,s as Ot,t as ue,u as te,v as It,w as At,x as Mt,y as re,z as Bt}from"./chunks/ORCYIIHB.js";import{a as J}from"./chunks/QPXNXMLC.js";import"./chunks/VER355VN.js";import{a as yr,d as gt,k as xr,l as Er}from"./chunks/YVDCJN7D.js";import"./chunks/3MTXB4MK.js";import{i as ut}from"./chunks/TDNTU4TF.js";import"./chunks/HTLIRVP7.js";import{a as U}from"./chunks/QDYMR6KS.js";import{b as br}from"./chunks/E7TFIHC5.js";import"./chunks/Y7JGSUOA.js";import"./chunks/4F6ZIHXU.js";import"./chunks/VGYWI4X2.js";import"./chunks/J4AXGE5W.js";import"./chunks/PYKAERZZ.js";import{a as ht}from"./chunks/Y5AUKKYG.js";import{H as mt,I as Pr,h as D,i as me,j as dt,k as lt,y as ft}from"./chunks/7QDOHWSY.js";import{a as L}from"./chunks/326F4XNG.js";import{a as Ie,b as pt,d as Sr}from"./chunks/IL2KRP3T.js";import{b as B,c as ie}from"./chunks/2PSNOSJ2.js";import{b as Ue,c as qe,k as ct,o as Oe,q as wr}from"./chunks/G322LST6.js";import"./chunks/6YCABS5T.js";import"./chunks/SL27GMEN.js";import"./chunks/PVPEY7NF.js";import"./chunks/STZOC7LN.js";import{c as A}from"./chunks/VFENG4MR.js";import"./chunks/UEWL3GMQ.js";import{a as He,c as ne}from"./chunks/OFBJNHC6.js";import"./chunks/DTMHXKP6.js";import"./chunks/U5HOEVPE.js";import"./chunks/ZMUBMYWN.js";import"./chunks/ZAA44GPI.js";import{a as M,b as De}from"./chunks/3227KXHF.js";import"./chunks/M7MMAUAK.js";import"./chunks/57M4OQJM.js";import"./chunks/IBCFGUHI.js";import"./chunks/KU5DINLW.js";import{Ab as it,I as _,J as Je,K as fe,Ka as rt,N as Ye,S as Qe,b as $e,d as le,e as pe,fb as ot,g as X,ga as R,ja as Ze,jb as st,la as q,ma as z,na as et,nb as nt,q as C,r as Ge,t as We,vb as at,w as Xe,x as Ce,za as tt}from"./chunks/EQTIRIMU.js";import"./chunks/74FPPPIG.js";import"./chunks/EH3QQ3T4.js";import{f as K,i as ce,j as ze,k as ve,l as de}from"./chunks/KEKTZDIK.js";import"./chunks/FSLWD2PE.js";import"./chunks/JF4GYMOZ.js";import{a as Re}from"./chunks/BZNHHLNP.js";import{a as Ve,c as v,e as H}from"./chunks/T5TREZCQ.js";import{b as ae}from"./chunks/724WZMYW.js";function G(r,e,o,s){let t=new Set(o.map(c=>v(c.path,s))),n=r.CF_READING_NOTE_AGENT_ONLY!=="0"&&bt(r),d=new Set(e.agents),h=c=>!t.has(c)&&(!n||d.has(c)),u=e.instruction.filter(h),k=e.code.filter(h),l=e.agents.filter(c=>!t.has(c)),f=new Set(Ft(l)),b=[...u,...k].every(c=>f.has(c)),P=u.length,i=k.length,p=[!b&&P>0&&`${P} instruction file${P===1?"":"s"} left out by the ${Math.round(C.sourceFetch.instructionBytes/1e3)}KB instruction budget`,!b&&i>0&&`${i} analyzable file${i===1?"":"s"} left out by the ${Math.round(C.sourceFetch.codeBytes/1e3)}KB/${C.sourceFetch.codeFiles}-file code budget \u2014 the analysis reads the most agent-shaped files first`,Rt(l,n)].filter(Boolean),a=o.filter(c=>c.readBytes!==void 0).map(c=>v(c.path,s));return a.length&&p.push(`${a.join(", ")}: only the first ${C.sourceFetch.codeFileBytes/1e3} KB was read`),p.length?p.map((c,m)=>m<p.length-1?String(c).replace(/\.$/,""):c).join("; "):void 0}function be(r,e,o){let s=e.filter(g=>{let x=R(r,g,{purpose:"source",route:"github",root:o});return x.admitted||x.reason==="wrong-type"||x.reason==="too-large"}),t=X(r)?D(r,s.map(g=>g.path),o):void 0,n=new Set(t?.pluginDeclarations?.map(g=>g.path)),d=t?{files:t.files.map(g=>({...g,path:v(g.path,o)})),ownerOf:g=>{let x=t.ownerOf(H(g,o));return x?{...x,folder:x.key===null?"":v(x.folder,o)}:null}}:void 0,h=new Set(t?.ignoredPaths),u=xt(r,{paths:s.map(g=>v(g.path,o)),scopes:d}),k=[],l=e.flatMap(g=>{if(h.has(g.path))return[];let x=v(g.path,o),w=x===null?{size:g.size}:vt(u,x,g.size),E=R(r,{...g,size:w.size},{purpose:"source",route:"github",root:o,scopes:d});return E.admitted?[{entry:{...g,...w},rel:x,score:Ot(r,x,d),size:w.size,...u.enabled?{tier:u.tierOf(x)}:{}}]:(k.push({path:g.path,reason:E.reason}),[])}),f=l.filter(({score:g})=>g===0).sort(ue),b=l.filter(({score:g})=>g>0).sort(ue),P=[],i={instruction:0,code:0},p={instruction:[],code:[]},a=0,c=(u.enabled?[...l].sort(ue):[...f,...b]).sort((g,x)=>Number(n.has(x.entry.path))-Number(n.has(g.entry.path)));for(let{entry:g,rel:x,score:w}of c){let E=!n.has(g.path)&&!Ct(u,x)&&($e(g.path)||Qe(r,x,d)||w===0)?"instruction":"code",F=E==="instruction"?C.sourceFetch.instructionBytes:C.sourceFetch.codeBytes;if(i[E]+g.size>F||E==="code"&&a>=C.sourceFetch.codeFiles){p[E].push(x),k.push({path:g.path,reason:i[E]+g.size>F?"total":"allowance"});continue}P.push(g),i[E]+=g.size,E==="code"&&(a+=1)}let m=Et(u,k.flatMap(g=>{let x=v(g.path,o);return x===null?[]:[{...g,path:x}]})),S={...p,agents:m},y=G(r,S,P,o);return{selected:P,totalBytes:i.instruction+i.code,refused:k,...y?{skippedNote:y}:{},...u.enabled&&y?{readingNotes:S}:{}}}var Zt=(r,e)=>{let{markerToRead:o}=he(e.settings,{paths:r.map(({path:s})=>s),root:e.dir??void 0,scanFlag:e.flags.scan,marker:null});return o?{strength:"partial",wants:[o]}:null};function er(r,e,o="bare"){let{scan:s}=he(e.settings,{paths:r.map(({path:t})=>t),root:e.dir??void 0,scanFlag:e.flags.scan,marker:o});return s?{strength:"partial",wants:[]}:null}var _r=2e3;function tr(r,e,o,s={}){let t=e.filter(w=>v(w.path,o)!=null),n={},d=[],h=new Map,u=s.mode!=="core"&&tt(r),k=D(r,t.map(w=>w.path),o,{mode:u?"all":"core"}),l=new Set([...k.ignoredPaths,...k.ignoredImportPaths]),f=new Map(k.files.filter(w=>w.role!=="reference").map(w=>[w.path,w])),b=new Map(k.scopes.map(w=>[w.key,C.conventionImport.totalBytes])),P=C.conventionImport.skillBytes,i=X(r)?C.codeAgent.importBytes:1/0,p=0,a=w=>v(w.path,k.ownerOf(w.path).folder)??w.path,c=(w,E)=>{h.set(w.path,{path:w.path,reason:E})},m=(w,E)=>{let F=R(r,w,{purpose:E,route:"github",root:o});return F.admitted?!0:(c(w,F.reason),!1)},S=w=>{if(n[w.path])return;let E=u&&f.get(w.path)?.role==="skill"?"skill":"core",F=k.ownerOf(w.path),I=E==="skill"?P:b.get(F.key),T=w.size??0;if(E==="skill"&&p>=C.conventionImport.skillFiles){c(w,"allowance");return}if(T>I||T>i){c(w,"total");return}n[w.path]=w.ref,d.push(w.path),i-=T,E==="skill"?(P-=T,p++):b.set(F.key,I-T)},y=t.filter(w=>f.has(w.path));for(let w of y)m(w,f.get(w.path)?.role==="skill"?"skill":"definition")&&S(w);let g=0;if(me(r))for(let w of dt(new Set(t.map(E=>E.path)))){let E=t.find(F=>F.path===w);if(g>=C.conventionImport.extractionFiles){c(E,"allowance");continue}if(m(E,"source")&&m(E,"definition")){let F=d.length;S(E),d.length>F&&g++}}let x=k.needsExtraction;if(x){let w=t.flatMap(F=>{if(l.has(F.path)||n[F.path]||u&&Xe(a(F)))return[];if(!m(F,"extraction"))return[];let I=et(a(F));return I===null?[]:[{entry:F,rank:I}]}).sort((F,I)=>F.rank-I.rank||(F.entry.size??0)-(I.entry.size??0)),E=g;for(let{entry:F}of w){if(E>=C.conventionImport.extractionFiles){c(F,"allowance");continue}let I=d.length;S(F),d.length>I&&E++}}if(u&&s.files){let w=Te(r,{entries:e,selected:t.filter(E=>Object.hasOwn(n,E.path)),files:s.files,root:o});for(let E of w.paths)Object.hasOwn(n,E)||(d.push(E),n[E]=t.find(F=>F.path===E).ref);for(let E of w.refused)h.set(E.path,E)}return{...X(r)&&y.some(w=>!Object.hasOwn(n,w.path))?{definitionsOmitted:!0}:{},selectedPaths:d,shaByPath:n,treeListing:t.slice(0,_r).map(w=>w.path),needsExtraction:x,refused:[...h.values()]}}function Te(r,e){let o=new Set(e.selected.map(n=>n.path)),s=D(r,e.entries.map(n=>n.path),e.root).files.filter(n=>n.role==="skill"&&o.has(n.path)).map(n=>n.path),t=lt(r,{skillPaths:s,paths:e.entries.map(n=>n.path),files:e.files,sizes:new Map(e.entries.map(n=>[n.path,n.size])),selected:e.selected,root:e.root,admission:e.admission,referencePaths:e.referencePaths});return{paths:[...new Set(t?.flatMap(n=>n.files.map(d=>d.path))??[])],refused:t?.flatMap(n=>n.refused)??[]}}var rr=(r,e)=>{let o=tr(e.settings,r,e.dir??void 0,{mode:e.mode});return{strength:"partial",wants:o.selectedPaths,state:{needsExtraction:o.needsExtraction,treeListing:o.treeListing,shaByPath:o.shaByPath,refused:o.refused,...o.definitionsOmitted?{definitionsOmitted:!0}:{}}}};var or=["marker","code-scan","conventions"];var Lr={marker:Zt,"code-scan":er,conventions:rr};function ye(r,e,o,s,t=Lr){let n={...o,settings:r},d={readers:[]};for(let h of or)if(!(s&&!s.includes(h)))try{let u=t[h]?.(e,n);u&&d.readers.push({id:h,claim:u,done:!1})}catch{}return d}function Nr(r){return{readers:r.readers.map(({id:e,done:o})=>({id:e,done:o}))}}function _e(r){let e=r.readers.find(({id:o})=>o==="conventions").claim;return{selectedPaths:e.wants,...e.state}}function Le(r,e){let o={dir:e.root??null,mode:e.profile==="hosted-import"?e.mode??"all":"all",flags:e.profile==="hosted-import"?e.flags??te(r):te(r)};if(e.profile==="hosted-import"){let n=ye(r,e.listing,o);return{profile:e.profile,...n,selection:_e(n)}}let s=e.listing.filter(n=>R(r,n,{purpose:"pointer",route:"github",root:e.root}).admitted),t=ye(r,s,o,["marker","code-scan"]);return{profile:e.profile,...t,listing:s,selection:e.selection??be(r,e.listing,e.root),context:o}}var W=20;function oe(r,e,o,s){e.requestedPaths.push(...o);let t=ke(r,e.selected,o,s);e.selected=t.selected,e.refused.push(...t.refused)}function xe(r,e,o){let s=r.hosted;if(!s)return;let t=new Set(e),n=r.selected.filter(d=>t.has(d.path));o==="code"?s.codePaths&&(s.codePaths=[...new Set([...s.codePaths,...n.map(d=>d.path)])]):s.weakCodeFallback&&(r.conventionPaths=[...new Set([...r.conventionPaths,...n.map(d=>d.path)])],s.fallback={...s.fallback,selectedPaths:[...new Set([...s.fallback.selectedPaths,...n.map(d=>d.path)])],shaByPath:{...s.fallback.shaByPath,...Object.fromEntries(n.map(d=>[d.path,d.ref]))}})}function Ee(r,e){let o=new Set(r.conventionPaths);if(r.decision.kind==="settled"&&r.decision.scanPaths&&r.markerKind&&r.markerKind!=="bare")for(let t of r.selected)o.add(t.path);let s=new Map(e.map(t=>[t.path,t]));for(let t of r.selected)o.has(t.path)&&!s.has(t.path)&&s.set(t.path,t);r.selected=[...s.values()],r.cursor=0,r.hosted&&(r.hosted.codeMode=!0,r.hosted.needsExtraction=!1)}function sr(r,e=St(r.ranked,r.scan)){return e.agents.length>0}function nr(r,e){if(r.hosted&&(r.hosted.codePaths=e.map(s=>s.path)),!r.hosted?.weakCodeFallback||r.hosted.codeMode||sr(r)){Ee(r,e);return}let o=new Map(r.selected.map(s=>[s.path,s]));for(let s of e)o.has(s.path)||o.set(s.path,s);r.selected=[...o.values()],r.cursor=0}function ar(r,e){let o=r.hosted;if(!o?.weakCodeFallback||!o.codePaths||r.markerKind&&r.markerKind!=="bare")return;let s=new Map([...r.entries,...r.selected].map(n=>[n.path,n]));sr(r,e)?Ee(r,o.codePaths.map(n=>s.get(n))):(r.selected=o.fallback.selectedPaths.map(n=>s.get(n)),r.cursor=0,o.codeMode=!1,o.needsExtraction=o.fallback.needsExtraction);let t=new Set(r.selected.map(n=>n.path));r.files=Object.fromEntries(Object.entries(r.files).filter(([n])=>t.has(n)))}function Ne(r,e){if(!_(r))return;let o=new Set(e.entries.map(n=>n.path)),s=Object.fromEntries(Object.entries(e.files).filter(([n])=>e.selected.some(d=>d.path===n&&d.readBytes===void 0))),t=new Set(fe(r,[...o],s));for(let[n,d]of Object.entries(e.files)){let h=R(r,{path:n,text:d},{...e.admission,purpose:"override",route:"github",root:e.root,listing:o,managedFiles:e.files});(!h.admitted||t.has(n))&&(delete e.files[n],e.refused.push({path:n,reason:h.admitted?"unreadable":h.reason}))}}function N(r,e,o){Ne(r,e);let s=e.selected.filter(h=>e.files[h.path]!==void 0),t=new Set(s.filter(h=>h.readBytes===void 0).map(h=>h.path)),n=new Set(e.requestedPaths),d=B(e.selectionRefused.filter(h=>!n.has(h.path)),e.refused).filter(h=>!t.has(h.path));return{state:e,requestedReads:o,files:e.files,settled:s,refused:d,treeTruncated:e.treeTruncated}}async function ir(r,e,o){e.manifestReadPaths??=e.selected.slice(0,e.cursor).filter(a=>a.readBytes===void 0).map(a=>a.path);let s=new Set(e.selected.filter(a=>a.readBytes===void 0).map(a=>a.path)),t=Object.fromEntries(Object.entries(e.files).filter(([a])=>s.has(a))),n=new Map(e.entries.map(a=>[a.path,a.size])),d=new Map(Object.entries(e.files).map(([a,c])=>[a,Buffer.byteLength(c)]));for(let[a,c]of Object.entries(t))n.set(a,Buffer.byteLength(c));let h=Y(r,e.ranked,n,!1,d,e.codeImportV2,{files:t,root:e.root}),u=new Set(e.manifestReadPaths),k=h.paths.filter(a=>t[a]===void 0&&!u.has(a)),l=new Map(e.selected.filter(a=>a.readBytes!==void 0).map(a=>[a.path,a]));e.requestedPaths.push(...k.filter(a=>l.has(a))),oe(r,e,k.filter(a=>!l.has(a)),e.entries);let f=new Set(k),b=new Map(e.entries.map(a=>[a.path,a])),P=e.selected.filter(a=>f.has(a.path)).map(a=>l.has(a.path)?b.get(a.path):a).slice(0,W);if(P.length){let a=await L(P,4,async g=>{let x=R(r,g,{...e.admission,purpose:"pointer",route:"github",root:e.root});return x.admitted?o(g):(e.refused.push({path:g.path,reason:x.reason}),null)});e.manifestReadPaths=[...e.manifestReadPaths,...P.map(g=>g.path)];let c=new Map(n);P.forEach((g,x)=>{a[x]!==null&&c.set(g.path,Buffer.byteLength(a[x]))});let m=new Map(P.filter((g,x)=>l.has(g.path)&&a[x]!==null).map(g=>[g.path,d.get(g.path)])),S=Y(r,e.ranked,c,!1,d,e.codeImportV2,{files:t,root:e.root,replacementBytes:m}),y=new Set(S.paths);P.forEach((g,x)=>{a[x]!==null&&(y.has(g.path)?(e.files[g.path]=a[x],e.selected=e.selected.map(w=>w.path===g.path?g:w)):e.refused.push(S.refused.find(w=>w.path===g.path)??{path:g.path,reason:"total"}))});return}let i=new Map((h.manifests??[]).map(a=>{let m=a.files.filter(S=>t[S.path]===void 0).map(S=>e.refused.find(y=>y.path===S.path)??{path:S.path,reason:"missing"});return[a.agentId,{...a,files:a.files.filter(S=>t[S.path]!==void 0),refused:[...a.refused,...m]}]})),p=a=>{let c=i.get(rt(a.prompt));return c?{...a,manifest:c}:a};e.ranked={...e.ranked,strong:e.ranked.strong.map(p),possible:e.ranked.possible.map(p)},xe(e,[...i.values()].flatMap(a=>a.files.map(c=>c.path)),"code"),e.refused.push(...[...i.values()].flatMap(kt)),e.phase="done"}async function cr(r,e,o){if(!_(r))return!1;let s=Je(r,e.entries.map(f=>f.path));if(!s.length)return!1;let t=new Set(s.flatMap(f=>f.agents)),n=new Map(e.selected.map(f=>[f.path,f])),d=new Set(e.selected.filter(f=>f.readBytes===void 0&&e.files[f.path]!==void 0).map(f=>f.path));e.managedReadPaths||(e.managedReadPaths=[],(e.scan||e.ranked)&&(delete e.scan,delete e.ranked,delete e.manifestReadPaths,e.phase!=="marker"&&(e.phase="scan")));let h=new Set([...e.managedReadPaths,...d]),u=e.entries.filter(f=>t.has(f.path)&&n.has(f.path)&&!h.has(f.path)),k=u.slice(0,W);if(!k.length)return!1;let l=await L(k,4,async f=>{let b=R(r,f,{...e.admission,purpose:"pointer",route:"github",root:e.root});return b.admitted?o(f):(e.refused.push({path:f.path,reason:b.reason}),null)});if(k.forEach((f,b)=>{l[b]!==null&&(e.files[f.path]=l[b],e.selected=e.selected.map(P=>P.path===f.path?f:P))}),e.managedReadPaths.push(...k.map(f=>f.path)),u.length>k.length){for(let f of Object.keys(e.files))!t.has(f)&&s.some(b=>v(f,b.folder)!==null)&&delete e.files[f];e.cursor=0,(e.phase==="done"||e.phase==="manifest")&&(e.phase="files")}return!0}function dr(r,e){let{plan:o,entries:s}=e,t=o.profile==="local-analysis"?o.context.dir??"":e.root??"",n=o.readers.find(l=>l.id==="marker")?.claim.wants[0],d=o.readers.some(l=>l.id==="code-scan"),h=new Map(s.map(l=>[l.path,l])),u=o.profile==="local-analysis"?o.selection.selected:o.selection.selectedPaths.flatMap(l=>h.has(l)?[h.get(l)]:[]),k=wt(r)?$(r,{phase:"start",root:t,paths:s.map(l=>l.path),scanFlag:!!n||d}):void 0;return{version:1,profile:o.profile,root:t,entries:s,selected:[...u],conventionPaths:o.profile==="hosted-import"?D(r,s.map(l=>l.path),t).files.filter(l=>l.role!=="reference").map(l=>l.path):[],...e.admission?{admission:e.admission}:{},selectionRefused:o.selection.refused,requestedPaths:[],refused:[],files:{},cursor:0,treeTruncated:e.treeTruncated??!1,codeImportV2:o.profile==="local-analysis"&&le(r),...o.profile==="hosted-import"?{hosted:{fallback:structuredClone(o.selection),weakCodeFallback:r.CF_IMPORT_WEAK_CODE_FALLBACK!=="0",codeMode:!1,needsExtraction:o.selection.needsExtraction}}:{},decision:k??(n?{kind:"marker",markerPath:n,scanIfBare:d}:{kind:"settled",markerPath:null,markerKind:null,scan:d}),phase:n?"marker":d?"scan":"files"}}function jr(r,e){e.ranked??=ge(r,e.scan,!1,new Map,e.codeImportV2);let o=Y(r,e.ranked,_t(e.scan.plan),!1,new Map,e.codeImportV2),s=[...o.refused,...e.ranked.skippedFiles??[]];if(e.requestedPaths.push(...s.map(t=>t.path)),e.refused.push(...s),e.profile==="hosted-import"&&o.paths.length){let t=ke(r,[],o.paths,e.scan.plan);e.refused.push(...t.refused),nr(e,t.selected)}else oe(r,e,o.paths,e.scan.plan);e.phase=e.selected.length?"files":"done"}async function lr(r,e,o){if(e.version!==1)throw new Error("unsupported-import-checkpoint");let s=e.profile==="hosted-import"?{...r,CF_IMPORT_CALLS:"0"}:r,t={...e,selected:[...e.selected],files:{...e.files},requestedPaths:[...e.requestedPaths],refused:[...e.refused],...e.hosted?{hosted:{...e.hosted}}:{},...e.managedReadPaths?{managedReadPaths:[...e.managedReadPaths]}:{}},n=new Set(t.entries.map(i=>i.path)),d=Object.fromEntries(Object.entries(t.files).filter(([i])=>t.selected.some(p=>p.path===i&&p.readBytes===void 0))),h=new Set(fe(s,[...n],d)),u=[],k=new Set,l=async i=>{if(h.has(i.path)||t.managedReadPaths?.includes(i.path)&&t.files[i.path]===void 0)return t.refused.push({path:i.path,reason:"unreadable"}),null;u.push(i);try{let p=await o.read(i);if(p!==null){if(k.has(i.path)){let a=R(s,{path:i.path,size:Buffer.byteLength(p),text:p},{...t.admission,purpose:"skill",route:"github",root:t.root,listing:n,managedFiles:t.files});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}if(_(s)||ae(s)){let a=R(s,{path:i.path,text:p},{...t.admission,purpose:"override",route:"github",root:t.root,listing:n,managedFiles:t.files});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}if(t.phase==="manifest"){let a=R(s,{path:i.path,size:Buffer.byteLength(p)},{...t.admission,purpose:"pointer",route:"github",root:t.root});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}return p}}catch(p){if(p instanceof Ye&&(p.reason==="secret-content"||_(s)||k.has(i.path)))return t.refused.push({path:i.path,reason:p.reason}),null;if(t.profile==="hosted-import"&&!k.has(i.path))throw p}return t.refused.push({path:i.path,reason:"unreadable"}),null};if(await cr(s,t,l))return N(s,t,u);if(Ne(s,t),t.phase==="done")return o.resolvedCode&&ar(t,o.resolvedCode),N(s,t,u);if(t.phase==="manifest")return await ir(s,t,l),N(s,t,u);if(t.phase==="marker"&&t.decision.kind==="marker"){let i=t.decision,p=i.markerPath,a=t.entries.find(m=>m.path===p);if(t.profile==="hosted-import"){let m=R(s,a,{purpose:"pointer",route:"github",root:t.root});if(!m.admitted)return t.refused.push({path:p,reason:m.reason}),t.decision={kind:"settled",markerPath:null,markerKind:null,scan:i.scanIfBare},t.phase=i.scanIfBare?"scan":"files",N(s,t,u)}oe(s,t,[p],t.entries);let c=await l(a);if(c!==null&&(t.files[p]=c),t.decision=$(s,{phase:"read",pending:i,text:c}),t.markerPath=p,t.markerKind=t.decision.markerKind,t.markerKind!=="bare"){let m=t.profile==="hosted-import"?await o.listing():{entries:t.entries,truncated:!1};t.treeTruncated||=m.truncated;let S=await Nt(s,{config:ft(c).config,markerDir:p.split("/").slice(0,-1).join("/"),selected:t.profile==="hosted-import"?[]:t.selected,admission:{...t.admission,root:t.root||void 0},modelReader:!1,codeImportV2:t.codeImportV2,priorRefused:t.refused,refusalMode:"append",requestedMode:"kept-and-refused",listing:async()=>m.entries});t.requestedPaths.push(...S.requestedPaths),t.refused=S.refused,t.profile==="hosted-import"?Ee(t,S.selected??[]):S.selected&&(t.selected=S.selected)}if(t.phase=t.decision.scan?"scan":"files",t.profile!=="hosted-import"||t.markerKind!=="bare"||t.decision.scan)return N(s,t,u)}if(t.phase==="scan"){if(!t.scan){let i=Mt(s,t.entries,t.root,!0,t.decision.kind==="settled"?t.decision.scanPaths:void 0);t.scan=i.state,t.refused.push(...i.refused)}if(!re(t.scan)){let i=await Lt(s,t.scan,l,{modelReader:!1,alreadyRead:new Map,codeImportV2:t.codeImportV2,size:{batch:It,parallel:4}});t.scan=i.scan,i.selection&&(t.ranked=i.selection.ranked)}return re(t.scan)&&jr(s,t),N(s,t,u)}Ce(s)&&(k=new Set(t.skillReferencePaths));let f=t.selected.slice(t.cursor,t.cursor+W),b=f.filter(i=>t.files[i.path]===void 0),P=await L(b,4,l);if(b.forEach((i,p)=>{P[p]!==null&&(t.files[i.path]=P[p])}),t.cursor+=f.length,Ce(s)){let i=Object.fromEntries(Object.entries(t.files).filter(([y])=>t.selected.some(g=>g.path===y&&g.readBytes===void 0))),p=Te(s,{entries:t.entries,selected:t.selected,files:i,root:t.root,admission:t.admission,referencePaths:t.skillReferencePaths});t.refused=B(t.refused,p.refused);for(let y of p.refused)k.has(y.path)&&delete t.files[y.path];if(t.cursor<t.selected.length)return N(s,t,u);let a=new Map(t.selected.map(y=>[y.path,y])),c=p.paths.filter(y=>!a.has(y)||a.get(y).readBytes!==void 0),m=new Set(c.filter(y=>a.has(y)));t.cursor-=t.selected.slice(0,t.cursor).filter(y=>m.has(y.path)).length,t.selected=t.selected.filter(y=>!m.has(y.path));for(let y of m)delete t.files[y];t.requestedPaths.push(...c),c.length&&(t.skillReferencePaths=[...t.skillReferencePaths??[],...c]);let S=new Map(t.entries.map(y=>[y.path,y]));t.selected.push(...c.map(y=>{let g=S.get(y);return{path:y,size:g.size,ref:g.ref}})),xe(t,c,"fallback")}return t.cursor>=t.selected.length&&(t.phase=me(s)&&t.ranked?"manifest":"done"),N(s,t,u)}async function pr(r,e){let o=dr(r,e),s;do s=await lr(r,o,{listing:async()=>({entries:e.entries,truncated:!1}),read:e.read}),o=s.state;while(o.phase!=="done");let t={};return o.markerPath!==void 0&&(t.markerPath=o.markerPath,t.markerKind=o.markerKind),o.ranked!==void 0&&(t.ranked=o.ranked,t.scan=o.scan),{files:s.files,settled:s.settled,skippedFiles:s.refused,...t}}async function je(r,e){let o=Le(r,{profile:"local-analysis",listing:e.entries,selection:e.selection}),{files:s,settled:t,skippedFiles:n,...d}=await pr(r,{entries:e.entries,read:e.read,admission:e.admission,plan:o}),h=s,u=t,k=n,l=Q({key:e.repoKey,files:h,...d},o.context.flags,void 0,{markerPolicy:"any-read"}),{selection:f}=o,b;if(pt(r)&&e.repository){let a=await ht(r,{selected:{files:h,listedPaths:e.entries.map(m=>m.path),fallbackName:Pt(e),skills:!0},selection:f,codeAgentsFound:(l?.resolved?.agents.length??0)>0,port:e.repository}),c=new Set(Object.keys(h).map(m=>H(m,a.root)));if(h=a.files,f=a.selection,b=a.root,b!==void 0){k=k.map(S=>({...S,path:H(S.path,b)})),u=u.map(S=>({...S,path:H(S.path,b)}));let m=new Set(u.map(S=>S.path));u.push(...f.selected.filter(S=>!m.has(S.path)&&Object.hasOwn(h,S.path)))}k=B(k,a.skippedFiles).filter(m=>c.has(m.path)||!Object.hasOwn(h,m.path))}let P={repoKey:e.repoKey,files:h,listedPaths:e.entries.map(a=>H(a.path,b)),...b!==void 0?{root:b}:{},forLocal:!0,code:l},i=ee(r,Z(r,P)),p=f.readingNotes?G(r,f.readingNotes,u):f.skippedNote;return{...i,files:h,...b!==void 0?{root:b}:{},skippedFiles:k,warnings:[...new Set([...i.warnings,...p?[p]:[],...ie(k)])],selection:f}}var Kr=new Set;function Hr(r,e={}){let o=Ve(e.dir),s=e.limits??C.archive,t=e.listing??Kr,n={commit:null,files:new Map,skipped:[]},d=new Set,h=0,u=0;function k(i){let p=i.replace(/\/$/,"").split("/");return!i.startsWith("/")&&!i.includes("\\")&&!/^[a-z]:/i.test(i)&&!p.some(a=>a===".."||a==="."||!a)}function l(i,p,a,c=t){if(!a||!k(i)||!Number.isSafeInteger(p)||p<0)return"refused";let m=R(r,{path:i,size:p},{purpose:"archive",route:"github",root:o});return m.admitted?e.exampleFolders?.some(S=>i.startsWith(S))||We(i,{root:o,listing:c})?"example":null:m.reason==="excluded"&&Ge(r,i,o)?"example":m.reason==="excluded"||m.reason==="wrong-type"?"excluded":"refused"}function f(i,p){d.has(i)||(d.add(i),n.skipped.push({path:i,reason:p}))}function b(i,p=t){let a=i.split("/");for(let c=1;c<=a.length;c++){let m=a.slice(0,c).join("/");if(m===o||o.startsWith(`${m}/`))continue;if(v(m,o)===null)return!1;let S=l(`${m}/`,0,!0,p);if(S)return f(`${m}/`,S),!1}return!0}function P(i,p,a=!0){if(v(i,o)===null)return!1;if(!k(i))return f(i,"refused"),!1;let c=i.split("/");if(c.length>1&&!b(c.slice(0,-1).join("/")))return!1;let m=l(i,p,a);return m?(f(i,m),!1):u>=s.files||p>s.bytes-h?(f(i,"over-limit"),!1):(h+=p,u++,!0)}return{result:n,accept:P,enterFolder:b}}var zr=new Set(Ae);function Dr(r,e){for(let s of[...Object.keys(e.set),...e.clear])if(!zr.has(s))throw new Error(`Unknown analysis field: ${s}`);let o={...r,...e.set};for(let s of e.clear)o[s]=void 0;return o}async function Ur(r,e,o,s){o=q(r,o);let t=structuredClone(e);for(t.files??={},t.cursor=0;;){let n=await Se(r,t,o,s);if(n){t=n;continue}let d=t.selected??[];if((t.cursor??0)>=d.length)return t;let h=d.slice(t.cursor).filter(l=>!Object.hasOwn(t.files,l.path)),u=[],k=await L(h,4,async l=>{try{return{path:l.path,text:await we(l,f=>o.read(f),u,t.refused)}}catch(f){return{error:f}}});for(let l of k){if("error"in l)throw l.error;l.text!==null&&(t.files[l.path]=l.text)}u.length&&(t.refused=B(t.refused,u)),t.cursor=d.length}}async function fr(r,e,o,s){let{codeFindingNote:t}=gt(s),n={deriveBytes:0,codeEvidence:[]};if(!e.findingQuality?.config.switches.codeInputs||!e.projectAgents?.enabled)return n;let d=e.projectAgents,h=(e.repos??[]).filter(c=>[...d.byRepo[c.key]??[],...d.codeByRepo?.[c.key]??[]].some(m=>m.codeInputsJson&&(m.codeInputsJson.tools.length||m.codeInputsJson.contextInputs.length))),k=(await L(h,1,async c=>{try{let m=o.find(S=>S.repoKey===c.key);if(!m)throw new Error("Source reader is missing.");return{repo:await Ur(r,c,m,e.modelReader??!1)}}catch(m){return{error:m}}})).map(c=>{if("error"in c)throw c.error;return c.repo}),l=k.map(c=>{let m=Pe(r,c,V(r,e),e.modelReader,d);return Object.assign(c.files,m.virtualFiles),m.fragment}),f=Object.fromEntries(k.map(c=>[c.key,c.files??{}])),P=zt({...e,repos:k,mapped:l}).findingQuality?.codeEvidence?.filter(c=>Object.keys(c.input.files).length)??[];if(!P.length)return n;let i=P.map(c=>({repo:c.repo,unitKey:c.unitKey,enabled:!0,inputs:[c.input],files:f[c.repo]}));return{deriveBytes:[...new Map(P.flatMap(c=>Object.entries(c.input.files).map(([m,S])=>[JSON.stringify([c.repo,m]),{path:m,text:S}]))).values()].reduce((c,{path:m,text:S})=>c+Buffer.byteLength(`### ${m}
1
+ import{$ as Ar,A as Fr,B as Rr,C as he,D as q,E as At,F as _t,G as ge,H as Mt,I as ke,J as Bt,K as Ce,L as Tt,M as It,N as Lt,O as Nt,P as jt,Q as Kt,R as Ht,S as vr,T as Dt,U as zt,V as Ut,W as qt,Y as Or,_ as Cr,a as wt,b as Y,ba as _r,c as St,d as fe,da as Mr,e as U,f as Pt,g as Q,h as bt,i as V,j as Z,k as ee,l as yt,m as Et,n as xt,o as te,p as Ft,q as Rt,r as vt,s as me,t as Ot,u as ue,v as Ct,w as ve,x as Oe,y as Er,z as xr}from"./chunks/T2SAP7OV.js";import{a as J}from"./chunks/QMIXCT62.js";import"./chunks/T66VDFXF.js";import"./chunks/J4AXGE5W.js";import{a as Pr,d as kt,k as br,l as yr}from"./chunks/IVDDV6CU.js";import"./chunks/Y7JGSUOA.js";import"./chunks/3MTXB4MK.js";import{i as gt}from"./chunks/TDNTU4TF.js";import"./chunks/HTLIRVP7.js";import{a as D}from"./chunks/QDYMR6KS.js";import{b as Sr}from"./chunks/E7TFIHC5.js";import{a as ht}from"./chunks/D6AWHLRI.js";import{C as wr,d as pe,e as pt,f as ft,t as ut}from"./chunks/K5OTWBTT.js";import{a as L}from"./chunks/326F4XNG.js";import{a as Re,b as mt,d as kr}from"./chunks/V7BFUTM7.js";import"./chunks/4F6ZIHXU.js";import"./chunks/VGYWI4X2.js";import"./chunks/PYKAERZZ.js";import{a as lt,b as mr,c as ur,d as hr,e as gr}from"./chunks/QV2EOS7U.js";import{a as nt,d as at,g as it,h as ct,i as dt,o as le}from"./chunks/7OYIBWX3.js";import{h as X}from"./chunks/NCWEOJVJ.js";import{b as B,c as ae}from"./chunks/2PSNOSJ2.js";import{b as He,c as De,k as st,o as Fe,q as fr}from"./chunks/DRGDIIFA.js";import"./chunks/6YCABS5T.js";import"./chunks/SL27GMEN.js";import"./chunks/3CKW5JIF.js";import"./chunks/STZOC7LN.js";import{c as _}from"./chunks/MJGB25S5.js";import"./chunks/UEWL3GMQ.js";import{a as Le,c as se}from"./chunks/OFBJNHC6.js";import"./chunks/MXXNED6N.js";import"./chunks/U5HOEVPE.js";import"./chunks/FTODBFQW.js";import"./chunks/ZAA44GPI.js";import{a as M,b as Ke}from"./chunks/3227KXHF.js";import"./chunks/O652FQQH.js";import"./chunks/57M4OQJM.js";import"./chunks/IBCFGUHI.js";import"./chunks/KU5DINLW.js";import{G as I,H as Ge,I as de,Ja as Ve,L as We,M as Xe,e as Ee,eb as Ze,fa as F,ia as Je,ib as et,ka as z,la as H,ma as Ye,mb as tt,o as v,p as Ue,r as qe,u as $e,ub as rt,v as xe,ya as Qe,zb as ot}from"./chunks/HPIAEQHE.js";import"./chunks/74FPPPIG.js";import"./chunks/EH3QQ3T4.js";import{f as K,i as ie,j as Ne,m as je,n as ce}from"./chunks/JKWTHRUR.js";import"./chunks/FSLWD2PE.js";import"./chunks/JF4GYMOZ.js";import{a as pr,b as ye}from"./chunks/3GUKUEEJ.js";import{a as ze,c as C,e as W}from"./chunks/T5TREZCQ.js";import{b as ne}from"./chunks/724WZMYW.js";function $(r,e,o,s){let t=new Set(o.map(c=>C(c.path,s))),n=r.CF_READING_NOTE_AGENT_ONLY!=="0"&&nt(r),l=new Set(e.agents),u=c=>!t.has(c)&&(!n||l.has(c)),g=e.instruction.filter(u),h=e.code.filter(u),p=e.agents.filter(c=>!t.has(c)),f=new Set(ct(p)),w=[...g,...h].every(c=>f.has(c)),b=g.length,i=h.length,m=[!w&&b>0&&`${b} instruction file${b===1?"":"s"} left out by the ${Math.round(v.sourceFetch.instructionBytes/1e3)}KB instruction budget`,!w&&i>0&&`${i} analyzable file${i===1?"":"s"} left out by the ${Math.round(v.sourceFetch.codeBytes/1e3)}KB/${v.sourceFetch.codeFiles}-file code budget \u2014 the analysis reads the most agent-shaped files first`,dt(p,n)].filter(Boolean),a=o.filter(c=>c.readBytes!==void 0).map(c=>C(c.path,s));return a.length&&m.push(`${a.join(", ")}: only the first ${v.sourceFetch.codeFileBytes/1e3} KB was read`),m.length?m.map((c,d)=>d<m.length-1?String(c).replace(/\.$/,""):c).join("; "):void 0}function we(r,e,o){let{descriptions:s,priority:t,declarations:n}=lt(r,e,{root:o}),l=[],u=s.flatMap(d=>d.admission.admitted?[{entry:d.readEntry,rel:d.rel,score:d.score,size:d.readEntry.size,pool:d.pool,...d.tier===void 0?{}:{tier:d.tier}}]:(l.push({path:d.entry.path,reason:d.admission.reason}),[])),g=u.filter(({score:d})=>d===0).sort(le),h=u.filter(({score:d})=>d>0).sort(le),p=[],f={instruction:0,code:0},w={instruction:[],code:[]},b=0,i=(t.enabled?[...u].sort(le):[...g,...h]).sort((d,k)=>Number(n.has(k.entry.path))-Number(n.has(d.entry.path)));for(let{entry:d,rel:k,pool:P}of i){let y=P==="instruction"?v.sourceFetch.instructionBytes:v.sourceFetch.codeBytes;if(f[P]+d.size>y||P==="code"&&b>=v.sourceFetch.codeFiles){w[P].push(k),l.push({path:d.path,reason:f[P]+d.size>y?"total":"allowance"});continue}p.push(d),f[P]+=d.size,P==="code"&&(b+=1)}let m=it(t,l.flatMap(d=>{let k=C(d.path,o);return k===null?[]:[{...d,path:k}]})),a={...w,agents:m},c=$(r,a,p,o);return{selected:p,totalBytes:f.instruction+f.code,refused:l,...c?{skippedNote:c}:{},...t.enabled&&c?{readingNotes:a}:{}}}var $t=(r,e)=>{let{markerToRead:o}=fe(e.settings,{paths:r.map(({path:s})=>s),root:e.dir??void 0,scanFlag:e.flags.scan,marker:null});return o?{strength:"partial",wants:[o]}:null};function Gt(r,e,o="bare"){let{scan:s}=fe(e.settings,{paths:r.map(({path:t})=>t),root:e.dir??void 0,scanFlag:e.flags.scan,marker:o});return s?{strength:"partial",wants:[]}:null}var Br=2e3;function Wt(r,e,o,s={}){let t=e.filter(S=>C(S.path,o)!=null),n={},l=[],u=new Map,g=s.mode!=="core"&&Qe(r),h=X(r,t.map(S=>S.path),o,{mode:g?"all":"core"}),p=new Set([...h.ignoredPaths,...h.ignoredImportPaths]),f=new Map(h.files.filter(S=>S.role!=="reference").map(S=>[S.path,S])),w=new Map(h.scopes.map(S=>[S.key,v.conventionImport.totalBytes])),b=v.conventionImport.skillBytes,i=Ee(r)?v.codeAgent.importBytes:1/0,m=0,a=S=>C(S.path,h.ownerOf(S.path).folder)??S.path,c=(S,E)=>{u.set(S.path,{path:S.path,reason:E})},d=(S,E)=>{let x=F(r,S,{purpose:E,route:"github",root:o});return x.admitted?!0:(c(S,x.reason),!1)},k=S=>{if(n[S.path])return;let E=g&&f.get(S.path)?.role==="skill"?"skill":"core",x=h.ownerOf(S.path),A=E==="skill"?b:w.get(x.key),T=S.size??0;if(E==="skill"&&m>=v.conventionImport.skillFiles){c(S,"allowance");return}if(T>A||T>i){c(S,"total");return}n[S.path]=S.ref,l.push(S.path),i-=T,E==="skill"?(b-=T,m++):w.set(x.key,A-T)},P=t.filter(S=>f.has(S.path));for(let S of P)d(S,We(f.get(S.path).role))&&k(S);let y=0;if(pe(r))for(let S of pt(new Set(t.map(E=>E.path)))){let E=t.find(x=>x.path===S);if(y>=v.conventionImport.extractionFiles){c(E,"allowance");continue}if(d(E,"source")&&d(E,"definition")){let x=l.length;k(E),l.length>x&&y++}}let R=h.needsExtraction;if(R){let S=t.flatMap(x=>{if(p.has(x.path)||n[x.path]||g&&$e(a(x)))return[];if(!d(x,"extraction"))return[];let A=Ye(a(x));return A===null?[]:[{entry:x,rank:A}]}).sort((x,A)=>x.rank-A.rank||(x.entry.size??0)-(A.entry.size??0)),E=y;for(let{entry:x}of S){if(E>=v.conventionImport.extractionFiles){c(x,"allowance");continue}let A=l.length;k(x),l.length>A&&E++}}if(g&&s.files){let S=Ae(r,{entries:e,selected:t.filter(E=>Object.hasOwn(n,E.path)),files:s.files,root:o});for(let E of S.paths)Object.hasOwn(n,E)||(l.push(E),n[E]=t.find(x=>x.path===E).ref);for(let E of S.refused)u.set(E.path,E)}return{...Ee(r)&&P.some(S=>!Object.hasOwn(n,S.path))?{definitionsOmitted:!0}:{},selectedPaths:l,shaByPath:n,treeListing:t.slice(0,Br).map(S=>S.path),needsExtraction:R,refused:[...u.values()]}}function Ae(r,e){let o=new Set(e.selected.map(n=>n.path)),s=X(r,e.entries.map(n=>n.path),e.root).files.filter(n=>n.role==="skill"&&o.has(n.path)).map(n=>n.path),t=ft(r,{skillPaths:s,paths:e.entries.map(n=>n.path),files:e.files,sizes:new Map(e.entries.map(n=>[n.path,n.size])),selected:e.selected,root:e.root,admission:e.admission,referencePaths:e.referencePaths});return{paths:[...new Set(t?.flatMap(n=>n.files.map(l=>l.path))??[])],refused:t?.flatMap(n=>n.refused)??[]}}var Xt=(r,e)=>{let o=Wt(e.settings,r,e.dir??void 0,{mode:e.mode});return{strength:"partial",wants:o.selectedPaths,state:{needsExtraction:o.needsExtraction,treeListing:o.treeListing,shaByPath:o.shaByPath,refused:o.refused,...o.definitionsOmitted?{definitionsOmitted:!0}:{}}}};var Jt=["marker","code-scan","conventions"];var Tr={marker:$t,"code-scan":Gt,conventions:Xt};function Se(r,e,o,s,t=Tr){let n={...o,settings:r},l={readers:[]};for(let u of Jt)if(!(s&&!s.includes(u)))try{let g=t[u]?.(e,n);g&&l.readers.push({id:u,claim:g,done:!1})}catch{}return l}function Ir(r){return{readers:r.readers.map(({id:e,done:o})=>({id:e,done:o}))}}function _e(r){let e=r.readers.find(({id:o})=>o==="conventions").claim;return{selectedPaths:e.wants,...e.state}}function Me(r,e){let o={dir:e.root??null,mode:e.profile==="hosted-import"?e.mode??"all":"all",flags:e.profile==="hosted-import"?e.flags??ee(r):ee(r)};if(e.profile==="hosted-import"){let n=Se(r,e.listing,o);return{profile:e.profile,...n,selection:_e(n)}}let s=e.listing.filter(n=>F(r,n,{purpose:"pointer",route:"github",root:e.root}).admitted),t=Se(r,s,o,["marker","code-scan"]);return{profile:e.profile,...t,listing:s,selection:e.selection??we(r,e.listing,e.root),context:o}}var G=20;function re(r,e,o,s){e.requestedPaths.push(...o);let t=ue(r,e.selected,o,s);e.selected=t.selected,e.refused.push(...t.refused)}function Pe(r,e,o){let s=r.hosted;if(!s)return;let t=new Set(e),n=r.selected.filter(l=>t.has(l.path));o==="code"?s.codePaths&&(s.codePaths=[...new Set([...s.codePaths,...n.map(l=>l.path)])]):s.weakCodeFallback&&(r.conventionPaths=[...new Set([...r.conventionPaths,...n.map(l=>l.path)])],s.fallback={...s.fallback,selectedPaths:[...new Set([...s.fallback.selectedPaths,...n.map(l=>l.path)])],shaByPath:{...s.fallback.shaByPath,...Object.fromEntries(n.map(l=>[l.path,l.ref]))}})}function be(r,e){let o=new Set(r.conventionPaths);if(r.decision.kind==="settled"&&r.decision.scanPaths&&r.markerKind&&r.markerKind!=="bare")for(let t of r.selected)o.add(t.path);let s=new Map(e.map(t=>[t.path,t]));for(let t of r.selected)o.has(t.path)&&!s.has(t.path)&&s.set(t.path,t);r.selected=[...s.values()],r.cursor=0,r.hosted&&(r.hosted.codeMode=!0,r.hosted.needsExtraction=!1)}function Yt(r,e=Pt(r.ranked,r.scan)){return e.agents.length>0}function Qt(r,e){if(r.hosted&&(r.hosted.codePaths=e.map(s=>s.path)),!r.hosted?.weakCodeFallback||r.hosted.codeMode||Yt(r)){be(r,e);return}let o=new Map(r.selected.map(s=>[s.path,s]));for(let s of e)o.has(s.path)||o.set(s.path,s);r.selected=[...o.values()],r.cursor=0}function Vt(r,e){let o=r.hosted;if(!o?.weakCodeFallback||!o.codePaths||r.markerKind&&r.markerKind!=="bare")return;let s=new Map([...r.entries,...r.selected].map(n=>[n.path,n]));Yt(r,e)?be(r,o.codePaths.map(n=>s.get(n))):(r.selected=o.fallback.selectedPaths.map(n=>s.get(n)),r.cursor=0,o.codeMode=!1,o.needsExtraction=o.fallback.needsExtraction);let t=new Set(r.selected.map(n=>n.path));r.files=Object.fromEntries(Object.entries(r.files).filter(([n])=>t.has(n)))}function Be(r,e){if(!I(r))return;let o=new Set(e.entries.map(n=>n.path)),s=Object.fromEntries(Object.entries(e.files).filter(([n])=>e.selected.some(l=>l.path===n&&l.readBytes===void 0))),t=new Set(de(r,[...o],s));for(let[n,l]of Object.entries(e.files)){let u=F(r,{path:n,text:l},{...e.admission,purpose:"override",route:"github",root:e.root,listing:o,managedFiles:e.files});(!u.admitted||t.has(n))&&(delete e.files[n],e.refused.push({path:n,reason:u.admitted?"unreadable":u.reason}))}}function N(r,e,o){Be(r,e);let s=e.selected.filter(u=>e.files[u.path]!==void 0),t=new Set(s.filter(u=>u.readBytes===void 0).map(u=>u.path)),n=new Set(e.requestedPaths),l=B(e.selectionRefused.filter(u=>!n.has(u.path)),e.refused).filter(u=>!t.has(u.path));return{state:e,requestedReads:o,files:e.files,settled:s,refused:l,treeTruncated:e.treeTruncated}}async function Zt(r,e,o){e.manifestReadPaths??=e.selected.slice(0,e.cursor).filter(a=>a.readBytes===void 0).map(a=>a.path);let s=new Set(e.selected.filter(a=>a.readBytes===void 0).map(a=>a.path)),t=Object.fromEntries(Object.entries(e.files).filter(([a])=>s.has(a))),n=new Map(e.entries.map(a=>[a.path,a.size])),l=new Map(Object.entries(e.files).map(([a,c])=>[a,Buffer.byteLength(c)]));for(let[a,c]of Object.entries(t))n.set(a,Buffer.byteLength(c));let u=Y(r,e.ranked,n,l,{files:t,root:e.root}),g=new Set(e.manifestReadPaths),h=u.paths.filter(a=>t[a]===void 0&&!g.has(a)),p=new Map(e.selected.filter(a=>a.readBytes!==void 0).map(a=>[a.path,a]));e.requestedPaths.push(...h.filter(a=>p.has(a))),re(r,e,h.filter(a=>!p.has(a)),e.entries);let f=new Set(h),w=new Map(e.entries.map(a=>[a.path,a])),b=e.selected.filter(a=>f.has(a.path)).map(a=>p.has(a.path)?w.get(a.path):a).slice(0,G);if(b.length){let a=await L(b,4,async y=>{let R=F(r,y,{...e.admission,purpose:"pointer",route:"github",root:e.root});return R.admitted?o(y):(e.refused.push({path:y.path,reason:R.reason}),null)});e.manifestReadPaths=[...e.manifestReadPaths,...b.map(y=>y.path)];let c=new Map(n);b.forEach((y,R)=>{a[R]!==null&&c.set(y.path,Buffer.byteLength(a[R]))});let d=new Map(b.filter((y,R)=>p.has(y.path)&&a[R]!==null).map(y=>[y.path,l.get(y.path)])),k=Y(r,e.ranked,c,l,{files:t,root:e.root,replacementBytes:d}),P=new Set(k.paths);b.forEach((y,R)=>{a[R]!==null&&(P.has(y.path)?(e.files[y.path]=a[R],e.selected=e.selected.map(S=>S.path===y.path?y:S)):e.refused.push(k.refused.find(S=>S.path===y.path)??{path:y.path,reason:"total"}))});return}let i=new Map((u.manifests??[]).map(a=>{let d=a.files.filter(k=>t[k.path]===void 0).map(k=>e.refused.find(P=>P.path===k.path)??{path:k.path,reason:"missing"});return[a.agentId,{...a,files:a.files.filter(k=>t[k.path]!==void 0),refused:[...a.refused,...d]}]})),m=a=>{let c=i.get(Ve(a.prompt));return c?{...a,manifest:c}:a};e.ranked={...e.ranked,strong:e.ranked.strong.map(m),possible:e.ranked.possible.map(m)},Pe(e,[...i.values()].flatMap(a=>a.files.map(c=>c.path)),"code"),e.refused.push(...[...i.values()].flatMap(wt)),e.phase="done"}async function er(r,e,o){if(!I(r))return!1;let s=Ge(r,e.entries.map(f=>f.path));if(!s.length)return!1;let t=new Set(s.flatMap(f=>f.agents)),n=new Map(e.selected.map(f=>[f.path,f])),l=new Set(e.selected.filter(f=>f.readBytes===void 0&&e.files[f.path]!==void 0).map(f=>f.path));e.managedReadPaths||(e.managedReadPaths=[],(e.scan||e.ranked)&&(delete e.scan,delete e.ranked,delete e.manifestReadPaths,e.phase!=="marker"&&(e.phase="scan")));let u=new Set([...e.managedReadPaths,...l]),g=e.entries.filter(f=>t.has(f.path)&&n.has(f.path)&&!u.has(f.path)),h=g.slice(0,G);if(!h.length)return!1;let p=await L(h,4,async f=>{let w=F(r,f,{...e.admission,purpose:"pointer",route:"github",root:e.root});return w.admitted?o(f):(e.refused.push({path:f.path,reason:w.reason}),null)});if(h.forEach((f,w)=>{p[w]!==null&&(e.files[f.path]=p[w],e.selected=e.selected.map(b=>b.path===f.path?f:b))}),e.managedReadPaths.push(...h.map(f=>f.path)),g.length>h.length){for(let f of Object.keys(e.files))!t.has(f)&&s.some(w=>C(f,w.folder)!==null)&&delete e.files[f];e.cursor=0,(e.phase==="done"||e.phase==="manifest")&&(e.phase="files")}return!0}function tr(r,e){let{plan:o,entries:s}=e,t=o.profile==="local-analysis"?o.context.dir??"":e.root??"",n=o.readers.find(p=>p.id==="marker")?.claim.wants[0],l=o.readers.some(p=>p.id==="code-scan"),u=new Map(s.map(p=>[p.path,p])),g=o.profile==="local-analysis"?o.selection.selected:o.selection.selectedPaths.flatMap(p=>u.has(p)?[u.get(p)]:[]),h=St(r)?U(r,{phase:"start",root:t,paths:s.map(p=>p.path),scanFlag:!!n||l}):void 0;return{version:1,profile:o.profile,root:t,entries:s,selected:[...g],conventionPaths:o.profile==="hosted-import"?X(r,s.map(p=>p.path),t).files.filter(p=>p.role!=="reference").map(p=>p.path):[],...e.admission?{admission:e.admission}:{},selectionRefused:o.selection.refused,requestedPaths:[],refused:[],files:{},cursor:0,treeTruncated:e.treeTruncated??!1,...o.profile==="hosted-import"?{hosted:{fallback:structuredClone(o.selection),weakCodeFallback:r.CF_IMPORT_WEAK_CODE_FALLBACK!=="0",codeMode:!1,needsExtraction:o.selection.needsExtraction}}:{},decision:h??(n?{kind:"marker",markerPath:n,scanIfBare:l}:{kind:"settled",markerPath:null,markerKind:null,scan:l}),phase:n?"marker":l?"scan":"files"}}function Lr(r,e){e.ranked??=me(r,e.scan,new Map);let o=Y(r,e.ranked,vt(e.scan.plan),new Map),s=[...o.refused,...e.ranked.skippedFiles??[]];if(e.requestedPaths.push(...s.map(t=>t.path)),e.refused.push(...s),e.profile==="hosted-import"&&o.paths.length){let t=ue(r,[],o.paths,e.scan.plan);e.refused.push(...t.refused),Qt(e,t.selected)}else re(r,e,o.paths,e.scan.plan);e.phase=e.selected.length?"files":"done"}async function rr(r,e,o){if(e.version!==1)throw new Error("unsupported-import-checkpoint");let s=e.profile==="hosted-import"?{...r,CF_IMPORT_CALLS:"0"}:r,t={...e,selected:[...e.selected],files:{...e.files},requestedPaths:[...e.requestedPaths],refused:[...e.refused],...e.hosted?{hosted:{...e.hosted}}:{},...e.managedReadPaths?{managedReadPaths:[...e.managedReadPaths]}:{}},n=new Set(t.entries.map(i=>i.path)),l=Object.fromEntries(Object.entries(t.files).filter(([i])=>t.selected.some(m=>m.path===i&&m.readBytes===void 0))),u=new Set(de(s,[...n],l)),g=[],h=new Set,p=async i=>{if(u.has(i.path)||t.managedReadPaths?.includes(i.path)&&t.files[i.path]===void 0)return t.refused.push({path:i.path,reason:"unreadable"}),null;g.push(i);try{let m=await o.read(i);if(m!==null){if(h.has(i.path)){let a=F(s,{path:i.path,size:Buffer.byteLength(m),text:m},{...t.admission,purpose:"skill",route:"github",root:t.root,listing:n,managedFiles:t.files});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}if(I(s)||ne(s)){let a=F(s,{path:i.path,text:m},{...t.admission,purpose:"override",route:"github",root:t.root,listing:n,managedFiles:t.files});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}if(t.phase==="manifest"){let a=F(s,{path:i.path,size:Buffer.byteLength(m)},{...t.admission,purpose:"pointer",route:"github",root:t.root});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}return m}}catch(m){if(m instanceof Xe&&(m.reason==="secret-content"||I(s)||h.has(i.path)))return t.refused.push({path:i.path,reason:m.reason}),null;if(t.profile==="hosted-import"&&!h.has(i.path))throw m}return t.refused.push({path:i.path,reason:"unreadable"}),null};if(await er(s,t,p))return N(s,t,g);if(Be(s,t),t.phase==="done")return o.resolvedCode&&Vt(t,o.resolvedCode),N(s,t,g);if(t.phase==="manifest")return await Zt(s,t,p),N(s,t,g);if(t.phase==="marker"&&t.decision.kind==="marker"){let i=t.decision,m=i.markerPath,a=t.entries.find(d=>d.path===m);if(t.profile==="hosted-import"){let d=F(s,a,{purpose:"pointer",route:"github",root:t.root});if(!d.admitted)return t.refused.push({path:m,reason:d.reason}),t.decision={kind:"settled",markerPath:null,markerKind:null,scan:i.scanIfBare},t.phase=i.scanIfBare?"scan":"files",N(s,t,g)}re(s,t,[m],t.entries);let c=await p(a);if(c!==null&&(t.files[m]=c),t.decision=U(s,{phase:"read",pending:i,text:c}),t.markerPath=m,t.markerKind=t.decision.markerKind,t.markerKind!=="bare"){let d=t.profile==="hosted-import"?await o.listing():{entries:t.entries,truncated:!1};t.treeTruncated||=d.truncated;let k=await Ct(s,{config:ut(c).config,markerDir:m.split("/").slice(0,-1).join("/"),selected:t.profile==="hosted-import"?[]:t.selected,admission:{...t.admission,root:t.root||void 0},modelReader:!1,priorRefused:t.refused,refusalMode:"append",requestedMode:"kept-and-refused",listing:async()=>d.entries});t.requestedPaths.push(...k.requestedPaths),t.refused=k.refused,t.profile==="hosted-import"?be(t,k.selected??[]):k.selected&&(t.selected=k.selected)}if(t.phase=t.decision.scan?"scan":"files",t.profile!=="hosted-import"||t.markerKind!=="bare"||t.decision.scan)return N(s,t,g)}if(t.phase==="scan"){if(!t.scan){let i=xt(s,t.entries,t.root,!0,t.decision.kind==="settled"?t.decision.scanPaths:void 0);t.scan=i.state,t.refused.push(...i.refused)}if(!te(t.scan)){let i=await Ot(s,t.scan,p,{modelReader:!1,alreadyRead:new Map,size:{batch:yt,parallel:4}});t.scan=i.scan,i.selection&&(t.ranked=i.selection.ranked)}return te(t.scan)&&Lr(s,t),N(s,t,g)}xe(s)&&(h=new Set(t.skillReferencePaths));let f=t.selected.slice(t.cursor,t.cursor+G),w=f.filter(i=>t.files[i.path]===void 0),b=await L(w,4,p);if(w.forEach((i,m)=>{b[m]!==null&&(t.files[i.path]=b[m])}),t.cursor+=f.length,xe(s)){let i=Object.fromEntries(Object.entries(t.files).filter(([P])=>t.selected.some(y=>y.path===P&&y.readBytes===void 0))),m=Ae(s,{entries:t.entries,selected:t.selected,files:i,root:t.root,admission:t.admission,referencePaths:t.skillReferencePaths});t.refused=B(t.refused,m.refused);for(let P of m.refused)h.has(P.path)&&delete t.files[P.path];if(t.cursor<t.selected.length)return N(s,t,g);let a=new Map(t.selected.map(P=>[P.path,P])),c=m.paths.filter(P=>!a.has(P)||a.get(P).readBytes!==void 0),d=new Set(c.filter(P=>a.has(P)));t.cursor-=t.selected.slice(0,t.cursor).filter(P=>d.has(P.path)).length,t.selected=t.selected.filter(P=>!d.has(P.path));for(let P of d)delete t.files[P];t.requestedPaths.push(...c),c.length&&(t.skillReferencePaths=[...t.skillReferencePaths??[],...c]);let k=new Map(t.entries.map(P=>[P.path,P]));t.selected.push(...c.map(P=>{let y=k.get(P);return{path:P,size:y.size,ref:y.ref}})),Pe(t,c,"fallback")}return t.cursor>=t.selected.length&&(t.phase=pe(s)&&t.ranked?"manifest":"done"),N(s,t,g)}async function or(r,e){let o=tr(r,e),s;do s=await rr(r,o,{listing:async()=>({entries:e.entries,truncated:!1}),read:e.read}),o=s.state;while(o.phase!=="done");let t={};return o.markerPath!==void 0&&(t.markerPath=o.markerPath,t.markerKind=o.markerKind),o.ranked!==void 0&&(t.ranked=o.ranked,t.scan=o.scan),{files:s.files,settled:s.settled,skippedFiles:s.refused,...t}}async function Te(r,e){let o=Me(r,{profile:"local-analysis",listing:e.entries,selection:e.selection}),{files:s,settled:t,skippedFiles:n,...l}=await or(r,{entries:e.entries,read:e.read,admission:e.admission,plan:o}),u=s,g=t,h=n,p=Q({key:e.repoKey,files:u,...l},o.context.flags,void 0,{markerPolicy:"any-read"}),{selection:f}=o,w;if(mt(r)&&e.repository){let a=await ht(r,{selected:{files:u,listedPaths:e.entries.map(d=>d.path),fallbackName:bt(e),skills:!0},selection:f,codeAgentsFound:(p?.resolved?.agents.length??0)>0,port:e.repository}),c=new Set(Object.keys(u).map(d=>W(d,a.root)));if(u=a.files,f=a.selection,w=a.root,w!==void 0){h=h.map(k=>({...k,path:W(k.path,w)})),g=g.map(k=>({...k,path:W(k.path,w)}));let d=new Set(g.map(k=>k.path));g.push(...f.selected.filter(k=>!d.has(k.path)&&Object.hasOwn(u,k.path)))}h=B(h,a.skippedFiles).filter(d=>c.has(d.path)||!Object.hasOwn(u,d.path))}let b={repoKey:e.repoKey,files:u,listedPaths:e.entries.map(a=>W(a.path,w)),...w!==void 0?{root:w}:{},forLocal:!0,code:p},i=Z(r,V(r,b)),m=f.readingNotes?$(r,f.readingNotes,g):f.skippedNote;return{...i,files:u,...w!==void 0?{root:w}:{},skippedFiles:h,warnings:[...new Set([...i.warnings,...m?[m]:[],...ae(h)])],selection:f}}var Nr=new Set;function jr(r,e={}){let o=ze(e.dir),s=e.limits??v.archive,t=e.listing??Nr,n={commit:null,files:new Map,skipped:[]},l=new Set,u=0,g=0;function h(i){let m=i.replace(/\/$/,"").split("/");return!i.startsWith("/")&&!i.includes("\\")&&!/^[a-z]:/i.test(i)&&!m.some(a=>a===".."||a==="."||!a)}function p(i,m,a,c=t){if(!a||!h(i)||!Number.isSafeInteger(m)||m<0)return"refused";let d=F(r,{path:i,size:m},{purpose:"archive",route:"github",root:o});return d.admitted?e.exampleFolders?.some(k=>i.startsWith(k))||qe(i,{root:o,listing:c})?"example":null:d.reason==="excluded"&&Ue(r,i,o)?"example":d.reason==="excluded"||d.reason==="wrong-type"?"excluded":"refused"}function f(i,m){l.has(i)||(l.add(i),n.skipped.push({path:i,reason:m}))}function w(i,m=t){let a=i.split("/");for(let c=1;c<=a.length;c++){let d=a.slice(0,c).join("/");if(d===o||o.startsWith(`${d}/`))continue;if(C(d,o)===null)return!1;let k=p(`${d}/`,0,!0,m);if(k)return f(`${d}/`,k),!1}return!0}function b(i,m,a=!0){if(C(i,o)===null)return!1;if(!h(i))return f(i,"refused"),!1;let c=i.split("/");if(c.length>1&&!w(c.slice(0,-1).join("/")))return!1;let d=p(i,m,a);return d?(f(i,d),!1):g>=s.files||m>s.bytes-u?(f(i,"over-limit"),!1):(u+=m,g++,!0)}return{result:n,accept:b,enterFolder:w}}var Kr=new Set(ve);function Hr(r,e){for(let s of[...Object.keys(e.set),...e.clear])if(!Kr.has(s))throw new Error(`Unknown analysis field: ${s}`);let o={...r,...e.set};for(let s of e.clear)o[s]=void 0;return o}function sr(r){return r.CF_MODEL_READER!=="0"}async function Dr(r,e,o,s){o=z(r,o);let t=structuredClone(e);for(t.files??={},t.cursor=0;;){let n=await ge(r,t,o,s);if(n){t=n;continue}let l=t.selected??[];if((t.cursor??0)>=l.length)return t;let u=l.slice(t.cursor).filter(p=>!Object.hasOwn(t.files,p.path)),g=[],h=await L(u,4,async p=>{try{return{path:p.path,text:await he(p,f=>o.read(f),g,t.refused)}}catch(f){return{error:f}}});for(let p of h){if("error"in p)throw p.error;p.text!==null&&(t.files[p.path]=p.text)}g.length&&(t.refused=B(t.refused,g)),t.cursor=l.length}}async function nr(r,e,o,s){let{codeFindingNote:t}=kt(s),n={deriveBytes:0,codeEvidence:[]};if(!e.findingQuality?.config.switches.codeInputs||!e.projectAgents?.enabled)return n;let l=e.projectAgents,u=(e.repos??[]).filter(c=>[...l.byRepo[c.key]??[],...l.codeByRepo?.[c.key]??[]].some(d=>d.codeInputsJson&&(d.codeInputsJson.tools.length||d.codeInputsJson.contextInputs.length))),h=(await L(u,1,async c=>{try{let d=o.find(k=>k.repoKey===c.key);if(!d)throw new Error("Source reader is missing.");return{repo:await Dr(r,c,d,e.modelReader??!1)}}catch(d){return{error:d}}})).map(c=>{if("error"in c)throw c.error;return c.repo}),p=h.map(c=>{let d=ke(r,c,q(r,e),e.modelReader,l);return Object.assign(c.files,d.virtualFiles),d.fragment}),f=Object.fromEntries(h.map(c=>[c.key,c.files??{}])),b=Bt({...e,repos:h,mapped:p}).findingQuality?.codeEvidence?.filter(c=>Object.keys(c.input.files).length)??[];if(!b.length)return n;let i=b.map(c=>({repo:c.repo,unitKey:c.unitKey,enabled:!0,inputs:[c.input],files:f[c.repo]}));return{deriveBytes:[...new Map(b.flatMap(c=>Object.entries(c.input.files).map(([d,k])=>[JSON.stringify([c.repo,d]),{path:d,text:k}]))).values()].reduce((c,{path:d,text:k})=>c+Buffer.byteLength(`### ${d}
2
2
  \`\`\`
3
- ${it(S)}
3
+ ${ot(k)}
4
4
  \`\`\`
5
5
 
6
- `),0)+Buffer.byteLength(t(P.flatMap(c=>c.input.sources))),codeEvidence:i}}function ur(r,e,o,s,t){let n=e.analysisFlags,d=[],h=new Set,u=0,k=0;for(let m of e.repos??[]){k+=(m.selected??[]).reduce((y,g)=>y+(g.readBytes??g.size),0),d.push(...(m.selected??[]).map(y=>({path:v(y.path,m.root)??y.path,size:y.size})));let S=st(e.projectAgents,m.key,{nodes:[],edges:[],warnings:[]},t);for(let[y,g]of Object.entries(S.files)){let x=yt(g).length;u+=x,d.push({path:y,size:x}),h.add(y)}}u+=k;let l=$t(d,n.multiPass,h),f=l>1?24:at,b=(h.size?u:Math.min(u,15e4))+s.deriveBytes,P=Oe("derive",r,o),i=Array.from({length:l},(m,S)=>A(r,{template:P},l>1?`Derive findings (part ${S+1} of ${l})`:"Derive findings",M.generate,K(b+Vt(u,l))+4e3,De)),p=n.multiPass&&h.size?k:Math.min(k,15e4);i.push(A(r,{template:"derive-structure"},"Structural pass",M.generate,K(p)+4e3,12e3));let a=Math.ceil(f/Ue)*(1+qe);i.push(A(r,{template:"scope-findings"},"Scope check",o.switches.enabled?o.models.scope:M.mechanical,a*(4e3+K(s.scopeBytes)),a*1e3));let c=ct(r,f,n.findingCheck??!0,Oe("check",r,o),o.switches.fullContext?"whole-file":"legacy");return c&&i.push(c),(n.sourceNotes??!0)&&i.push(A(r,{template:"explain-sources"},"Explain sources",Dt,K(qt)*f,Ut*f)),e.codeAgents?.model&&e.repos?.some(m=>m.scanNeeded)&&i.push(A(r,{template:"judge-code-prompt"},"Check possible agents in code",M.mechanical,6*3e3,1200)),i.push(...Gt(Ie(r),r)),i}var Gr=async(r,e)=>{if(e.progress.assertHeld(),e.progress.signal?.throwIfAborted(),!e.model)throw new Re("llm","Analysis needs a live model; no provider key is configured.");if(!e.readers.length)throw new Re("not_found","This project has no analyzable repository.");let o=r.execution.preparation;if(!o)throw new Error("Preparation options are required for estimation.");let{state:s,settings:t}=r;await z(t,s,e.readers),await e.context.refreshStructureParts?.().catch(()=>{});let n=U(await e.instructions()),d=J(n),h=n.bundleText("model-reader-runtime-prompt"),u=[...s.warnings??[]],k=V(t,s),l=s.modelReader??mt(t),f=s.codeImportV2??le(t),b=s.analysisFlags?ne(t,s):He(t),P=s.findingQuality??{config:o.qualityConfig},i=await ot(t,s.projectAgents,e.context.loadProjectAgents,void 0,P.config.switches.codeInputs),p=[],a=[],c=e.readers.map(O=>q(t,O));for(let O of c){e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let se=await O.head(),Ke=await O.list(),j=be(t,Ke,O.root);!j.readingNotes&&j.skippedNote&&u.push(`${O.repoKey}: ${j.skippedNote}`),a.push({key:O.repoKey,kind:"github",root:O.root,selected:j.selected}),p.push({key:O.repoKey,...O.source??{kind:O.repoKey.startsWith("local:")?"fs":"github"},headSha:se.sha,branch:se.branch,selected:j.selected,...j.readingNotes?{sourceReadNotes:j.readingNotes}:{},cursor:0,files:{},...O.root?{root:O.root}:{},...jt(t,Ke,j.selected,O.root,k,l,f)})}let m={...s,repos:p,projectAgents:i,codeAgents:k,modelReader:l,codeImportV2:f,analysisFlags:b,findingQuality:P};await z(t,m,c);let S=await fr(t,m,c,n),{sources:y,files:g}=Be({qualityConfig:P.config,codeEvidence:S.codeEvidence}),x=d.enrichRequestInputs("scope-findings",{codeSources:y,codeFiles:g},t),w=Buffer.byteLength(String(x.code))+Math.max(0,Buffer.byteLength(String(x.system))-Buffer.byteLength(d.RULE)),E=[...o.uploadReadingAllowance?[o.uploadReadingAllowance]:[],...ur(t,{...m,repos:a},P.config,{deriveBytes:S.deriveBytes,scopeBytes:w},h)],F=await e.context.loadOpenStructures?.()??[],I=(await e.context.loadPendingRechecks?.().catch(()=>[])??[]).reduce((O,se)=>O+se.children.length,0);I&&E.push(A(t,{template:"structure-recheck"},"Post-merge re-check",M.mechanical,I*3e3,I*300));let T=await e.context.chatFindingCount?.().catch(()=>(e.progress.log({level:"warn",code:"chat.count_failed"}),0))??0;T&&E.push(A(t,{},"Re-check chat findings",M.mechanical,T*3e3,T*300));let Fe=ce(E,o.capUsd);return de(Fe),{next:o.confirmPrice?"awaiting_confirm":"fetching_files",clear:[],estimate:Fe,set:{repos:p,warnings:u,openStructures:F,codeAgents:k,modelReader:l,codeImportV2:f,analysisFlags:b,projectAgents:i,findingQuality:P,...b.splitCheck?{splitEstimateBase:Fe}:{}}}};var Wr=async({state:r,settings:e},o)=>{o.progress.assertHeld(),o.progress.signal?.throwIfAborted();let s=[...r.repos??[]];await z(e,r,o.readers);let t=r.repoCursor??0;if(t>=s.length)return{next:"mapping",set:{repoCursor:0},clear:[]};let n=structuredClone(s[t]),d=o.readers.find(a=>a.repoKey===n.key);if(!d)throw new Error(`no reader for ${n.key}`);let h=q(e,d),u=pe(r).remapping,k=await Se(e,n,h,r.modelReader??!1,u);if(k)return s[t]=k,{next:"fetching_files",set:{repos:s},clear:[]};let l=n.selected??[],f=n.cursor??0,b=l.slice(f,f+20),P={...n.files??{}},i=[];for(let a of b){if(o.progress.assertHeld(),o.progress.signal?.throwIfAborted(),P[a.path]!==void 0)continue;let c=await we(a,m=>h.read(m),i,n.refused);c!==null&&(P[a.path]=c)}i.length&&(n.refused=B(n.refused,i)),n.files=P,n.cursor=f+b.length,s[t]=n;let p=n.cursor>=l.length&&!Kt(n);return{next:"fetching_files",set:{repos:s,repoCursor:p?t+1:t},clear:[]}};async function Xr(r,e){let o=e.admission?.exclusions?.length?e.entries.filter(n=>R(r,n,{purpose:"override",route:"github",...e.admission}).admitted):e.entries,s=_(r)?new Set(o.map(n=>n.path)):void 0,t=!e.admission?.exclusions?.length&&!ae(r)?e.read:n=>Ze(r,n,e.read,{...e.admission,...s?{listing:s}:{}});return je(r,{...e,entries:o,read:t})}async function Jr(r,e,o){let s=Object.entries(e).map(([n,d])=>({path:n,size:Buffer.byteLength(d),ref:n})),t=At(r,s,o.root,!1,o.scanPaths);for(;!re(t);)t=await Bt(t,async n=>e[n.path]??null);return{scan:ge(r,t),summary:Tt(t)}}async function gr(r,e,o){let{repoKey:s,root:t,codingGuides:n,forLocal:d}=o,h=o.flags??te(r),u=Object.keys(e),k=$(r,{phase:"start",paths:u,root:t,scanFlag:h.scan}),l=k.kind==="marker"?$(r,{phase:"read",pending:k,text:e[k.markerPath]??null}):k,f=l.kind==="off"?null:l.markerPath,b=l.kind==="off"?null:l.markerKind;if(l.kind==="off"||!l.scan){let m=Q({key:s,files:e,markerPath:f,markerKind:b},h,void 0,{markerPolicy:"any-read"});return{...ee(r,Z(r,{repoKey:s,files:e,root:t,codingGuides:n,forLocal:d,code:m})),scanned:!1,resolved:null}}let{scan:P,summary:i}=await Jr(r,e,{repoKey:s,root:t,scanPaths:l.scanPaths}),p=Q({key:s,files:e,ranked:P,scan:i,markerPath:f,markerKind:b},h,void 0,{markerPolicy:"any-read"});return{...ee(r,Z(r,{repoKey:s,files:e,root:t,codingGuides:n,forLocal:d,code:p})),scanned:!0,resolved:p.resolved}}async function kr(r,e){let{state:o,settings:s}=r;if(!ne(s,o).splitCheck||!o.splitEstimateBase)return{next:"inspecting",set:{repoCursor:0},clear:[]};let n=r.execution.preparation?.capUsd??o.splitEstimateBase.capUsd,d={...o.splitEstimateBase,capUsd:n};de(d);let h=Wt(s,o),u={next:"inspecting",set:{repoCursor:0,splitCheckPriced:!0,splitFindingsPriced:!0},clear:["splitEstimateBase"]};if(!h.length)return u;let k=J(U(await e.instructions())),l=h.reduce((p,{inventory:a})=>p+K(Buffer.byteLength(Jt({tools:k},{...a,findings:[]}).prompt))+K(k.SHAPE_FINDINGS_INPUT_BYTES),0),f=d.lines.find(p=>p.label==="Scope check"),b=A(s,{template:"scope-findings"},"Scope check",M.mechanical,(f?.inputTokens??0)+h.length*Qt,(f?.outputTokens??0)+h.length*Yt),P=d.lines.map(p=>p.label==="Scope check"?b:p);f||P.push(b),P.push(A(s,{template:"derive-shape"},"Split check",Xt,l,h.length*ut));let i=ce(P,n);return ze(i)?(u.estimate=d,u.clear.push("splitCheckPriced","splitFindingsPriced"),delete u.set.splitCheckPriced,delete u.set.splitFindingsPriced,u.set.warnings=[...o.warnings??[],`The split check was skipped because its estimate (${ve(i.totalUsd)}) exceeds the ${ve(i.capUsd)} cap. The rest of the analysis continues.`]):u.estimate=i,u}var Yr=async(r,e)=>{e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let{state:o,settings:s}=r,t=o.repos??[];await z(s,o,e.readers);let n=o.repoCursor??0;if(n>=t.length)return kr(r,e);let d=t[n],h=r.execution.forLocal,u=h?o.mapped?.[n]?{fragment:Me(o,n),warnings:[]}:await gr(s,d.files??{},{repoKey:d.key,root:d.root,forLocal:!0}):void 0,k=pe(o).remapping,l=u?(()=>{let p=nt(u.fragment,d.key);return{...p,warnings:[...u.warnings,...p.warnings]}})():Pe(s,d,V(s,o),o.modelReader??!1,o.projectAgents,k,U(await e.instructions()).bundleText("model-reader-runtime-prompt")),f=!h&&d.sourceReadNotes?G(s,d.sourceReadNotes,d.selected??[],d.root):void 0,b=h?[]:ie((d.refused??[]).filter(p=>p.reason==="secret-content")),P="virtualFiles"in l?l.virtualFiles:void 0,i=[...o.mapped??[]];return i[n]=l.fragment,{next:"mapping",clear:[],set:{...P?{repos:t.map((p,a)=>a===n?{...p,files:{...p.files,...P}}:p)}:{},mapped:i,warnings:[...o.warnings??[],...f?[`${d.key}: ${f}`]:[],...b,...l.warnings,...Ht(d)],repoCursor:n+1}}};function Qr(r,e){let o=e?.findingHeadlineDiagnostics??(r.findingHeadlines?.version===2?r.findingHeadlines.diagnostics:r.findingHeadlineDiagnostics);return{set:{...o?{findingHeadlineDiagnostics:o}:{},repos:(r.repos??[]).map(s=>({...s,files:{},selected:[],scan:void 0,ranked:void 0})),...r.projectAgents?{projectAgents:{enabled:r.projectAgents.enabled,byRepo:{}}}:{}},clear:["passResults","sourceNotes","findingHeadlines","findingsRaw","structuresRaw","loadModes","rechecks","recheckedChangeIds","readPaths","inspectPlan","passFindings","codeChecks","newVerdicts",...r.shapeFindings?["shapeFindings"]:[]]}}export{Ae as ANALYSIS_FIELDS,xr as InputBudgetError,M as MODELS,R as admitFile,Cr as analysisFieldsOf,Or as analysisRuntime,Dr as applyAnalysisDelta,Mr as buildAnalysisResult,yr as buildRequest,U as createInstructionText,Er as createRequestRegistry,J as createRequestTools,je as discoverLocalSources,ye as discoverReaders,Gr as estimateStage,Xr as fetchLocalSources,Wr as fetchStage,vr as fetchedPathsOf,Ie as findingHeadlinesEnabled,Qr as finishAnalysis,Br as headlinesStage,Ir as inspectStage,Yr as mapStage,Nr as planForJob,Le as planImport,wr as readFindingQualityConfig,br as render,Hr as repoCollector,Pr as resolveAgents,Me as savedFragmentAt,Rr as savedFragmentsOf,Be as scopeCodeContext,_e as selectionOfPlan,Sr as snapshotSettings,Ar as sourceNotesStage,Tr as structureStage,Fr as trySavedFragmentAt};
6
+ `),0)+Buffer.byteLength(t(b.flatMap(c=>c.input.sources))),codeEvidence:i}}function cr(r,e,o,s,t){let n=e.analysisFlags,l=[],u=new Set,g=0,h=0;for(let d of e.repos??[]){h+=(d.selected??[]).reduce((P,y)=>P+(y.readBytes??y.size),0),l.push(...(d.selected??[]).map(P=>({path:C(P.path,d.root)??P.path,size:P.size})));let k=et(e.projectAgents,d.key,{nodes:[],edges:[],warnings:[]},t);for(let[P,y]of Object.entries(k.files)){let R=at(y).length;g+=R,l.push({path:P,size:R}),u.add(P)}}g+=h;let p=Nt(l,n.multiPass,u),f=p>1?24:rt,w=(u.size?g:Math.min(g,15e4))+s.deriveBytes,b=Fe("derive",r,o),i=Array.from({length:p},(d,k)=>_(r,{template:b},p>1?`Derive findings (part ${k+1} of ${p})`:"Derive findings",M.generate,K(w+jt(g,p))+4e3,Ke)),m=n.multiPass&&u.size?h:Math.min(h,15e4);i.push(_(r,{template:"derive-structure"},"Structural pass",M.generate,K(m)+4e3,12e3));let a=Math.ceil(f/He)*(1+De);i.push(_(r,{template:"scope-findings"},"Scope check",o.switches.enabled?o.models.scope:M.mechanical,a*(4e3+K(s.scopeBytes)),a*1e3));let c=st(r,f,n.findingCheck??!0,Fe("check",r,o),o.switches.fullContext?"whole-file":"legacy");return c&&i.push(c),(n.sourceNotes??!0)&&i.push(_(r,{template:"explain-sources"},"Explain sources",Tt,K(Lt)*f,It*f)),e.codeAgents?.model&&e.repos?.some(d=>d.scanNeeded)&&i.push(_(r,{template:"judge-code-prompt"},"Check possible agents in code",M.mechanical,6*3e3,1200)),i.push(...Kt(Re(r),r)),i}var $r=async(r,e)=>{if(e.progress.assertHeld(),e.progress.signal?.throwIfAborted(),!e.model)throw new ye("llm","Analysis needs a live model; no provider key is configured.");if(!e.readers.length)throw new ye("not_found","This project has no analyzable repository.");let o=r.execution.preparation;if(!o)throw new Error("Preparation options are required for estimation.");let{state:s,settings:t}=r;await H(t,s,e.readers),await e.context.refreshStructureParts?.().catch(()=>{});let n=D(await e.instructions()),l=J(n),u=n.bundleText("model-reader-runtime-prompt"),g=[...s.warnings??[]],h=q(t,s),p=s.modelReader??sr(t),f=s.analysisFlags?se(t,s):Le(t),w=s.findingQuality??{config:o.qualityConfig},b=await Ze(t,s.projectAgents,e.context.loadProjectAgents,void 0,w.config.switches.codeInputs),i=[],m=[],a=e.readers.map(O=>z(t,O));for(let O of a){e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let oe=await O.head(),Ie=await O.list(),j=we(t,Ie,O.root);!j.readingNotes&&j.skippedNote&&g.push(`${O.repoKey}: ${j.skippedNote}`),m.push({key:O.repoKey,kind:"github",root:O.root,selected:j.selected}),i.push({key:O.repoKey,...O.source??{kind:O.repoKey.startsWith("local:")?"fs":"github"},headSha:oe.sha,branch:oe.branch,selected:j.selected,...j.readingNotes?{sourceReadNotes:j.readingNotes}:{},cursor:0,files:{},...O.root?{root:O.root}:{},...At(t,Ie,j.selected,O.root,h,p)})}let c={...s,repos:i,projectAgents:b,codeAgents:h,modelReader:p,analysisFlags:f,findingQuality:w};await H(t,c,a);let d=await nr(t,c,a,n),{sources:k,files:P}=Ce({qualityConfig:w.config,codeEvidence:d.codeEvidence}),y=l.enrichRequestInputs("scope-findings",{codeSources:k,codeFiles:P},t),R=Buffer.byteLength(String(y.code))+Math.max(0,Buffer.byteLength(String(y.system))-Buffer.byteLength(l.RULE)),S=[...o.uploadReadingAllowance?[o.uploadReadingAllowance]:[],...cr(t,{...c,repos:m},w.config,{deriveBytes:d.deriveBytes,scopeBytes:R},u)],E=await e.context.loadOpenStructures?.()??[],x=(await e.context.loadPendingRechecks?.().catch(()=>[])??[]).reduce((O,oe)=>O+oe.children.length,0);x&&S.push(_(t,{template:"structure-recheck"},"Post-merge re-check",M.mechanical,x*3e3,x*300));let A=await e.context.chatFindingCount?.().catch(()=>(e.progress.log({level:"warn",code:"chat.count_failed"}),0))??0;A&&S.push(_(t,{},"Re-check chat findings",M.mechanical,A*3e3,A*300));let T=ie(S,o.capUsd);return ce(T,e.progress.log),{next:o.confirmPrice?"awaiting_confirm":"fetching_files",clear:[],estimate:T,set:{repos:i,warnings:g,openStructures:E,codeAgents:h,modelReader:p,analysisFlags:f,projectAgents:b,findingQuality:w,...f.splitCheck?{splitEstimateBase:T}:{}}}};var Gr=async({state:r,settings:e},o)=>{o.progress.assertHeld(),o.progress.signal?.throwIfAborted();let s=[...r.repos??[]];await H(e,r,o.readers);let t=r.repoCursor??0;if(t>=s.length)return{next:"mapping",set:{repoCursor:0},clear:[]};let n=structuredClone(s[t]),l=o.readers.find(m=>m.repoKey===n.key);if(!l)throw new Error(`no reader for ${n.key}`);let u=z(e,l),g=await ge(e,n,u,r.modelReader??!1);if(g)return s[t]=g,{next:"fetching_files",set:{repos:s},clear:[]};let h=n.selected??[],p=n.cursor??0,f=h.slice(p,p+20),w={...n.files??{}},b=[];for(let m of f){if(o.progress.assertHeld(),o.progress.signal?.throwIfAborted(),w[m.path]!==void 0)continue;let a=await he(m,c=>u.read(c),b,n.refused);a!==null&&(w[m.path]=a)}b.length&&(n.refused=B(n.refused,b)),n.files=w,n.cursor=p+f.length,s[t]=n;let i=n.cursor>=h.length&&!_t(n);return{next:"fetching_files",set:{repos:s,repoCursor:i?t+1:t},clear:[]}};async function Wr(r,e){let o=e.admission?.exclusions?.length?e.entries.filter(n=>F(r,n,{purpose:"override",route:"github",...e.admission}).admitted):e.entries,s=I(r)?new Set(o.map(n=>n.path)):void 0,t=!e.admission?.exclusions?.length&&!ne(r)?e.read:n=>Je(r,n,e.read,{...e.admission,...s?{listing:s}:{}});return Te(r,{...e,entries:o,read:t})}async function Xr(r,e,o){let s=Object.entries(e).map(([n,l])=>({path:n,size:Buffer.byteLength(l),ref:n})),t=Et(r,s,o.root,!1,o.scanPaths);for(;!te(t);)t=await Ft(t,async n=>e[n.path]??null);return{scan:me(r,t),summary:Rt(t)}}async function dr(r,e,o){let{repoKey:s,root:t,codingGuides:n,forLocal:l}=o,u=o.flags??ee(r),g=Object.keys(e),h=U(r,{phase:"start",paths:g,root:t,scanFlag:u.scan}),p=h.kind==="marker"?U(r,{phase:"read",pending:h,text:e[h.markerPath]??null}):h,f=p.kind==="off"?null:p.markerPath,w=p.kind==="off"?null:p.markerKind;if(p.kind==="off"||!p.scan){let d=Q({key:s,files:e,markerPath:f,markerKind:w},u,void 0,{markerPolicy:"any-read"});return{...Z(r,V(r,{repoKey:s,files:e,root:t,codingGuides:n,forLocal:l,code:d})),scanned:!1,resolved:null}}let{scan:b,summary:i}=await Xr(r,e,{repoKey:s,root:t,scanPaths:p.scanPaths}),m=Q({key:s,files:e,ranked:b,scan:i,markerPath:f,markerKind:w},u,void 0,{markerPolicy:"any-read"});return{...Z(r,V(r,{repoKey:s,files:e,root:t,codingGuides:n,forLocal:l,code:m})),scanned:!0,resolved:m.resolved}}async function lr(r,e){let{state:o,settings:s}=r;if(!se(s,o).splitCheck||!o.splitEstimateBase)return{next:"inspecting",set:{repoCursor:0},clear:[]};let n=r.execution.preparation?.capUsd??o.splitEstimateBase.capUsd,l={...o.splitEstimateBase,capUsd:n};ce(l,e.progress.log);let u=Ht(s,o),g={next:"inspecting",set:{repoCursor:0,splitCheckPriced:!0,splitFindingsPriced:!0},clear:["splitEstimateBase"]};if(!u.length)return g;let h=J(D(await e.instructions())),p=u.reduce((m,{inventory:a})=>m+K(Buffer.byteLength(zt({tools:h},{...a,findings:[]}).prompt))+K(h.SHAPE_FINDINGS_INPUT_BYTES),0),f=l.lines.find(m=>m.label==="Scope check"),w=_(s,{template:"scope-findings"},"Scope check",M.mechanical,(f?.inputTokens??0)+u.length*qt,(f?.outputTokens??0)+u.length*Ut),b=l.lines.map(m=>m.label==="Scope check"?w:m);f||b.push(w),b.push(_(s,{template:"derive-shape"},"Split check",Dt,p,u.length*gt));let i=ie(b,n);return Ne(i)?(g.estimate=l,g.clear.push("splitCheckPriced","splitFindingsPriced"),delete g.set.splitCheckPriced,delete g.set.splitFindingsPriced,e.progress.log({level:"warn",code:"analysis.split_check_over_cap",counts:{totalUsd:i.totalUsd,capUsd:i.capUsd}}),g.set.warnings=[...o.warnings??[],je]):g.estimate=i,g}var Jr=async(r,e)=>{e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let{state:o,settings:s}=r,t=o.repos??[];await H(s,o,e.readers);let n=o.repoCursor??0;if(n>=t.length)return lr(r,e);let l=t[n],u=r.execution.forLocal,g=u?o.mapped?.[n]?{fragment:Oe(o,n),warnings:[]}:await dr(s,l.files??{},{repoKey:l.key,root:l.root,forLocal:!0}):void 0,h=g?(()=>{let i=tt(g.fragment,l.key);return{...i,warnings:[...g.warnings,...i.warnings]}})():ke(s,l,q(s,o),o.modelReader??!1,o.projectAgents,D(await e.instructions()).bundleText("model-reader-runtime-prompt")),p=!u&&l.sourceReadNotes?$(s,l.sourceReadNotes,l.selected??[],l.root):void 0,f=u?[]:ae((l.refused??[]).filter(i=>i.reason==="secret-content")),w="virtualFiles"in h?h.virtualFiles:void 0,b=[...o.mapped??[]];return b[n]=h.fragment,{next:"mapping",clear:[],set:{...w?{repos:t.map((i,m)=>m===n?{...i,files:{...i.files,...w}}:i)}:{},mapped:b,warnings:[...o.warnings??[],...p?[`${l.key}: ${p}`]:[],...f,...h.warnings,...Mt(l)],repoCursor:n+1}}};function Yr(r,e){let o=e?.findingHeadlineDiagnostics??(r.findingHeadlines?.version===2?r.findingHeadlines.diagnostics:r.findingHeadlineDiagnostics);return{set:{...o?{findingHeadlineDiagnostics:o}:{},repos:(r.repos??[]).map(s=>({...s,files:{},selected:[],scan:void 0,ranked:void 0})),...r.projectAgents?{projectAgents:{enabled:r.projectAgents.enabled,byRepo:{}}}:{}},clear:["passResults","sourceNotes","findingHeadlines","findingsRaw","structuresRaw","loadModes","rechecks","recheckedChangeIds","readPaths","inspectPlan","passFindings","codeChecks","newVerdicts",...r.shapeFindings?["shapeFindings"]:[]]}}export{ve as ANALYSIS_FIELDS,pr as FOLDER_TOO_LARGE_MESSAGE,br as InputBudgetError,M as MODELS,F as admitFile,Rr as analysisFieldsOf,vr as analysisRuntime,mr as analysisSizeLimits,Hr as applyAnalysisDelta,hr as assessAnalysisSize,Ar as buildAnalysisResult,Pr as buildRequest,D as createInstructionText,yr as createRequestRegistry,J as createRequestTools,Te as discoverLocalSources,Se as discoverReaders,$r as estimateStage,Wr as fetchLocalSources,Gr as fetchStage,Fr as fetchedPathsOf,Re as findingHeadlinesEnabled,Yr as finishAnalysis,_r as headlinesStage,Or as inspectStage,Jr as mapStage,gr as measureAnalysisSize,ur as parseAnalysisSize,Ir as planForJob,Me as planImport,fr as readFindingQualityConfig,Sr as render,jr as repoCollector,wr as resolveAgents,Oe as savedFragmentAt,xr as savedFragmentsOf,Ce as scopeCodeContext,_e as selectionOfPlan,kr as snapshotSettings,Cr as sourceNotesStage,Mr as structureStage,Er as trySavedFragmentAt};
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"../chunks/VFENG4MR.js";import"../chunks/KEKTZDIK.js";import"../chunks/BZNHHLNP.js";export{b as applyCacheBreakpoints,d as captureAllowanceMultiplier,e as promptCacheEnabled,c as promptCacheEstimateLine,a as promptCachePolicy};
1
+ import{a,b,c,d,e}from"../chunks/MJGB25S5.js";import"../chunks/JKWTHRUR.js";import"../chunks/3GUKUEEJ.js";export{b as applyCacheBreakpoints,d as captureAllowanceMultiplier,e as promptCacheEnabled,c as promptCacheEstimateLine,a as promptCachePolicy};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l}from"../chunks/KEKTZDIK.js";import"../chunks/BZNHHLNP.js";export{a as ANTHROPIC_CACHE_READ_RATE,b as CACHE_WRITE_MULTIPLIERS,d as FALLBACK_MODEL,c as PRICE_PER_MTOK,l as assertEstimateWithinCap,e as cacheWriteMultiplier,f as estimateTokensFromBytes,g as estimateUsd,k as formatUsd,h as line,j as overCap,i as sumEstimate};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"../chunks/JKWTHRUR.js";import"../chunks/3GUKUEEJ.js";export{l as ANALYSIS_TOO_LARGE,a as ANTHROPIC_CACHE_READ_RATE,b as CACHE_WRITE_MULTIPLIERS,d as FALLBACK_MODEL,c as PRICE_PER_MTOK,m as SPLIT_CHECK_TOO_LARGE,n as assertEstimateWithinCap,e as cacheWriteMultiplier,f as estimateTokensFromBytes,g as estimateUsd,k as formatUsd,h as line,j as overCap,i as sumEstimate};
@@ -1 +1 @@
1
- import{fa as o,ha as p,ka as e,ma as m}from"../chunks/ORCYIIHB.js";import"../chunks/QPXNXMLC.js";import"../chunks/VER355VN.js";import"../chunks/YVDCJN7D.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/Y7JGSUOA.js";import"../chunks/4F6ZIHXU.js";import"../chunks/VGYWI4X2.js";import"../chunks/J4AXGE5W.js";import"../chunks/PYKAERZZ.js";import"../chunks/7QDOHWSY.js";import"../chunks/326F4XNG.js";import"../chunks/IL2KRP3T.js";import"../chunks/2PSNOSJ2.js";import"../chunks/G322LST6.js";import"../chunks/6YCABS5T.js";import"../chunks/SL27GMEN.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/OFBJNHC6.js";import"../chunks/DTMHXKP6.js";import"../chunks/U5HOEVPE.js";import"../chunks/ZMUBMYWN.js";import"../chunks/ZAA44GPI.js";import"../chunks/3227KXHF.js";import"../chunks/M7MMAUAK.js";import"../chunks/57M4OQJM.js";import"../chunks/IBCFGUHI.js";import"../chunks/KU5DINLW.js";import"../chunks/EQTIRIMU.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";import"../chunks/T5TREZCQ.js";import"../chunks/724WZMYW.js";function i(l,r,a={}){let n=o(l,r,a.structureState);return[...n.calls,...p(l,n.findings),...m(l,r,a),...e(l)]}export{i as localCallPlan};
1
+ import{X as o,Z as p,aa as e,ca as m}from"../chunks/T2SAP7OV.js";import"../chunks/QMIXCT62.js";import"../chunks/T66VDFXF.js";import"../chunks/J4AXGE5W.js";import"../chunks/IVDDV6CU.js";import"../chunks/Y7JGSUOA.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/K5OTWBTT.js";import"../chunks/326F4XNG.js";import"../chunks/V7BFUTM7.js";import"../chunks/4F6ZIHXU.js";import"../chunks/VGYWI4X2.js";import"../chunks/PYKAERZZ.js";import"../chunks/7OYIBWX3.js";import"../chunks/NCWEOJVJ.js";import"../chunks/2PSNOSJ2.js";import"../chunks/DRGDIIFA.js";import"../chunks/6YCABS5T.js";import"../chunks/SL27GMEN.js";import"../chunks/3CKW5JIF.js";import"../chunks/STZOC7LN.js";import"../chunks/MJGB25S5.js";import"../chunks/UEWL3GMQ.js";import"../chunks/OFBJNHC6.js";import"../chunks/MXXNED6N.js";import"../chunks/U5HOEVPE.js";import"../chunks/FTODBFQW.js";import"../chunks/ZAA44GPI.js";import"../chunks/3227KXHF.js";import"../chunks/O652FQQH.js";import"../chunks/57M4OQJM.js";import"../chunks/IBCFGUHI.js";import"../chunks/KU5DINLW.js";import"../chunks/HPIAEQHE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/JKWTHRUR.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/3GUKUEEJ.js";import"../chunks/T5TREZCQ.js";import"../chunks/724WZMYW.js";function i(l,r,a={}){let n=o(l,r,a.structureState);return[...n.calls,...p(l,n.findings),...m(l,r,a),...e(l)]}export{i as localCallPlan};
@@ -1 +1 @@
1
- import{k as a,l as b,m as c,n as d}from"../chunks/YVDCJN7D.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/Y7JGSUOA.js";import"../chunks/IL2KRP3T.js";import"../chunks/6YCABS5T.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as InputBudgetError,d as buildAnalysisCall,c as callInputBytes,b as createRequestRegistry};
1
+ import{k as a,l as b,m as c,n as d}from"../chunks/IVDDV6CU.js";import"../chunks/Y7JGSUOA.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/V7BFUTM7.js";import"../chunks/6YCABS5T.js";import"../chunks/3CKW5JIF.js";import"../chunks/STZOC7LN.js";import"../chunks/MJGB25S5.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/JKWTHRUR.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/3GUKUEEJ.js";export{a as InputBudgetError,d as buildAnalysisCall,c as callInputBytes,b as createRequestRegistry};
@@ -1 +1 @@
1
- import{a}from"../chunks/VER355VN.js";import"../chunks/E7TFIHC5.js";import"../chunks/IL2KRP3T.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as createTemplateVersion};
1
+ import{a}from"../chunks/T66VDFXF.js";import"../chunks/E7TFIHC5.js";import"../chunks/V7BFUTM7.js";import"../chunks/3CKW5JIF.js";import"../chunks/STZOC7LN.js";import"../chunks/MJGB25S5.js";import"../chunks/UEWL3GMQ.js";import"../chunks/EH3QQ3T4.js";import"../chunks/JKWTHRUR.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/3GUKUEEJ.js";export{a as createTemplateVersion};
@@ -1 +1 @@
1
- import{a}from"../chunks/QPXNXMLC.js";import"../chunks/VER355VN.js";import"../chunks/YVDCJN7D.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/Y7JGSUOA.js";import"../chunks/IL2KRP3T.js";import"../chunks/6YCABS5T.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as createRequestTools};
1
+ import{a}from"../chunks/QMIXCT62.js";import"../chunks/T66VDFXF.js";import"../chunks/IVDDV6CU.js";import"../chunks/Y7JGSUOA.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/V7BFUTM7.js";import"../chunks/6YCABS5T.js";import"../chunks/3CKW5JIF.js";import"../chunks/STZOC7LN.js";import"../chunks/MJGB25S5.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/JKWTHRUR.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/3GUKUEEJ.js";export{a as createRequestTools};
@@ -1 +1 @@
1
- import{a,b,c,d}from"./chunks/IL2KRP3T.js";import"./chunks/PVPEY7NF.js";import"./chunks/STZOC7LN.js";import"./chunks/VFENG4MR.js";import"./chunks/UEWL3GMQ.js";import"./chunks/EH3QQ3T4.js";import"./chunks/KEKTZDIK.js";import"./chunks/FSLWD2PE.js";import"./chunks/JF4GYMOZ.js";import"./chunks/BZNHHLNP.js";export{a as findingHeadlinesEnabled,b as outsideLoadersEnabled,c as promptAgreementEnabled,d as snapshotSettings};
1
+ import{a,b,c,d}from"./chunks/V7BFUTM7.js";import"./chunks/3CKW5JIF.js";import"./chunks/STZOC7LN.js";import"./chunks/MJGB25S5.js";import"./chunks/UEWL3GMQ.js";import"./chunks/EH3QQ3T4.js";import"./chunks/JKWTHRUR.js";import"./chunks/FSLWD2PE.js";import"./chunks/JF4GYMOZ.js";import"./chunks/3GUKUEEJ.js";export{a as findingHeadlinesEnabled,b as outsideLoadersEnabled,c as promptAgreementEnabled,d as snapshotSettings};
@@ -2,8 +2,8 @@ import { createHash, createPublicKey, sign, verify } from "node:crypto";
2
2
  import { stableStringify } from "../../analysis-core/llm/stable-json.js";
3
3
  export const RELEASE_SIGNING_INPUT_LIMIT = 64 * 1024;
4
4
  /** Billing identifies the encrypted payload; publication receipts separately identify the full JSON file. */
5
- export function sealedBundleHash(bundle) {
6
- return createHash("sha256").update(Buffer.from(bundle.sealed, "base64")).digest("hex");
5
+ export function bundleContentHash(sealed) {
6
+ return createHash("sha256").update(Buffer.from(sealed, "base64")).digest("hex");
7
7
  }
8
8
  function signingBytes(bundle) {
9
9
  // One encoding serves both release tooling and the relay, independent of JSON key order on disk.
@@ -1,3 +1,4 @@
1
+ import { loadDevelopmentRelay } from "../development-relay.js";
1
2
  import { loadInstalledRelease } from "../../adapters/release.js";
2
3
  import { cliRefusals, START_FAILURE_MESSAGE } from "../../contract/cli-refusals.js";
3
4
  import { CLI_VERSION } from "../../contract/cli-version.js";
@@ -28,7 +29,8 @@ function requireLocal(value) {
28
29
  export async function analyze(path, _options, ctx) {
29
30
  const startup = ctx.startup;
30
31
  requireLocal(await ctx.api.request("checks/mode"));
31
- const release = ctx.relayRuntime?.release ?? await loadInstalledRelease();
32
+ const development = startup.transport.CF_RELAY_DEV === "1" ? await loadDevelopmentRelay(startup.transport) : undefined;
33
+ const release = development?.release ?? ctx.relayRuntime?.release ?? await loadInstalledRelease();
32
34
  if (release.projectContext !== "checks")
33
35
  throw new Error(unavailable);
34
36
  const token = await ctx.token?.();
@@ -48,7 +50,7 @@ export async function analyze(path, _options, ctx) {
48
50
  } };
49
51
  try {
50
52
  return await (ctx.relayRuntime?.run ?? runRelayCheck)(folder, {
51
- settings: startup.settings, config, release, connect: ctx.relayRuntime?.connect,
53
+ settings: startup.settings, config, release, connect: development?.connect ?? ctx.relayRuntime?.connect,
52
54
  signal: ctx.signal ? AbortSignal.any([controller.signal, ctx.signal]) : controller.signal,
53
55
  stdout() { }, stderr() { },
54
56
  onStart: () => { ctx.onCheckStart?.(); ctx.write("\r\u001b[2KAnalyzing the agent…"); progressShown = true; },
@@ -0,0 +1,34 @@
1
+ import { createPublicKey } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { cliRefusals } from "../contract/cli-refusals.js";
4
+ import { z } from "zod";
5
+ import { loadDevelopmentRelease } from "../adapters/release.js";
6
+ import { attestationPolicy } from "../gatekeeper/attestation.js";
7
+ import { connectRelay } from "../gatekeeper/connection.js";
8
+ const developmentTrust = z.object({
9
+ imageDigests: z.array(z.string().regex(/^sha256:[a-f0-9]{64}$/)).min(1),
10
+ developmentIssuer: z.object({ issuer: z.string().url(), keys: z.array(z.object({
11
+ kid: z.string().min(1), publicKey: z.string().min(1),
12
+ }).strict()).min(1) }).strict(),
13
+ }).strict();
14
+ /** Development paths are explicit and never replace the installed production pins. */
15
+ export async function loadDevelopmentRelay(config) {
16
+ try {
17
+ if (config.CF_RELAY_DEV !== "1" || !config.CF_RELAY_DEV_TRUST || !config.CF_RELAY_DEV_BUNDLE || !config.CF_RELAY_DEV_RELEASE)
18
+ throw new Error();
19
+ const trust = developmentTrust.parse(JSON.parse(await readFile(config.CF_RELAY_DEV_TRUST, "utf8")));
20
+ const policy = attestationPolicy(config, { ...trust, developmentIssuer: { ...trust.developmentIssuer,
21
+ keys: trust.developmentIssuer.keys.map(({ kid, publicKey }) => {
22
+ const key = createPublicKey(publicKey);
23
+ if (key.asymmetricKeyType !== "ed25519")
24
+ throw new Error();
25
+ return { kid, publicKey: key };
26
+ }),
27
+ } });
28
+ const release = await loadDevelopmentRelease({ bundle: config.CF_RELAY_DEV_BUNDLE, metadata: config.CF_RELAY_DEV_RELEASE });
29
+ return { release, connect: (url) => connectRelay(url, { development: policy }) };
30
+ }
31
+ catch {
32
+ throw new Error(cliRefusals.release_unavailable);
33
+ }
34
+ }
@@ -134,10 +134,10 @@ async function runRelayLifecycle(folder, options, existing) {
134
134
  if (error.code !== "ENOENT")
135
135
  throw error;
136
136
  }
137
- const { source, provenance, plan, start } = await prepareRelayCheck(folder, { ...options, signal, expectedCommit: existing?.expectedCommit }, validated);
137
+ const { source, provenance, plan, start, startMetadata } = await prepareRelayCheck(folder, { ...options, signal, expectedCommit: existing?.expectedCommit }, validated);
138
138
  let reservation = existing?.reservation;
139
139
  if (!reservation) {
140
- const started = await client.start(start);
140
+ const started = await client.start(start, startMetadata);
141
141
  projectId = started.projectId;
142
142
  signal.throwIfAborted();
143
143
  const created = await client.create({ ...started, checkId: randomUUID(), plan });
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { outsideLoadersEnabled } from "../analysis-core/settings.js";
2
3
  import { readLocalFolder } from "../adapters/files.js";
3
4
  import { snapshotProvenance } from "../adapters/snapshot.js";
@@ -27,5 +28,6 @@ export async function prepareRelayCheck(folder, options, validated = validateCli
27
28
  options.signal?.throwIfAborted();
28
29
  const facts = earlyFacts ?? await (options.facts ?? repositoryFacts)(folder);
29
30
  options.signal?.throwIfAborted();
30
- return { source, provenance, plan, start: buildRelayStartPayload(source.sourceBase ? { ...facts, relPath: "" } : facts, files) };
31
+ const startMetadata = { analysisSize: source.analysisSize, startAttempt: randomUUID() };
32
+ return { source, provenance, plan, start: buildRelayStartPayload(source.sourceBase ? { ...facts, relPath: "" } : facts, files), startMetadata };
31
33
  }
@@ -1,3 +1,4 @@
1
+ import { FOLDER_TOO_LARGE_MESSAGE } from "../analysis-core/errors.js";
1
2
  export const START_FAILURE_MESSAGE = "This couldn't start. Try again.";
2
3
  export const RESERVATION_EXPIRED_MESSAGE = "This reservation expired. Start a new analysis.";
3
4
  export const FINISH_FAILURE_MESSAGE = "The analysis couldn't finish. Try again.";
@@ -6,6 +7,7 @@ export const COMMITTED_FILES_MESSAGE = "Counterfact analyzes the committed versi
6
7
  const unsupportedVersion = "This version of Counterfact can't run analyses. Update it: npm install -g @counterfact-labs/cli@latest.";
7
8
  /** Shared public refusals keep mode admission and reservation errors consistent. */
8
9
  export const cliRefusals = {
10
+ folder_too_large: FOLDER_TOO_LARGE_MESSAGE,
9
11
  low_balance: "Your balance doesn't cover this analysis. Add credit at https://app.counterfactlabs.com/account?status=low_balance#balance",
10
12
  local_checks_paused: "Analyses are paused right now. Try again later.",
11
13
  cli_update_required: "Update Counterfact: run npm install -g @counterfact-labs/cli@latest.",
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.2.3";
1
+ export const CLI_VERSION = "0.2.4";
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { fixDeltaSchema, fixFactsSchema } from "../analysis-core/data/finding-types.js";
3
3
  import { inspectFixSchema, otherSiteSchema, rawFindingSchema } from "../analysis-core/analysis/schemas.js";
4
4
  import { sourceNotesSchema } from "../analysis-core/analysis/source-notes/types.js";
5
+ import { parseAnalysisSize } from "../analysis-core/conventions/analysis-fit.js";
5
6
  export const id = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
6
7
  const uuid = z.uuid().transform(value => value.toLowerCase());
7
8
  const money = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
@@ -9,6 +10,25 @@ const count = (max) => z.number().int().positive().max(max);
9
10
  // These data-only boundaries follow the SaaS local start, reservation and findings owners; see docs/provenance.md.
10
11
  export const LOCAL_START_EXECUTION_HEADER = { name: "x-counterfact-execution", value: "local" };
11
12
  export const LOCAL_START_BODY_LIMIT = 2 * 1024 * 1024;
13
+ export const ANALYSIS_SIZE_HEADER = "x-counterfact-analysis-size";
14
+ export const START_ATTEMPT_HEADER = "x-counterfact-start-attempt";
15
+ export const ANALYSIS_SIZE_HEADER_LIMIT = 256;
16
+ /** Additive headers let older consoles keep accepting the unchanged, strict start body. */
17
+ export function serializeLocalStartMetadata(metadata) {
18
+ const size = JSON.stringify(parseAnalysisSize(metadata.analysisSize));
19
+ if (Buffer.byteLength(size, "utf8") > ANALYSIS_SIZE_HEADER_LIMIT)
20
+ throw new Error("Invalid analysis size header");
21
+ return { [ANALYSIS_SIZE_HEADER]: size, [START_ATTEMPT_HEADER]: uuid.parse(metadata.startAttempt) };
22
+ }
23
+ /** Missing measurements preserve old clients; present measurements must be complete. */
24
+ export function parseLocalStartMetadata(headers) {
25
+ const raw = headers.get(ANALYSIS_SIZE_HEADER);
26
+ if (raw === null)
27
+ return undefined;
28
+ if (Buffer.byteLength(raw, "utf8") > ANALYSIS_SIZE_HEADER_LIMIT)
29
+ throw new Error("Invalid analysis size header");
30
+ return { analysisSize: parseAnalysisSize(JSON.parse(raw)), startAttempt: uuid.parse(headers.get(START_ATTEMPT_HEADER)) };
31
+ }
12
32
  const localStartPath = z.string().min(1).max(4096).refine(value => !value.includes("\\") && !value.includes("\0") && !value.startsWith("/")
13
33
  && value.split("/").every(part => part !== ".." && part !== "." && part !== ""));
14
34
  export const localStartRequestSchema = z.strictObject({
@@ -14,7 +14,8 @@ export function createRelayExchange(options) {
14
14
  throw new Error();
15
15
  // Provider work can exceed a network-body timeout; evidence expiry still closes this exact socket.
16
16
  const response = await options.exchange("/relay", request, RELAY_MAX_FRAME_BYTES, options.remainingEvidenceMs());
17
- const frame = options.development ? { answer: relayAnswer.parse(response.body), delivery: undefined } : relayAnswerFrame.parse(response.body);
17
+ const legacy = options.development ? relayAnswer.safeParse(response.body) : undefined;
18
+ const frame = legacy?.success ? { answer: legacy.data, delivery: undefined } : relayAnswerFrame.parse(response.body);
18
19
  if (frame.answer.nonce !== request.nonce)
19
20
  throw new Error();
20
21
  if (frame.delivery) {
@@ -3,7 +3,7 @@ import { request as httpRequest } from "node:http";
3
3
  import { request as httpsRequest } from "node:https";
4
4
  import { CLI_VERSION } from "../contract/cli-version.js";
5
5
  import { cliRefusals, FINISH_FAILURE_MESSAGE, RESERVATION_EXPIRED_MESSAGE, RESULTS_TOO_LARGE_MESSAGE, START_FAILURE_MESSAGE } from "../contract/cli-refusals.js";
6
- import { cliRelayReservationRequestSchema, consoleCreatedSchema, consoleIntakeResultSchema, consoleReservationSchema, consoleStatusSchema, LOCAL_FINDINGS_BODY_LIMIT, localFindingsPayloadSchema, LOCAL_START_BODY_LIMIT, LOCAL_START_EXECUTION_HEADER, localStartRequestSchema, localStartResponseSchema } from "../contract/console.js";
6
+ import { cliRelayReservationRequestSchema, consoleCreatedSchema, consoleIntakeResultSchema, consoleReservationSchema, consoleStatusSchema, LOCAL_FINDINGS_BODY_LIMIT, localFindingsPayloadSchema, LOCAL_START_BODY_LIMIT, LOCAL_START_EXECUTION_HEADER, localStartRequestSchema, localStartResponseSchema, serializeLocalStartMetadata } from "../contract/console.js";
7
7
  const RESPONSE_LIMIT = 64 * 1024;
8
8
  const RESERVATION_BODY_LIMIT = 64 * 1024;
9
9
  const messages = {
@@ -54,8 +54,15 @@ export class ConsoleClient {
54
54
  throw new ConsoleError("invalid_configuration");
55
55
  }
56
56
  }
57
- start(input) {
58
- return this.#send("/api/cli/checks", input, localStartRequestSchema, localStartResponseSchema, LOCAL_START_BODY_LIMIT, { statuses: [201], header: LOCAL_START_EXECUTION_HEADER, context: "start" });
57
+ async start(input, metadata) {
58
+ let headers;
59
+ try {
60
+ headers = metadata === undefined ? {} : serializeLocalStartMetadata(metadata);
61
+ }
62
+ catch {
63
+ throw new ConsoleError("invalid_request", "start");
64
+ }
65
+ return this.#send("/api/cli/checks", input, localStartRequestSchema, localStartResponseSchema, LOCAL_START_BODY_LIMIT, { statuses: [201], headers: { ...headers, [LOCAL_START_EXECUTION_HEADER.name]: LOCAL_START_EXECUTION_HEADER.value }, context: "start" });
59
66
  }
60
67
  create(input) {
61
68
  return this.#lifecycle({ ...input, action: "create" }, consoleCreatedSchema);
@@ -115,7 +122,7 @@ export class ConsoleClient {
115
122
  method: "POST", agent: false, rejectUnauthorized: true, maxHeaderSize: 16 * 1024,
116
123
  headers: { "x-counterfact-cli-version": CLI_VERSION, authorization: `Bearer ${this.#token}`, "content-type": "application/json", accept: "application/json",
117
124
  "content-length": body.length, "accept-encoding": "identity",
118
- ...(options.header ? { [options.header.name]: options.header.value } : {}) },
125
+ ...options.headers },
119
126
  }, response => {
120
127
  const status = response.statusCode ?? 0;
121
128
  const declared = response.headers["content-length"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact-labs/cli",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist/**/*.js",
@@ -44,7 +44,7 @@
44
44
  "tsx": "4.23.15",
45
45
  "typescript": "6.0.3",
46
46
  "typescript-eslint": "8.64.0",
47
- "@counterfact-labs/analysis-core": "0.7.1",
47
+ "@counterfact-labs/analysis-core": "0.8.0",
48
48
  "@counterfact-labs/setup-pings": "0.1.0"
49
49
  },
50
50
  "workspaces": [