import{existsSync as s,mkdirSync as N,readFileSync as g,renameSync as h,unlinkSync as v,writeFileSync as w}from"node:fs";import{join as f}from"node:path";import{existsSync as F,mkdirSync as C,readFileSync as R,readdirSync as _,statSync as A,writeFileSync as O}from"node:fs";import{join as P}from"node:path";function m(t){let e=Number(t);if(!Number.isFinite(e)||e<=0)return null;try{return process.kill(e,0),!0}catch(n){let r=n&&typeof n=="object"?n.code:"";return r==="ESRCH"?!1:r==="EPERM"?!0:null}}var S="run-capacity-wait.json",c=1,E=10800*1e3;function x(t){return f(t,S)}function T(t){return!t||typeof t!="string"?null:f(f(t,".."),S)}function a(){return{v:c,entries:[]}}function l(t){if(!t||!s(t))return a();let e=x(t);if(!s(e))return a();try{let n=g(e,"utf8"),r=JSON.parse(n);if(!r||typeof r!="object")return a();let i=Array.isArray(r.entries)?r.entries:[];return{v:c,entries:i}}catch{return a()}}function p(t,e=Date.now()){let n=t&&Array.isArray(t.entries)?t.entries:[],r=[];for(let i of n){if(!i||typeof i!="object")continue;let u=Number(i.pid),o=Number(i.updatedAt)||Number(i.enqueuedAt)||0,y=Number.isFinite(u)&&u>0?m(u):null;y!==!1&&(y===null&&o>0&&e-o>E||r.push(i))}return{v:c,entries:r}}function d(t,e){let n=x(t);N(t,{recursive:!0});let r={v:c,entries:Array.isArray(e.entries)?e.entries:[]},i=`${n}.${process.pid}.${Date.now()}.tmp`;w(i,`${JSON.stringify(r)}
`,"utf8");try{s(n)&&v(n)}catch{}h(i,n)}function $(t,e){let n=p(l(t)),r=e?.id!=null?String(e.id):"";if(!r)return;let i=n.entries.filter(o=>o&&String(o.id)!==r),u=Date.now();i.push({...e,id:r,pid:Number.isFinite(Number(e.pid))?Number(e.pid):process.pid,enqueuedAt:Number(e.enqueuedAt)||u,updatedAt:u}),d(t,{v:c,entries:i})}function L(t,e){let n=e!=null?String(e):"";if(!n||!t)return;let r=p(l(t)),i=r.entries.filter(u=>u&&String(u.id)!==n);i.length!==r.entries.length&&d(t,{v:c,entries:i})}function J(t){let e=l(t),n=p(e);return n.entries.length!==e.entries.length&&d(t,n),n.entries}export{S as RUN_CAPACITY_QUEUE_FILENAME,l as readRunCapacityQueueDoc,J as readRunCapacityWaitSnapshot,p as reconcileRunCapacityQueueDoc,L as removeRunCapacityQueueEntry,x as runCapacityQueuePathFromOutputDir,T as runCapacityQueuePathFromSessionsRoot,$ as upsertRunCapacityQueueEntry,d as writeRunCapacityQueueDocAtomic};
