ilml-plugin-linkedin 1.15.0 → 1.17.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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.17.0
4
+ - **Duplicate contacts are now prevented at the source, automatically — no command to run.** A person can appear on LinkedIn under two different URLs (a permanent id-based one and their custom-name one), and different parts of the plugin used to save them as two separate contacts. Two things fix this at the root: (1) whenever any command visits a profile, the plugin records the other URL LinkedIn redirects it to; (2) every write now checks whether you already have that person under any of their known URLs before creating a record — so a second copy isn't created in the first place. Works across all flows (apply, enrich, visit, sync), adds no profile visits, and needs nothing from you. Collapsing contacts that were *already* duplicated before this version is a separate follow-up. No schema change.
5
+
6
+ ## 1.16.0
7
+ - **New `ilml linkedin sync-connections` — find out who accepted your connection requests.** It scans your LinkedIn connections list and updates your local contacts: people who accepted flip to "connected" (with the accept date), and brand-new connections are imported. This is the piece that makes acceptance analytics (`quota`) and de-duplication actually accurate — run it after a batch of requests. (`sync`/`sync-all` handle your inbox; this handles your connections list.)
8
+ - **Won't silently create a duplicate contact when someone accepts.** A LinkedIn profile can have two different URLs for the same person (a permanent id-based one and their custom name one), which could make `sync-connections` file an accepted person as a second, separate contact. Now `connect run` remembers both URLs the moment it visits a profile, so acceptance is matched back to the original contact. As a fallback, if a brand-new connection shares a name with someone you still have a pending request to, it's flagged as a possible duplicate for you to review — never silently merged (two people can share a name). No schema change.
9
+
3
10
  ## 1.15.0
4
11
  - **Connection dates are now split into "requested" vs "accepted".** The plugin records when you *sent* a connection request separately from when it was *accepted* — before, one field held whichever happened last, so a still-pending person could look like they'd already connected. A one-time migration cleans up your existing contacts on first run (an automatic backup is saved before it touches anything).
5
12
 
