import{Ln as e,vt as t,wn as n}from"./schemas-BGAvj1T4.js";import{t as r}from"./v4-f1i_CNUT.js";import{D as i,E as a,G as o,O as s,U as c,l,p as u}from"./debug-otxXY3j-.js";import{_ as d,c as f,g as p,l as m,m as h}from"./sessionStoragePortable-CJUZrbIq.js";import{n as g,t as _}from"./lazySchema-B0QShMaQ.js";import{dirname as v,join as y}from"path";import{mkdir as b,readFile as x,stat as S,unlink as C,writeFile as w}from"fs/promises";r(),l(),c(),d(),_(),m(),a();var T=50,E=g(()=>n({sessionId:e(),environmentId:e(),source:t([`standalone`,`repl`])}));function D(e){return y(f(),h(e),`bridge-pointer.json`)}async function O(e,t){let n=D(e);try{await b(v(n),{recursive:!0}),await w(n,s(t),`utf8`),u(`[bridge:pointer] wrote ${n}`)}catch(e){u(`[bridge:pointer] write failed: ${e}`,{level:`warn`})}}async function k(e){let t=D(e),n,r;try{r=(await S(t)).mtimeMs,n=await x(t,`utf8`)}catch{return null}let i=E().safeParse(M(n));if(!i.success)return u(`[bridge:pointer] invalid schema, clearing: ${t}`),await j(e),null;let a=Math.max(0,Date.now()-r);return a>144e5?(u(`[bridge:pointer] stale (>4h mtime), clearing: ${t}`),await j(e),null):{...i.data,ageMs:a}}async function A(e){let t=await k(e);if(t)return{pointer:t,dir:e};let n=await p(e);if(n.length<=1)return null;if(n.length>T)return u(`[bridge:pointer] ${n.length} worktrees exceeds fanout cap ${T}, skipping`),null;let r=h(e),i=n.filter(e=>h(e)!==r),a=await Promise.all(i.map(async e=>{let t=await k(e);return t?{pointer:t,dir:e}:null})),o=null;for(let e of a)e&&(!o||e.pointer.ageMs<o.pointer.ageMs)&&(o=e);return o&&u(`[bridge:pointer] fanout found pointer in worktree ${o.dir} (ageMs=${o.pointer.ageMs})`),o}async function j(e){let t=D(e);try{await C(t),u(`[bridge:pointer] cleared ${t}`)}catch(e){o(e)||u(`[bridge:pointer] clear failed: ${e}`,{level:`warn`})}}function M(e){try{return i(e)}catch{return null}}export{j as clearBridgePointer,k as readBridgePointer,A as readBridgePointerAcrossWorktrees,O as writeBridgePointer};