ilml-plugin-linkedin 1.20.22 → 1.20.27

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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.20.27
4
+ - **Fixed: Easy Apply often failed at the final review step because Yes/No questions (work authorization, visa sponsorship, relocation, hybrid/on-site) weren't being answered.** LinkedIn switched these questions from its old custom controls to standard radio buttons, which the form-filler no longer recognised — so it left the required question blank, the form wouldn't submit, and the whole application was skipped. In recent runs this was failing a large share of applications. The filler now reads the standard radio layout — pulling the question text and the Yes/No choices — and selects the answer, so these applications go through. It still answers a question only when it can clearly read both the question and its options; otherwise it skips it exactly as before, so no application ever gets a guessed answer.
5
+ - The stuck-form log now captures the full field details (question, options, surrounding markup) so a future form change is faster to pin down.
6
+ - No schema change.
7
+
8
+ ## 1.20.26
9
+ - **Discovered people now use one consistent `title` field — and your existing pool is repaired on upgrade.** The discovery pool had drifted to two names for the same thing (the position line under a person's name): some records used `title`, others `headline`. Worse, the pre-1.20.25 side-panel bug had glued names to the badge + position ("Jane Doe· 3rd+Head of Talent…"). On upgrade a one-time migration cleans discovered-people.json: it de-glues the names and moves every `headline` into `title`, so each record carries a single, clean `title` (matching the rest of your contacts). Your data file is backed up automatically first, and the fix is safe to re-run. In practice this makes the accumulated pool searchable again — e.g. the investors you'd harvested but couldn't tell apart now show up by title. Going forward the harvest writes `title` directly.
10
+ - No data lost — a field is renamed/relocated, not dropped.
11
+
12
+ ## 1.20.25
13
+ - **Fixed: the "people also viewed / similar profiles" harvest was storing garbled names and no usable title.** LinkedIn changed the side-panel markup (and rebranded the block to "Explore Premium profiles"), which the old extractor no longer read correctly — it was saving entries like a name glued to the degree and headline ("Jane Doe· 3rd+Retail Sales Specialist…") with the actual title lost. The harvest now reads each card's real lines, so discovered people are stored with a **clean name and their real headline/title** — you can finally tell who they are (and it now also picks up the rebranded "Explore Premium profiles" block). Verified live. (Existing already-garbled entries are cleaned up separately.)
14
+ - No schema change.
15
+
16
+ ## 1.20.24
17
+ - **New: `search` — search LinkedIn people by any query and harvest whole result cards.** Point it at a people-search URL you copied (`--url="..."`) or give it keywords (`--keywords="investor VC pre-seed" --2nd`), and it pages through the results pulling each person's name, title, location and connection degree. By default it just SHOWS them, flagging who you already know — ✓connected, …pending, ⋯in-queue, ·known, +new. Add `--harvest` and it also saves each person into your contacts DB **with their title** (so they're no longer "unknown who") and drops the new, not-yet-connected ones into the connect queue as `queued` for your review — a targeted way to build a pipeline (e.g. investors) instead of relying on the recruiter-heavy discovery pool. It never sends: approving and sending stay with `connect approve` + `connect run`. `--dry-run` previews the writes; `--pages=N` caps how far it pages.
18
+ - **`apply` prints a fuller diagnostic when a form gets stuck.** When a job's form loops without progressing, the log now dumps the exact fields blocking it (labels, the raw option markup) so a recurring stuck-on-review can be pinned down and fixed. No behaviour change to applying.
19
+ - No schema change.
20
+
21
+ ## 1.20.23
22
+ - **Fixed: `apply-queue` did nothing — it couldn't start, and when forced it skipped every job as "no Easy Apply button".** Two bugs: (1) it launched the applier via a path that doesn't exist in the installed plugin, failing instantly with a "module not found" error; (2) its own pre-check for the Apply button used an outdated selector that never matches LinkedIn's current job page, so every job was wrongly skipped. `apply-queue` (and `apply --job-urls`) now start correctly and reuse the same proven Apply detection as the main apply flow — so they actually apply to your scored/queued jobs, and correctly mark ones that are expired or already applied.
23
+ - No schema change.
24
+
3
25
  ## 1.20.22
4
26
  - **Run reports now tell the truth when a command stops early instead of finishing.** If `connect` (or another step) is cut short — LinkedIn asked you to sign in again, the browser dropped mid-run, or it stopped itself after repeated failures — the report now reads "⚠ stopped — <reason>" instead of a misleading "✓ done". The counts were always accurate; now the status line is too.
5
27
  - **Fixed the inbox-sync report showing "0 cards scanned" and "0 new messages".** Those two figures were read from the wrong place and always came out zero — the sync itself worked correctly, only the summary under-reported. It now shows the real cards-scanned and new-message counts.
