ilml-plugin-linkedin 1.5.0 → 1.8.0

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.
package/dist/daily.mjs CHANGED
@@ -1,22 +1,53 @@
1
- var ht=Object.defineProperty;var De=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ie=(t,e)=>{for(var o in e)ht(t,o,{get:e[o],enumerable:!0})};var Ge={};Ie(Ge,{addEncounter:()=>Ne,canSendConnection:()=>ee,commitDataSnapshot:()=>We,default:()=>xt,getAllApplications:()=>Qe,getPersonStatus:()=>Me,getQuestionStats:()=>ze,getQuotaStatus:()=>te,getRecentConnections:()=>Z,linkPersonToJob:()=>ke,loadApplicationQuestions:()=>me,loadConversations:()=>xe,loadJobs:()=>K,loadPeople:()=>O,loadQuota:()=>X,loadSyncState:()=>qe,logApplicationQuestions:()=>Ye,migrateFromDailyFiles:()=>Ue,recordConnectionSent:()=>Pe,resetCaches:()=>Ct,saveConversations:()=>Fe,saveJobs:()=>H,savePeople:()=>A,saveQuota:()=>de,saveSyncState:()=>Ve,updateConnectionStatus:()=>Je,upsertJob:()=>Le,upsertPerson:()=>fe});import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as $t}from"url";import{execSync as ce}from"child_process";function Ct(){x=null,F=null,I=null,T=null,L=null,R=null}function S(){d.existsSync(h)||d.mkdirSync(h,{recursive:!0})}function C(t,e){let o=JSON.stringify(e,null,2),s=t+".tmp";d.writeFileSync(s,o);for(let n=0;n<3;n++)try{d.renameSync(s,t);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function P(t,e){if(!d.existsSync(t))return null;try{let o=JSON.parse(d.readFileSync(t,"utf-8"));try{d.copyFileSync(t,t+".backup")}catch{}return o}catch(o){console.error(`[!] ${e} is corrupted: ${o.message}`),console.error(` File: ${m.resolve(t)}`);let s=t+".backup";if(d.existsSync(s))try{let n=JSON.parse(d.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{d.copyFileSync(s,t)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{d.copyFileSync(t,t+".corrupted")}catch{}return null}}function k(){return new Date().toISOString().split("T")[0]}function O(){return x||(S(),x=P(le,"people.json")||{},x)}function A(t){S(),x=t;try{C(le,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${m.resolve(le)}`)}}function K(){return F||(S(),F=P(ae,"jobs.json")||{},F)}function H(t){S(),F=t;try{C(ae,t)}catch(e){console.error(`[!] Failed to save jobs.json: ${e.message}`),console.error(` Path: ${m.resolve(ae)}`)}}function xe(){return T||(S(),T=P(G,"conversations.json")||{},At(T),T)}function At(t){let e=0;for(let o of Object.values(t)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let n=(o.messages||[]).find(r=>r.status==="draft");n&&o.draftStatus&&o.draftStatus!=="pending"&&(n.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,e++}if(e>0){console.log(` [migration] Moved draft state from conv to msg.status for ${e} conversations`);try{C(G,t)}catch{}}}function Fe(t){S(),T=t;try{C(G,t)}catch(e){console.error(`[!] Failed to save conversations.json: ${e.message}`),console.error(` Path: ${m.resolve(G)}`)}}function fe(t,e={}){if(!t)return null;let o=O(),s=k(),n=new Date().toISOString(),r=o[t];if(r){r.seenCount=(r.seenCount||1)+1,r.lastSeen=s,r.lastUpdated=n,e.source&&!r.sources?.includes(e.source)&&(r.sources=r.sources||[],r.sources.push(e.source));for(let i of pe)e[i]!=null&&(r[i]=e[i])}else o[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,firstSeen:s,lastSeen:s,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n};return A(o),o[t]}function Le(t,e={}){if(!t)return null;let o=K(),s=k(),n=o[t];if(n){let r=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let i of r)e[i]!=null&&(n[i]=e[i])}else o[t]={title:e.title||null,company:e.company||null,location:e.location||null,salary:e.salary||null,url:e.url||null,applied:e.applied||!1,appliedDate:e.appliedDate||s,recruiterUrl:e.recruiterUrl||null,firstSeen:s};return H(o),o[t]}function ke(t,e){if(!t||!e)return;let o=O(),s=o[t];s&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(e)||(s.jobIds.push(e),s.lastUpdated=new Date().toISOString(),A(o)))}function Ne(t,e){if(!t||!e)return;let o=O(),s=o[t];if(!s)return;s.encounters||(s.encounters=[]);let r={date:k(),source:e.source||"unknown",action:e.action||"unknown"};e.jobId&&(r.jobId=String(e.jobId)),e.jobTitle&&(r.jobTitle=e.jobTitle),e.jobCompany&&(r.jobCompany=e.jobCompany),!s.encounters.some(c=>c.date===r.date&&c.source===r.source&&c.action===r.action&&(c.jobId||"")===(r.jobId||""))&&(s.encounters.push(r),s.lastUpdated=new Date().toISOString(),A(o))}function Me(t){return t&&O()[t]?.connectionStatus||null}function Je(t,e,o={}){if(!t)return;let s=O(),n=s[t];if(n||(fe(t,o.profileInfo||{}),n=s[t]),!!n){if(n.connectionStatus=e,n.connectionDate=k(),n.connectionMethod=o.method||n.connectionMethod,n.messageSent=o.messageSent||n.messageSent,n.lastUpdated=new Date().toISOString(),o.profileInfo)for(let r of pe)o.profileInfo[r]!=null&&(n[r]=o.profileInfo[r]);A(s)}}function X(){return I||(S(),I=P(Ee,"quota.json"),(!I||!I.connections)&&(I={connections:[]}),I)}function de(t){S(),I=t;try{C(Ee,t)}catch(e){console.error(`[!] Failed to save quota.json: ${e.message}`)}}function Pe(t,e="unknown"){let o=X(),s=new Date;o.connections.push({date:s.toISOString().split("T")[0],time:s.toTimeString().split(" ")[0],profileUrl:t,source:e}),de(o)}function Z(){let t=X(),e=new Date;e.setDate(e.getDate()-7);let o=e.toISOString().split("T")[0];return t.connections.filter(s=>s.date>=o)}function ee(){let t=Z(),e=k(),o=t.filter(a=>a.date===e).length,s=t.length,n=o>=M,r=s>=J,i=!n&&!r,c={allowed:i,daily:{sent:o,max:M},weekly:{sent:s,max:J}};return i||(c.reason=n?`Daily limit reached (${o}/${M})`:`Weekly limit reached (${s}/${J})`),c}function te(){let t=Z(),e=k(),o=t.filter(n=>n.date===e).length,s=t.length;return{daily:{sent:o,max:M,remaining:M-o},weekly:{sent:s,max:J,remaining:J-s}}}function Et(t){if(!t)return null;let e=t.match(/jobs\/view\/(\d+)/);return e?e[1]:null}function Ue(){S();let t=d.readdirSync(h).filter(r=>r.endsWith(".json")&&r!=="people.json"&&r!=="jobs.json"&&r!=="quota.json");if(t.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
2
- Migrating from ${t.length} daily files...
3
- `);let e=O(),o=K(),s=0,n=0;t.sort();for(let r of t){let i=m.join(h,r),c;try{c=JSON.parse(d.readFileSync(i,"utf-8"))}catch(u){console.log(` Skipping ${r}: ${u.message}`);continue}let a=c.date||r.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,f=c.source||r.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!c.profiles||!Array.isArray(c.profiles)){console.log(` Skipping ${r}: no profiles array`);continue}console.log(` ${r}: ${c.profiles.length} profiles`);for(let u of c.profiles){let v=u.profileUrl;if(!v)continue;let l=e[v];if(l){l.seenCount=(l.seenCount||1)+1,a&&(!l.lastSeen||a>l.lastSeen)&&(l.lastSeen=a),a&&(!l.firstSeen||a<l.firstSeen)&&(l.firstSeen=a),f&&!l.sources?.includes(f)&&(l.sources=l.sources||[],l.sources.push(f));for(let p of pe)u[p]!=null&&(l[p]=u[p]);u.status&&u.processed&&(l.connectionStatus=u.status,l.connectionDate=a,u.funnelResult&&(l.connectionMethod=u.funnelResult.method||l.connectionMethod,l.messageSent=u.funnelResult.message||l.messageSent)),l.lastUpdated=new Date().toISOString()}else e[v]={name:u.name||null,title:u.title||null,location:u.location||null,company:u.company||null,connectionDegree:u.connectionDegree||null,connectionsCount:u.connectionsCount||null,mutualConnections:u.mutualConnections||null,photoUrl:u.photoUrl||null,hasVerifiedBadge:u.hasVerifiedBadge||!1,firstSeen:a,lastSeen:a,seenCount:1,sources:f?[f]:[],connectionStatus:u.processed&&u.status||null,connectionDate:u.processed?a:null,connectionMethod:u.funnelResult?.method||null,messageSent:u.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},s++;if(u.fromJob?.url){let p=Et(u.fromJob.url);p&&(e[v].jobIds||(e[v].jobIds=[]),e[v].jobIds.includes(p)||e[v].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=v):(o[p]={title:u.fromJob.title||null,company:u.fromJob.company||null,location:null,salary:null,url:u.fromJob.url,applied:!0,appliedDate:a,recruiterUrl:v,firstSeen:a},n++))}}}return A(e),H(o),console.log(`
4
- Migration complete!`),console.log(` People: ${Object.keys(e).length} total (${s} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${n} new)`),{people:Object.keys(e).length,jobs:Object.keys(o).length}}function qe(){return L||(S(),L=P(_e,"sync-state.json")||{},L)}function Ve(t){S(),L=t;try{C(_e,t)}catch(e){console.error(`[!] Failed to save sync-state.json: ${e.message}`)}}function me(){if(R)return R;S();try{d.existsSync(ue)&&(R=JSON.parse(d.readFileSync(ue,"utf-8")))}catch{}return R||(R={}),R}function Be(t){return Array.isArray(t.applications)}function Qe(){let t=me();if(Be(t))return t.applications;let e=[];for(let o of Object.values(t))o.applications&&e.push(...o.applications);return e}function Ye(t){if(!t||!t.questions||t.questions.length===0)return;let e=me(),o=t.jobId||"unknown",n={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:t.result||"submitted",formPages:t.formPages||null,duration:t.duration||null,retries:t.retries||0,failedField:t.failedField||null,questionCount:t.questions.length,questions:t.questions.map(r=>{let i={type:r.type||"input",question:r.labelText||r.question||"",answer:r.answer||""};return r.options&&(r.options.length<=_t?i.options=r.options:i.optionsOmitted=!0),r.page&&(i.page=r.page),r.wasPreFilled&&(i.wasPreFilled=!0),r.wasRetry&&(i.wasRetry=!0),typeof r.isRequired=="boolean"&&(i.isRequired=r.isRequired),r.wasOptional&&(i.wasOptional=!0),i})};Be(e)?(n.jobId=o,n.jobTitle=t.jobTitle||null,n.jobCompany=t.jobCompany||null,n.jobUrl=t.jobUrl||null,e.applications.push(n)):(e[o]||(e[o]={applications:[]}),e[o].applications.push(n));try{C(ue,e)}catch(r){console.error(`[!] Failed to save application-questions.json: ${r.message}`)}}function ze(){let t=Qe(),e=new Map;for(let r of t)for(let i of r.questions||[]){let c=i.question.toLowerCase().trim();if(!c)continue;e.has(c)||e.set(c,{question:i.question,count:0,answers:new Map});let a=e.get(c);a.count++;let f=(i.answer||"").trim();a.answers.set(f,(a.answers.get(f)||0)+1)}let o=[...e.values()].sort((r,i)=>i.count-r.count),s=o.slice(0,15).map(r=>({question:r.question,count:r.count,topAnswer:[...r.answers.entries()].sort((i,c)=>c[1]-i[1])[0]?.[0]||""})),n=o.filter(r=>r.answers.size>1&&r.count>=3).map(r=>({question:r.question,count:r.count,answers:[...r.answers.entries()].sort((i,c)=>c[1]-i[1]).map(([i,c])=>`${i} (${c}x)`)}));return{totalApplications:t.length,uniqueQuestions:e.size,topQuestions:s,inconsistent:n}}function We(t){if(d.existsSync(m.join(h,".git")))try{let e={cwd:h,stdio:"pipe",timeout:1e4};ce("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",e);try{ce("git diff --cached --quiet",e);return}catch{}let o=(t||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');ce(`git commit -m "${o}"`,e)}catch(e){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${e.message?.slice(0,80)}`)}}var Rt,Tt,h,le,ae,Ee,G,_e,ue,M,J,x,F,I,T,L,R,pe,_t,xt,ge=De(()=>{Rt=$t(import.meta.url),Tt=m.dirname(m.dirname(Rt)),h=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(Tt,"collected-profiles"),le=m.join(h,"people.json"),ae=m.join(h,"jobs.json"),Ee=m.join(h,"quota.json"),G=m.join(h,"conversations.json"),_e=m.join(h,"sync-state.json"),ue=m.join(h,"application-questions.json"),M=20,J=100,x=null,F=null,I=null,T=null,L=null,R=null;pe=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];_t=50;xt={loadPeople:O,savePeople:A,loadJobs:K,saveJobs:H,loadConversations:xe,saveConversations:Fe,upsertPerson:fe,upsertJob:Le,linkPersonToJob:ke,addEncounter:Ne,getPersonStatus:Me,updateConnectionStatus:Je,migrateFromDailyFiles:Ue,loadQuota:X,saveQuota:de,recordConnectionSent:Pe,canSendConnection:ee,getRecentConnections:Z,getQuotaStatus:te,loadSyncState:qe,saveSyncState:Ve,commitDataSnapshot:We,logApplicationQuestions:Ye,getQuestionStats:ze}});var ot={};Ie(ot,{getJobDecision:()=>Pt,getLastVisit:()=>Bt,getScoutStats:()=>Qt,loadCompanies:()=>tt,loadDiscoveredPeople:()=>ye,loadJobDecisions:()=>Se,loadScoutedJobs:()=>he,loadVisitLog:()=>oe,recordVisit:()=>Vt,resetCaches:()=>Nt,saveCompany:()=>qt,saveDiscoveredPerson:()=>Ut,saveScoutedJob:()=>Mt,setJobDecision:()=>Jt});import"dotenv/config";import*as D from"fs";import*as y from"path";import{fileURLToPath as Ft}from"url";function Q(){D.existsSync(_)||D.mkdirSync(_,{recursive:!0})}function Y(t,e){let o=JSON.stringify(e,null,2),s=t+".tmp";D.writeFileSync(s,o);for(let n=0;n<3;n++)try{D.renameSync(s,t);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function z(t){try{if(D.existsSync(t))return JSON.parse(D.readFileSync(t,"utf-8"))}catch{}return null}function Nt(){U=null,q=null,V=null,B=null,E=null}function he(){return U||(U=z(Ke)||{},U)}function Mt(t,e){if(!t)return;Q();let o=he(),s=new Date().toISOString().slice(0,10);if(o[t]){for(let[n,r]of Object.entries(e))r!=null&&(o[t][n]=r);o[t].lastSeen=s}else o[t]={...e,scoutedAt:s,lastSeen:s};try{Y(Ke,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}function Se(){return q||(q=z(et)||{},q)}function Jt(t,e,o={}){if(!t||!e)return;Q();let s=Se(),n=new Date().toISOString().slice(0,10);s[t]?(s[t].status=e,s[t].updatedAt=n,o.reason&&(s[t].reason=o.reason),o.score!=null&&(s[t].score=o.score),o.source&&(s[t].source=o.source)):s[t]={status:e,decidedAt:n,updatedAt:n,reason:o.reason||null,score:o.score??null,source:o.source||null};try{Y(et,s)}catch(r){console.error(`[!] Failed to save job-decisions.json: ${r.message}`)}}function Pt(t){return Se()[t]||null}function ye(){return V||(V=z(He)||{},V)}function Ut(t,e){if(!t)return;Q();let o=ye(),s=new Date().toISOString().slice(0,10);if(o[t]){let n=o[t];e.name&&(n.name=e.name),e.title&&(n.title=e.title),e.company&&(n.company=e.company),e.location&&(n.location=e.location),e.role&&(n.role=e.role),e.isConnected!=null&&(n.isConnected=e.isConnected),e.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(e.jobId)||n.jobIds.push(e.jobId)),n.lastSeen=s,n.seenCount=(n.seenCount||1)+1}else o[t]={name:e.name||null,title:e.title||null,company:e.company||null,location:e.location||null,role:e.role||null,source:e.source||"scout",isConnected:e.isConnected||!1,discoveredAt:s,lastSeen:s,seenCount:1,jobIds:e.jobId?[e.jobId]:[]};try{Y(He,o)}catch(n){console.error(`[!] Failed to save discovered-people.json: ${n.message}`)}}function tt(){return B||(B=z(Ze)||{},B)}function qt(t,e){if(!t)return;Q();let o=tt(),s=new Date().toISOString().slice(0,10);if(o[t]){let n=o[t];e.name&&(n.name=e.name),e.about&&(n.about=e.about),e.size&&(n.size=e.size),e.industries&&(n.industries=e.industries),e.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(e.jobId)||n.jobIds.push(e.jobId)),e.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(e.recruiterUrl)||n.recruiterUrls.push(e.recruiterUrl)),n.lastSeen=s,n.jobCount=n.jobIds?.length||0}else o[t]={name:e.name||null,about:e.about||null,size:e.size||null,industries:e.industries||null,discoveredAt:s,lastSeen:s,jobIds:e.jobId?[e.jobId]:[],recruiterUrls:e.recruiterUrl?[e.recruiterUrl]:[],jobCount:e.jobId?1:0};try{Y(Ze,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}function oe(){return E||(E=z(Xe)||{visits:[]},Array.isArray(E.visits)||(E.visits=[]),E)}function Vt(t,e={}){if(!t)return;Q();let o=oe();o.visits.push({date:new Date().toISOString(),profileUrl:t,name:e.name||null,source:e.source||"manual"});let s=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(n=>new Date(n.date).getTime()>s);try{Y(Xe,o)}catch(n){console.error(`[!] Failed to save visit-log.json: ${n.message}`)}}function Bt(t){let e=oe();for(let o=e.visits.length-1;o>=0;o--)if(e.visits[o].profileUrl===t)return e.visits[o].date;return null}function Qt(){let t=he(),e=ye(),o=Object.values(t),s=Object.values(e),n={};for(let l of o)l.company&&(n[l.company]=(n[l.company]||0)+1);let r=Object.entries(n).sort((l,p)=>p[1]-l[1]).slice(0,5).map(([l,p])=>`${l} (${p})`),i={};for(let l of o)for(let p of l.techStack||[])i[p]=(i[p]||0)+1;let c=Object.entries(i).sort((l,p)=>p[1]-l[1]).slice(0,8).map(([l,p])=>`${l} (${p})`),a=oe(),f=new Date().toISOString().slice(0,10),u=a.visits.filter(l=>l.date.startsWith(f)).length,v=new Set(a.visits.map(l=>l.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:s.length,topCompanies:r,topTech:c,totalVisited:v,todayVisited:u,lastScoutDate:o.length>0?o.sort((l,p)=>(p.scoutedAt||"").localeCompare(l.scoutedAt||""))[0]?.scoutedAt:null}}var Lt,kt,_,Ke,He,Xe,Ze,et,U,q,V,B,E,nt=De(()=>{Lt=Ft(import.meta.url),kt=y.dirname(y.dirname(Lt)),_=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(kt,"market-research"),Ke=y.join(_,"scouted-jobs.json"),He=y.join(_,"discovered-people.json"),Xe=y.join(_,"visit-log.json"),Ze=y.join(_,"companies.json"),et=y.join(_,"job-decisions.json");U=null;q=null;V=null;B=null;E=null});import{execFileSync as Ht}from"child_process";import"dotenv/config";import*as b from"fs";import*as w from"path";import{fileURLToPath as Dt}from"url";import"dotenv/config";import{createGraphClient as St,resolveToken as yt}from"@ilivemylife/graph-sdk";import{config as jt}from"dotenv";jt();var we=yt()||process.env.TOKEN;we||(console.error(`
1
+ var Te=Object.defineProperty;var Z=(e,o)=>{for(var t in o)Te(e,t,{get:o[t],enumerable:!0})};import{execFileSync as Co}from"child_process";import"dotenv/config";import*as S from"fs";import*as R from"path";import{fileURLToPath as Fe}from"url";import"dotenv/config";import{createGraphClient as Ee,resolveToken as De}from"@ilivemylife/graph-sdk";import{config as Ne}from"dotenv";Ne();var ee=De()||process.env.TOKEN;ee||(console.error(`
5
2
  [FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
6
3
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
7
4
  `),console.error(` Or add ILML_TOKEN=... to .env
8
- `),process.exit(1));var Oe=St({token:we});function vt(t){if(!t||t<1e3)return`${t||0}ms`;let e=Math.round(t/1e3);if(e<60)return`${e}s`;let o=Math.floor(e/60),s=e%60;return s?`${o}m ${s}s`:`${o}m`}function bt({scriptName:t,mode:e,status:o,error:s,duration:n}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=n?` ${vt(n)}`:"",a=o==="error"?`error${s?`: ${String(s).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",f=e&&e!=="default"?` (${e})`:"";return`${r} ${t}${f} \u2014 ${a} \u2014 ${i}${c}`}async function $e({scriptName:t,mode:e,status:o,summaryLines:s,error:n,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(s)||s.length===0)return;let a=`**${bt({scriptName:t,mode:e,status:o,error:n,duration:r})}**
5
+ `),process.exit(1));var oe=Ee({token:ee});function Ce(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return n?`${t}m ${n}s`:`${t}m`}function xe({scriptName:e,mode:o,status:t,error:n,duration:s}){let r=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${Ce(s)}`:"",a=t==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:t==="quota-reached"?"daily quota reached":"done",u=o&&o!=="default"?` (${o})`:"";return`${r} ${e}${u} \u2014 ${a} \u2014 ${i}${l}`}async function ne({scriptName:e,mode:o,status:t,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let a=`**${xe({scriptName:e,mode:o,status:t,error:s,duration:r})}**
9
6
 
10
- ${s.join(`
11
- `)}`;try{await Oe.addMessage(i,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var It=Dt(import.meta.url),wt=w.dirname(w.dirname(It)),re=process.env.DATA_DIR?w.resolve(process.env.DATA_DIR,"collected-profiles"):w.join(wt,"collected-profiles"),ie=w.join(re,"run-log.json");function Ot(t,e){let o=JSON.stringify(e,null,2),s=t+".tmp";b.writeFileSync(s,o);for(let n=0;n<3;n++)try{b.renameSync(s,t);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Re(){try{if(!b.existsSync(ie))return{runs:[]};let t=JSON.parse(b.readFileSync(ie,"utf-8"));return!t.runs||!Array.isArray(t.runs)?{runs:[]}:t}catch{return{runs:[]}}}function Te(t){b.existsSync(re)||b.mkdirSync(re,{recursive:!0});try{Ot(ie,t)}catch(e){console.error(`[!] Failed to save run-log.json: ${e.message}`)}}function Ce(t,e="default"){let o=Re();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let s=new Date,n={timestamp:s.toISOString(),script:t,mode:e,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),Te(o),{script:t,mode:e,startTime:s.getTime(),runIndex:o.runs.length-1}}function Ae(t,e,o=null,s=null){if(!t)return;let n=null;try{let i=Re(),c=i.runs[t.runIndex];if(c&&c.status==="running"&&c.script===t.script)c.status=e,c.result=e,c.duration=Date.now()-t.startTime,c.stats=o,c.error=s,n=c.duration;else{let a=i.runs.find(f=>f.script===t.script&&f.status==="running"&&f.timestamp===new Date(t.startTime).toISOString());a&&(a.status=e,a.result=e,a.duration=Date.now()-t.startTime,a.stats=o,a.error=s,n=a.duration)}Te(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=e==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";$e({scriptName:t.script,mode:t.mode,status:i,summaryLines:r,error:s,duration:n??Date.now()-t.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}ge();import"dotenv/config";import*as j from"fs";import*as g from"path";import{fileURLToPath as Yt}from"url";var zt=Yt(import.meta.url),Wt=g.dirname(zt),it=g.dirname(g.dirname(Wt)),ne=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(it,"collected-profiles"),se=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"market-research"):g.join(it,"market-research"),je=1,Gt=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function ct(t){return g.join(t,".schema-version")}function ve(t){let e=ct(t);if(!j.existsSync(e))return{version:0,migrations:[]};try{return JSON.parse(j.readFileSync(e,"utf-8"))}catch{return{version:0,migrations:[]}}}function Kt(t,e){j.writeFileSync(ct(t),JSON.stringify(e,null,2))}function st(t,e){if(!j.existsSync(t))return;let o=`.pre-v${String(e).padStart(3,"0")}.backup`,s=j.readdirSync(t).filter(n=>n.endsWith(".json")&&!n.includes(".backup"));for(let n of s){let r=g.join(t,n),i=g.join(t,n+o);try{j.copyFileSync(r,i)}catch(c){console.error(` [!] Failed to backup ${n}: ${c.message}`)}}s.length>0&&console.log(` Backed up ${s.length} files in ${g.basename(t)}/ (${o})`)}var rt=!1;async function lt(){if(rt)return;rt=!0;let t=ve(ne),e=ve(se),o=Math.min(t.version,e.version);if(o>=je)return;console.log(`
12
- \u{1F4E6} Schema migration: v${o} \u2192 v${je}`);let s=Gt.filter(n=>n.version>o);for(let n of s){console.log(`
13
- Running migration v${String(n.version).padStart(3,"0")}...`),st(ne,n.version),st(se,n.version);let r=await import(n.file);try{await r.up(ne,se)}catch(a){console.error(`
14
- [FATAL] Migration v${n.version} failed: ${a.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(n.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
15
- `),process.exit(1)}let i=new Date().toISOString(),c={version:n.version,name:r.NAME||`v${String(n.version).padStart(3,"0")}`,appliedAt:i};for(let a of[ne,se]){if(!j.existsSync(a))continue;let f=ve(a);f.version=n.version,f.migratedAt=i,f.migrations.push(c),Kt(a,f)}console.log(` \u2713 Migration v${String(n.version).padStart(3,"0")} complete`)}try{let{resetCaches:n}=await Promise.resolve().then(()=>(ge(),Ge));n()}catch{}try{let{resetCaches:n}=await Promise.resolve().then(()=>(nt(),ot));n()}catch{}console.log(`
16
- \u2713 Schema is now at v${je}
17
- `)}await lt();var W=process.argv.slice(2),be=new Set((W.find(t=>t.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),at=new Set((W.find(t=>t.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),ft=W.includes("--dry-run"),dt=W.includes("--jobs"),mt=W.includes("--comms"),ut=["apply-queue","apply","funnel","scout","visit"],pt=["sync","today"],gt=dt?ut:mt?pt:[...ut,...pt];function $(t){return at.size>0?at.has(t):!be.has(t)&&gt.includes(t)}function N(t,e,o=[],{optional:s=!1}={}){if(console.log(`
18
- ${"\u2550".repeat(50)}`),console.log(` STEP: ${t}`),console.log("\u2550".repeat(50)),ft)return console.log(` [DRY RUN] Would run: node ${e} ${o.join(" ")}`),!0;try{return Ht("node",[e,...o],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${t} completed`),!0}catch(n){return s?(console.log(` \u26A0 ${t} failed (optional): ${n.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${t} failed: ${n.message?.slice(0,80)}`),!1)}}async function Xt(){let t=dt?"jobs":mt?"comms":"full";console.log(`
19
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` DAILY PIPELINE (${t})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let e=gt.filter($);console.log(` Steps: ${e.join(" \u2192 ")}`),be.size>0&&console.log(` Skipping: ${[...be].join(", ")}`),ft&&console.log(" [DRY RUN MODE]");let o=Ce("daily",t),s={};if($("apply-queue")&&(s["apply-queue"]=N("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),$("apply")){let r=te();s.apply=N("Apply from Search","run.mjs",["--no-wait"],{optional:!0})}if($("funnel")&&!$("apply")){let r=ee();r.allowed?s.funnel=N("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
20
- \u26A0 Funnel skipped: ${r.reason}`),s.funnel="skipped_quota")}$("scout")&&(s.scout=N("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),$("sync")&&(s.sync=N("Sync Inbox","syncAll.mjs")),$("today")&&(s.today=N("Daily Report","syncAll.mjs",["--today"])),console.log(`
21
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PIPELINE COMPLETE"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let[r,i]of Object.entries(s))console.log(` ${i===!0?"\u2713":i===!1?"\u2717":"\u26A0"} ${r}: ${i===!0?"success":i===!1?"failed":i}`);console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
22
- `);let n=Object.values(s).some(r=>r===!1);Ae(o,n?"partial":"success",s)}Xt().catch(t=>{console.error("Daily pipeline failed:",t),process.exit(1)});
7
+ ${n.join(`
8
+ `)}`;try{await oe.addMessage(i,a)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var _e=Fe(import.meta.url),Le=R.dirname(R.dirname(_e)),B=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Le,"collected-profiles"),V=R.join(B,"run-log.json");function Pe(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";S.writeFileSync(n,t);for(let s=0;s<3;s++)try{S.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function te(){try{if(!S.existsSync(V))return{runs:[]};let e=JSON.parse(S.readFileSync(V,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function se(e){S.existsSync(B)||S.mkdirSync(B,{recursive:!0});try{Pe(V,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function re(e,o="default"){let t=te();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>r),se(t),{script:e,mode:o,startTime:n.getTime(),runIndex:t.runs.length-1}}function ie(e,o,t=null,n=null){if(!e)return;let s=null;try{let i=te(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=o,l.result=o,l.duration=Date.now()-e.startTime,l.stats=t,l.error=n,s=l.duration;else{let a=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());a&&(a.status=o,a.result=o,a.duration=Date.now()-e.startTime,a.stats=t,a.error=n,s=a.duration)}se(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";ne({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as d from"fs";import*as h from"path";import{fileURLToPath as Me}from"url";var Je=Me(import.meta.url),Ue=h.dirname(h.dirname(Je)),k=process.env.DATA_DIR?h.resolve(process.env.DATA_DIR,"collected-profiles"):h.join(Ue,"collected-profiles"),Ho=h.join(k,"people.json"),Qo=h.join(k,"jobs.json"),Be=h.join(k,"quota.json"),zo=h.join(k,"conversations.json"),Ko=h.join(k,"sync-state.json"),Xo=h.join(k,"application-questions.json"),Zo=h.join(k,"profile-history"),_=20,L=100,Ve=null,qe=null,I=null,We=null,Ye=null,Ge=null;function ce(){Ve=null,qe=null,I=null,We=null,Ye=null,Ge=null}function He(){d.existsSync(k)||d.mkdirSync(k,{recursive:!0})}function Qe(e,o){if(!d.existsSync(e))return null;try{let t=JSON.parse(d.readFileSync(e,"utf-8"));try{d.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${h.resolve(e)}`);let n=e+".backup";if(d.existsSync(n))try{let s=JSON.parse(d.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{d.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function le(){return new Date().toISOString().split("T")[0]}function ze(){return I||(He(),I=Qe(Be,"quota.json"),(!I||!I.connections)&&(I={connections:[]}),I)}function ae(){let e=ze(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(n=>n.date>=t)}function ue(){let e=ae(),o=le(),t=e.filter(a=>a.date===o).length,n=e.length,s=t>=_,r=n>=L,i=!s&&!r,l={allowed:i,daily:{sent:t,max:_},weekly:{sent:n,max:L}};return i||(l.reason=s?`Daily limit reached (${t}/${_})`:`Weekly limit reached (${n}/${L})`),l}function fe(){let e=ae(),o=le(),t=e.filter(s=>s.date===o).length,n=e.length;return{daily:{sent:t,max:_,remaining:_-t},weekly:{sent:n,max:L,remaining:L-n}}}import"dotenv/config";import*as c from"fs";import*as Q from"os";import*as f from"path";import{fileURLToPath as go}from"url";var Y={};Z(Y,{NAME:()=>Xe,VERSION:()=>Ke,up:()=>oo});import*as b from"fs";import*as J from"path";var Ke=1,Xe="normalize-jobs-and-questions",Ze=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],eo=50;function q(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function W(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{b.writeFileSync(n,t)}catch(s){try{b.unlinkSync(n)}catch{}throw s}try{b.renameSync(n,e)}catch(s){try{b.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function oo(e,o){let t=J.join(e,"jobs.json"),n=J.join(o,"scouted-jobs.json"),s=J.join(e,"application-questions.json"),r=q(t)||{},i=q(n)||{},l=0,a=[];for(let p of Object.keys(r)){if(!i[p])continue;let O=i[p],m=r[p];for(let A of Ze)O[A]!=null&&m[A]==null&&(m[A]=O[A]);a.push(p),l++}l>0?(W(t,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=q(s);if(u&&Array.isArray(u.applications)){let p={},O=0;for(let m of u.applications){let A=m.jobId||"unknown";p[A]||(p[A]={applications:[]});let X=(m.questions||[]).map($=>{let x={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=eo?x.options=$.options:(x.optionsOmitted=!0,O++)),$.page&&(x.page=$.page),$.wasPreFilled&&(x.wasPreFilled=!0),$.wasRetry&&(x.wasRetry=!0),x});p[A].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||X.length,questions:X})}W(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),O>0&&console.log(` Phase 2: Stripped bloated options from ${O} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let p of a)delete i[p];W(n,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var G={};Z(G,{NAME:()=>to,VERSION:()=>no,up:()=>io});import*as v from"fs";import*as pe from"path";var no=2,to="reset-unread-flags";function so(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function ro(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{v.writeFileSync(n,t)}catch(s){try{v.unlinkSync(n)}catch{}throw s}try{v.renameSync(n,e)}catch(s){try{v.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function io(e){let o=pe.join(e,"conversations.json"),t=so(o);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(t))t[s].unread===!0&&(t[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}ro(o,t),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}import"dotenv/config";import*as y from"path";import{fileURLToPath as co}from"url";var lo=co(import.meta.url),ao=y.dirname(y.dirname(lo)),P=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(ao,"market-research"),tn=y.join(P,"scouted-jobs.json"),sn=y.join(P,"discovered-people.json"),rn=y.join(P,"visit-log.json"),cn=y.join(P,"companies.json"),ln=y.join(P,"job-decisions.json");function de(){uo=null,fo=null,po=null,ho=null,mo=null}var uo=null;var fo=null;var po=null;var ho=null;var mo=null;var yo=go(import.meta.url),So=f.dirname(yo),bo=f.dirname(f.dirname(So));function vo(e){return e&&(e==="~"?Q.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(Q.homedir(),e.slice(2)):e)}var w=process.env.DATA_DIR?f.resolve(vo(process.env.DATA_DIR)):bo,N=f.join(w,"collected-profiles"),C=f.join(w,"market-research"),g=f.join(w,".schema-version"),he=[f.join(N,".schema-version"),f.join(C,".schema-version")],T=2,j=[{version:1,module:Y},{version:2,module:G}];(function(){j.sort((n,s)=>n.version-s.version);let o=new Set;for(let n of j){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(o.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);o.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=j.length?j[j.length-1].version:0;if(t!==T)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${T}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<j.length;n++){let s=n+1;if(j[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${j[n].version}`)}})();function Se(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
9
+ [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
10
+ `),process.exit(1));try{c.mkdirSync(w,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
11
+ [FATAL] Cannot create DATA_DIR (${w}): ${o.message}`),console.error(` Fix the path or permissions and try again.
12
+ `),process.exit(1))}let e;try{e=c.statSync(w)}catch(o){console.error(`
13
+ [FATAL] DATA_DIR (${w}) is not accessible: ${o.message}
14
+ `),process.exit(1)}e.isDirectory()||(console.error(`
15
+ [FATAL] DATA_DIR (${w}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
16
+ `),process.exit(1));for(let o of[N,C]){let t;try{t=c.lstatSync(o)}catch(n){if(n.code==="ENOENT")continue;throw n}t.isSymbolicLink()&&(console.error(`
17
+ [FATAL] Data subdirectory is a symbolic link: ${o}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
18
+ `),process.exit(1))}}var D=f.join(w,".migration-lock");function $o(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return c.writeFileSync(D,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let o;try{o=JSON.parse(c.readFileSync(D,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let n=!1;try{process.kill(o.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(o.startedAt){let i=Date.parse(o.startedAt);Number.isNaN(i)||(r=Date.now()-i)}n&&r<s&&(console.error(`
19
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${D}
20
+ `),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
21
+ `),process.exit(1)),n&&r>=s&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let t=D+".tmp";try{return c.writeFileSync(t,e),c.renameSync(t,D),!0}catch(n){try{c.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function z(){try{if(JSON.parse(c.readFileSync(D,"utf-8")).pid!==process.pid)return;c.unlinkSync(D)}catch{}}var me=!1;function wo(){if(me)return;me=!0;let e=()=>{try{z()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function ko(){if(c.existsSync(g))return;let e=[],o=[];for(let r of he)if(c.existsSync(r))try{e.push({file:r,schema:U(r)})}catch(i){o.push({file:r,err:i.message})}if(o.length>0){console.error(`
22
+ [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of o)console.error(` ${r.file}: ${r.err}`);console.error(`
23
+ Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
24
+ `),process.exit(1)}if(e.length===0)return;let t=e.map(r=>r.schema.version);if(new Set(t).size>1){console.error(`
25
+ [FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
26
+ `),process.exit(1)}let n=e[0].schema,s=g+".tmp";try{c.writeFileSync(s,JSON.stringify(n,null,2)),c.renameSync(s,g)}catch(r){try{c.unlinkSync(s)}catch{}throw r}for(let r of he)if(c.existsSync(r))try{c.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${g}`)}function jo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function U(e){let o=c.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function ge(){if(ko(),!c.existsSync(g))return{version:0,migrations:[]};let e;try{e=U(g)}catch(t){if(t.code==="ENOENT")return{version:0,migrations:[]};console.error(`
27
+ [FATAL] ${g} is not valid JSON: ${t.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
28
+ `),process.exit(1)}let o=jo(e);return o===null&&(console.error(`
29
+ [FATAL] ${g} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
30
+ `),process.exit(1)),o}function be(e){try{c.chmodSync(e,384)}catch{}}function Oo(e){if(Se(),c.existsSync(g))try{if(c.lstatSync(g).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${g}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(t){if(t.message?.includes("symbolic link"))throw t}let o=g+".tmp";try{c.writeFileSync(o,JSON.stringify(e,null,2)),be(o),c.renameSync(o,g)}catch(t){try{c.unlinkSync(o)}catch{}throw t}}function ye(e,o){if(!c.existsSync(e))return;let t=`.pre-v${String(o).padStart(3,"0")}.backup`,n=c.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return c.statSync(f.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let a=f.join(e,l),u=f.join(e,l+t);if(c.existsSync(u)){r++;continue}try{$e(a,u),s++}catch(p){i.push({file:l,err:p.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${f.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${f.basename(e)}/ (${t})${l}`)}}var H=!1;async function ve(){if(H)return;Se(),Eo();let o=ge().version;if(o===T){H=!0;return}wo(),$o(),process.on("exit",z),o>T&&(console.error(`
31
+ [FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${T}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
32
+ `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${T}.
33
+ `),process.exit(1)),console.log(`
34
+ \u{1F4E6} Schema migration: v${o} \u2192 v${T}`);let t=Do();if(!t.ok){console.error(`
35
+ [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of t.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
36
+ Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
37
+ `),process.exit(1)}let n=j.filter(s=>s.version>o);for(let s of n){console.log(`
38
+ Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{ye(N,s.version),ye(C,s.version)}catch(a){console.error(`
39
+ [FATAL] Pre-migration backup failed for ${r}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
40
+ `),process.exit(1)}let l=s.module;try{await l.up(N,C)}catch(a){console.error(`
41
+ [FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=No(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
42
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
43
+ `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
44
+ `)}process.exit(1)}try{let a=new Date().toISOString(),u={version:s.version,name:l.NAME||r,appliedAt:a},p=ge();p.version=s.version,p.migratedAt=a,p.migrations=p.migrations||[],p.migrations.push(u),Oo(p)}catch(a){console.error(`
45
+ [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${o}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
46
+ `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{ce()}catch{}try{de()}catch{}H=!0,z(),console.log(`
47
+ \u2713 Schema is now at v${T}
48
+ `)}var Ao=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Ro(e){let o=e.toLowerCase();return Ao.some(t=>t.test(o))}var Io=6e4;function To(){let e=Date.now(),o=[];for(let t of[w,N,C]){if(!c.existsSync(t))continue;let n;try{n=c.readdirSync(t)}catch{continue}for(let s of n){if(!Ro(s))continue;let r=f.join(t,s);try{let i=c.statSync(r);if(!i.isFile()||e-i.mtimeMs<Io)continue;o.push({dir:t,file:s,fullPath:r})}catch{}}}return o}function Eo({verbose:e=!1}={}){let o=To();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let n of o)try{c.unlinkSync(n.fullPath),t++,e&&console.log(` Removed orphan: ${f.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function Do(){let e=[];for(let o of[N,C]){if(!c.existsSync(o))continue;let t=c.readdirSync(o).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of t){let s=f.join(o,n);try{U(s)}catch(r){e.push({dir:f.basename(o),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function No(e){let o=[],t=[];for(let r of[N,C]){if(!c.existsSync(r))continue;let i=c.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let a=f.join(r,l),u=l.slice(0,-e.length),p=f.join(r,u);try{u.toLowerCase().endsWith(".json")?U(a):c.accessSync(a,c.constants.R_OK),o.push({backupPath:a,originalPath:p,fileName:l,dir:r})}catch(O){t.push(`${f.basename(r)}/${l}: ${O.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of o)try{$e(r,i),n++}catch(u){s.push(`${f.basename(a)}/${l}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function $e(e,o){let t=o+".tmp";try{c.copyFileSync(e,t),be(t)}catch(n){try{c.unlinkSync(t)}catch{}throw n}try{c.renameSync(t,o)}catch(n){try{c.unlinkSync(t)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${o} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=n.code,s}throw n}}await ve();var M=process.argv.slice(2),K=new Set((M.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),we=new Set((M.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Oe=M.includes("--dry-run"),Ae=M.includes("--jobs"),Re=M.includes("--comms"),ke=["apply-queue","apply","funnel","scout","visit"],je=["sync","today"],Ie=Ae?ke:Re?je:[...ke,...je];function E(e){return we.size>0?we.has(e):!K.has(e)&&Ie.includes(e)}function F(e,o,t=[],{optional:n=!1}={}){if(console.log(`
49
+ ${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Oe)return console.log(` [DRY RUN] Would run: node ${o} ${t.join(" ")}`),!0;try{return Co("node",[o,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(s){return n?(console.log(` \u26A0 ${e} failed (optional): ${s.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${s.message?.slice(0,80)}`),!1)}}async function xo(){let e=Ae?"jobs":Re?"comms":"full";console.log(`
50
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` DAILY PIPELINE (${e})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let o=Ie.filter(E);console.log(` Steps: ${o.join(" \u2192 ")}`),K.size>0&&console.log(` Skipping: ${[...K].join(", ")}`),Oe&&console.log(" [DRY RUN MODE]");let t=re("daily",e),n={};if(E("apply-queue")&&(n["apply-queue"]=F("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),E("apply")){let r=fe();n.apply=F("Apply from Search","run.mjs",[],{optional:!0})}if(E("funnel")&&!E("apply")){let r=ue();r.allowed?n.funnel=F("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
51
+ \u26A0 Funnel skipped: ${r.reason}`),n.funnel="skipped_quota")}E("scout")&&(n.scout=F("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),E("sync")&&(n.sync=F("Sync Inbox","syncAll.mjs")),E("today")&&(n.today=F("Daily Report","syncAll.mjs",["--today"])),console.log(`
52
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PIPELINE COMPLETE"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");for(let[r,i]of Object.entries(n))console.log(` ${i===!0?"\u2713":i===!1?"\u2717":"\u26A0"} ${r}: ${i===!0?"success":i===!1?"failed":i}`);console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
53
+ `);let s=Object.values(n).some(r=>r===!1);ie(t,s?"partial":"success",n)}xo().catch(e=>{console.error("Daily pipeline failed:",e),process.exit(1)});