@seoagent-official/seoagent 1.74.0 → 1.75.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/index.js CHANGED
@@ -1,47 +1,47 @@
1
1
  #!/usr/bin/env node
2
- import{Command as ng}from"commander";import{dirname as ii,relative as en}from"path";import{intro as gl,outro as hl,text as ni,select as Kn,spinner as yl,isCancel as Ge,cancel as We,confirm as wl}from"@clack/prompts";var Ie=[".env.local",".env.production",".env"],Vr=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var se="@seoagent-official/seoagent",jt=`${se}@latest`;import{homedir as Ca}from"os";import{join as Oe}from"path";var k=".seoagent",zr=["audit","strategy/clusters","briefs","content","content/images","performance"],ke={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Nt=".claude/settings.json",Dt=".pull-receipt.json",Yr=".ack-queue.json",Jr=".sync.lock",Xr=`# SEOAgent local files
2
+ import{Command as Og}from"commander";import{dirname as mi,relative as an}from"path";import{intro as El,outro as Rl,text as di,select as Xn,spinner as Al,isCancel as We,cancel as He,confirm as Pl}from"@clack/prompts";var Te=[".env.local",".env.production",".env"],to=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var se="@seoagent-official/seoagent",Bt=`${se}@latest`;import{homedir as Fa}from"os";import{join as Le}from"path";var w=".seoagent",no=["audit","strategy/clusters","briefs","content","content/images","performance"],ve={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},st=".claude/settings.json",Gt=".pull-receipt.json",ro=".ack-queue.json",oo=".sync.lock",io=`# SEOAgent local files
3
3
  .legacy/
4
4
  content/images/*
5
5
  !content/images/.gitkeep
6
6
  .pull-receipt.json
7
7
  .ack-queue.json
8
8
  .sync.lock
9
- `,Ra=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Oe(Ca(),".config"),W=Oe(Ra,"seoagent"),de=Oe(W,"auth.json"),Rn=Oe(W,"state"),Ft=Oe(W,"update-check.json"),Ut=Oe(W,"projects.json");var ot="https://seoagent.com",Te=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):ot,T={BASE:Te,PRICING:`${Te}/pricing`,LEAD_API:`${Te}/api/cli/lead`,CLI_AUTH_PAGE:`${Te}/cli/auth`,CLI_AUTH_POLL:`${Te}/api/cli/auth/poll`,CLI_SYNC:`${Te}/api/cli/sync`};function ee(e,t){let n=t&&t!=="unknown"?`&domain=${encodeURIComponent(t)}`:"";return`${T.PRICING}?ref=${encodeURIComponent(e)}${n}`}import{readFileSync as Ea}from"fs";import{fileURLToPath as Aa}from"url";import{dirname as Pa,join as Ia}from"path";var Qr="0.0.0";function Oa(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Qr}function Ta(e=t=>Ea(t,"utf-8")){try{let t=Pa(Aa(import.meta.url));return Oa(e(Ia(t,"package.json")))}catch{return Qr}}var A=Ta();function En(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function f(e,t=En()){return t?`seoagent ${e}`:`npx -y ${jt} ${e}`}import{randomUUID as Ua}from"crypto";import{existsSync as to,mkdirSync as no,readFileSync as Ma,writeFileSync as ro}from"fs";import{join as Pn}from"path";import{existsSync as La,readFileSync as ja}from"fs";var Mt="---";function Na(e){let t=e.trim();return t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function Da(e){let t=[];for(let n of e){let r=n.trim();if(r===""||r.startsWith("#"))continue;let o=n.indexOf(":");if(o===-1)continue;let i=n.slice(0,o).trim();if(!i)continue;let s=n.slice(o+1),a=n.length-n.replace(/^\s+/,"").length;t.push({indent:a,key:i,valueRaw:s,value:s.trim()})}return t}function Zr(e,t,n){let r={},o=t;for(;o<e.length;){let i=e[o];if(i.indent<n)break;if(i.indent>n){o++;continue}if(i.value===""){let s=e[o+1];if(s&&s.indent>n){let[a,c]=Zr(e,o+1,s.indent);r[i.key]=a,o=c}else r[i.key]="",o++}else r[i.key]=Na(i.valueRaw),o++}return[r,o]}function pe(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Mt)return{data:{},body:e};let n=-1;for(let c=1;c<t.length;c++)if(t[c].trim()===Mt){n=c;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
10
- `),i=Da(r),s=i.length>0?i[0].indent:0,[a]=Zr(i,0,s);return{data:a,body:o}}function Bt(e){if(!La(e))return null;try{return pe(ja(e,"utf-8"))}catch{return null}}function Fa(e){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return String(e);let t=String(e);return t===""||/[:#\[\]{}&*!|>'"%@`,]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function eo(e,t,n){let r=" ".repeat(t);for(let[o,i]of Object.entries(e))i!==void 0&&(i!==null&&typeof i=="object"?(n.push(`${r}${o}:`),eo(i,t+1,n)):n.push(`${r}${o}: ${Fa(i)}`))}function An(e,t=""){let n=[Mt];eo(e,0,n),n.push(Mt);let r=t.length===0?"":t.startsWith(`
9
+ `,Ma=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Le(Fa(),".config"),W=Le(Ma,"seoagent"),pe=Le(W,"auth.json"),Ln=Le(W,"state"),Wt=Le(W,"update-check.json"),Ht=Le(W,"projects.json");var at="https://seoagent.com",je=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):at,T={BASE:je,PRICING:`${je}/pricing`,LEAD_API:`${je}/api/cli/lead`,CLI_AUTH_PAGE:`${je}/cli/auth`,CLI_AUTH_POLL:`${je}/api/cli/auth/poll`,CLI_SYNC:`${je}/api/cli/sync`};function ee(e,t){let n=t&&t!=="unknown"?`&domain=${encodeURIComponent(t)}`:"";return`${T.PRICING}?ref=${encodeURIComponent(e)}${n}`}import{readFileSync as Ua}from"fs";import{fileURLToPath as Ba}from"url";import{dirname as Ga,join as Wa}from"path";var so="0.0.0";function Ha(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return so}function Ka(e=t=>Ua(t,"utf-8")){try{let t=Ga(Ba(import.meta.url));return Ha(e(Wa(t,"package.json")))}catch{return so}}var A=Ka();function jn(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function f(e,t=jn()){return t?`seoagent ${e}`:`npx -y ${Bt} ${e}`}import{randomUUID as Xa}from"crypto";import{existsSync as lo,mkdirSync as uo,readFileSync as Qa,writeFileSync as po}from"fs";import{join as Dn}from"path";import{existsSync as qa,readFileSync as Va}from"fs";var Kt="---";function Ya(e){let t=e.trim();return t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function za(e){let t=[];for(let n of e){let r=n.trim();if(r===""||r.startsWith("#"))continue;let o=n.indexOf(":");if(o===-1)continue;let i=n.slice(0,o).trim();if(!i)continue;let s=n.slice(o+1),a=n.length-n.replace(/^\s+/,"").length;t.push({indent:a,key:i,valueRaw:s,value:s.trim()})}return t}function ao(e,t,n){let r={},o=t;for(;o<e.length;){let i=e[o];if(i.indent<n)break;if(i.indent>n){o++;continue}if(i.value===""){let s=e[o+1];if(s&&s.indent>n){let[a,c]=ao(e,o+1,s.indent);r[i.key]=a,o=c}else r[i.key]="",o++}else r[i.key]=Ya(i.valueRaw),o++}return[r,o]}function fe(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Kt)return{data:{},body:e};let n=-1;for(let c=1;c<t.length;c++)if(t[c].trim()===Kt){n=c;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
10
+ `),i=za(r),s=i.length>0?i[0].indent:0,[a]=ao(i,0,s);return{data:a,body:o}}function qt(e){if(!qa(e))return null;try{return fe(Va(e,"utf-8"))}catch{return null}}function Ja(e){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return String(e);let t=String(e);return t===""||/[:#\[\]{}&*!|>'"%@`,]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function co(e,t,n){let r=" ".repeat(t);for(let[o,i]of Object.entries(e))i!==void 0&&(i!==null&&typeof i=="object"?(n.push(`${r}${o}:`),co(i,t+1,n)):n.push(`${r}${o}: ${Ja(i)}`))}function Nn(e,t=""){let n=[Kt];co(e,0,n),n.push(Kt);let r=t.length===0?"":t.startsWith(`
11
11
  `)?t:`
12
12
  ${t}`;return n.join(`
13
13
  `)+r+(r.endsWith(`
14
14
  `)?"":`
15
- `)}var Ba=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function In(){return Ua()}var Ga=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),Wa="project.md";function it(e){return Pn(e,k)}function Gt(e){return Pn(it(e),Wa)}function oo(e){return to(Gt(e))}function E(e){let t=Bt(Gt(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&Ga.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",skill_version:typeof n.skill_version=="string"&&n.skill_version?n.skill_version:void 0,install_id:s&&Ba.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0,live_url:typeof n.live_url=="string"&&n.live_url?n.live_url:void 0}}function Wt(e){let t=E(e);if(!t)return null;if(t.install_id)return t.install_id;let n=In();return q(e,{install_id:n}),n}function Ha(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
16
- `)}function Ka(e){let t={domain:e.domain,site_type:e.site_type,language:e.language,initialized_at:e.initialized_at,seoagent_version:e.seoagent_version};return e.skill_version&&(t.skill_version=e.skill_version),e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),e.live_url&&(t.live_url=e.live_url),t}function io(e,t){let n=it(e);no(n,{recursive:!0});let r=An(Ka(t),Ha(t));ro(Gt(e),r,"utf-8")}function q(e,t){let n=Gt(e);if(!to(n))return!1;let r=pe(Ma(n,"utf-8")),o={...r.data,...t};return ro(n,An(o,r.body),"utf-8"),!0}function so(e){let t=it(e);for(let n of zr)no(Pn(t,n),{recursive:!0})}var On="Sent an anonymous install ping (random id + CLI version only \u2014 no domain, no paths). Opt out: SEOAGENT_TELEMETRY=0",qa=2500;function Tn(e=process.env){let t=(e.SEOAGENT_TELEMETRY??"").trim().toLowerCase();if(t==="0"||t==="false"||t==="off")return!0;let n=(e.DO_NOT_TRACK??"").trim().toLowerCase();return n==="1"||n==="true"}async function Ln(e){let t=(e.apiBase||T.BASE).replace(/\/$/,""),n=e.fetchImpl??fetch;try{return(await n(`${t}/api/cli/telemetry`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:e.installId,event:e.event,cli_version:e.cliVersion,platform:process.platform}),signal:AbortSignal.timeout(e.timeoutMs??qa)})).ok}catch{return!1}}import{existsSync as co,mkdirSync as ao,readFileSync as Va,writeFileSync as za,chmodSync as Ya,unlinkSync as Ja}from"fs";import{dirname as Xa}from"path";function N(){if(!co(de))return null;try{let e=JSON.parse(Va(de,"utf-8"));return!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||ot}}catch{return null}}function lo(e){ao(W,{recursive:!0}),ao(Xa(de),{recursive:!0}),za(de,JSON.stringify(e,null,2)+`
17
- `,"utf-8");try{Ya(de,384)}catch{}}function uo(){if(!co(de))return!1;try{return Ja(de),!0}catch{return!1}}var Qa=new Set([502,503,504]),Za=1e4;async function P(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??Za,s=n.fetchImpl??fetch,a=n.sleep??ec,c=n.transientStatuses??Qa,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:m}=tc(t,i);try{let g=await s(e,p);if(c.has(g.status)&&d<r-1){await a(po(o,d));continue}return g}catch(g){if(u=g,d<r-1){await a(po(o,d));continue}}finally{m()}}throw u instanceof Error?u:new Error(String(u))}function po(e,t){return e*Math.pow(3,t)}function ec(e){return new Promise(t=>setTimeout(t,e))}function tc(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}var Le="unknown";function Ht(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):""}function nc(e,t){let n=Ht(e),r=Ht(t);return!n||!r||n===Le||r===Le?!1:n===r}async function je(e){let t;try{t=await P(`${e.apiBase}/api/cli/whoami`,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}},e.fetchImpl?{fetchImpl:e.fetchImpl}:{})}catch(o){return{verdict:"unverified",detail:o.message||"network error"}}if(t.status===404)return{verdict:"unverified",detail:"server does not support /api/cli/whoami"};if(!t.ok)return{verdict:"unverified",detail:`whoami returned HTTP ${t.status}`};let n=null;try{n=await t.json()}catch{n=null}if(!n||n.status!=="ok")return{verdict:"unverified",detail:"malformed whoami response"};let r=typeof n.domain=="string"?n.domain.trim():"";return r?nc(r,e.localDomain)?{verdict:"match",cloudDomain:r}:{verdict:"mismatch",cloudDomain:r}:{verdict:"unverified",detail:"whoami did not return a bound domain"}}function fo(e,t){return`Cloud project is ${Ht(e)||e} but this workspace is ${Ht(t)||t} \u2014 not syncing. Run \`seoagent logout && seoagent login\` from this directory to connect the right site.`}var rc=new Set(["co","com","net","org","ac","gov","edu"]);function oc(e){let t=e.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,"").replace(/:\d+$/,"").replace(/^www\./,"");if(!t)return null;let n=t.split(".").filter(Boolean);if(n.length===0)return null;if(n.length===1)return n[0];let r=n.length>=3&&rc.has(n[n.length-2])?n.length-3:n.length-2;return n[Math.max(0,r)]||null}async function mo(e){let t=oc(e.domain);if(!t)return{status:"unavailable"};let n=(e.apiBase||T.BASE).replace(/\/$/,"");try{let r=await P(`${n}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:e.installId,keyword:t,domain:e.domain})},{attempts:2,timeoutMs:6e3,fetchImpl:e.fetchImpl});if(!r.ok)return{status:"unavailable"};let o=await r.json();return!o?.ok||!o.opportunity?{status:"unavailable"}:o.opportunity.volume==null?{status:"no-data",keyword:t}:{status:"data",keyword:t,volume:o.opportunity.volume,difficulty:o.opportunity.difficulty,intent:o.opportunity.intent}}catch{return{status:"unavailable"}}}import{existsSync as Kt,lstatSync as ic,mkdirSync as st,readFileSync as go,readdirSync as sc,rmSync as ac,statSync as cc,symlinkSync as lc,writeFileSync as ho}from"fs";import{dirname as qt,join as te,relative as yo}from"path";import{fileURLToPath as uc}from"url";var dc=qt(uc(import.meta.url));function wo(){return te(dc,"skills")}function pc(){let e=te(wo(),"seoagent.md");if(Kt(e))return go(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function bo(e,t){let n=[];if(!Kt(e))return n;for(let r of sc(e,{withFileTypes:!0})){let o=te(e,r.name),i=te(t,r.name);r.isDirectory()?(st(i,{recursive:!0}),n.push(...bo(o,i))):r.isFile()&&(st(qt(i),{recursive:!0}),ho(i,go(o)),n.push(i))}return n}function Ne(e,t){let n=Kt(te(e,".agents")),r=te(e,n?ke.AGENTS:ke.CLAUDE),o=te(r,"SKILL.md");st(r,{recursive:!0}),ho(o,t??pc(),"utf-8");let i=te(wo(),"references"),s=te(r,"references"),a=[];try{Kt(i)&&cc(i).isDirectory()&&(st(s,{recursive:!0}),a=bo(i,s).map(u=>yo(r,u)))}catch{}let c=n?fc(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function fc(e,t){let n=te(e,ke.CLAUDE),r=null;try{r=ic(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{ac(n,{force:!0})}catch{return}}try{st(qt(n),{recursive:!0});let o=yo(qt(n),t);return lc(o,n,"dir"),n}catch{return}}import{existsSync as zt,mkdirSync as jn,readFileSync as mc,writeFileSync as Vt}from"fs";import{dirname as vo,join as De}from"path";var gc=`npx -y ${jt} sync --silent`;function $o(e){let t=De(e,k);jn(t,{recursive:!0});let n=De(t,".gitignore");Vt(n,Xr,"utf-8");let r=De(t,"content","images",".gitkeep");return jn(vo(r),{recursive:!0}),zt(r)||Vt(r,"","utf-8"),n}var So=["PostToolUse","SessionStart"];function Nn(e){if(!zt(e))return{};try{let t=mc(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Dn(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function ko(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(Dn)?!1:(r.hooks.push({type:"command",command:gc}),!0)}function ve(e){let t=De(e,Nt);jn(vo(t),{recursive:!0});let n=Nn(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=ko(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=ko(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return Vt(t,JSON.stringify(n,null,2)+`
18
- `,"utf-8"),{file:t,added:o||s}}function xo(e){let t=De(e,Nt);if(!zt(t))return!1;let n=Nn(t).hooks;return n?So.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(Dn))}):!1}function _o(e){let t=De(e,Nt);if(!zt(t))return{file:t,removed:!1};let n=Nn(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of So){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(d=>!Dn(d)),c.hooks.length!==u&&(o=!0)}let a=s.filter(c=>c.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,Vt(t,JSON.stringify(n,null,2)+`
19
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as Co,mkdirSync as hc,readFileSync as yc,writeFileSync as wc}from"fs";import{join as bc}from"path";function Ro(e){return Co(bc(e,k,"project.md"))}function Eo(){try{if(!Co(Ut))return[];let e=JSON.parse(yc(Ut,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function Ao(e){try{hc(W,{recursive:!0}),wc(Ut,JSON.stringify({projects:e},null,2)+`
20
- `,"utf-8")}catch{}}function $e(e){try{if(!Ro(e))return;let t=Eo();if(t.includes(e))return;t.push(e),Ao(t)}catch{}}function Po(){let e=Eo(),t=e.filter(Ro);return t.length!==e.length&&Ao(t),t}import{readFileSync as Sc,writeFileSync as xc,existsSync as _c}from"fs";import{join as Lo}from"path";function Oo(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=kc(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=vc(o):i==="writing instructions"?t.writingInstructions=Io(o):i==="reference urls"?t.referenceUrls=$c(o):i==="topics to avoid"?t.topicsToAvoid=Io(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function To(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
21
- `)}function kc(e){let t=e.split(`
15
+ `)}var Za=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fn(){return Xa()}var ec=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),tc="project.md";function ct(e){return Dn(e,w)}function Vt(e){return Dn(ct(e),tc)}function fo(e){return lo(Vt(e))}function R(e){let t=qt(Vt(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&ec.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",skill_version:typeof n.skill_version=="string"&&n.skill_version?n.skill_version:void 0,install_id:s&&Za.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0,live_url:typeof n.live_url=="string"&&n.live_url?n.live_url:void 0}}function Yt(e){let t=R(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Fn();return q(e,{install_id:n}),n}function nc(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
16
+ `)}function rc(e){let t={domain:e.domain,site_type:e.site_type,language:e.language,initialized_at:e.initialized_at,seoagent_version:e.seoagent_version};return e.skill_version&&(t.skill_version=e.skill_version),e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),e.live_url&&(t.live_url=e.live_url),t}function mo(e,t){let n=ct(e);uo(n,{recursive:!0});let r=Nn(rc(t),nc(t));po(Vt(e),r,"utf-8")}function q(e,t){let n=Vt(e);if(!lo(n))return!1;let r=fe(Qa(n,"utf-8")),o={...r.data,...t};return po(n,Nn(o,r.body),"utf-8"),!0}function go(e){let t=ct(e);for(let n of no)uo(Dn(t,n),{recursive:!0})}var Mn="Sent an anonymous install ping (random id + CLI version only \u2014 no domain, no paths). Opt out: SEOAGENT_TELEMETRY=0",oc=2500;function Un(e=process.env){let t=(e.SEOAGENT_TELEMETRY??"").trim().toLowerCase();if(t==="0"||t==="false"||t==="off")return!0;let n=(e.DO_NOT_TRACK??"").trim().toLowerCase();return n==="1"||n==="true"}async function Bn(e){let t=(e.apiBase||T.BASE).replace(/\/$/,""),n=e.fetchImpl??fetch;try{return(await n(`${t}/api/cli/telemetry`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:e.installId,event:e.event,cli_version:e.cliVersion,platform:process.platform}),signal:AbortSignal.timeout(e.timeoutMs??oc)})).ok}catch{return!1}}import{existsSync as yo,mkdirSync as ho,readFileSync as ic,writeFileSync as sc,chmodSync as ac,unlinkSync as cc}from"fs";import{dirname as lc}from"path";function N(){if(!yo(pe))return null;try{let e=JSON.parse(ic(pe,"utf-8"));return!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||at}}catch{return null}}function wo(e){ho(W,{recursive:!0}),ho(lc(pe),{recursive:!0}),sc(pe,JSON.stringify(e,null,2)+`
17
+ `,"utf-8");try{ac(pe,384)}catch{}}function bo(){if(!yo(pe))return!1;try{return cc(pe),!0}catch{return!1}}var uc=new Set([502,503,504]),dc=1e4;async function P(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??dc,s=n.fetchImpl??fetch,a=n.sleep??pc,c=n.transientStatuses??uc,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:m}=fc(t,i);try{let g=await s(e,p);if(c.has(g.status)&&d<r-1){await a(ko(o,d));continue}return g}catch(g){if(u=g,d<r-1){await a(ko(o,d));continue}}finally{m()}}throw u instanceof Error?u:new Error(String(u))}function ko(e,t){return e*Math.pow(3,t)}function pc(e){return new Promise(t=>setTimeout(t,e))}function fc(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}var Ne="unknown";function zt(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):""}function mc(e,t){let n=zt(e),r=zt(t);return!n||!r||n===Ne||r===Ne?!1:n===r}async function De(e){let t;try{t=await P(`${e.apiBase}/api/cli/whoami`,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}},e.fetchImpl?{fetchImpl:e.fetchImpl}:{})}catch(o){return{verdict:"unverified",detail:o.message||"network error"}}if(t.status===404)return{verdict:"unverified",detail:"server does not support /api/cli/whoami"};if(!t.ok)return{verdict:"unverified",detail:`whoami returned HTTP ${t.status}`};let n=null;try{n=await t.json()}catch{n=null}if(!n||n.status!=="ok")return{verdict:"unverified",detail:"malformed whoami response"};let r=typeof n.domain=="string"?n.domain.trim():"";return r?mc(r,e.localDomain)?{verdict:"match",cloudDomain:r}:{verdict:"mismatch",cloudDomain:r}:{verdict:"unverified",detail:"whoami did not return a bound domain"}}function vo(e,t){return`Cloud project is ${zt(e)||e} but this workspace is ${zt(t)||t} \u2014 not syncing. Run \`seoagent logout && seoagent login\` from this directory to connect the right site.`}var gc=new Set(["co","com","net","org","ac","gov","edu"]);function hc(e){let t=e.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,"").replace(/:\d+$/,"").replace(/^www\./,"");if(!t)return null;let n=t.split(".").filter(Boolean);if(n.length===0)return null;if(n.length===1)return n[0];let r=n.length>=3&&gc.has(n[n.length-2])?n.length-3:n.length-2;return n[Math.max(0,r)]||null}async function $o(e){let t=hc(e.domain);if(!t)return{status:"unavailable"};let n=(e.apiBase||T.BASE).replace(/\/$/,"");try{let r=await P(`${n}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:e.installId,keyword:t,domain:e.domain})},{attempts:2,timeoutMs:6e3,fetchImpl:e.fetchImpl});if(!r.ok)return{status:"unavailable"};let o=await r.json();return!o?.ok||!o.opportunity?{status:"unavailable"}:o.opportunity.volume==null?{status:"no-data",keyword:t}:{status:"data",keyword:t,volume:o.opportunity.volume,difficulty:o.opportunity.difficulty,intent:o.opportunity.intent}}catch{return{status:"unavailable"}}}import{existsSync as Jt,lstatSync as yc,mkdirSync as lt,readFileSync as So,readdirSync as wc,rmSync as bc,statSync as kc,symlinkSync as vc,writeFileSync as xo}from"fs";import{dirname as Xt,join as te,relative as _o}from"path";import{fileURLToPath as $c}from"url";var Sc=Xt($c(import.meta.url));function Co(){return te(Sc,"skills")}function xc(){let e=te(Co(),"seoagent.md");if(Jt(e))return So(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Eo(e,t){let n=[];if(!Jt(e))return n;for(let r of wc(e,{withFileTypes:!0})){let o=te(e,r.name),i=te(t,r.name);r.isDirectory()?(lt(i,{recursive:!0}),n.push(...Eo(o,i))):r.isFile()&&(lt(Xt(i),{recursive:!0}),xo(i,So(o)),n.push(i))}return n}function Fe(e,t){let n=Jt(te(e,".agents")),r=te(e,n?ve.AGENTS:ve.CLAUDE),o=te(r,"SKILL.md");lt(r,{recursive:!0}),xo(o,t??xc(),"utf-8");let i=te(Co(),"references"),s=te(r,"references"),a=[];try{Jt(i)&&kc(i).isDirectory()&&(lt(s,{recursive:!0}),a=Eo(i,s).map(u=>_o(r,u)))}catch{}let c=n?_c(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function _c(e,t){let n=te(e,ve.CLAUDE),r=null;try{r=yc(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{bc(n,{force:!0})}catch{return}}try{lt(Xt(n),{recursive:!0});let o=_o(Xt(n),t);return vc(o,n,"dir"),n}catch{return}}import{existsSync as ut,mkdirSync as Gn,readFileSync as Cc,writeFileSync as Qt}from"fs";import{dirname as Ao,join as $e}from"path";var Wn=`command -v seoagent >/dev/null 2>&1 && seoagent sync --silent || npx -y ${Bt} sync --silent`,Po=60;function Io(e){let t=$e(e,w);Gn(t,{recursive:!0});let n=$e(t,".gitignore");Qt(n,io,"utf-8");let r=$e(t,"content","images",".gitkeep");return Gn(Ao(r),{recursive:!0}),ut(r)||Qt(r,"","utf-8"),n}var Zt=["PostToolUse","SessionStart"];function en(e){if(!ut(e))return{};try{let t=Cc(e,"utf-8");return JSON.parse(t)}catch{return{}}}function dt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Ro(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(dt)?!1:(r.hooks.push({type:"command",command:Wn,timeout:Po}),!0)}function Ec(e){let t=!1;for(let n of Zt){let r=e[n];if(Array.isArray(r))for(let o of r)for(let i of o.hooks??[])dt(i)&&(i.command!==Wn&&(i.command=Wn,t=!0),typeof i.timeout!="number"&&(i.timeout=Po,t=!0))}return t}function Se(e){let t=$e(e,st);Gn(Ao(t),{recursive:!0});let n=en(t);n.hooks=n.hooks??{};let r=Ec(n.hooks),o=n.hooks.PostToolUse=n.hooks.PostToolUse??[],i=Ro(o,c=>(c.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),s=n.hooks.SessionStart=n.hooks.SessionStart??[],a=Ro(s,c=>(c.matcher??"")==="",()=>({hooks:[]}));return Qt(t,JSON.stringify(n,null,2)+`
18
+ `,"utf-8"),{file:t,added:i||a,migrated:r}}function Oo(e){let t=$e(e,st);if(!ut(t))return 0;let n=en(t).hooks;if(!n)return 0;let r=0;for(let o of Zt){let i=n[o];if(Array.isArray(i))for(let s of i)for(let a of s.hooks??[])dt(a)&&typeof a.timeout!="number"&&r++}return r}function To(e){let t=$e(e,st);if(!ut(t))return!1;let n=en(t).hooks;return n?Zt.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(dt))}):!1}function Lo(e){let t=$e(e,st);if(!ut(t))return{file:t,removed:!1};let n=en(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of Zt){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(d=>!dt(d)),c.hooks.length!==u&&(o=!0)}let a=s.filter(c=>c.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,Qt(t,JSON.stringify(n,null,2)+`
19
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as jo,mkdirSync as Rc,readFileSync as Ac,writeFileSync as Pc}from"fs";import{join as Ic}from"path";function No(e){return jo(Ic(e,w,"project.md"))}function Do(){try{if(!jo(Ht))return[];let e=JSON.parse(Ac(Ht,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function Fo(e){try{Rc(W,{recursive:!0}),Pc(Ht,JSON.stringify({projects:e},null,2)+`
20
+ `,"utf-8")}catch{}}function xe(e){try{if(!No(e))return;let t=Do();if(t.includes(e))return;t.push(e),Fo(t)}catch{}}function Mo(){let e=Do(),t=e.filter(No);return t.length!==e.length&&Fo(t),t}import{readFileSync as jc,writeFileSync as Nc,existsSync as Dc}from"fs";import{join as Wo}from"path";function Bo(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Oc(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=Tc(o):i==="writing instructions"?t.writingInstructions=Uo(o):i==="reference urls"?t.referenceUrls=Lc(o):i==="topics to avoid"?t.topicsToAvoid=Uo(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function Go(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
21
+ `)}function Oc(e){let t=e.split(`
22
22
  `),n=[],r="",o=[];for(let i of t){let s=i.match(/^#\s+(.+)$/);s?(r&&n.push([r,o.join(`
23
23
  `)]),r=s[1],o=[]):o.push(i)}return r&&n.push([r,o.join(`
24
- `)]),n}function vc(e){let t={},n=e.split(`
25
- `);for(let r of n){let o=r.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)$/);if(o){let i=o[1].toLowerCase().trim(),s=o[2].trim();s&&(t[i]=s)}}return t}function Io(e){let t=[],n=e.split(`
26
- `);for(let r of n){let o=r.match(/^[-*]\s+(.+)$/);if(o){let i=o[1].trim();(!i.startsWith("(")||!i.endsWith(")"))&&t.push(i)}}return t}function $c(e){let t=[],n=e.split(`
27
- `);for(let r of n){let o=r.match(/^[-*]\s+(https?:\/\/\S+)(?:\s+[—–-]\s+(.+))?$/);o&&t.push({url:o[1].trim(),description:o[2]?.trim()||""})}return t}var jo="context.md";function Yt(e){let t=Lo(e,".seoagent",jo);if(!_c(t))return null;let n=Sc(t,"utf-8");return Oo(n)}function Cc(e,t){let n=Lo(e,".seoagent",jo),r=To(t);xc(n,r,"utf-8")}function No(e,t){Cc(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as at,readFileSync as Do,readdirSync as Rc,statSync as Fo}from"fs";import{join as Se}from"path";var Ec=[{cms:"strapi",deps:["strapi","@strapi/strapi","@strapi/"],envKeys:["STRAPI_URL","STRAPI_API_URL","NEXT_PUBLIC_STRAPI_URL","STRAPI_API_TOKEN"],fsMarkers:["strapi/","apps/strapi/","packages/strapi/","cms/"]},{cms:"wordpress",deps:["wpapi","wp-graphql","@wordpress/api-fetch","@wordpress/"],envKeys:["WORDPRESS_API_URL","WP_API_URL","NEXT_PUBLIC_WORDPRESS_URL"],fsMarkers:[]},{cms:"sanity",deps:["@sanity/client","next-sanity","sanity"],envKeys:["SANITY_PROJECT_ID","NEXT_PUBLIC_SANITY_PROJECT_ID","SANITY_API_TOKEN"],fsMarkers:["sanity/","studio/","sanity.config.ts","sanity.config.js"]},{cms:"contentful",deps:["contentful","@contentful/rich-text-react-renderer","@contentful/"],envKeys:["CONTENTFUL_SPACE_ID","CONTENTFUL_ACCESS_TOKEN","NEXT_PUBLIC_CONTENTFUL_SPACE_ID"],fsMarkers:[]},{cms:"ghost",deps:["@tryghost/content-api","@tryghost/"],envKeys:["GHOST_URL","GHOST_API_KEY","NEXT_PUBLIC_GHOST_URL"],fsMarkers:[]},{cms:"webflow",deps:["webflow-api"],envKeys:["WEBFLOW_API_TOKEN","WEBFLOW_SITE_ID"],fsMarkers:[]},{cms:"shopify",deps:["@shopify/hydrogen","@shopify/storefront-api-client","@shopify/shopify-api","@shopify/"],envKeys:["SHOPIFY_STOREFRONT_TOKEN","SHOPIFY_STORE_DOMAIN","SHOPIFY_ADMIN_API_TOKEN"],fsMarkers:["shopify.config.ts","shopify.config.js"]},{cms:"payload",deps:["payload","@payloadcms/next","@payloadcms/"],envKeys:["PAYLOAD_SECRET","PAYLOAD_PUBLIC_SERVER_URL"],fsMarkers:["payload.config.ts","payload.config.js"]},{cms:"directus",deps:["@directus/sdk","directus"],envKeys:["DIRECTUS_URL","DIRECTUS_TOKEN"],fsMarkers:[]}];function Ac(e){let t=Se(e,"package.json");if(!at(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Do(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Pc(e,t){for(let n of t)if(n.endsWith("/")){if(e.startsWith(n))return!0}else if(e===n)return!0;return!1}function Ic(e){let t={};for(let n of Ie){let r=Se(e,n);if(at(r))try{let o=Do(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function Oc(e,t){let n=Se(e,t.replace(/\/$/,""));if(!at(n))return!1;if(t.endsWith("/"))try{return Fo(n).isDirectory()}catch{return!1}return!0}function Tc(e){let t=["content","_posts","posts",Se("src","content")];for(let n of t){let r=Se(e,n);if(at(r))try{if(!Fo(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Rc(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(Se(s,a.name));continue}if(a.isFile()&&/\.(md|mdx)$/i.test(a.name))return{type:"directory",detail:n,source:`${n}/${a.name}`}}}}catch{}}return null}function Lc(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(at(Se(e,n.marker)))return n.path;return null}function Uo(e){let t=[],{deps:n}=Ac(e),r=Ic(e),o="none";for(let s of Ec){let a=[];for(let c of Object.keys(n))if(Pc(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(r[c]){a.push({type:"env",detail:c,source:r[c]});break}for(let c of s.fsMarkers)if(Oc(e,c)){let u=c.endsWith("/")?"directory":"file";a.push({type:u,detail:c,source:c});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Tc(e);s&&(o="mdx-local",t.push(s))}let i=Lc(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as jc,readFileSync as Nc}from"fs";import{join as Dc}from"path";var Mo=["openai","fal","replicate"],Fe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Fc(e){let t={};if(!jc(e))return t;let n=Nc(e,"utf-8");for(let r of n.split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function Bo(e,t){let n={};for(let r of t){let o=process.env[r];o&&o.trim().length>0&&(n[r]={value:o,source:"process"})}for(let r of Ie){let o=Dc(e,r),i=Fc(o);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:r})}}return{found:n}}function fe(e){let t=[].concat(...Mo.map(a=>Fe[a])),n=Bo(e,t),r=[];for(let a of Mo)Fe[a].some(c=>n.found[c])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=Fe[o].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:o,matched_key:i,source:s,available_providers:r}}function Go(e,t){let n=Bo(e,Fe[t]);for(let r of Fe[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Wo(){return Fe}import{existsSync as xe,readFileSync as Fn}from"fs";import{join as _e}from"path";function Ho(e){try{return new URL(e).hostname}catch{return e}}function Ko(e){let t=e.toLowerCase();return!!(t==="github.com"||t.endsWith(".github.com")||t==="gitlab.com"||t.endsWith(".gitlab.com")||t==="bitbucket.org"||t.endsWith(".bitbucket.org")||t==="dev.azure.com"||t==="visualstudio.com"||t.endsWith(".visualstudio.com")||t==="npmjs.com"||t.endsWith(".npmjs.com"))}function Uc(e){for(let t of Ie){let n=_e(e,t);if(!xe(n))continue;let r=Fn(n,"utf-8");for(let o of Vr){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Ho(s);if(Ko(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Mc(e){let t=_e(e,"package.json");if(!xe(t))return null;try{let n=JSON.parse(Fn(t,"utf-8"));if(!n.homepage)return null;let r=Ho(n.homepage);return Ko(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function qo(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),xe(_e(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=Uc(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Mc(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=_e(e,"package.json"),s=null;if(xe(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Fn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||xe(_e(e,"shopify.config.js"))||xe(_e(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":xe(_e(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),m=u("next");d&&(m||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:m?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as Hc,readFileSync as Gn,readdirSync as zo,statSync as Kc}from"fs";import{join as Y,sep as qc}from"path";var Bc=[/^\/admin(\/|$)/i,/^\/account(s)?(\/|$)/i,/^\/dashboard(\/|$)/i,/^\/settings(\/|$)/i,/^\/login(\/|$)/i,/^\/logout(\/|$)/i,/^\/sign[-_]?in(\/|$)/i,/^\/sign[-_]?up(\/|$)/i,/^\/register(\/|$)/i,/^\/reset[-_]?password(\/|$)/i,/^\/verify(\/|$)/i,/^\/api(\/|$)/i,/^\/_next(\/|$)/i,/^\/checkout(\/|$)/i,/^\/cart(\/|$)/i];function ct(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'").replace(/&quot;/g,'"').trim();o&&t.push(o)}return t}function Ce(e){let t=e;try{t=new URL(e).pathname}catch{let n=t.indexOf("#");n!==-1&&(t=t.slice(0,n));let r=t.indexOf("?");r!==-1&&(t=t.slice(0,r))}return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t||"/"}function Ue(e){return Bc.some(t=>t.test(e))}function Gc(e){return e.filter(t=>Ue(Ce(t)))}function Wc(e,t){let n=new Set(e.map(Ce)),r=[],o=new Set;for(let i of t){let s=Ce(i);Ue(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function Un(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function Vo(e){let t=e.sitemapUrl||Un(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await P(t,{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:e.fetchImpl});if(r.status=i.status,r.fetched=!0,!i.ok)return n.push({level:"error",message:`Sitemap returned HTTP ${i.status} \u2014 Google can't fetch it. Make sure ${t} serves 200.`}),r;o=await i.text()}catch(i){return n.push({level:"error",message:`Could not reach ${t} (${i instanceof Error?i.message:String(i)}). If the site isn't deployed yet, that's expected.`}),r}return/<urlset|<sitemapindex/i.test(o)?(r.urls=ct(o),r.hasLastmod=/<lastmod>/i.test(o),r.urls.length===0?(n.push({level:"error",message:"Sitemap is valid XML but contains zero <loc> URLs."}),r):(/<sitemapindex/i.test(o)&&n.push({level:"info",message:`Sitemap index with ${r.urls.length} child sitemap(s). Child URLs are not expanded by this check.`}),r.privateUrls=Gc(r.urls),r.privateUrls.length>0&&n.push({level:"warning",message:`${r.privateUrls.length} private/noindex URL(s) leaked into the sitemap (e.g. ${r.privateUrls.slice(0,3).map(Ce).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates \u2014 adding them helps crawlers prioritize changed pages."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=Wc(r.urls,e.knownUrls),r.missing.length>0&&n.push({level:"warning",message:`${r.missing.length} public page(s) in the repo are missing from the sitemap (e.g. ${r.missing.slice(0,3).join(", ")}). Add them to the generator so Google can find them.`})),r.ok=!n.some(i=>i.level==="error"),r)):(n.push({level:"error",message:`Response is not a valid XML sitemap (no <urlset>/<sitemapindex>). Got ${o.length} bytes.`}),r)}var Yo=["tsx","jsx","js","mdx","md"],Vc=["astro","md","mdx"],zc=5e3;function ne(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=Zc(i);if(c===null){r++;return}let u=n.get(c);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(c,{route:c,url:al(t,c),in_sitemap:a,source:s})};for(let i of Jc(e))Yc(i,o);return{pages:[...n.values()].filter(i=>!Ue(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function Jo(e,t,n){let r=[];try{let s=await P(Un(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,liveCount:0,flipped:0};r=ct(await s.text())}catch{return{checked:!1,liveCount:0,flipped:0}}if(r.length===0)return{checked:!1,liveCount:0,flipped:0};let o=new Set(r.map(Ce)),i=0;for(let s of e)!s.in_sitemap&&o.has(Ce(s.url||s.route))&&(s.in_sitemap=!0,i++,s.source.includes("live-sitemap")||(s.source+=", live-sitemap"));return{checked:!0,liveCount:r.length,flipped:i}}function Yc(e,t){for(let n of["app",Y("src","app")]){let r=Y(e,n);if(lt(r))for(let o of Mn(r)){let i=Bn(r,o),s=i[i.length-1];ol(s)&&(i.some(a=>a.startsWith("@"))||t(el(i.slice(0,-1)),"app router"))}}for(let n of["pages",Y("src","pages")]){let r=Y(e,n);if(lt(r))for(let o of Mn(r)){let i=Bn(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=Wn(s),c=Yo.includes(a),u=Vc.includes(a);if(!c&&!u)continue;let d=Jt(s);il(d)||t(tl(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=Y(e,n);if(lt(r))for(let o of Mn(r,n==="."?1:1/0)){let i=Bn(r,o),s=i[i.length-1];Wn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(nl(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=Y(e,...n.split("/"));if(Hc(r)){for(let o of sl(r)){let i=rl(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function Jc(e){let t=[e],n=new Set([e]);for(let r of Xc(e))for(let o of Qc(e,r))n.has(o)||(n.add(o),t.push(o));return t}function Xc(e){let t=[];try{let n=Gn(Y(e,"pnpm-workspace.yaml"),"utf-8"),r=!1;for(let o of n.split(/\r?\n/)){let i=o.replace(/#.*$/,"");if(/^\s*packages\s*:/.test(i)){r=!0;continue}if(r){let s=i.match(/^\s*-\s*['"]?([^'"\s]+)['"]?\s*$/);s?t.push(s[1]):/^\S/.test(i)&&(r=!1)}}}catch{}try{let r=JSON.parse(Gn(Y(e,"package.json"),"utf-8")).workspaces,o=Array.isArray(r)?r:Array.isArray(r?.packages)?r.packages:[];for(let i of o??[])typeof i=="string"&&t.push(i)}catch{}return t}function Qc(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=Y(e,...n.split("/").filter(Boolean));return lt(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=Y(e,...o.split("/").filter(Boolean));if(!lt(i))return[];let s=[];try{for(let a of zo(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Xo.has(a.name)&&(s.push(Y(i,a.name)),s.length>=200))break}catch{}return s}function Zc(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function el(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function tl(e){let t=[...e],n=Jt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function nl(e){let t=[...e],n=Jt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function rl(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function ol(e){return Jt(e)==="page"&&Yo.includes(Wn(e))}function il(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function sl(e){try{let t=Gn(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var Xo=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function lt(e){try{return Kc(e).isDirectory()}catch{return!1}}function*Mn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=zo(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=zc)return;if(a.name.startsWith("."))continue;let c=Y(o,a.name);if(a.isDirectory()){if(Xo.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function Bn(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(qc).filter(Boolean)}function Wn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Jt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function al(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as cl,mkdirSync as ll,readFileSync as ul,writeFileSync as dl}from"fs";import{join as Qo}from"path";function Zo(e,t){let n=!1,r=t.status!==null?String(t.status):"\u2014";e.status!==r&&(e.status=r,n=!0),e.rendered!==t.rendered&&(e.rendered=t.rendered,n=!0);let o=t.rendered==="error"?"\u2014":String(t.wordCount);return e.word_count!==o&&(e.word_count=o,n=!0),n}function Xt(e,t,n){let r=Qo(e,k,"pages.md"),o=cl(r),i=o?fl(r):new Map;if(t.length===0&&!o)return{wrote:!1,added:0,total:0,merged:!1};let s=new Map(i),a=0,c=!1;for(let d of t){let p=ti(d.url),m=n?.get(d.url),g=s.get(p);if(g)d.in_sitemap&&g.in_sitemap!=="yes"&&(g.in_sitemap="yes",c=!0),m&&Zo(g,m)&&(c=!0);else{let b={url:p,in_sitemap:d.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:ti(d.source)};m&&Zo(b,m),s.set(p,b),a++,c=!0}}if(o&&!c)return{wrote:!1,added:0,total:s.size,merged:!0};let u=[...s.values()];return ll(Qo(e,k),{recursive:!0}),dl(r,pl(u),"utf-8"),{wrote:!0,added:a,total:u.length,merged:o}}function pl(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
24
+ `)]),n}function Tc(e){let t={},n=e.split(`
25
+ `);for(let r of n){let o=r.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)$/);if(o){let i=o[1].toLowerCase().trim(),s=o[2].trim();s&&(t[i]=s)}}return t}function Uo(e){let t=[],n=e.split(`
26
+ `);for(let r of n){let o=r.match(/^[-*]\s+(.+)$/);if(o){let i=o[1].trim();(!i.startsWith("(")||!i.endsWith(")"))&&t.push(i)}}return t}function Lc(e){let t=[],n=e.split(`
27
+ `);for(let r of n){let o=r.match(/^[-*]\s+(https?:\/\/\S+)(?:\s+[—–-]\s+(.+))?$/);o&&t.push({url:o[1].trim(),description:o[2]?.trim()||""})}return t}var Ho="context.md";function tn(e){let t=Wo(e,".seoagent",Ho);if(!Dc(t))return null;let n=jc(t,"utf-8");return Bo(n)}function Fc(e,t){let n=Wo(e,".seoagent",Ho),r=Go(t);Nc(n,r,"utf-8")}function Ko(e,t){Fc(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as pt,readFileSync as qo,readdirSync as Mc,statSync as Vo}from"fs";import{join as _e}from"path";var Uc=[{cms:"strapi",deps:["strapi","@strapi/strapi","@strapi/"],envKeys:["STRAPI_URL","STRAPI_API_URL","NEXT_PUBLIC_STRAPI_URL","STRAPI_API_TOKEN"],fsMarkers:["strapi/","apps/strapi/","packages/strapi/","cms/"]},{cms:"wordpress",deps:["wpapi","wp-graphql","@wordpress/api-fetch","@wordpress/"],envKeys:["WORDPRESS_API_URL","WP_API_URL","NEXT_PUBLIC_WORDPRESS_URL"],fsMarkers:[]},{cms:"sanity",deps:["@sanity/client","next-sanity","sanity"],envKeys:["SANITY_PROJECT_ID","NEXT_PUBLIC_SANITY_PROJECT_ID","SANITY_API_TOKEN"],fsMarkers:["sanity/","studio/","sanity.config.ts","sanity.config.js"]},{cms:"contentful",deps:["contentful","@contentful/rich-text-react-renderer","@contentful/"],envKeys:["CONTENTFUL_SPACE_ID","CONTENTFUL_ACCESS_TOKEN","NEXT_PUBLIC_CONTENTFUL_SPACE_ID"],fsMarkers:[]},{cms:"ghost",deps:["@tryghost/content-api","@tryghost/"],envKeys:["GHOST_URL","GHOST_API_KEY","NEXT_PUBLIC_GHOST_URL"],fsMarkers:[]},{cms:"webflow",deps:["webflow-api"],envKeys:["WEBFLOW_API_TOKEN","WEBFLOW_SITE_ID"],fsMarkers:[]},{cms:"shopify",deps:["@shopify/hydrogen","@shopify/storefront-api-client","@shopify/shopify-api","@shopify/"],envKeys:["SHOPIFY_STOREFRONT_TOKEN","SHOPIFY_STORE_DOMAIN","SHOPIFY_ADMIN_API_TOKEN"],fsMarkers:["shopify.config.ts","shopify.config.js"]},{cms:"payload",deps:["payload","@payloadcms/next","@payloadcms/"],envKeys:["PAYLOAD_SECRET","PAYLOAD_PUBLIC_SERVER_URL"],fsMarkers:["payload.config.ts","payload.config.js"]},{cms:"directus",deps:["@directus/sdk","directus"],envKeys:["DIRECTUS_URL","DIRECTUS_TOKEN"],fsMarkers:[]}];function Bc(e){let t=_e(e,"package.json");if(!pt(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(qo(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Gc(e,t){for(let n of t)if(n.endsWith("/")){if(e.startsWith(n))return!0}else if(e===n)return!0;return!1}function Wc(e){let t={};for(let n of Te){let r=_e(e,n);if(pt(r))try{let o=qo(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function Hc(e,t){let n=_e(e,t.replace(/\/$/,""));if(!pt(n))return!1;if(t.endsWith("/"))try{return Vo(n).isDirectory()}catch{return!1}return!0}function Kc(e){let t=["content","_posts","posts",_e("src","content")];for(let n of t){let r=_e(e,n);if(pt(r))try{if(!Vo(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Mc(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(_e(s,a.name));continue}if(a.isFile()&&/\.(md|mdx)$/i.test(a.name))return{type:"directory",detail:n,source:`${n}/${a.name}`}}}}catch{}}return null}function qc(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(pt(_e(e,n.marker)))return n.path;return null}function Yo(e){let t=[],{deps:n}=Bc(e),r=Wc(e),o="none";for(let s of Uc){let a=[];for(let c of Object.keys(n))if(Gc(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(r[c]){a.push({type:"env",detail:c,source:r[c]});break}for(let c of s.fsMarkers)if(Hc(e,c)){let u=c.endsWith("/")?"directory":"file";a.push({type:u,detail:c,source:c});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Kc(e);s&&(o="mdx-local",t.push(s))}let i=qc(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as Vc,readFileSync as Yc}from"fs";import{join as zc}from"path";var zo=["openai","fal","replicate"],Me={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Jc(e){let t={};if(!Vc(e))return t;let n=Yc(e,"utf-8");for(let r of n.split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function Jo(e,t){let n={};for(let r of t){let o=process.env[r];o&&o.trim().length>0&&(n[r]={value:o,source:"process"})}for(let r of Te){let o=zc(e,r),i=Jc(o);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:r})}}return{found:n}}function me(e){let t=[].concat(...zo.map(a=>Me[a])),n=Jo(e,t),r=[];for(let a of zo)Me[a].some(c=>n.found[c])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=Me[o].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:o,matched_key:i,source:s,available_providers:r}}function Xo(e,t){let n=Jo(e,Me[t]);for(let r of Me[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Qo(){return Me}import{existsSync as Ce,readFileSync as Hn}from"fs";import{join as Ee}from"path";function Zo(e){try{return new URL(e).hostname}catch{return e}}function ei(e){let t=e.toLowerCase();return!!(t==="github.com"||t.endsWith(".github.com")||t==="gitlab.com"||t.endsWith(".gitlab.com")||t==="bitbucket.org"||t.endsWith(".bitbucket.org")||t==="dev.azure.com"||t==="visualstudio.com"||t.endsWith(".visualstudio.com")||t==="npmjs.com"||t.endsWith(".npmjs.com"))}function Xc(e){for(let t of Te){let n=Ee(e,t);if(!Ce(n))continue;let r=Hn(n,"utf-8");for(let o of to){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Zo(s);if(ei(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Qc(e){let t=Ee(e,"package.json");if(!Ce(t))return null;try{let n=JSON.parse(Hn(t,"utf-8"));if(!n.homepage)return null;let r=Zo(n.homepage);return ei(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function ti(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),Ce(Ee(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=Xc(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Qc(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=Ee(e,"package.json"),s=null;if(Ce(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Hn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||Ce(Ee(e,"shopify.config.js"))||Ce(Ee(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":Ce(Ee(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),m=u("next");d&&(m||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:m?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as nl,readFileSync as Yn,readdirSync as ri,statSync as rl}from"fs";import{join as z,sep as ol}from"path";var Zc=[/^\/admin(\/|$)/i,/^\/account(s)?(\/|$)/i,/^\/dashboard(\/|$)/i,/^\/settings(\/|$)/i,/^\/login(\/|$)/i,/^\/logout(\/|$)/i,/^\/sign[-_]?in(\/|$)/i,/^\/sign[-_]?up(\/|$)/i,/^\/register(\/|$)/i,/^\/reset[-_]?password(\/|$)/i,/^\/verify(\/|$)/i,/^\/api(\/|$)/i,/^\/_next(\/|$)/i,/^\/checkout(\/|$)/i,/^\/cart(\/|$)/i];function ft(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'").replace(/&quot;/g,'"').trim();o&&t.push(o)}return t}function Re(e){let t=e;try{t=new URL(e).pathname}catch{let n=t.indexOf("#");n!==-1&&(t=t.slice(0,n));let r=t.indexOf("?");r!==-1&&(t=t.slice(0,r))}return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t||"/"}function Ue(e){return Zc.some(t=>t.test(e))}function el(e){return e.filter(t=>Ue(Re(t)))}function tl(e,t){let n=new Set(e.map(Re)),r=[],o=new Set;for(let i of t){let s=Re(i);Ue(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function Kn(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function ni(e){let t=e.sitemapUrl||Kn(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await P(t,{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:e.fetchImpl});if(r.status=i.status,r.fetched=!0,!i.ok)return n.push({level:"error",message:`Sitemap returned HTTP ${i.status} \u2014 Google can't fetch it. Make sure ${t} serves 200.`}),r;o=await i.text()}catch(i){return n.push({level:"error",message:`Could not reach ${t} (${i instanceof Error?i.message:String(i)}). If the site isn't deployed yet, that's expected.`}),r}return/<urlset|<sitemapindex/i.test(o)?(r.urls=ft(o),r.hasLastmod=/<lastmod>/i.test(o),r.urls.length===0?(n.push({level:"error",message:"Sitemap is valid XML but contains zero <loc> URLs."}),r):(/<sitemapindex/i.test(o)&&n.push({level:"info",message:`Sitemap index with ${r.urls.length} child sitemap(s). Child URLs are not expanded by this check.`}),r.privateUrls=el(r.urls),r.privateUrls.length>0&&n.push({level:"warning",message:`${r.privateUrls.length} private/noindex URL(s) leaked into the sitemap (e.g. ${r.privateUrls.slice(0,3).map(Re).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates \u2014 adding them helps crawlers prioritize changed pages."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=tl(r.urls,e.knownUrls),r.missing.length>0&&n.push({level:"warning",message:`${r.missing.length} public page(s) in the repo are missing from the sitemap (e.g. ${r.missing.slice(0,3).join(", ")}). Add them to the generator so Google can find them.`})),r.ok=!n.some(i=>i.level==="error"),r)):(n.push({level:"error",message:`Response is not a valid XML sitemap (no <urlset>/<sitemapindex>). Got ${o.length} bytes.`}),r)}var oi=["tsx","jsx","js","mdx","md"],il=["astro","md","mdx"],sl=5e3;function ne(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=dl(i);if(c===null){r++;return}let u=n.get(c);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(c,{route:c,url:bl(t,c),in_sitemap:a,source:s})};for(let i of cl(e))al(i,o);return{pages:[...n.values()].filter(i=>!Ue(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function ii(e,t,n){let r=[];try{let s=await P(Kn(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,liveCount:0,flipped:0};r=ft(await s.text())}catch{return{checked:!1,liveCount:0,flipped:0}}if(r.length===0)return{checked:!1,liveCount:0,flipped:0};let o=new Set(r.map(Re)),i=0;for(let s of e)!s.in_sitemap&&o.has(Re(s.url||s.route))&&(s.in_sitemap=!0,i++,s.source.includes("live-sitemap")||(s.source+=", live-sitemap"));return{checked:!0,liveCount:r.length,flipped:i}}function al(e,t){for(let n of["app",z("src","app")]){let r=z(e,n);if(mt(r))for(let o of qn(r)){let i=Vn(r,o),s=i[i.length-1];hl(s)&&(i.some(a=>a.startsWith("@"))||t(pl(i.slice(0,-1)),"app router"))}}for(let n of["pages",z("src","pages")]){let r=z(e,n);if(mt(r))for(let o of qn(r)){let i=Vn(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=zn(s),c=oi.includes(a),u=il.includes(a);if(!c&&!u)continue;let d=nn(s);yl(d)||t(fl(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=z(e,n);if(mt(r))for(let o of qn(r,n==="."?1:1/0)){let i=Vn(r,o),s=i[i.length-1];zn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(ml(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=z(e,...n.split("/"));if(nl(r)){for(let o of wl(r)){let i=gl(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function cl(e){let t=[e],n=new Set([e]);for(let r of ll(e))for(let o of ul(e,r))n.has(o)||(n.add(o),t.push(o));return t}function ll(e){let t=[];try{let n=Yn(z(e,"pnpm-workspace.yaml"),"utf-8"),r=!1;for(let o of n.split(/\r?\n/)){let i=o.replace(/#.*$/,"");if(/^\s*packages\s*:/.test(i)){r=!0;continue}if(r){let s=i.match(/^\s*-\s*['"]?([^'"\s]+)['"]?\s*$/);s?t.push(s[1]):/^\S/.test(i)&&(r=!1)}}}catch{}try{let r=JSON.parse(Yn(z(e,"package.json"),"utf-8")).workspaces,o=Array.isArray(r)?r:Array.isArray(r?.packages)?r.packages:[];for(let i of o??[])typeof i=="string"&&t.push(i)}catch{}return t}function ul(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=z(e,...n.split("/").filter(Boolean));return mt(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=z(e,...o.split("/").filter(Boolean));if(!mt(i))return[];let s=[];try{for(let a of ri(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!si.has(a.name)&&(s.push(z(i,a.name)),s.length>=200))break}catch{}return s}function dl(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function pl(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function fl(e){let t=[...e],n=nn(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function ml(e){let t=[...e],n=nn(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function gl(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function hl(e){return nn(e)==="page"&&oi.includes(zn(e))}function yl(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function wl(e){try{let t=Yn(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var si=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function mt(e){try{return rl(e).isDirectory()}catch{return!1}}function*qn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=ri(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=sl)return;if(a.name.startsWith("."))continue;let c=z(o,a.name);if(a.isDirectory()){if(si.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function Vn(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ol).filter(Boolean)}function zn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function nn(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function bl(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as kl,mkdirSync as vl,readFileSync as $l,writeFileSync as Sl}from"fs";import{join as ai}from"path";function ci(e,t){let n=!1,r=t.status!==null?String(t.status):"\u2014";e.status!==r&&(e.status=r,n=!0),e.rendered!==t.rendered&&(e.rendered=t.rendered,n=!0);let o=t.rendered==="error"?"\u2014":String(t.wordCount);return e.word_count!==o&&(e.word_count=o,n=!0),n}function rn(e,t,n){let r=ai(e,w,"pages.md"),o=kl(r),i=o?_l(r):new Map;if(t.length===0&&!o)return{wrote:!1,added:0,total:0,merged:!1};let s=new Map(i),a=0,c=!1;for(let d of t){let p=ui(d.url),m=n?.get(d.url),g=s.get(p);if(g)d.in_sitemap&&g.in_sitemap!=="yes"&&(g.in_sitemap="yes",c=!0),m&&ci(g,m)&&(c=!0);else{let k={url:p,in_sitemap:d.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:ui(d.source)};m&&ci(k,m),s.set(p,k),a++,c=!0}}if(o&&!c)return{wrote:!1,added:0,total:s.size,merged:!0};let u=[...s.values()];return vl(ai(e,w),{recursive:!0}),Sl(r,xl(u),"utf-8"),{wrote:!0,added:a,total:u.length,merged:o}}function xl(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
28
28
  `),n=["# Pages","","Inventory of pages discovered in your codebase. Re-running `seoagent init`","or `seoagent refresh` re-scans and merges in newly-added pages without","touching rows you or the audit have edited. `In sitemap` is refreshed from","the live sitemap; `Status` / `Rendered` / `Word count` are filled by","`seoagent refresh --crawl` (a live fetch of each page). This file syncs to","the cloud on login."].join(`
29
29
  `),r="| URL | In sitemap | In nav | Status | Rendered | Word count | Notes |",o="|---|---|---|---|---|---|---|",i=e.map(s=>`| ${s.url} | ${s.in_sitemap} | ${s.in_nav} | ${s.status} | ${s.rendered} | ${s.word_count} | ${s.notes} |`);return[t,"",n,"",r,o,...i,""].join(`
30
- `)}function fl(e){let t=new Map,n;try{n=ul(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!Hn(r[o])||!ml(r[o+1]))continue;let i=ei(r[o]).map(a=>a.toLowerCase()),s={url:i.findIndex(a=>a.includes("url")),in_sitemap:i.findIndex(a=>a.includes("sitemap")),in_nav:i.findIndex(a=>a.includes("nav")),status:i.findIndex(a=>a.includes("status")||a.includes("http")),rendered:i.findIndex(a=>a.includes("render")),word_count:i.findIndex(a=>a.includes("word")),notes:i.findIndex(a=>a.includes("note"))};if(s.url===-1)return t;for(let a=o+2;a<r.length&&Hn(r[a]);a++){let c=ei(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Me(c,s.in_sitemap),in_nav:Me(c,s.in_nav),status:Me(c,s.status),rendered:Me(c,s.rendered),word_count:Me(c,s.word_count),notes:Me(c,s.notes)})}break}return t}function Me(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function Hn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function ml(e){let t=e.trim();return Hn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function ei(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function ti(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Be}from"@clack/prompts";var l={info:e=>Be.info(e),warn:e=>Be.warn(e),error:e=>Be.error(e),success:e=>Be.success(e),step:e=>Be.step(e),message:e=>Be.message(e)};function $(e,t,n,r=n){e?e.stop(r):l[t](n)}var ri=[{value:"saas",label:"SaaS / App"},{value:"service",label:"Service business"},{value:"product",label:"E-commerce / Product"},{value:"content",label:"Content / Blog"},{value:"marketplace",label:"Marketplace"},{value:"tool",label:"Tool / Utility"},{value:"nonprofit",label:"Nonprofit / Community"},{value:"unknown",label:"Not sure"}],Zt="unknown",bl=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function kl(e){return e.field==="context"?`${e.detail} \u2014 ${e.source}`:e.field==="domain"?`Domain: ${e.detail} \u2014 ${e.source}`:`Site type: ${e.detail} \u2014 ${e.source}`}function Qt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return bl.has(t)?t:null}async function ut(e={}){let t=process.cwd();if(oo(t)){let a=E(t),c=Ne(t);ve(t),q(t,{skill_version:A}),$e(t);let u=ii(en(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${en(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==A?`${a.skill_version} \u2192 ${A}`:A;if(l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`),!Tn()){let m=Wt(t);m&&await Ln({installId:m,event:"reinit",cliVersion:A})&&l.info(On)}return}let n=!!e.yes||!process.stdin.isTTY;n||gl("SEOAgent \u2014 AI SEO Agent");let r=qo(t,a=>l.step(a)),o=()=>{if(r.evidence.length!==0){l.info("Inferred from your project:");for(let a of r.evidence)l.info(` \u2022 ${kl(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=Qt(e.siteType)||Qt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&Qt(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&Qt(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=Zt),s||(s="unknown"),await oi(t,i,s);return}if(o(),!i){let a=await ni({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Ge(a)&&(We("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Kn({message:"What kind of site is this?",options:[...ri]});Ge(a)&&(We("Cancelled"),process.exit(0)),s=a}for(;;){let a=await wl({message:`Create .seoagent for ${i} (${s})?`});if(Ge(a)&&(We("Cancelled"),process.exit(0)),a)break;let c=await Kn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Ge(c)||c==="abort")&&(We("Cancelled"),process.exit(0)),c==="domain"){let u=await ni({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Ge(u)&&(We("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Kn({message:"What kind of site is this?",options:[...ri]});Ge(u)&&(We("Cancelled"),process.exit(0)),s=u}}await oi(t,i,s)}async function oi(e,t,n){let r=yl();r.start("Setting up your SEO project");let o=Uo(e),i=fe(e),s=In(),a={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:A,skill_version:A,install_id:s,...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}},c=Tn(),u=c?Promise.resolve(!1):Ln({installId:s,event:"init",cliVersion:A}),d=c||t===Zt?Promise.resolve(null):mo({domain:t,installId:s}),p=N(),m=p&&t!==Zt?je({apiBase:p.api_base,authHeader:`Bearer ${p.user_token}:${p.website_token}`,localDomain:t}).catch(()=>null):Promise.resolve(null);so(e),io(e,a),$e(e),No(e,n),$o(e);let g=Ne(e),b=en(e,g.skillFile),h=ii(b),v=`${h}/references/audit-checks.md`,x=g.claudeSymlink?en(e,g.claudeSymlink):void 0;ve(e);let S=t!==Zt,j={pages:[],dynamicCount:0},O={wrote:!1,added:0,total:0,merged:!1};try{j=ne(e,S?t:null),O=Xt(e,j.pages)}catch{}if(r.stop(S?`Created .seoagent/ project for ${a.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let ue=o.evidence.map(rt=>`${rt.detail} (${rt.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${ue}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&l.info(`Image generation: ${i.provider} (detected ${i.matched_key}) \u2014 articles can get AI hero images.`),j.pages.length>0){let ue=O.merged?O.added>0?`Re-scanned your codebase: +${O.added} new page${O.added===1?"":"s"} merged into .seoagent/pages.md (${O.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${O.total} pages)`:`Found ${j.pages.length} page${j.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(ue+(j.dynamicCount>0?` (plus ${j.dynamicCount} dynamic route template${j.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let[X,Z,nt]=await Promise.all([u,d,m]);if(nt?.verdict==="mismatch"&&l.warn(`Heads up: you're logged in to a SEOAgent cloud project for ${nt.cloudDomain}, but this workspace is ${t}. This workspace stays LOCAL-ONLY \u2014 nothing will be pushed to or pulled from that project. To connect ${t} to the cloud, run \`seoagent logout && seoagent login\` from this directory and pick (or create) the right site.`),Z?.status==="data"){let ue=Z.difficulty!=null?`, difficulty ${Z.difficulty}/100`:"";l.info(`Free keyword peek \u2014 "${Z.keyword}": ${Z.volume.toLocaleString("en-US")} searches/mo${ue}. You get ~10 free peeks/day: ${f('keywords --peek "<keyword>"')}`)}else Z?.status==="no-data"&&l.info(`Free keyword peek is live \u2014 no search-volume data for "${Z.keyword}" yet. Try a topic keyword (~10 free/day): ${f('keywords --peek "best <your category> tool"')}`);X&&l.info(On);let M=S?a.domain:"your site",be=S?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${a.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];hl([S?`\u2713 SEOAgent installed for ${a.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${b} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...be,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${M}`," (homepage + sitemap + robots.txt; the checks live in",` ${v} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${b} is picked up automatically.`,...x?[` Symlinked at ${x} \u2192 ${h} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
31
- `))}import{existsSync as ci}from"fs";import{intro as $l,outro as Sl,confirm as xl,isCancel as _l,cancel as Cl}from"@clack/prompts";import{existsSync as tn,rmSync as vl}from"fs";import{join as nn}from"path";function si(e,t={}){let n=[],r=nn(e,k);tn(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=nn(e,ke.CLAUDE);tn(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=nn(e,ke.AGENTS);return tn(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),xo(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:nn(e,".claude","settings.json"),kind:"hook"}),t.global&&tn(W)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:W,kind:"global"}),n}function ai(e,t){for(let n of t)n.kind==="hook"?_o(e):vl(n.path,{recursive:!0,force:!0})}async function dt(e={}){let t=process.cwd(),n=si(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&ci(W)&&l.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
32
- `);if(!r){$l("SEOAgent \u2014 uninstall"),l.message(`This will remove:
33
- ${o}`);let s=await xl({message:"Remove these and start fresh?"});if(_l(s)||!s){Cl("Cancelled \u2014 nothing was removed.");return}}ai(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
30
+ `)}function _l(e){let t=new Map,n;try{n=$l(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!Jn(r[o])||!Cl(r[o+1]))continue;let i=li(r[o]).map(a=>a.toLowerCase()),s={url:i.findIndex(a=>a.includes("url")),in_sitemap:i.findIndex(a=>a.includes("sitemap")),in_nav:i.findIndex(a=>a.includes("nav")),status:i.findIndex(a=>a.includes("status")||a.includes("http")),rendered:i.findIndex(a=>a.includes("render")),word_count:i.findIndex(a=>a.includes("word")),notes:i.findIndex(a=>a.includes("note"))};if(s.url===-1)return t;for(let a=o+2;a<r.length&&Jn(r[a]);a++){let c=li(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Be(c,s.in_sitemap),in_nav:Be(c,s.in_nav),status:Be(c,s.status),rendered:Be(c,s.rendered),word_count:Be(c,s.word_count),notes:Be(c,s.notes)})}break}return t}function Be(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function Jn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function Cl(e){let t=e.trim();return Jn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function li(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function ui(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Ge}from"@clack/prompts";var l={info:e=>Ge.info(e),warn:e=>Ge.warn(e),error:e=>Ge.error(e),success:e=>Ge.success(e),step:e=>Ge.step(e),message:e=>Ge.message(e)};function $(e,t,n,r=n){e?e.stop(r):l[t](n)}var pi=[{value:"saas",label:"SaaS / App"},{value:"service",label:"Service business"},{value:"product",label:"E-commerce / Product"},{value:"content",label:"Content / Blog"},{value:"marketplace",label:"Marketplace"},{value:"tool",label:"Tool / Utility"},{value:"nonprofit",label:"Nonprofit / Community"},{value:"unknown",label:"Not sure"}],sn="unknown",Il=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Ol(e){return e.field==="context"?`${e.detail} \u2014 ${e.source}`:e.field==="domain"?`Domain: ${e.detail} \u2014 ${e.source}`:`Site type: ${e.detail} \u2014 ${e.source}`}function on(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Il.has(t)?t:null}async function gt(e={}){let t=process.cwd();if(fo(t)){let a=R(t),c=Fe(t);Se(t),q(t,{skill_version:A}),xe(t);let u=mi(an(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${an(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==A?`${a.skill_version} \u2192 ${A}`:A;if(l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`),!Un()){let m=Yt(t);m&&await Bn({installId:m,event:"reinit",cliVersion:A})&&l.info(Mn)}return}let n=!!e.yes||!process.stdin.isTTY;n||El("SEOAgent \u2014 AI SEO Agent");let r=ti(t,a=>l.step(a)),o=()=>{if(r.evidence.length!==0){l.info("Inferred from your project:");for(let a of r.evidence)l.info(` \u2022 ${Ol(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=on(e.siteType)||on(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&on(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&on(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=sn),s||(s="unknown"),await fi(t,i,s);return}if(o(),!i){let a=await di({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});We(a)&&(He("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Xn({message:"What kind of site is this?",options:[...pi]});We(a)&&(He("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Pl({message:`Create .seoagent for ${i} (${s})?`});if(We(a)&&(He("Cancelled"),process.exit(0)),a)break;let c=await Xn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((We(c)||c==="abort")&&(He("Cancelled"),process.exit(0)),c==="domain"){let u=await di({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});We(u)&&(He("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Xn({message:"What kind of site is this?",options:[...pi]});We(u)&&(He("Cancelled"),process.exit(0)),s=u}}await fi(t,i,s)}async function fi(e,t,n){let r=Al();r.start("Setting up your SEO project");let o=Yo(e),i=me(e),s=Fn(),a={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:A,skill_version:A,install_id:s,...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}},c=Un(),u=c?Promise.resolve(!1):Bn({installId:s,event:"init",cliVersion:A}),d=c||t===sn?Promise.resolve(null):$o({domain:t,installId:s}),p=N(),m=p&&t!==sn?De({apiBase:p.api_base,authHeader:`Bearer ${p.user_token}:${p.website_token}`,localDomain:t}).catch(()=>null):Promise.resolve(null);go(e),mo(e,a),xe(e),Ko(e,n),Io(e);let g=Fe(e),k=an(e,g.skillFile),h=mi(k),v=`${h}/references/audit-checks.md`,x=g.claudeSymlink?an(e,g.claudeSymlink):void 0;Se(e);let S=t!==sn,j={pages:[],dynamicCount:0},O={wrote:!1,added:0,total:0,merged:!1};try{j=ne(e,S?t:null),O=rn(e,j.pages)}catch{}if(r.stop(S?`Created .seoagent/ project for ${a.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let de=o.evidence.map(it=>`${it.detail} (${it.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${de}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&l.info(`Image generation: ${i.provider} (detected ${i.matched_key}) \u2014 articles can get AI hero images.`),j.pages.length>0){let de=O.merged?O.added>0?`Re-scanned your codebase: +${O.added} new page${O.added===1?"":"s"} merged into .seoagent/pages.md (${O.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${O.total} pages)`:`Found ${j.pages.length} page${j.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(de+(j.dynamicCount>0?` (plus ${j.dynamicCount} dynamic route template${j.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let[X,Z,ot]=await Promise.all([u,d,m]);if(ot?.verdict==="mismatch"&&l.warn(`Heads up: you're logged in to a SEOAgent cloud project for ${ot.cloudDomain}, but this workspace is ${t}. This workspace stays LOCAL-ONLY \u2014 nothing will be pushed to or pulled from that project. To connect ${t} to the cloud, run \`seoagent logout && seoagent login\` from this directory and pick (or create) the right site.`),Z?.status==="data"){let de=Z.difficulty!=null?`, difficulty ${Z.difficulty}/100`:"";l.info(`Free keyword peek \u2014 "${Z.keyword}": ${Z.volume.toLocaleString("en-US")} searches/mo${de}. You get ~10 free peeks/day: ${f('keywords --peek "<keyword>"')}`)}else Z?.status==="no-data"&&l.info(`Free keyword peek is live \u2014 no search-volume data for "${Z.keyword}" yet. Try a topic keyword (~10 free/day): ${f('keywords --peek "best <your category> tool"')}`);X&&l.info(Mn);let U=S?a.domain:"your site",ke=S?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${a.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];Rl([S?`\u2713 SEOAgent installed for ${a.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${k} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...ke,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${U}`," (homepage + sitemap + robots.txt; the checks live in",` ${v} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${k} is picked up automatically.`,...x?[` Symlinked at ${x} \u2192 ${h} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
31
+ `))}import{existsSync as yi}from"fs";import{intro as Ll,outro as jl,confirm as Nl,isCancel as Dl,cancel as Fl}from"@clack/prompts";import{existsSync as cn,rmSync as Tl}from"fs";import{join as ln}from"path";function gi(e,t={}){let n=[],r=ln(e,w);cn(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=ln(e,ve.CLAUDE);cn(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=ln(e,ve.AGENTS);return cn(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),To(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:ln(e,".claude","settings.json"),kind:"hook"}),t.global&&cn(W)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:W,kind:"global"}),n}function hi(e,t){for(let n of t)n.kind==="hook"?Lo(e):Tl(n.path,{recursive:!0,force:!0})}async function ht(e={}){let t=process.cwd(),n=gi(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&yi(W)&&l.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
32
+ `);if(!r){Ll("SEOAgent \u2014 uninstall"),l.message(`This will remove:
33
+ ${o}`);let s=await Nl({message:"Remove these and start fresh?"});if(Dl(s)||!s){Fl("Cancelled \u2014 nothing was removed.");return}}hi(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
34
34
  `);r?l.success(`Removed:
35
- ${i}`):Sl(`Removed:
36
- ${i}`),!e.global&&ci(W)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import C from"picocolors";import{existsSync as pt,readdirSync as qn,statSync as Rl,readFileSync as li}from"fs";import{join as He}from"path";function El(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Al(e){let t=He(e,"audit","latest.md");if(!pt(t))return null;let n=Bt(t);if(!n)return null;let r=li(t,"utf-8"),o=El(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Pl(e){try{let n=li(e,"utf-8").split(/\r?\n/),r=!1,o=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){r=!0;continue}r&&o++}else if(r&&s==="")break}return o}catch{return 0}}function Il(e){let t=He(e,"strategy","clusters");if(!pt(t))return null;let n=qn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Pl(He(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Ol(e){let t=He(e,"briefs");if(!pt(t))return null;let n=qn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Tl(e){let t=He(e,"content");if(!pt(t))return null;let n=qn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Ll(e){let t=He(e,"roadmap.md");return pt(t)?{exists:!0,updatedAt:Rl(t).mtime.toISOString()}:null}function ui(e){let t=E(e);if(!t)return null;let n=it(e);return{domain:t.domain,audit:Al(n),strategy:Il(n),briefs:Ol(n),content:Tl(n),roadmap:Ll(n)}}import me from"picocolors";var jl=/\x1b\[[0-9;]*m/g;function di(e){return e.replace(jl,"").length}function D(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Nl(n,t.title),s=me.dim(`\u251C${o}\u2524`),a=me.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(Dl(u.content,r))}return c.push(a),c.join(`
37
- `)}function Nl(e,t){if(!t)return me.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=di(t),r=e-5-n;return r<1?me.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${me.dim("\u250C\u2500 ")}${t}${me.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Dl(e,t){let n=di(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${me.dim("\u2502")} ${r} ${me.dim("\u2502")}`}function Vn(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function ft(){let e=ui(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(Fl(e))}function Fl(e){if(!e)return"";let t=11,n=s=>C.dim(s.padEnd(t)),r=[];N()?(r.push({content:`${C.green("\u2713")} ${C.dim("Logged in")}`}),r.push({content:C.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${C.dim("\u25CB Not logged in")}`}),r.push({content:C.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${C.green(`last run ${Vn(e.audit.date??"")}`)} ${C.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${C.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${C.bold(C.cyan(String(e.strategy.clusterCount??0)))} ${C.dim("clusters")} \xB7 ${C.bold(C.cyan(String(e.strategy.articleCount??0)))} ${C.dim("ideas")}`:`${n("Strategy:")}${C.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${C.bold(C.cyan(String(e.briefs.count??0)))} ${C.dim("ready")}`:`${n("Briefs:")}${C.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${C.green("\u2713")} ${C.bold(C.cyan(String(e.content.count??0)))} ${C.dim("articles written")}`:`${n("Content:")}${C.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${C.green("updated")} ${C.dim(Vn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${C.dim("not yet created")}`});let i=`${C.bold(C.cyan("SEOAgent"))} ${C.dim("\xB7")} ${C.bold(e.domain)}`;return D(r,{width:78,title:i})}import{exec as Ul,spawn as pi}from"child_process";import{confirm as Ml,isCancel as Bl}from"@clack/prompts";import G from"picocolors";function Ke(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}var Gl=`https://registry.npmjs.org/${se}/latest`,mt=["free","starter","pro","scale","enterprise"],rn={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Wl(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return mt.includes(t)?t:null}function Hl(e){let t=mt.indexOf(e);return t===-1||t===mt.length-1?null:mt[t+1]}async function Kl(e,t=fetch){if(!e)return null;try{let n=(e.api_base||T.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ql(e){let t=[],r=s=>G.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${G.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${G.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of mt){let a=rn[s];s===e.current?t.push({content:`${G.bold(G.green("\u25CF"))} ${G.bold(G.green(a.padEnd(11)))} ${G.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${G.yellow("\u25C6")} ${G.bold(G.yellow(a.padEnd(11)))} ${G.yellow("next tier")}`}):t.push({content:G.dim(` ${a}`)})}let i=`${G.bold(G.cyan("SEOAgent Cloud"))} ${G.dim("\xB7")} ${G.dim("your plan")}`;return D(t,{width:55,title:i})}async function gt(){let e=N(),t=!!process.stdin.isTTY;if(e&&t){let n=await Kl(e);if(n){let r=Wl(n.plan),o=r?Hl(r):null;if(r&&l.message(ql({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${rn[r]} (highest tier).`);return}if(r&&o){let i=await Ml({message:`Upgrade from ${rn[r]} to ${rn[o]}?`});if(Bl(i)||!i){l.info("No changes.");return}}}}Vl()}function Vl(){let e=zl();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Ul(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function zl(){let e=E(process.cwd());return ee("cli-upgrade",e?.domain)}async function ht(e={}){let t=A,n=await Jl();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${se}@latest`);return}if(Ke(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!En()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${se}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${se}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${se}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await Xl()){l.error(`Update failed. Try manually: npm install -g ${se}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await Yl()||l.info("Could not run the project sweep automatically \u2014 run `seoagent refresh --all` to update all projects now (otherwise each updates itself the next time you open it in Claude Code).")}function Yl(){return new Promise(e=>{try{let t=pi("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function Jl(e=fetch){try{let t=await e(Gl,{headers:{Accept:"application/json"}});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function Xl(){return new Promise(e=>{let t=pi("npm",["install","-g",`${se}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as Ql}from"child_process";import{randomBytes as Zl}from"crypto";import{isCancel as eu,spinner as tu,text as nu}from"@clack/prompts";import ge from"picocolors";function fi(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var ru=1500,ou=300*1e3;function iu(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Ql(t,()=>{})}function su(){return Zl(16).toString("hex")}function au(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function mi(e){let t=e.trim().replace(/^https?:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"");return!t||!/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(t)?null:t.toLowerCase()}async function cu(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"}}),o=null;try{o=await r.json()}catch{}return fi(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function lu(e){return new Promise(t=>setTimeout(t,e))}async function yt(e={}){let t=process.cwd(),n=E(t),r=(e.apiBase||T.BASE||ot).replace(/\/$/,"");if(N()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await nu({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(g){if(!String(g??"").trim())return"A site URL is required.";if(!mi(String(g)))return"Please enter a valid domain like `example.com`."}});if(eu(p)){l.warn("Login cancelled.");return}let m=mi(String(p));if(m){o=m;try{q(t,{domain:m}),l.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=su(),s=au(r,i,o);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),iu(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?tu():null;c?.start(ge.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+ou,d=!0;for(;Date.now()<u;){d||await lu(ru),d=!1;let p=await cu(r,i);if(p.status==="ready"){lo({user_token:p.user_token,website_token:p.website_token,api_base:r});let m=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",g=p.email&&p.domain?`Logged in as ${ge.bold(p.email)} (${ge.cyan(p.domain)}).`:p.email?`Logged in as ${ge.bold(p.email)}.`:"Logged in.";$(c,"success",m,ge.green(g)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){$(c,"warn",`Session expired. Run \`${f("login")}\` again.`,ge.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){$(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,ge.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}$(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,ge.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function wt(){uo()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as Yd}from"@clack/prompts";import V from"picocolors";import{existsSync as sr,mkdirSync as hd,readFileSync as ns,readdirSync as yd,writeFileSync as wd}from"fs";import{createHash as bd}from"crypto";import{join as ar,relative as kd,sep as vd}from"path";import{existsSync as uu,mkdirSync as du,readdirSync as gi,readFileSync as hi,writeFileSync as pu}from"fs";import{dirname as fu,join as qe,relative as mu}from"path";var Re=e=>typeof e=="string"&&e?e:void 0;function zn(e,t){let n=qe(e,t),r;try{r=gi(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=qe(n,i),a;try{a=pe(hi(s,"utf-8")).data}catch{continue}let c=Re(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:c,title:Re(a.title)??c,draft:a.draft===!0,page_type:Re(a.page_type)??Re(a.type),path:mu(e,s)})}return o}function Yn(e){let t;try{t=gi(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=qe(e,r),i;try{i=pe(hi(o,"utf-8")).data}catch{continue}n.push({slug:Re(i.slug)??r.replace(/\.md$/,""),source:Re(i.source)??"external",repo_path:Re(i.repo_path)??null,file:o})}return n}function Jn(e,t,n){let r=new Set(t.map(s=>s.slug)),o=e.filter(s=>!s.draft&&!r.has(s.slug)),i=t.filter(s=>s.source==="repo"&&s.repo_path!==null&&!n(s.repo_path));return{toTrack:o,stale:i,alreadyTracked:t.length-i.length}}function Xn(e){return t=>uu(qe(e,t))}function Qn(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function yi(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function bt(e,t){if(t.url&&t.url.trim())return t.url.trim().replace(/\/+$/,"");if(!t.domain||t.domain==="unknown")return null;let n=t.domain.replace(/^https?:\/\//,"").replace(/\/$/,""),r=(t.blogPath||"").replace(/\/+$/,"");return`https://${n}${r}/${e}`}function kt(e){let t=["---",`slug: ${e.slug}`,`title: ${JSON.stringify(e.title)}`];e.page_type&&t.push(`page_type: ${e.page_type}`),e.canonical&&t.push(`canonical: ${e.canonical}`),t.push(`status: ${e.status}`),t.push(`source: ${e.source}`),e.repo_path&&t.push(`repo_path: ${e.repo_path}`),e.primary_keyword&&t.push(`primary_keyword: ${JSON.stringify(e.primary_keyword)}`),t.push(`tracked_at: ${e.tracked_at}`),t.push("---");let n=e.repo_path?`rendered from \`${e.repo_path}\` (the source of truth for its body)`:"rendered from its source (repo or CMS)",r=e.canonical?`
35
+ ${i}`):jl(`Removed:
36
+ ${i}`),!e.global&&yi(W)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import C from"picocolors";import{existsSync as yt,readdirSync as Qn,statSync as Ml,readFileSync as wi}from"fs";import{join as Ke}from"path";function Ul(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Bl(e){let t=Ke(e,"audit","latest.md");if(!yt(t))return null;let n=qt(t);if(!n)return null;let r=wi(t,"utf-8"),o=Ul(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Gl(e){try{let n=wi(e,"utf-8").split(/\r?\n/),r=!1,o=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){r=!0;continue}r&&o++}else if(r&&s==="")break}return o}catch{return 0}}function Wl(e){let t=Ke(e,"strategy","clusters");if(!yt(t))return null;let n=Qn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Gl(Ke(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Hl(e){let t=Ke(e,"briefs");if(!yt(t))return null;let n=Qn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Kl(e){let t=Ke(e,"content");if(!yt(t))return null;let n=Qn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function ql(e){let t=Ke(e,"roadmap.md");return yt(t)?{exists:!0,updatedAt:Ml(t).mtime.toISOString()}:null}function bi(e){let t=R(e);if(!t)return null;let n=ct(e);return{domain:t.domain,audit:Bl(n),strategy:Wl(n),briefs:Hl(n),content:Kl(n),roadmap:ql(n)}}import ge from"picocolors";var Vl=/\x1b\[[0-9;]*m/g;function ki(e){return e.replace(Vl,"").length}function D(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Yl(n,t.title),s=ge.dim(`\u251C${o}\u2524`),a=ge.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(zl(u.content,r))}return c.push(a),c.join(`
37
+ `)}function Yl(e,t){if(!t)return ge.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=ki(t),r=e-5-n;return r<1?ge.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ge.dim("\u250C\u2500 ")}${t}${ge.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function zl(e,t){let n=ki(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ge.dim("\u2502")} ${r} ${ge.dim("\u2502")}`}function Zn(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function wt(){let e=bi(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(Jl(e))}function Jl(e){if(!e)return"";let t=11,n=s=>C.dim(s.padEnd(t)),r=[];N()?(r.push({content:`${C.green("\u2713")} ${C.dim("Logged in")}`}),r.push({content:C.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${C.dim("\u25CB Not logged in")}`}),r.push({content:C.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${C.green(`last run ${Zn(e.audit.date??"")}`)} ${C.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${C.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${C.bold(C.cyan(String(e.strategy.clusterCount??0)))} ${C.dim("clusters")} \xB7 ${C.bold(C.cyan(String(e.strategy.articleCount??0)))} ${C.dim("ideas")}`:`${n("Strategy:")}${C.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${C.bold(C.cyan(String(e.briefs.count??0)))} ${C.dim("ready")}`:`${n("Briefs:")}${C.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${C.green("\u2713")} ${C.bold(C.cyan(String(e.content.count??0)))} ${C.dim("articles written")}`:`${n("Content:")}${C.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${C.green("updated")} ${C.dim(Zn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${C.dim("not yet created")}`});let i=`${C.bold(C.cyan("SEOAgent"))} ${C.dim("\xB7")} ${C.bold(e.domain)}`;return D(r,{width:78,title:i})}import{exec as Xl,spawn as vi}from"child_process";import{confirm as Ql,isCancel as Zl}from"@clack/prompts";import G from"picocolors";function qe(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}var eu=`https://registry.npmjs.org/${se}/latest`,bt=["free","starter","pro","scale","enterprise"],un={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function tu(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return bt.includes(t)?t:null}function nu(e){let t=bt.indexOf(e);return t===-1||t===bt.length-1?null:bt[t+1]}async function ru(e,t=fetch){if(!e)return null;try{let n=(e.api_base||T.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ou(e){let t=[],r=s=>G.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${G.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${G.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of bt){let a=un[s];s===e.current?t.push({content:`${G.bold(G.green("\u25CF"))} ${G.bold(G.green(a.padEnd(11)))} ${G.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${G.yellow("\u25C6")} ${G.bold(G.yellow(a.padEnd(11)))} ${G.yellow("next tier")}`}):t.push({content:G.dim(` ${a}`)})}let i=`${G.bold(G.cyan("SEOAgent Cloud"))} ${G.dim("\xB7")} ${G.dim("your plan")}`;return D(t,{width:55,title:i})}async function kt(){let e=N(),t=!!process.stdin.isTTY;if(e&&t){let n=await ru(e);if(n){let r=tu(n.plan),o=r?nu(r):null;if(r&&l.message(ou({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${un[r]} (highest tier).`);return}if(r&&o){let i=await Ql({message:`Upgrade from ${un[r]} to ${un[o]}?`});if(Zl(i)||!i){l.info("No changes.");return}}}}iu()}function iu(){let e=su();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Xl(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function su(){let e=R(process.cwd());return ee("cli-upgrade",e?.domain)}async function vt(e={}){let t=A,n=await cu();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${se}@latest`);return}if(qe(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!jn()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${se}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${se}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${se}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await lu()){l.error(`Update failed. Try manually: npm install -g ${se}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await au()||l.info("Could not run the project sweep automatically \u2014 run `seoagent refresh --all` to update all projects now (otherwise each updates itself the next time you open it in Claude Code).")}function au(){return new Promise(e=>{try{let t=vi("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function cu(e=fetch){try{let t=await e(eu,{headers:{Accept:"application/json"}});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function lu(){return new Promise(e=>{let t=vi("npm",["install","-g",`${se}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as uu}from"child_process";import{randomBytes as du}from"crypto";import{isCancel as pu,spinner as fu,text as mu}from"@clack/prompts";import he from"picocolors";function $i(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var gu=1500,hu=300*1e3;function yu(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;uu(t,()=>{})}function wu(){return du(16).toString("hex")}function bu(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Si(e){let t=e.trim().replace(/^https?:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"");return!t||!/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(t)?null:t.toLowerCase()}async function ku(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)}),o=null;try{o=await r.json()}catch{}return $i(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function vu(e){return new Promise(t=>setTimeout(t,e))}async function $t(e={}){let t=process.cwd(),n=R(t),r=(e.apiBase||T.BASE||at).replace(/\/$/,"");if(N()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await mu({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(g){if(!String(g??"").trim())return"A site URL is required.";if(!Si(String(g)))return"Please enter a valid domain like `example.com`."}});if(pu(p)){l.warn("Login cancelled.");return}let m=Si(String(p));if(m){o=m;try{q(t,{domain:m}),l.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=wu(),s=bu(r,i,o);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),yu(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?fu():null;c?.start(he.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+hu,d=!0;for(;Date.now()<u;){d||await vu(gu),d=!1;let p=await ku(r,i);if(p.status==="ready"){wo({user_token:p.user_token,website_token:p.website_token,api_base:r});let m=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",g=p.email&&p.domain?`Logged in as ${he.bold(p.email)} (${he.cyan(p.domain)}).`:p.email?`Logged in as ${he.bold(p.email)}.`:"Logged in.";$(c,"success",m,he.green(g)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){$(c,"warn",`Session expired. Run \`${f("login")}\` again.`,he.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){$(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,he.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}$(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,he.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function St(){bo()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as cp}from"@clack/prompts";import V from"picocolors";import{existsSync as pr,mkdirSync as Rd,readFileSync as ls,readdirSync as Ad,writeFileSync as Pd}from"fs";import{createHash as Id}from"crypto";import{join as fr,relative as Od,sep as Td}from"path";import{existsSync as $u,mkdirSync as Su,readdirSync as xi,readFileSync as _i,writeFileSync as xu}from"fs";import{dirname as _u,join as Ve,relative as Cu}from"path";var Ae=e=>typeof e=="string"&&e?e:void 0;function er(e,t){let n=Ve(e,t),r;try{r=xi(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=Ve(n,i),a;try{a=fe(_i(s,"utf-8")).data}catch{continue}let c=Ae(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:c,title:Ae(a.title)??c,draft:a.draft===!0,page_type:Ae(a.page_type)??Ae(a.type),path:Cu(e,s)})}return o}function tr(e){let t;try{t=xi(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Ve(e,r),i;try{i=fe(_i(o,"utf-8")).data}catch{continue}n.push({slug:Ae(i.slug)??r.replace(/\.md$/,""),source:Ae(i.source)??"external",repo_path:Ae(i.repo_path)??null,file:o})}return n}function nr(e,t,n){let r=new Set(t.map(s=>s.slug)),o=e.filter(s=>!s.draft&&!r.has(s.slug)),i=t.filter(s=>s.source==="repo"&&s.repo_path!==null&&!n(s.repo_path));return{toTrack:o,stale:i,alreadyTracked:t.length-i.length}}function rr(e){return t=>$u(Ve(e,t))}function or(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ci(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function xt(e,t){if(t.url&&t.url.trim())return t.url.trim().replace(/\/+$/,"");if(!t.domain||t.domain==="unknown")return null;let n=t.domain.replace(/^https?:\/\//,"").replace(/\/$/,""),r=(t.blogPath||"").replace(/\/+$/,"");return`https://${n}${r}/${e}`}function _t(e){let t=["---",`slug: ${e.slug}`,`title: ${JSON.stringify(e.title)}`];e.page_type&&t.push(`page_type: ${e.page_type}`),e.canonical&&t.push(`canonical: ${e.canonical}`),t.push(`status: ${e.status}`),t.push(`source: ${e.source}`),e.repo_path&&t.push(`repo_path: ${e.repo_path}`),e.primary_keyword&&t.push(`primary_keyword: ${JSON.stringify(e.primary_keyword)}`),t.push(`tracked_at: ${e.tracked_at}`),t.push("---");let n=e.repo_path?`rendered from \`${e.repo_path}\` (the source of truth for its body)`:"rendered from its source (repo or CMS)",r=e.canonical?`
38
38
 
39
39
  Live: ${e.canonical}`:"",o=[`# ${e.title}`,"",`Tracked record \u2014 this article is **${e.status}** and ${n}.`,"This is a pointer so the cloud dashboard can track it without duplicating","the body. Edit the source file to change the article."+r,""].join(`
40
40
  `);return`${t.join(`
41
41
  `)}
42
42
 
43
43
  ${o}
44
- `}function wi(e,t){let n=qe(e,k,"content"),r=Yn(n),o=new Set;for(let c of r)c.source==="repo"&&c.repo_path&&o.add(fu(c.repo_path));if(o.size===0)return{tracked:[]};let i=[...o].flatMap(c=>zn(e,c)),s=Jn(i,r,Xn(e));if(s.toTrack.length===0)return{tracked:[]};du(n,{recursive:!0});let a=[];for(let c of s.toTrack){let u=kt({slug:c.slug,title:c.title,canonical:bt(c.slug,{domain:t.domain,blogPath:t.blog_path}),status:"published",page_type:c.page_type,source:"repo",repo_path:c.path,tracked_at:new Date().toISOString()});pu(qe(n,`${c.slug}.md`),u,"utf-8"),a.push(c.slug)}return{tracked:a}}import{existsSync as er,mkdirSync as gu,readdirSync as bi,readFileSync as hu,unlinkSync as yu,writeFileSync as Zn}from"fs";import{join as ze}from"path";import U from"picocolors";function ae(e){return ze(e,k,"inbox")}function ki(e){return`${e.action_type}-${e.id}.md`}function wu(e,t){let n=0;if(!er(e))return 0;for(let r of bi(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{yu(ze(e,r)),n++}catch{}}return n}function bu(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
44
+ `}function Ei(e,t){let n=Ve(e,w,"content"),r=tr(n),o=new Set;for(let c of r)c.source==="repo"&&c.repo_path&&o.add(_u(c.repo_path));if(o.size===0)return{tracked:[]};let i=[...o].flatMap(c=>er(e,c)),s=nr(i,r,rr(e));if(s.toTrack.length===0)return{tracked:[]};Su(n,{recursive:!0});let a=[];for(let c of s.toTrack){let u=_t({slug:c.slug,title:c.title,canonical:xt(c.slug,{domain:t.domain,blogPath:t.blog_path}),status:"published",page_type:c.page_type,source:"repo",repo_path:c.path,tracked_at:new Date().toISOString()});xu(Ve(n,`${c.slug}.md`),u,"utf-8"),a.push(c.slug)}return{tracked:a}}import{existsSync as sr,mkdirSync as Eu,readdirSync as Ri,readFileSync as Ru,unlinkSync as Au,writeFileSync as ir}from"fs";import{join as ze}from"path";import M from"picocolors";function ae(e){return ze(e,w,"inbox")}function Ai(e){return`${e.action_type}-${e.id}.md`}function Pu(e,t){let n=0;if(!sr(e))return 0;for(let r of Ri(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{Au(ze(e,r)),n++}catch{}}return n}function Iu(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
45
45
  action_id: ${e.id}
46
46
  action_type: ${e.action_type}
47
47
  article_id: ${n}
@@ -84,8 +84,8 @@ positive, you disagree, etc.), close it out as failed with a reason:
84
84
  \`\`\`bash
85
85
  ${f(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
86
86
  \`\`\`
87
- `}function ku(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
88
- `)}}function vu(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function $u(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
87
+ `}function Ou(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
88
+ `)}}function Tu(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function Lu(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
89
89
  action_id: ${e.id}
90
90
  action_type: ${e.action_type}
91
91
  issue: ${r}
@@ -108,8 +108,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
108
108
 
109
109
  ## How to apply
110
110
 
111
- 1. ${vu(r,o,n)}
112
- 2. ${ku(r)}
111
+ 1. ${Tu(r,o,n)}
112
+ 2. ${Ou(r)}
113
113
  3. Show the user the diff before committing (confirm once per session, then proceed).
114
114
 
115
115
  ## How to close this out
@@ -126,7 +126,7 @@ next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
126
126
  \`\`\`bash
127
127
  ${f(`ack ${e.id}`)} --failed --reason "not applicable; ..."
128
128
  \`\`\`
129
- `}function vi(e){return e.capture_screenshots!==!0?"":`
129
+ `}function Pi(e){return e.capture_screenshots!==!0?"":`
130
130
  ## Screenshots to capture
131
131
 
132
132
  This is a **SaaS / product site**, so this page should include **real product
@@ -138,7 +138,7 @@ project's dev server \u2014 no Playwright/Puppeteer dependency, no paid API), sa
138
138
  them under \`public/screenshots/\`, and reference them with descriptive alt text.
139
139
  If you can't capture (no dev server / no screenshot tool / no real UI), leave a
140
140
  \`<!-- SCREENSHOT-TODO -->\` marker + an AI image prompt so publishing still works.
141
- `}function Su(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium",c=t.capture_screenshots===!0;return`---
141
+ `}function ju(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium",c=t.capture_screenshots===!0;return`---
142
142
  action_id: ${e.id}
143
143
  action_type: ${e.action_type}
144
144
  brief_slug: ${n??""}
@@ -163,7 +163,7 @@ is auto-generated.
163
163
  - **Role**: ${i??"(none)"}
164
164
  - **Search intent**: ${s??"(none)"}
165
165
  - **Priority**: ${a}
166
- ${vi(t)}
166
+ ${Pi(t)}
167
167
  ## How to write it
168
168
 
169
169
  1. Read the full brief \u2014 it's synced under \`.seoagent/\` (look for a briefs file
@@ -188,7 +188,7 @@ If you decide not to write it (off-strategy, duplicate, etc.), decline it:
188
188
  \`\`\`bash
189
189
  ${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
190
190
  \`\`\`
191
- `}function xu(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
191
+ `}function Nu(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
192
192
  `):"- (no metrics)";return`---
193
193
  action_id: ${e.id}
194
194
  action_type: ${e.action_type}
@@ -235,7 +235,7 @@ If you disagree (page is fine as-is, intentionally short, etc.), decline it:
235
235
  \`\`\`bash
236
236
  ${f(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
237
237
  \`\`\`
238
- `}function _u(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
238
+ `}function Du(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
239
239
  ${o.join(`
240
240
  `)}
241
241
  \`\`\`${i?`
@@ -281,7 +281,7 @@ SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exi
281
281
  \`\`\`bash
282
282
  ${f(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
283
283
  \`\`\`
284
- `}function Cu(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=t.capture_screenshots===!0,c=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
284
+ `}function Fu(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=t.capture_screenshots===!0,c=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
285
285
  action_id: ${e.id}
286
286
  action_type: ${e.action_type}
287
287
  keyword: ${n??""}
@@ -309,7 +309,7 @@ for **you** (or Claude Code reading this file) \u2014 nothing is auto-generated.
309
309
  - **Search intent**: ${s??"(unknown)"}
310
310
 
311
311
  ${e.description??""}
312
- ${vi(t)}
312
+ ${Pi(t)}
313
313
  ## How to write it
314
314
 
315
315
  1. Decide what *kind* of page this should be \u2014 a guide, comparison, listicle,
@@ -340,10 +340,10 @@ decline it:
340
340
  \`\`\`bash
341
341
  ${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
342
342
  \`\`\`
343
- `}function Ru(e){switch(e.action_type){case"cli_prune_pending":return bu(e);case"cli_technical_fix":return $u(e);case"cli_new_content":return Su(e);case"cli_content_update":return xu(e);case"cli_sitemap_update":return _u(e);case"cli_new_landing_page":return Cu(e);default:return null}}function Eu(e){if(e.length===0)return`# SEOAgent Inbox
343
+ `}function Mu(e){switch(e.action_type){case"cli_prune_pending":return Iu(e);case"cli_technical_fix":return Lu(e);case"cli_new_content":return ju(e);case"cli_content_update":return Nu(e);case"cli_sitemap_update":return Du(e);case"cli_new_landing_page":return Fu(e);default:return null}}function Uu(e){if(e.length===0)return`# SEOAgent Inbox
344
344
 
345
345
  No pending actions. Run \`seoagent sync\` later to check for new ones.
346
- `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${ki(n)}\``);return`# SEOAgent Inbox
346
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Ai(n)}\``);return`# SEOAgent Inbox
347
347
 
348
348
  You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
349
349
 
@@ -355,7 +355,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
355
355
 
356
356
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
357
357
  skill knows what to do.
358
- `}function Ee(e){let t=ae(e);if(!er(t))return[];let n=[];for(let r of bi(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",c=null,u=null,d=null,p=null,m=null,g=null;try{let b=hu(ze(t,r),"utf-8"),h=b.match(/^---\n([\s\S]*?)\n---/);if(h){let S=h[1];c=Ve(S,"severity"),u=Ve(S,"issue"),d=Ve(S,"page_url");let j=Ve(S,"priority");(j==="high"||j==="medium"||j==="low")&&(p=j),m=Ve(S,"impact_estimate"),g=Ve(S,"effort_estimate")}let x=b.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);x&&(a=x[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:d,priority:p,impact_estimate:m,effort_estimate:g})}return n.sort((r,o)=>r.id-o.id)}function Ye(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Au[e.severity??""]??U.dim,r=e.severity??"unknown",o=[U.dim("\u25B8"),U.bold(`id ${e.id}`),U.dim("\xB7"),U.cyan(t),n(r)];if(e.priority){let i=Pu[e.priority];o.push(U.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(U.dim("\xB7"),U.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(U.dim("\xB7"),U.dim(`\u23F1 ${e.effort_estimate}`)),o.push(U.dim("\u2014"),e.title),o.join(" ")}var Au={critical:e=>U.red(U.bold(e)),high:e=>U.red(e),medium:e=>U.yellow(e),low:e=>U.dim(e)},Pu={high:e=>U.red(U.bold(e)),medium:e=>U.yellow(e),low:e=>U.dim(e)};function Ve(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let r=n[1].replace(/^["']|["']$/g,"").trim();return!r||r==="null"||r==="~"?null:r}function on(e){let t=ae(e);if(!er(t))return;let n=Ee(e),r=n.length===0?`# SEOAgent Inbox
358
+ `}function Pe(e){let t=ae(e);if(!sr(t))return[];let n=[];for(let r of Ri(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",c=null,u=null,d=null,p=null,m=null,g=null;try{let k=Ru(ze(t,r),"utf-8"),h=k.match(/^---\n([\s\S]*?)\n---/);if(h){let S=h[1];c=Ye(S,"severity"),u=Ye(S,"issue"),d=Ye(S,"page_url");let j=Ye(S,"priority");(j==="high"||j==="medium"||j==="low")&&(p=j),m=Ye(S,"impact_estimate"),g=Ye(S,"effort_estimate")}let x=k.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);x&&(a=x[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:d,priority:p,impact_estimate:m,effort_estimate:g})}return n.sort((r,o)=>r.id-o.id)}function Je(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Bu[e.severity??""]??M.dim,r=e.severity??"unknown",o=[M.dim("\u25B8"),M.bold(`id ${e.id}`),M.dim("\xB7"),M.cyan(t),n(r)];if(e.priority){let i=Gu[e.priority];o.push(M.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(M.dim("\xB7"),M.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(M.dim("\xB7"),M.dim(`\u23F1 ${e.effort_estimate}`)),o.push(M.dim("\u2014"),e.title),o.join(" ")}var Bu={critical:e=>M.red(M.bold(e)),high:e=>M.red(e),medium:e=>M.yellow(e),low:e=>M.dim(e)},Gu={high:e=>M.red(M.bold(e)),medium:e=>M.yellow(e),low:e=>M.dim(e)};function Ye(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let r=n[1].replace(/^["']|["']$/g,"").trim();return!r||r==="null"||r==="~"?null:r}function dn(e){let t=ae(e);if(!sr(t))return;let n=Pe(e),r=n.length===0?`# SEOAgent Inbox
359
359
 
360
360
  No pending actions. Run \`seoagent sync\` later to check for new ones.
361
361
  `:`# SEOAgent Inbox
@@ -370,38 +370,38 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
370
370
 
371
371
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
372
372
  skill knows what to do.
373
- `;Zn(ze(t,"README.md"),r,"utf-8")}function $i(e,t){let n=ae(e);gu(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=wu(n,r),i=0;for(let s of t){let a=Ru(s);a!==null&&(Zn(ze(n,ki(s)),a,"utf-8"),i++)}return Zn(ze(n,"README.md"),Eu(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Tu}from"crypto";import{existsSync as _i,mkdirSync as Lu,readFileSync as ju,statSync as Ci,writeFileSync as xi,rmSync as Nu}from"fs";import{dirname as Du,join as tr,sep as Fu}from"path";function Iu(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Ou=[{cls:"project",test:e=>e==="project.md"},{cls:"audit",test:e=>e==="audit/latest.md"||/^audit\/(critical|high|medium|low)\.md$/.test(e)},{cls:"brief",test:e=>/^briefs\/[^/]+\.md$/.test(e)},{cls:"article",test:e=>/^content\/[^/]+\.md$/.test(e)},{cls:"cluster",test:e=>/^strategy\/clusters\/[^/]+\.md$/.test(e)},{cls:"keywords",test:e=>e==="keywords.md"||/^strategy\/keywords\/[^/]+\.md$/.test(e)},{cls:"pages",test:e=>e==="pages.md"||/^pages\/[^/]+\.md$/.test(e)},{cls:"competitors",test:e=>e==="competitors.md"},{cls:"changelog",test:e=>e==="changelog.md"}];function Si(e,t){let n=Iu(e);for(let{cls:r,test:o}of Ou)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Uu(e){return"sha256:"+Tu("sha256").update(e).digest("hex")}function Mu(e,t,n={}){let r=[];for(let o of e.artifacts){let i=t[o.path]??{exists:!1,locallyEdited:!1};if(!i.exists){r.push({path:o.path,kind:"write",body:o.body_md});continue}if(i.contentHash===o.content_hash){r.push({path:o.path,kind:"skip"});continue}if(o.generated){r.push({path:o.path,kind:"overwrite",body:o.body_md,note:i.locallyEdited?"discarded local edits \u2014 this is a cloud-generated file (edit it in the dashboard)":void 0});continue}if(i.locallyEdited&&!n.force){r.push({path:o.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}r.push({path:o.path,kind:"overwrite",body:o.body_md})}for(let o of e.deleted){let i=t[o];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){r.push({path:o,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}r.push({path:o,kind:"delete"})}}return r}function Bu(e,t,n,r){let o=new Map;for(let s of t.artifacts)o.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Si(s.path,o.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:r,cursor:n,changes:i}}async function Ri(e){let t=await Ai({apiBase:e.apiBase,authHeader:e.authHeader,since:null,fetchImpl:e.fetchImpl});if(!t.ok)return{ok:!1,error:t.error};let n=e.path.replace(/^\/+/,"").replace(/\\/g,"/"),r=t.manifest.artifacts.find(o=>o.path===n);return r?{ok:!0,body:r.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function Ei(e,t){return tr(e,t.split("/").join(Fu))}function Gu(e,t,n){let r={};for(let o of t){let i=Ei(e,o);if(!_i(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=Ci(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Uu(ju(i,"utf-8")),locallyEdited:c}}return r}async function Ai(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let r=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,error:`${r.status} ${i.slice(0,200)}`.trim()}}let o=await r.json().catch(()=>null);return!o||!Array.isArray(o.artifacts)||typeof o.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(o.deleted)||(o.deleted=[]),{ok:!0,manifest:o})}catch(r){return{ok:!1,error:r.message}}}async function Pi(e){let t=tr(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!_i(t))return{...n,ok:!0};let r=await Ai({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=Gu(t,i,e.stateFiles),a=Mu(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=Ei(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{Lu(Du(p),{recursive:!0}),xi(p,d.body??"","utf-8");let m=Ci(p);e.stateFiles[d.path]={mtime:m.mtimeMs,size:m.size},d.kind==="write"?c.written++:c.overwritten++,d.note&&c.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Nu(p,{force:!0}),delete e.stateFiles[d.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(m){c.ok=!1,c.error=`${d.path}: ${m.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=Bu(a,o,c.cursor,new Date().toISOString());if(u)try{xi(tr(t,Dt),JSON.stringify(u,null,2)+`
374
- `,"utf-8")}catch{}return c}import{existsSync as Oi,mkdirSync as Ti,readFileSync as Wu,writeFileSync as nr}from"fs";import{dirname as Li,join as Hu}from"path";var rr=1,Ii=500;function or(e){return Hu(e,k,Yr)}function sn(e){let t=or(e);if(!Oi(t))return[];try{let n=Wu(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==rr||!Array.isArray(o.entries)?[]:o.entries.filter(Ku)}catch{return[]}}function ji(e,t){let n=or(e),o=sn(e).filter(a=>a.action_id!==t.action_id);o.push({action_id:t.action_id,status:t.status,reason:t.reason,queued_at:new Date().toISOString()});let i=o.length>Ii?o.slice(-Ii):o,s={version:rr,entries:i};try{Ti(Li(n),{recursive:!0}),nr(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Ni(e,t){if(t.length===0)return;let n=or(e),r=sn(e).filter(i=>!t.includes(i.action_id)),o={version:rr,entries:r};try{if(r.length===0&&Oi(n)){nr(n,JSON.stringify(o,null,2),"utf-8");return}Ti(Li(n),{recursive:!0}),nr(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function Ku(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action_id=="number"&&(t.status==="completed"||t.status==="failed")&&(t.reason===null||typeof t.reason=="string")&&typeof t.queued_at=="string"}import{existsSync as Di,readFileSync as qu,unlinkSync as Vu,writeFileSync as zu,openSync as Yu,closeSync as Ju,mkdirSync as Xu}from"fs";import{dirname as Qu,join as Zu}from"path";var ed=6e4;function Fi(e){return Zu(e,k,Jr)}function Ui(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??ed,i=Fi(e);if(!Di(i))return an(i,r,n());let s=Bi(i);return!s||n()-s.started_at>o||!td(s.pid)?an(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function Mi(e,t={}){let n=t.pid??process.pid,r=Fi(e);if(!Di(r))return;let o=Bi(r);if(!(o&&o.pid!==n))try{Vu(r)}catch{}}function an(e,t,n){let r={pid:t,started_at:n};try{Xu(Qu(e),{recursive:!0});let o=Yu(e,"w");try{zu(o,JSON.stringify(r))}finally{Ju(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Bi(e){try{let t=qu(e,"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"&&typeof n.pid=="number"&&typeof n.started_at=="number"?n:null}catch{return null}}function td(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}import{readdirSync as nd,readFileSync as Gi,statSync as rd,writeFileSync as od,existsSync as Wi}from"fs";import{join as ir,relative as Hi,resolve as Ki,sep as Xi,posix as cn}from"path";function Je(e,t){let n=new RegExp(`^- \\*\\*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\*\\* *:?\\s*(.*)$`,"mi"),o=new RegExp(`^- \\*\\*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}:\\*\\*\\s*(.*)$`,"mi").exec(e)??n.exec(e);return o?o[1].trim():null}function Xe(e){return e!==null&&!e.startsWith("_(none")}function id(e){try{let t=new URL(e).pathname.replace(/\/+$/,"");return t===""?"/":t}catch{return"/"}}function Qi(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);return t&&/^source_render:\s*true\s*$/m.test(t[1])?!0:/SOURCE RENDER \(local dev server\)/.test(e)}function sd(e){let t=[],n=e.split(/^## /m).slice(1);for(let r of n){let o=r.split(`
375
- `,1)[0].trim();if(!/^https?:\/\//i.test(o))continue;let i=r.slice(o.length),s=!/^- Not fetched/m.test(i),a=Je(i,"JSON-LD @types present")??"",c=Xe(a)?Array.from(a.matchAll(/`([^`]+)`/g)).map(u=>u[1].toLowerCase()):[];t.push({url:o,pathname:id(o),fetched:s,titlePresent:Xe(Je(i,"title")),metaDescriptionPresent:Xe(Je(i,"meta description")),canonicalPresent:Xe(Je(i,"canonical")),jsonLdTypes:c,openGraphPresent:Xe(Je(i,"Open Graph")),twitterPresent:Xe(Je(i,"Twitter"))})}return t}var qi="CORRECTION (verify-recs)",Zi=/\b(add(?:ed|ing|s)?|implement(?:ed|ing|s)?|inject(?:ed|ing|s)?|creat(?:e|ed|ing|es)|introduc(?:e|ed|ing|es))\b/i,es=/\b(none existed|there (?:was|is|were|are) no|not present|missing|absent|lack(?:s|ed|ing)?|ha[sd] no|have no|did ?not (?:have|exist|serve)|didn'?t (?:have|exist|serve)|does ?not (?:have|exist|serve)|doesn'?t (?:have|exist|serve)|no existing)\b/i,ad=/\b(pages|posts|articles|subpages|templates|blog posts|every page|all pages)\b/i,cd=/\b(home ?page)\b/i,ld=["organization","softwareapplication","website","webpage","aboutpage","contactpage","collectionpage","profilepage","article","blogposting","newsarticle","faqpage","qapage","breadcrumblist","product","howto","itemlist","localbusiness","person","review","aggregaterating","videoobject","event","offer","service","recipe","course","jobposting"],ud=/\bjson[\s-]*ld\b|\bstructured\s+data\b|\bschema\b|@type|\bmarkup\b/i,dd=[{id:"title",re:/\btitle\s+tag\b|<title>/i,present:e=>e.titlePresent,label:"a <title> tag"},{id:"meta_description",re:/\bmeta[\s-]*description\b/i,present:e=>e.metaDescriptionPresent,label:"a meta description"},{id:"canonical",re:/\bcanonical\b/i,present:e=>e.canonicalPresent,label:"a canonical tag"},{id:"open_graph",re:/\bopen[\s-]*graph\b|\bog:[a-z]+|\bog\s+tags?\b/i,present:e=>e.openGraphPresent,label:"Open Graph tags"},{id:"twitter_card",re:/\btwitter:[a-z_]+|\btwitter\s+(card|tags?)\b/i,present:e=>e.twitterPresent,label:"a Twitter card"}];function pd(e,t,n){let r=e.toLowerCase(),o=t.filter(i=>r.includes(i.url.toLowerCase())||i.pathname!=="/"&&r.includes(i.pathname.toLowerCase()));return o.length>0?o:cd.test(e)?n?[n]:null:ad.test(e)?null:n?[n]:null}function Vi(e){return{organization:"Organization",softwareapplication:"SoftwareApplication",website:"WebSite",webpage:"WebPage",blogposting:"BlogPosting",newsarticle:"NewsArticle",faqpage:"FAQPage",breadcrumblist:"BreadcrumbList"}[e]??e.charAt(0).toUpperCase()+e.slice(1)}function fd(e){let t=/^(\s*(?:(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?|>\s+|#{1,6}\s+)?)(.*)$/.exec(e);return t?{prefix:t[1],content:t[2]}:{prefix:"",content:e}}function md(e,t){if(Qi(t))return{text:e,corrections:[]};let n=sd(t).filter(s=>s.fetched);if(n.length===0)return{text:e,corrections:[]};let r=n.find(s=>s.pathname==="/")??n[0],o=e.split(`
376
- `),i=[];for(let s=0;s<o.length;s++){let a=o[s];if(a.includes(qi)||!Zi.test(a)&&!es.test(a)&&!/\bno\b/i.test(a))continue;let c=pd(a,n,r);if(!c||c.length===0)continue;let u=[];for(let v of dd){let x=v.re.exec(a);x&&zi(a,x.index)&&c.every(S=>v.present(S))&&u.push(v.label)}let d=ud.exec(a);if(d&&zi(a,d.index)){let v=a.toLowerCase(),x=ld.filter(S=>new RegExp(`\\b${S}\\b`,"i").test(v));if(x.length>0){let S=x.filter(j=>c.every(O=>O.jsonLdTypes.includes(j)));S.length>0&&u.push(`${S.map(Vi).join(", ")} JSON-LD`)}else c.every(S=>S.jsonLdTypes.length>0)&&u.push(`JSON-LD (${Array.from(new Set(c.flatMap(S=>S.jsonLdTypes))).map(Vi).join(", ")})`)}if(u.length===0)continue;let p=u.join(" + "),m=c.map(v=>v.url).join(", "),{prefix:g,content:b}=fd(a),h=`${g}~~${b}~~ \u2192 ${qi}: the live page (${m}) already serves ${p} per evidence.md \u2014 this was a repo-source reconciliation, not a net-new addition.`;o[s]=h,i.push({line:s+1,original:a,corrected:h,entityLabel:p,pageUrl:m})}return{text:o.join(`
377
- `),corrections:i}}function zi(e,t){if(Zi.test(e)||es.test(e))return!0;let n=e.slice(Math.max(0,t-40),t);return/\bno\s+(?:\w+[\s/-]+){0,3}$/i.test(n)}var gd=cn.join(k,"audit","evidence.md");function Yi(e){let t=e.split(Xi).join("/");return t===gd||t===cn.join(k,"pages.md")||t===cn.join(k,"keywords.md")||t.startsWith(cn.join(k,"inbox")+"/")}function Ji(e){return e.split(Xi).join("/").split("/").includes(".claude")}function ts(e,t=[]){let n;try{n=nd(e)}catch{return t}for(let r of n){let o=ir(e,r),i;try{i=rd(o)}catch{continue}i.isDirectory()?ts(o,t):r.endsWith(".md")&&t.push(o)}return t}function ln(e,t={}){let n=ir(e,k,"audit","evidence.md"),r={evidenceFound:Wi(n),evidencePath:n,sourceRender:!1,scanned:[],skipped:[],corrections:[]};if(!r.evidenceFound)return r;let o=Gi(n,"utf-8");if(Qi(o))return r.sourceRender=!0,r;let i=new Map;for(let s of ts(ir(e,k))){let a=Hi(e,s);Yi(a)||Ji(a)||i.set(Ki(s),a)}for(let s of t.extraFiles??[]){let a=Ki(e,s),c=Hi(e,a);if(Yi(c)||Ji(c)){r.skipped.push(c);continue}Wi(a)?i.set(a,c):r.skipped.push(c)}for(let[s,a]of i){let c;try{c=Gi(s,"utf-8")}catch{continue}r.scanned.push(a);let{text:u,corrections:d}=md(c,o);if(d.length>0){od(s,u,"utf-8");for(let p of d)r.corrections.push({...p,file:a})}}return r}function $d(e){try{let t=ln(e);return t.evidenceFound?t:void 0}catch{return}}var Sd=new Set([".md"]),xd=new Set(["inbox"]);function _d(e){let t=[];function n(r,o){if(sr(r))for(let i of yd(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&xd.has(i.name))continue;let s=ar(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a);Sd.has(c)&&t.push(s)}}}return n(e,""),t}function rs(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ar(Rn,`${t}.json`)}function Cd(e){return bd("sha256").update(e,"utf-8").digest("hex")}function Rd(e){let t=rs(e);if(!sr(t))return{files:{},last_synced_at:null};try{return JSON.parse(ns(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Ed(e,t){hd(Rn,{recursive:!0}),wd(rs(e),JSON.stringify(t,null,2)+`
378
- `,"utf-8")}function Ad(e,t){return kd(e,t).split(vd).join("/")}async function Pd(e,t){try{let n=await P(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function Id(e,t,n){try{let r=await P(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function os(e,t={}){let n=$d(e),r=c=>n?{...c,verifyRecs:n}:c,o=N();if(!o)return r({ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]});let i=E(e);if(!i)return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(i.domain===Le)return r({ok:!0,reason:"domain-unknown",synced:0,failed:0,errors:[]});let s=ar(e,k);if(!sr(s))return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(!Ui(e).acquired)return r({ok:!0,reason:"busy",synced:0,failed:0,errors:[]});try{return r(await Od(e,t,o,i,s))}finally{Mi(e)}}async function Od(e,t,n,r,o){let i=n.api_base||T.BASE,s=`Bearer ${n.user_token}:${n.website_token}`,a=await je({apiBase:i,authHeader:s,localDomain:r.domain});if(a.verdict==="mismatch")return{ok:!0,reason:"project-mismatch",synced:0,failed:0,errors:[],cloudDomain:a.cloudDomain,localDomain:r.domain};if(a.verdict==="unverified")return{ok:!0,reason:"unverified",synced:0,failed:0,errors:[`could not verify cloud project binding: ${a.detail}`]};let c=Rd(r.domain);try{wi(e,r)}catch{}let u=_d(o),d=0,p=0,m=[],g=0,b=await Td(e,i,s);if(!t.pullOnly)for(let M of u){let be=Ad(o,M);if(t.pathFilter&&!be.endsWith(t.pathFilter))continue;let ue=ns(M,"utf-8"),rt=Cd(ue),qr=c.files[be];if(!(!qr||qr.hash!==rt)&&!t.force)continue;g++;let Cn=await Id(i,{path:be,contents:ue,domain:r.domain},s);Cn.ok?(c.files[be]={hash:rt},d++):(p++,m.push(`${be}: ${Cn.status} ${Cn.error??""}`.trim()))}let h=await Pd(i,s),v=0,x=0;if(h.ok){let M=$i(e,h.actions);v=M.wrote,x=M.removed}else h.error&&m.push(`pull actions: ${h.error}`);let S,j=!1,O=c.last_synced_at;if(!t.pushOnly){let M=await Pi({projectDir:e,apiBase:i,authHeader:s,since:c.last_synced_at,stateFiles:c.files,force:t.force});M.ok?O=M.cursor:(j=!0,M.error&&m.push(`pull: ${M.error}`)),S={written:M.written,overwritten:M.overwritten,skipped:M.skipped,conflicts:M.conflicts,deleted:M.deleted,warnings:M.warnings}}let X=!!S&&S.written+S.overwritten+S.deleted+S.conflicts>0;if(c.last_synced_at=O,Ed(r.domain,c),g===0&&v===0&&x===0&&!X&&b.flushed===0&&b.dropped===0&&!j&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:m,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:S};let nt=p===0&&!j;return{ok:nt,reason:nt?void 0:"error",synced:d,failed:p,errors:m,actionsPulled:v,actionsRemoved:x,acksFlushed:b.flushed,acksDropped:b.dropped,pull:S}}async function Td(e,t,n){let r=sn(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Ld(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Ni(e,s),{flushed:o,dropped:i}}async function Ld(e,t,n){try{let r=await P(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}function is(e){let t;try{t=E(e)}catch{return{refreshed:!1,reason:"error"}}if(!t)return{refreshed:!1,reason:"no-project"};let n=t.skill_version||t.seoagent_version||"0.0.0";if(Ke(A,n)<=0){if(!t.skill_version)try{q(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return Ne(e),q(e,{skill_version:A}),{refreshed:!0,from:n,to:A,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function cr(e){let t;try{t=E(e)}catch{return{refreshed:!1,from:null,to:A,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:A,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return Ne(e),q(e,{skill_version:A}),{refreshed:!0,from:n,to:A,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:A,reason:"error"}}}import{existsSync as jd,mkdirSync as Nd,readFileSync as Dd,writeFileSync as Fd}from"fs";var Ud="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Md=1440*60*1e3,Bd=720*60*1e3,Gd=2e3;function Wd(e,t,n=Md){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Hd(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Bd;if(!n||Ke(n,t)<=0)return null;if(r.notifiedVersion===n&&r.notifiedAt){let s=Date.parse(r.notifiedAt);if(!Number.isNaN(s)&&o.getTime()-s<i)return null}return`\u2191 SEOAgent ${n} is available (you have ${t}). Ask me to run \`seoagent update-cli\`, or run it yourself, to upgrade the CLI + all your projects.`}async function Kd(e){let t=e.readCache();if(Wd(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Hd({current:e.current,latest:t.latest,cache:t,now:e.now,notifyIntervalMs:e.notifyIntervalMs});return n&&t.latest&&e.writeCache({...t,notifiedVersion:t.latest,notifiedAt:e.now.toISOString()}),n}function qd(){try{return jd(Ft)?JSON.parse(Dd(Ft,"utf-8")):{}}catch{return{}}}function Vd(e){try{Nd(W,{recursive:!0}),Fd(Ft,JSON.stringify(e,null,2)+`
379
- `,"utf-8")}catch{}}async function zd(){try{let e=await fetch(Ud,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Gd)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function ss(e){try{return await Kd({current:e,now:new Date,fetchLatest:zd,readCache:qd,writeCache:Vd})}catch{return null}}async function z(e={}){let t=is(process.cwd());if(t.refreshed){try{ve(process.cwd())}catch{}e.silent||l.info(V.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}$e(process.cwd());let n=await ss(A);n&&l.message(V.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?Yd():null;i?.start(`${o} ${V.dim(".seoagent/")} with your dashboard\u2026`);let s=await os(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly}),a=s.verifyRecs;if(a){a.sourceRender&&l.message(V.yellow("verify-recs: evidence.md is a SOURCE RENDER (undesignated local dev-server crawl) \u2014 live-state claims cannot be verified. Re-run `seoagent crawl --url <live origin>`."));for(let d of a.corrections)l.message(V.yellow(`verify-recs: corrected ${d.file}:${d.line} \u2014 the live page (${d.pageUrl}) already serves ${d.entityLabel}; reflect this correction in your summary.`))}if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){$(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,V.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){$(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,V.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="domain-unknown"){$(i,"info","`.seoagent/project.md` has `domain: unknown` \u2014 cloud sync skipped until you set your site's domain.",V.dim("domain: unknown \u2014 cloud sync skipped.")),i&&l.info("Set `domain:` in .seoagent/project.md, then re-run sync.");return}if(s.reason==="project-mismatch"){let d=`Cloud project is ${s.cloudDomain} but this workspace is ${s.localDomain} \u2014 not syncing. Run \`${f("logout")}\` then \`${f("login")}\` from this directory to connect the right site.`;$(i,"warn",d,V.yellow(d));return}if(s.reason==="unverified"){$(i,"info","Could not verify which cloud site this login is connected to \u2014 sync skipped (nothing pushed or pulled).",V.dim("Cloud binding unverified \u2014 sync skipped.")),i&&s.errors[0]&&l.info(` \u2022 ${s.errors[0]}`);return}if(s.reason==="no-changes"){$(i,"info","Already in sync.",V.green("Already in sync."));return}if(s.reason==="busy"){$(i,"info","Another sync is in progress \u2014 skipping this run.",V.dim("Another sync is in progress \u2014 skipping this run."));return}let c=Jd(s);$(i,"success",c??"Sync complete.",V.green(c??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let u=s.pull;if(u){let d=u.written+u.overwritten;d>0&&l.success(`Pulled ${d} file${d===1?"":"s"} from the cloud`+(u.overwritten>0?` (${u.overwritten} updated)`:"")),u.deleted>0&&l.info(`Removed ${u.deleted} file${u.deleted===1?"":"s"} deleted in the cloud.`),u.conflicts>0&&l.warn(`${u.conflicts} conflict${u.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let p of u.warnings.slice(0,5))l.info(` \u2022 ${p}`)}if(s.acksFlushed&&s.acksFlushed>0&&l.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&l.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(l.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&l.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){l.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let d of s.errors.slice(0,3))l.info(` \u2022 ${d}`)}}function Jd(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,r=e.actionsPulled??0,o=e.acksFlushed??0,i=e.pull?.conflicts??0,s=[];return o>0&&s.push(`${o} ack${o===1?"":"s"} flushed`),t>0&&s.push(`${t} pushed`),n>0&&s.push(`${n} pulled`),r>0&&s.push(`${r} action${r===1?"":"s"}`),i>0&&s.push(`${i} conflict${i===1?"":"s"}`),s.length===0&&e.failed===0?null:s.length>0?s.join(" \xB7 "):"Sync complete."}function L(e){let t=E(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function Ae(e={}){if(e.print){let t=N();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=L(process.cwd());if(!n)return;let r=t.api_base||T.BASE,o=`Bearer ${t.user_token}:${t.website_token}`;if(n.domain===Le){l.warn("`.seoagent/project.md` has `domain: unknown` \u2014 set your site's domain before pulling from the cloud."),process.exitCode=1;return}let i=await je({apiBase:r,authHeader:o,localDomain:n.domain});if(i.verdict==="mismatch"){l.warn(fo(i.cloudDomain,n.domain)),process.exitCode=1;return}if(i.verdict==="unverified"){l.warn(`Could not verify which cloud site this login is connected to (${i.detail}) \u2014 not pulling.`),process.exitCode=1;return}let s=await Ri({apiBase:r,authHeader:o,path:e.print});if(!s.ok){l.warn(s.error),process.exitCode=1;return}process.stdout.write(s.body),s.body.endsWith(`
373
+ `;ir(ze(t,"README.md"),r,"utf-8")}function Ii(e,t){let n=ae(e);Eu(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Pu(n,r),i=0;for(let s of t){let a=Mu(s);a!==null&&(ir(ze(n,Ai(s)),a,"utf-8"),i++)}return ir(ze(n,"README.md"),Uu(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Ku}from"crypto";import{existsSync as Li,mkdirSync as qu,readFileSync as Vu,statSync as ji,writeFileSync as Ti,rmSync as Yu}from"fs";import{dirname as zu,join as ar,sep as Ju}from"path";function Wu(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Hu=[{cls:"project",test:e=>e==="project.md"},{cls:"audit",test:e=>e==="audit/latest.md"||/^audit\/(critical|high|medium|low)\.md$/.test(e)},{cls:"brief",test:e=>/^briefs\/[^/]+\.md$/.test(e)},{cls:"article",test:e=>/^content\/[^/]+\.md$/.test(e)},{cls:"cluster",test:e=>/^strategy\/clusters\/[^/]+\.md$/.test(e)},{cls:"keywords",test:e=>e==="keywords.md"||/^strategy\/keywords\/[^/]+\.md$/.test(e)},{cls:"pages",test:e=>e==="pages.md"||/^pages\/[^/]+\.md$/.test(e)},{cls:"competitors",test:e=>e==="competitors.md"},{cls:"changelog",test:e=>e==="changelog.md"}];function Oi(e,t){let n=Wu(e);for(let{cls:r,test:o}of Hu)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Xu(e){return"sha256:"+Ku("sha256").update(e).digest("hex")}function Qu(e,t,n={}){let r=[];for(let o of e.artifacts){let i=t[o.path]??{exists:!1,locallyEdited:!1};if(!i.exists){r.push({path:o.path,kind:"write",body:o.body_md});continue}if(i.contentHash===o.content_hash){r.push({path:o.path,kind:"skip"});continue}if(o.generated){r.push({path:o.path,kind:"overwrite",body:o.body_md,note:i.locallyEdited?"discarded local edits \u2014 this is a cloud-generated file (edit it in the dashboard)":void 0});continue}if(i.locallyEdited&&!n.force){r.push({path:o.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}r.push({path:o.path,kind:"overwrite",body:o.body_md})}for(let o of e.deleted){let i=t[o];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){r.push({path:o,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}r.push({path:o,kind:"delete"})}}return r}function Zu(e,t,n,r){let o=new Map;for(let s of t.artifacts)o.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Oi(s.path,o.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:r,cursor:n,changes:i}}async function Ni(e){let t=await Fi({apiBase:e.apiBase,authHeader:e.authHeader,since:null,fetchImpl:e.fetchImpl});if(!t.ok)return{ok:!1,error:t.error};let n=e.path.replace(/^\/+/,"").replace(/\\/g,"/"),r=t.manifest.artifacts.find(o=>o.path===n);return r?{ok:!0,body:r.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function Di(e,t){return ar(e,t.split("/").join(Ju))}function ed(e,t,n){let r={};for(let o of t){let i=Di(e,o);if(!Li(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=ji(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Xu(Vu(i,"utf-8")),locallyEdited:c}}return r}async function Fi(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let r=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,error:`${r.status} ${i.slice(0,200)}`.trim()}}let o=await r.json().catch(()=>null);return!o||!Array.isArray(o.artifacts)||typeof o.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(o.deleted)||(o.deleted=[]),{ok:!0,manifest:o})}catch(r){return{ok:!1,error:r.message}}}async function Mi(e){let t=ar(e.projectDir,w),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Li(t))return{...n,ok:!0};let r=await Fi({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=ed(t,i,e.stateFiles),a=Qu(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=Di(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{qu(zu(p),{recursive:!0}),Ti(p,d.body??"","utf-8");let m=ji(p);e.stateFiles[d.path]={mtime:m.mtimeMs,size:m.size},d.kind==="write"?c.written++:c.overwritten++,d.note&&c.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Yu(p,{force:!0}),delete e.stateFiles[d.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(m){c.ok=!1,c.error=`${d.path}: ${m.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=Zu(a,o,c.cursor,new Date().toISOString());if(u)try{Ti(ar(t,Gt),JSON.stringify(u,null,2)+`
374
+ `,"utf-8")}catch{}return c}import{existsSync as Bi,mkdirSync as Gi,readFileSync as td,writeFileSync as cr}from"fs";import{dirname as Wi,join as nd}from"path";var lr=1,Ui=500;function ur(e){return nd(e,w,ro)}function pn(e){let t=ur(e);if(!Bi(t))return[];try{let n=td(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==lr||!Array.isArray(o.entries)?[]:o.entries.filter(rd)}catch{return[]}}function Hi(e,t){let n=ur(e),o=pn(e).filter(a=>a.action_id!==t.action_id);o.push({action_id:t.action_id,status:t.status,reason:t.reason,queued_at:new Date().toISOString()});let i=o.length>Ui?o.slice(-Ui):o,s={version:lr,entries:i};try{Gi(Wi(n),{recursive:!0}),cr(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Ki(e,t){if(t.length===0)return;let n=ur(e),r=pn(e).filter(i=>!t.includes(i.action_id)),o={version:lr,entries:r};try{if(r.length===0&&Bi(n)){cr(n,JSON.stringify(o,null,2),"utf-8");return}Gi(Wi(n),{recursive:!0}),cr(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function rd(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action_id=="number"&&(t.status==="completed"||t.status==="failed")&&(t.reason===null||typeof t.reason=="string")&&typeof t.queued_at=="string"}import{existsSync as qi,readFileSync as od,unlinkSync as id,writeFileSync as sd,openSync as ad,closeSync as cd,mkdirSync as ld}from"fs";import{dirname as ud,join as dd}from"path";var pd=6e4;function Vi(e){return dd(e,w,oo)}function Yi(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??pd,i=Vi(e);if(!qi(i))return fn(i,r,n());let s=Ji(i);return!s||n()-s.started_at>o||!fd(s.pid)?fn(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function zi(e,t={}){let n=t.pid??process.pid,r=Vi(e);if(!qi(r))return;let o=Ji(r);if(!(o&&o.pid!==n))try{id(r)}catch{}}function fn(e,t,n){let r={pid:t,started_at:n};try{ld(ud(e),{recursive:!0});let o=ad(e,"w");try{sd(o,JSON.stringify(r))}finally{cd(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Ji(e){try{let t=od(e,"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"&&typeof n.pid=="number"&&typeof n.started_at=="number"?n:null}catch{return null}}function fd(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}import{readdirSync as md,readFileSync as Xi,statSync as gd,writeFileSync as hd,existsSync as Qi}from"fs";import{join as dr,relative as Zi,resolve as es,sep as is,posix as mn}from"path";function Xe(e,t){let n=new RegExp(`^- \\*\\*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\*\\* *:?\\s*(.*)$`,"mi"),o=new RegExp(`^- \\*\\*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}:\\*\\*\\s*(.*)$`,"mi").exec(e)??n.exec(e);return o?o[1].trim():null}function Qe(e){return e!==null&&!e.startsWith("_(none")}function yd(e){try{let t=new URL(e).pathname.replace(/\/+$/,"");return t===""?"/":t}catch{return"/"}}function hn(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);return t&&/^source_render:\s*true\s*$/m.test(t[1])?!0:/SOURCE RENDER \(local dev server\)/.test(e)}function wd(e){let t=[],n=e.split(/^## /m).slice(1);for(let r of n){let o=r.split(`
375
+ `,1)[0].trim();if(!/^https?:\/\//i.test(o))continue;let i=r.slice(o.length),s=!/^- Not fetched/m.test(i),a=Xe(i,"JSON-LD @types present")??"",c=Qe(a)?Array.from(a.matchAll(/`([^`]+)`/g)).map(u=>u[1].toLowerCase()):[];t.push({url:o,pathname:yd(o),fetched:s,titlePresent:Qe(Xe(i,"title")),metaDescriptionPresent:Qe(Xe(i,"meta description")),canonicalPresent:Qe(Xe(i,"canonical")),jsonLdTypes:c,openGraphPresent:Qe(Xe(i,"Open Graph")),twitterPresent:Qe(Xe(i,"Twitter"))})}return t}var gn="CORRECTION (verify-recs)",ss=/\b(add(?:ed|ing|s)?|implement(?:ed|ing|s)?|inject(?:ed|ing|s)?|creat(?:e|ed|ing|es)|introduc(?:e|ed|ing|es))\b/i,as=/\b(none existed|there (?:was|is|were|are) no|not present|missing|absent|lack(?:s|ed|ing)?|ha[sd] no|have no|did ?not (?:have|exist|serve)|didn'?t (?:have|exist|serve)|does ?not (?:have|exist|serve)|doesn'?t (?:have|exist|serve)|no existing)\b/i,bd=/\b(pages|posts|articles|subpages|templates|blog posts|every page|all pages)\b/i,kd=/\b(home ?page)\b/i,vd=["organization","softwareapplication","website","webpage","aboutpage","contactpage","collectionpage","profilepage","article","blogposting","newsarticle","faqpage","qapage","breadcrumblist","product","howto","itemlist","localbusiness","person","review","aggregaterating","videoobject","event","offer","service","recipe","course","jobposting"],$d=/\bjson[\s-]*ld\b|\bstructured\s+data\b|\bschema\b|@type|\bmarkup\b/i,Sd=[{id:"title",re:/\btitle\s+tag\b|<title>/i,present:e=>e.titlePresent,label:"a <title> tag"},{id:"meta_description",re:/\bmeta[\s-]*description\b/i,present:e=>e.metaDescriptionPresent,label:"a meta description"},{id:"canonical",re:/\bcanonical\b/i,present:e=>e.canonicalPresent,label:"a canonical tag"},{id:"open_graph",re:/\bopen[\s-]*graph\b|\bog:[a-z]+|\bog\s+tags?\b/i,present:e=>e.openGraphPresent,label:"Open Graph tags"},{id:"twitter_card",re:/\btwitter:[a-z_]+|\btwitter\s+(card|tags?)\b/i,present:e=>e.twitterPresent,label:"a Twitter card"}];function xd(e,t,n){let r=e.toLowerCase(),o=t.filter(i=>r.includes(i.url.toLowerCase())||i.pathname!=="/"&&r.includes(i.pathname.toLowerCase()));return o.length>0?o:kd.test(e)?n?[n]:null:bd.test(e)?null:n?[n]:null}function ts(e){return{organization:"Organization",softwareapplication:"SoftwareApplication",website:"WebSite",webpage:"WebPage",blogposting:"BlogPosting",newsarticle:"NewsArticle",faqpage:"FAQPage",breadcrumblist:"BreadcrumbList"}[e]??e.charAt(0).toUpperCase()+e.slice(1)}function _d(e){let t=/^(\s*(?:(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?|>\s+|#{1,6}\s+)?)(.*)$/.exec(e);return t?{prefix:t[1],content:t[2]}:{prefix:"",content:e}}function Cd(e,t){if(hn(t))return{text:e,corrections:[]};let n=wd(t).filter(s=>s.fetched);if(n.length===0)return{text:e,corrections:[]};let r=n.find(s=>s.pathname==="/")??n[0],o=e.split(`
376
+ `),i=[];for(let s=0;s<o.length;s++){let a=o[s];if(a.includes(gn)||!ss.test(a)&&!as.test(a)&&!/\bno\b/i.test(a))continue;let c=xd(a,n,r);if(!c||c.length===0)continue;let u=[];for(let v of Sd){let x=v.re.exec(a);x&&ns(a,x.index)&&c.every(S=>v.present(S))&&u.push(v.label)}let d=$d.exec(a);if(d&&ns(a,d.index)){let v=a.toLowerCase(),x=vd.filter(S=>new RegExp(`\\b${S}\\b`,"i").test(v));if(x.length>0){let S=x.filter(j=>c.every(O=>O.jsonLdTypes.includes(j)));S.length>0&&u.push(`${S.map(ts).join(", ")} JSON-LD`)}else c.every(S=>S.jsonLdTypes.length>0)&&u.push(`JSON-LD (${Array.from(new Set(c.flatMap(S=>S.jsonLdTypes))).map(ts).join(", ")})`)}if(u.length===0)continue;let p=u.join(" + "),m=c.map(v=>v.url).join(", "),{prefix:g,content:k}=_d(a),h=`${g}~~${k}~~ \u2192 ${gn}: the live page (${m}) already serves ${p} per evidence.md \u2014 this was a repo-source reconciliation, not a net-new addition.`;o[s]=h,i.push({line:s+1,original:a,corrected:h,entityLabel:p,pageUrl:m})}return{text:o.join(`
377
+ `),corrections:i}}function ns(e,t){if(ss.test(e)||as.test(e))return!0;let n=e.slice(Math.max(0,t-40),t);return/\bno\s+(?:\w+[\s/-]+){0,3}$/i.test(n)}var Ed=mn.join(w,"audit","evidence.md");function rs(e){let t=e.split(is).join("/");return t===Ed||t===mn.join(w,"pages.md")||t===mn.join(w,"keywords.md")||t.startsWith(mn.join(w,"inbox")+"/")}function os(e){return e.split(is).join("/").split("/").includes(".claude")}function cs(e,t=[]){let n;try{n=md(e)}catch{return t}for(let r of n){let o=dr(e,r),i;try{i=gd(o)}catch{continue}i.isDirectory()?cs(o,t):r.endsWith(".md")&&t.push(o)}return t}function Ze(e,t={}){let n=dr(e,w,"audit","evidence.md"),r={evidenceFound:Qi(n),evidencePath:n,sourceRender:!1,scanned:[],skipped:[],corrections:[]};if(!r.evidenceFound)return r;let o=Xi(n,"utf-8");if(hn(o))return r.sourceRender=!0,r;let i=new Map;for(let s of cs(dr(e,w))){let a=Zi(e,s);rs(a)||os(a)||i.set(es(s),a)}for(let s of t.extraFiles??[]){let a=es(e,s),c=Zi(e,a);if(rs(c)||os(c)){r.skipped.push(c);continue}Qi(a)?i.set(a,c):r.skipped.push(c)}for(let[s,a]of i){let c;try{c=Xi(s,"utf-8")}catch{continue}r.scanned.push(a);let{text:u,corrections:d}=Cd(c,o);if(d.length>0){hd(s,u,"utf-8");for(let p of d)r.corrections.push({...p,file:a})}}return r}function Ld(e){try{let t=Ze(e);return t.evidenceFound?t:void 0}catch{return}}var jd=new Set([".md"]),Nd=new Set(["inbox"]);function Dd(e){let t=[];function n(r,o){if(pr(r))for(let i of Ad(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Nd.has(i.name))continue;let s=fr(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a);jd.has(c)&&t.push(s)}}}return n(e,""),t}function us(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return fr(Ln,`${t}.json`)}function Fd(e){return Id("sha256").update(e,"utf-8").digest("hex")}function Md(e){let t=us(e);if(!pr(t))return{files:{},last_synced_at:null};try{return JSON.parse(ls(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Ud(e,t){Rd(Ln,{recursive:!0}),Pd(us(e),JSON.stringify(t,null,2)+`
378
+ `,"utf-8")}function Bd(e,t){return Od(e,t).split(Td).join("/")}async function Gd(e,t){try{let n=await P(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function Wd(e,t,n){try{let r=await P(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function ds(e,t={}){let n=Ld(e),r=c=>n?{...c,verifyRecs:n}:c,o=N();if(!o)return r({ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]});let i=R(e);if(!i)return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(i.domain===Ne)return r({ok:!0,reason:"domain-unknown",synced:0,failed:0,errors:[]});let s=fr(e,w);if(!pr(s))return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(!Yi(e).acquired)return r({ok:!0,reason:"busy",synced:0,failed:0,errors:[]});try{return r(await Hd(e,t,o,i,s))}finally{zi(e)}}async function Hd(e,t,n,r,o){let i=n.api_base||T.BASE,s=`Bearer ${n.user_token}:${n.website_token}`,a=await De({apiBase:i,authHeader:s,localDomain:r.domain});if(a.verdict==="mismatch")return{ok:!0,reason:"project-mismatch",synced:0,failed:0,errors:[],cloudDomain:a.cloudDomain,localDomain:r.domain};if(a.verdict==="unverified")return{ok:!0,reason:"unverified",synced:0,failed:0,errors:[`could not verify cloud project binding: ${a.detail}`]};let c=Md(r.domain);try{Ei(e,r)}catch{}let u=Dd(o),d=0,p=0,m=[],g=0,k=await Kd(e,i,s);if(!t.pullOnly)for(let U of u){let ke=Bd(o,U);if(t.pathFilter&&!ke.endsWith(t.pathFilter))continue;let de=ls(U,"utf-8"),it=Fd(de),eo=c.files[ke];if(!(!eo||eo.hash!==it)&&!t.force)continue;g++;let Tn=await Wd(i,{path:ke,contents:de,domain:r.domain},s);Tn.ok?(c.files[ke]={hash:it},d++):(p++,m.push(`${ke}: ${Tn.status} ${Tn.error??""}`.trim()))}let h=await Gd(i,s),v=0,x=0;if(h.ok){let U=Ii(e,h.actions);v=U.wrote,x=U.removed}else h.error&&m.push(`pull actions: ${h.error}`);let S,j=!1,O=c.last_synced_at;if(!t.pushOnly){let U=await Mi({projectDir:e,apiBase:i,authHeader:s,since:c.last_synced_at,stateFiles:c.files,force:t.force});U.ok?O=U.cursor:(j=!0,U.error&&m.push(`pull: ${U.error}`)),S={written:U.written,overwritten:U.overwritten,skipped:U.skipped,conflicts:U.conflicts,deleted:U.deleted,warnings:U.warnings}}let X=!!S&&S.written+S.overwritten+S.deleted+S.conflicts>0;if(c.last_synced_at=O,Ud(r.domain,c),g===0&&v===0&&x===0&&!X&&k.flushed===0&&k.dropped===0&&!j&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:m,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:S};let ot=p===0&&!j;return{ok:ot,reason:ot?void 0:"error",synced:d,failed:p,errors:m,actionsPulled:v,actionsRemoved:x,acksFlushed:k.flushed,acksDropped:k.dropped,pull:S}}async function Kd(e,t,n){let r=pn(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await qd(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Ki(e,s),{flushed:o,dropped:i}}async function qd(e,t,n){try{let r=await P(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}function ps(e,t=3e4){let n=setTimeout(e,t);return n.unref?.(),{cancel:()=>clearTimeout(n)}}function fs(e){let t;try{t=R(e)}catch{return{refreshed:!1,reason:"error"}}if(!t)return{refreshed:!1,reason:"no-project"};let n=t.skill_version||t.seoagent_version||"0.0.0";if(qe(A,n)<=0){if(!t.skill_version)try{q(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return Fe(e),q(e,{skill_version:A}),{refreshed:!0,from:n,to:A,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function mr(e){let t;try{t=R(e)}catch{return{refreshed:!1,from:null,to:A,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:A,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return Fe(e),q(e,{skill_version:A}),{refreshed:!0,from:n,to:A,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:A,reason:"error"}}}import{existsSync as Vd,mkdirSync as Yd,readFileSync as zd,writeFileSync as Jd}from"fs";var Xd="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Qd=1440*60*1e3,Zd=720*60*1e3,ep=2e3;function tp(e,t,n=Qd){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function np(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Zd;if(!n||qe(n,t)<=0)return null;if(r.notifiedVersion===n&&r.notifiedAt){let s=Date.parse(r.notifiedAt);if(!Number.isNaN(s)&&o.getTime()-s<i)return null}return`\u2191 SEOAgent ${n} is available (you have ${t}). Ask me to run \`seoagent update-cli\`, or run it yourself, to upgrade the CLI + all your projects.`}async function rp(e){let t=e.readCache();if(tp(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=np({current:e.current,latest:t.latest,cache:t,now:e.now,notifyIntervalMs:e.notifyIntervalMs});return n&&t.latest&&e.writeCache({...t,notifiedVersion:t.latest,notifiedAt:e.now.toISOString()}),n}function op(){try{return Vd(Wt)?JSON.parse(zd(Wt,"utf-8")):{}}catch{return{}}}function ip(e){try{Yd(W,{recursive:!0}),Jd(Wt,JSON.stringify(e,null,2)+`
379
+ `,"utf-8")}catch{}}async function sp(){try{let e=await fetch(Xd,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(ep)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function ms(e){try{return await rp({current:e,now:new Date,fetchLatest:sp,readCache:op,writeCache:ip})}catch{return null}}async function Y(e={}){let t=ps(()=>{e.silent||l.warn(`Sync gave up after ${Math.round(3e4/1e3)}s (network too slow or stalled). Sync is best-effort \u2014 nothing is lost; it will retry on the next run.`),process.exit(0)});try{await lp(e)}finally{t.cancel()}}async function lp(e){let t=fs(process.cwd());if(t.refreshed){try{Se(process.cwd())}catch{}e.silent||l.info(V.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}xe(process.cwd());let n=await ms(A);n&&l.message(V.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?cp():null;i?.start(`${o} ${V.dim(".seoagent/")} with your dashboard\u2026`);let s=await ds(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly}),a=s.verifyRecs;if(a){a.sourceRender&&l.message(V.yellow("verify-recs: evidence.md is a SOURCE RENDER (undesignated local dev-server crawl) \u2014 live-state claims cannot be verified. Re-run `seoagent crawl --url <live origin>`."));for(let d of a.corrections)l.message(V.yellow(`verify-recs: corrected ${d.file}:${d.line} \u2014 the live page (${d.pageUrl}) already serves ${d.entityLabel}; reflect this correction in your summary.`))}if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){$(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,V.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){$(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,V.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="domain-unknown"){$(i,"info","`.seoagent/project.md` has `domain: unknown` \u2014 cloud sync skipped until you set your site's domain.",V.dim("domain: unknown \u2014 cloud sync skipped.")),i&&l.info("Set `domain:` in .seoagent/project.md, then re-run sync.");return}if(s.reason==="project-mismatch"){let d=`Cloud project is ${s.cloudDomain} but this workspace is ${s.localDomain} \u2014 not syncing. Run \`${f("logout")}\` then \`${f("login")}\` from this directory to connect the right site.`;$(i,"warn",d,V.yellow(d));return}if(s.reason==="unverified"){$(i,"info","Could not verify which cloud site this login is connected to \u2014 sync skipped (nothing pushed or pulled).",V.dim("Cloud binding unverified \u2014 sync skipped.")),i&&s.errors[0]&&l.info(` \u2022 ${s.errors[0]}`);return}if(s.reason==="no-changes"){$(i,"info","Already in sync.",V.green("Already in sync."));return}if(s.reason==="busy"){$(i,"info","Another sync is in progress \u2014 skipping this run.",V.dim("Another sync is in progress \u2014 skipping this run."));return}let c=up(s);$(i,"success",c??"Sync complete.",V.green(c??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let u=s.pull;if(u){let d=u.written+u.overwritten;d>0&&l.success(`Pulled ${d} file${d===1?"":"s"} from the cloud`+(u.overwritten>0?` (${u.overwritten} updated)`:"")),u.deleted>0&&l.info(`Removed ${u.deleted} file${u.deleted===1?"":"s"} deleted in the cloud.`),u.conflicts>0&&l.warn(`${u.conflicts} conflict${u.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let p of u.warnings.slice(0,5))l.info(` \u2022 ${p}`)}if(s.acksFlushed&&s.acksFlushed>0&&l.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&l.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(l.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&l.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){l.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let d of s.errors.slice(0,3))l.info(` \u2022 ${d}`)}}function up(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,r=e.actionsPulled??0,o=e.acksFlushed??0,i=e.pull?.conflicts??0,s=[];return o>0&&s.push(`${o} ack${o===1?"":"s"} flushed`),t>0&&s.push(`${t} pushed`),n>0&&s.push(`${n} pulled`),r>0&&s.push(`${r} action${r===1?"":"s"}`),i>0&&s.push(`${i} conflict${i===1?"":"s"}`),s.length===0&&e.failed===0?null:s.length>0?s.join(" \xB7 "):"Sync complete."}function L(e){let t=R(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function Ie(e={}){if(e.print){let t=N();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=L(process.cwd());if(!n)return;let r=t.api_base||T.BASE,o=`Bearer ${t.user_token}:${t.website_token}`;if(n.domain===Ne){l.warn("`.seoagent/project.md` has `domain: unknown` \u2014 set your site's domain before pulling from the cloud."),process.exitCode=1;return}let i=await De({apiBase:r,authHeader:o,localDomain:n.domain});if(i.verdict==="mismatch"){l.warn(vo(i.cloudDomain,n.domain)),process.exitCode=1;return}if(i.verdict==="unverified"){l.warn(`Could not verify which cloud site this login is connected to (${i.detail}) \u2014 not pulling.`),process.exitCode=1;return}let s=await Ni({apiBase:r,authHeader:o,path:e.print});if(!s.ok){l.warn(s.error),process.exitCode=1;return}process.stdout.write(s.body),s.body.endsWith(`
380
380
  `)||process.stdout.write(`
381
- `);return}await z({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Xd,readdirSync as Qd,unlinkSync as Zd}from"fs";import{join as as}from"path";import{isCancel as ep,select as tp}from"@clack/prompts";async function he(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){l.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await np(),n===null)return;let r=n,o=N();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let i=o.api_base||T.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await P(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{ji(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),lr(r),on(process.cwd()),t.silent||l.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!c.ok){let u=await c.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(c.status===409&&d?.code==="already_acked"){lr(r),on(process.cwd());let b=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${b}.`);return}let p=typeof d?.code=="string"?d.code:null,m=typeof d?.error=="string"?d.error:u,g=p?`, code: ${p}`:"";l.error(`Server rejected ack (${c.status}${g}): ${m.slice(0,200)}`),process.exitCode=1;return}lr(r),on(process.cwd()),!t.silent&&(t.failed?l.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):l.success(`Action ${r} marked completed.`),l.info(` inbox location: ${as(k,"inbox")}`))}function lr(e){let t=ae(process.cwd());if(Xd(t)){for(let n of Qd(t))if(n.endsWith(`-${e}.md`))try{Zd(as(t,n))}catch{}}}async function np(){let e=process.cwd(),t=Ee(e);if(t.length===0)return l.info("No pending actions in .seoagent/inbox/."),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return l.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${f("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await tp({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Ye(r)}))});return ep(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import un from"picocolors";async function ur(e={}){let t=process.cwd();if(!e.json&&!L(t))return;let n=Ee(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:ae(t),actions:n})+`
382
- `);return}if(n.length===0){l.info(un.dim("No pending actions.")),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}l.message(`${un.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Ye(r));l.message(""),l.message(`Apply one: ${un.bold(f("ack <id>"))} \xB7 Interactive picker: ${un.bold(f("ack"))} (no id)`)}import{readFileSync as pp}from"fs";import{join as fp,relative as mp}from"path";import{confirm as ps,isCancel as pn,multiselect as gp,note as gs,select as hp}from"@clack/prompts";import y from"picocolors";import{query as yp}from"@anthropic-ai/claude-agent-sdk";import{existsSync as rp,readdirSync as op}from"fs";import{homedir as ip}from"os";import{join as sp}from"path";import{execSync as dr}from"child_process";function vt(){return process.env.ANTHROPIC_API_KEY?"env-key":process.env.CLAUDE_CODE_USE_BEDROCK==="1"||process.env.CLAUDE_CODE_USE_VERTEX==="1"||process.env.CLAUDE_CODE_USE_FOUNDRY==="1"||process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS==="1"?"enterprise":ap()?cp()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function ap(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return dr(e,{stdio:"ignore"}),!0}catch{return!1}}function cp(){let e=sp(ip(),".claude");if(!rp(e))return!1;try{return op(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function cs(){try{return dr("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function ls(){try{return dr("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var ce={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-likely":{summary:"Using your existing `claude login` session.",next:""},"claude-installed-no-session":{summary:"Claude Code is installed but you are not logged in.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, or set `ANTHROPIC_API_KEY` and re-run."},"not-installed":{summary:"Claude Code is not installed on this machine.",next:"Install it with `npm install -g @anthropic-ai/claude-code` then `claude login`, or set `ANTHROPIC_API_KEY` (get one at https://console.anthropic.com/) and re-run."}};import{marked as ds}from"marked";import{markedTerminal as lp}from"marked-terminal";import pr from"picocolors";var us=!1;function up(){us||(ds.use(lp({reflowText:!1,width:100})),us=!0)}function dn(e){if(!e)return e;up();try{let t=ds.parse(e);return typeof t=="string"?dp(t):e}catch{return e}}function dp(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>pr.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>pr.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+pr.italic(r))}async function mr(e={}){let t=process.cwd();if(!L(t))return;if(!process.stdout.isTTY&&!e.yes){l.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await Sp(e.yes)){process.exitCode=1;return}if(e.yes)await z({embedded:!0});else{let u=await hp({message:"Sync the inbox before processing?",options:[{value:"sync",label:"Sync (recommended) \u2014 pull pending actions + push local changes"},{value:"pull",label:"Pull only \u2014 get new actions, skip pushing your local changes"},{value:"skip",label:"Skip \u2014 use the current local inbox state"}],initialValue:"sync"});if(pn(u)){l.info("Cancelled.");return}u==="sync"?await z({embedded:!0}):u==="pull"&&await Ae({embedded:!0})}let r=Ee(t);if(r.length===0){l.info(y.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),l.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(g=>g.priority!==null),d=u?r.filter(g=>g.priority==="high").map(g=>g.id):r.map(g=>g.id),p=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",m=await gp({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(g=>({value:g.id,label:Ye(g)})),initialValues:d,required:!1});if(pn(m)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(m)||m.length===0){l.info("No actions selected. Nothing to do.");return}o=m}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(x=>x.id===d);if(!p)continue;wp({index:u+1,total:o.length,entry:p});let m=fp(ae(t),p.filename),g;try{g=pp(m,"utf-8")}catch(x){l.error(` Could not read ${p.filename}: ${x.message}`),a++;continue}let b=Date.now(),h=await $p({cwd:t,entry:p,actionContent:g,model:e.model}),v=fs(Date.now()-b);if(h.kind==="applied")try{await he(String(d),{silent:!0}),i++,l.message("");let x=h.summary?`
383
- `+y.dim(" "+h.summary):"";l.message(` ${y.green("\u2713")} id ${d} ${y.dim("\u2014 applied in "+v)}${x}`)}catch(x){l.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(h.kind==="declined")try{await he(String(d),{silent:!0,failed:!0,reason:h.reason}),s++,l.message(""),l.message(` ${y.yellow("\u2298")} id ${d} ${y.dim("\u2014 declined: "+Q(h.reason,100))}`)}catch(x){l.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${d} --failed --reason "${h.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${y.red("\u2717")} id ${d} ${y.dim("\u2014 agent did not converge after "+v)}`)}kp({applied:i,declined:s,failed:a,total:o.length,elapsed:fs(Date.now()-c)})}function wp(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=bp[i]??y.dim,a=[y.bold(`[${t}/${n}]`),y.dim("\xB7"),y.bold(`id ${r.id}`),y.dim("\xB7"),y.cyan(o),s(i)].join(" ");gs(r.title,a)}var bp={critical:e=>y.red(y.bold(e)),high:y.red,medium:y.yellow,low:y.dim};function kp(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?y.green(`\u2713 ${t}/${o} applied`):y.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=y.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=y.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}gs(`${a}
384
- ${y.dim("elapsed: "+i)}`,y.bold("Done"))}function fs(e){if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;if(n<60)return r>0?`${n}m ${r}s`:`${n}m`;let o=Math.floor(n/60),i=n%60;return i>0?`${o}h ${i}m`:`${o}h`}function vp(e){if(typeof e!="string"||!e)return null;let t=e.split(`
385
- `);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function $p(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Tp(n,r);try{let s=yp({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let c of s)if(c.type==="assistant"){let u=c.message.content;if(Array.isArray(u))for(let d of u)_p(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Ep(d,a)}else if(c.type==="result"){if(process.stdout.write(`
386
- `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=vp(c.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
387
- `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Sp(e){let t=vt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(y.dim(ce[t].summary)),!0;if(l.warn(ce[t].summary),l.message(` ${ce[t].next}`),e)return!1;if(t==="not-installed"){let n=await ps({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(pn(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(y.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=cs();if(!r.ok)return l.error(`Install failed: ${r.error}`),l.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=vt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await ps({message:"Run `claude login` now to sign in?",initialValue:!0});if(pn(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(y.dim("Launching `claude login`\u2026"));let r=ls();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function xp(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function _p(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&xp(e)){process.stdout.write(dn(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=Rp[o]??y.cyan,a=Op(o,i);process.stdout.write(s(Cp)+" "+y.bold(o)+y.dim("(")+a+y.dim(")")+`
381
+ `);return}await Y({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as dp,readdirSync as pp,unlinkSync as fp}from"fs";import{join as gs}from"path";import{isCancel as mp,select as gp}from"@clack/prompts";async function ye(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){l.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await hp(),n===null)return;let r=n,o=N();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let i=o.api_base||T.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await P(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{Hi(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),gr(r),dn(process.cwd()),t.silent||l.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!c.ok){let u=await c.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(c.status===409&&d?.code==="already_acked"){gr(r),dn(process.cwd());let k=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${k}.`);return}let p=typeof d?.code=="string"?d.code:null,m=typeof d?.error=="string"?d.error:u,g=p?`, code: ${p}`:"";l.error(`Server rejected ack (${c.status}${g}): ${m.slice(0,200)}`),process.exitCode=1;return}gr(r),dn(process.cwd()),!t.silent&&(t.failed?l.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):l.success(`Action ${r} marked completed.`),l.info(` inbox location: ${gs(w,"inbox")}`))}function gr(e){let t=ae(process.cwd());if(dp(t)){for(let n of pp(t))if(n.endsWith(`-${e}.md`))try{fp(gs(t,n))}catch{}}}async function hp(){let e=process.cwd(),t=Pe(e);if(t.length===0)return l.info("No pending actions in .seoagent/inbox/."),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return l.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${f("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await gp({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Je(r)}))});return mp(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import yn from"picocolors";async function hr(e={}){let t=process.cwd();if(!e.json&&!L(t))return;let n=Pe(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:ae(t),actions:n})+`
382
+ `);return}if(n.length===0){l.info(yn.dim("No pending actions.")),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}l.message(`${yn.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Je(r));l.message(""),l.message(`Apply one: ${yn.bold(f("ack <id>"))} \xB7 Interactive picker: ${yn.bold(f("ack"))} (no id)`)}import{readFileSync as Cp}from"fs";import{join as Ep,relative as Rp}from"path";import{confirm as ks,isCancel as bn,multiselect as Ap,note as Ss,select as Pp}from"@clack/prompts";import y from"picocolors";import{query as Ip}from"@anthropic-ai/claude-agent-sdk";import{existsSync as yp,readdirSync as wp}from"fs";import{homedir as bp}from"os";import{join as kp}from"path";import{execSync as yr}from"child_process";function Ct(){return process.env.ANTHROPIC_API_KEY?"env-key":process.env.CLAUDE_CODE_USE_BEDROCK==="1"||process.env.CLAUDE_CODE_USE_VERTEX==="1"||process.env.CLAUDE_CODE_USE_FOUNDRY==="1"||process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS==="1"?"enterprise":vp()?$p()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function vp(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return yr(e,{stdio:"ignore"}),!0}catch{return!1}}function $p(){let e=kp(bp(),".claude");if(!yp(e))return!1;try{return wp(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function hs(){try{return yr("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function ys(){try{return yr("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var ce={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-likely":{summary:"Using your existing `claude login` session.",next:""},"claude-installed-no-session":{summary:"Claude Code is installed but you are not logged in.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, or set `ANTHROPIC_API_KEY` and re-run."},"not-installed":{summary:"Claude Code is not installed on this machine.",next:"Install it with `npm install -g @anthropic-ai/claude-code` then `claude login`, or set `ANTHROPIC_API_KEY` (get one at https://console.anthropic.com/) and re-run."}};import{marked as bs}from"marked";import{markedTerminal as Sp}from"marked-terminal";import wr from"picocolors";var ws=!1;function xp(){ws||(bs.use(Sp({reflowText:!1,width:100})),ws=!0)}function wn(e){if(!e)return e;xp();try{let t=bs.parse(e);return typeof t=="string"?_p(t):e}catch{return e}}function _p(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>wr.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>wr.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+wr.italic(r))}async function kr(e={}){let t=process.cwd();if(!L(t))return;if(!process.stdout.isTTY&&!e.yes){l.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await Dp(e.yes)){process.exitCode=1;return}if(e.yes)await Y({embedded:!0});else{let u=await Pp({message:"Sync the inbox before processing?",options:[{value:"sync",label:"Sync (recommended) \u2014 pull pending actions + push local changes"},{value:"pull",label:"Pull only \u2014 get new actions, skip pushing your local changes"},{value:"skip",label:"Skip \u2014 use the current local inbox state"}],initialValue:"sync"});if(bn(u)){l.info("Cancelled.");return}u==="sync"?await Y({embedded:!0}):u==="pull"&&await Ie({embedded:!0})}let r=Pe(t);if(r.length===0){l.info(y.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),l.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(g=>g.priority!==null),d=u?r.filter(g=>g.priority==="high").map(g=>g.id):r.map(g=>g.id),p=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",m=await Ap({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(g=>({value:g.id,label:Je(g)})),initialValues:d,required:!1});if(bn(m)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(m)||m.length===0){l.info("No actions selected. Nothing to do.");return}o=m}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(x=>x.id===d);if(!p)continue;Op({index:u+1,total:o.length,entry:p});let m=Ep(ae(t),p.filename),g;try{g=Cp(m,"utf-8")}catch(x){l.error(` Could not read ${p.filename}: ${x.message}`),a++;continue}let k=Date.now(),h=await Np({cwd:t,entry:p,actionContent:g,model:e.model}),v=vs(Date.now()-k);if(h.kind==="applied")try{await ye(String(d),{silent:!0}),i++,l.message("");let x=h.summary?`
383
+ `+y.dim(" "+h.summary):"";l.message(` ${y.green("\u2713")} id ${d} ${y.dim("\u2014 applied in "+v)}${x}`)}catch(x){l.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(h.kind==="declined")try{await ye(String(d),{silent:!0,failed:!0,reason:h.reason}),s++,l.message(""),l.message(` ${y.yellow("\u2298")} id ${d} ${y.dim("\u2014 declined: "+Q(h.reason,100))}`)}catch(x){l.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${d} --failed --reason "${h.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${y.red("\u2717")} id ${d} ${y.dim("\u2014 agent did not converge after "+v)}`)}Lp({applied:i,declined:s,failed:a,total:o.length,elapsed:vs(Date.now()-c)})}function Op(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Tp[i]??y.dim,a=[y.bold(`[${t}/${n}]`),y.dim("\xB7"),y.bold(`id ${r.id}`),y.dim("\xB7"),y.cyan(o),s(i)].join(" ");Ss(r.title,a)}var Tp={critical:e=>y.red(y.bold(e)),high:y.red,medium:y.yellow,low:y.dim};function Lp(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?y.green(`\u2713 ${t}/${o} applied`):y.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=y.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=y.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Ss(`${a}
384
+ ${y.dim("elapsed: "+i)}`,y.bold("Done"))}function vs(e){if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;if(n<60)return r>0?`${n}m ${r}s`:`${n}m`;let o=Math.floor(n/60),i=n%60;return i>0?`${o}h ${i}m`:`${o}h`}function jp(e){if(typeof e!="string"||!e)return null;let t=e.split(`
385
+ `);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function Np(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Vp(n,r);try{let s=Ip({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let c of s)if(c.type==="assistant"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Mp(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Gp(d,a)}else if(c.type==="result"){if(process.stdout.write(`
386
+ `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=jp(c.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
387
+ `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Dp(e){let t=Ct();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(y.dim(ce[t].summary)),!0;if(l.warn(ce[t].summary),l.message(` ${ce[t].next}`),e)return!1;if(t==="not-installed"){let n=await ks({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(bn(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(y.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=hs();if(!r.ok)return l.error(`Install failed: ${r.error}`),l.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Ct()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await ks({message:"Run `claude login` now to sign in?",initialValue:!0});if(bn(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(y.dim("Launching `claude login`\u2026"));let r=ys();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Fp(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Mp(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Fp(e)){process.stdout.write(wn(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=Bp[o]??y.cyan,a=qp(o,i);process.stdout.write(s(Up)+" "+y.bold(o)+y.dim("(")+a+y.dim(")")+`
388
388
  `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(y.dim(y.italic(" "+Q(r,200)))+`
389
- `)}}var Cp="\u23FA",ms="\u23BF",Rp={Read:y.blue,Glob:y.cyan,Grep:y.cyan,Edit:y.yellow,Write:y.magenta,Bash:y.green,WebFetch:y.magenta,WebSearch:y.magenta};function Ep(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=Ap(s);if(n){process.stdout.write(y.red(` ${ms} Error`)+`
390
- `),a&&process.stdout.write(Ip(Q(a,500)," ",y.red)+`
391
- `);return}let c=Pp(i,a,o?.input);c&&process.stdout.write(y.dim(` ${ms} `)+c+`
392
- `)}function Ap(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function Pp(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
389
+ `)}}var Up="\u23FA",$s="\u23BF",Bp={Read:y.blue,Glob:y.cyan,Grep:y.cyan,Edit:y.yellow,Write:y.magenta,Bash:y.green,WebFetch:y.magenta,WebSearch:y.magenta};function Gp(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=Wp(s);if(n){process.stdout.write(y.red(` ${$s} Error`)+`
390
+ `),a&&process.stdout.write(Kp(Q(a,500)," ",y.red)+`
391
+ `);return}let c=Hp(i,a,o?.input);c&&process.stdout.write(y.dim(` ${$s} `)+c+`
392
+ `)}function Wp(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function Hp(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
393
393
  `).filter(Boolean).length;return y.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
394
394
  `).filter(o=>o.trim().length>0).length;return y.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
395
395
  `)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return y.dim(r);let o=t.split(`
396
- `).filter(i=>i.trim()).length;return y.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return y.dim(r?`${o} ${fr(String(r))}`:o)}case"Bash":{let r=t.split(`
396
+ `).filter(i=>i.trim()).length;return y.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return y.dim(r?`${o} ${br(String(r))}`:o)}case"Bash":{let r=t.split(`
397
397
  `),o=r.slice(0,5).map(u=>Q(u.trimEnd(),100)),i=r.length-5,s=o.join(`
398
398
  `)+(i>0?`
399
399
  \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...c]=s.split(`
400
400
  `);return c.length===0?y.dim(a):y.dim(a)+`
401
401
  `+y.dim(c.map(u=>" "+u).join(`
402
- `))}case"WebFetch":case"WebSearch":return y.dim(`Fetched ${Q(t.replace(/\s+/g," "),80)}`);default:return""}}function Ip(e,t,n){return e.split(`
402
+ `))}case"WebFetch":case"WebSearch":return y.dim(`Fetched ${Q(t.replace(/\s+/g," "),80)}`);default:return""}}function Kp(e,t,n){return e.split(`
403
403
  `).map(r=>n(t+r)).join(`
404
- `)}function Op(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return y.dim(Q(fr(String(n.file_path??"")),80));case"Bash":return y.dim(Q(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${fr(String(n.path))}`:"";return y.dim(Q(r+o,80))}case"Glob":return y.dim(Q(String(n.pattern??""),80));case"WebFetch":return y.dim(Q(String(n.url??""),80));case"WebSearch":return y.dim(Q(String(n.query??""),80));default:return""}}function fr(e){if(!e)return e;let t=process.cwd(),n=mp(t,e);return n.startsWith("..")?e:n||e}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Tp(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
404
+ `)}function qp(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return y.dim(Q(br(String(n.file_path??"")),80));case"Bash":return y.dim(Q(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${br(String(n.path))}`:"";return y.dim(Q(r+o,80))}case"Glob":return y.dim(Q(String(n.pattern??""),80));case"WebFetch":return y.dim(Q(String(n.url??""),80));case"WebSearch":return y.dim(Q(String(n.query??""),80));default:return""}}function br(e){if(!e)return e;let t=process.cwd(),n=Rp(t,e);return n.startsWith("..")?e:n||e}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Vp(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
405
405
 
406
406
  Your job: apply the change this action describes to the codebase at the current working directory. Read the "How to apply" section in the action file \u2014 it tells you what to do and where to look. Make the edit, then briefly state what you changed.
407
407
 
@@ -421,19 +421,19 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
421
421
  \`\`\`
422
422
  ${t}
423
423
  \`\`\`
424
- `}import{spinner as Lp}from"@clack/prompts";import _ from"picocolors";var jp=new Set(["on","off","status"]);async function $t(e,t={}){let n=(e||"").toLowerCase();if(!jp.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=N();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||T.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Lp():null,c=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(c);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(g){$(a,"error",`Network error: ${g.message}`,_.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let g=E(process.cwd()),b=ee("cli-autopilot",g?.domain);$(a,"warn","CLI autopilot is a paid feature.",_.yellow("Autopilot is a paid feature.")),l.message(Np(b)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){$(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,_.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:m}=d.autopilot;if(n==="on"){a?.stop(_.green("Autopilot enabled.")),l.message(gr({enabled:!0,deliveryMode:m,action:n}));return}if(n==="off"){a?.stop(_.dim("Autopilot disabled.")),l.message(gr({enabled:!1,deliveryMode:m,action:n}));return}a?.stop(_.dim("Status:")),l.message(gr({enabled:p,deliveryMode:m,action:n}))}function gr(e){let n=s=>_.dim(s.padEnd(11)),r=e.enabled?`${_.bold(_.green("\u25CF ON"))} ${_.dim("(queueing fixes for your coding agent)")}`:`${_.dim("\u25CB OFF")} ${_.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${_.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${_.dim("Apply queued fixes:")} ${_.cyan(f("sync"))}`}),o.push({content:`${_.dim("Turn off any time:")} ${_.cyan(f("autopilot off"))}`})):(o.push({content:`${_.dim("Enable (paid):")} ${_.cyan(f("autopilot on"))}`}),o.push({content:_.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("autopilot")}`;return D(o,{width:78,title:i})}function Np(e){let t=[{content:_.bold(_.yellow("Autopilot is a paid feature."))},{sep:!0},{content:_.dim("SEOAgent continuously audits your site and queues fixes for")},{content:_.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:_.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${_.dim("Upgrade:")} ${_.cyan(e)}`}],n=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("autopilot")}`;return D(t,{width:78,title:n})}import{mkdirSync as zp,writeFileSync as Yp}from"fs";import{join as hr}from"path";import{readdirSync as Dp,readFileSync as Fp,statSync as hs}from"fs";import{join as Up}from"path";var Mp=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Bp=new Set(["png","jpg","jpeg","gif","svg","webp","avif","ico","bmp","css","js","mjs","json","xml","txt","pdf","zip","gz","woff","woff2","ttf","eot","mp4","webm","mp3","wav","csv"]),Gp=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Wp=5e3,Hp=512*1024;function vs(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function ys(e,t){let n=(e||"").trim();if(!n||(n=n.replace(/[?#].*$/,""),!n)||/^(mailto:|tel:|javascript:|data:)/i.test(n)||n.startsWith("//"))return null;if(/^https?:\/\//i.test(n))try{let i=new URL(n),s=i.hostname.toLowerCase().replace(/^www\./,"");if(!t||s!==t)return null;n=i.pathname||"/"}catch{return null}if(!n.startsWith("/")||n.startsWith("/api/")||n==="/api")return null;let r=n.split("/").pop()||"",o=r.lastIndexOf(".");return o>0&&Bp.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var ws=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,bs=/\]\(\s*([^)\s]+)/g;function Kp(e,t){if(!e)return[];let n=vs(t),r=[],o;for(ws.lastIndex=0;(o=ws.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=ys(i,n);s&&r.push(s)}for(bs.lastIndex=0;(o=bs.exec(e))!==null;){let i=ys(o[1],n);i&&r.push(i)}return r}function qp(e,t,n=0){let r={};for(let s of e)r[s.route]=0;for(let s of t)s in r&&(r[s]+=1);let o=[],i=[];for(let s of e){if(s.route==="/")continue;let a=r[s.route]??0;a===0?o.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return o.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:o,weak:i,inboundByRoute:r,filesScanned:n}}function $s(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),r=["---","generated: false",`analyzed_at: ${new Date().toISOString()}`,`page_count: ${e.pageCount}`,`orphan_count: ${e.orphans.length}`,`weak_count: ${e.weak.length}`,`orphans_json: ${n}`,"---"].join(`
425
- `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${vs(t)})`:""}. **Orphans** are pages no other page links to \u2014 they're hard for crawlers`,"and users to reach and tend to underperform. Add relevant internal links","pointing at them (from related, higher-authority pages).","",`Scanned ${e.filesScanned} file${e.filesScanned===1?"":"s"}, ${e.linkOccurrences} internal link${e.linkOccurrences===1?"":"s"}, ${e.pageCount} page${e.pageCount===1?"":"s"}.`,"","_Note: this scans the repo, so links inside CMS-hosted content aren't counted._"].join(`
424
+ `}import{spinner as Yp}from"@clack/prompts";import _ from"picocolors";var zp=new Set(["on","off","status"]);async function Et(e,t={}){let n=(e||"").toLowerCase();if(!zp.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=N();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||T.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Yp():null,c=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(c);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}",signal:AbortSignal.timeout(1e4)})}catch(g){$(a,"error",`Network error: ${g.message}`,_.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let g=R(process.cwd()),k=ee("cli-autopilot",g?.domain);$(a,"warn","CLI autopilot is a paid feature.",_.yellow("Autopilot is a paid feature.")),l.message(Jp(k)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){$(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,_.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:m}=d.autopilot;if(n==="on"){a?.stop(_.green("Autopilot enabled.")),l.message(vr({enabled:!0,deliveryMode:m,action:n}));return}if(n==="off"){a?.stop(_.dim("Autopilot disabled.")),l.message(vr({enabled:!1,deliveryMode:m,action:n}));return}a?.stop(_.dim("Status:")),l.message(vr({enabled:p,deliveryMode:m,action:n}))}function vr(e){let n=s=>_.dim(s.padEnd(11)),r=e.enabled?`${_.bold(_.green("\u25CF ON"))} ${_.dim("(queueing fixes for your coding agent)")}`:`${_.dim("\u25CB OFF")} ${_.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${_.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${_.dim("Apply queued fixes:")} ${_.cyan(f("sync"))}`}),o.push({content:`${_.dim("Turn off any time:")} ${_.cyan(f("autopilot off"))}`})):(o.push({content:`${_.dim("Enable (paid):")} ${_.cyan(f("autopilot on"))}`}),o.push({content:_.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("autopilot")}`;return D(o,{width:78,title:i})}function Jp(e){let t=[{content:_.bold(_.yellow("Autopilot is a paid feature."))},{sep:!0},{content:_.dim("SEOAgent continuously audits your site and queues fixes for")},{content:_.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:_.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${_.dim("Upgrade:")} ${_.cyan(e)}`}],n=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("autopilot")}`;return D(t,{width:78,title:n})}import{mkdirSync as lf,writeFileSync as uf}from"fs";import{join as $r}from"path";import{readdirSync as Xp,readFileSync as Qp,statSync as xs}from"fs";import{join as Zp}from"path";var ef=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),tf=new Set(["png","jpg","jpeg","gif","svg","webp","avif","ico","bmp","css","js","mjs","json","xml","txt","pdf","zip","gz","woff","woff2","ttf","eot","mp4","webm","mp3","wav","csv"]),nf=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),rf=5e3,of=512*1024;function As(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function _s(e,t){let n=(e||"").trim();if(!n||(n=n.replace(/[?#].*$/,""),!n)||/^(mailto:|tel:|javascript:|data:)/i.test(n)||n.startsWith("//"))return null;if(/^https?:\/\//i.test(n))try{let i=new URL(n),s=i.hostname.toLowerCase().replace(/^www\./,"");if(!t||s!==t)return null;n=i.pathname||"/"}catch{return null}if(!n.startsWith("/")||n.startsWith("/api/")||n==="/api")return null;let r=n.split("/").pop()||"",o=r.lastIndexOf(".");return o>0&&tf.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Cs=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Es=/\]\(\s*([^)\s]+)/g;function sf(e,t){if(!e)return[];let n=As(t),r=[],o;for(Cs.lastIndex=0;(o=Cs.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=_s(i,n);s&&r.push(s)}for(Es.lastIndex=0;(o=Es.exec(e))!==null;){let i=_s(o[1],n);i&&r.push(i)}return r}function af(e,t,n=0){let r={};for(let s of e)r[s.route]=0;for(let s of t)s in r&&(r[s]+=1);let o=[],i=[];for(let s of e){if(s.route==="/")continue;let a=r[s.route]??0;a===0?o.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return o.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:o,weak:i,inboundByRoute:r,filesScanned:n}}function Ps(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),r=["---","generated: false",`analyzed_at: ${new Date().toISOString()}`,`page_count: ${e.pageCount}`,`orphan_count: ${e.orphans.length}`,`weak_count: ${e.weak.length}`,`orphans_json: ${n}`,"---"].join(`
425
+ `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${As(t)})`:""}. **Orphans** are pages no other page links to \u2014 they're hard for crawlers`,"and users to reach and tend to underperform. Add relevant internal links","pointing at them (from related, higher-authority pages).","",`Scanned ${e.filesScanned} file${e.filesScanned===1?"":"s"}, ${e.linkOccurrences} internal link${e.linkOccurrences===1?"":"s"}, ${e.pageCount} page${e.pageCount===1?"":"s"}.`,"","_Note: this scans the repo, so links inside CMS-hosted content aren't counted._"].join(`
426
426
  `),i=e.orphans.length===0?`## Orphan pages
427
427
 
428
- None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## Orphan pages (${e.orphans.length})`,"","No internal links point to these. Add links from related pages.","","| Page | Suggested link source (fill in) |","|---|---|",...e.orphans.map(a=>`| ${ks(a.url)} | \u2014 |`)].join(`
429
- `),s=e.weak.length===0?"":["",`## Weakly linked (${e.weak.length})`,"","Exactly one inbound internal link \u2014 fragile. Consider adding more.","","| Page | Inbound |","|---|---|",...e.weak.map(a=>`| ${ks(a.url)} | ${a.inbound} |`)].join(`
428
+ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## Orphan pages (${e.orphans.length})`,"","No internal links point to these. Add links from related pages.","","| Page | Suggested link source (fill in) |","|---|---|",...e.orphans.map(a=>`| ${Rs(a.url)} | \u2014 |`)].join(`
429
+ `),s=e.weak.length===0?"":["",`## Weakly linked (${e.weak.length})`,"","Exactly one inbound internal link \u2014 fragile. Consider adding more.","","| Page | Inbound |","|---|---|",...e.weak.map(a=>`| ${Rs(a.url)} | ${a.inbound} |`)].join(`
430
430
  `);return[r,"",o,"",i,s,""].join(`
431
- `)}function ks(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Vp(e){let t=0;function*n(r){let o;try{o=Dp(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Wp)return;if(i.name.startsWith("."))continue;let s=Up(r,i.name);if(i.isDirectory()){if(Gp.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a+1).toLowerCase();if(!Mp.has(c))continue;t++,yield s}}}yield*n(e)}function Ss(e,t){let{pages:n}=ne(e,t),r=[],o=0,i=!1;try{i=hs(e).isDirectory()}catch{i=!1}if(i)for(let s of Vp(e)){let a;try{if(hs(s).size>Hp)continue;a=Fp(s,"utf-8")}catch{continue}o++;for(let c of Kp(a,t))r.push(c)}return qp(n,r,o)}function St(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Ss(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
432
- `);return}let i=hr(t,k);zp(i,{recursive:!0});let s=hr(i,"internal-links.md");if(Yp(s,$s(o,r),"utf-8"),l.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)l.info("No orphan pages \u2014 every page has an inbound internal link.");else{l.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))l.message(` \u2022 ${a.url}`);o.orphans.length>10&&l.message(` \u2026and ${o.orphans.length-10} more`)}l.info(`Report written to ${hr(k,"internal-links.md")}`)}import{existsSync as Jp,mkdirSync as Xp,rmSync as Qp,writeFileSync as xs}from"fs";import{dirname as Zp,join as fn}from"path";import re from"picocolors";async function yr(e,t={}){if(e!=="track"&&e!=="reconcile"){l.message(`Usage:
431
+ `)}function Rs(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*cf(e){let t=0;function*n(r){let o;try{o=Xp(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=rf)return;if(i.name.startsWith("."))continue;let s=Zp(r,i.name);if(i.isDirectory()){if(nf.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a+1).toLowerCase();if(!ef.has(c))continue;t++,yield s}}}yield*n(e)}function Is(e,t){let{pages:n}=ne(e,t),r=[],o=0,i=!1;try{i=xs(e).isDirectory()}catch{i=!1}if(i)for(let s of cf(e)){let a;try{if(xs(s).size>of)continue;a=Qp(s,"utf-8")}catch{continue}o++;for(let c of sf(a,t))r.push(c)}return af(n,r,o)}function Rt(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Is(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
432
+ `);return}let i=$r(t,w);lf(i,{recursive:!0});let s=$r(i,"internal-links.md");if(uf(s,Ps(o,r),"utf-8"),l.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)l.info("No orphan pages \u2014 every page has an inbound internal link.");else{l.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))l.message(` \u2022 ${a.url}`);o.orphans.length>10&&l.message(` \u2026and ${o.orphans.length-10} more`)}l.info(`Report written to ${$r(w,"internal-links.md")}`)}import{existsSync as df,mkdirSync as pf,rmSync as ff,writeFileSync as Os}from"fs";import{dirname as mf,join as kn}from"path";import re from"picocolors";async function Sr(e,t={}){if(e!=="track"&&e!=="reconcile"){l.message(`Usage:
433
433
  ${f("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft]
434
- ${f("content reconcile")} [--dir <content-dir>] [--prune] # backfill pointers for published articles missing one`),e&&(l.error(`Unknown content action: ${e}. Actions: \`track\`, \`reconcile\`.`),process.exitCode=1);return}let n=process.cwd(),r=E(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await ef(n,r,t);return}let o=t.slug??(t.file?t.file:""),i=Qn(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=bt(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||l.warn("No live URL \u2014 pass --url, or set domain + blog_path in project.md. Tracking without a canonical URL.");let a=t.title?.trim()||yi(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=kt({slug:i,title:a,canonical:s,status:t.status?.trim()||"published",page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,source:c,repo_path:t.file?.trim()||void 0,tracked_at:new Date().toISOString()}),d=fn(n,k,"content");Xp(d,{recursive:!0});let p=fn(d,`${i}.md`),m=Jp(p);xs(p,u,"utf-8"),l.success(`${m?"Updated":"Tracked"} ${re.bold(i)}${s?` \u2192 ${re.cyan(s)}`:""} in .seoagent/content/.`);try{await z({silent:!0,pushOnly:!0})}catch{}l.message(re.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}async function ef(e,t,n){let r=fn(e,k,"content"),o=Yn(r),i=new Set;for(let c of(n.dir??"").split(",").map(u=>u.trim()).filter(Boolean))i.add(c);for(let c of o)c.source==="repo"&&c.repo_path&&i.add(Zp(c.repo_path));if(i.size===0){l.error("No content directory to scan. Pass `--dir <path>` (e.g. --dir apps/web/content/blog) \u2014 or track one article first so reconcile can infer the rest."),process.exitCode=1;return}let s=[...i].flatMap(c=>zn(e,c)),a=Jn(s,o,Xn(e));if(a.toTrack.length===0&&a.stale.length===0){l.success(`Content tracking is in sync \u2014 ${a.alreadyTracked} pointer${a.alreadyTracked===1?"":"s"} cover every published article in ${[...i].join(", ")}.`);return}for(let c of a.toTrack){let u=bt(c.slug,{domain:t.domain,blogPath:t.blog_path}),d=kt({slug:c.slug,title:c.title,canonical:u,status:"published",page_type:c.page_type,source:"repo",repo_path:c.path,tracked_at:new Date().toISOString()});xs(fn(r,`${c.slug}.md`),d,"utf-8"),l.message(`${re.green("+")} tracked ${re.bold(c.slug)}${u?re.dim(` \u2192 ${u}`):""}`)}for(let c of a.stale)n.prune?(Qp(c.file,{force:!0}),l.message(`${re.red("-")} pruned stale pointer ${re.bold(c.slug)} (source ${c.repo_path} is gone)`)):l.message(`${re.yellow("!")} stale pointer ${re.bold(c.slug)} \u2192 ${c.repo_path} no longer exists (re-run with --prune to delete)`);l.success(`Reconciled content: +${a.toTrack.length} tracked, ${a.stale.length} stale${n.prune?" (pruned)":""}.`);try{await z({silent:!0,pushOnly:!0})}catch{}}import{existsSync as br,readFileSync as Cs,statSync as tf}from"fs";import{join as kr}from"path";import wr from"picocolors";var _s=24;function nf(e){let t=[];if(e.pullReceiptCount!=null&&t.push({level:"action",code:"pull_receipt",message:`${e.pullReceiptCount} cloud change${e.pullReceiptCount===1?"":"s"} pulled but not triaged yet.`,fix:"Triage them (skill \xA7 Pull Receipt Triage), then delete .seoagent/.pull-receipt.json."}),(e.domain==="unknown"||!e.domain)&&t.push({level:"action",code:"domain_unknown",message:"Site URL is unknown \u2014 nothing works without a real domain.",fix:"Ask the user for their site URL, then set `domain:` in .seoagent/project.md."}),(e.siteType==="unknown"||!e.siteType)&&t.push({level:"action",code:"site_type_unknown",message:"Site type is unknown \u2014 strategy/briefs make worse calls without it.",fix:"WebFetch the homepage, infer the type, set `site_type:` in project.md."}),e.auditExists){let r=e.evidenceAgeHours===null,o=!r&&e.evidenceAgeHours>_s;(r||o)&&t.push({level:"action",code:"evidence_stale",message:r?"An audit exists but there is NO live-crawl evidence base (.seoagent/audit/evidence.md) \u2014 its live-state claims are ungrounded.":`The live-crawl evidence base is ${Math.round(e.evidenceAgeHours)}h old (> ${_s}h) \u2014 the live site may have changed since.`,fix:"Run `seoagent crawl` to refresh .seoagent/audit/evidence.md before asserting any live-state finding \u2014 findings must cite the evidence."})}return!(e.imageProvider&&e.imageProvider!=="none")&&e.detectedImageProvider!=="none"&&t.push({level:"action",code:"image_provider_unset",message:`Image generation is available (${e.detectedImageKey} found) but not enabled.`,fix:`Run \`${f("env-check")}\` to record image_provider, then articles can get AI hero images.`}),t.length===0&&t.push({level:"ok",code:"healthy",message:"Everything looks healthy."}),t}function rf(e,t=Date.now()){let n=kr(e,k,"audit","evidence.md");if(!br(n))return null;try{let r=Cs(n,"utf-8").slice(0,2e3),o=/^captured_at:\s*(\S+)\s*$/m.exec(r);if(o){let i=Date.parse(o[1]);if(!Number.isNaN(i))return(t-i)/36e5}return(t-tf(n).mtimeMs)/36e5}catch{return null}}function of(e){let t=kr(e,k,Dt);if(!br(t))return null;try{let n=JSON.parse(Cs(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function vr(e={}){let t=process.cwd(),n=E(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
435
- `);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=fe(t),o=nf({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:of(t),auditExists:br(kr(t,k,"audit","latest.md")),evidenceAgeHours:rf(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
436
- `);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(wr.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${wr.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${wr.dim("\u2192 "+s.fix)}`)}import oe from"picocolors";import{existsSync as Qe,mkdirSync as mn,readdirSync as sf,readFileSync as af,statSync as Qk,writeFileSync as Rs}from"fs";import{dirname as cf,join as ye,relative as lf,resolve as uf}from"path";var Ze="okf";function gn(e){return ye(e,k,Ze)}var df=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function $r(e){let t=[];for(let n of sf(e,{withFileTypes:!0})){let r=ye(e,n.name);n.isDirectory()?t.push(...$r(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function pf(e){let t=[],n=/\[[^\]]*\]\(([^)]+)\)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim().split(/\s+/)[0];o&&(/^[a-z][a-z0-9+.-]*:/i.test(o)||o.startsWith("#")||t.push(o))}return t}function Es(e){let t=[],n=[];if(!Qe(e))return{ok:!1,fileCount:0,errors:[{file:Ze,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=$r(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Ze,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Qe(ye(e,"index.md"))||n.push({file:Ze,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=lf(e,i),a;try{a=pe(af(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let c=a.data.type;(c==null||String(c).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!df.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of pf(a.body)){let m=p.split("#")[0];if(!m)continue;let g=uf(cf(i),m);Qe(g)||t.push({file:s,message:`Broken link \u2192 "${p}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function hn(e){let t=gn(e);if(!Qe(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:$r(t).length}}catch{return{exists:!0,fileCount:0}}}function As(e,t){let n=gn(e);mn(n,{recursive:!0}),mn(ye(n,"concepts"),{recursive:!0}),mn(ye(n,"faqs"),{recursive:!0}),mn(ye(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=ye(n,"index.md");Qe(i)||(Rs(i,`---
434
+ ${f("content reconcile")} [--dir <content-dir>] [--prune] # backfill pointers for published articles missing one`),e&&(l.error(`Unknown content action: ${e}. Actions: \`track\`, \`reconcile\`.`),process.exitCode=1);return}let n=process.cwd(),r=R(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await gf(n,r,t);return}let o=t.slug??(t.file?t.file:""),i=or(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=xt(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||l.warn("No live URL \u2014 pass --url, or set domain + blog_path in project.md. Tracking without a canonical URL.");let a=t.title?.trim()||Ci(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=_t({slug:i,title:a,canonical:s,status:t.status?.trim()||"published",page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,source:c,repo_path:t.file?.trim()||void 0,tracked_at:new Date().toISOString()}),d=kn(n,w,"content");pf(d,{recursive:!0});let p=kn(d,`${i}.md`),m=df(p);Os(p,u,"utf-8"),l.success(`${m?"Updated":"Tracked"} ${re.bold(i)}${s?` \u2192 ${re.cyan(s)}`:""} in .seoagent/content/.`);try{await Y({silent:!0,pushOnly:!0})}catch{}l.message(re.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}async function gf(e,t,n){let r=kn(e,w,"content"),o=tr(r),i=new Set;for(let c of(n.dir??"").split(",").map(u=>u.trim()).filter(Boolean))i.add(c);for(let c of o)c.source==="repo"&&c.repo_path&&i.add(mf(c.repo_path));if(i.size===0){l.error("No content directory to scan. Pass `--dir <path>` (e.g. --dir apps/web/content/blog) \u2014 or track one article first so reconcile can infer the rest."),process.exitCode=1;return}let s=[...i].flatMap(c=>er(e,c)),a=nr(s,o,rr(e));if(a.toTrack.length===0&&a.stale.length===0){l.success(`Content tracking is in sync \u2014 ${a.alreadyTracked} pointer${a.alreadyTracked===1?"":"s"} cover every published article in ${[...i].join(", ")}.`);return}for(let c of a.toTrack){let u=xt(c.slug,{domain:t.domain,blogPath:t.blog_path}),d=_t({slug:c.slug,title:c.title,canonical:u,status:"published",page_type:c.page_type,source:"repo",repo_path:c.path,tracked_at:new Date().toISOString()});Os(kn(r,`${c.slug}.md`),d,"utf-8"),l.message(`${re.green("+")} tracked ${re.bold(c.slug)}${u?re.dim(` \u2192 ${u}`):""}`)}for(let c of a.stale)n.prune?(ff(c.file,{force:!0}),l.message(`${re.red("-")} pruned stale pointer ${re.bold(c.slug)} (source ${c.repo_path} is gone)`)):l.message(`${re.yellow("!")} stale pointer ${re.bold(c.slug)} \u2192 ${c.repo_path} no longer exists (re-run with --prune to delete)`);l.success(`Reconciled content: +${a.toTrack.length} tracked, ${a.stale.length} stale${n.prune?" (pruned)":""}.`);try{await Y({silent:!0,pushOnly:!0})}catch{}}import{existsSync as _r,readFileSync as Ls,statSync as hf}from"fs";import{join as Cr}from"path";import xr from"picocolors";var Ts=24;function yf(e){let t=[];if(e.pullReceiptCount!=null&&t.push({level:"action",code:"pull_receipt",message:`${e.pullReceiptCount} cloud change${e.pullReceiptCount===1?"":"s"} pulled but not triaged yet.`,fix:"Triage them (skill \xA7 Pull Receipt Triage), then delete .seoagent/.pull-receipt.json."}),(e.domain==="unknown"||!e.domain)&&t.push({level:"action",code:"domain_unknown",message:"Site URL is unknown \u2014 nothing works without a real domain.",fix:"Ask the user for their site URL, then set `domain:` in .seoagent/project.md."}),(e.siteType==="unknown"||!e.siteType)&&t.push({level:"action",code:"site_type_unknown",message:"Site type is unknown \u2014 strategy/briefs make worse calls without it.",fix:"WebFetch the homepage, infer the type, set `site_type:` in project.md."}),e.auditExists){let r=e.evidenceAgeHours===null,o=!r&&e.evidenceAgeHours>Ts;(r||o)&&t.push({level:"action",code:"evidence_stale",message:r?"An audit exists but there is NO live-crawl evidence base (.seoagent/audit/evidence.md) \u2014 its live-state claims are ungrounded.":`The live-crawl evidence base is ${Math.round(e.evidenceAgeHours)}h old (> ${Ts}h) \u2014 the live site may have changed since.`,fix:"Run `seoagent crawl` to refresh .seoagent/audit/evidence.md before asserting any live-state finding \u2014 findings must cite the evidence."})}if((e.hookTimeoutMissingCount??0)>0){let r=e.hookTimeoutMissingCount;t.push({level:"action",code:"hook_timeout_missing",message:`${r} SEOAgent hook entr${r===1?"y":"ies"} in .claude/settings.json ha${r===1?"s":"ve"} no timeout \u2014 a stalled sync could wedge the session.`,fix:"Run `seoagent init` (safe re-run) \u2014 it rewrites the hook entries with an explicit 60s timeout."})}return!(e.imageProvider&&e.imageProvider!=="none")&&e.detectedImageProvider!=="none"&&t.push({level:"action",code:"image_provider_unset",message:`Image generation is available (${e.detectedImageKey} found) but not enabled.`,fix:`Run \`${f("env-check")}\` to record image_provider, then articles can get AI hero images.`}),t.length===0&&t.push({level:"ok",code:"healthy",message:"Everything looks healthy."}),t}function wf(e,t=Date.now()){let n=Cr(e,w,"audit","evidence.md");if(!_r(n))return null;try{let r=Ls(n,"utf-8").slice(0,2e3),o=/^captured_at:\s*(\S+)\s*$/m.exec(r);if(o){let i=Date.parse(o[1]);if(!Number.isNaN(i))return(t-i)/36e5}return(t-hf(n).mtimeMs)/36e5}catch{return null}}function bf(e){let t=Cr(e,w,Gt);if(!_r(t))return null;try{let n=JSON.parse(Ls(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function Er(e={}){let t=process.cwd(),n=R(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
435
+ `);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=me(t),o=yf({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:bf(t),auditExists:_r(Cr(t,w,"audit","latest.md")),evidenceAgeHours:wf(t),hookTimeoutMissingCount:Oo(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
436
+ `);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(xr.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${xr.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${xr.dim("\u2192 "+s.fix)}`)}import oe from"picocolors";import{existsSync as et,mkdirSync as vn,readdirSync as kf,readFileSync as vf,statSync as Iv,writeFileSync as js}from"fs";import{dirname as $f,join as we,relative as Sf,resolve as xf}from"path";var tt="okf";function $n(e){return we(e,w,tt)}var _f=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function Rr(e){let t=[];for(let n of kf(e,{withFileTypes:!0})){let r=we(e,n.name);n.isDirectory()?t.push(...Rr(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Cf(e){let t=[],n=/\[[^\]]*\]\(([^)]+)\)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim().split(/\s+/)[0];o&&(/^[a-z][a-z0-9+.-]*:/i.test(o)||o.startsWith("#")||t.push(o))}return t}function Ns(e){let t=[],n=[];if(!et(e))return{ok:!1,fileCount:0,errors:[{file:tt,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=Rr(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:tt,message:"OKF directory exists but contains no markdown files."}],warnings:[]};et(we(e,"index.md"))||n.push({file:tt,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Sf(e,i),a;try{a=fe(vf(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let c=a.data.type;(c==null||String(c).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!_f.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of Cf(a.body)){let m=p.split("#")[0];if(!m)continue;let g=xf($f(i),m);et(g)||t.push({file:s,message:`Broken link \u2192 "${p}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function Sn(e){let t=$n(e);if(!et(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:Rr(t).length}}catch{return{exists:!0,fileCount:0}}}function Ds(e,t){let n=$n(e);vn(n,{recursive:!0}),vn(we(n,"concepts"),{recursive:!0}),vn(we(n,"faqs"),{recursive:!0}),vn(we(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=we(n,"index.md");et(i)||(js(i,`---
437
437
  type: Organization
438
438
  title: ${o}
439
439
  description: Knowledge bundle describing ${o} for AI agents and answer engines.
@@ -460,7 +460,7 @@ _Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`
460
460
  ## Published articles
461
461
 
462
462
  - _Link article files here, e.g._ \`articles/guide-to-x.md\`
463
- `,"utf-8"),r.push("index.md"));let s=ye(n,"log.md");return Qe(s)||(Rs(s,`---
463
+ `,"utf-8"),r.push("index.md"));let s=we(n,"log.md");return et(s)||(js(s,`---
464
464
  type: Log
465
465
  title: Change log
466
466
  description: Chronological history of changes to this OKF bundle.
@@ -469,16 +469,25 @@ description: Chronological history of changes to this OKF bundle.
469
469
  # Change log
470
470
 
471
471
  - Bundle scaffolded.
472
- `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Sr=`${k}/${Ze}`;function xt(e,t={}){let n=process.cwd(),r=L(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=As(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${Sr}/.`):(l.success(`Scaffolded ${Sr}/ \u2014 created ${a.join(", ")}.`),l.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=Es(gn(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
473
- `);return}for(let c of a.errors)l.message(`${oe.red("\u2717")} ${oe.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${oe.yellow("!")} ${oe.dim(c.file)} \u2014 ${c.message}`);a.ok?l.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(l.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=hn(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
474
- `);return}l.message(D([{content:oe.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?oe.green(Sr+"/"):oe.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?oe.dim("Run `seoagent okf validate` to check it."):oe.dim("Run `seoagent okf scaffold` to start one.")}],{title:oe.cyan("OKF")}))}import H from"picocolors";async function xr(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r&&!e.url){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` (or pass `--url <sitemap-url>`) so I know which sitemap to check."),process.exitCode=1;return}let o=r?ne(t,r).pages.map(s=>s.url||s.route):[],i=await Vo({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
475
- `),i.ok||(process.exitCode=1);return}ff(i),i.ok||(process.exitCode=1)}function ff(e){let t=e.fetched?e.status===200?H.green(`200 \xB7 ${e.urls.length} URL${e.urls.length===1?"":"s"}`):H.red(String(e.status)):H.red("unreachable");l.message(D([{content:H.bold("Sitemap check")},{sep:!0},{content:`URL: ${H.dim(e.sitemapUrl)}`},{content:`Status: ${t}`},...e.fetched&&e.status===200?[{content:`Private leaked: ${e.privateUrls.length===0?H.green("none"):H.yellow(String(e.privateUrls.length))}`},{content:`Missing public: ${e.missing.length===0?H.green("none"):H.yellow(String(e.missing.length))}`},{content:`<lastmod>: ${e.hasLastmod?H.green("present"):H.dim("absent")}`}]:[]],{title:e.ok?H.cyan("Sitemap"):H.red("Sitemap")}));for(let n of e.issues){let r=n.level==="error"?H.red("\u2717"):n.level==="warning"?H.yellow("!"):H.dim("\xB7");l.message(`${r} ${n.message}`)}e.ok?l.success("Sitemap looks healthy."):l.error("Sitemap has errors (see above).")}import{mkdirSync as Ff,writeFileSync as Uf}from"fs";import{join as Hs}from"path";import Pe from"picocolors";var Cr=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi,Ps=30;function Ct(e){let t=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(e);return t?t[1]:e}function _t(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#0?39;/g,"'").replace(/&apos;/g,"'").replace(/&nbsp;/gi," ")}function le(e,t){let n=new RegExp(`\\b${t}\\s*=\\s*"([^"]*)"`,"i").exec(e);if(n)return _t(n[1]).trim();let r=new RegExp(`\\b${t}\\s*=\\s*'([^']*)'`,"i").exec(e);if(r)return _t(r[1]).trim();let o=new RegExp(`\\b${t}\\s*=\\s*([^\\s>]+)`,"i").exec(e);return o?_t(o[1]).trim():null}function mf(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);return t&&_t(t[1].replace(/\s+/g," ")).trim()||null}function gf(e){let t=e.match(/<meta\b[^>]*>/gi)??[];for(let n of t){let r=le(n,"name");if(r&&r.toLowerCase()==="description"){let o=le(n,"content");return o&&o.trim()?o.trim():null}}return null}function hf(e){let t=Ct(e),n=[],r=/<h1\b[^>]*>([\s\S]*?)<\/h1>/gi,o;for(;(o=r.exec(t))!==null;){let i=_t(o[1].replace(/<[^>]+>/g," ").replace(/\s+/g," ")).trim();i&&n.push(i)}return n}function yf(e){let t=e.match(/<link\b[^>]*>/gi)??[];for(let n of t){let r=le(n,"rel");if(r&&r.toLowerCase().split(/\s+/).includes("canonical")){let o=le(n,"href");return o&&o.trim()?o.trim():null}}return null}function wf(e){let t=[],n=/<script\b[^>]*type\s*=\s*['"]application\/ld\+json['"][^>]*>([\s\S]*?)<\/script>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim();if(o)try{let i=JSON.parse(o);t.push({types:_r(i),valid:!0})}catch{let i=Array.from(o.matchAll(/"@type"\s*:\s*"([^"]+)"/g)).map(s=>s[1]);t.push({types:i,valid:!1})}}return t}function _r(e,t=[]){if(Array.isArray(e)){for(let n of e)_r(n,t);return t}if(e&&typeof e=="object"){let n=e,r=n["@type"];if(typeof r=="string")t.push(r);else if(Array.isArray(r))for(let o of r)typeof o=="string"&&t.push(o);Array.isArray(n["@graph"])&&_r(n["@graph"],t)}return t}function Is(e,t){let n={},r=e.match(/<meta\b[^>]*>/gi)??[];for(let o of r){let i=(le(o,"property")||le(o,"name")||"").toLowerCase();if(i.startsWith(t)){let s=le(o,"content");s!==null&&(n[i.slice(t.length)]=s)}}return n}function bf(e){return Is(e,"og:")}function kf(e){return Is(e,"twitter:")}function vf(e,t=5){let r=Ct(e).match(/<img\b[^>]*>/gi)??[],o=0,i=[];for(let s of r)if(!/\salt(?=[\s=/>])/i.test(s)&&(o++,i.length<t)){let c=le(s,"src");c&&i.push(c)}return{imgCount:r.length,missingAlt:o,missingAltSrcs:i}}var $f=/\.(png|jpe?g|gif|svg|webp|avif|ico|css|js|mjs|json|pdf|zip|gz|mp4|webm|mp3|woff2?|ttf|xml|txt)$/i;function Os(e,t,n=100){let r;try{r=new URL(t).origin}catch{return[]}let o=[],i=new Set,s=e.match(/<a\b[^>]*>/gi)??[];for(let a of s){if(o.length>=n)break;let c=le(a,"href");if(!c||c.startsWith("#")||/^(mailto:|tel:|javascript:|data:)/i.test(c))continue;let u;try{u=new URL(c,t)}catch{continue}if(u.origin!==r||$f.test(u.pathname)||Ue(u.pathname))continue;u.hash="";let d=u.pathname==="/"?`${u.origin}/${u.search}`:`${u.origin}${u.pathname.replace(/\/+$/,"")}${u.search}`;i.has(d)||(i.add(d),o.push(d))}return o}function Ts(e){return(Ct(e).replace(Cr," ").match(/<a\b[^>]*\bhref\s*=/gi)??[]).length}function Ls(e){let t=Ct(e).replace(Cr," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&[a-z]+;/gi," ").replace(/\s+/g," ").trim();return t===""?0:t.split(" ").filter(Boolean).length}var Sf=/\b(loading|please wait|just a moment|redirecting)\b[\s.…]*/i;function xf(e){let t=Ls(e),n=Ts(e),r=Ct(e).replace(Cr," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),o=t<Ps&&Sf.test(r),i=t<Ps&&n===0;return o||i}function _f(e,t,n=200){let r=wf(t),o=Array.from(new Set(r.flatMap(a=>a.types))),i=yf(t),s=vf(t);return{url:e,status:n,fetched:!0,title:mf(t),metaDescription:gf(t),h1s:hf(t),canonical:i,canonicalServerRendered:i===null?null:!0,jsonLd:r,jsonLdTypes:o,openGraph:bf(t),twitter:kf(t),wordCount:Ls(t),clientRenderedShell:xf(t),bodyLinkCount:Ts(t),imgCount:s.imgCount,imgsMissingAlt:s.missingAlt,imgsMissingAltSrcs:s.missingAltSrcs}}function Cf(e){return{url:e,status:null,fetched:!1,title:null,metaDescription:null,h1s:[],canonical:null,canonicalServerRendered:null,jsonLd:[],jsonLdTypes:[],openGraph:{},twitter:{},wordCount:0,clientRenderedShell:!1,bodyLinkCount:0,imgCount:0,imgsMissingAlt:0,imgsMissingAltSrcs:[]}}async function Rr(e,t){let n=Cf(e);try{let r=await P(e,{headers:{"user-agent":"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) SEOAgent-CLI"},redirect:"follow"},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!r.ok)return{evidence:{...n,status:r.status},html:null};let o=await r.text();return{evidence:_f(e,o,r.status),html:o}}catch{return{evidence:n,html:null}}}async function Rf(e,t){return(await Rr(e,t)).evidence}async function js(e,t={}){let n=Math.max(1,t.concurrency??5),r=new Array(e.length),o=0;async function i(){for(;;){let s=o++;if(s>=e.length)return;r[s]=await Rf(e[s],t.fetchImpl)}}return await Promise.all(Array.from({length:Math.min(n,e.length)},()=>i())),r}function Ef(e){let t=[],n=[],r=null,o=!1;for(let i of e.split(/\r?\n/)){let s=i.replace(/#.*$/,"").trim();if(!s)continue;let a=s.indexOf(":");if(a===-1)continue;let c=s.slice(0,a).trim().toLowerCase(),u=s.slice(a+1).trim();if(c==="user-agent"){(!r||!o)&&(r={userAgents:[],disallow:[],allow:[]},t.push(r)),r.userAgents.push(u.toLowerCase()),o=!0;continue}if(o=!1,c==="sitemap"){u&&n.push(u);continue}r||(r={userAgents:["*"],disallow:[],allow:[]},t.push(r)),c==="disallow"?r.disallow.push(u):c==="allow"&&r.allow.push(u)}return{groups:t,sitemaps:n}}function Ns(e){let t=e.trim().replace(/\/+$/,"");return/^https?:\/\//i.test(t)?t:`https://${t}`}async function Ds(e,t){let n=`${Ns(e)}/robots.txt`,r={fetched:!1,status:null,raw:"",groups:[],sitemaps:[]};try{let o=await P(n,{headers:{"user-agent":"SEOAgent-CLI/robots-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!o.ok)return{...r,status:o.status};let i=await o.text();return/^\s*</.test(i)?{...r,status:o.status,raw:""}:{fetched:!0,status:o.status,raw:i,...Ef(i)}}catch{return r}}var Af=/\/(blog|posts?|articles?|news)\//i;function Pf(e){return e.filter(t=>Af.test(t)).length}async function Fs(e,t){let n=`${Ns(e)}/sitemap.xml`,r={fetched:!1,status:null,urls:[],count:0,blogUrlCount:0};try{let o=await P(n,{headers:{"user-agent":"SEOAgent-CLI/sitemap-facts"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!o.ok)return{...r,status:o.status};let i=await o.text();if(!/<urlset|<sitemapindex/i.test(i))return{...r,status:o.status};let s=ct(i);return{fetched:!0,status:o.status,urls:s,count:s.length,blogUrlCount:Pf(s)}}catch{return r}}function If(e){return Object.keys(e.twitter).length>0}function Of(e){return Object.keys(e.openGraph).length>0}function Tf(e,t){switch(t){case"title":return e.title!==null&&e.title.trim()!=="";case"meta_description":return e.metaDescription!==null&&e.metaDescription.trim()!=="";case"canonical":return e.canonical!==null&&e.canonical.trim()!=="";case"open_graph":return Of(e);case"twitter_card":return If(e);case"json_ld":return e.jsonLdTypes.length>0}}var Lf=["title","meta_description","canonical","open_graph","twitter_card","json_ld"];function jf(e,t){switch(t){case"title":return`title already present: "${e.title}"`;case"meta_description":return`meta description already present: "${e.metaDescription}"`;case"canonical":return`canonical already present: ${e.canonical}`;case"open_graph":return`Open Graph already present: ${Object.keys(e.openGraph).map(n=>`og:${n}`).join(", ")}`;case"twitter_card":return`Twitter card already present: ${Object.keys(e.twitter).map(n=>`twitter:${n}`).join(", ")}`;case"json_ld":return`JSON-LD already present: ${e.jsonLdTypes.join(", ")}`}}function Nf(e,t){if(!e.fetched)return{kind:t,present:!1,safeToRecommendAdding:!1,reason:'page not fetched \u2014 cannot confirm absence, so "add" is unverified (Hypothesis)'};let n=Tf(e,t);return{kind:t,present:n,safeToRecommendAdding:!n,reason:n?jf(e,t):`${t} genuinely absent in the server HTML \u2014 safe to recommend adding`}}function Us(e){return Lf.map(t=>Nf(e,t))}var Ms={title:"<title>",meta_description:"meta description",canonical:"canonical",open_graph:"Open Graph tags",twitter_card:"Twitter card",json_ld:"JSON-LD schema"};var Df="SOURCE RENDER (local dev server) \u2014 NOT the public live site";function Bs(e){return e===null||e===""?"_(none)_":e}function Er(e){let t=e.filter(n=>n.fetched);return{pagesMissingCanonical:t.filter(n=>!n.canonical).map(n=>n.url),pagesMissingMetaDescription:t.filter(n=>!n.metaDescription||n.metaDescription.trim()==="").map(n=>n.url),pagesWithMultipleH1s:t.filter(n=>n.h1s.length>1).map(n=>n.url),pagesWithNoStructuredData:t.filter(n=>n.jsonLd.length===0).map(n=>n.url),totalImgsMissingAlt:t.reduce((n,r)=>n+r.imgsMissingAlt,0),pagesWithImgsMissingAlt:t.filter(n=>n.imgsMissingAlt>0).map(n=>({url:n.url,count:n.imgsMissingAlt}))}}function yn(e,t){return t.length===0?`- **${e}:** _(none \u2014 all pages pass)_`:`- **${e}:** ${t.join(", ")}`}function Gs(e){let{domain:t,capturedAt:n,pages:r,robots:o,sitemap:i}=e,s=e.origin??`https://${t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}`,a=e.sourceRender===!0,c=[];if(c.push("---"),c.push(`domain: ${t}`),c.push(`origin: ${s}`),e.originSource&&c.push(`origin_source: ${e.originSource}`),c.push(`source_render: ${a}`),c.push(`captured_at: ${n}`),c.push(`pages_crawled: ${r.length}`),c.push("note: >-"),a?(c.push(" SOURCE-RENDER evidence (local dev server). Every fact here was fetched"),c.push(" from a loopback origin that was NOT designated as the live site \u2014 it"),c.push(" describes the LOCAL RENDER only, never the public live site. Do NOT"),c.push(" emit live-state claims (present OR absent) from this file.")):(c.push(" Live-crawl evidence base. Every fact here was fetched from the live site."),c.push(" The audit must ground all Confirmed claims on THIS file, never on repo"),c.push(" source or priors. Do NOT recommend adding schema / robots rules /"),c.push(" canonical tags that already appear below.")),c.push("---"),c.push(""),c.push(`# Live-Crawl Evidence \u2014 ${t}`),c.push(""),c.push(`**Crawled origin:** ${s} at ${n}`),c.push(""),a&&(c.push(`> **\u26A0 ${Df}.**`),c.push(`> This crawl fetched a loopback origin (${s}) that nobody designated as the live site (no \`--url\`, no \`live_url:\` in project.md) \u2014 a self-started local dev server renders the REPO's current state, which may differ from production in either direction. Nothing below is live-state evidence: "(Confirmed absent)" here means absent from the LOCAL render only, NOT absent on the live site. Do not base any live-site claim or "add X" recommendation on this file. If this loopback origin genuinely IS the site under audit (the user said so), re-run \`seoagent crawl --url ${s}\` to designate it; otherwise re-run with \`--url <live origin>\`.`),c.push("")),c.push("## robots.txt (Confirmed)"),!o.fetched)c.push(`- Not fetched (HTTP ${o.status??"network error"}). Do NOT assert any robots.txt rule \u2014 it is unverified (Hypothesis).`);else{let d=o.groups.flatMap(p=>p.disallow).filter(Boolean);c.push(`- Fetched: HTTP ${o.status}`),c.push(`- Disallow rules present: ${d.length===0?"**none** (do NOT claim any path is blocked)":d.map(p=>`\`${p}\``).join(", ")}`),c.push(`- Sitemap declarations: ${o.sitemaps.length===0?"_(none)_":o.sitemaps.join(", ")}`),c.push("- Raw contents:"),c.push("```"),c.push(o.raw.trim()),c.push("```")}c.push(""),c.push("## sitemap.xml (Confirmed)"),i.fetched?(c.push(`- **${i.count} URL${i.count===1?"":"s"}**, ${i.blogUrlCount} blog/article post${i.blogUrlCount===1?"":"s"}`),i.blogUrlCount===0&&c.push(" - No blog posts are in the sitemap \u2014 if the site has a blog, its posts are not discoverable this way (report as a finding, Confirmed).")):c.push(`- Not fetched (HTTP ${i.status??"network error"}). Do NOT assert a sitemap URL count.`),c.push("");let u=Er(r);c.push("## Site-wide rollup (Confirmed)"),c.push(yn("Pages missing canonical",u.pagesMissingCanonical)),c.push(yn("Pages missing meta description",u.pagesMissingMetaDescription)),c.push(yn("Pages with multiple H1s",u.pagesWithMultipleH1s)),c.push(yn("Pages with no structured data (zero JSON-LD)",u.pagesWithNoStructuredData)),c.push(u.totalImgsMissingAlt===0?"- **Images missing alt:** _(none \u2014 every crawled image has an alt attribute)_":`- **Images missing alt:** ${u.totalImgsMissingAlt} total \u2014 ${u.pagesWithImgsMissingAlt.map(d=>`${d.url} (${d.count})`).join(", ")}`),c.push("");for(let d of r){if(c.push(`## ${d.url}`),!d.fetched){c.push(`- Not fetched (HTTP ${d.status??"network error"}). No claims about this page are Confirmed.`),c.push("");continue}c.push(`- HTTP ${d.status} \xB7 ${d.wordCount} body words`),c.push(`- **title:** ${Bs(d.title)}`),c.push(`- **meta description:** ${Bs(d.metaDescription)}`),c.push(`- **h1(s):** ${d.h1s.length===0?"_(none \u2014 missing H1, Confirmed)_":d.h1s.map(b=>`\`${b}\``).join(" | ")}${d.h1s.length>1?` **(\u26A0 ${d.h1s.length} H1s \u2014 conflicting)**`:""}`),c.push(`- **canonical:** ${d.canonical===null?"_(none in server HTML)_":`\`${d.canonical}\` (${d.canonicalServerRendered?"server-rendered":"client-rendered"})`}`),c.push(`- **JSON-LD @types present:** ${d.jsonLdTypes.length===0?"_(none \u2014 safe to recommend adding schema)_":d.jsonLdTypes.map(b=>`\`${b}\``).join(", ")+" \u2014 **already present; do NOT recommend adding these**"}`);let p=Object.keys(d.openGraph),m=Object.keys(d.twitter);c.push(`- **Open Graph:** ${p.length===0?"_(none)_":p.map(b=>`og:${b}`).join(", ")}`),c.push(`- **Twitter:** ${m.length===0?"_(none)_":m.map(b=>`twitter:${b}`).join(", ")}`),c.push(`- **images:** ${d.imgCount} total, ${d.imgsMissingAlt===0?"all have alt":`**${d.imgsMissingAlt} missing alt**${d.imgsMissingAltSrcs.length>0?` (${d.imgsMissingAltSrcs.map(b=>`\`${b}\``).join(", ")}${d.imgsMissingAlt>d.imgsMissingAltSrcs.length?", \u2026":""})`:""} (Confirmed)`}`),d.clientRenderedShell&&c.push(`- **\u26A0 client-rendered shell:** server HTML has ${d.wordCount} words and ${d.bodyLinkCount} in-body links \u2014 crawlers can't see the content (Confirmed). Any on-page data (counts, listings) is Likely/Hypothesis, not Confirmed.`);let g=Us(d).filter(b=>b.present).map(b=>Ms[b.kind]);g.length>0&&c.push(`- **Already present (do NOT recommend adding):** ${g.join(", ")} \u2014 verified in the server \`<head>\`.`),c.push("")}return c.join(`
476
- `)}function Ws(e){return{pages:e.pages.length,fetched:e.pages.filter(t=>t.fetched).length,multiH1:e.pages.filter(t=>t.h1s.length>1).length,shells:e.pages.filter(t=>t.clientRenderedShell).length,robotsFetched:e.robots.fetched,sitemapCount:e.sitemap.fetched?e.sitemap.count:null}}var Mf=15,Bf=30,Gf=5;function Ks(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="0.0.0.0"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}function Wf(e){let t=e.trim().replace(/\/+$/,"");if(!t)return null;let n=t;if(!/^https?:\/\//i.test(n)){let r=n.split("/")[0].split(":")[0];n=`${Ks(r)?"http":"https"}://${n}`}try{let r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.origin}catch{return null}}function Hf(e){let t=[];e.urlFlag&&t.push({raw:e.urlFlag,source:"flag"}),e.liveUrl&&t.push({raw:e.liveUrl,source:"live_url"}),e.domain&&e.domain!=="unknown"&&t.push({raw:e.domain,source:"domain"});for(let n of t){let r=Wf(n.raw);if(!r){if(n.source==="flag")return{ok:!1,error:`Invalid --url value: ${JSON.stringify(n.raw)} \u2014 pass a full origin like https://example.com or http://127.0.0.1:3000.`};continue}let o=n.source==="flag"||n.source==="live_url",i=Ks(new URL(r).hostname);return{ok:!0,origin:r,source:n.source,designated:o,loopback:i,sourceRender:i&&!o}}return{ok:!1,error:"No crawl origin \u2014 pass --url <live site origin> or set live_url: (or domain:) in .seoagent/project.md. The crawl never guesses which site is live, and starting a local dev server does NOT count as the live site."}}async function Ar(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=Hf({urlFlag:e.url,liveUrl:n.live_url,domain:n.domain});if(!r.ok){l.error(r.error),process.exitCode=1;return}if(r.source==="flag")try{q(t,{live_url:r.origin})}catch{}let o=n.domain&&n.domain!=="unknown"?n.domain:new URL(r.origin).host,i=Math.min(Math.max(1,e.max??Mf),Bf),s=`${r.origin}/`;l.info(`Capturing live-crawl evidence from ${r.origin} (up to ${i} pages + robots + sitemap)\u2026`),r.sourceRender&&l.warn("Loopback origin without a --url/live_url designation \u2014 evidence will be labeled SOURCE RENDER (local dev server), NOT the public live site.");let[a,c,u]=await Promise.all([Rr(s,e.fetchImpl),Ds(r.origin,e.fetchImpl),Fs(r.origin,e.fetchImpl)]),d=a.html?Os(a.html,s):[],m=qf({home:s,sitemapUrls:u.urls,navLinks:d,repoUrls:zf(Vf(t,o),r.origin),max:i}).filter(S=>S!==s),g=await js(m,{concurrency:Gf,fetchImpl:e.fetchImpl}),b=[a.evidence,...g],h={domain:o,origin:r.origin,originSource:r.source,sourceRender:r.sourceRender,capturedAt:new Date().toISOString(),pages:b,robots:c,sitemap:u},v=Hs(t,k,"audit");Ff(v,{recursive:!0});let x=Hs(v,"evidence.md");if(Uf(x,Gs(h),"utf-8"),e.json){process.stdout.write(JSON.stringify(h,null,2)+`
477
- `);return}Yf(h,x)}function Kf(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.pathname==="/"?`${t.origin}/${t.search}`:`${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`)}catch{return null}}function qf(e){let t=new Set,n=[],r=o=>{if(n.length>=e.max)return;let i=Kf(o);!i||t.has(i)||(t.add(i),n.push(i))};r(e.home);for(let o of e.sitemapUrls??[])r(o);for(let o of e.navLinks??[])r(o);for(let o of e.repoUrls??[])r(o);return n}function Vf(e,t){try{return ne(e,t).pages.map(n=>n.url).filter(n=>/^https?:\/\//.test(n))}catch{return[]}}function zf(e,t){let n=[];for(let r of e)try{let o=new URL(r);n.push(`${t}${o.pathname}${o.search}`)}catch{}return n}function Yf(e,t){let n=Ws(e),r=Er(e.pages);l.success(`Captured evidence for ${n.fetched}/${n.pages} page${n.pages===1?"":"s"} from ${e.origin??e.domain} \u2192 ${Pe.dim(t)}`),e.sourceRender&&l.warn("SOURCE RENDER (local dev server) \u2014 this evidence describes the local render, NOT the public live site. Re-run with --url <live origin> for live evidence."),l.message(` robots.txt: ${n.robotsFetched?Pe.green("fetched"):Pe.yellow("not reachable")} \xB7 sitemap: ${n.sitemapCount===null?Pe.yellow("not reachable"):Pe.green(`${n.sitemapCount} URLs`)}`);let o=[];r.pagesMissingCanonical.length>0&&o.push(`${r.pagesMissingCanonical.length} missing canonical`),r.pagesMissingMetaDescription.length>0&&o.push(`${r.pagesMissingMetaDescription.length} missing meta description`),r.pagesWithMultipleH1s.length>0&&o.push(`${r.pagesWithMultipleH1s.length} with multiple H1s`),r.pagesWithNoStructuredData.length>0&&o.push(`${r.pagesWithNoStructuredData.length} with no structured data`),r.totalImgsMissingAlt>0&&o.push(`${r.totalImgsMissingAlt} image${r.totalImgsMissingAlt===1?"":"s"} missing alt`),o.length>0&&l.message(` ${Pe.yellow("!")} rollup: ${o.join(" \xB7 ")}`),n.shells>0&&l.message(` ${Pe.yellow("!")} ${n.shells} page(s) render as a client-side shell \u2014 crawlers can't see the content`),l.info("The audit will ground its Confirmed findings on this evidence \u2014 no invented robots rules, no recommending schema that already exists.")}import Pr from"picocolors";async function Ir(e={}){let t=process.cwd(),n=ln(t,{extraFiles:e.files});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
478
- `);return}if(!n.evidenceFound){if(e.quiet)return;l.info(`No crawl evidence found (.seoagent/audit/evidence.md) \u2014 run \`${f("crawl")}\` first, then re-run verify-recs. Nothing was verified.`);return}if(n.sourceRender){l.warn(`evidence.md is a SOURCE RENDER (undesignated local dev-server crawl) \u2014 verify-recs CANNOT verify live-state claims against it. No corrections were applied. Re-run \`${f("crawl")} --url <live origin>\` to capture live evidence, then re-run verify-recs.`);return}if(n.corrections.length===0){if(e.quiet)return;l.success(`Verified ${n.scanned.length} authored file${n.scanned.length===1?"":"s"} against the crawl evidence \u2014 no false absence/add claims found.`)}else{l.warn(`Corrected ${n.corrections.length} claim${n.corrections.length===1?"":"s"} that contradicted the live-crawl evidence:`);for(let r of n.corrections)l.message(` ${Pr.dim(`${r.file}:${r.line}`)} \u2014 the live page already serves ${Pr.bold(r.entityLabel)} (${r.pageUrl})`);l.info("Each line was rewritten in place with a CORRECTION annotation. Reflect these corrections in your final summary \u2014 the original claims were wrong.")}n.skipped.length>0&&l.message(` ${Pr.dim(`skipped (protected): ${n.skipped.join(", ")}`)}`)}import{existsSync as am,mkdirSync as cm,readFileSync as ea,writeFileSync as lm}from"fs";import{join as Lr}from"path";import et from"picocolors";import{readdirSync as Jf,readFileSync as Xf,statSync as Qf}from"fs";import{join as bn}from"path";var Vs={minImpressionsToPreserve:50,onTopicRelevance:.34},Zf=new Set(["the","a","an","and","or","for","to","of","in","on","with","how","what","why","best","top","is","are","your","you","my","vs","app","tool","tools","software","online","free","guide","com","www","http","https"]);function zs(e){return e.toLowerCase().replace(/https?:\/\/[^/]+/g," ").replace(/[^a-z0-9]+/g," ").split(" ").filter(t=>t.length>2&&!Zf.has(t)&&!/^\d+$/.test(t))}function Ys(e){let t=new Set;for(let n of e)for(let r of zs(n))t.add(r);return t}function em(e,t){let n=zs(e);return n.length===0||t.size===0?0:n.filter(o=>t.has(o)).length/n.length}function tm(e,t,n=Vs){let r=em(e.key,t),o=r>=n.onTopicRelevance,i=e.impressions>=n.minImpressionsToPreserve,s=e.position===null?"unknown":e.position.toFixed(1),a=`${e.impressions} impressions, ${e.clicks} clicks, avg position ${s}`,c,u,d;return o&&i?(c="harvest",u=`On-strategy for the new direction (relevance ${(r*100).toFixed(0)}%) with real authority (${a}). Bridgeable \u2014 keep the equity.`,d=e.kind==="page"?`Refresh/repurpose ${e.key} into the new narrative (keep the URL, retarget the content to the new positioning).`:`Build/retarget an on-strategy page for "${e.key}" \u2014 real demand that fits the new direction.`):!o&&i?(c="redirect",u=`Off-topic for the new direction (relevance ${(r*100).toFixed(0)}%) but holds authority (${a}). Don't throw the equity away.`,d=e.kind==="page"?`301-redirect ${e.key} into the most relevant new page (pass the authority forward).`:`Point the closest new page at "${e.key}" via a 301 from any legacy URL that ranks for it.`):(c="sunset",u=o?`On-topic but negligible authority (${a}) \u2014 not worth active migration.`:`Off-topic for the new direction and negligible authority (${a}).`,d=e.kind==="page"?`Let ${e.key} decay / noindex it \u2014 low-value legacy that doesn't fit the new direction.`:`Ignore "${e.key}" \u2014 legacy off-strategy query with no real traffic to preserve.`),{row:e,disposition:c,onTopic:o,relevance:r,rationale:u,action:d}}function Js(e,t,n=Vs){return e.map(r=>tm(r,t,n)).sort((r,o)=>o.row.impressions-r.row.impressions)}function Or(e){let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];i==='"'?r&&e[o+1]==='"'?(n+='"',o++):r=!r:i===","&&!r?(t.push(n),n=""):n+=i}return t.push(n),t.map(o=>o.trim())}function wn(e){if(e===void 0||e==="")return null;let t=e.replace(/[",%\s]/g,"");if(t==="")return null;let n=Number(t);return Number.isFinite(n)?n:null}function Tr(e){let t=e.split(/\r?\n/).filter(p=>p.trim()!=="");if(t.length<2)return[];let n=Or(t[0]).map(p=>p.toLowerCase()),r=n[0]??"",o=/quer/i.test(r)?"query":"page",i=p=>n.findIndex(m=>p.some(g=>m.includes(g))),s=i(["click"]),a=i(["impression"]),c=i(["ctr"]),u=i(["position"]),d=[];for(let p=1;p<t.length;p++){let m=Or(t[p]),g=(m[0]??"").trim();if(!g)continue;let b=c>=0?m[c]??"":"",h=wn(b);d.push({key:g,kind:o,clicks:s>=0?wn(m[s]??"")??0:0,impressions:a>=0?wn(m[a]??"")??0:0,position:u>=0?wn(m[u]??""):null,ctr:h===null?null:/%/.test(b)?h/100:h})}return d}function nm(e){let t=e.split(/\r?\n/).find(s=>s.trim()!=="");if(!t)return!1;let n=Or(t).map(s=>s.toLowerCase()),r=n[0]??"",o=/page|url|quer/.test(r),i=n.some(s=>s.includes("impression"));return o&&i}var rm=[".","gsc",bn(".seoagent","gsc"),bn("data","gsc")],om=4096;function Xs(e){let t=[];for(let n of rm){let r=bn(e,n),o;try{o=Jf(r)}catch{continue}for(let i of o){if(!/\.csv$/i.test(i))continue;let s=bn(r,i);try{if(!Qf(s).isFile())continue;let a=Xf(s,"utf-8").slice(0,om);nm(a)&&t.push(s)}catch{}}}return t}var qs=["harvest","redirect","sunset"],im={harvest:"Harvest \u2014 refresh/repurpose into the new direction (keep the URL)",redirect:"Redirect \u2014 301 the legacy authority into the closest new page",sunset:"Sunset \u2014 let decay / noindex (low value, off-strategy)"};function sm(e){return e.filter(t=>t.disposition==="redirect"&&t.row.kind==="page").map(t=>({from:t.row.key,note:t.action}))}function Qs(e){let{domain:t,directionSummary:n,decisions:r,generatedAt:o}=e,i=qs.reduce((c,u)=>(c[u]=r.filter(d=>d.disposition===u).length,c),{harvest:0,redirect:0,sunset:0}),s=[];if(s.push("---"),s.push(`domain: ${t}`),s.push(`generated_at: ${o}`),s.push(`assets: ${r.length}`),s.push(`harvest: ${i.harvest}`),s.push(`redirect: ${i.redirect}`),s.push(`sunset: ${i.sunset}`),s.push("note: >-"),s.push(" Per-asset migration plan for legacy ranking authority. Every disposition"),s.push(" is backed by real Google Search Console impressions/position. Run this"),s.push(" when the live positioning has shifted away from what history ranks for."),s.push("---"),s.push(""),s.push(`# Migration Plan \u2014 ${t}`),s.push(""),s.push(`**New direction:** ${n||"_(set in project.md / context.md)_"}`),s.push(""),s.push(`**${r.length} legacy asset${r.length===1?"":"s"}** classified: ${i.harvest} harvest \xB7 ${i.redirect} redirect \xB7 ${i.sunset} sunset.`),s.push(""),r.length===0)return s.push("_No GSC rows supplied \u2014 export Search Console Pages/Queries and re-run._"),s.push(""),s.join(`
479
- `);for(let c of qs){let u=r.filter(d=>d.disposition===c);if(u.length!==0){s.push(`## ${im[c]}`),s.push("");for(let d of u)s.push(`- [ ] \`${d.row.key}\``),s.push(` - **Evidence (GSC):** ${d.row.impressions} impressions, ${d.row.clicks} clicks, avg position ${d.row.position===null?"unknown":d.row.position.toFixed(1)}`),s.push(` - **Why:** ${d.rationale}`),s.push(` - **Action:** ${d.action}`);s.push("")}}let a=sm(r);if(a.length>0){s.push("## Redirect config (proposed \u2014 approval-gated)"),s.push(""),s.push("These `redirect` dispositions can be expressed as 301s. Pick the target new"),s.push("page for each, then apply (the operator shows the diff before writing):"),s.push(""),s.push("```");for(let c of a)s.push(`${c.from} -> <choose the closest new page>`);s.push("```"),s.push("")}return s.join(`
480
- `)}function Zs(e){return{total:e.length,harvest:e.filter(t=>t.disposition==="harvest").length,redirect:e.filter(t=>t.disposition==="redirect").length,sunset:e.filter(t=>t.disposition==="sunset").length}}async function jr(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` so the migration plan knows which site it is."),process.exitCode=1;return}let o=Yt(t),i=[r,n.site_type],s=e.direction??"";if(o){let h=o.business;for(let v of[h.type,h.audience,h.industry,h.description,h.name])v&&i.push(v);for(let v of o.writingInstructions)i.push(v);s||(s=[h.description,h.type,h.audience].filter(Boolean).join(" \xB7 "))}s||(s=`${n.site_type} at ${r}`);let a=Ys(i);if(a.size===0){l.error('Not enough direction signal to plan a migration \u2014 add a business description to `.seoagent/context.md` or pass `--direction "<what the site is now about>"`.'),process.exitCode=1;return}let c=[],u="";if(e.csv){let h=e.csv.startsWith("/")?e.csv:Lr(t,e.csv);if(!am(h)){l.error(`GSC CSV not found: ${h}`),process.exitCode=1;return}let v=Tr(ea(h,"utf-8"));c.push(...v),u=`${v.length} row(s) from ${e.csv}`}else{let h=Xs(t);if(h.length>0){let v=null;for(let x of h)try{let S=Tr(ea(x,"utf-8"));(!v||S.length>v.rows.length)&&(v={path:x,rows:S})}catch{}v&&v.rows.length>0&&(c.push(...v.rows),u=`${v.rows.length} row(s) auto-detected from ${v.path}`,l.info(`Auto-detected GSC export: ${et.dim(v.path)}`))}}if(c.length===0){l.error("No GSC performance rows to plan from. Export Search Console \u2192 Performance \u2192 Pages (or Queries) as CSV and pass it with `--csv <path>` (or drop it in the repo \u2014 `gsc/*.csv` and root *.csv exports are auto-detected)."),l.message(et.dim(' In Search Console: Performance report \u2192 set the date range \u2192 Export \u2192 CSV \u2192 use the "Pages" or "Queries" sheet.')),process.exitCode=1;return}let d=Js(c,a),p=new Date().toISOString(),m=Lr(t,k,"strategy");cm(m,{recursive:!0});let g=Lr(m,"migration-plan.md");lm(g,Qs({domain:r,directionSummary:s,decisions:d,generatedAt:p}),"utf-8");let b=Zs(d);if(e.json){process.stdout.write(JSON.stringify({domain:r,directionSummary:s,source:u,summary:b,decisions:d},null,2)+`
481
- `);return}l.success(`Migration plan written \u2192 ${et.dim(g)} (${u})`),l.message(` ${et.green(`${b.harvest} harvest`)} \xB7 ${et.cyan(`${b.redirect} redirect`)} \xB7 ${et.yellow(`${b.sunset} sunset`)} across ${b.total} legacy asset${b.total===1?"":"s"}`),l.info("Every disposition is backed by real GSC impressions/position. Redirects are listed as proposed 301s \u2014 pick a target per row, then apply (approval-gated).")}import{mkdirSync as da,writeFileSync as pa,readFileSync as bm,readdirSync as km,existsSync as vm}from"fs";import{join as fa}from"path";import I from"picocolors";import{query as $m}from"@anthropic-ai/claude-agent-sdk";import{join as Nr}from"path";var Dr="citations",Fr="scorecard.md",um="history",dm=6,pm=1,fm=12,mm=5,kn="Claude (web-grounded)";function vn(e){return Nr(e,k,Dr)}function na(e){return Nr(vn(e),Fr)}function ra(e){return Nr(vn(e),um)}function oa(e){return`${e.replace(/[:.]/g,"-")}.json`}function ia(e){return typeof e!="number"||!Number.isFinite(e)?dm:Math.max(pm,Math.min(fm,Math.floor(e)))}function $n(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let o=typeof r=="string"?r.trim():"";if(!o)continue;let i=o.toLowerCase();if(!t.has(i)&&(t.add(i),n.push(o),n.length>=mm))break}return n}function Rt(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Ur(e){let t=e.results.length,n={brand:e.brand,isYou:!0,surfaced:e.results.filter(o=>o.surfaced).length,total:t},r=e.competitors.map(o=>({brand:o,isYou:!1,surfaced:e.results.filter(i=>i.competitorsSurfaced.some(s=>s.toLowerCase()===o.toLowerCase())).length,total:t}));return r.sort((o,i)=>i.surfaced-o.surfaced||o.brand.localeCompare(i.brand)),[n,...r]}function sa(e,t){let{cited:n,total:r}=Rt(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function aa(e,t){if(!t)return null;let{cited:n}=Rt(e),r=new Map(t.results.map(s=>[s.query.toLowerCase(),s.surfaced])),o=[],i=[];for(let s of e.results){let a=r.get(s.query.toLowerCase());a!==void 0&&(s.surfaced&&!a&&o.push(s.query),!s.surfaced&&a&&i.push(s.query))}return{scoreDelta:n-t.cited,prevCited:t.cited,prevTotal:t.total,prevDate:t.generated_at.slice(0,10),newlyCited:o,newlyDropped:i}}function ca(e,t){let n=$n(e.competitors),r=[`- Domain: ${e.domain}`,e.name?`- Business name: ${e.name}`:null,e.type?`- Business type: ${e.type}`:null,e.description?`- What it does: ${e.description}`:null,`- OKF knowledge bundle present in repo: ${e.hasOkfBundle?"yes":"no"}`,n.length?`- Competitors to track: ${n.join(", ")}`:null].filter(Boolean).join(`
472
+ `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Ar=`${w}/${tt}`;function At(e,t={}){let n=process.cwd(),r=L(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=Ds(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${Ar}/.`):(l.success(`Scaffolded ${Ar}/ \u2014 created ${a.join(", ")}.`),l.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=Ns($n(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
473
+ `);return}for(let c of a.errors)l.message(`${oe.red("\u2717")} ${oe.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${oe.yellow("!")} ${oe.dim(c.file)} \u2014 ${c.message}`);a.ok?l.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(l.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=Sn(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
474
+ `);return}l.message(D([{content:oe.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?oe.green(Ar+"/"):oe.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?oe.dim("Run `seoagent okf validate` to check it."):oe.dim("Run `seoagent okf scaffold` to start one.")}],{title:oe.cyan("OKF")}))}import H from"picocolors";async function Pr(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r&&!e.url){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` (or pass `--url <sitemap-url>`) so I know which sitemap to check."),process.exitCode=1;return}let o=r?ne(t,r).pages.map(s=>s.url||s.route):[],i=await ni({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
475
+ `),i.ok||(process.exitCode=1);return}Ef(i),i.ok||(process.exitCode=1)}function Ef(e){let t=e.fetched?e.status===200?H.green(`200 \xB7 ${e.urls.length} URL${e.urls.length===1?"":"s"}`):H.red(String(e.status)):H.red("unreachable");l.message(D([{content:H.bold("Sitemap check")},{sep:!0},{content:`URL: ${H.dim(e.sitemapUrl)}`},{content:`Status: ${t}`},...e.fetched&&e.status===200?[{content:`Private leaked: ${e.privateUrls.length===0?H.green("none"):H.yellow(String(e.privateUrls.length))}`},{content:`Missing public: ${e.missing.length===0?H.green("none"):H.yellow(String(e.missing.length))}`},{content:`<lastmod>: ${e.hasLastmod?H.green("present"):H.dim("absent")}`}]:[]],{title:e.ok?H.cyan("Sitemap"):H.red("Sitemap")}));for(let n of e.issues){let r=n.level==="error"?H.red("\u2717"):n.level==="warning"?H.yellow("!"):H.dim("\xB7");l.message(`${r} ${n.message}`)}e.ok?l.success("Sitemap looks healthy."):l.error("Sitemap has errors (see above).")}import{mkdirSync as Qf,writeFileSync as Zf}from"fs";import{join as Qs}from"path";import Oe from"picocolors";var Or=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi,Fs=30;function It(e){let t=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(e);return t?t[1]:e}function Pt(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#0?39;/g,"'").replace(/&apos;/g,"'").replace(/&nbsp;/gi," ")}function le(e,t){let n=new RegExp(`\\b${t}\\s*=\\s*"([^"]*)"`,"i").exec(e);if(n)return Pt(n[1]).trim();let r=new RegExp(`\\b${t}\\s*=\\s*'([^']*)'`,"i").exec(e);if(r)return Pt(r[1]).trim();let o=new RegExp(`\\b${t}\\s*=\\s*([^\\s>]+)`,"i").exec(e);return o?Pt(o[1]).trim():null}function Rf(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);return t&&Pt(t[1].replace(/\s+/g," ")).trim()||null}function Af(e){let t=e.match(/<meta\b[^>]*>/gi)??[];for(let n of t){let r=le(n,"name");if(r&&r.toLowerCase()==="description"){let o=le(n,"content");return o&&o.trim()?o.trim():null}}return null}function Pf(e){let t=It(e),n=[],r=/<h1\b[^>]*>([\s\S]*?)<\/h1>/gi,o;for(;(o=r.exec(t))!==null;){let i=Pt(o[1].replace(/<[^>]+>/g," ").replace(/\s+/g," ")).trim();i&&n.push(i)}return n}function If(e){let t=e.match(/<link\b[^>]*>/gi)??[];for(let n of t){let r=le(n,"rel");if(r&&r.toLowerCase().split(/\s+/).includes("canonical")){let o=le(n,"href");return o&&o.trim()?o.trim():null}}return null}function Of(e){let t=[],n=/<script\b[^>]*type\s*=\s*['"]application\/ld\+json['"][^>]*>([\s\S]*?)<\/script>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim();if(o)try{let i=JSON.parse(o);t.push({types:Ir(i),valid:!0})}catch{let i=Array.from(o.matchAll(/"@type"\s*:\s*"([^"]+)"/g)).map(s=>s[1]);t.push({types:i,valid:!1})}}return t}function Ir(e,t=[]){if(Array.isArray(e)){for(let n of e)Ir(n,t);return t}if(e&&typeof e=="object"){let n=e,r=n["@type"];if(typeof r=="string")t.push(r);else if(Array.isArray(r))for(let o of r)typeof o=="string"&&t.push(o);Array.isArray(n["@graph"])&&Ir(n["@graph"],t)}return t}function Ms(e,t){let n={},r=e.match(/<meta\b[^>]*>/gi)??[];for(let o of r){let i=(le(o,"property")||le(o,"name")||"").toLowerCase();if(i.startsWith(t)){let s=le(o,"content");s!==null&&(n[i.slice(t.length)]=s)}}return n}function Tf(e){return Ms(e,"og:")}function Lf(e){return Ms(e,"twitter:")}function jf(e,t=5){let r=It(e).match(/<img\b[^>]*>/gi)??[],o=0,i=[];for(let s of r)if(!/\salt(?=[\s=/>])/i.test(s)&&(o++,i.length<t)){let c=le(s,"src");c&&i.push(c)}return{imgCount:r.length,missingAlt:o,missingAltSrcs:i}}var Nf=/\.(png|jpe?g|gif|svg|webp|avif|ico|css|js|mjs|json|pdf|zip|gz|mp4|webm|mp3|woff2?|ttf|xml|txt)$/i;function Us(e,t,n=100){let r;try{r=new URL(t).origin}catch{return[]}let o=[],i=new Set,s=e.match(/<a\b[^>]*>/gi)??[];for(let a of s){if(o.length>=n)break;let c=le(a,"href");if(!c||c.startsWith("#")||/^(mailto:|tel:|javascript:|data:)/i.test(c))continue;let u;try{u=new URL(c,t)}catch{continue}if(u.origin!==r||Nf.test(u.pathname)||Ue(u.pathname))continue;u.hash="";let d=u.pathname==="/"?`${u.origin}/${u.search}`:`${u.origin}${u.pathname.replace(/\/+$/,"")}${u.search}`;i.has(d)||(i.add(d),o.push(d))}return o}function Bs(e){return(It(e).replace(Or," ").match(/<a\b[^>]*\bhref\s*=/gi)??[]).length}function Gs(e){let t=It(e).replace(Or," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&[a-z]+;/gi," ").replace(/\s+/g," ").trim();return t===""?0:t.split(" ").filter(Boolean).length}var Df=/\b(loading|please wait|just a moment|redirecting)\b[\s.…]*/i;function Ff(e){let t=Gs(e),n=Bs(e),r=It(e).replace(Or," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),o=t<Fs&&Df.test(r),i=t<Fs&&n===0;return o||i}function Mf(e,t,n=200){let r=Of(t),o=Array.from(new Set(r.flatMap(a=>a.types))),i=If(t),s=jf(t);return{url:e,status:n,fetched:!0,title:Rf(t),metaDescription:Af(t),h1s:Pf(t),canonical:i,canonicalServerRendered:i===null?null:!0,jsonLd:r,jsonLdTypes:o,openGraph:Tf(t),twitter:Lf(t),wordCount:Gs(t),clientRenderedShell:Ff(t),bodyLinkCount:Bs(t),imgCount:s.imgCount,imgsMissingAlt:s.missingAlt,imgsMissingAltSrcs:s.missingAltSrcs}}function Uf(e){return{url:e,status:null,fetched:!1,title:null,metaDescription:null,h1s:[],canonical:null,canonicalServerRendered:null,jsonLd:[],jsonLdTypes:[],openGraph:{},twitter:{},wordCount:0,clientRenderedShell:!1,bodyLinkCount:0,imgCount:0,imgsMissingAlt:0,imgsMissingAltSrcs:[]}}async function Tr(e,t){let n=Uf(e);try{let r=await P(e,{headers:{"user-agent":"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) SEOAgent-CLI"},redirect:"follow"},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!r.ok)return{evidence:{...n,status:r.status},html:null};let o=await r.text();return{evidence:Mf(e,o,r.status),html:o}}catch{return{evidence:n,html:null}}}async function Bf(e,t){return(await Tr(e,t)).evidence}async function Ws(e,t={}){let n=Math.max(1,t.concurrency??5),r=new Array(e.length),o=0;async function i(){for(;;){let s=o++;if(s>=e.length)return;r[s]=await Bf(e[s],t.fetchImpl)}}return await Promise.all(Array.from({length:Math.min(n,e.length)},()=>i())),r}function Gf(e){let t=[],n=[],r=null,o=!1;for(let i of e.split(/\r?\n/)){let s=i.replace(/#.*$/,"").trim();if(!s)continue;let a=s.indexOf(":");if(a===-1)continue;let c=s.slice(0,a).trim().toLowerCase(),u=s.slice(a+1).trim();if(c==="user-agent"){(!r||!o)&&(r={userAgents:[],disallow:[],allow:[]},t.push(r)),r.userAgents.push(u.toLowerCase()),o=!0;continue}if(o=!1,c==="sitemap"){u&&n.push(u);continue}r||(r={userAgents:["*"],disallow:[],allow:[]},t.push(r)),c==="disallow"?r.disallow.push(u):c==="allow"&&r.allow.push(u)}return{groups:t,sitemaps:n}}function Hs(e){let t=e.trim().replace(/\/+$/,"");return/^https?:\/\//i.test(t)?t:`https://${t}`}async function Ks(e,t){let n=`${Hs(e)}/robots.txt`,r={fetched:!1,status:null,raw:"",groups:[],sitemaps:[]};try{let o=await P(n,{headers:{"user-agent":"SEOAgent-CLI/robots-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!o.ok)return{...r,status:o.status};let i=await o.text();return/^\s*</.test(i)?{...r,status:o.status,raw:""}:{fetched:!0,status:o.status,raw:i,...Gf(i)}}catch{return r}}var Wf=/\/(blog|posts?|articles?|news)\//i;function Hf(e){return e.filter(t=>Wf.test(t)).length}async function qs(e,t){let n=`${Hs(e)}/sitemap.xml`,r={fetched:!1,status:null,urls:[],count:0,blogUrlCount:0};try{let o=await P(n,{headers:{"user-agent":"SEOAgent-CLI/sitemap-facts"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!o.ok)return{...r,status:o.status};let i=await o.text();if(!/<urlset|<sitemapindex/i.test(i))return{...r,status:o.status};let s=ft(i);return{fetched:!0,status:o.status,urls:s,count:s.length,blogUrlCount:Hf(s)}}catch{return r}}function Kf(e){return Object.keys(e.twitter).length>0}function qf(e){return Object.keys(e.openGraph).length>0}function Vf(e,t){switch(t){case"title":return e.title!==null&&e.title.trim()!=="";case"meta_description":return e.metaDescription!==null&&e.metaDescription.trim()!=="";case"canonical":return e.canonical!==null&&e.canonical.trim()!=="";case"open_graph":return qf(e);case"twitter_card":return Kf(e);case"json_ld":return e.jsonLdTypes.length>0}}var Yf=["title","meta_description","canonical","open_graph","twitter_card","json_ld"];function zf(e,t){switch(t){case"title":return`title already present: "${e.title}"`;case"meta_description":return`meta description already present: "${e.metaDescription}"`;case"canonical":return`canonical already present: ${e.canonical}`;case"open_graph":return`Open Graph already present: ${Object.keys(e.openGraph).map(n=>`og:${n}`).join(", ")}`;case"twitter_card":return`Twitter card already present: ${Object.keys(e.twitter).map(n=>`twitter:${n}`).join(", ")}`;case"json_ld":return`JSON-LD already present: ${e.jsonLdTypes.join(", ")}`}}function Jf(e,t){if(!e.fetched)return{kind:t,present:!1,safeToRecommendAdding:!1,reason:'page not fetched \u2014 cannot confirm absence, so "add" is unverified (Hypothesis)'};let n=Vf(e,t);return{kind:t,present:n,safeToRecommendAdding:!n,reason:n?zf(e,t):`${t} genuinely absent in the server HTML \u2014 safe to recommend adding`}}function Vs(e){return Yf.map(t=>Jf(e,t))}var Ys={title:"<title>",meta_description:"meta description",canonical:"canonical",open_graph:"Open Graph tags",twitter_card:"Twitter card",json_ld:"JSON-LD schema"};var Xf="SOURCE RENDER (local dev server) \u2014 NOT the public live site";function zs(e){return e===null||e===""?"_(none)_":e}function Lr(e){let t=e.filter(n=>n.fetched);return{pagesMissingCanonical:t.filter(n=>!n.canonical).map(n=>n.url),pagesMissingMetaDescription:t.filter(n=>!n.metaDescription||n.metaDescription.trim()==="").map(n=>n.url),pagesWithMultipleH1s:t.filter(n=>n.h1s.length>1).map(n=>n.url),pagesWithNoStructuredData:t.filter(n=>n.jsonLd.length===0).map(n=>n.url),totalImgsMissingAlt:t.reduce((n,r)=>n+r.imgsMissingAlt,0),pagesWithImgsMissingAlt:t.filter(n=>n.imgsMissingAlt>0).map(n=>({url:n.url,count:n.imgsMissingAlt}))}}function xn(e,t){return t.length===0?`- **${e}:** _(none \u2014 all pages pass)_`:`- **${e}:** ${t.join(", ")}`}function Js(e){let{domain:t,capturedAt:n,pages:r,robots:o,sitemap:i}=e,s=e.origin??`https://${t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}`,a=e.sourceRender===!0,c=[];if(c.push("---"),c.push(`domain: ${t}`),c.push(`origin: ${s}`),e.originSource&&c.push(`origin_source: ${e.originSource}`),c.push(`source_render: ${a}`),c.push(`captured_at: ${n}`),c.push(`pages_crawled: ${r.length}`),c.push("note: >-"),a?(c.push(" SOURCE-RENDER evidence (local dev server). Every fact here was fetched"),c.push(" from a loopback origin that was NOT designated as the live site \u2014 it"),c.push(" describes the LOCAL RENDER only, never the public live site. Do NOT"),c.push(" emit live-state claims (present OR absent) from this file.")):(c.push(" Live-crawl evidence base. Every fact here was fetched from the live site."),c.push(" The audit must ground all Confirmed claims on THIS file, never on repo"),c.push(" source or priors. Do NOT recommend adding schema / robots rules /"),c.push(" canonical tags that already appear below.")),c.push("---"),c.push(""),c.push(`# Live-Crawl Evidence \u2014 ${t}`),c.push(""),c.push(`**Crawled origin:** ${s} at ${n}`),c.push(""),a&&(c.push(`> **\u26A0 ${Xf}.**`),c.push(`> This crawl fetched a loopback origin (${s}) that nobody designated as the live site (no \`--url\`, no \`live_url:\` in project.md) \u2014 a self-started local dev server renders the REPO's current state, which may differ from production in either direction. Nothing below is live-state evidence: "(Confirmed absent)" here means absent from the LOCAL render only, NOT absent on the live site. Do not base any live-site claim or "add X" recommendation on this file. If this loopback origin genuinely IS the site under audit (the user said so), re-run \`seoagent crawl --url ${s}\` to designate it; otherwise re-run with \`--url <live origin>\`.`),c.push("")),c.push("## robots.txt (Confirmed)"),!o.fetched)c.push(`- Not fetched (HTTP ${o.status??"network error"}). Do NOT assert any robots.txt rule \u2014 it is unverified (Hypothesis).`);else{let d=o.groups.flatMap(p=>p.disallow).filter(Boolean);c.push(`- Fetched: HTTP ${o.status}`),c.push(`- Disallow rules present: ${d.length===0?"**none** (do NOT claim any path is blocked)":d.map(p=>`\`${p}\``).join(", ")}`),c.push(`- Sitemap declarations: ${o.sitemaps.length===0?"_(none)_":o.sitemaps.join(", ")}`),c.push("- Raw contents:"),c.push("```"),c.push(o.raw.trim()),c.push("```")}c.push(""),c.push("## sitemap.xml (Confirmed)"),i.fetched?(c.push(`- **${i.count} URL${i.count===1?"":"s"}**, ${i.blogUrlCount} blog/article post${i.blogUrlCount===1?"":"s"}`),i.blogUrlCount===0&&c.push(" - No blog posts are in the sitemap \u2014 if the site has a blog, its posts are not discoverable this way (report as a finding, Confirmed).")):c.push(`- Not fetched (HTTP ${i.status??"network error"}). Do NOT assert a sitemap URL count.`),c.push("");let u=Lr(r);c.push("## Site-wide rollup (Confirmed)"),c.push(xn("Pages missing canonical",u.pagesMissingCanonical)),c.push(xn("Pages missing meta description",u.pagesMissingMetaDescription)),c.push(xn("Pages with multiple H1s",u.pagesWithMultipleH1s)),c.push(xn("Pages with no structured data (zero JSON-LD)",u.pagesWithNoStructuredData)),c.push(u.totalImgsMissingAlt===0?"- **Images missing alt:** _(none \u2014 every crawled image has an alt attribute)_":`- **Images missing alt:** ${u.totalImgsMissingAlt} total \u2014 ${u.pagesWithImgsMissingAlt.map(d=>`${d.url} (${d.count})`).join(", ")}`),c.push("");for(let d of r){if(c.push(`## ${d.url}`),!d.fetched){c.push(`- Not fetched (HTTP ${d.status??"network error"}). No claims about this page are Confirmed.`),c.push("");continue}c.push(`- HTTP ${d.status} \xB7 ${d.wordCount} body words`),c.push(`- **title:** ${zs(d.title)}`),c.push(`- **meta description:** ${zs(d.metaDescription)}`),c.push(`- **h1(s):** ${d.h1s.length===0?"_(none \u2014 missing H1, Confirmed)_":d.h1s.map(k=>`\`${k}\``).join(" | ")}${d.h1s.length>1?` **(\u26A0 ${d.h1s.length} H1s \u2014 conflicting)**`:""}`),c.push(`- **canonical:** ${d.canonical===null?"_(none in server HTML)_":`\`${d.canonical}\` (${d.canonicalServerRendered?"server-rendered":"client-rendered"})`}`),c.push(`- **JSON-LD @types present:** ${d.jsonLdTypes.length===0?"_(none \u2014 safe to recommend adding schema)_":d.jsonLdTypes.map(k=>`\`${k}\``).join(", ")+" \u2014 **already present; do NOT recommend adding these**"}`);let p=Object.keys(d.openGraph),m=Object.keys(d.twitter);c.push(`- **Open Graph:** ${p.length===0?"_(none)_":p.map(k=>`og:${k}`).join(", ")}`),c.push(`- **Twitter:** ${m.length===0?"_(none)_":m.map(k=>`twitter:${k}`).join(", ")}`),c.push(`- **images:** ${d.imgCount} total, ${d.imgsMissingAlt===0?"all have alt":`**${d.imgsMissingAlt} missing alt**${d.imgsMissingAltSrcs.length>0?` (${d.imgsMissingAltSrcs.map(k=>`\`${k}\``).join(", ")}${d.imgsMissingAlt>d.imgsMissingAltSrcs.length?", \u2026":""})`:""} (Confirmed)`}`),d.clientRenderedShell&&c.push(`- **\u26A0 client-rendered shell:** server HTML has ${d.wordCount} words and ${d.bodyLinkCount} in-body links \u2014 crawlers can't see the content (Confirmed). Any on-page data (counts, listings) is Likely/Hypothesis, not Confirmed.`);let g=Vs(d).filter(k=>k.present).map(k=>Ys[k.kind]);g.length>0&&c.push(`- **Already present (do NOT recommend adding):** ${g.join(", ")} \u2014 verified in the server \`<head>\`.`),c.push("")}return c.join(`
476
+ `)}function Xs(e){return{pages:e.pages.length,fetched:e.pages.filter(t=>t.fetched).length,multiH1:e.pages.filter(t=>t.h1s.length>1).length,shells:e.pages.filter(t=>t.clientRenderedShell).length,robotsFetched:e.robots.fetched,sitemapCount:e.sitemap.fetched?e.sitemap.count:null}}var em=15,tm=30,nm=5;function Zs(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="0.0.0.0"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}function rm(e){let t=e.trim().replace(/\/+$/,"");if(!t)return null;let n=t;if(!/^https?:\/\//i.test(n)){let r=n.split("/")[0].split(":")[0];n=`${Zs(r)?"http":"https"}://${n}`}try{let r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.origin}catch{return null}}function om(e){let t=[];e.urlFlag&&t.push({raw:e.urlFlag,source:"flag"}),e.liveUrl&&t.push({raw:e.liveUrl,source:"live_url"}),e.domain&&e.domain!=="unknown"&&t.push({raw:e.domain,source:"domain"});for(let n of t){let r=rm(n.raw);if(!r){if(n.source==="flag")return{ok:!1,error:`Invalid --url value: ${JSON.stringify(n.raw)} \u2014 pass a full origin like https://example.com or http://127.0.0.1:3000.`};continue}let o=n.source==="flag"||n.source==="live_url",i=Zs(new URL(r).hostname);return{ok:!0,origin:r,source:n.source,designated:o,loopback:i,sourceRender:i&&!o}}return{ok:!1,error:"No crawl origin \u2014 pass --url <live site origin> or set live_url: (or domain:) in .seoagent/project.md. The crawl never guesses which site is live, and starting a local dev server does NOT count as the live site."}}async function jr(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=om({urlFlag:e.url,liveUrl:n.live_url,domain:n.domain});if(!r.ok){l.error(r.error),process.exitCode=1;return}if(r.source==="flag")try{q(t,{live_url:r.origin})}catch{}let o=n.domain&&n.domain!=="unknown"?n.domain:new URL(r.origin).host,i=Math.min(Math.max(1,e.max??em),tm),s=`${r.origin}/`;l.info(`Capturing live-crawl evidence from ${r.origin} (up to ${i} pages + robots + sitemap)\u2026`),r.sourceRender&&l.warn("Loopback origin without a --url/live_url designation \u2014 evidence will be labeled SOURCE RENDER (local dev server), NOT the public live site.");let[a,c,u]=await Promise.all([Tr(s,e.fetchImpl),Ks(r.origin,e.fetchImpl),qs(r.origin,e.fetchImpl)]),d=a.html?Us(a.html,s):[],m=sm({home:s,sitemapUrls:u.urls,navLinks:d,repoUrls:cm(am(t,o),r.origin),max:i}).filter(S=>S!==s),g=await Ws(m,{concurrency:nm,fetchImpl:e.fetchImpl}),k=[a.evidence,...g],h={domain:o,origin:r.origin,originSource:r.source,sourceRender:r.sourceRender,capturedAt:new Date().toISOString(),pages:k,robots:c,sitemap:u},v=Qs(t,w,"audit");Qf(v,{recursive:!0});let x=Qs(v,"evidence.md");if(Zf(x,Js(h),"utf-8"),e.json){process.stdout.write(JSON.stringify(h,null,2)+`
477
+ `);return}lm(h,x)}function im(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.pathname==="/"?`${t.origin}/${t.search}`:`${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`)}catch{return null}}function sm(e){let t=new Set,n=[],r=o=>{if(n.length>=e.max)return;let i=im(o);!i||t.has(i)||(t.add(i),n.push(i))};r(e.home);for(let o of e.sitemapUrls??[])r(o);for(let o of e.navLinks??[])r(o);for(let o of e.repoUrls??[])r(o);return n}function am(e,t){try{return ne(e,t).pages.map(n=>n.url).filter(n=>/^https?:\/\//.test(n))}catch{return[]}}function cm(e,t){let n=[];for(let r of e)try{let o=new URL(r);n.push(`${t}${o.pathname}${o.search}`)}catch{}return n}function lm(e,t){let n=Xs(e),r=Lr(e.pages);l.success(`Captured evidence for ${n.fetched}/${n.pages} page${n.pages===1?"":"s"} from ${e.origin??e.domain} \u2192 ${Oe.dim(t)}`),e.sourceRender&&l.warn("SOURCE RENDER (local dev server) \u2014 this evidence describes the local render, NOT the public live site. Re-run with --url <live origin> for live evidence."),l.message(` robots.txt: ${n.robotsFetched?Oe.green("fetched"):Oe.yellow("not reachable")} \xB7 sitemap: ${n.sitemapCount===null?Oe.yellow("not reachable"):Oe.green(`${n.sitemapCount} URLs`)}`);let o=[];r.pagesMissingCanonical.length>0&&o.push(`${r.pagesMissingCanonical.length} missing canonical`),r.pagesMissingMetaDescription.length>0&&o.push(`${r.pagesMissingMetaDescription.length} missing meta description`),r.pagesWithMultipleH1s.length>0&&o.push(`${r.pagesWithMultipleH1s.length} with multiple H1s`),r.pagesWithNoStructuredData.length>0&&o.push(`${r.pagesWithNoStructuredData.length} with no structured data`),r.totalImgsMissingAlt>0&&o.push(`${r.totalImgsMissingAlt} image${r.totalImgsMissingAlt===1?"":"s"} missing alt`),o.length>0&&l.message(` ${Oe.yellow("!")} rollup: ${o.join(" \xB7 ")}`),n.shells>0&&l.message(` ${Oe.yellow("!")} ${n.shells} page(s) render as a client-side shell \u2014 crawlers can't see the content`),l.info("The audit will ground its Confirmed findings on this evidence \u2014 no invented robots rules, no recommending schema that already exists.")}import Nr from"picocolors";async function Dr(e={}){let t=process.cwd(),n=Ze(t,{extraFiles:e.files});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
478
+ `);return}if(!n.evidenceFound){if(e.quiet)return;l.info(`No crawl evidence found (.seoagent/audit/evidence.md) \u2014 run \`${f("crawl")}\` first, then re-run verify-recs. Nothing was verified.`);return}if(n.sourceRender){l.warn(`evidence.md is a SOURCE RENDER (undesignated local dev-server crawl) \u2014 verify-recs CANNOT verify live-state claims against it. No corrections were applied. Re-run \`${f("crawl")} --url <live origin>\` to capture live evidence, then re-run verify-recs.`);return}if(n.corrections.length===0){if(e.quiet)return;l.success(`Verified ${n.scanned.length} authored file${n.scanned.length===1?"":"s"} against the crawl evidence \u2014 no false absence/add claims found.`)}else{l.warn(`Corrected ${n.corrections.length} claim${n.corrections.length===1?"":"s"} that contradicted the live-crawl evidence:`);for(let r of n.corrections)l.message(` ${Nr.dim(`${r.file}:${r.line}`)} \u2014 the live page already serves ${Nr.bold(r.entityLabel)} (${r.pageUrl})`);l.info("Each line was rewritten in place with a CORRECTION annotation. Reflect these corrections in your final summary \u2014 the original claims were wrong.")}n.skipped.length>0&&l.message(` ${Nr.dim(`skipped (protected): ${n.skipped.join(", ")}`)}`)}import{existsSync as ea,readFileSync as ta,readdirSync as um,statSync as dm}from"fs";import{join as ue,relative as pm,sep as fm}from"path";var mm=["Critical","High","Medium","Low"],gm={Critical:5,High:3,Medium:2,Low:1},hm=8;function ym(e){let t=[],n=e.split(/^## /m).slice(1);for(let r of n){let o=r.split(`
479
+ `,1)[0].trim(),i=mm.find(p=>o.toLowerCase().startsWith(p.toLowerCase()));if(!i)continue;let s=r.split(`
480
+ `).slice(1),a=null,c=0,u=gm[i]??2,d=()=>{a&&c<u&&(t.push({severity:i,block:a.join(`
481
+ `).trimEnd()}),c++),a=null};for(let p of s)/^- \[[ xX]\]/.test(p)?(d(),a=/^- \[ \]/.test(p)?[p]:null):a&&/^\s+\S/.test(p)?a.push(p):a&&p.trim()===""&&d();d()}return t.slice(0,hm)}function wm(e){let t={harvest:0,redirect:0,sunset:0},n=/^---\n([\s\S]*?)\n---/.exec(e);if(n)for(let a of["harvest","redirect","sunset"]){let c=new RegExp(`^${a}:\\s*(\\d+)\\s*$`,"m").exec(n[1]);c&&(t[a]=parseInt(c[1],10))}let r=[],o=null,i=null,s=()=>{i&&r.push(i),i=null};for(let a of e.split(`
482
+ `)){let c=/^## (Harvest|Redirect|Sunset)\b/i.exec(a);if(c){s(),o=c[1].toLowerCase();continue}if(/^## /.test(a)){s(),o=null;continue}let u=/^- \[[ xX]\] `([^`]+)`/.exec(a);if(u&&o){s(),i={asset:u[1],disposition:o,evidence:"",action:""};continue}if(!i)continue;let d=/\*\*Evidence \(GSC\):\*\*\s*(.+)$/.exec(a);d&&(i.evidence=d[1].trim());let p=/\*\*Action:\*\*\s*(.+)$/.exec(a);p&&(i.action=p[1].trim())}return s(),r.length===0&&t.harvest+t.redirect+t.sunset===0?null:{...t,rows:r}}var bm=5;function km(e){let t=[];for(let n of e.split(`
483
+ `)){let r=/^\s*- \[ \]\s+(.+)$/.exec(n);if(r&&t.push(r[1].trim()),t.length>=bm)break}return t}function na(e,t=[]){let n;try{n=um(e)}catch{return t}for(let r of n){let o=ue(e,r),i;try{i=dm(o)}catch{continue}i.isDirectory()?na(o,t):r.endsWith(".md")&&t.push(o)}return t}function vm(e,t=[]){let n=[],r=new Set(na(ue(e,w)));for(let o of t){let i=ue(e,o);ea(i)&&r.add(i)}for(let o of r){let i;try{i=ta(o,"utf-8")}catch{continue}let s=i.split(`
484
+ `);for(let a=0;a<s.length;a++)s[a].includes(gn)&&n.push({file:pm(e,o).split(fm).join("/"),line:a+1,text:s[a].trim()})}return n}function $m(e){let t=e.evidenceMd===null?"missing":hn(e.evidenceMd)?"source-render":"live",n=t==="live",r=e.auditMd?ym(e.auditMd):[],o=e.migrationMd?wm(e.migrationMd):null,i=e.roadmapMd?km(e.roadmapMd):[],s=[];if(s.push(`# SEOAgent session summary \u2014 ${e.domain??"unknown site"}`),s.push(""),t==="source-render"?(s.push("> \u26A0\uFE0F **Live-state claims are UNVERIFIED.** The latest crawl evidence is a SOURCE RENDER (a local dev-server crawl that was never designated as the live origin) \u2014 it describes the local render only. Say so in the final message; re-run `seoagent crawl --url <live origin>` to verify."),s.push("")):t==="missing"&&(s.push("> \u26A0\uFE0F **Live-state claims are UNVERIFIED.** No crawl evidence exists (.seoagent/audit/evidence.md) \u2014 nothing below is grounded in a live fetch. Run `seoagent crawl` before asserting live-site facts."),s.push("")),s.push("## Top findings (quoted from `.seoagent/audit/latest.md`)"),s.push(""),r.length===0)s.push(e.auditMd?"_No open findings in the audit file._":"_No audit file found (`.seoagent/audit/latest.md`) \u2014 no findings to report._"),s.push("");else{let a="";for(let c of r)c.severity!==a&&(s.push(`### ${c.severity}`),s.push(""),a=c.severity),s.push(c.block),s.push("")}if(e.corrections.length>0){s.push("## Corrections applied by verify-recs \u2014 relay THESE, not the original claims"),s.push("");for(let a of e.corrections)s.push(`- \`${a.file}:${a.line}\` \u2014 ${a.text}`);s.push("")}if(o&&(s.push("## Migration plan (from `.seoagent/strategy/migration-plan.md`)"),s.push(""),s.push(`**${o.harvest} harvest \xB7 ${o.redirect} redirect \xB7 ${o.sunset} sunset**`),s.push(""),o.rows.length>0)){s.push("| Asset | Disposition | GSC evidence | Action |"),s.push("|---|---|---|---|");for(let a of o.rows)s.push(`| \`${a.asset}\` | ${a.disposition} | ${a.evidence} | ${a.action} |`);s.push("")}return i.length>0&&(s.push("## Next steps (top open roadmap items)"),s.push(""),i.forEach((a,c)=>s.push(`${c+1}. ${a}`)),s.push("")),{markdown:s.join(`
485
+ `),json:{domain:e.domain,liveStateVerified:n,evidenceStatus:t,findings:r,corrections:e.corrections,migration:o,roadmap:i}}}function Ot(e){try{return ea(e)?ta(e,"utf-8"):null}catch{return null}}function Sm(e){let t=Ot(ue(e,w,"project.md"));if(!t)return null;let n=/^domain:\s*(\S+)\s*$/m.exec(t);return n?n[1]:null}function ra(e,t=[]){try{Ze(e,{extraFiles:t})}catch{}let n=ue(e,w);return $m({domain:Sm(e),auditMd:Ot(ue(n,"audit","latest.md")),migrationMd:Ot(ue(n,"strategy","migration-plan.md")),roadmapMd:Ot(ue(n,"roadmap.md")),evidenceMd:Ot(ue(n,"audit","evidence.md")),corrections:vm(e,t)})}function Fr(e={}){let t=ra(process.cwd(),e.files??[]);if(e.json){process.stdout.write(JSON.stringify(t.json,null,2)+`
486
+ `);return}process.stdout.write(t.markdown.trimEnd()+`
487
+ `)}import{existsSync as jm,mkdirSync as Nm,readFileSync as pa,writeFileSync as Dm}from"fs";import{join as Br}from"path";import nt from"picocolors";import{readdirSync as xm,readFileSync as _m,statSync as Cm}from"fs";import{join as Cn}from"path";var ia={minImpressionsToPreserve:50,onTopicRelevance:.34},Em=new Set(["the","a","an","and","or","for","to","of","in","on","with","how","what","why","best","top","is","are","your","you","my","vs","app","tool","tools","software","online","free","guide","com","www","http","https"]);function sa(e){return e.toLowerCase().replace(/https?:\/\/[^/]+/g," ").replace(/[^a-z0-9]+/g," ").split(" ").filter(t=>t.length>2&&!Em.has(t)&&!/^\d+$/.test(t))}function aa(e){let t=new Set;for(let n of e)for(let r of sa(n))t.add(r);return t}function Rm(e,t){let n=sa(e);return n.length===0||t.size===0?0:n.filter(o=>t.has(o)).length/n.length}function Am(e,t,n=ia){let r=Rm(e.key,t),o=r>=n.onTopicRelevance,i=e.impressions>=n.minImpressionsToPreserve,s=e.position===null?"unknown":e.position.toFixed(1),a=`${e.impressions} impressions, ${e.clicks} clicks, avg position ${s}`,c,u,d;return o&&i?(c="harvest",u=`On-strategy for the new direction (relevance ${(r*100).toFixed(0)}%) with real authority (${a}). Bridgeable \u2014 keep the equity.`,d=e.kind==="page"?`Refresh/repurpose ${e.key} into the new narrative (keep the URL, retarget the content to the new positioning).`:`Build/retarget an on-strategy page for "${e.key}" \u2014 real demand that fits the new direction.`):!o&&i?(c="redirect",u=`Off-topic for the new direction (relevance ${(r*100).toFixed(0)}%) but holds authority (${a}). Don't throw the equity away.`,d=e.kind==="page"?`301-redirect ${e.key} into the most relevant new page (pass the authority forward).`:`Point the closest new page at "${e.key}" via a 301 from any legacy URL that ranks for it.`):(c="sunset",u=o?`On-topic but negligible authority (${a}) \u2014 not worth active migration.`:`Off-topic for the new direction and negligible authority (${a}).`,d=e.kind==="page"?`Let ${e.key} decay / noindex it \u2014 low-value legacy that doesn't fit the new direction.`:`Ignore "${e.key}" \u2014 legacy off-strategy query with no real traffic to preserve.`),{row:e,disposition:c,onTopic:o,relevance:r,rationale:u,action:d}}function ca(e,t,n=ia){return e.map(r=>Am(r,t,n)).sort((r,o)=>o.row.impressions-r.row.impressions)}function Mr(e){let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];i==='"'?r&&e[o+1]==='"'?(n+='"',o++):r=!r:i===","&&!r?(t.push(n),n=""):n+=i}return t.push(n),t.map(o=>o.trim())}function _n(e){if(e===void 0||e==="")return null;let t=e.replace(/[",%\s]/g,"");if(t==="")return null;let n=Number(t);return Number.isFinite(n)?n:null}function Ur(e){let t=e.split(/\r?\n/).filter(p=>p.trim()!=="");if(t.length<2)return[];let n=Mr(t[0]).map(p=>p.toLowerCase()),r=n[0]??"",o=/quer/i.test(r)?"query":"page",i=p=>n.findIndex(m=>p.some(g=>m.includes(g))),s=i(["click"]),a=i(["impression"]),c=i(["ctr"]),u=i(["position"]),d=[];for(let p=1;p<t.length;p++){let m=Mr(t[p]),g=(m[0]??"").trim();if(!g)continue;let k=c>=0?m[c]??"":"",h=_n(k);d.push({key:g,kind:o,clicks:s>=0?_n(m[s]??"")??0:0,impressions:a>=0?_n(m[a]??"")??0:0,position:u>=0?_n(m[u]??""):null,ctr:h===null?null:/%/.test(k)?h/100:h})}return d}function Pm(e){let t=e.split(/\r?\n/).find(s=>s.trim()!=="");if(!t)return!1;let n=Mr(t).map(s=>s.toLowerCase()),r=n[0]??"",o=/page|url|quer/.test(r),i=n.some(s=>s.includes("impression"));return o&&i}var Im=[".","gsc",Cn(".seoagent","gsc"),Cn("data","gsc")],Om=4096;function la(e){let t=[];for(let n of Im){let r=Cn(e,n),o;try{o=xm(r)}catch{continue}for(let i of o){if(!/\.csv$/i.test(i))continue;let s=Cn(r,i);try{if(!Cm(s).isFile())continue;let a=_m(s,"utf-8").slice(0,Om);Pm(a)&&t.push(s)}catch{}}}return t}var oa=["harvest","redirect","sunset"],Tm={harvest:"Harvest \u2014 refresh/repurpose into the new direction (keep the URL)",redirect:"Redirect \u2014 301 the legacy authority into the closest new page",sunset:"Sunset \u2014 let decay / noindex (low value, off-strategy)"};function Lm(e){return e.filter(t=>t.disposition==="redirect"&&t.row.kind==="page").map(t=>({from:t.row.key,note:t.action}))}function ua(e){let{domain:t,directionSummary:n,decisions:r,generatedAt:o}=e,i=oa.reduce((c,u)=>(c[u]=r.filter(d=>d.disposition===u).length,c),{harvest:0,redirect:0,sunset:0}),s=[];if(s.push("---"),s.push(`domain: ${t}`),s.push(`generated_at: ${o}`),s.push(`assets: ${r.length}`),s.push(`harvest: ${i.harvest}`),s.push(`redirect: ${i.redirect}`),s.push(`sunset: ${i.sunset}`),s.push("note: >-"),s.push(" Per-asset migration plan for legacy ranking authority. Every disposition"),s.push(" is backed by real Google Search Console impressions/position. Run this"),s.push(" when the live positioning has shifted away from what history ranks for."),s.push("---"),s.push(""),s.push(`# Migration Plan \u2014 ${t}`),s.push(""),s.push(`**New direction:** ${n||"_(set in project.md / context.md)_"}`),s.push(""),s.push(`**${r.length} legacy asset${r.length===1?"":"s"}** classified: ${i.harvest} harvest \xB7 ${i.redirect} redirect \xB7 ${i.sunset} sunset.`),s.push(""),r.length===0)return s.push("_No GSC rows supplied \u2014 export Search Console Pages/Queries and re-run._"),s.push(""),s.join(`
488
+ `);for(let c of oa){let u=r.filter(d=>d.disposition===c);if(u.length!==0){s.push(`## ${Tm[c]}`),s.push("");for(let d of u)s.push(`- [ ] \`${d.row.key}\``),s.push(` - **Evidence (GSC):** ${d.row.impressions} impressions, ${d.row.clicks} clicks, avg position ${d.row.position===null?"unknown":d.row.position.toFixed(1)}`),s.push(` - **Why:** ${d.rationale}`),s.push(` - **Action:** ${d.action}`);s.push("")}}let a=Lm(r);if(a.length>0){s.push("## Redirect config (proposed \u2014 approval-gated)"),s.push(""),s.push("These `redirect` dispositions can be expressed as 301s. Pick the target new"),s.push("page for each, then apply (the operator shows the diff before writing):"),s.push(""),s.push("```");for(let c of a)s.push(`${c.from} -> <choose the closest new page>`);s.push("```"),s.push("")}return s.join(`
489
+ `)}function da(e){return{total:e.length,harvest:e.filter(t=>t.disposition==="harvest").length,redirect:e.filter(t=>t.disposition==="redirect").length,sunset:e.filter(t=>t.disposition==="sunset").length}}async function Gr(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` so the migration plan knows which site it is."),process.exitCode=1;return}let o=tn(t),i=[r,n.site_type],s=e.direction??"";if(o){let h=o.business;for(let v of[h.type,h.audience,h.industry,h.description,h.name])v&&i.push(v);for(let v of o.writingInstructions)i.push(v);s||(s=[h.description,h.type,h.audience].filter(Boolean).join(" \xB7 "))}s||(s=`${n.site_type} at ${r}`);let a=aa(i);if(a.size===0){l.error('Not enough direction signal to plan a migration \u2014 add a business description to `.seoagent/context.md` or pass `--direction "<what the site is now about>"`.'),process.exitCode=1;return}let c=[],u="";if(e.csv){let h=e.csv.startsWith("/")?e.csv:Br(t,e.csv);if(!jm(h)){l.error(`GSC CSV not found: ${h}`),process.exitCode=1;return}let v=Ur(pa(h,"utf-8"));c.push(...v),u=`${v.length} row(s) from ${e.csv}`}else{let h=la(t);if(h.length>0){let v=null;for(let x of h)try{let S=Ur(pa(x,"utf-8"));(!v||S.length>v.rows.length)&&(v={path:x,rows:S})}catch{}v&&v.rows.length>0&&(c.push(...v.rows),u=`${v.rows.length} row(s) auto-detected from ${v.path}`,l.info(`Auto-detected GSC export: ${nt.dim(v.path)}`))}}if(c.length===0){l.error("No GSC performance rows to plan from. Export Search Console \u2192 Performance \u2192 Pages (or Queries) as CSV and pass it with `--csv <path>` (or drop it in the repo \u2014 `gsc/*.csv` and root *.csv exports are auto-detected)."),l.message(nt.dim(' In Search Console: Performance report \u2192 set the date range \u2192 Export \u2192 CSV \u2192 use the "Pages" or "Queries" sheet.')),process.exitCode=1;return}let d=ca(c,a),p=new Date().toISOString(),m=Br(t,w,"strategy");Nm(m,{recursive:!0});let g=Br(m,"migration-plan.md");Dm(g,ua({domain:r,directionSummary:s,decisions:d,generatedAt:p}),"utf-8");let k=da(d);if(e.json){process.stdout.write(JSON.stringify({domain:r,directionSummary:s,source:u,summary:k,decisions:d},null,2)+`
490
+ `);return}l.success(`Migration plan written \u2192 ${nt.dim(g)} (${u})`),l.message(` ${nt.green(`${k.harvest} harvest`)} \xB7 ${nt.cyan(`${k.redirect} redirect`)} \xB7 ${nt.yellow(`${k.sunset} sunset`)} across ${k.total} legacy asset${k.total===1?"":"s"}`),l.info("Every disposition is backed by real GSC impressions/position. Redirects are listed as proposed 301s \u2014 pick a target per row, then apply (approval-gated).")}import{mkdirSync as Sa,writeFileSync as xa,readFileSync as Vm,readdirSync as Ym,existsSync as zm}from"fs";import{join as _a}from"path";import I from"picocolors";import{query as Jm}from"@anthropic-ai/claude-agent-sdk";import{join as Wr}from"path";var Hr="citations",Kr="scorecard.md",Fm="history",Mm=6,Um=1,Bm=12,Gm=5,En="Claude (web-grounded)";function Rn(e){return Wr(e,w,Hr)}function ma(e){return Wr(Rn(e),Kr)}function ga(e){return Wr(Rn(e),Fm)}function ha(e){return`${e.replace(/[:.]/g,"-")}.json`}function ya(e){return typeof e!="number"||!Number.isFinite(e)?Mm:Math.max(Um,Math.min(Bm,Math.floor(e)))}function An(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let o=typeof r=="string"?r.trim():"";if(!o)continue;let i=o.toLowerCase();if(!t.has(i)&&(t.add(i),n.push(o),n.length>=Gm))break}return n}function Tt(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function qr(e){let t=e.results.length,n={brand:e.brand,isYou:!0,surfaced:e.results.filter(o=>o.surfaced).length,total:t},r=e.competitors.map(o=>({brand:o,isYou:!1,surfaced:e.results.filter(i=>i.competitorsSurfaced.some(s=>s.toLowerCase()===o.toLowerCase())).length,total:t}));return r.sort((o,i)=>i.surfaced-o.surfaced||o.brand.localeCompare(i.brand)),[n,...r]}function wa(e,t){let{cited:n,total:r}=Tt(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function ba(e,t){if(!t)return null;let{cited:n}=Tt(e),r=new Map(t.results.map(s=>[s.query.toLowerCase(),s.surfaced])),o=[],i=[];for(let s of e.results){let a=r.get(s.query.toLowerCase());a!==void 0&&(s.surfaced&&!a&&o.push(s.query),!s.surfaced&&a&&i.push(s.query))}return{scoreDelta:n-t.cited,prevCited:t.cited,prevTotal:t.total,prevDate:t.generated_at.slice(0,10),newlyCited:o,newlyDropped:i}}function ka(e,t){let n=An(e.competitors),r=[`- Domain: ${e.domain}`,e.name?`- Business name: ${e.name}`:null,e.type?`- Business type: ${e.type}`:null,e.description?`- What it does: ${e.description}`:null,`- OKF knowledge bundle present in repo: ${e.hasOkfBundle?"yes":"no"}`,n.length?`- Competitors to track: ${n.join(", ")}`:null].filter(Boolean).join(`
482
491
  `),o=n.length?`
483
492
  4. For EACH question, also record which of these competitor brands appear in the cited sources: ${n.join(", ")}. Use these EXACT names in \`competitorsSurfaced\` (only the ones that actually appear; empty array if none). This powers a share-of-voice comparison.`:"",i=n.length?`,
484
493
  "competitorsSurfaced": [${JSON.stringify(n[0])}]`:`,
@@ -520,10 +529,10 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
520
529
  }
521
530
  \`\`\`
522
531
 
523
- \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown. \`competitors\` must echo the tracked list exactly (${n.length?n.join(", "):"empty when none were given"}).`}function la(e){if(typeof e!="string"||!e.trim())return null;let t=/```json\s*([\s\S]*?)```/gi,n=[],r;for(;(r=t.exec(e))!==null;)r[1].trim()&&n.push(r[1].trim());if(n.length===0)return null;for(let o=n.length-1;o>=0;o--){let i=gm(n[o]);if(i)return i}return null}function gm(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r,i=$n(Array.isArray(n.competitors)?n.competitors.map(c=>String(c)):[]),s=new Set(i.map(c=>c.toLowerCase()));if(!Array.isArray(n.results))return null;let a=[];for(let c of n.results){if(!c||typeof c!="object")continue;let u=c,d=typeof u.query=="string"?u.query.trim():"";if(!d)continue;let p=u.surfaced===!0,m=typeof u.rank=="number"&&Number.isFinite(u.rank)?Math.round(u.rank):null,g=typeof u.evidence=="string"?u.evidence.trim():"",b=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,h=Array.isArray(u.competitorsSurfaced)?hm(u.competitorsSurfaced.map(v=>typeof v=="string"?v.trim():"").filter(v=>v&&s.has(v.toLowerCase()))):[];a.push({query:d,surfaced:p,rank:p?m:null,evidence:g,source:b,competitorsSurfaced:h})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function hm(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}function ua(e,t){let{cited:n,total:r}=Rt(e),o=t.generatedAt.slice(0,10),i=e.results.some(p=>p.source),s=e.results.map((p,m)=>{let g=p.surfaced?"\u2705":"\u2014",b=p.surfaced&&p.rank?`#${p.rank}`:"\u2014",h=ie(p.evidence||(p.surfaced?"surfaced":"not found")),v=p.source?ie(ta(p.source)):"\u2014";return i?`| ${m+1} | ${ie(p.query)} | ${g} | ${b} | ${v} | ${h} |`:`| ${m+1} | ${ie(p.query)} | ${g} | ${b} | ${h} |`}).join(`
532
+ \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown. \`competitors\` must echo the tracked list exactly (${n.length?n.join(", "):"empty when none were given"}).`}function va(e){if(typeof e!="string"||!e.trim())return null;let t=/```json\s*([\s\S]*?)```/gi,n=[],r;for(;(r=t.exec(e))!==null;)r[1].trim()&&n.push(r[1].trim());if(n.length===0)return null;for(let o=n.length-1;o>=0;o--){let i=Wm(n[o]);if(i)return i}return null}function Wm(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r,i=An(Array.isArray(n.competitors)?n.competitors.map(c=>String(c)):[]),s=new Set(i.map(c=>c.toLowerCase()));if(!Array.isArray(n.results))return null;let a=[];for(let c of n.results){if(!c||typeof c!="object")continue;let u=c,d=typeof u.query=="string"?u.query.trim():"";if(!d)continue;let p=u.surfaced===!0,m=typeof u.rank=="number"&&Number.isFinite(u.rank)?Math.round(u.rank):null,g=typeof u.evidence=="string"?u.evidence.trim():"",k=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,h=Array.isArray(u.competitorsSurfaced)?Hm(u.competitorsSurfaced.map(v=>typeof v=="string"?v.trim():"").filter(v=>v&&s.has(v.toLowerCase()))):[];a.push({query:d,surfaced:p,rank:p?m:null,evidence:g,source:k,competitorsSurfaced:h})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function Hm(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}function $a(e,t){let{cited:n,total:r}=Tt(e),o=t.generatedAt.slice(0,10),i=e.results.some(p=>p.source),s=e.results.map((p,m)=>{let g=p.surfaced?"\u2705":"\u2014",k=p.surfaced&&p.rank?`#${p.rank}`:"\u2014",h=ie(p.evidence||(p.surfaced?"surfaced":"not found")),v=p.source?ie(fa(p.source)):"\u2014";return i?`| ${m+1} | ${ie(p.query)} | ${g} | ${k} | ${v} | ${h} |`:`| ${m+1} | ${ie(p.query)} | ${g} | ${k} | ${h} |`}).join(`
524
533
  `),a=i?`| # | Query | Cited? | ~Rank | Source cited | Evidence |
525
534
  |---|-------|--------|-------|--------------|----------|`:`| # | Query | Cited? | ~Rank | Evidence |
526
- |---|-------|--------|-------|----------|`,c=e.results.filter(p=>!p.surfaced),u=c.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":c.map(p=>{let m=p.source?` _(currently cited: ${ie(ta(p.source))})_`:"";return`- **${ie(p.query)}** \u2014 ${p.evidence||"not surfaced"}${m}`}).join(`
535
+ |---|-------|--------|-------|----------|`,c=e.results.filter(p=>!p.surfaced),u=c.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":c.map(p=>{let m=p.source?` _(currently cited: ${ie(fa(p.source))})_`:"";return`- **${ie(p.query)}** \u2014 ${p.evidence||"not surfaced"}${m}`}).join(`
527
536
  `),d=c.length?"- Enrich the Open Knowledge Format bundle so answer engines understand the business: run `seoagent okf scaffold` then fill it (the skill maps your `.seoagent/` knowledge into it), and publish it at `/.well-known/okf/`.\n- Cover the missed questions directly in your content (a page or FAQ that answers each one), then re-run `seoagent citations`.":"- Keep the OKF bundle current as the business evolves, and re-run to catch regressions.";return`---
528
537
  type: Report
529
538
  title: AI Citation Scorecard \u2014 ${e.domain}
@@ -538,11 +547,11 @@ engine: claude-web-grounded
538
547
  > measurement half of the AEO/GEO loop \u2014 \`seoagent okf\` makes you citable, this
539
548
  > tells you whether it's working.
540
549
 
541
- **Cited: ${n} / ${r} queries** \xB7 engine: ${kn} \xB7 ${o}
542
- ${ym(t.trend,n,r)}
550
+ **Cited: ${n} / ${r} queries** \xB7 engine: ${En} \xB7 ${o}
551
+ ${Km(t.trend,n,r)}
543
552
  ${a}
544
553
  ${s}
545
- ${wm(e)}
554
+ ${qm(e)}
546
555
  ## Where you're not surfacing (opportunities)
547
556
 
548
557
  ${u}
@@ -566,13 +575,13 @@ This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
566
575
  rank and cite differently, and tracking them individually is a planned
567
576
  follow-up. Treat the score as directional \u2014 watch the trend rather than fixating
568
577
  on a single number.
569
- `}function ym(e,t,n){if(!e)return`
578
+ `}function Km(e,t,n){if(!e)return`
570
579
  _First run \u2014 re-run on a cadence to start tracking the trend._
571
580
  `;let r=e.scoreDelta>0?`\u25B2 up ${e.scoreDelta}`:e.scoreDelta<0?`\u25BC down ${Math.abs(e.scoreDelta)}`:"\u25AA no change",o=`
572
581
  **Trend:** ${t}/${n} this run \u2014 ${r} from ${e.prevCited}/${e.prevTotal} on ${e.prevDate}.`;return e.newlyCited.length&&(o+=`
573
582
  - \u2705 Newly cited: ${e.newlyCited.map(i=>`_${ie(i)}_`).join("; ")}`),e.newlyDropped.length&&(o+=`
574
583
  - \u26A0\uFE0F Dropped: ${e.newlyDropped.map(i=>`_${ie(i)}_`).join("; ")}`),o+`
575
- `}function wm(e){if(!e.competitors.length)return"";let t=Ur(e).map(n=>{let r=n.isYou?`**${ie(n.brand)} (you)**`:ie(n.brand),o=n.total>0?`${Math.round(n.surfaced/n.total*100)}%`:"\u2014";return`| ${r} | ${n.surfaced} / ${n.total} | ${o} |`}).join(`
584
+ `}function qm(e){if(!e.competitors.length)return"";let t=qr(e).map(n=>{let r=n.isYou?`**${ie(n.brand)} (you)**`:ie(n.brand),o=n.total>0?`${Math.round(n.surfaced/n.total*100)}%`:"\u2014";return`| ${r} | ${n.surfaced} / ${n.total} | ${o} |`}).join(`
576
585
  `);return`
577
586
  ## Share of voice
578
587
 
@@ -581,17 +590,17 @@ How often each brand surfaces across the same ${e.results.length} queries.
581
590
  | Brand | Surfaced | Rate |
582
591
  |-------|----------|------|
583
592
  ${t}
584
- `}function ta(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function ie(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function Et(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=vt();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(ce[r].summary),ce[r].next&&l.message(` ${ce[r].next}`),process.exitCode=1;return}l.info(I.dim(ce[r].summary));let o=Yt(t),i=hn(t),s=$n(e.competitors&&e.competitors.length?e.competitors:Cm(o?.business.competitors)),a={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0,competitors:s},c=ia(e.queries);l.message(`${I.cyan("\u25C7")} Auditing AI citations for ${I.bold(a.domain)} \u2014 ${c} web-grounded quer${c===1?"y":"ies"} via ${kn}.`),l.message(I.dim(` This runs live web searches and can take a minute\u2026
585
- `));let u=ca(a,c),d=await Sm({cwd:t,prompt:u,model:e.model});if(d===null){process.exitCode=1;return}let p=la(d);if(!p){l.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let m=new Date().toISOString(),g=ra(t),b=Rm(g),h=aa(p,b),v=ua(p,{generatedAt:m,trend:h});da(vn(t),{recursive:!0}),pa(na(t),v,"utf-8"),da(g,{recursive:!0}),pa(fa(g,oa(m)),JSON.stringify(sa(p,{generatedAt:m}),null,2)+`
586
- `,"utf-8");let{cited:x,total:S}=Rt(p),j=x===0?I.red:x<S?I.yellow:I.green,O=[{content:I.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${I.cyan(p.domain)}`},{content:`Cited: ${j(`${x} / ${S}`)} ${I.dim("queries")}`}];if(h){let X=h.scoreDelta>0?I.green(`\u25B2 +${h.scoreDelta}`):h.scoreDelta<0?I.red(`\u25BC ${h.scoreDelta}`):I.dim("\u25AA 0");O.push({content:`Trend: ${X} ${I.dim(`vs ${h.prevCited}/${h.prevTotal} on ${h.prevDate}`)}`})}else O.push({content:I.dim("Trend: first run \u2014 re-run to start tracking")});if(O.push({content:`Engine: ${I.dim(kn)}`}),p.competitors.length){O.push({sep:!0}),O.push({content:I.dim("Share of voice:")});for(let X of Ur(p)){let Z=X.isYou?I.bold(`${X.brand} (you)`):X.brand;O.push({content:` ${Z}: ${X.surfaced}/${X.total}`})}}O.push({sep:!0}),O.push({content:I.dim(`Saved \u2192 .seoagent/${Dr}/${Fr}`)}),O.push({content:x<S?I.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):I.dim("Surfacing across the board. Re-run periodically to catch drift.")}),l.message(D(O,{title:I.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(p,null,2)+`
587
- `)}async function Sm(e){let{cwd:t,prompt:n,model:r}=e;try{let o=$m({prompt:n,options:{cwd:t,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}}),i="";for await(let s of o)if(s.type==="assistant"){let a=s.message.content;if(Array.isArray(a))for(let c of a)xm(c)}else if(s.type==="result"){if(process.stdout.write(`
593
+ `}function fa(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function ie(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function Lt(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=Ct();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(ce[r].summary),ce[r].next&&l.message(` ${ce[r].next}`),process.exitCode=1;return}l.info(I.dim(ce[r].summary));let o=tn(t),i=Sn(t),s=An(e.competitors&&e.competitors.length?e.competitors:eg(o?.business.competitors)),a={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0,competitors:s},c=ya(e.queries);l.message(`${I.cyan("\u25C7")} Auditing AI citations for ${I.bold(a.domain)} \u2014 ${c} web-grounded quer${c===1?"y":"ies"} via ${En}.`),l.message(I.dim(` This runs live web searches and can take a minute\u2026
594
+ `));let u=ka(a,c),d=await Xm({cwd:t,prompt:u,model:e.model});if(d===null){process.exitCode=1;return}let p=va(d);if(!p){l.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let m=new Date().toISOString(),g=ga(t),k=tg(g),h=ba(p,k),v=$a(p,{generatedAt:m,trend:h});Sa(Rn(t),{recursive:!0}),xa(ma(t),v,"utf-8"),Sa(g,{recursive:!0}),xa(_a(g,ha(m)),JSON.stringify(wa(p,{generatedAt:m}),null,2)+`
595
+ `,"utf-8");let{cited:x,total:S}=Tt(p),j=x===0?I.red:x<S?I.yellow:I.green,O=[{content:I.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${I.cyan(p.domain)}`},{content:`Cited: ${j(`${x} / ${S}`)} ${I.dim("queries")}`}];if(h){let X=h.scoreDelta>0?I.green(`\u25B2 +${h.scoreDelta}`):h.scoreDelta<0?I.red(`\u25BC ${h.scoreDelta}`):I.dim("\u25AA 0");O.push({content:`Trend: ${X} ${I.dim(`vs ${h.prevCited}/${h.prevTotal} on ${h.prevDate}`)}`})}else O.push({content:I.dim("Trend: first run \u2014 re-run to start tracking")});if(O.push({content:`Engine: ${I.dim(En)}`}),p.competitors.length){O.push({sep:!0}),O.push({content:I.dim("Share of voice:")});for(let X of qr(p)){let Z=X.isYou?I.bold(`${X.brand} (you)`):X.brand;O.push({content:` ${Z}: ${X.surfaced}/${X.total}`})}}O.push({sep:!0}),O.push({content:I.dim(`Saved \u2192 .seoagent/${Hr}/${Kr}`)}),O.push({content:x<S?I.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):I.dim("Surfacing across the board. Re-run periodically to catch drift.")}),l.message(D(O,{title:I.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(p,null,2)+`
596
+ `)}async function Xm(e){let{cwd:t,prompt:n,model:r}=e;try{let o=Jm({prompt:n,options:{cwd:t,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}}),i="";for await(let s of o)if(s.type==="assistant"){let a=s.message.content;if(Array.isArray(a))for(let c of a)Qm(c)}else if(s.type==="result"){if(process.stdout.write(`
588
597
  `),!(s.subtype==="success"&&!s.is_error))return l.error(" Agent did not complete the citation audit (rate limit, auth, or network)."),null;i=String(s.result??"")}return i}catch(o){return process.stdout.write(`
589
- `),l.error(` Agent error: ${o.message}`),null}}function xm(e){if(!e||typeof e!="object")return;let t=e.type;if(t==="text"){let n=e.text;typeof n=="string"&&n&&process.stdout.write(dn(n));return}if(t==="tool_use"){let n=String(e.name??"tool"),r=e.input,o=n==="WebSearch"?String(r?.query??""):n==="WebFetch"?String(r?.url??""):"";process.stdout.write(I.dim(` ${I.magenta("\u{1F50E}")} ${n}${o?` ${_m(o,70)}`:""}
590
- `))}}function _m(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Cm(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function Rm(e){try{if(!vm(e))return null;let t=km(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(bm(fa(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import tt from"picocolors";var Em=30,Am=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi;function Pm(e){let t=e,n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t);n&&(t=n[1]),t=t.replace(Am," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&[a-z]+;/gi," ").replace(/\s+/g," ").trim();let r=t===""?0:t.split(" ").filter(Boolean).length;return{wordCount:r,rendered:r<Em?"empty":"yes"}}async function Im(e,t){try{let n=await P(e,{headers:{"user-agent":"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) SEOAgent-CLI"},redirect:"follow"},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!n.ok)return{status:n.status,rendered:"error",wordCount:0};let r=await n.text(),{wordCount:o,rendered:i}=Pm(r);return{status:n.status,rendered:i,wordCount:o}}catch{return{status:null,rendered:"error",wordCount:0}}}async function ma(e,t={}){let n=Math.max(1,t.concurrency??5),r=new Map,o=[...e],i=0;async function s(){for(;;){let a=o.shift();if(a===void 0)return;r.set(a,await Im(a,t.fetchImpl)),i+=1,t.onProgress?.(i,e.length)}}return await Promise.all(Array.from({length:Math.min(n,e.length)},()=>s())),r}var Mr=300;async function At(e={}){if(e.all){await Om();return}let t=process.cwd();if(!L(t))return;$e(t);let n=cr(t);ha(t);let r=await ga(t,{enrichSitemap:!0,crawl:e.crawl});if(n.reason==="refreshed"?(l.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),l.info("Your `.seoagent/` knowledge was left untouched.")):(l.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?l.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&l.info(`Page inventory already current (${r.total} pages).`),r.crawl){let{crawled:o,empty:i,errors:s}=r.crawl;l.success(`Crawled ${o} page${o===1?"":"s"} \u2192 filled Status / Rendered / Word count`+(i>0?`, ${i} render empty`:"")+(s>0?`, ${s} unreachable`:"")+".")}}async function ga(e,t={}){try{let n=E(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=ne(e,r);t.enrichSitemap&&r&&await Jo(o,r);let i,s;if(t.crawl&&r){let c=o.map(d=>d.url).filter(d=>/^https?:\/\//.test(d)),u=c.slice(0,Mr);if(c.length>Mr&&l.info(`Crawling the first ${Mr} of ${c.length} pages (cap).`),u.length>0){l.info(`Crawling ${u.length} page${u.length===1?"":"s"}\u2026`),s=await ma(u);let d=0,p=0;for(let m of s.values())m.rendered==="empty"?d++:m.rendered==="error"&&p++;i={crawled:s.size,empty:d,errors:p}}}let a=Xt(e,o,s);return{added:a.added,total:a.total,crawl:i}}catch{return{added:0,total:0}}}async function Om(){let e=Po();if(e.length===0){l.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}l.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${tt.bold(A)}\u2026`);let t=0,n=0;for(let r of e){let o=cr(r);ha(r);let i=await ga(r),s=i.added>0?tt.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?tt.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${tt.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${tt.yellow("!")} ${r} ${tt.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${A}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function ha(e){try{ve(e)}catch{}}import{spinner as Gr,confirm as Tm,isCancel as Lm}from"@clack/prompts";import w from"picocolors";var wa={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function jm(e){let t=process.cwd(),n=Wt(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=E(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||T.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Gr():null;a?.start(`Looking up ${w.bold(`"${e.keyword}"`)} ${w.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await P(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){$(a,"error",`Network error: ${d.message}`,w.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await c.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:c.status,body:u??null})+`
591
- `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";$(a,"warn",`Daily peek quota reached for ${d}.`,w.yellow(`Daily peek quota reached for ${d}.`)),l.message(ya()),process.exitCode=1;return}if(!c.ok||!u){$(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,w.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){$(a,"warn","Real keyword data is temporarily unavailable. Try again later.",w.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(w.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){$(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",w.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){$(a,"warn",`No data returned for "${e.keyword}".`,w.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(w.green("Got it.")),l.message(Nm(u.opportunity)),u.remaining&&l.message(`${w.dim("Peeks remaining today:")} ${w.bold(String(u.remaining.install))} ${w.dim("\u2014 "+ya())}`)}function Nm(e){let n=u=>w.dim(u.padEnd(14)),r=e.volume!=null?w.bold(String(e.volume)):w.dim("n/a"),o=e.difficulty!=null?`${w.bold(String(e.difficulty))} ${w.dim(Dm(e.difficulty))}`:w.dim("n/a"),i=wa[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?w.bold(w.green(i)):e.opportunity==="striking_distance"?w.bold(w.cyan(i)):e.opportunity==="competitor_gap"?w.bold(w.yellow(i)):w.dim(i),a=[{content:`${w.green("\u25CF")} ${w.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${w.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${w.bold(w.cyan("Keyword peek"))}`;return D(a,{width:55,title:c})}function Dm(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function ya(e=N()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota). Pro unlocks the full inventory beyond the ~25 cap plus \`${f("keywords --discover")}\` (new targets) + \`${f("keywords --competitors")}\` (competitor gaps): ${f("upgrade")}.`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Br(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){l.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";l.message(` \u2022 [${wa[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Fm(e){if(e.length!==0){l.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";l.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function Um(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await Tm({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(Lm(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||T.BASE,r=process.stdout.isTTY?Gr():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await P(`${n}/api/cli/keywords/purge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.auth.user_token}:${e.auth.website_token}`},body:JSON.stringify({scope:t})})}catch(a){$(r,"error",`Network error: ${a.message}`,w.red("Network error.")),process.exitCode=1;return}let i=null;try{i=await o.json()}catch{i=null}if(i?.skipped==="no-table"||i?.skipped==="no-columns"){$(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",w.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){$(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,w.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;$(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,w.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(w.dim(t==="all"?"Cleared the cloud inventory. Re-run `seoagent keywords --seed` / strategy to rebuild it.":"Cleared discovery noise. Your clustered keywords were kept."))}async function we(e={}){if(e.peek&&e.peek.trim().length>0){await jm({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=N();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await Um({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||T.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":e.seed?"seed":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":o==="seed"?"/api/cli/keywords/seed":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":o==="seed"?"Seeding keywords from your Search Console data\u2026":"Enriching keywords with real volume + difficulty\u2026",c=!!process.stdout.isTTY?Gr():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await P(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(g){$(c,"error",`Network error: ${g.message}`,w.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await d.json()}catch{p=null}if(d.status===402||p?.code==="upgrade_required"){$(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",w.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${w.cyan(ee("cli-keywords-competitors"))}`:`Upgrade to find new keywords to target: ${w.cyan(ee("cli-keywords-discover"))}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){$(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,w.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){$(c,"warn","No Search Console data to seed from yet. Connect Google Search Console (run `seoagent login` and link GSC) \u2014 or wait for impressions to accrue on a new site.",w.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){$(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",w.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){$(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",w.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){$(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",w.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){$(c,"warn",`Skipped: ${p.skipped}`,w.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let g=p.gaps??0;$(c,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,w.green(`${g} competitor gap${g===1?"":"s"} found.`)),Fm(p.topGaps??[]),l.message(`Review them in ${w.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Keep the on-topic ones for your clusters; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="discover"){let g=p.discovered??0;$(c,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,w.green(`${g} new keyword${g===1?"":"s"} discovered.`)),Br(p.opportunities??[]),l.message(`Review them in ${w.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Relevance-check before adopting; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="seed"){let g=p.seeded??0;$(c,"success",`Seeded ${g} keyword${g===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,w.green(`${g} keyword${g===1?"":"s"} seeded from Search Console.`)),Br(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${w.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let m=p.enriched??0;$(c,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,w.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),Br(p.opportunities??[]),p.paid||l.message(`${w.dim("Free plan:")} enriched up to ${w.bold(String(p.cap??25))} keywords. ${w.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${w.cyan(ee("cli-keywords-cap"))}`)}import F from"picocolors";function Pt(e={}){let t=process.cwd(),n=E(t),r=fe(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
592
- `);return}if(l.message(Mm(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}q(t,{image_provider:r.provider}),l.info(`Saved to ${F.cyan(".seoagent/project.md")} ${F.dim(`(image_provider: ${r.provider})`)}`)}function Mm(e){let n=i=>F.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${F.dim("\u25CB")} ${F.bold(F.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:F.dim("Set ONE of these to enable image generation:")});let i=Wo();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${F.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:F.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${F.cyan(f("env-check"))}`})}else{r.push({content:`${F.green("\u2713")} ${F.dim("Image provider:")} ${F.bold(F.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${F.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${F.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${F.dim(i.join(", "))}`})}let o=`${F.bold(F.cyan("SEOAgent"))} ${F.dim("\xB7")} ${F.dim("env-check")}`;return D(r,{width:64,title:o})}import{existsSync as Hr,mkdirSync as va,writeFileSync as $a}from"fs";import{dirname as xn,isAbsolute as Km,join as Sn,resolve as qm}from"path";import{tmpdir as Vm}from"os";import{spinner as zm}from"@clack/prompts";import B from"picocolors";import{Buffer as ba}from"buffer";async function Wr(e){let t=await fetch(e);if(!t.ok)throw new Error(`Image download failed: ${t.status} ${t.statusText}`);let n=await t.arrayBuffer();return ba.from(n)}async function Bm(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let o=(await n.json()).data?.[0];if(!o)throw new Error("OpenAI image API returned no data");if(o.b64_json)return{bytes:ba.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Wr(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Gm(e){let t=process.env.FAL_MODEL||"fal-ai/flux/schnell",n=await fetch(`https://fal.run/${t}`,{method:"POST",headers:{Authorization:`Key ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({prompt:e.prompt,image_size:"landscape_16_9",num_images:1})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`fal.ai API ${n.status}: ${s.slice(0,300)}`)}let o=(await n.json()).images?.[0];if(!o?.url)throw new Error("fal.ai API returned no image url");return{bytes:await Wr(o.url),contentType:o.content_type??"image/png"}}async function Wm(e,t,n=9e4){let r=Date.now(),o=1e3;for(;Date.now()-r<n;){let i=await fetch(`https://api.replicate.com/v1/predictions/${e}`,{headers:{Authorization:`Token ${t}`}});if(!i.ok)throw new Error(`Replicate poll failed: ${i.status}`);let s=await i.json();if(s.status==="succeeded"||s.status==="failed"||s.status==="canceled")return s;await new Promise(a=>setTimeout(a,o)),o=Math.min(o*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function Hm(e){let t=process.env.REPLICATE_MODEL||"black-forest-labs/flux-schnell",n=await fetch(`https://api.replicate.com/v1/models/${t}/predictions`,{method:"POST",headers:{Authorization:`Token ${e.apiKey}`,"Content-Type":"application/json",Prefer:"wait"},body:JSON.stringify({input:{prompt:e.prompt,aspect_ratio:"16:9"}})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Replicate API ${n.status}: ${s.slice(0,300)}`)}let r=await n.json();if(r.status!=="succeeded"&&r.status!=="failed"&&(r=await Wm(r.id,e.apiKey)),r.status!=="succeeded")throw new Error(`Replicate prediction ${r.status}: ${r.error??""}`);let o=Array.isArray(r.output)?r.output[0]:r.output;if(!o)throw new Error("Replicate prediction returned no output");return{bytes:await Wr(o),contentType:"image/png",providerImageId:r.id}}async function ka(e,t){switch(e){case"openai":return Bm(t);case"fal":return Gm(t);case"replicate":return Hm(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Ym(e){return e==="openai"||e==="fal"||e==="replicate"}async function It(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=E(t),r=null;if(e.provider){if(!Ym(e.provider)){l.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}r=e.provider}else n?.image_provider&&n.image_provider!=="none"?r=n.image_provider:r=fe(t).provider;if(!r||r==="none"){l.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=Go(t,r);if(!o){l.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=Km(e.out)?e.out:qm(t,e.out),a=!e.silent&&!!process.stdout.isTTY?zm():null;a?.start(`Generating image with ${B.bold(r)} ${B.dim(`(${o.envName})`)}\u2026`);try{let c=await ka(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Hr(xn(i))||va(xn(i),{recursive:!0}),$a(i,c.bytes),e.silent||$(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,B.green(`Wrote ${i} ${B.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(B.red("Image generation failed."));let u=Xm(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Jm({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${B.dim("Full error log:")} ${B.cyan(u)}`),process.exitCode=1}}function Jm(e){let n=d=>B.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${B.red("\u2717")} ${B.bold(B.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${B.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${B.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:B.red(c)});let u=`${B.bold(B.cyan("SEOAgent"))} ${B.dim("\xB7")} ${B.dim("generate-image")}`;return D(i,{width:70,title:u})}function Xm(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Sn(e,k),i=Sn(o,".errors"),s=Hr(o)?Sn(i,r):Sn(Vm(),r),a=["# SEOAgent generate-image error",`# ${new Date().toISOString()}`,"","## Request",`provider: ${t.provider}`,`env_var: ${t.envName}`,`prompt: ${JSON.stringify(t.prompt)}`,`size: ${t.size??"(default)"}`,`out_path: ${t.outPath}`,`cwd: ${e}`,"","## Error",`message: ${t.error.message}`,"","## Stack",t.error.stack??"(no stack)",""];t.error.cause&&a.push("## Cause",String(t.error.cause),"");try{return Hr(xn(s))||va(xn(s),{recursive:!0}),$a(s,a.join(`
593
- `)),s}catch{return null}}import K from"picocolors";async function Ot(e={}){let t=N();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
594
- `):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||T.BASE).replace(/\/$/,""),r=`Bearer ${t.user_token}:${t.website_token}`,o;try{o=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:r,Accept:"application/json"}})}catch(s){l.error(`Network error: ${s.message}`),process.exitCode=1;return}if(o.status===404){if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,server_supports_whoami:!1,api_base:n})}
598
+ `),l.error(` Agent error: ${o.message}`),null}}function Qm(e){if(!e||typeof e!="object")return;let t=e.type;if(t==="text"){let n=e.text;typeof n=="string"&&n&&process.stdout.write(wn(n));return}if(t==="tool_use"){let n=String(e.name??"tool"),r=e.input,o=n==="WebSearch"?String(r?.query??""):n==="WebFetch"?String(r?.url??""):"";process.stdout.write(I.dim(` ${I.magenta("\u{1F50E}")} ${n}${o?` ${Zm(o,70)}`:""}
599
+ `))}}function Zm(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function eg(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function tg(e){try{if(!zm(e))return null;let t=Ym(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(Vm(_a(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import rt from"picocolors";var ng=30,rg=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi;function og(e){let t=e,n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t);n&&(t=n[1]),t=t.replace(rg," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&[a-z]+;/gi," ").replace(/\s+/g," ").trim();let r=t===""?0:t.split(" ").filter(Boolean).length;return{wordCount:r,rendered:r<ng?"empty":"yes"}}async function ig(e,t){try{let n=await P(e,{headers:{"user-agent":"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) SEOAgent-CLI"},redirect:"follow"},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!n.ok)return{status:n.status,rendered:"error",wordCount:0};let r=await n.text(),{wordCount:o,rendered:i}=og(r);return{status:n.status,rendered:i,wordCount:o}}catch{return{status:null,rendered:"error",wordCount:0}}}async function Ca(e,t={}){let n=Math.max(1,t.concurrency??5),r=new Map,o=[...e],i=0;async function s(){for(;;){let a=o.shift();if(a===void 0)return;r.set(a,await ig(a,t.fetchImpl)),i+=1,t.onProgress?.(i,e.length)}}return await Promise.all(Array.from({length:Math.min(n,e.length)},()=>s())),r}var Vr=300;async function jt(e={}){if(e.all){await sg();return}let t=process.cwd();if(!L(t))return;xe(t);let n=mr(t);Ra(t);let r=await Ea(t,{enrichSitemap:!0,crawl:e.crawl});if(n.reason==="refreshed"?(l.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),l.info("Your `.seoagent/` knowledge was left untouched.")):(l.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?l.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&l.info(`Page inventory already current (${r.total} pages).`),r.crawl){let{crawled:o,empty:i,errors:s}=r.crawl;l.success(`Crawled ${o} page${o===1?"":"s"} \u2192 filled Status / Rendered / Word count`+(i>0?`, ${i} render empty`:"")+(s>0?`, ${s} unreachable`:"")+".")}}async function Ea(e,t={}){try{let n=R(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=ne(e,r);t.enrichSitemap&&r&&await ii(o,r);let i,s;if(t.crawl&&r){let c=o.map(d=>d.url).filter(d=>/^https?:\/\//.test(d)),u=c.slice(0,Vr);if(c.length>Vr&&l.info(`Crawling the first ${Vr} of ${c.length} pages (cap).`),u.length>0){l.info(`Crawling ${u.length} page${u.length===1?"":"s"}\u2026`),s=await Ca(u);let d=0,p=0;for(let m of s.values())m.rendered==="empty"?d++:m.rendered==="error"&&p++;i={crawled:s.size,empty:d,errors:p}}}let a=rn(e,o,s);return{added:a.added,total:a.total,crawl:i}}catch{return{added:0,total:0}}}async function sg(){let e=Mo();if(e.length===0){l.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}l.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${rt.bold(A)}\u2026`);let t=0,n=0;for(let r of e){let o=mr(r);Ra(r);let i=await Ea(r),s=i.added>0?rt.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?rt.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${rt.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${rt.yellow("!")} ${r} ${rt.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${A}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Ra(e){try{Se(e)}catch{}}import{spinner as zr,confirm as ag,isCancel as cg}from"@clack/prompts";import b from"picocolors";var Pa={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function lg(e){let t=process.cwd(),n=Yt(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=R(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||T.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?zr():null;a?.start(`Looking up ${b.bold(`"${e.keyword}"`)} ${b.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await P(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){$(a,"error",`Network error: ${d.message}`,b.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await c.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:c.status,body:u??null})+`
600
+ `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";$(a,"warn",`Daily peek quota reached for ${d}.`,b.yellow(`Daily peek quota reached for ${d}.`)),l.message(Aa()),process.exitCode=1;return}if(!c.ok||!u){$(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,b.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){$(a,"warn","Real keyword data is temporarily unavailable. Try again later.",b.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(b.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){$(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",b.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){$(a,"warn",`No data returned for "${e.keyword}".`,b.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(b.green("Got it.")),l.message(ug(u.opportunity)),u.remaining&&l.message(`${b.dim("Peeks remaining today:")} ${b.bold(String(u.remaining.install))} ${b.dim("\u2014 "+Aa())}`)}function ug(e){let n=u=>b.dim(u.padEnd(14)),r=e.volume!=null?b.bold(String(e.volume)):b.dim("n/a"),o=e.difficulty!=null?`${b.bold(String(e.difficulty))} ${b.dim(dg(e.difficulty))}`:b.dim("n/a"),i=Pa[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?b.bold(b.green(i)):e.opportunity==="striking_distance"?b.bold(b.cyan(i)):e.opportunity==="competitor_gap"?b.bold(b.yellow(i)):b.dim(i),a=[{content:`${b.green("\u25CF")} ${b.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${b.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${b.bold(b.cyan("Keyword peek"))}`;return D(a,{width:55,title:c})}function dg(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Aa(e=N()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota). Pro unlocks the full inventory beyond the ~25 cap plus \`${f("keywords --discover")}\` (new targets) + \`${f("keywords --competitors")}\` (competitor gaps): ${f("upgrade")}.`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Yr(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){l.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";l.message(` \u2022 [${Pa[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function pg(e){if(e.length!==0){l.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";l.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function fg(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await ag({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(cg(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||T.BASE,r=process.stdout.isTTY?zr():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await P(`${n}/api/cli/keywords/purge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.auth.user_token}:${e.auth.website_token}`},body:JSON.stringify({scope:t})})}catch(a){$(r,"error",`Network error: ${a.message}`,b.red("Network error.")),process.exitCode=1;return}let i=null;try{i=await o.json()}catch{i=null}if(i?.skipped==="no-table"||i?.skipped==="no-columns"){$(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",b.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){$(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,b.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;$(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,b.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(b.dim(t==="all"?"Cleared the cloud inventory. Re-run `seoagent keywords --seed` / strategy to rebuild it.":"Cleared discovery noise. Your clustered keywords were kept."))}async function be(e={}){if(e.peek&&e.peek.trim().length>0){await lg({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=N();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await fg({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||T.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":e.seed?"seed":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":o==="seed"?"/api/cli/keywords/seed":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":o==="seed"?"Seeding keywords from your Search Console data\u2026":"Enriching keywords with real volume + difficulty\u2026",c=!!process.stdout.isTTY?zr():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await P(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(g){$(c,"error",`Network error: ${g.message}`,b.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await d.json()}catch{p=null}if(d.status===402||p?.code==="upgrade_required"){$(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",b.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${b.cyan(ee("cli-keywords-competitors"))}`:`Upgrade to find new keywords to target: ${b.cyan(ee("cli-keywords-discover"))}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){$(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,b.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){$(c,"warn","No Search Console data to seed from yet. Connect Google Search Console (run `seoagent login` and link GSC) \u2014 or wait for impressions to accrue on a new site.",b.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){$(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",b.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){$(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",b.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){$(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",b.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){$(c,"warn",`Skipped: ${p.skipped}`,b.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let g=p.gaps??0;$(c,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,b.green(`${g} competitor gap${g===1?"":"s"} found.`)),pg(p.topGaps??[]),l.message(`Review them in ${b.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Keep the on-topic ones for your clusters; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="discover"){let g=p.discovered??0;$(c,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,b.green(`${g} new keyword${g===1?"":"s"} discovered.`)),Yr(p.opportunities??[]),l.message(`Review them in ${b.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Relevance-check before adopting; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="seed"){let g=p.seeded??0;$(c,"success",`Seeded ${g} keyword${g===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,b.green(`${g} keyword${g===1?"":"s"} seeded from Search Console.`)),Yr(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${b.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let m=p.enriched??0;$(c,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,b.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),Yr(p.opportunities??[]),p.paid||l.message(`${b.dim("Free plan:")} enriched up to ${b.bold(String(p.cap??25))} keywords. ${b.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${b.cyan(ee("cli-keywords-cap"))}`)}import F from"picocolors";function Nt(e={}){let t=process.cwd(),n=R(t),r=me(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
601
+ `);return}if(l.message(mg(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}q(t,{image_provider:r.provider}),l.info(`Saved to ${F.cyan(".seoagent/project.md")} ${F.dim(`(image_provider: ${r.provider})`)}`)}function mg(e){let n=i=>F.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${F.dim("\u25CB")} ${F.bold(F.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:F.dim("Set ONE of these to enable image generation:")});let i=Qo();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${F.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:F.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${F.cyan(f("env-check"))}`})}else{r.push({content:`${F.green("\u2713")} ${F.dim("Image provider:")} ${F.bold(F.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${F.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${F.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${F.dim(i.join(", "))}`})}let o=`${F.bold(F.cyan("SEOAgent"))} ${F.dim("\xB7")} ${F.dim("env-check")}`;return D(r,{width:64,title:o})}import{existsSync as Qr,mkdirSync as Ta,writeFileSync as La}from"fs";import{dirname as In,isAbsolute as vg,join as Pn,resolve as $g}from"path";import{tmpdir as Sg}from"os";import{spinner as xg}from"@clack/prompts";import B from"picocolors";import{Buffer as Ia}from"buffer";var gg=6e4,Jr=18e4,hg=15e3;async function Xr(e){let t=await fetch(e,{signal:AbortSignal.timeout(gg)});if(!t.ok)throw new Error(`Image download failed: ${t.status} ${t.statusText}`);let n=await t.arrayBuffer();return Ia.from(n)}async function yg(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1}),signal:AbortSignal.timeout(Jr)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let o=(await n.json()).data?.[0];if(!o)throw new Error("OpenAI image API returned no data");if(o.b64_json)return{bytes:Ia.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Xr(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function wg(e){let t=process.env.FAL_MODEL||"fal-ai/flux/schnell",n=await fetch(`https://fal.run/${t}`,{method:"POST",headers:{Authorization:`Key ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({prompt:e.prompt,image_size:"landscape_16_9",num_images:1}),signal:AbortSignal.timeout(Jr)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`fal.ai API ${n.status}: ${s.slice(0,300)}`)}let o=(await n.json()).images?.[0];if(!o?.url)throw new Error("fal.ai API returned no image url");return{bytes:await Xr(o.url),contentType:o.content_type??"image/png"}}async function bg(e,t,n=9e4){let r=Date.now(),o=1e3;for(;Date.now()-r<n;){let i=await fetch(`https://api.replicate.com/v1/predictions/${e}`,{headers:{Authorization:`Token ${t}`},signal:AbortSignal.timeout(hg)});if(!i.ok)throw new Error(`Replicate poll failed: ${i.status}`);let s=await i.json();if(s.status==="succeeded"||s.status==="failed"||s.status==="canceled")return s;await new Promise(a=>setTimeout(a,o)),o=Math.min(o*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function kg(e){let t=process.env.REPLICATE_MODEL||"black-forest-labs/flux-schnell",n=await fetch(`https://api.replicate.com/v1/models/${t}/predictions`,{method:"POST",headers:{Authorization:`Token ${e.apiKey}`,"Content-Type":"application/json",Prefer:"wait"},body:JSON.stringify({input:{prompt:e.prompt,aspect_ratio:"16:9"}}),signal:AbortSignal.timeout(Jr)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Replicate API ${n.status}: ${s.slice(0,300)}`)}let r=await n.json();if(r.status!=="succeeded"&&r.status!=="failed"&&(r=await bg(r.id,e.apiKey)),r.status!=="succeeded")throw new Error(`Replicate prediction ${r.status}: ${r.error??""}`);let o=Array.isArray(r.output)?r.output[0]:r.output;if(!o)throw new Error("Replicate prediction returned no output");return{bytes:await Xr(o),contentType:"image/png",providerImageId:r.id}}async function Oa(e,t){switch(e){case"openai":return yg(t);case"fal":return wg(t);case"replicate":return kg(t);default:throw new Error(`Unknown image provider: ${e}`)}}function _g(e){return e==="openai"||e==="fal"||e==="replicate"}async function Dt(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=R(t),r=null;if(e.provider){if(!_g(e.provider)){l.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}r=e.provider}else n?.image_provider&&n.image_provider!=="none"?r=n.image_provider:r=me(t).provider;if(!r||r==="none"){l.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=Xo(t,r);if(!o){l.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=vg(e.out)?e.out:$g(t,e.out),a=!e.silent&&!!process.stdout.isTTY?xg():null;a?.start(`Generating image with ${B.bold(r)} ${B.dim(`(${o.envName})`)}\u2026`);try{let c=await Oa(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Qr(In(i))||Ta(In(i),{recursive:!0}),La(i,c.bytes),e.silent||$(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,B.green(`Wrote ${i} ${B.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(B.red("Image generation failed."));let u=Eg(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Cg({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${B.dim("Full error log:")} ${B.cyan(u)}`),process.exitCode=1}}function Cg(e){let n=d=>B.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${B.red("\u2717")} ${B.bold(B.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${B.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${B.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:B.red(c)});let u=`${B.bold(B.cyan("SEOAgent"))} ${B.dim("\xB7")} ${B.dim("generate-image")}`;return D(i,{width:70,title:u})}function Eg(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Pn(e,w),i=Pn(o,".errors"),s=Qr(o)?Pn(i,r):Pn(Sg(),r),a=["# SEOAgent generate-image error",`# ${new Date().toISOString()}`,"","## Request",`provider: ${t.provider}`,`env_var: ${t.envName}`,`prompt: ${JSON.stringify(t.prompt)}`,`size: ${t.size??"(default)"}`,`out_path: ${t.outPath}`,`cwd: ${e}`,"","## Error",`message: ${t.error.message}`,"","## Stack",t.error.stack??"(no stack)",""];t.error.cause&&a.push("## Cause",String(t.error.cause),"");try{return Qr(In(s))||Ta(In(s),{recursive:!0}),La(s,a.join(`
602
+ `)),s}catch{return null}}import K from"picocolors";async function Ft(e={}){let t=N();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
603
+ `):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||T.BASE).replace(/\/$/,""),r=`Bearer ${t.user_token}:${t.website_token}`,o;try{o=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:r,Accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch(s){l.error(`Network error: ${s.message}`),process.exitCode=1;return}if(o.status===404){if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,server_supports_whoami:!1,api_base:n})}
595
604
  `);return}l.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${f("update-cli")}\` (or re-deploy your server).`),l.message(`API base: ${n}`);return}let i=null;try{i=await o.json()}catch{i=null}if(!o.ok||!i||i.status!=="ok"){e.json?process.stdout.write(`${JSON.stringify({logged_in:!0,error:i?.error??`HTTP ${o.status}`})}
596
605
  `):l.error(`Could not fetch your account (HTTP ${o.status})${i?.error?`: ${i.error}`:""}`),process.exitCode=1;return}if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,...i},null,2)}
597
- `);return}l.message(Qm(i)),i.paid===!1&&l.message(`${K.dim("Upgrade for autopilot:")} ${K.cyan(ee("cli-whoami"))}`)}function Qm(e){let n=i=>K.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${K.green("\u2713")} ${K.dim("Logged in as")} ${K.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${K.cyan(e.domain)}`}),e.plan){let i=e.paid?K.bold(K.green(e.plan)):K.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${K.dim(e.api_base)}`});let o=`${K.bold(K.cyan("SEOAgent"))} ${K.dim("\xB7")} ${K.dim("whoami")}`;return D(r,{width:55,title:o})}import{select as Lt,text as Tt,confirm as _a,isCancel as J,intro as Zm,outro as eg}from"@clack/prompts";import _n from"picocolors";function tg(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>ft()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await z()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await ut()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await yt()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await Ot()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Lt({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!J(e))if(e==="peek"){let t=await Tt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(J(t))return;await we({peek:String(t)})}else e==="discover"?await we({discover:!0}):e==="competitors"?await we({competitors:!0}):await we()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>St({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await Lt({message:"Which OKF action?",options:[{value:"status",label:"status",hint:"Is a bundle present?"},{value:"scaffold",label:"scaffold",hint:"Create the starter bundle"},{value:"validate",label:"validate",hint:"Check type fields, timestamps, links"}]});J(e)||xt(e==="status"?void 0:String(e))}},{command:"citations",label:"Measure AI citations (AEO/GEO)",hint:"Are answer engines citing you? Web-grounded \u2192 .seoagent/citations/scorecard.md",run:async()=>await Et()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Tt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(J(e))return;let t=await Tt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});J(t)||await It({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Pt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Lt({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});J(e)||await $t(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await Ae()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Tt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(J(e))return;let t=await _a({message:"Mark as failed instead of completed?",initialValue:!1});if(J(t))return;let n;if(t===!0){let r=await Tt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(J(r))return;String(r).trim()&&(n=String(r))}await he(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await gt()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest + refresh your projects",run:async()=>await ht({})},{command:"refresh",label:"Refresh the skill to your CLI version",hint:"This project \u2014 or every project on the machine via `refresh --all`.",run:async()=>{let e=await Lt({message:"Refresh which?",options:[{value:"this",label:"This project",hint:"Just the current directory"},{value:"all",label:"All projects",hint:"Every SEOAgent project on this machine"}]});J(e)||At({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>wt()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await dt({})}]}var Sa="__exit__";async function xa(e=tg()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:Sa,label:"Exit",hint:"Close the menu"});let n=await Lt({message:"What would you like to do?",options:t});if(J(n)||n===Sa)return!0;let r=e.find(o=>o.command===n);if(!r)return l.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){l.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function Kr(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Zm(`${_n.bold(_n.cyan("SEOAgent"))} ${_n.dim("\xB7 menu")}`);let e=await xa();for(;!e;){let t=await _a({message:"Do another?",initialValue:!0});if(J(t)||t===!1){e=!0;break}e=await xa()}eg(_n.dim("See you next time."))}var R=new ng;R.name("seoagent").description("AI SEO agent for Claude Code").version(A).showSuggestionAfterError(!0).showHelpAfterError(!0);R.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{ut({yes:e.yes,domain:e.domain,siteType:e.siteType})});R.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{dt({yes:e.yes,global:e.global})});R.command("status").description("Show current SEO project state").action(ft);R.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{vr({json:e.json})});R.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{yt({apiBase:e.apiBase})});R.command("logout").description("Remove stored credentials for seoagent.com").action(wt);R.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{z({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});R.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{Ae({force:e.force,silent:e.silent,print:e.print})});R.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{he(e,{failed:t.failed,reason:t.reason})});R.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{ur({json:e.json})});R.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{mr({yes:e.yes,model:e.model})});R.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{$t(e,{apiBase:t.apiBase})});R.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{we({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});R.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{St({json:e.json})});R.command("content [action]").description("Track published articles so the dashboard sees them \u2014 `content track` (one) or `content reconcile` (backfill all)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").option("--dir <dirs>","reconcile: content dir(s) to scan, comma-separated (else inferred from tracked articles)").option("--prune","reconcile: delete stale pointers whose source file is gone").action((e,t)=>{yr(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword,dir:t.dir,prune:t.prune})});R.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{xt(e,{json:t.json})});R.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{xr({url:e.url,json:e.json})});R.command("crawl").description("Capture the live-crawl evidence base (title, meta, all H1s, canonical, JSON-LD @types, OG/Twitter, img-alt gaps, robots.txt, sitemap counts, client-render detection) for the homepage + subpages discovered from the live sitemap + nav links, with a site-wide rollup \u2192 .seoagent/audit/evidence.md. Grounds every audit claim so nothing is invented. The crawled origin is EXPLICIT: --url wins (and is persisted as live_url: in project.md), else live_url:/domain: from project.md, else it errors \u2014 never a guess. An undesignated loopback origin is labeled SOURCE RENDER, not live evidence.").option("--url <origin>","The live site origin to crawl (e.g. https://example.com or http://127.0.0.1:3000) \u2014 persisted as live_url: in project.md for later runs").option("--max <n>","Max pages to crawl (default 15, max 30)",e=>parseInt(e,10)).option("--json","Output the full evidence bundle as JSON").action(e=>{Ar({url:e.url,max:e.max,json:e.json})});R.command("verify-recs [files...]").description('Mechanically verify authored recommendations against the crawl evidence (.seoagent/audit/evidence.md) \u2014 rewrites false "added X / none existed / missing X" claims about head-level entities (title, meta description, canonical, OG, twitter:card, JSON-LD) the live page already serves, across .seoagent/**/*.md plus any files passed. Mandatory final step of an audit/optimization session. Always exits 0.').option("--json","Output the machine-readable correction report as JSON").option("--quiet","Print only actionable output (corrections / source-render warning) \u2014 for hooks").action((e,t)=>{Ir({files:e??[],json:t.json,quiet:t.quiet})});R.command("migrate").description("Plan the migration of legacy Google Search Console authority when the site has repositioned \u2014 classifies each URL/query as harvest | redirect | sunset \u2192 .seoagent/strategy/migration-plan.md").option("--csv <path>","Search Console Pages/Queries CSV export to plan from (no login required)").option("--direction <text>","Override the new-direction summary (else inferred from project.md + context.md)").option("--json","Output the full plan + decisions as JSON").action(e=>{jr({csv:e.csv,direction:e.direction,json:e.json})});R.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{Et({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});R.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Pt({json:e.json})});R.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{It({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});R.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Ot({json:e.json,apiBase:e.apiBase})});R.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(gt);R.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{ht({dryRun:e.dryRun,projects:e.projects})});R.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").option("--crawl","Also fetch each page to fill Status / Rendered / Word count in pages.md (slower)").action(e=>{At({all:e.all,crawl:e.crawl})});R.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Kr()});process.argv.length===2&&(R.outputHelp(),process.exit(0));R.parse();
606
+ `);return}l.message(Rg(i)),i.paid===!1&&l.message(`${K.dim("Upgrade for autopilot:")} ${K.cyan(ee("cli-whoami"))}`)}function Rg(e){let n=i=>K.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${K.green("\u2713")} ${K.dim("Logged in as")} ${K.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${K.cyan(e.domain)}`}),e.plan){let i=e.paid?K.bold(K.green(e.plan)):K.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${K.dim(e.api_base)}`});let o=`${K.bold(K.cyan("SEOAgent"))} ${K.dim("\xB7")} ${K.dim("whoami")}`;return D(r,{width:55,title:o})}import{select as Ut,text as Mt,confirm as Da,isCancel as J,intro as Ag,outro as Pg}from"@clack/prompts";import On from"picocolors";function Ig(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>wt()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await Y()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await gt()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await $t()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await Ft()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Ut({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!J(e))if(e==="peek"){let t=await Mt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(J(t))return;await be({peek:String(t)})}else e==="discover"?await be({discover:!0}):e==="competitors"?await be({competitors:!0}):await be()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Rt({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await Ut({message:"Which OKF action?",options:[{value:"status",label:"status",hint:"Is a bundle present?"},{value:"scaffold",label:"scaffold",hint:"Create the starter bundle"},{value:"validate",label:"validate",hint:"Check type fields, timestamps, links"}]});J(e)||At(e==="status"?void 0:String(e))}},{command:"citations",label:"Measure AI citations (AEO/GEO)",hint:"Are answer engines citing you? Web-grounded \u2192 .seoagent/citations/scorecard.md",run:async()=>await Lt()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Mt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(J(e))return;let t=await Mt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});J(t)||await Dt({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Nt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Ut({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});J(e)||await Et(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await Ie()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Mt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(J(e))return;let t=await Da({message:"Mark as failed instead of completed?",initialValue:!1});if(J(t))return;let n;if(t===!0){let r=await Mt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(J(r))return;String(r).trim()&&(n=String(r))}await ye(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await kt()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest + refresh your projects",run:async()=>await vt({})},{command:"refresh",label:"Refresh the skill to your CLI version",hint:"This project \u2014 or every project on the machine via `refresh --all`.",run:async()=>{let e=await Ut({message:"Refresh which?",options:[{value:"this",label:"This project",hint:"Just the current directory"},{value:"all",label:"All projects",hint:"Every SEOAgent project on this machine"}]});J(e)||jt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>St()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await ht({})}]}var ja="__exit__";async function Na(e=Ig()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:ja,label:"Exit",hint:"Close the menu"});let n=await Ut({message:"What would you like to do?",options:t});if(J(n)||n===ja)return!0;let r=e.find(o=>o.command===n);if(!r)return l.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){l.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function Zr(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Ag(`${On.bold(On.cyan("SEOAgent"))} ${On.dim("\xB7 menu")}`);let e=await Na();for(;!e;){let t=await Da({message:"Do another?",initialValue:!0});if(J(t)||t===!1){e=!0;break}e=await Na()}Pg(On.dim("See you next time."))}var E=new Og;E.name("seoagent").description("AI SEO agent for Claude Code").version(A).showSuggestionAfterError(!0).showHelpAfterError(!0);E.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{gt({yes:e.yes,domain:e.domain,siteType:e.siteType})});E.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{ht({yes:e.yes,global:e.global})});E.command("status").description("Show current SEO project state").action(wt);E.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{Er({json:e.json})});E.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{$t({apiBase:e.apiBase})});E.command("logout").description("Remove stored credentials for seoagent.com").action(St);E.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{Y({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});E.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{Ie({force:e.force,silent:e.silent,print:e.print})});E.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{ye(e,{failed:t.failed,reason:t.reason})});E.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{hr({json:e.json})});E.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{kr({yes:e.yes,model:e.model})});E.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Et(e,{apiBase:t.apiBase})});E.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{be({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});E.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{Rt({json:e.json})});E.command("content [action]").description("Track published articles so the dashboard sees them \u2014 `content track` (one) or `content reconcile` (backfill all)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").option("--dir <dirs>","reconcile: content dir(s) to scan, comma-separated (else inferred from tracked articles)").option("--prune","reconcile: delete stale pointers whose source file is gone").action((e,t)=>{Sr(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword,dir:t.dir,prune:t.prune})});E.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{At(e,{json:t.json})});E.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{Pr({url:e.url,json:e.json})});E.command("crawl").description("Capture the live-crawl evidence base (title, meta, all H1s, canonical, JSON-LD @types, OG/Twitter, img-alt gaps, robots.txt, sitemap counts, client-render detection) for the homepage + subpages discovered from the live sitemap + nav links, with a site-wide rollup \u2192 .seoagent/audit/evidence.md. Grounds every audit claim so nothing is invented. The crawled origin is EXPLICIT: --url wins (and is persisted as live_url: in project.md), else live_url:/domain: from project.md, else it errors \u2014 never a guess. An undesignated loopback origin is labeled SOURCE RENDER, not live evidence.").option("--url <origin>","The live site origin to crawl (e.g. https://example.com or http://127.0.0.1:3000) \u2014 persisted as live_url: in project.md for later runs").option("--max <n>","Max pages to crawl (default 15, max 30)",e=>parseInt(e,10)).option("--json","Output the full evidence bundle as JSON").action(e=>{jr({url:e.url,max:e.max,json:e.json})});E.command("verify-recs [files...]").description('Mechanically verify authored recommendations against the crawl evidence (.seoagent/audit/evidence.md) \u2014 rewrites false "added X / none existed / missing X" claims about head-level entities (title, meta description, canonical, OG, twitter:card, JSON-LD) the live page already serves, across .seoagent/**/*.md plus any files passed. Mandatory final step of an audit/optimization session. Always exits 0.').option("--json","Output the machine-readable correction report as JSON").option("--quiet","Print only actionable output (corrections / source-render warning) \u2014 for hooks").action((e,t)=>{Dr({files:e??[],json:t.json,quiet:t.quiet})});E.command("summary [files...]").description("Compose the ready-to-deliver session summary FROM the corrected on-disk .seoagent state \u2014 top audit findings quoted verbatim (confidence labels + Evidence citations), every verify-recs CORRECTION (so corrected framing is what gets relayed), the migration-plan harvest/redirect/sunset table, and top roadmap items. Runs the verify-recs pass first. The final message of an audit/optimization session must be built from this output, not from memory. Flags live-state claims as UNVERIFIED when the crawl evidence is missing or a source render. Plain markdown to stdout; always exits 0.").option("--json","Output the structured summary as JSON").action((e,t)=>{Fr({files:e??[],json:t.json})});E.command("migrate").description("Plan the migration of legacy Google Search Console authority when the site has repositioned \u2014 classifies each URL/query as harvest | redirect | sunset \u2192 .seoagent/strategy/migration-plan.md").option("--csv <path>","Search Console Pages/Queries CSV export to plan from (no login required)").option("--direction <text>","Override the new-direction summary (else inferred from project.md + context.md)").option("--json","Output the full plan + decisions as JSON").action(e=>{Gr({csv:e.csv,direction:e.direction,json:e.json})});E.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{Lt({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});E.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Nt({json:e.json})});E.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{Dt({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});E.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Ft({json:e.json,apiBase:e.apiBase})});E.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(kt);E.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{vt({dryRun:e.dryRun,projects:e.projects})});E.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").option("--crawl","Also fetch each page to fill Status / Rendered / Word count in pages.md (slower)").action(e=>{jt({all:e.all,crawl:e.crawl})});E.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Zr()});process.argv.length===2&&(E.outputHelp(),process.exit(0));E.parse();