@@ -1,29 +1,29 @@
1
- var Le=Object.defineProperty;var B=(e,n)=>{for(var o in n)Le(e,o,{get:n[o],enumerable:!0})};import"dotenv/config";import*as N from"fs";import*as M from"path";import{fileURLToPath as un}from"url";import{execFileSync as fn}from"child_process";import{getPluginConfig as Me}from"@ilivemylife/graph-sdk";var Pe=await Me();for(let[e,n]of Object.entries(Pe))process.env[e]===void 0&&(process.env[e]=n);var bn=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),vn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),wn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Je}from"url";var Ue=Je(import.meta.url),qe=g.dirname(g.dirname(Ue)),R=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(qe,"collected-profiles"),Be=g.join(R,"people.json"),En=g.join(R,"jobs.json"),On=g.join(R,"quota.json"),Rn=g.join(R,"conversations.json"),In=g.join(R,"sync-state.json"),Tn=g.join(R,"application-questions.json"),Dn=g.join(R,"profile-history"),ue=(e,n)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:n},Nn=ue(process.env.CONNECT_MAX_DAILY,20),Cn=ue(process.env.CONNECT_MAX_WEEKLY,100),J=null,Ve=null,We=null,Ge=null,Ye=null,He=null;function fe(){J=null,Ve=null,We=null,Ge=null,Ye=null,He=null}function Ke(){h.existsSync(R)||h.mkdirSync(R,{recursive:!0})}function Qe(e,n){if(!h.existsSync(e))return null;try{let o=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${n} is corrupted: ${o.message}`),console.error(` File: ${g.resolve(e)}`);let t=e+".backup";if(h.existsSync(t))try{let s=JSON.parse(h.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{h.copyFileSync(t,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function pe(){return J||(Ke(),J=Qe(Be,"people.json")||{},J)}import"dotenv/config";import*as v from"fs";import*as b from"path";import{fileURLToPath as ze}from"url";var Xe=ze(import.meta.url),Ze=b.dirname(b.dirname(Xe)),_=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(Ze,"market-research"),de=b.join(_,"scouted-jobs.json"),Ln=b.join(_,"discovered-people.json"),Mn=b.join(_,"visit-log.json"),Pn=b.join(_,"companies.json"),eo=b.join(_,"job-decisions.json");function oo(){v.existsSync(_)||v.mkdirSync(_,{recursive:!0})}function no(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";v.writeFileSync(t,o);for(let s=0;s<3;s++)try{v.renameSync(t,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 me(e){try{if(v.existsSync(e))return JSON.parse(v.readFileSync(e,"utf-8"))}catch{}return null}function he(){U=null,q=null,to=null,so=null,ro=null}var U=null;function H(){return U||(U=me(de)||{},U)}function ge(e,n){if(!e)return;oo();let o=H(),t=new Date().toISOString().slice(0,10);if(o[e]){for(let[s,r]of Object.entries(n))r!=null&&(o[e][s]=r);o[e].lastSeen=t}else o[e]={...n,scoutedAt:t,lastSeen:t};try{no(de,o)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}var q=null;function ye(){return q||(q=me(eo)||{},q)}var to=null;var so=null;var ro=null;var io=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),co=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Se=["vancouver","british columbia"],lo=["canada","montreal","quebec","alberta","calgary","ottawa"],ao=["toronto","ontario"],uo=["india","pakistan","nigeria","philippines"];function fo(e,n={}){let o=0,t=(e.techStack||[]).map(a=>a.toLowerCase()),s=0,r=0;for(let a of t)io.has(a)&&s++,co.has(a)&&r++;if(o+=Math.min(s*6,24),o+=Math.min(r*3,6),e.salary){let a=po(e.salary);a&&(a>=15e4?o+=20:a>=12e4?o+=15:a>=1e5?o+=10:a>=8e4?o+=5:a>=100&&a<1e3?o+=15:a>=70&&a<1e3&&(o+=10))}let i=(e.location||"").toLowerCase(),u=/remote/i.test(i)||e.workplaceType==="remote";uo.some(a=>i.includes(a))?o-=30:u&&/united states|usa|\bus\b/i.test(i)?o+=25:u&&Se.some(a=>i.includes(a))?o+=22:u?o+=20:Se.some(a=>i.includes(a))?o+=18:lo.some(a=>i.includes(a))?o+=10:ao.some(a=>i.includes(a))&&(o+=5),e.isEasyApply&&(o+=5);let c=(e.seniority||"").toLowerCase();c.includes("senior")||c.includes("lead")||c.includes("staff")?o+=10:c.includes("mid")?o+=5:(c.includes("entry")||c.includes("intern"))&&(o-=10),e.recruiterUrl&&(n.conversationRecruiters?.has(e.recruiterUrl)?o+=20:n.connectedRecruiters?.has(e.recruiterUrl)?o+=15:o+=3);let f=new Set(e.jobTags||[]);return f.has("managerial")?o+=8:f.has("senior-ic")&&(o+=5),f.has("junior")&&(o-=15),f.has("consultant")&&(o-=3),Math.max(0,Math.min(100,o))}function K(e=10,n={}){let{easyApplyOnly:o=!0}=n,t=H(),s=pe(),r=new Set,i=new Set;for(let[m,p]of Object.entries(s))p.connectionStatus==="connected"&&r.add(m);let u={connectedRecruiters:r,conversationRecruiters:i},c=ye(),f=new Set(["applied","skipped","expired","archived"]);return Object.entries(t).filter(([m,p])=>{if(typeof p!="object"||o&&!p.isEasyApply||p.applied)return!1;let y=c[m];return!(y&&f.has(y.status))}).map(([m,p])=>({jobId:m,score:fo(p,u),job:p})).sort((m,p)=>{if(p.score!==m.score)return p.score-m.score;let y=m.job.scoutedAt||m.job.postedTime||"";return(p.job.scoutedAt||p.job.postedTime||"").localeCompare(y)}).slice(0,e)}function po(e){if(!e)return null;let n=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!n||n.length===0)return null;let o=n.map(t=>{let s=parseFloat(t.replace(/[^\d.]/g,""));return t.toLowerCase().includes("k")&&(s*=1e3),s}).filter(t=>t>0);return o.length>=2?(o[0]+o[1])/2:o.length===1?o[0]:null}import"dotenv/config";import*as w from"fs";import*as T from"path";import{fileURLToPath as bo}from"url";import"dotenv/config";import{createGraphClient as mo,resolveToken as ho}from"@ilivemylife/graph-sdk";import{config as go}from"dotenv";go();var be=ho()||process.env.TOKEN;be||(console.error(`
1
+ var Le=Object.defineProperty;var B=(e,n)=>{for(var o in n)Le(e,o,{get:n[o],enumerable:!0})};import"dotenv/config";import*as N from"fs";import*as M from"path";import{fileURLToPath as un}from"url";import{execFileSync as fn}from"child_process";import{getPluginConfig as Me}from"@ilivemylife/graph-sdk";var Pe=await Me();for(let[e,n]of Object.entries(Pe))process.env[e]===void 0&&(process.env[e]=n);var bn=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),vn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),wn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Je}from"url";var Ue=Je(import.meta.url),qe=g.dirname(g.dirname(Ue)),I=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(qe,"collected-profiles"),Be=g.join(I,"people.json"),On=g.join(I,"jobs.json"),En=g.join(I,"quota.json"),In=g.join(I,"conversations.json"),Rn=g.join(I,"sync-state.json"),Tn=g.join(I,"application-questions.json"),Dn=g.join(I,"profile-history"),ue=(e,n)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:n},Nn=ue(process.env.CONNECT_MAX_DAILY,20),Cn=ue(process.env.CONNECT_MAX_WEEKLY,100),J=null,Ve=null,We=null,Ge=null,Ye=null,He=null;function fe(){J=null,Ve=null,We=null,Ge=null,Ye=null,He=null}function Ke(){h.existsSync(I)||h.mkdirSync(I,{recursive:!0})}function Qe(e,n){if(!h.existsSync(e))return null;try{let o=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${n} is corrupted: ${o.message}`),console.error(` File: ${g.resolve(e)}`);let t=e+".backup";if(h.existsSync(t))try{let s=JSON.parse(h.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{h.copyFileSync(t,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function pe(){return J||(Ke(),J=Qe(Be,"people.json")||{},J)}import"dotenv/config";import*as v from"fs";import*as b from"path";import{fileURLToPath as ze}from"url";var Xe=ze(import.meta.url),Ze=b.dirname(b.dirname(Xe)),_=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(Ze,"market-research"),de=b.join(_,"scouted-jobs.json"),Ln=b.join(_,"discovered-people.json"),Mn=b.join(_,"visit-log.json"),Pn=b.join(_,"companies.json"),eo=b.join(_,"job-decisions.json");function oo(){v.existsSync(_)||v.mkdirSync(_,{recursive:!0})}function no(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";v.writeFileSync(t,o);for(let s=0;s<3;s++)try{v.renameSync(t,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 me(e){try{if(v.existsSync(e))return JSON.parse(v.readFileSync(e,"utf-8"))}catch{}return null}function he(){U=null,q=null,to=null,so=null,ro=null}var U=null;function H(){return U||(U=me(de)||{},U)}function ge(e,n){if(!e)return;oo();let o=H(),t=new Date().toISOString().slice(0,10);if(o[e]){for(let[s,r]of Object.entries(n))r!=null&&(o[e][s]=r);o[e].lastSeen=t}else o[e]={...n,scoutedAt:t,lastSeen:t};try{no(de,o)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}var q=null;function ye(){return q||(q=me(eo)||{},q)}var to=null;var so=null;var ro=null;var io=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),co=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Se=["vancouver","british columbia"],lo=["canada","montreal","quebec","alberta","calgary","ottawa"],ao=["toronto","ontario"],uo=["india","pakistan","nigeria","philippines"];function fo(e,n={}){let o=0,t=(e.techStack||[]).map(a=>a.toLowerCase()),s=0,r=0;for(let a of t)io.has(a)&&s++,co.has(a)&&r++;if(o+=Math.min(s*6,24),o+=Math.min(r*3,6),e.salary){let a=po(e.salary);a&&(a>=15e4?o+=20:a>=12e4?o+=15:a>=1e5?o+=10:a>=8e4?o+=5:a>=100&&a<1e3?o+=15:a>=70&&a<1e3&&(o+=10))}let i=(e.location||"").toLowerCase(),u=/remote/i.test(i)||e.workplaceType==="remote";uo.some(a=>i.includes(a))?o-=30:u&&/united states|usa|\bus\b/i.test(i)?o+=25:u&&Se.some(a=>i.includes(a))?o+=22:u?o+=20:Se.some(a=>i.includes(a))?o+=18:lo.some(a=>i.includes(a))?o+=10:ao.some(a=>i.includes(a))&&(o+=5),e.isEasyApply&&(o+=5);let c=(e.seniority||"").toLowerCase();c.includes("senior")||c.includes("lead")||c.includes("staff")?o+=10:c.includes("mid")?o+=5:(c.includes("entry")||c.includes("intern"))&&(o-=10),e.recruiterUrl&&(n.conversationRecruiters?.has(e.recruiterUrl)?o+=20:n.connectedRecruiters?.has(e.recruiterUrl)?o+=15:o+=3);let f=new Set(e.jobTags||[]);return f.has("managerial")?o+=8:f.has("senior-ic")&&(o+=5),f.has("junior")&&(o-=15),f.has("consultant")&&(o-=3),Math.max(0,Math.min(100,o))}function K(e=10,n={}){let{easyApplyOnly:o=!0}=n,t=H(),s=pe(),r=new Set,i=new Set;for(let[m,p]of Object.entries(s))p.connectionStatus==="connected"&&r.add(m);let u={connectedRecruiters:r,conversationRecruiters:i},c=ye(),f=new Set(["applied","skipped","expired","archived"]);return Object.entries(t).filter(([m,p])=>{if(typeof p!="object"||o&&!p.isEasyApply||p.applied)return!1;let y=c[m];return!(y&&f.has(y.status))}).map(([m,p])=>({jobId:m,score:fo(p,u),job:p})).sort((m,p)=>{if(p.score!==m.score)return p.score-m.score;let y=m.job.scoutedAt||m.job.postedTime||"";return(p.job.scoutedAt||p.job.postedTime||"").localeCompare(y)}).slice(0,e)}function po(e){if(!e)return null;let n=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!n||n.length===0)return null;let o=n.map(t=>{let s=parseFloat(t.replace(/[^\d.]/g,""));return t.toLowerCase().includes("k")&&(s*=1e3),s}).filter(t=>t>0);return o.length>=2?(o[0]+o[1])/2:o.length===1?o[0]:null}import"dotenv/config";import*as w from"fs";import*as T from"path";import{fileURLToPath as bo}from"url";import"dotenv/config";import{createGraphClient as mo,resolveToken as ho}from"@ilivemylife/graph-sdk";import{config as go}from"dotenv";go();var be=ho()||process.env.TOKEN;be||(console.error(`
2
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.
3
3
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
4
4
  `),console.error(` Or add ILML_TOKEN=... to .env
5
5
  `),process.exit(1));var ve=mo({token:be});function yo(e){if(!e||e<1e3)return`${e||0}ms`;let n=Math.round(e/1e3);if(n<60)return`${n}s`;let o=Math.floor(n/60),t=n%60;return t?`${o}m ${t}s`:`${o}m`}function So({scriptName:e,mode:n,status:o,error:t,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),u=s?` ${yo(s)}`:"",c=o==="error"?`error${t?`: ${String(t).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",f=n&&n!=="default"?` (${n})`:"";return`${r} ${e}${f} \u2014 ${c} \u2014 ${i}${u}`}async function we({scriptName:e,mode:n,status:o,summaryLines:t,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(t)||t.length===0)return;let c=`**${So({scriptName:e,mode:n,status:o,error:s,duration:r})}**
6
6
 
7
7
  ${t.join(`
8
- `)}`;try{await ve.addMessage(i,c)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var vo=bo(import.meta.url),wo=T.dirname(T.dirname(vo)),Q=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(wo,"collected-profiles"),z=T.join(Q,"run-log.json");function $o(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";w.writeFileSync(t,o);for(let s=0;s<3;s++)try{w.renameSync(t,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 $e(){try{if(!w.existsSync(z))return{runs:[]};let e=JSON.parse(w.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ae(e){w.existsSync(Q)||w.mkdirSync(Q,{recursive:!0});try{$o(z,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function ke(e,n="default"){let o=$e();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 t=new Date,s={timestamp:t.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),Ae(o),{script:e,mode:n,startTime:t.getTime(),runIndex:o.runs.length-1}}function X(e,n,o=null,t=null){if(!e)return;let s=null;try{let i=$e(),u=i.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=n,u.result=n,u.duration=Date.now()-e.startTime,u.stats=o,u.error=t,s=u.duration;else{let c=i.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());c&&(c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=o,c.error=t,s=c.duration)}Ae(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=n==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";we({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:t,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}import"dotenv/config";import*as l from"fs";import*as ie from"os";import*as d from"path";import{fileURLToPath as Go}from"url";var oe={};B(oe,{NAME:()=>ko,VERSION:()=>Ao,up:()=>Oo});import*as $ from"fs";import*as V from"path";var Ao=1,ko="normalize-jobs-and-questions",jo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Eo=50;function Z(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function ee(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{$.writeFileSync(t,o)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}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,n){let o=V.join(e,"jobs.json"),t=V.join(n,"scouted-jobs.json"),s=V.join(e,"application-questions.json"),r=Z(o)||{},i=Z(t)||{},u=0,c=[];for(let a of Object.keys(r)){if(!i[a])continue;let m=i[a],p=r[a];for(let y of jo)m[y]!=null&&p[y]==null&&(p[y]=m[y]);c.push(a),u++}u>0?(ee(o,r),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Z(s);if(f&&Array.isArray(f.applications)){let a={},m=0;for(let p of f.applications){let y=p.jobId||"unknown";a[y]||(a[y]={applications:[]});let Y=(p.questions||[]).map(E=>{let P={type:E.type||"input",question:E.question||"",answer:E.answer||""};return E.options&&(E.options.length<=Eo?P.options=E.options:(P.optionsOmitted=!0,m++)),E.page&&(P.page=E.page),E.wasPreFilled&&(P.wasPreFilled=!0),E.wasRetry&&(P.wasRetry=!0),P});a[y].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||Y.length,questions:Y})}ee(s,a),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let a of c)delete i[a];ee(t,i),console.log(` Phase 3: Removed ${c.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 ne={};B(ne,{NAME:()=>Io,VERSION:()=>Ro,up:()=>No});import*as A from"fs";import*as je from"path";var Ro=2,Io="reset-unread-flags";function To(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Do(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{A.writeFileSync(t,o)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}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 No(e){let n=je.join(e,"conversations.json"),o=To(n);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Do(n,o),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var te={};B(te,{NAME:()=>_o,VERSION:()=>Co,up:()=>Po});import*as k from"fs";import*as Ee from"path";var Co=3,_o="recompute-last-message-by",xo=new Set(["draft","confirmed","rejected","needs_review"]);function Fo(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Lo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{k.writeFileSync(t,o)}catch(s){try{k.unlinkSync(t)}catch{}throw s}try{k.renameSync(t,e)}catch(s){try{k.unlinkSync(t)}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}}function Mo(e,n){if(!e||e.length===0)return"them";let o=e.filter(r=>!xo.has(r.status));if(o.length===0)return"them";let t=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=t.length>0?t:[...o].reverse();for(let r of s){let i=r.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Po(e){let n=Ee.join(e,"conversations.json"),o=Fo(n);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let u of Object.keys(o)){let c=o[u];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let f=Array.isArray(c.messages)?c.messages:[],a=Mo(f,t),m=a==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==a&&i++,c.lastMessageBy=a,c.conversationStatus=m,s++}if(s===0){console.log(" No conversations to recompute.");return}Lo(n,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var se={};B(se,{NAME:()=>Uo,VERSION:()=>Jo,up:()=>Wo});import*as j from"fs";import*as Oe from"path";var Jo=4,Uo="split-connection-timestamps",qo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Bo(e){if(!j.existsSync(e))return null;let n=j.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Vo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{j.writeFileSync(t,o)}catch(s){try{j.unlinkSync(t)}catch{}throw s}try{j.renameSync(t,e)}catch(s){try{j.unlinkSync(t)}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 Wo(e){let n=Oe.join(e,"people.json"),o=Bo(n);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,qo.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Vo(n,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var Yo=Go(import.meta.url),Ho=d.dirname(Yo),Ko=d.dirname(d.dirname(Ho));function Qo(e){return e&&(e==="~"?ie.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ie.homedir(),e.slice(2)):e)}var O=process.env.DATA_DIR?d.resolve(Qo(process.env.DATA_DIR)):Ko,F=d.join(O,"collected-profiles"),L=d.join(O,"market-research"),S=d.join(O,".schema-version"),Re=[d.join(F,".schema-version"),d.join(L,".schema-version")],D=4,I=[{version:1,module:oe},{version:2,module:ne},{version:3,module:te},{version:4,module:se}];(function(){I.sort((t,s)=>t.version-s.version);let n=new Set;for(let t of I){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(n.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);n.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=I.length?I[I.length-1].version:0;if(o!==D)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${D}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<I.length;t++){let s=t+1;if(I[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${I[t].version}`)}})();function Ne(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
8
+ `)}`;try{await ve.addMessage(i,c)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var vo=bo(import.meta.url),wo=T.dirname(T.dirname(vo)),Q=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(wo,"collected-profiles"),z=T.join(Q,"run-log.json");function $o(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";w.writeFileSync(t,o);for(let s=0;s<3;s++)try{w.renameSync(t,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 $e(){try{if(!w.existsSync(z))return{runs:[]};let e=JSON.parse(w.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ae(e){w.existsSync(Q)||w.mkdirSync(Q,{recursive:!0});try{$o(z,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function ke(e,n="default"){let o=$e();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 t=new Date,s={timestamp:t.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),Ae(o),{script:e,mode:n,startTime:t.getTime(),runIndex:o.runs.length-1}}function X(e,n,o=null,t=null){if(!e)return;let s=null;try{let i=$e(),u=i.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=n,u.result=n,u.duration=Date.now()-e.startTime,u.stats=o,u.error=t,s=u.duration;else{let c=i.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());c&&(c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=o,c.error=t,s=c.duration)}Ae(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=n==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";we({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:t,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}import"dotenv/config";import*as l from"fs";import*as ie from"os";import*as d from"path";import{fileURLToPath as Go}from"url";var oe={};B(oe,{NAME:()=>ko,VERSION:()=>Ao,up:()=>Eo});import*as $ from"fs";import*as V from"path";var Ao=1,ko="normalize-jobs-and-questions",jo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Oo=50;function Z(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function ee(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{$.writeFileSync(t,o)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}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 Eo(e,n){let o=V.join(e,"jobs.json"),t=V.join(n,"scouted-jobs.json"),s=V.join(e,"application-questions.json"),r=Z(o)||{},i=Z(t)||{},u=0,c=[];for(let a of Object.keys(r)){if(!i[a])continue;let m=i[a],p=r[a];for(let y of jo)m[y]!=null&&p[y]==null&&(p[y]=m[y]);c.push(a),u++}u>0?(ee(o,r),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Z(s);if(f&&Array.isArray(f.applications)){let a={},m=0;for(let p of f.applications){let y=p.jobId||"unknown";a[y]||(a[y]={applications:[]});let Y=(p.questions||[]).map(O=>{let P={type:O.type||"input",question:O.question||"",answer:O.answer||""};return O.options&&(O.options.length<=Oo?P.options=O.options:(P.optionsOmitted=!0,m++)),O.page&&(P.page=O.page),O.wasPreFilled&&(P.wasPreFilled=!0),O.wasRetry&&(P.wasRetry=!0),P});a[y].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||Y.length,questions:Y})}ee(s,a),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let a of c)delete i[a];ee(t,i),console.log(` Phase 3: Removed ${c.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 ne={};B(ne,{NAME:()=>Ro,VERSION:()=>Io,up:()=>No});import*as A from"fs";import*as je from"path";var Io=2,Ro="reset-unread-flags";function To(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Do(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{A.writeFileSync(t,o)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}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 No(e){let n=je.join(e,"conversations.json"),o=To(n);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Do(n,o),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var te={};B(te,{NAME:()=>_o,VERSION:()=>Co,up:()=>Po});import*as k from"fs";import*as Oe from"path";var Co=3,_o="recompute-last-message-by",xo=new Set(["draft","confirmed","rejected","needs_review"]);function Fo(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Lo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{k.writeFileSync(t,o)}catch(s){try{k.unlinkSync(t)}catch{}throw s}try{k.renameSync(t,e)}catch(s){try{k.unlinkSync(t)}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}}function Mo(e,n){if(!e||e.length===0)return"them";let o=e.filter(r=>!xo.has(r.status));if(o.length===0)return"them";let t=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=t.length>0?t:[...o].reverse();for(let r of s){let i=r.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Po(e){let n=Oe.join(e,"conversations.json"),o=Fo(n);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let u of Object.keys(o)){let c=o[u];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let f=Array.isArray(c.messages)?c.messages:[],a=Mo(f,t),m=a==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==a&&i++,c.lastMessageBy=a,c.conversationStatus=m,s++}if(s===0){console.log(" No conversations to recompute.");return}Lo(n,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var se={};B(se,{NAME:()=>Uo,VERSION:()=>Jo,up:()=>Wo});import*as j from"fs";import*as Ee from"path";var Jo=4,Uo="split-connection-timestamps",qo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Bo(e){if(!j.existsSync(e))return null;let n=j.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Vo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{j.writeFileSync(t,o)}catch(s){try{j.unlinkSync(t)}catch{}throw s}try{j.renameSync(t,e)}catch(s){try{j.unlinkSync(t)}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 Wo(e){let n=Ee.join(e,"people.json"),o=Bo(n);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,qo.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Vo(n,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var Yo=Go(import.meta.url),Ho=d.dirname(Yo),Ko=d.dirname(d.dirname(Ho));function Qo(e){return e&&(e==="~"?ie.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ie.homedir(),e.slice(2)):e)}var E=process.env.DATA_DIR?d.resolve(Qo(process.env.DATA_DIR)):Ko,F=d.join(E,"collected-profiles"),L=d.join(E,"market-research"),S=d.join(E,".schema-version"),Ie=[d.join(F,".schema-version"),d.join(L,".schema-version")],D=4,R=[{version:1,module:oe},{version:2,module:ne},{version:3,module:te},{version:4,module:se}];(function(){R.sort((t,s)=>t.version-s.version);let n=new Set;for(let t of R){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(n.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);n.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=R.length?R[R.length-1].version:0;if(o!==D)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${D}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<R.length;t++){let s=t+1;if(R[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${R[t].version}`)}})();function Ne(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
9
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{l.mkdirSync(O,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
11
- [FATAL] Cannot create DATA_DIR (${O}): ${n.message}`),console.error(` Fix the path or permissions and try again.
12
- `),process.exit(1))}let e;try{e=l.statSync(O)}catch(n){console.error(`
13
- [FATAL] DATA_DIR (${O}) is not accessible: ${n.message}
10
+ `),process.exit(1));try{l.mkdirSync(E,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
11
+ [FATAL] Cannot create DATA_DIR (${E}): ${n.message}`),console.error(` Fix the path or permissions and try again.
12
+ `),process.exit(1))}let e;try{e=l.statSync(E)}catch(n){console.error(`
13
+ [FATAL] DATA_DIR (${E}) is not accessible: ${n.message}
14
14
  `),process.exit(1)}e.isDirectory()||(console.error(`
15
- [FATAL] DATA_DIR (${O}) 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.
15
+ [FATAL] DATA_DIR (${E}) 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
16
  `),process.exit(1));for(let n of[F,L]){let o;try{o=l.lstatSync(n)}catch(t){if(t.code==="ENOENT")continue;throw t}o.isSymbolicLink()&&(console.error(`
17
17
  [FATAL] Data subdirectory is a symbolic link: ${n}`),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 x=d.join(O,".migration-lock");function zo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return l.writeFileSync(x,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let n;try{n=JSON.parse(l.readFileSync(x,"utf-8"))}catch{n=null}if(n&&Number.isInteger(n.pid)){let t=!1;try{process.kill(n.pid,0),t=!0}catch(i){i.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(n.startedAt){let i=Date.parse(n.startedAt);Number.isNaN(i)||(r=Date.now()-i)}t&&r<s&&(console.error(`
18
+ `),process.exit(1))}}var x=d.join(E,".migration-lock");function zo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return l.writeFileSync(x,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let n;try{n=JSON.parse(l.readFileSync(x,"utf-8"))}catch{n=null}if(n&&Number.isInteger(n.pid)){let t=!1;try{process.kill(n.pid,0),t=!0}catch(i){i.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(n.startedAt){let i=Date.parse(n.startedAt);Number.isNaN(i)||(r=Date.now()-i)}t&&r<s&&(console.error(`
19
19
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${n.pid}`),console.error(` Started at: ${n.startedAt||"(unknown)"}`),console.error(` Lock file: ${x}
20
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)),t&&r>=s&&console.log(` Lock holder PID ${n.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${n?.pid??"?"} found \u2014 taking over.`);let o=x+".tmp";try{return l.writeFileSync(o,e),l.renameSync(o,x),!0}catch(t){try{l.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function ce(){try{if(JSON.parse(l.readFileSync(x,"utf-8")).pid!==process.pid)return;l.unlinkSync(x)}catch{}}var Ie=!1;function Xo(){if(Ie)return;Ie=!0;let e=()=>{try{ce()}catch{}process.exit(1)};for(let n of["SIGINT","SIGTERM","SIGHUP"])try{process.on(n,e)}catch{}}function Zo(){if(l.existsSync(S))return;let e=[],n=[];for(let r of Re)if(l.existsSync(r))try{e.push({file:r,schema:W(r)})}catch(i){n.push({file:r,err:i.message})}if(n.length>0){console.error(`
21
+ `),process.exit(1)),t&&r>=s&&console.log(` Lock holder PID ${n.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${n?.pid??"?"} found \u2014 taking over.`);let o=x+".tmp";try{return l.writeFileSync(o,e),l.renameSync(o,x),!0}catch(t){try{l.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function ce(){try{if(JSON.parse(l.readFileSync(x,"utf-8")).pid!==process.pid)return;l.unlinkSync(x)}catch{}}var Re=!1;function Xo(){if(Re)return;Re=!0;let e=()=>{try{ce()}catch{}process.exit(1)};for(let n of["SIGINT","SIGTERM","SIGHUP"])try{process.on(n,e)}catch{}}function Zo(){if(l.existsSync(S))return;let e=[],n=[];for(let r of Ie)if(l.existsSync(r))try{e.push({file:r,schema:W(r)})}catch(i){n.push({file:r,err:i.message})}if(n.length>0){console.error(`
22
22
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of n)console.error(` ${r.file}: ${r.err}`);console.error(`
23
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
24
  `),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
25
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 t=e[0].schema,s=S+".tmp";try{l.writeFileSync(s,JSON.stringify(t,null,2)),l.renameSync(s,S)}catch(r){try{l.unlinkSync(s)}catch{}throw r}for(let r of Re)if(l.existsSync(r))try{l.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${S}`)}function en(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=Number(e.version);return!Number.isFinite(n)||n<0||!Number.isInteger(n)?null:(e.version=n,Array.isArray(e.migrations)||(e.migrations=[]),e)}function W(e){let n=l.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Te(){if(Zo(),!l.existsSync(S))return{version:0,migrations:[]};let e;try{e=W(S)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
26
+ `),process.exit(1)}let t=e[0].schema,s=S+".tmp";try{l.writeFileSync(s,JSON.stringify(t,null,2)),l.renameSync(s,S)}catch(r){try{l.unlinkSync(s)}catch{}throw r}for(let r of Ie)if(l.existsSync(r))try{l.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${S}`)}function en(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=Number(e.version);return!Number.isFinite(n)||n<0||!Number.isInteger(n)?null:(e.version=n,Array.isArray(e.migrations)||(e.migrations=[]),e)}function W(e){let n=l.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Te(){if(Zo(),!l.existsSync(S))return{version:0,migrations:[]};let e;try{e=W(S)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
27
27
  [FATAL] ${S} is not valid JSON: ${o.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
28
  `),process.exit(1)}let n=en(e);return n===null&&(console.error(`
29
29
  [FATAL] ${S} 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.
@@ -34,7 +34,7 @@ ${t.join(`
34
34
  \u{1F4E6} Schema migration: v${n} \u2192 v${D}`);let o=ln();if(!o.ok){console.error(`
35
35
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
36
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 t=I.filter(s=>s.version>n);for(let s of t){console.log(`
37
+ `),process.exit(1)}let t=R.filter(s=>s.version>n);for(let s of t){console.log(`
38
38
  Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{De(F,s.version),De(L,s.version)}catch(c){console.error(`
39
39
  [FATAL] Pre-migration backup failed for ${r}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
40
40
  `),process.exit(1)}let u=s.module;try{await u.up(F,L)}catch(c){console.error(`
@@ -45,7 +45,7 @@ ${t.join(`
45
45
  [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${n}.`),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
46
  `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{fe()}catch{}try{he()}catch{}re=!0,ce(),console.log(`
47
47
  \u2713 Schema is now at v${D}
48
- `)}var nn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tn(e){let n=e.toLowerCase();return nn.some(o=>o.test(n))}var sn=6e4;function rn(){let e=Date.now(),n=[];for(let o of[O,F,L]){if(!l.existsSync(o))continue;let t;try{t=l.readdirSync(o)}catch{continue}for(let s of t){if(!tn(s))continue;let r=d.join(o,s);try{let i=l.statSync(r);if(!i.isFile()||e-i.mtimeMs<sn)continue;n.push({dir:o,file:s,fullPath:r})}catch{}}}return n}function cn({verbose:e=!1}={}){let n=rn();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let t of n)try{l.unlinkSync(t.fullPath),o++,e&&console.log(` Removed orphan: ${d.basename(t.dir)}/${t.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function ln(){let e=[];for(let n of[F,L]){if(!l.existsSync(n))continue;let o=l.readdirSync(n).filter(t=>{let s=t.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let t of o){let s=d.join(n,t);try{W(s)}catch(r){e.push({dir:d.basename(n),file:t,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function an(e){let n=[],o=[];for(let r of[F,L]){if(!l.existsSync(r))continue;let i=l.readdirSync(r).filter(u=>u.endsWith(e));for(let u of i){let c=d.join(r,u),f=u.slice(0,-e.length),a=d.join(r,f);try{f.toLowerCase().endsWith(".json")?W(c):l.accessSync(c,l.constants.R_OK),n.push({backupPath:c,originalPath:a,fileName:u,dir:r})}catch(m){o.push(`${d.basename(r)}/${u}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let t=0,s=[];for(let{backupPath:r,originalPath:i,fileName:u,dir:c}of n)try{xe(r,i),t++}catch(f){s.push(`${d.basename(c)}/${u}: ${f.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:t}:{ok:!0,restored:t}}function xe(e,n){let o=n+".tmp";try{l.copyFileSync(e,o),Ce(o)}catch(t){try{l.unlinkSync(o)}catch{}throw t}try{l.renameSync(o,n)}catch(t){try{l.unlinkSync(o)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let s=new Error(`File locked: ${n} (${t.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=t.code,s}throw t}}var pn=un(import.meta.url),dn=M.dirname(pn),le=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(dn,"collected-profiles");await _e();var ae=process.argv.slice(2),Fe=parseInt(ae.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),G=parseInt(ae.find(e=>e.startsWith("--min-score="))?.split("=")[1]||"50"),mn=ae.includes("--list");function hn(){let n=K(20,{easyApplyOnly:!0}).filter(o=>o.score>=G);if(console.log(`
48
+ `)}var nn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tn(e){let n=e.toLowerCase();return nn.some(o=>o.test(n))}var sn=6e4;function rn(){let e=Date.now(),n=[];for(let o of[E,F,L]){if(!l.existsSync(o))continue;let t;try{t=l.readdirSync(o)}catch{continue}for(let s of t){if(!tn(s))continue;let r=d.join(o,s);try{let i=l.statSync(r);if(!i.isFile()||e-i.mtimeMs<sn)continue;n.push({dir:o,file:s,fullPath:r})}catch{}}}return n}function cn({verbose:e=!1}={}){let n=rn();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let t of n)try{l.unlinkSync(t.fullPath),o++,e&&console.log(` Removed orphan: ${d.basename(t.dir)}/${t.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function ln(){let e=[];for(let n of[F,L]){if(!l.existsSync(n))continue;let o=l.readdirSync(n).filter(t=>{let s=t.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let t of o){let s=d.join(n,t);try{W(s)}catch(r){e.push({dir:d.basename(n),file:t,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function an(e){let n=[],o=[];for(let r of[F,L]){if(!l.existsSync(r))continue;let i=l.readdirSync(r).filter(u=>u.endsWith(e));for(let u of i){let c=d.join(r,u),f=u.slice(0,-e.length),a=d.join(r,f);try{f.toLowerCase().endsWith(".json")?W(c):l.accessSync(c,l.constants.R_OK),n.push({backupPath:c,originalPath:a,fileName:u,dir:r})}catch(m){o.push(`${d.basename(r)}/${u}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let t=0,s=[];for(let{backupPath:r,originalPath:i,fileName:u,dir:c}of n)try{xe(r,i),t++}catch(f){s.push(`${d.basename(c)}/${u}: ${f.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:t}:{ok:!0,restored:t}}function xe(e,n){let o=n+".tmp";try{l.copyFileSync(e,o),Ce(o)}catch(t){try{l.unlinkSync(o)}catch{}throw t}try{l.renameSync(o,n)}catch(t){try{l.unlinkSync(o)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let s=new Error(`File locked: ${n} (${t.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=t.code,s}throw t}}var pn=un(import.meta.url),dn=M.dirname(pn),le=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"collected-profiles"):M.join(dn,"collected-profiles");await _e();var ae=process.argv.slice(2),Fe=parseInt(ae.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),G=parseInt(ae.find(e=>e.startsWith("--min-score="))?.split("=")[1]||"50"),mn=ae.includes("--list");function hn(){let n=K(20,{easyApplyOnly:!0}).filter(o=>o.score>=G);if(console.log(`
49
49
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` APPLY QUEUE (${n.length} jobs, min score ${G})`),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"),n.length===0)console.log(" No jobs in queue. Run: npm run scout");else for(let o=0;o<n.length;o++){let{score:t,job:s,jobId:r}=n[o],i=(s.techStack||[]).slice(0,4).join(", ");console.log(` ${String(o+1).padStart(2)}. [${t}] ${(s.title||"?").slice(0,35)} @ ${(s.company||"?").slice(0,20)}`),console.log(` ${s.salary||"no salary"} | ${s.location||"?"} | ${i||"no tech"}`),console.log(` ${s.url}`)}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
50
50
  `)}async function gn(){if(console.log(`
51
51
  LinkedIn Apply Queue