@@ -1,56 +1,56 @@
1
- var Ue=Object.defineProperty;var V=(e,n)=>{for(var o in n)Ue(e,o,{get:n[o],enumerable:!0})};import"dotenv/config";import*as D from"fs";import*as P from"path";import{fileURLToPath as yn}from"url";import{execFileSync as Sn}from"child_process";import{getPluginConfig as qe}from"@ilivemylife/graph-sdk";var Je={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},ue=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Be(e){return String(e??"").split(/[,\s|]+/).map(n=>n.trim()).filter(Boolean)}function fe(e=process.env){let n=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!n)return null;let o=new URLSearchParams;o.set("keywords",n);let t=(e.JOB_SEARCH_LOCATION||"").trim();t&&o.set("location",t);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&o.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&o.set("distance",String(s)),ue(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),ue(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let i=Be(e.JOB_SEARCH_COMPANY_IDS);i.length&&o.set("f_C",i.join(","));let u=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();u&&o.set("f_TPR",Je[u]||u),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+o.toString(),f=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return f&&(c+="&"+f),c}var Ve=await qe();for(let[e,n]of Object.entries(Ve))process.env[e]===void 0&&(process.env[e]=n);var pe=fe(process.env);pe&&(process.env.LINKEDIN_SEARCH_URL=pe);var jn=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),In=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),Tn=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.REJECTED,N.NEEDS_REVIEW]));import"dotenv/config";import*as g from"fs";import*as y from"path";import{fileURLToPath as We}from"url";var Ge=We(import.meta.url),He=y.dirname(y.dirname(Ge)),j=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(He,"collected-profiles"),Ye=y.join(j,"people.json"),xn=y.join(j,"jobs.json"),Fn=y.join(j,"quota.json"),Ln=y.join(j,"conversations.json"),Mn=y.join(j,"sync-state.json"),Pn=y.join(j,"application-questions.json"),Un=y.join(j,"profile-history"),de=(e,n)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:n},Jn=de(process.env.CONNECT_MAX_DAILY,20),Bn=de(process.env.CONNECT_MAX_WEEKLY,100),J=null,Ke=null,ze=null,Qe=null,Xe=null,Ze=null;function me(){J=null,Ke=null,ze=null,Qe=null,Xe=null,Ze=null}function eo(){g.existsSync(j)||g.mkdirSync(j,{recursive:!0})}function oo(e,n){if(!g.existsSync(e))return null;try{let o=JSON.parse(g.readFileSync(e,"utf-8"));try{g.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${n} is corrupted: ${o.message}`),console.error(` File: ${y.resolve(e)}`);let t=e+".backup";if(g.existsSync(t))try{let r=JSON.parse(g.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{g.copyFileSync(t,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function he(){return J||(eo(),J=oo(Ye,"people.json")||{},J)}import"dotenv/config";import*as w from"fs";import*as b from"path";import{fileURLToPath as no}from"url";var to=no(import.meta.url),ro=b.dirname(b.dirname(to)),x=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(ro,"market-research"),ge=b.join(x,"scouted-jobs.json"),zn=b.join(x,"discovered-people.json"),Qn=b.join(x,"visit-log.json"),Xn=b.join(x,"companies.json"),so=b.join(x,"job-decisions.json");function io(){w.existsSync(x)||w.mkdirSync(x,{recursive:!0})}function co(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";w.writeFileSync(t,o);for(let r=0;r<3;r++)try{w.renameSync(t,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ye(e){try{if(w.existsSync(e))return JSON.parse(w.readFileSync(e,"utf-8"))}catch{}return null}function Se(){B=null,q=null,lo=null,ao=null,uo=null}var B=null;function Y(){return B||(B=ye(ge)||{},B)}function be(e,n){if(!e)return;io();let o=Y(),t=new Date().toISOString().slice(0,10);if(o[e]){for(let[r,s]of Object.entries(n))s!=null&&(o[e][r]=s);o[e].lastSeen=t}else o[e]={...n,scoutedAt:t,lastSeen:t};try{co(ge,o)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}var q=null;function we(){return q||(q=ye(so)||{},q)}var lo=null;var ao=null;var uo=null;var fo=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"]),po=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),ve=["vancouver","british columbia"],mo=["canada","montreal","quebec","alberta","calgary","ottawa"],ho=["toronto","ontario"],go=["india","pakistan","nigeria","philippines"];function yo(e,n={}){let o=0,t=(e.techStack||[]).map(l=>l.toLowerCase()),r=0,s=0;for(let l of t)fo.has(l)&&r++,po.has(l)&&s++;if(o+=Math.min(r*6,24),o+=Math.min(s*3,6),e.salary){let l=So(e.salary);l&&(l>=15e4?o+=20:l>=12e4?o+=15:l>=1e5?o+=10:l>=8e4?o+=5:l>=100&&l<1e3?o+=15:l>=70&&l<1e3&&(o+=10))}let i=(e.location||"").toLowerCase(),u=/remote/i.test(i)||e.workplaceType==="remote";go.some(l=>i.includes(l))?o-=30:u&&/united states|usa|\bus\b/i.test(i)?o+=25:u&&ve.some(l=>i.includes(l))?o+=22:u?o+=20:ve.some(l=>i.includes(l))?o+=18:mo.some(l=>i.includes(l))?o+=10:ho.some(l=>i.includes(l))&&(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=Y(),r=he(),s=new Set,i=new Set;for(let[m,p]of Object.entries(r))p.connectionStatus==="connected"&&s.add(m);let u={connectedRecruiters:s,conversationRecruiters:i},c=we(),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 h=c[m];return!(h&&f.has(h.status))}).map(([m,p])=>({jobId:m,score:yo(p,u),job:p})).sort((m,p)=>{if(p.score!==m.score)return p.score-m.score;let h=m.job.scoutedAt||m.job.postedTime||"";return(p.job.scoutedAt||p.job.postedTime||"").localeCompare(h)}).slice(0,e)}function So(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 r=parseFloat(t.replace(/[^\d.]/g,""));return t.toLowerCase().includes("k")&&(r*=1e3),r}).filter(t=>t>0);return o.length>=2?(o[0]+o[1])/2:o.length===1?o[0]:null}import"dotenv/config";import*as v from"fs";import*as _ from"path";import{fileURLToPath as Ro}from"url";import"dotenv/config";import{createGraphClient as bo,resolveToken as wo}from"@ilivemylife/graph-sdk";import{config as vo}from"dotenv";vo();var ke=wo()||process.env.TOKEN;ke||(console.error(`
1
+ var We=Object.defineProperty;var q=(e,n)=>{for(var o in n)We(e,o,{get:n[o],enumerable:!0})};import"dotenv/config";import*as x from"fs";import*as N from"path";import{fileURLToPath as In}from"url";import{execFileSync as Tn}from"child_process";import{getPluginConfig as Ke}from"@ilivemylife/graph-sdk";var Ye={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},me=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function He(e){return String(e??"").split(/[,\s|]+/).map(n=>n.trim()).filter(Boolean)}function he(e=process.env){let n=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!n)return null;let o=new URLSearchParams;o.set("keywords",n);let t=(e.JOB_SEARCH_LOCATION||"").trim();t&&o.set("location",t);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&o.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&o.set("distance",String(s)),me(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),me(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let c=He(e.JOB_SEARCH_COMPANY_IDS);c.length&&o.set("f_C",c.join(","));let u=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();u&&o.set("f_TPR",Ye[u]||u),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let i="https://www.linkedin.com/jobs/search/?"+o.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(i+="&"+a),i}var ze=await Ke();for(let[e,n]of Object.entries(ze))process.env[e]===void 0&&(process.env[e]=n);var ge=he(process.env);ge&&(process.env.LINKEDIN_SEARCH_URL=ge);var Pn=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Un=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),Jn=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import"dotenv/config";import*as g from"fs";import*as y from"path";import{fileURLToPath as Qe}from"url";var Xe=Qe(import.meta.url),Ze=y.dirname(y.dirname(Xe)),I=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(Ze,"collected-profiles"),eo=y.join(I,"people.json"),Wn=y.join(I,"jobs.json"),Yn=y.join(I,"quota.json"),Hn=y.join(I,"conversations.json"),Kn=y.join(I,"sync-state.json"),zn=y.join(I,"application-questions.json"),Qn=y.join(I,"profile-history"),ye=(e,n)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:n},Xn=ye(process.env.CONNECT_MAX_DAILY,20),Zn=ye(process.env.CONNECT_MAX_WEEKLY,100),V=null,oo=null,no=null,to=null,ro=null,so=null;function Se(){V=null,oo=null,no=null,to=null,ro=null,so=null}function io(){g.existsSync(I)||g.mkdirSync(I,{recursive:!0})}function co(e,n){if(!g.existsSync(e))return null;try{let o=JSON.parse(g.readFileSync(e,"utf-8"));try{g.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${n} is corrupted: ${o.message}`),console.error(` File: ${y.resolve(e)}`);let t=e+".backup";if(g.existsSync(t))try{let r=JSON.parse(g.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{g.copyFileSync(t,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function be(){return V||(io(),V=co(eo,"people.json")||{},V)}import"dotenv/config";import*as w from"fs";import*as b from"path";import{fileURLToPath as lo}from"url";var ao=lo(import.meta.url),uo=b.dirname(b.dirname(ao)),L=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(uo,"market-research"),we=b.join(L,"scouted-jobs.json"),ct=b.join(L,"discovered-people.json"),lt=b.join(L,"visit-log.json"),at=b.join(L,"companies.json"),fo=b.join(L,"job-decisions.json");function po(){w.existsSync(L)||w.mkdirSync(L,{recursive:!0})}function mo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";w.writeFileSync(t,o);for(let r=0;r<3;r++)try{w.renameSync(t,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let c=Date.now();for(;Date.now()-c<200;);continue}throw s}}function ve(e){try{if(w.existsSync(e))return JSON.parse(w.readFileSync(e,"utf-8"))}catch{}return null}function ke(){G=null,W=null,ho=null,go=null,yo=null}var G=null;function Q(){return G||(G=ve(we)||{},G)}function Ae(e,n){if(!e)return;po();let o=Q(),t=new Date().toISOString().slice(0,10);if(o[e]){for(let[r,s]of Object.entries(n))s!=null&&(o[e][r]=s);o[e].lastSeen=t}else o[e]={...n,scoutedAt:t,lastSeen:t};try{mo(we,o)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}var W=null;function $e(){return W||(W=ve(fo)||{},W)}var ho=null;var go=null;var yo=null;var So=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"]),bo=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Ee=["vancouver","british columbia"],wo=["canada","montreal","quebec","alberta","calgary","ottawa"],vo=["toronto","ontario"],ko=["india","pakistan","nigeria","philippines"];function Ao(e,n={}){let o=0,t=(e.techStack||[]).map(l=>l.toLowerCase()),r=0,s=0;for(let l of t)So.has(l)&&r++,bo.has(l)&&s++;if(o+=Math.min(r*6,24),o+=Math.min(s*3,6),e.salary){let l=$o(e.salary);l&&(l>=15e4?o+=20:l>=12e4?o+=15:l>=1e5?o+=10:l>=8e4?o+=5:l>=100&&l<1e3?o+=15:l>=70&&l<1e3&&(o+=10))}let c=(e.location||"").toLowerCase(),u=/remote/i.test(c)||e.workplaceType==="remote";ko.some(l=>c.includes(l))?o-=30:u&&/united states|usa|\bus\b/i.test(c)?o+=25:u&&Ee.some(l=>c.includes(l))?o+=22:u?o+=20:Ee.some(l=>c.includes(l))?o+=18:wo.some(l=>c.includes(l))?o+=10:vo.some(l=>c.includes(l))&&(o+=5),e.isEasyApply&&(o+=5);let i=(e.seniority||"").toLowerCase();i.includes("senior")||i.includes("lead")||i.includes("staff")?o+=10:i.includes("mid")?o+=5:(i.includes("entry")||i.includes("intern"))&&(o-=10),e.recruiterUrl&&(n.conversationRecruiters?.has(e.recruiterUrl)?o+=20:n.connectedRecruiters?.has(e.recruiterUrl)?o+=15:o+=3);let a=new Set(e.jobTags||[]);return a.has("managerial")?o+=8:a.has("senior-ic")&&(o+=5),a.has("junior")&&(o-=15),a.has("consultant")&&(o-=3),Math.max(0,Math.min(100,o))}function X(e=10,n={}){let{easyApplyOnly:o=!0}=n,t=Q(),r=be(),s=new Set,c=new Set;for(let[m,p]of Object.entries(r))p.connectionStatus==="connected"&&s.add(m);let u={connectedRecruiters:s,conversationRecruiters:c},i=$e(),a=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 h=i[m];return!(h&&a.has(h.status))}).map(([m,p])=>({jobId:m,score:Ao(p,u),job:p})).sort((m,p)=>{if(p.score!==m.score)return p.score-m.score;let h=m.job.scoutedAt||m.job.postedTime||"";return(p.job.scoutedAt||p.job.postedTime||"").localeCompare(h)}).slice(0,e)}function $o(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 r=parseFloat(t.replace(/[^\d.]/g,""));return t.toLowerCase().includes("k")&&(r*=1e3),r}).filter(t=>t>0);return o.length>=2?(o[0]+o[1])/2:o.length===1?o[0]:null}import"dotenv/config";import*as v from"fs";import*as C from"path";import{fileURLToPath as Co}from"url";import"dotenv/config";import{createGraphClient as Eo,resolveToken as Oo}from"@ilivemylife/graph-sdk";import{config as jo}from"dotenv";jo();var Oe=Oo()||process.env.TOKEN;Oe||(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
- `),process.exit(1));var Ae=bo({token:ke});function ko(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`}var Ao={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function $o(e){let n=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(n)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(n)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(n)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(n)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(n)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Eo({scriptName:e,mode:n,status:o,summaryLines:t,error:r,stoppedReason:s,duration:i}){let u=o==="error"||o==="stopped"?o==="error"?"\u2717":"\u26A0":o==="quota-reached"?"\u26A0":"\u2713",c=o==="error"?"stopped early":o==="stopped"?`stopped \u2014 ${s||"did not finish"}`:o==="quota-reached"?"daily limit reached":"done",f=Ao[e]||e,l=n&&n!=="default"?` \xB7 ${n}`:"",m=new Date().toISOString().slice(0,16).replace("T"," "),p=i?` \xB7 ${ko(i)}`:"",h=[];h.push(`## ${u} ${f} \u2014 ${c}`),h.push(`_${m}${l}${p}_`),h.push("");for(let T of t)h.push(`- ${T}`);if(o==="error"){h.push(""),h.push(`**What happened:** ${$o(r)}`);let T=String(r||"").replace(/\s+/g," ").trim();T&&h.push(`_Technical detail: ${T.slice(0,140)}_`)}return h.join(`
6
- `)}async function $e({scriptName:e,mode:n,status:o,summaryLines:t,error:r,stoppedReason:s,duration:i}){let u=process.env.NODE_RUN_REPORTS;if(!u||!Array.isArray(t)||t.length===0)return;let c=Eo({scriptName:e,mode:n,status:o,summaryLines:t,error:r,stoppedReason:s,duration:i});try{await Ae.addMessage(u,c)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Oo=Ro(import.meta.url),jo=_.dirname(_.dirname(Oo)),z=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"collected-profiles"):_.join(jo,"collected-profiles"),Q=_.join(z,"run-log.json");function Io(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";v.writeFileSync(t,o);for(let r=0;r<3;r++)try{v.renameSync(t,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ee(){try{if(!v.existsSync(Q))return{runs:[]};let e=JSON.parse(v.readFileSync(Q,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Re(e){v.existsSync(z)||v.mkdirSync(z,{recursive:!0});try{Io(Q,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function Oe(e,n="default"){let o=Ee();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,r={timestamp:t.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>s),Re(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 r=null;try{let u=Ee(),c=u.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=o,c.error=t,r=c.duration;else{let f=u.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());f&&(f.status=n,f.result=n,f.duration=Date.now()-e.startTime,f.stats=o,f.error=t,r=f.duration)}Re(u)}catch(u){console.error(`[runLog] Failed to end run: ${u.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null,i=o&&o.__deferReport===!0;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS&&!i){let u=n==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";$e({scriptName:e.script,mode:e.mode,status:u,summaryLines:s,error:t,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ie from"os";import*as d from"path";import{fileURLToPath as Zo}from"url";var oe={};V(oe,{NAME:()=>_o,VERSION:()=>To,up:()=>No});import*as k from"fs";import*as W from"path";var To=1,_o="normalize-jobs-and-questions",Co=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Do=50;function Z(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function ee(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{k.writeFileSync(t,o)}catch(r){try{k.unlinkSync(t)}catch{}throw r}try{k.renameSync(t,e)}catch(r){try{k.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function No(e,n){let o=W.join(e,"jobs.json"),t=W.join(n,"scouted-jobs.json"),r=W.join(e,"application-questions.json"),s=Z(o)||{},i=Z(t)||{},u=0,c=[];for(let l of Object.keys(s)){if(!i[l])continue;let m=i[l],p=s[l];for(let h of Co)m[h]!=null&&p[h]==null&&(p[h]=m[h]);c.push(l),u++}u>0?(ee(o,s),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Z(r);if(f&&Array.isArray(f.applications)){let l={},m=0;for(let p of f.applications){let h=p.jobId||"unknown";l[h]||(l[h]={applications:[]});let T=(p.questions||[]).map(R=>{let U={type:R.type||"input",question:R.question||"",answer:R.answer||""};return R.options&&(R.options.length<=Do?U.options=R.options:(U.optionsOmitted=!0,m++)),R.page&&(U.page=R.page),R.wasPreFilled&&(U.wasPreFilled=!0),R.wasRetry&&(U.wasRetry=!0),U});l[h].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||T.length,questions:T})}ee(r,l),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(l).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 l of c)delete i[l];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={};V(ne,{NAME:()=>Fo,VERSION:()=>xo,up:()=>Po});import*as A from"fs";import*as je from"path";var xo=2,Fo="reset-unread-flags";function Lo(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Mo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{A.writeFileSync(t,o)}catch(r){try{A.unlinkSync(t)}catch{}throw r}try{A.renameSync(t,e)}catch(r){try{A.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Po(e){let n=je.join(e,"conversations.json"),o=Lo(n);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Mo(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={};V(te,{NAME:()=>Jo,VERSION:()=>Uo,up:()=>Go});import*as $ from"fs";import*as Ie from"path";var Uo=3,Jo="recompute-last-message-by",Bo=new Set(["draft","confirmed","rejected","needs_review"]);function qo(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Vo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{$.writeFileSync(t,o)}catch(r){try{$.unlinkSync(t)}catch{}throw r}try{$.renameSync(t,e)}catch(r){try{$.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Wo(e,n){if(!e||e.length===0)return"them";let o=e.filter(s=>!Bo.has(s.status));if(o.length===0)return"them";let t=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=t.length>0?t:[...o].reverse();for(let s of r){let i=s.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Go(e){let n=Ie.join(e,"conversations.json"),o=qo(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 r=0,s=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,s++);let f=Array.isArray(c.messages)?c.messages:[],l=Wo(f,t),m=l==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==l&&i++,c.lastMessageBy=l,c.conversationStatus=m,r++}if(r===0){console.log(" No conversations to recompute.");return}Vo(n,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var re={};V(re,{NAME:()=>Yo,VERSION:()=>Ho,up:()=>Xo});import*as E from"fs";import*as Te from"path";var Ho=4,Yo="split-connection-timestamps",Ko=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function zo(e){if(!E.existsSync(e))return null;let n=E.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Qo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{E.writeFileSync(t,o)}catch(r){try{E.unlinkSync(t)}catch{}throw r}try{E.renameSync(t,e)}catch(r){try{E.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Xo(e){let n=Te.join(e,"people.json"),o=zo(n);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,r=0;for(let s of Object.keys(o)){let i=o[s];!i||typeof i!="object"||(r++,Ko.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Qo(n,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var en=Zo(import.meta.url),on=d.dirname(en),nn=d.dirname(d.dirname(on));function tn(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(tn(process.env.DATA_DIR)):nn,L=d.join(O,"collected-profiles"),M=d.join(O,"market-research"),S=d.join(O,".schema-version"),_e=[d.join(L,".schema-version"),d.join(M,".schema-version")],C=4,I=[{version:1,module:oe},{version:2,module:ne},{version:3,module:te},{version:4,module:re}];(function(){I.sort((t,r)=>t.version-r.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 r=t.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=I.length?I[I.length-1].version:0;if(o!==C)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${C}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<I.length;t++){let r=t+1;if(I[t].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${t} but found v${I[t].version}`)}})();function xe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
5
+ `),process.exit(1));var je=Eo({token:Oe});function Ro(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`}var Io={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function To(e){let n=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(n)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(n)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(n)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(n)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(n)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function _o({scriptName:e,mode:n,status:o,summaryLines:t,error:r,stoppedReason:s,duration:c}){let u=o==="error"||o==="stopped"?o==="error"?"\u2717":"\u26A0":o==="quota-reached"?"\u26A0":"\u2713",i=o==="error"?"stopped early":o==="stopped"?`stopped \u2014 ${s||"did not finish"}`:o==="quota-reached"?"daily limit reached":"done",a=Io[e]||e,l=n&&n!=="default"?` \xB7 ${n}`:"",m=new Date().toISOString().slice(0,16).replace("T"," "),p=c?` \xB7 ${Ro(c)}`:"",h=[];h.push(`## ${u} ${a} \u2014 ${i}`),h.push(`_${m}${l}${p}_`),h.push("");for(let _ of t)h.push(`- ${_}`);if(o==="error"){h.push(""),h.push(`**What happened:** ${To(r)}`);let _=String(r||"").replace(/\s+/g," ").trim();_&&h.push(`_Technical detail: ${_.slice(0,140)}_`)}return h.join(`
6
+ `)}async function Re({scriptName:e,mode:n,status:o,summaryLines:t,error:r,stoppedReason:s,duration:c}){let u=process.env.NODE_RUN_REPORTS;if(!u||!Array.isArray(t)||t.length===0)return;let i=_o({scriptName:e,mode:n,status:o,summaryLines:t,error:r,stoppedReason:s,duration:c});try{await je.addMessage(u,i)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Do=Co(import.meta.url),No=C.dirname(C.dirname(Do)),Z=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"collected-profiles"):C.join(No,"collected-profiles"),ee=C.join(Z,"run-log.json");function xo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";v.writeFileSync(t,o);for(let r=0;r<3;r++)try{v.renameSync(t,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let c=Date.now();for(;Date.now()-c<200;);continue}throw s}}function Ie(){try{if(!v.existsSync(ee))return{runs:[]};let e=JSON.parse(v.readFileSync(ee,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Te(e){v.existsSync(Z)||v.mkdirSync(Z,{recursive:!0});try{xo(ee,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function _e(e,n="default"){let o=Ie();for(let c of o.runs)c.status==="running"&&(c.status="interrupted",c.result="interrupted",c.timestamp&&(c.duration=Date.now()-new Date(c.timestamp).getTime()));let t=new Date,r={timestamp:t.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(c=>new Date(c.timestamp).getTime()>s),Te(o),{script:e,mode:n,startTime:t.getTime(),runIndex:o.runs.length-1}}function oe(e,n,o=null,t=null){if(!e)return;let r=null;try{let u=Ie(),i=u.runs[e.runIndex];if(i&&i.status==="running"&&i.script===e.script)i.status=n,i.result=n,i.duration=Date.now()-e.startTime,i.stats=o,i.error=t,r=i.duration;else{let a=u.runs.find(l=>l.script===e.script&&l.status==="running"&&l.timestamp===new Date(e.startTime).toISOString());a&&(a.status=n,a.result=n,a.duration=Date.now()-e.startTime,a.stats=o,a.error=t,r=a.duration)}Te(u)}catch(u){console.error(`[runLog] Failed to end run: ${u.message}`)}let s=o&&Array.isArray(o.summaryLines)?o.summaryLines:null,c=o&&o.__deferReport===!0;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS&&!c){let u=n==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Re({scriptName:e.script,mode:e.mode,status:u,summaryLines:s,error:t,duration:r??Date.now()-e.startTime}).catch(i=>console.error(`[runLog] postRunReport failed: ${i.message}`))}}import"dotenv/config";import*as f from"fs";import*as ue from"os";import*as d from"path";import{fileURLToPath as pn}from"url";var re={};q(re,{NAME:()=>Lo,VERSION:()=>Fo,up:()=>Uo});import*as k from"fs";import*as H from"path";var Fo=1,Lo="normalize-jobs-and-questions",Mo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Po=50;function ne(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function te(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{k.writeFileSync(t,o)}catch(r){try{k.unlinkSync(t)}catch{}throw r}try{k.renameSync(t,e)}catch(r){try{k.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Uo(e,n){let o=H.join(e,"jobs.json"),t=H.join(n,"scouted-jobs.json"),r=H.join(e,"application-questions.json"),s=ne(o)||{},c=ne(t)||{},u=0,i=[];for(let l of Object.keys(s)){if(!c[l])continue;let m=c[l],p=s[l];for(let h of Mo)m[h]!=null&&p[h]==null&&(p[h]=m[h]);i.push(l),u++}u>0?(te(o,s),console.log(` Phase 1: Merged ${u} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ne(r);if(a&&Array.isArray(a.applications)){let l={},m=0;for(let p of a.applications){let h=p.jobId||"unknown";l[h]||(l[h]={applications:[]});let _=(p.questions||[]).map(j=>{let B={type:j.type||"input",question:j.question||"",answer:j.answer||""};return j.options&&(j.options.length<=Po?B.options=j.options:(B.optionsOmitted=!0,m++)),j.page&&(B.page=j.page),j.wasPreFilled&&(B.wasPreFilled=!0),j.wasRetry&&(B.wasRetry=!0),B});l[h].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||_.length,questions:_})}te(r,l),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(l).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(i.length>0){for(let l of i)delete c[l];te(t,c),console.log(` Phase 3: Removed ${i.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var se={};q(se,{NAME:()=>Bo,VERSION:()=>Jo,up:()=>Go});import*as A from"fs";import*as Ce from"path";var Jo=2,Bo="reset-unread-flags";function qo(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Vo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{A.writeFileSync(t,o)}catch(r){try{A.unlinkSync(t)}catch{}throw r}try{A.renameSync(t,e)}catch(r){try{A.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Go(e){let n=Ce.join(e,"conversations.json"),o=qo(n);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Vo(n,o),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ie={};q(ie,{NAME:()=>Yo,VERSION:()=>Wo,up:()=>Xo});import*as $ from"fs";import*as De from"path";var Wo=3,Yo="recompute-last-message-by",Ho=new Set(["draft","confirmed","rejected","needs_review"]);function Ko(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function zo(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{$.writeFileSync(t,o)}catch(r){try{$.unlinkSync(t)}catch{}throw r}try{$.renameSync(t,e)}catch(r){try{$.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Qo(e,n){if(!e||e.length===0)return"them";let o=e.filter(s=>!Ho.has(s.status));if(o.length===0)return"them";let t=o.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,c)=>c.t-s.t).map(s=>s.m),r=t.length>0?t:[...o].reverse();for(let s of r){let c=s.sender;if(c===n)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function Xo(e){let n=De.join(e,"conversations.json"),o=Ko(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 r=0,s=0,c=0;for(let u of Object.keys(o)){let i=o[u];if(!i||typeof i!="object")continue;Object.prototype.hasOwnProperty.call(i,"_cardSynced")&&(delete i._cardSynced,s++);let a=Array.isArray(i.messages)?i.messages:[],l=Qo(a,t),m=l==="me"?"awaiting_reply":"unanswered_by_us";i.lastMessageBy!==l&&c++,i.lastMessageBy=l,i.conversationStatus=m,r++}if(r===0){console.log(" No conversations to recompute.");return}zo(n,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${c} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ce={};q(ce,{NAME:()=>en,VERSION:()=>Zo,up:()=>rn});import*as E from"fs";import*as Ne from"path";var Zo=4,en="split-connection-timestamps",on=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function nn(e){if(!E.existsSync(e))return null;let n=E.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function tn(e,n){let o=JSON.stringify(n,null,2),t=e+".tmp";try{E.writeFileSync(t,o)}catch(r){try{E.unlinkSync(t)}catch{}throw r}try{E.renameSync(t,e)}catch(r){try{E.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function rn(e){let n=Ne.join(e,"people.json"),o=nn(n);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,r=0;for(let s of Object.keys(o)){let c=o[s];!c||typeof c!="object"||(r++,on.has(c.connectionStatus)&&c.connectionDate&&!c.requestedConnectionAt&&(c.requestedConnectionAt=c.connectionDate,c.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}tn(n,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var le={};q(le,{NAME:()=>cn,VERSION:()=>sn,up:()=>fn});import*as O from"fs";import*as xe from"path";var sn=5,cn="rename-headline-to-title",M=/[·•]\s*(1st|2nd|3rd)\+?/i,ln=e=>(e||"").replace(/\s+/g," ").trim(),Y=e=>ln(e).replace(/^[+·•\s]+/,"").replace(/[·•\s]+$/,"");function an(e){if(!O.existsSync(e))return null;let n=O.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function un(e,n){let o=JSON.stringify(n),t=e+".tmp";try{O.writeFileSync(t,o)}catch(r){try{O.unlinkSync(t)}catch{}throw r}try{O.renameSync(t,e)}catch(r){try{O.unlinkSync(t)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function fn(e,n){let o=xe.join(n,"discovered-people.json"),t=an(o);if(!t||typeof t!="object"){console.log(" discovered-people.json not found \u2014 nothing to migrate.");return}let r=Array.isArray(t)?t:Object.values(t),s=0,c=0,u=0;for(let i of r)if(!(!i||typeof i!="object")){if(s++,i.name&&M.test(i.name)){let a=Y(String(i.name).split(M)[0]),l=String(i.name).match(/[·•]\s*(?:1st|2nd|3rd)\+?\s*(.+)$/i),m=l?Y(l[1]):"";a&&(i.name=a,c++),m&&(!i.headline||M.test(String(i.headline))||!Y(i.headline))&&(i.headline=m)}if(Object.prototype.hasOwnProperty.call(i,"headline")){let a=Y(i.headline||"");M.test(a)&&(a=""),(!i.title||M.test(String(i.title)))&&(i.title=a||(i.title&&!M.test(String(i.title))?i.title:null)||null),delete i.headline,u++}else if(typeof i.title=="string"){let a=Y(i.title);a&&!M.test(a)&&a!==i.title&&(i.title=a)}}if(u===0&&c===0){console.log(` Scanned ${s} discovered people \u2014 already unified (no headline field, clean names).`);return}un(o,t),console.log(` discovered-people.json: scanned ${s}, de-glued ${c} names, moved ${u} headline\u2192title.`),console.log(" Every record now carries a single `title` field (matches people.json).")}var dn=pn(import.meta.url),mn=d.dirname(dn),hn=d.dirname(d.dirname(mn));function gn(e){return e&&(e==="~"?ue.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ue.homedir(),e.slice(2)):e)}var R=process.env.DATA_DIR?d.resolve(gn(process.env.DATA_DIR)):hn,U=d.join(R,"collected-profiles"),J=d.join(R,"market-research"),S=d.join(R,".schema-version"),Fe=[d.join(U,".schema-version"),d.join(J,".schema-version")],D=5,T=[{version:1,module:re},{version:2,module:se},{version:3,module:ie},{version:4,module:ce},{version:5,module:le}];(function(){T.sort((t,r)=>t.version-r.version);let n=new Set;for(let t of T){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 r=t.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=T.length?T[T.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<T.length;t++){let r=t+1;if(T[t].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${t} but found v${T[t].version}`)}})();function Ue(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
7
7
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
8
- `),process.exit(1));try{a.mkdirSync(O,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
9
- [FATAL] Cannot create DATA_DIR (${O}): ${n.message}`),console.error(` Fix the path or permissions and try again.
10
- `),process.exit(1))}let e;try{e=a.statSync(O)}catch(n){console.error(`
11
- [FATAL] DATA_DIR (${O}) is not accessible: ${n.message}
8
+ `),process.exit(1));try{f.mkdirSync(R,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
9
+ [FATAL] Cannot create DATA_DIR (${R}): ${n.message}`),console.error(` Fix the path or permissions and try again.
10
+ `),process.exit(1))}let e;try{e=f.statSync(R)}catch(n){console.error(`
11
+ [FATAL] DATA_DIR (${R}) is not accessible: ${n.message}
12
12
  `),process.exit(1)}e.isDirectory()||(console.error(`
13
- [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.
14
- `),process.exit(1));for(let n of[L,M]){let o;try{o=a.lstatSync(n)}catch(t){if(t.code==="ENOENT")continue;throw t}o.isSymbolicLink()&&(console.error(`
13
+ [FATAL] DATA_DIR (${R}) 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.
14
+ `),process.exit(1));for(let n of[U,J]){let o;try{o=f.lstatSync(n)}catch(t){if(t.code==="ENOENT")continue;throw t}o.isSymbolicLink()&&(console.error(`
15
15
  [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.
16
- `),process.exit(1))}}var F=d.join(O,".migration-lock");function rn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(F,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let n;try{n=JSON.parse(a.readFileSync(F,"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 r=24*60*60*1e3,s=1/0;if(n.startedAt){let i=Date.parse(n.startedAt);Number.isNaN(i)||(s=Date.now()-i)}t&&s<r&&(console.error(`
17
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${n.pid}`),console.error(` Started at: ${n.startedAt||"(unknown)"}`),console.error(` Lock file: ${F}
16
+ `),process.exit(1))}}var P=d.join(R,".migration-lock");function yn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return f.writeFileSync(P,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let n;try{n=JSON.parse(f.readFileSync(P,"utf-8"))}catch{n=null}if(n&&Number.isInteger(n.pid)){let t=!1;try{process.kill(n.pid,0),t=!0}catch(c){c.code==="EPERM"&&(t=!0)}let r=24*60*60*1e3,s=1/0;if(n.startedAt){let c=Date.parse(n.startedAt);Number.isNaN(c)||(s=Date.now()-c)}t&&s<r&&(console.error(`
17
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${n.pid}`),console.error(` Started at: ${n.startedAt||"(unknown)"}`),console.error(` Lock file: ${P}
18
18
  `),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.
19
- `),process.exit(1)),t&&s>=r&&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=F+".tmp";try{return a.writeFileSync(o,e),a.renameSync(o,F),!0}catch(t){try{a.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function ce(){try{if(JSON.parse(a.readFileSync(F,"utf-8")).pid!==process.pid)return;a.unlinkSync(F)}catch{}}var Ce=!1;function sn(){if(Ce)return;Ce=!0;let e=()=>{try{ce()}catch{}process.exit(1)};for(let n of["SIGINT","SIGTERM","SIGHUP"])try{process.on(n,e)}catch{}}function cn(){if(a.existsSync(S))return;let e=[],n=[];for(let s of _e)if(a.existsSync(s))try{e.push({file:s,schema:G(s)})}catch(i){n.push({file:s,err:i.message})}if(n.length>0){console.error(`
19
+ `),process.exit(1)),t&&s>=r&&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=P+".tmp";try{return f.writeFileSync(o,e),f.renameSync(o,P),!0}catch(t){try{f.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function fe(){try{if(JSON.parse(f.readFileSync(P,"utf-8")).pid!==process.pid)return;f.unlinkSync(P)}catch{}}var Le=!1;function Sn(){if(Le)return;Le=!0;let e=()=>{try{fe()}catch{}process.exit(1)};for(let n of["SIGINT","SIGTERM","SIGHUP"])try{process.on(n,e)}catch{}}function bn(){if(f.existsSync(S))return;let e=[],n=[];for(let s of Fe)if(f.existsSync(s))try{e.push({file:s,schema:K(s)})}catch(c){n.push({file:s,err:c.message})}if(n.length>0){console.error(`
20
20
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of n)console.error(` ${s.file}: ${s.err}`);console.error(`
21
21
  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.
22
22
  `),process.exit(1)}if(e.length===0)return;let o=e.map(s=>s.schema.version);if(new Set(o).size>1){console.error(`
23
23
  [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.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.
24
- `),process.exit(1)}let t=e[0].schema,r=S+".tmp";try{a.writeFileSync(r,JSON.stringify(t,null,2)),a.renameSync(r,S)}catch(s){try{a.unlinkSync(r)}catch{}throw s}for(let s of _e)if(a.existsSync(s))try{a.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${S}`)}function ln(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 G(e){let n=a.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function De(){if(cn(),!a.existsSync(S))return{version:0,migrations:[]};let e;try{e=G(S)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
24
+ `),process.exit(1)}let t=e[0].schema,r=S+".tmp";try{f.writeFileSync(r,JSON.stringify(t,null,2)),f.renameSync(r,S)}catch(s){try{f.unlinkSync(r)}catch{}throw s}for(let s of Fe)if(f.existsSync(s))try{f.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${S}`)}function wn(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 K(e){let n=f.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function Me(){if(bn(),!f.existsSync(S))return{version:0,migrations:[]};let e;try{e=K(S)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
25
25
  [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.
26
- `),process.exit(1)}let n=ln(e);return n===null&&(console.error(`
26
+ `),process.exit(1)}let n=wn(e);return n===null&&(console.error(`
27
27
  [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.
28
- `),process.exit(1)),n}function Fe(e){try{a.chmodSync(e,384)}catch{}}function an(e){if(xe(),a.existsSync(S))try{if(a.lstatSync(S).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${S}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let n=S+".tmp";try{a.writeFileSync(n,JSON.stringify(e,null,2)),Fe(n),a.renameSync(n,S)}catch(o){try{a.unlinkSync(n)}catch{}throw o}}function Ne(e,n){if(!a.existsSync(e))return;let o=`.pre-v${String(n).padStart(3,"0")}.backup`,t=a.readdirSync(e).filter(u=>{let c=u.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,u)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let u of t){let c=d.join(e,u),f=d.join(e,u+o);if(a.existsSync(f)){s++;continue}try{Me(c,f),r++}catch(l){i.push({file:u,err:l.message})}}if(i.length>0){let u=new Error(`Failed to back up ${i.length} file(s) in ${d.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||s>0){let u=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${d.basename(e)}/ (${o})${u}`)}}var se=!1;async function Le(){if(se)return;xe(),mn();let n=De().version;if(n===C){se=!0;return}sn(),rn(),process.on("exit",ce),n>C&&(console.error(`
29
- [FATAL] Your data schema is at v${n}, but this plugin build only understands up to v${C}.`),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.
30
- `),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${C}.
28
+ `),process.exit(1)),n}function Je(e){try{f.chmodSync(e,384)}catch{}}function vn(e){if(Ue(),f.existsSync(S))try{if(f.lstatSync(S).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${S}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let n=S+".tmp";try{f.writeFileSync(n,JSON.stringify(e,null,2)),Je(n),f.renameSync(n,S)}catch(o){try{f.unlinkSync(n)}catch{}throw o}}function Pe(e,n){if(!f.existsSync(e))return;let o=`.pre-v${String(n).padStart(3,"0")}.backup`,t=f.readdirSync(e).filter(u=>{let i=u.toLowerCase();if(i.includes(".backup")||i===".schema-version"||i.endsWith(".tmp"))return!1;try{return f.statSync(d.join(e,u)).isFile()}catch{return!1}}),r=0,s=0,c=[];for(let u of t){let i=d.join(e,u),a=d.join(e,u+o);if(f.existsSync(a)){s++;continue}try{qe(i,a),r++}catch(l){c.push({file:u,err:l.message})}}if(c.length>0){let u=new Error(`Failed to back up ${c.length} file(s) in ${d.basename(e)}/: `+c.map(i=>`${i.file} (${i.err})`).join(", "));throw u.code="BACKUP_INCOMPLETE",u}if(r>0||s>0){let u=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${d.basename(e)}/ (${o})${u}`)}}var ae=!1;async function Be(){if(ae)return;Ue(),On();let n=Me().version;if(n===D){ae=!0;return}Sn(),yn(),process.on("exit",fe),n>D&&(console.error(`
29
+ [FATAL] Your data schema is at v${n}, but this plugin build only understands up to v${D}.`),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.
30
+ `),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${D}.
31
31
  `),process.exit(1)),console.log(`
32
- \u{1F4E6} Schema migration: v${n} \u2192 v${C}`);let o=hn();if(!o.ok){console.error(`
32
+ \u{1F4E6} Schema migration: v${n} \u2192 v${D}`);let o=jn();if(!o.ok){console.error(`
33
33
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of o.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
34
34
  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'.
35
- `),process.exit(1)}let t=I.filter(r=>r.version>n);for(let r of t){console.log(`
36
- Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Ne(L,r.version),Ne(M,r.version)}catch(c){console.error(`
37
- [FATAL] Pre-migration backup failed for ${s}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
38
- `),process.exit(1)}let u=r.module;try{await u.up(L,M)}catch(c){console.error(`
39
- [FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let f=gn(i);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${n}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
40
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${f.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
41
- `))}catch(f){console.error(` [!] Auto-rollback CRASHED while restoring: ${f.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
42
- `)}process.exit(1)}try{let c=new Date().toISOString(),f={version:r.version,name:u.NAME||s,appliedAt:c},l=De();l.version=r.version,l.migratedAt=c,l.migrations=l.migrations||[],l.migrations.push(f),an(l)}catch(c){console.error(`
43
- [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${n}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
44
- `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{me()}catch{}try{Se()}catch{}se=!0,ce(),console.log(`
45
- \u2713 Schema is now at v${C}
46
- `)}var un=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function fn(e){let n=e.toLowerCase();return un.some(o=>o.test(n))}var pn=6e4;function dn(){let e=Date.now(),n=[];for(let o of[O,L,M]){if(!a.existsSync(o))continue;let t;try{t=a.readdirSync(o)}catch{continue}for(let r of t){if(!fn(r))continue;let s=d.join(o,r);try{let i=a.statSync(s);if(!i.isFile()||e-i.mtimeMs<pn)continue;n.push({dir:o,file:r,fullPath:s})}catch{}}}return n}function mn({verbose:e=!1}={}){let n=dn();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let t of n)try{a.unlinkSync(t.fullPath),o++,e&&console.log(` Removed orphan: ${d.basename(t.dir)}/${t.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${r.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function hn(){let e=[];for(let n of[L,M]){if(!a.existsSync(n))continue;let o=a.readdirSync(n).filter(t=>{let r=t.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let t of o){let r=d.join(n,t);try{G(r)}catch(s){e.push({dir:d.basename(n),file:t,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function gn(e){let n=[],o=[];for(let s of[L,M]){if(!a.existsSync(s))continue;let i=a.readdirSync(s).filter(u=>u.endsWith(e));for(let u of i){let c=d.join(s,u),f=u.slice(0,-e.length),l=d.join(s,f);try{f.toLowerCase().endsWith(".json")?G(c):a.accessSync(c,a.constants.R_OK),n.push({backupPath:c,originalPath:l,fileName:u,dir:s})}catch(m){o.push(`${d.basename(s)}/${u}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let t=0,r=[];for(let{backupPath:s,originalPath:i,fileName:u,dir:c}of n)try{Me(s,i),t++}catch(f){r.push(`${d.basename(c)}/${u}: ${f.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:t}:{ok:!0,restored:t}}function Me(e,n){let o=n+".tmp";try{a.copyFileSync(e,o),Fe(o)}catch(t){try{a.unlinkSync(o)}catch{}throw t}try{a.renameSync(o,n)}catch(t){try{a.unlinkSync(o)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let r=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 r.code=t.code,r}throw t}}var bn=yn(import.meta.url),wn=P.dirname(bn),le=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(wn,"collected-profiles");await Le();var ae=process.argv.slice(2),Pe=parseInt(ae.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),H=parseInt(ae.find(e=>e.startsWith("--min-score="))?.split("=")[1]||"50"),vn=ae.includes("--list");function kn(){let n=K(20,{easyApplyOnly:!0}).filter(o=>o.score>=H);if(console.log(`
47
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 ${H})`),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:r,jobId:s}=n[o],i=(r.techStack||[]).slice(0,4).join(", ");console.log(` ${String(o+1).padStart(2)}. [${t}] ${(r.title||"?").slice(0,35)} @ ${(r.company||"?").slice(0,20)}`),console.log(` ${r.salary||"no salary"} | ${r.location||"?"} | ${i||"no tech"}`),console.log(` ${r.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
48
- `)}async function An(){if(console.log(`
35
+ `),process.exit(1)}let t=T.filter(r=>r.version>n);for(let r of t){console.log(`
36
+ Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,c=`.pre-${s}.backup`;try{Pe(U,r.version),Pe(J,r.version)}catch(i){console.error(`
37
+ [FATAL] Pre-migration backup failed for ${s}: ${i.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
38
+ `),process.exit(1)}let u=r.module;try{await u.up(U,J)}catch(i){console.error(`
39
+ [FATAL] Migration ${s} failed: ${i.message}`),console.error(` Attempting auto-rollback from ${c} files...`);try{let a=Rn(c);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${n}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
40
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${c} files back over the originals.
41
+ `))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${c} files back over the originals.
42
+ `)}process.exit(1)}try{let i=new Date().toISOString(),a={version:r.version,name:u.NAME||s,appliedAt:i},l=Me();l.version=r.version,l.migratedAt=i,l.migrations=l.migrations||[],l.migrations.push(a),vn(l)}catch(i){console.error(`
43
+ [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${i.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${n}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
44
+ `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Se()}catch{}try{ke()}catch{}ae=!0,fe(),console.log(`
45
+ \u2713 Schema is now at v${D}
46
+ `)}var kn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function An(e){let n=e.toLowerCase();return kn.some(o=>o.test(n))}var $n=6e4;function En(){let e=Date.now(),n=[];for(let o of[R,U,J]){if(!f.existsSync(o))continue;let t;try{t=f.readdirSync(o)}catch{continue}for(let r of t){if(!An(r))continue;let s=d.join(o,r);try{let c=f.statSync(s);if(!c.isFile()||e-c.mtimeMs<$n)continue;n.push({dir:o,file:r,fullPath:s})}catch{}}}return n}function On({verbose:e=!1}={}){let n=En();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let t of n)try{f.unlinkSync(t.fullPath),o++,e&&console.log(` Removed orphan: ${d.basename(t.dir)}/${t.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${r.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function jn(){let e=[];for(let n of[U,J]){if(!f.existsSync(n))continue;let o=f.readdirSync(n).filter(t=>{let r=t.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let t of o){let r=d.join(n,t);try{K(r)}catch(s){e.push({dir:d.basename(n),file:t,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Rn(e){let n=[],o=[];for(let s of[U,J]){if(!f.existsSync(s))continue;let c=f.readdirSync(s).filter(u=>u.endsWith(e));for(let u of c){let i=d.join(s,u),a=u.slice(0,-e.length),l=d.join(s,a);try{a.toLowerCase().endsWith(".json")?K(i):f.accessSync(i,f.constants.R_OK),n.push({backupPath:i,originalPath:l,fileName:u,dir:s})}catch(m){o.push(`${d.basename(s)}/${u}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let t=0,r=[];for(let{backupPath:s,originalPath:c,fileName:u,dir:i}of n)try{qe(s,c),t++}catch(a){r.push(`${d.basename(i)}/${u}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:t}:{ok:!0,restored:t}}function qe(e,n){let o=n+".tmp";try{f.copyFileSync(e,o),Je(o)}catch(t){try{f.unlinkSync(o)}catch{}throw t}try{f.renameSync(o,n)}catch(t){try{f.unlinkSync(o)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let r=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 r.code=t.code,r}throw t}}var _n=In(import.meta.url),Ge=N.dirname(_n),pe=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"collected-profiles"):N.join(Ge,"collected-profiles");await Be();var de=process.argv.slice(2),Ve=parseInt(de.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),z=parseInt(de.find(e=>e.startsWith("--min-score="))?.split("=")[1]||"50"),Cn=de.includes("--list");function Dn(){let n=X(20,{easyApplyOnly:!0}).filter(o=>o.score>=z);if(console.log(`
47
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 ${z})`),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:r,jobId:s}=n[o],c=(r.techStack||[]).slice(0,4).join(", ");console.log(` ${String(o+1).padStart(2)}. [${t}] ${(r.title||"?").slice(0,35)} @ ${(r.company||"?").slice(0,20)}`),console.log(` ${r.salary||"no salary"} | ${r.location||"?"} | ${c||"no tech"}`),console.log(` ${r.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
48
+ `)}async function Nn(){if(console.log(`
49
49
  LinkedIn Apply Queue
50
- `),vn){kn();return}let n=K(Pe*3,{easyApplyOnly:!0}).filter(s=>s.score>=H).slice(0,Pe);if(n.length===0){console.log(` No jobs to apply. Run: npm run scout
51
- `);return}console.log(` Applying to ${n.length} jobs (score >= ${H}):
52
- `);for(let{score:s,job:i}of n)console.log(` [${s}] ${(i.title||"?").slice(0,40)} @ ${(i.company||"?").slice(0,20)}`);D.existsSync(le)||D.mkdirSync(le,{recursive:!0});let o=P.join(le,"apply-queue-urls.json"),t=n.map(({job:s,jobId:i})=>({url:s.url,title:s.title,company:s.company,location:s.location,salary:s.salary}));D.writeFileSync(o,JSON.stringify(t,null,2)),console.log(`
53
- Generated ${o} with ${t.length} jobs`);for(let{jobId:s}of n)be(s,{queued:!0,queuedAt:new Date().toISOString().slice(0,10)});let r=Oe("apply-queue",`${n.length} jobs`);console.log(`
50
+ `),Cn){Dn();return}let n=X(Ve*3,{easyApplyOnly:!0}).filter(s=>s.score>=z).slice(0,Ve);if(n.length===0){console.log(` No jobs to apply. Run: npm run scout
51
+ `);return}console.log(` Applying to ${n.length} jobs (score >= ${z}):
52
+ `);for(let{score:s,job:c}of n)console.log(` [${s}] ${(c.title||"?").slice(0,40)} @ ${(c.company||"?").slice(0,20)}`);x.existsSync(pe)||x.mkdirSync(pe,{recursive:!0});let o=N.join(pe,"apply-queue-urls.json"),t=n.map(({job:s,jobId:c})=>({url:s.url,title:s.title,company:s.company,location:s.location,salary:s.salary}));x.writeFileSync(o,JSON.stringify(t,null,2)),console.log(`
53
+ Generated ${o} with ${t.length} jobs`);for(let{jobId:s}of n)Ae(s,{queued:!0,queuedAt:new Date().toISOString().slice(0,10)});let r=_e("apply-queue",`${n.length} jobs`);console.log(`
54
54
  Launching run.mjs --job-urls...
55
- `);try{Sn("node",["run.mjs",`--job-urls=${o}`],{stdio:"inherit",timeout:144e5}),X(r,"success",{applied:n.length})}catch(s){console.error(`
56
- Apply queue error: ${s.message?.slice(0,80)}`),X(r,"error",{applied:n.length},s.message)}try{D.unlinkSync(o)}catch{}}An().catch(e=>{console.error("Apply queue failed:",e),process.exit(1)});
55
+ `);try{Tn("node",[N.join(Ge,"run.mjs"),`--job-urls=${o}`],{stdio:"inherit",timeout:144e5}),oe(r,"success",{applied:n.length})}catch(s){console.error(`
56
+ Apply queue error: ${s.message?.slice(0,80)}`),oe(r,"error",{applied:n.length},s.message)}try{x.unlinkSync(o)}catch{}}Nn().catch(e=>{console.error("Apply queue failed:",e),process.exit(1)});