import{Bca as M,Eca as Y,Gca as O,Hca as S,Ica as _,qca as A,rca as k,xca as G,yca as N}from"./cli-0.5.3-kavpx97n.mjs";import{Nfa as C,Qfa as R,qfa as K,rfa as W,vfa as j}from"./cli-0.5.3-n3cxyxpg.mjs";import"./cli-0.5.3-kbvzmaax.mjs";import"./cli-0.5.3-7wdgps7z.mjs";import{Gga as y,Lga as c}from"./cli-0.5.3-c8bcrqa4.mjs";import"./cli-0.5.3-qrvd6cmy.mjs";import"./cli-0.5.3-2dk1sk8w.mjs";import"./cli-0.5.3-0df3r78b.mjs";O();R();c();k();_();M();j();import{mkdir as m,readFile as z,stat as E,unlink as T,writeFile as f}from"fs/promises";import{dirname as B,join as b}from"path";var I=50,D=14400000,u=S(()=>Y.object({sessionId:Y.string(),environmentId:Y.string(),source:Y.enum(["standalone","repl"])}));function J(q){return b(N(),G(q),"bridge-pointer.json")}async function g(q,x){let v=J(q);try{await m(B(v),{recursive:!0}),await f(v,K(x),"utf8"),C(`[bridge:pointer] wrote ${v}`)}catch(V){C(`[bridge:pointer] write failed: ${V}`,{level:"warn"})}}async function U(q){let x=J(q),v,V;try{V=(await E(x)).mtimeMs,v=await z(x,"utf8")}catch{return null}let Z=u().safeParse(F(v));if(!Z.success)return C(`[bridge:pointer] invalid schema, clearing: ${x}`),await X(q),null;let $=Math.max(0,Date.now()-V);if($>D)return C(`[bridge:pointer] stale (>4h mtime), clearing: ${x}`),await X(q),null;return{...Z.data,ageMs:$}}async function s(q){let x=await U(q);if(x)return{pointer:x,dir:q};let v=await A(q);if(v.length<=1)return null;if(v.length>I)return C(`[bridge:pointer] ${v.length} worktrees exceeds fanout cap ${I}, skipping`),null;let V=G(q),Z=v.filter((H)=>G(H)!==V),$=await Promise.all(Z.map(async(H)=>{let L=await U(H);return L?{pointer:L,dir:H}:null})),Q=null;for(let H of $)if(H&&(!Q||H.pointer.ageMs<Q.pointer.ageMs))Q=H;if(Q)C(`[bridge:pointer] fanout found pointer in worktree ${Q.dir} (ageMs=${Q.pointer.ageMs})`);return Q}async function X(q){let x=J(q);try{await T(x),C(`[bridge:pointer] cleared ${x}`)}catch(v){if(!y(v))C(`[bridge:pointer] clear failed: ${v}`,{level:"warn"})}}function F(q){try{return W(q)}catch{return null}}export{g as writeBridgePointer,s as readBridgePointerAcrossWorktrees,U as readBridgePointer,J as getBridgePointerPath,X as clearBridgePointer,D as BRIDGE_POINTER_TTL_MS};
