@seoagent-official/seoagent 1.70.0 → 1.71.1

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.
Files changed (3) hide show
  1. package/README.md +2 -2
  2. package/index.js +95 -95
  3. package/package.json +3 -3
package/index.js CHANGED
@@ -1,47 +1,47 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Ff}from"commander";import{dirname as Lo,relative as Wt}from"path";import{intro as vc,outro as xc,text as Io,select as In,spinner as _c,isCancel as De,cancel as Fe,confirm as Cc}from"@clack/prompts";var Ae=[".env.local",".env.production",".env"],Er=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var re="@seoagent-official/seoagent",_t=`${re}@latest`;import{homedir as Ms}from"os";import{join as Pe}from"path";var k=".seoagent",Rr=["audit","strategy/clusters","briefs","content","content/images","performance"],he={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Ct=".claude/settings.json",Et=".pull-receipt.json",Ar=".ack-queue.json",Pr=".sync.lock",Ir=`# SEOAgent local files
2
+ import{Command as Kf}from"commander";import{dirname as Ho,relative as Qt}from"path";import{intro as jc,outro as Nc,text as Bo,select as Un,spinner as Dc,isCancel as Be,cancel as Ge,confirm as Fc}from"@clack/prompts";var Ie=[".env.local",".env.production",".env"],Tr=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var se="@seoagent-official/seoagent",It=`${se}@latest`;import{homedir as qs}from"os";import{join as Te}from"path";var k=".seoagent",Or=["audit","strategy/clusters","briefs","content","content/images","performance"],ke={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Tt=".claude/settings.json",Ot=".pull-receipt.json",Lr=".ack-queue.json",jr=".sync.lock",Nr=`# 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
- `,Bs=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Pe(Ms(),".config"),G=Pe(Bs,"seoagent"),ae=Pe(G,"auth.json"),fn=Pe(G,"state"),Rt=Pe(G,"update-check.json"),At=Pe(G,"projects.json");var ze="https://seoagent.com",Ie=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):ze,R={BASE:Ie,PRICING:`${Ie}/pricing`,LEAD_API:`${Ie}/api/cli/lead`,CLI_AUTH_PAGE:`${Ie}/cli/auth`,CLI_AUTH_POLL:`${Ie}/api/cli/auth/poll`,CLI_SYNC:`${Ie}/api/cli/sync`};import{readFileSync as Gs}from"fs";import{fileURLToPath as Ws}from"url";import{dirname as Hs,join as Ks}from"path";var Tr="0.0.0";function qs(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Tr}function Ys(e=t=>Gs(t,"utf-8")){try{let t=Hs(Ws(import.meta.url));return qs(e(Ks(t,"package.json")))}catch{return Tr}}var A=Ys();function mn(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=mn()){return t?`seoagent ${e}`:`npx -y ${_t} ${e}`}import{randomUUID as Zs}from"crypto";import{existsSync as jr,mkdirSync as Nr,readFileSync as ea,writeFileSync as Dr}from"fs";import{join as hn}from"path";import{existsSync as zs,readFileSync as Vs}from"fs";var Pt="---";function Js(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 Qs(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 Or(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]=Or(e,o+1,s.indent);r[i.key]=a,o=c}else r[i.key]="",o++}else r[i.key]=Js(i.valueRaw),o++}return[r,o]}function ce(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Pt)return{data:{},body:e};let n=-1;for(let c=1;c<t.length;c++)if(t[c].trim()===Pt){n=c;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
10
- `),i=Qs(r),s=i.length>0?i[0].indent:0,[a]=Or(i,0,s);return{data:a,body:o}}function It(e){if(!zs(e))return null;try{return ce(Vs(e,"utf-8"))}catch{return null}}function Xs(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 Lr(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}:`),Lr(i,t+1,n)):n.push(`${r}${o}: ${Xs(i)}`))}function gn(e,t=""){let n=[Pt];Lr(e,0,n),n.push(Pt);let r=t.length===0?"":t.startsWith(`
9
+ `,Ys=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Te(qs(),".config"),W=Te(Ys,"seoagent"),ue=Te(W,"auth.json"),$n=Te(W,"state"),Lt=Te(W,"update-check.json"),jt=Te(W,"projects.json");var et="https://seoagent.com",Oe=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):et,T={BASE:Oe,PRICING:`${Oe}/pricing`,LEAD_API:`${Oe}/api/cli/lead`,CLI_AUTH_PAGE:`${Oe}/cli/auth`,CLI_AUTH_POLL:`${Oe}/api/cli/auth/poll`,CLI_SYNC:`${Oe}/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 zs}from"fs";import{fileURLToPath as Vs}from"url";import{dirname as Js,join as Qs}from"path";var Dr="0.0.0";function Xs(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Dr}function Zs(e=t=>zs(t,"utf-8")){try{let t=Js(Vs(import.meta.url));return Xs(e(Qs(t,"package.json")))}catch{return Dr}}var E=Zs();function Sn(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=Sn()){return t?`seoagent ${e}`:`npx -y ${It} ${e}`}import{randomUUID as ia}from"crypto";import{existsSync as Mr,mkdirSync as Br,readFileSync as sa,writeFileSync as Gr}from"fs";import{join as xn}from"path";import{existsSync as ea,readFileSync as ta}from"fs";var Nt="---";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 ra(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 Fr(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]=Fr(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 de(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Nt)return{data:{},body:e};let n=-1;for(let c=1;c<t.length;c++)if(t[c].trim()===Nt){n=c;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
10
+ `),i=ra(r),s=i.length>0?i[0].indent:0,[a]=Fr(i,0,s);return{data:a,body:o}}function Dt(e){if(!ea(e))return null;try{return de(ta(e,"utf-8"))}catch{return null}}function oa(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 Ur(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}:`),Ur(i,t+1,n)):n.push(`${r}${o}: ${oa(i)}`))}function vn(e,t=""){let n=[Nt];Ur(e,0,n),n.push(Nt);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 ta=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yn(){return Zs()}var na=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),ra="project.md";function Ve(e){return hn(e,k)}function Tt(e){return hn(Ve(e),ra)}function Fr(e){return jr(Tt(e))}function C(e){let t=It(Tt(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&&na.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&&ta.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}}function Ot(e){let t=C(e);if(!t)return null;if(t.install_id)return t.install_id;let n=yn();return V(e,{install_id:n}),n}function oa(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 ia(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),t}function Ur(e,t){let n=Ve(e);Nr(n,{recursive:!0});let r=gn(ia(t),oa(t));Dr(Tt(e),r,"utf-8")}function V(e,t){let n=Tt(e);if(!jr(n))return!1;let r=ce(ea(n,"utf-8")),o={...r.data,...t};return Dr(n,gn(o,r.body),"utf-8"),!0}function Mr(e){let t=Ve(e);for(let n of Rr)Nr(hn(t,n),{recursive:!0})}var wn="Sent an anonymous install ping (random id + CLI version only \u2014 no domain, no paths). Opt out: SEOAGENT_TELEMETRY=0",sa=2500;function kn(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||R.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??sa)})).ok}catch{return!1}}var aa=new Set([502,503,504]),ca=1e4;async function O(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??ca,s=n.fetchImpl??fetch,a=n.sleep??la,c=n.transientStatuses??aa,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:m}=ua(t,i);try{let g=await s(e,p);if(c.has(g.status)&&d<r-1){await a(Br(o,d));continue}return g}catch(g){if(u=g,d<r-1){await a(Br(o,d));continue}}finally{m()}}throw u instanceof Error?u:new Error(String(u))}function Br(e,t){return e*Math.pow(3,t)}function la(e){return new Promise(t=>setTimeout(t,e))}function ua(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 da=new Set(["co","com","net","org","ac","gov","edu"]);function pa(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&&da.has(n[n.length-2])?n.length-3:n.length-2;return n[Math.max(0,r)]||null}async function Gr(e){let t=pa(e.domain);if(!t)return{status:"unavailable"};let n=(e.apiBase||R.BASE).replace(/\/$/,"");try{let r=await O(`${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 Lt,lstatSync as fa,mkdirSync as Je,readFileSync as Wr,readdirSync as ma,rmSync as ga,statSync as ha,symlinkSync as ya,writeFileSync as Hr}from"fs";import{dirname as jt,join as X,relative as Kr}from"path";import{fileURLToPath as wa}from"url";var ka=jt(wa(import.meta.url));function qr(){return X(ka,"skills")}function ba(){let e=X(qr(),"seoagent.md");if(Lt(e))return Wr(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Yr(e,t){let n=[];if(!Lt(e))return n;for(let r of ma(e,{withFileTypes:!0})){let o=X(e,r.name),i=X(t,r.name);r.isDirectory()?(Je(i,{recursive:!0}),n.push(...Yr(o,i))):r.isFile()&&(Je(jt(i),{recursive:!0}),Hr(i,Wr(o)),n.push(i))}return n}function Te(e,t){let n=Lt(X(e,".agents")),r=X(e,n?he.AGENTS:he.CLAUDE),o=X(r,"SKILL.md");Je(r,{recursive:!0}),Hr(o,t??ba(),"utf-8");let i=X(qr(),"references"),s=X(r,"references"),a=[];try{Lt(i)&&ha(i).isDirectory()&&(Je(s,{recursive:!0}),a=Yr(i,s).map(u=>Kr(r,u)))}catch{}let c=n?$a(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function $a(e,t){let n=X(e,he.CLAUDE),r=null;try{r=fa(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{ga(n,{force:!0})}catch{return}}try{Je(jt(n),{recursive:!0});let o=Kr(jt(n),t);return ya(o,n,"dir"),n}catch{return}}import{existsSync as Dt,mkdirSync as $n,readFileSync as Sa,writeFileSync as Nt}from"fs";import{dirname as Vr,join as Oe}from"path";var va=`npx -y ${_t} sync --silent`;function Jr(e){let t=Oe(e,k);$n(t,{recursive:!0});let n=Oe(t,".gitignore");Nt(n,Ir,"utf-8");let r=Oe(t,"content","images",".gitkeep");return $n(Vr(r),{recursive:!0}),Dt(r)||Nt(r,"","utf-8"),n}var Qr=["PostToolUse","SessionStart"];function Sn(e){if(!Dt(e))return{};try{let t=Sa(e,"utf-8");return JSON.parse(t)}catch{return{}}}function vn(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function zr(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(vn)?!1:(r.hooks.push({type:"command",command:va}),!0)}function ye(e){let t=Oe(e,Ct);$n(Vr(t),{recursive:!0});let n=Sn(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=zr(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=zr(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return Nt(t,JSON.stringify(n,null,2)+`
17
- `,"utf-8"),{file:t,added:o||s}}function Xr(e){let t=Oe(e,Ct);if(!Dt(t))return!1;let n=Sn(t).hooks;return n?Qr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(vn))}):!1}function Zr(e){let t=Oe(e,Ct);if(!Dt(t))return{file:t,removed:!1};let n=Sn(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of Qr){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=>!vn(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,Nt(t,JSON.stringify(n,null,2)+`
18
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as eo,mkdirSync as xa,readFileSync as _a,writeFileSync as Ca}from"fs";import{join as Ea}from"path";function to(e){return eo(Ea(e,k,"project.md"))}function no(){try{if(!eo(At))return[];let e=JSON.parse(_a(At,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function ro(e){try{xa(G,{recursive:!0}),Ca(At,JSON.stringify({projects:e},null,2)+`
19
- `,"utf-8")}catch{}}function we(e){try{if(!to(e))return;let t=no();if(t.includes(e))return;t.push(e),ro(t)}catch{}}function oo(){let e=no(),t=e.filter(to);return t.length!==e.length&&ro(t),t}import{readFileSync as Ia,writeFileSync as Ta,existsSync as Oa}from"fs";import{join as co}from"path";function so(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Ra(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=Aa(o):i==="writing instructions"?t.writingInstructions=io(o):i==="reference urls"?t.referenceUrls=Pa(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 ao(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(`
20
- `)}function Ra(e){let t=e.split(`
15
+ `)}var aa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _n(){return ia()}var ca=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),la="project.md";function tt(e){return xn(e,k)}function Ft(e){return xn(tt(e),la)}function Wr(e){return Mr(Ft(e))}function x(e){let t=Dt(Ft(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&&ca.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&&aa.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}}function Ut(e){let t=x(e);if(!t)return null;if(t.install_id)return t.install_id;let n=_n();return J(e,{install_id:n}),n}function ua(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 da(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),t}function Hr(e,t){let n=tt(e);Br(n,{recursive:!0});let r=vn(da(t),ua(t));Gr(Ft(e),r,"utf-8")}function J(e,t){let n=Ft(e);if(!Mr(n))return!1;let r=de(sa(n,"utf-8")),o={...r.data,...t};return Gr(n,vn(o,r.body),"utf-8"),!0}function Kr(e){let t=tt(e);for(let n of Or)Br(xn(t,n),{recursive:!0})}var Cn="Sent an anonymous install ping (random id + CLI version only \u2014 no domain, no paths). Opt out: SEOAGENT_TELEMETRY=0",pa=2500;function En(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 Rn(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??pa)})).ok}catch{return!1}}import{existsSync as Yr,mkdirSync as qr,readFileSync as fa,writeFileSync as ma,chmodSync as ga,unlinkSync as ha}from"fs";import{dirname as ya}from"path";function j(){if(!Yr(ue))return null;try{let e=JSON.parse(fa(ue,"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||et}}catch{return null}}function zr(e){qr(W,{recursive:!0}),qr(ya(ue),{recursive:!0}),ma(ue,JSON.stringify(e,null,2)+`
17
+ `,"utf-8");try{ga(ue,384)}catch{}}function Vr(){if(!Yr(ue))return!1;try{return ha(ue),!0}catch{return!1}}var wa=new Set([502,503,504]),ka=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??ka,s=n.fetchImpl??fetch,a=n.sleep??ba,c=n.transientStatuses??wa,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:m}=$a(t,i);try{let g=await s(e,p);if(c.has(g.status)&&d<r-1){await a(Jr(o,d));continue}return g}catch(g){if(u=g,d<r-1){await a(Jr(o,d));continue}}finally{m()}}throw u instanceof Error?u:new Error(String(u))}function Jr(e,t){return e*Math.pow(3,t)}function ba(e){return new Promise(t=>setTimeout(t,e))}function $a(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 Mt(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):""}function Sa(e,t){let n=Mt(e),r=Mt(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?Sa(r,e.localDomain)?{verdict:"match",cloudDomain:r}:{verdict:"mismatch",cloudDomain:r}:{verdict:"unverified",detail:"whoami did not return a bound domain"}}function Qr(e,t){return`Cloud project is ${Mt(e)||e} but this workspace is ${Mt(t)||t} \u2014 not syncing. Run \`seoagent logout && seoagent login\` from this directory to connect the right site.`}var va=new Set(["co","com","net","org","ac","gov","edu"]);function xa(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&&va.has(n[n.length-2])?n.length-3:n.length-2;return n[Math.max(0,r)]||null}async function Xr(e){let t=xa(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 Bt,lstatSync as _a,mkdirSync as nt,readFileSync as Zr,readdirSync as Ca,rmSync as Ea,statSync as Ra,symlinkSync as Aa,writeFileSync as eo}from"fs";import{dirname as Gt,join as te,relative as to}from"path";import{fileURLToPath as Pa}from"url";var Ia=Gt(Pa(import.meta.url));function no(){return te(Ia,"skills")}function Ta(){let e=te(no(),"seoagent.md");if(Bt(e))return Zr(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function ro(e,t){let n=[];if(!Bt(e))return n;for(let r of Ca(e,{withFileTypes:!0})){let o=te(e,r.name),i=te(t,r.name);r.isDirectory()?(nt(i,{recursive:!0}),n.push(...ro(o,i))):r.isFile()&&(nt(Gt(i),{recursive:!0}),eo(i,Zr(o)),n.push(i))}return n}function Ne(e,t){let n=Bt(te(e,".agents")),r=te(e,n?ke.AGENTS:ke.CLAUDE),o=te(r,"SKILL.md");nt(r,{recursive:!0}),eo(o,t??Ta(),"utf-8");let i=te(no(),"references"),s=te(r,"references"),a=[];try{Bt(i)&&Ra(i).isDirectory()&&(nt(s,{recursive:!0}),a=ro(i,s).map(u=>to(r,u)))}catch{}let c=n?Oa(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function Oa(e,t){let n=te(e,ke.CLAUDE),r=null;try{r=_a(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{Ea(n,{force:!0})}catch{return}}try{nt(Gt(n),{recursive:!0});let o=to(Gt(n),t);return Aa(o,n,"dir"),n}catch{return}}import{existsSync as Ht,mkdirSync as An,readFileSync as La,writeFileSync as Wt}from"fs";import{dirname as io,join as De}from"path";var ja=`npx -y ${It} sync --silent`;function so(e){let t=De(e,k);An(t,{recursive:!0});let n=De(t,".gitignore");Wt(n,Nr,"utf-8");let r=De(t,"content","images",".gitkeep");return An(io(r),{recursive:!0}),Ht(r)||Wt(r,"","utf-8"),n}var ao=["PostToolUse","SessionStart"];function Pn(e){if(!Ht(e))return{};try{let t=La(e,"utf-8");return JSON.parse(t)}catch{return{}}}function In(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function oo(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(In)?!1:(r.hooks.push({type:"command",command:ja}),!0)}function be(e){let t=De(e,Tt);An(io(t),{recursive:!0});let n=Pn(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=oo(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=oo(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return Wt(t,JSON.stringify(n,null,2)+`
18
+ `,"utf-8"),{file:t,added:o||s}}function co(e){let t=De(e,Tt);if(!Ht(t))return!1;let n=Pn(t).hooks;return n?ao.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(In))}):!1}function lo(e){let t=De(e,Tt);if(!Ht(t))return{file:t,removed:!1};let n=Pn(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of ao){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=>!In(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,Wt(t,JSON.stringify(n,null,2)+`
19
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as uo,mkdirSync as Na,readFileSync as Da,writeFileSync as Fa}from"fs";import{join as Ua}from"path";function po(e){return uo(Ua(e,k,"project.md"))}function fo(){try{if(!uo(jt))return[];let e=JSON.parse(Da(jt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function mo(e){try{Na(W,{recursive:!0}),Fa(jt,JSON.stringify({projects:e},null,2)+`
20
+ `,"utf-8")}catch{}}function $e(e){try{if(!po(e))return;let t=fo();if(t.includes(e))return;t.push(e),mo(t)}catch{}}function go(){let e=fo(),t=e.filter(po);return t.length!==e.length&&mo(t),t}import{readFileSync as Wa,writeFileSync as Ha,existsSync as Ka}from"fs";import{join as ko}from"path";function yo(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Ma(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=Ba(o):i==="writing instructions"?t.writingInstructions=ho(o):i==="reference urls"?t.referenceUrls=Ga(o):i==="topics to avoid"?t.topicsToAvoid=ho(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function wo(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 Ma(e){let t=e.split(`
21
22
  `),n=[],r="",o=[];for(let i of t){let s=i.match(/^#\s+(.+)$/);s?(r&&n.push([r,o.join(`
22
23
  `)]),r=s[1],o=[]):o.push(i)}return r&&n.push([r,o.join(`
23
- `)]),n}function Aa(e){let t={},n=e.split(`
24
- `);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(`
25
- `);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 Pa(e){let t=[],n=e.split(`
26
- `);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 lo="context.md";function Ft(e){let t=co(e,".seoagent",lo);if(!Oa(t))return null;let n=Ia(t,"utf-8");return so(n)}function La(e,t){let n=co(e,".seoagent",lo),r=ao(t);Ta(n,r,"utf-8")}function uo(e,t){La(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Qe,readFileSync as po,readdirSync as ja,statSync as fo}from"fs";import{join as ke}from"path";var Na=[{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 Da(e){let t=ke(e,"package.json");if(!Qe(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(po(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Fa(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 Ua(e){let t={};for(let n of Ae){let r=ke(e,n);if(Qe(r))try{let o=po(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 Ma(e,t){let n=ke(e,t.replace(/\/$/,""));if(!Qe(n))return!1;if(t.endsWith("/"))try{return fo(n).isDirectory()}catch{return!1}return!0}function Ba(e){let t=["content","_posts","posts",ke("src","content")];for(let n of t){let r=ke(e,n);if(Qe(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 ja(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(ke(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 Ga(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(Qe(ke(e,n.marker)))return n.path;return null}function mo(e){let t=[],{deps:n}=Da(e),r=Ua(e),o="none";for(let s of Na){let a=[];for(let c of Object.keys(n))if(Fa(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(Ma(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=Ba(e);s&&(o="mdx-local",t.push(s))}let i=Ga(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as Wa,readFileSync as Ha}from"fs";import{join as Ka}from"path";var go=["openai","fal","replicate"],Le={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function qa(e){let t={};if(!Wa(e))return t;let n=Ha(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 ho(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 Ae){let o=Ka(e,r),i=qa(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 le(e){let t=[].concat(...go.map(a=>Le[a])),n=ho(e,t),r=[];for(let a of go)Le[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=Le[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 yo(e,t){let n=ho(e,Le[t]);for(let r of Le[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function wo(){return Le}import{existsSync as be,readFileSync as xn}from"fs";import{join as $e}from"path";function ko(e){try{return new URL(e).hostname}catch{return e}}function bo(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 Ya(e){for(let t of Ae){let n=$e(e,t);if(!be(n))continue;let r=xn(n,"utf-8");for(let o of Er){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=ko(s);if(bo(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function za(e){let t=$e(e,"package.json");if(!be(t))return null;try{let n=JSON.parse(xn(t,"utf-8"));if(!n.homepage)return null;let r=ko(n.homepage);return bo(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function $o(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),be($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=Ya(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=za(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=$e(e,"package.json"),s=null;if(be(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(xn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||be($e(e,"shopify.config.js"))||be($e(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":be($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 Xa,readFileSync as Rn,readdirSync as vo,statSync as Za}from"fs";import{join as q,sep as ec}from"path";var Va=[/^\/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 Xe(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 Se(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 Ut(e){return Va.some(t=>t.test(e))}function Ja(e){return e.filter(t=>Ut(Se(t)))}function Qa(e,t){let n=new Set(e.map(Se)),r=[],o=new Set;for(let i of t){let s=Se(i);Ut(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function _n(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function So(e){let t=e.sitemapUrl||_n(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await O(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=Xe(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=Ja(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(Se).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=Qa(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 xo=["tsx","jsx","js","mdx","md"],tc=["astro","md","mdx"],nc=5e3;function Z(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=ac(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:gc(t,c),in_sitemap:a,source:s})};for(let i of oc(e))rc(i,o);return{pages:[...n.values()].filter(i=>!Ut(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function _o(e,t,n){let r=[];try{let s=await O(_n(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=Xe(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(Se)),i=0;for(let s of e)!s.in_sitemap&&o.has(Se(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 rc(e,t){for(let n of["app",q("src","app")]){let r=q(e,n);if(Ze(r))for(let o of Cn(r)){let i=En(r,o),s=i[i.length-1];pc(s)&&(i.some(a=>a.startsWith("@"))||t(cc(i.slice(0,-1)),"app router"))}}for(let n of["pages",q("src","pages")]){let r=q(e,n);if(Ze(r))for(let o of Cn(r)){let i=En(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=An(s),c=xo.includes(a),u=tc.includes(a);if(!c&&!u)continue;let d=Mt(s);fc(d)||t(lc(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=q(e,n);if(Ze(r))for(let o of Cn(r,n==="."?1:1/0)){let i=En(r,o),s=i[i.length-1];An(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(uc(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=q(e,...n.split("/"));if(Xa(r)){for(let o of mc(r)){let i=dc(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function oc(e){let t=[e],n=new Set([e]);for(let r of ic(e))for(let o of sc(e,r))n.has(o)||(n.add(o),t.push(o));return t}function ic(e){let t=[];try{let n=Rn(q(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(Rn(q(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 sc(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=q(e,...n.split("/").filter(Boolean));return Ze(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=q(e,...o.split("/").filter(Boolean));if(!Ze(i))return[];let s=[];try{for(let a of vo(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Co.has(a.name)&&(s.push(q(i,a.name)),s.length>=200))break}catch{}return s}function ac(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function cc(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function lc(e){let t=[...e],n=Mt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function uc(e){let t=[...e],n=Mt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function dc(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function pc(e){return Mt(e)==="page"&&xo.includes(An(e))}function fc(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function mc(e){try{let t=Rn(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 Co=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ze(e){try{return Za(e).isDirectory()}catch{return!1}}function*Cn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=vo(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=nc)return;if(a.name.startsWith("."))continue;let c=q(o,a.name);if(a.isDirectory()){if(Co.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function En(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ec).filter(Boolean)}function An(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Mt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function gc(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as hc,mkdirSync as yc,readFileSync as wc,writeFileSync as kc}from"fs";import{join as Eo}from"path";function Ro(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 Bt(e,t,n){let r=Eo(e,k,"pages.md"),o=hc(r),i=o?$c(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=Po(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&&Ro(g,m)&&(c=!0);else{let $={url:p,in_sitemap:d.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:Po(d.source)};m&&Ro($,m),s.set(p,$),a++,c=!0}}if(o&&!c)return{wrote:!1,added:0,total:s.size,merged:!0};let u=[...s.values()];return yc(Eo(e,k),{recursive:!0}),kc(r,bc(u),"utf-8"),{wrote:!0,added:a,total:u.length,merged:o}}function bc(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
24
+ `)]),n}function Ba(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 ho(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 Ga(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 bo="context.md";function Kt(e){let t=ko(e,".seoagent",bo);if(!Ka(t))return null;let n=Wa(t,"utf-8");return yo(n)}function qa(e,t){let n=ko(e,".seoagent",bo),r=wo(t);Ha(n,r,"utf-8")}function $o(e,t){qa(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as rt,readFileSync as So,readdirSync as Ya,statSync as vo}from"fs";import{join as Se}from"path";var za=[{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 Va(e){let t=Se(e,"package.json");if(!rt(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(So(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Ja(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 Qa(e){let t={};for(let n of Ie){let r=Se(e,n);if(rt(r))try{let o=So(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 Xa(e,t){let n=Se(e,t.replace(/\/$/,""));if(!rt(n))return!1;if(t.endsWith("/"))try{return vo(n).isDirectory()}catch{return!1}return!0}function Za(e){let t=["content","_posts","posts",Se("src","content")];for(let n of t){let r=Se(e,n);if(rt(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 Ya(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 ec(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(rt(Se(e,n.marker)))return n.path;return null}function xo(e){let t=[],{deps:n}=Va(e),r=Qa(e),o="none";for(let s of za){let a=[];for(let c of Object.keys(n))if(Ja(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(Xa(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=Za(e);s&&(o="mdx-local",t.push(s))}let i=ec(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as tc,readFileSync as nc}from"fs";import{join as rc}from"path";var _o=["openai","fal","replicate"],Fe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function oc(e){let t={};if(!tc(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 Co(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=rc(e,r),i=oc(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 pe(e){let t=[].concat(..._o.map(a=>Fe[a])),n=Co(e,t),r=[];for(let a of _o)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 Eo(e,t){let n=Co(e,Fe[t]);for(let r of Fe[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Ro(){return Fe}import{existsSync as ve,readFileSync as Tn}from"fs";import{join as xe}from"path";function Ao(e){try{return new URL(e).hostname}catch{return e}}function Po(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 ic(e){for(let t of Ie){let n=xe(e,t);if(!ve(n))continue;let r=Tn(n,"utf-8");for(let o of Tr){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Ao(s);if(Po(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function sc(e){let t=xe(e,"package.json");if(!ve(t))return null;try{let n=JSON.parse(Tn(t,"utf-8"));if(!n.homepage)return null;let r=Ao(n.homepage);return Po(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Io(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ve(xe(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=ic(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=sc(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=xe(e,"package.json"),s=null;if(ve(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Tn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||ve(xe(e,"shopify.config.js"))||ve(xe(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ve(xe(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 uc,readFileSync as Nn,readdirSync as Oo,statSync as dc}from"fs";import{join as Y,sep as pc}from"path";var ac=[/^\/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 ot(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 _e(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 qt(e){return ac.some(t=>t.test(e))}function cc(e){return e.filter(t=>qt(_e(t)))}function lc(e,t){let n=new Set(e.map(_e)),r=[],o=new Set;for(let i of t){let s=_e(i);qt(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function On(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function To(e){let t=e.sitemapUrl||On(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=ot(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=cc(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(_e).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=lc(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 Lo=["tsx","jsx","js","mdx","md"],fc=["astro","md","mdx"],mc=5e3;function ne(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=kc(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:Ec(t,c),in_sitemap:a,source:s})};for(let i of hc(e))gc(i,o);return{pages:[...n.values()].filter(i=>!qt(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(On(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=ot(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(_e)),i=0;for(let s of e)!s.in_sitemap&&o.has(_e(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 gc(e,t){for(let n of["app",Y("src","app")]){let r=Y(e,n);if(it(r))for(let o of Ln(r)){let i=jn(r,o),s=i[i.length-1];xc(s)&&(i.some(a=>a.startsWith("@"))||t(bc(i.slice(0,-1)),"app router"))}}for(let n of["pages",Y("src","pages")]){let r=Y(e,n);if(it(r))for(let o of Ln(r)){let i=jn(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=Dn(s),c=Lo.includes(a),u=fc.includes(a);if(!c&&!u)continue;let d=Yt(s);_c(d)||t($c(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=Y(e,n);if(it(r))for(let o of Ln(r,n==="."?1:1/0)){let i=jn(r,o),s=i[i.length-1];Dn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Sc(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=Y(e,...n.split("/"));if(uc(r)){for(let o of Cc(r)){let i=vc(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function hc(e){let t=[e],n=new Set([e]);for(let r of yc(e))for(let o of wc(e,r))n.has(o)||(n.add(o),t.push(o));return t}function yc(e){let t=[];try{let n=Nn(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(Nn(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 wc(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 it(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=Y(e,...o.split("/").filter(Boolean));if(!it(i))return[];let s=[];try{for(let a of Oo(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!No.has(a.name)&&(s.push(Y(i,a.name)),s.length>=200))break}catch{}return s}function kc(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function bc(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function $c(e){let t=[...e],n=Yt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Sc(e){let t=[...e],n=Yt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function vc(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function xc(e){return Yt(e)==="page"&&Lo.includes(Dn(e))}function _c(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Cc(e){try{let t=Nn(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 No=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function it(e){try{return dc(e).isDirectory()}catch{return!1}}function*Ln(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=Oo(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=mc)return;if(a.name.startsWith("."))continue;let c=Y(o,a.name);if(a.isDirectory()){if(No.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function jn(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(pc).filter(Boolean)}function Dn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Yt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Ec(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as Rc,mkdirSync as Ac,readFileSync as Pc,writeFileSync as Ic}from"fs";import{join as Do}from"path";function Fo(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 zt(e,t,n){let r=Do(e,k,"pages.md"),o=Rc(r),i=o?Oc(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=Mo(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&&Fo(g,m)&&(c=!0);else{let $={url:p,in_sitemap:d.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:Mo(d.source)};m&&Fo($,m),s.set(p,$),a++,c=!0}}if(o&&!c)return{wrote:!1,added:0,total:s.size,merged:!0};let u=[...s.values()];return Ac(Do(e,k),{recursive:!0}),Ic(r,Tc(u),"utf-8"),{wrote:!0,added:a,total:u.length,merged:o}}function Tc(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
27
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(`
28
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(`
29
- `)}function $c(e){let t=new Map,n;try{n=wc(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!Pn(r[o])||!Sc(r[o+1]))continue;let i=Ao(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&&Pn(r[a]);a++){let c=Ao(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:je(c,s.in_sitemap),in_nav:je(c,s.in_nav),status:je(c,s.status),rendered:je(c,s.rendered),word_count:je(c,s.word_count),notes:je(c,s.notes)})}break}return t}function je(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function Pn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function Sc(e){let t=e.trim();return Pn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Ao(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Po(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Ne}from"@clack/prompts";var l={info:e=>Ne.info(e),warn:e=>Ne.warn(e),error:e=>Ne.error(e),success:e=>Ne.success(e),step:e=>Ne.step(e),message:e=>Ne.message(e)};function b(e,t,n,r=n){e?e.stop(r):l[t](n)}var To=[{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"}],Tn="unknown",Ec=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Rc(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 Gt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Ec.has(t)?t:null}async function et(e={}){let t=process.cwd();if(Fr(t)){let a=C(t),c=Te(t);ye(t),V(t,{skill_version:A}),we(t);let u=Lo(Wt(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${Wt(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.`),!kn()){let m=Ot(t);m&&await bn({installId:m,event:"reinit",cliVersion:A})&&l.info(wn)}return}let n=!!e.yes||!process.stdin.isTTY;n||vc("SEOAgent \u2014 AI SEO Agent");let r=$o(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 ${Rc(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=Gt(e.siteType)||Gt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&Gt(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()&&Gt(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=Tn),s||(s="unknown"),await Oo(t,i,s);return}if(o(),!i){let a=await Io({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});De(a)&&(Fe("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await In({message:"What kind of site is this?",options:[...To]});De(a)&&(Fe("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Cc({message:`Create .seoagent for ${i} (${s})?`});if(De(a)&&(Fe("Cancelled"),process.exit(0)),a)break;let c=await In({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((De(c)||c==="abort")&&(Fe("Cancelled"),process.exit(0)),c==="domain"){let u=await Io({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});De(u)&&(Fe("Cancelled"),process.exit(0)),i=String(u)}else{let u=await In({message:"What kind of site is this?",options:[...To]});De(u)&&(Fe("Cancelled"),process.exit(0)),s=u}}await Oo(t,i,s)}async function Oo(e,t,n){let r=_c();r.start("Setting up your SEO project");let o=mo(e),i=le(e),s=yn(),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=kn(),u=c?Promise.resolve(!1):bn({installId:s,event:"init",cliVersion:A}),d=c||t===Tn?Promise.resolve(null):Gr({domain:t,installId:s});Mr(e),Ur(e,a),we(e),uo(e,n),Jr(e);let p=Te(e),m=Wt(e,p.skillFile),g=Lo(m),$=`${g}/references/audit-checks.md`,w=p.claudeSymlink?Wt(e,p.claudeSymlink):void 0;ye(e);let _=t!==Tn,S={pages:[],dynamicCount:0},I={wrote:!1,added:0,total:0,merged:!1};try{S=Z(e,_?t:null),I=Bt(e,S.pages)}catch{}if(r.stop(_?`Created .seoagent/ project for ${a.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let T=o.evidence.map(se=>`${se.detail} (${se.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${T}`)}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.`),S.pages.length>0){let T=I.merged?I.added>0?`Re-scanned your codebase: +${I.added} new page${I.added===1?"":"s"} merged into .seoagent/pages.md (${I.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${I.total} pages)`:`Found ${S.pages.length} page${S.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(T+(S.dynamicCount>0?` (plus ${S.dynamicCount} dynamic route template${S.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let[z,D]=await Promise.all([u,d]);if(D?.status==="data"){let T=D.difficulty!=null?`, difficulty ${D.difficulty}/100`:"";l.info(`Free keyword peek \u2014 "${D.keyword}": ${D.volume.toLocaleString("en-US")} searches/mo${T}. You get ~10 free peeks/day: ${f('keywords --peek "<keyword>"')}`)}else D?.status==="no-data"&&l.info(`Free keyword peek is live \u2014 no search-volume data for "${D.keyword}" yet. Try a topic keyword (~10 free/day): ${f('keywords --peek "best <your category> tool"')}`);z&&l.info(wn);let Q=_?a.domain:"your site",Re=_?[" 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."];xc([_?`\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:","",` ${m} \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):","",...Re,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${Q}`," (homepage + sitemap + robots.txt; the checks live in",` ${$} \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 ${m} is picked up automatically.`,...w?[` Symlinked at ${w} \u2192 ${g} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
30
- `))}import{existsSync as Do}from"fs";import{intro as Pc,outro as Ic,confirm as Tc,isCancel as Oc,cancel as Lc}from"@clack/prompts";import{existsSync as Ht,rmSync as Ac}from"fs";import{join as Kt}from"path";function jo(e,t={}){let n=[],r=Kt(e,k);Ht(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=Kt(e,he.CLAUDE);Ht(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=Kt(e,he.AGENTS);return Ht(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),Xr(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Kt(e,".claude","settings.json"),kind:"hook"}),t.global&&Ht(G)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:G,kind:"global"}),n}function No(e,t){for(let n of t)n.kind==="hook"?Zr(e):Ac(n.path,{recursive:!0,force:!0})}async function tt(e={}){let t=process.cwd(),n=jo(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Do(G)&&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(`
31
- `);if(!r){Pc("SEOAgent \u2014 uninstall"),l.message(`This will remove:
32
- ${o}`);let s=await Tc({message:"Remove these and start fresh?"});if(Oc(s)||!s){Lc("Cancelled \u2014 nothing was removed.");return}}No(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
30
+ `)}function Oc(e){let t=new Map,n;try{n=Pc(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!Fn(r[o])||!Lc(r[o+1]))continue;let i=Uo(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&&Fn(r[a]);a++){let c=Uo(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Ue(c,s.in_sitemap),in_nav:Ue(c,s.in_nav),status:Ue(c,s.status),rendered:Ue(c,s.rendered),word_count:Ue(c,s.word_count),notes:Ue(c,s.notes)})}break}return t}function Ue(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function Fn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function Lc(e){let t=e.trim();return Fn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Uo(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Mo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Me}from"@clack/prompts";var l={info:e=>Me.info(e),warn:e=>Me.warn(e),error:e=>Me.error(e),success:e=>Me.success(e),step:e=>Me.step(e),message:e=>Me.message(e)};function b(e,t,n,r=n){e?e.stop(r):l[t](n)}var Go=[{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"}],Jt="unknown",Uc=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Mc(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 Vt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Uc.has(t)?t:null}async function st(e={}){let t=process.cwd();if(Wr(t)){let a=x(t),c=Ne(t);be(t),J(t,{skill_version:E}),$e(t);let u=Ho(Qt(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${Qt(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==E?`${a.skill_version} \u2192 ${E}`:E;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.`),!En()){let m=Ut(t);m&&await Rn({installId:m,event:"reinit",cliVersion:E})&&l.info(Cn)}return}let n=!!e.yes||!process.stdin.isTTY;n||jc("SEOAgent \u2014 AI SEO Agent");let r=Io(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 ${Mc(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=Vt(e.siteType)||Vt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&Vt(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()&&Vt(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=Jt),s||(s="unknown"),await Wo(t,i,s);return}if(o(),!i){let a=await Bo({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Be(a)&&(Ge("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Un({message:"What kind of site is this?",options:[...Go]});Be(a)&&(Ge("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Fc({message:`Create .seoagent for ${i} (${s})?`});if(Be(a)&&(Ge("Cancelled"),process.exit(0)),a)break;let c=await Un({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Be(c)||c==="abort")&&(Ge("Cancelled"),process.exit(0)),c==="domain"){let u=await Bo({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Be(u)&&(Ge("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Un({message:"What kind of site is this?",options:[...Go]});Be(u)&&(Ge("Cancelled"),process.exit(0)),s=u}}await Wo(t,i,s)}async function Wo(e,t,n){let r=Dc();r.start("Setting up your SEO project");let o=xo(e),i=pe(e),s=_n(),a={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:E,skill_version:E,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=En(),u=c?Promise.resolve(!1):Rn({installId:s,event:"init",cliVersion:E}),d=c||t===Jt?Promise.resolve(null):Xr({domain:t,installId:s}),p=j(),m=p&&t!==Jt?je({apiBase:p.api_base,authHeader:`Bearer ${p.user_token}:${p.website_token}`,localDomain:t}).catch(()=>null):Promise.resolve(null);Kr(e),Hr(e,a),$e(e),$o(e,n),so(e);let g=Ne(e),$=Qt(e,g.skillFile),w=Ho($),C=`${w}/references/audit-checks.md`,A=g.claudeSymlink?Qt(e,g.claudeSymlink):void 0;be(e);let R=t!==Jt,U={pages:[],dynamicCount:0},L={wrote:!1,added:0,total:0,merged:!1};try{U=ne(e,R?t:null),L=zt(e,U.pages)}catch{}if(r.stop(R?`Created .seoagent/ project for ${a.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let le=o.evidence.map(Ze=>`${Ze.detail} (${Ze.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${le}`)}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.`),U.pages.length>0){let le=L.merged?L.added>0?`Re-scanned your codebase: +${L.added} new page${L.added===1?"":"s"} merged into .seoagent/pages.md (${L.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${L.total} pages)`:`Found ${U.pages.length} page${U.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(le+(U.dynamicCount>0?` (plus ${U.dynamicCount} dynamic route template${U.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let[V,Z,Xe]=await Promise.all([u,d,m]);if(Xe?.verdict==="mismatch"&&l.warn(`Heads up: you're logged in to a SEOAgent cloud project for ${Xe.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 le=Z.difficulty!=null?`, difficulty ${Z.difficulty}/100`:"";l.info(`Free keyword peek \u2014 "${Z.keyword}": ${Z.volume.toLocaleString("en-US")} searches/mo${le}. 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"')}`);V&&l.info(Cn);let M=R?a.domain:"your site",we=R?[" 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."];Nc([R?`\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:","",` ${$} \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):","",...we,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${M}`," (homepage + sitemap + robots.txt; the checks live in",` ${C} \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 ${$} is picked up automatically.`,...A?[` Symlinked at ${A} \u2192 ${w} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
31
+ `))}import{existsSync as Yo}from"fs";import{intro as Gc,outro as Wc,confirm as Hc,isCancel as Kc,cancel as qc}from"@clack/prompts";import{existsSync as Xt,rmSync as Bc}from"fs";import{join as Zt}from"path";function Ko(e,t={}){let n=[],r=Zt(e,k);Xt(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=Zt(e,ke.CLAUDE);Xt(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=Zt(e,ke.AGENTS);return Xt(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),co(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Zt(e,".claude","settings.json"),kind:"hook"}),t.global&&Xt(W)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:W,kind:"global"}),n}function qo(e,t){for(let n of t)n.kind==="hook"?lo(e):Bc(n.path,{recursive:!0,force:!0})}async function at(e={}){let t=process.cwd(),n=Ko(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Yo(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){Gc("SEOAgent \u2014 uninstall"),l.message(`This will remove:
33
+ ${o}`);let s=await Hc({message:"Remove these and start fresh?"});if(Kc(s)||!s){qc("Cancelled \u2014 nothing was removed.");return}}qo(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
33
34
  `);r?l.success(`Removed:
34
- ${i}`):Ic(`Removed:
35
- ${i}`),!e.global&&Do(G)&&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 x from"picocolors";import{existsSync as Uo,mkdirSync as Fo,readFileSync as jc,writeFileSync as Nc,chmodSync as Dc,unlinkSync as Fc}from"fs";import{dirname as Uc}from"path";function U(){if(!Uo(ae))return null;try{let e=JSON.parse(jc(ae,"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||ze}}catch{return null}}function Mo(e){Fo(G,{recursive:!0}),Fo(Uc(ae),{recursive:!0}),Nc(ae,JSON.stringify(e,null,2)+`
36
- `,"utf-8");try{Dc(ae,384)}catch{}}function Bo(){if(!Uo(ae))return!1;try{return Fc(ae),!0}catch{return!1}}import{existsSync as nt,readdirSync as On,statSync as Mc,readFileSync as Go}from"fs";import{join as Ue}from"path";function Bc(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Gc(e){let t=Ue(e,"audit","latest.md");if(!nt(t))return null;let n=It(t);if(!n)return null;let r=Go(t,"utf-8"),o=Bc(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Wc(e){try{let n=Go(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 Hc(e){let t=Ue(e,"strategy","clusters");if(!nt(t))return null;let n=On(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Wc(Ue(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Kc(e){let t=Ue(e,"briefs");if(!nt(t))return null;let n=On(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function qc(e){let t=Ue(e,"content");if(!nt(t))return null;let n=On(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Yc(e){let t=Ue(e,"roadmap.md");return nt(t)?{exists:!0,updatedAt:Mc(t).mtime.toISOString()}:null}function Wo(e){let t=C(e);if(!t)return null;let n=Ve(e);return{domain:t.domain,audit:Gc(n),strategy:Hc(n),briefs:Kc(n),content:qc(n),roadmap:Yc(n)}}import ue from"picocolors";var zc=/\x1b\[[0-9;]*m/g;function Ho(e){return e.replace(zc,"").length}function j(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Vc(n,t.title),s=ue.dim(`\u251C${o}\u2524`),a=ue.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(Jc(u.content,r))}return c.push(a),c.join(`
37
- `)}function Vc(e,t){if(!t)return ue.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Ho(t),r=e-5-n;return r<1?ue.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ue.dim("\u250C\u2500 ")}${t}${ue.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Jc(e,t){let n=Ho(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ue.dim("\u2502")} ${r} ${ue.dim("\u2502")}`}function Ln(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 rt(){let e=Wo(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(Qc(e))}function Qc(e){if(!e)return"";let t=11,n=s=>x.dim(s.padEnd(t)),r=[];U()?(r.push({content:`${x.green("\u2713")} ${x.dim("Logged in")}`}),r.push({content:x.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${x.dim("\u25CB Not logged in")}`}),r.push({content:x.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${x.green(`last run ${Ln(e.audit.date??"")}`)} ${x.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${x.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${x.bold(x.cyan(String(e.strategy.clusterCount??0)))} ${x.dim("clusters")} \xB7 ${x.bold(x.cyan(String(e.strategy.articleCount??0)))} ${x.dim("ideas")}`:`${n("Strategy:")}${x.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${x.bold(x.cyan(String(e.briefs.count??0)))} ${x.dim("ready")}`:`${n("Briefs:")}${x.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${x.green("\u2713")} ${x.bold(x.cyan(String(e.content.count??0)))} ${x.dim("articles written")}`:`${n("Content:")}${x.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${x.green("updated")} ${x.dim(Ln(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${x.dim("not yet created")}`});let i=`${x.bold(x.cyan("SEOAgent"))} ${x.dim("\xB7")} ${x.bold(e.domain)}`;return j(r,{width:78,title:i})}import{exec as Xc,spawn as Ko}from"child_process";import{confirm as Zc,isCancel as el}from"@clack/prompts";import B from"picocolors";function Me(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 tl=`https://registry.npmjs.org/${re}/latest`,ot=["free","starter","pro","scale","enterprise"],qt={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function nl(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return ot.includes(t)?t:null}function rl(e){let t=ot.indexOf(e);return t===-1||t===ot.length-1?null:ot[t+1]}async function ol(e,t=fetch){if(!e)return null;try{let n=(e.api_base||R.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 il(e){let t=[],r=s=>B.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${B.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${B.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of ot){let a=qt[s];s===e.current?t.push({content:`${B.bold(B.green("\u25CF"))} ${B.bold(B.green(a.padEnd(11)))} ${B.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${B.yellow("\u25C6")} ${B.bold(B.yellow(a.padEnd(11)))} ${B.yellow("next tier")}`}):t.push({content:B.dim(` ${a}`)})}let i=`${B.bold(B.cyan("SEOAgent Cloud"))} ${B.dim("\xB7")} ${B.dim("your plan")}`;return j(t,{width:55,title:i})}async function it(){let e=U(),t=!!process.stdin.isTTY;if(e&&t){let n=await ol(e);if(n){let r=nl(n.plan),o=r?rl(r):null;if(r&&l.message(il({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${qt[r]} (highest tier).`);return}if(r&&o){let i=await Zc({message:`Upgrade from ${qt[r]} to ${qt[o]}?`});if(el(i)||!i){l.info("No changes.");return}}}}sl()}function sl(){let e=al();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}"`;Xc(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function al(){let e=process.cwd(),t=C(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${R.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function st(e={}){let t=A,n=await ll();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 ${re}@latest`);return}if(Me(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!mn()){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 ${re}@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 ${re}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${re}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await ul()){l.error(`Update failed. Try manually: npm install -g ${re}@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 cl()||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 cl(){return new Promise(e=>{try{let t=Ko("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function ll(e=fetch){try{let t=await e(tl,{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 ul(){return new Promise(e=>{let t=Ko("npm",["install","-g",`${re}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as dl}from"child_process";import{randomBytes as pl}from"crypto";import{isCancel as fl,spinner as ml,text as gl}from"@clack/prompts";import de from"picocolors";function qo(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 hl=1500,yl=300*1e3;function wl(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;dl(t,()=>{})}function kl(){return pl(16).toString("hex")}function bl(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Yo(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 $l(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 qo(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Sl(e){return new Promise(t=>setTimeout(t,e))}async function at(e={}){let t=process.cwd(),n=C(t),r=(e.apiBase||R.BASE||ze).replace(/\/$/,"");if(U()){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 gl({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(!Yo(String(g)))return"Please enter a valid domain like `example.com`."}});if(fl(p)){l.warn("Login cancelled.");return}let m=Yo(String(p));if(m){o=m;try{V(t,{domain:m}),l.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=kl(),s=bl(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}`),wl(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?ml():null;c?.start(de.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+yl,d=!0;for(;Date.now()<u;){d||await Sl(hl),d=!1;let p=await $l(r,i);if(p.status==="ready"){Mo({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 ${de.bold(p.email)} (${de.cyan(p.domain)}).`:p.email?`Logged in as ${de.bold(p.email)}.`:"Logged in.";b(c,"success",m,de.green(g)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){b(c,"warn",`Session expired. Run \`${f("login")}\` again.`,de.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){b(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,de.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}b(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,de.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function ct(){Bo()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as Yu}from"@clack/prompts";import pe from"picocolors";import{existsSync as qn,mkdirSync as gu,readFileSync as $i,readdirSync as hu,writeFileSync as yu}from"fs";import{createHash as wu}from"crypto";import{join as Yn,relative as ku,sep as bu}from"path";import{existsSync as vl,mkdirSync as xl,readdirSync as zo,readFileSync as Vo,writeFileSync as _l}from"fs";import{dirname as Cl,join as Be,relative as El}from"path";var ve=e=>typeof e=="string"&&e?e:void 0;function jn(e,t){let n=Be(e,t),r;try{r=zo(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=Be(n,i),a;try{a=ce(Vo(s,"utf-8")).data}catch{continue}let c=ve(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:c,title:ve(a.title)??c,draft:a.draft===!0,page_type:ve(a.page_type)??ve(a.type),path:El(e,s)})}return o}function Nn(e){let t;try{t=zo(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Be(e,r),i;try{i=ce(Vo(o,"utf-8")).data}catch{continue}n.push({slug:ve(i.slug)??r.replace(/\.md$/,""),source:ve(i.source)??"external",repo_path:ve(i.repo_path)??null,file:o})}return n}function Dn(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 Fn(e){return t=>vl(Be(e,t))}function Un(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Jo(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function lt(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 ut(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}`):Wc(`Removed:
36
+ ${i}`),!e.global&&Yo(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 v from"picocolors";import{existsSync as ct,readdirSync as Mn,statSync as Yc,readFileSync as zo}from"fs";import{join as We}from"path";function zc(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Vc(e){let t=We(e,"audit","latest.md");if(!ct(t))return null;let n=Dt(t);if(!n)return null;let r=zo(t,"utf-8"),o=zc(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Jc(e){try{let n=zo(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 Qc(e){let t=We(e,"strategy","clusters");if(!ct(t))return null;let n=Mn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Jc(We(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Xc(e){let t=We(e,"briefs");if(!ct(t))return null;let n=Mn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Zc(e){let t=We(e,"content");if(!ct(t))return null;let n=Mn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function el(e){let t=We(e,"roadmap.md");return ct(t)?{exists:!0,updatedAt:Yc(t).mtime.toISOString()}:null}function Vo(e){let t=x(e);if(!t)return null;let n=tt(e);return{domain:t.domain,audit:Vc(n),strategy:Qc(n),briefs:Xc(n),content:Zc(n),roadmap:el(n)}}import fe from"picocolors";var tl=/\x1b\[[0-9;]*m/g;function Jo(e){return e.replace(tl,"").length}function N(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=nl(n,t.title),s=fe.dim(`\u251C${o}\u2524`),a=fe.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(rl(u.content,r))}return c.push(a),c.join(`
37
+ `)}function nl(e,t){if(!t)return fe.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Jo(t),r=e-5-n;return r<1?fe.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${fe.dim("\u250C\u2500 ")}${t}${fe.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function rl(e,t){let n=Jo(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${fe.dim("\u2502")} ${r} ${fe.dim("\u2502")}`}function Bn(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 lt(){let e=Vo(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(ol(e))}function ol(e){if(!e)return"";let t=11,n=s=>v.dim(s.padEnd(t)),r=[];j()?(r.push({content:`${v.green("\u2713")} ${v.dim("Logged in")}`}),r.push({content:v.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${v.dim("\u25CB Not logged in")}`}),r.push({content:v.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${v.green(`last run ${Bn(e.audit.date??"")}`)} ${v.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${v.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${v.bold(v.cyan(String(e.strategy.clusterCount??0)))} ${v.dim("clusters")} \xB7 ${v.bold(v.cyan(String(e.strategy.articleCount??0)))} ${v.dim("ideas")}`:`${n("Strategy:")}${v.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${v.bold(v.cyan(String(e.briefs.count??0)))} ${v.dim("ready")}`:`${n("Briefs:")}${v.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${v.green("\u2713")} ${v.bold(v.cyan(String(e.content.count??0)))} ${v.dim("articles written")}`:`${n("Content:")}${v.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${v.green("updated")} ${v.dim(Bn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${v.dim("not yet created")}`});let i=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.bold(e.domain)}`;return N(r,{width:78,title:i})}import{exec as il,spawn as Qo}from"child_process";import{confirm as sl,isCancel as al}from"@clack/prompts";import G from"picocolors";function He(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 cl=`https://registry.npmjs.org/${se}/latest`,ut=["free","starter","pro","scale","enterprise"],en={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ll(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return ut.includes(t)?t:null}function ul(e){let t=ut.indexOf(e);return t===-1||t===ut.length-1?null:ut[t+1]}async function dl(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 pl(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 ut){let a=en[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 N(t,{width:55,title:i})}async function dt(){let e=j(),t=!!process.stdin.isTTY;if(e&&t){let n=await dl(e);if(n){let r=ll(n.plan),o=r?ul(r):null;if(r&&l.message(pl({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${en[r]} (highest tier).`);return}if(r&&o){let i=await sl({message:`Upgrade from ${en[r]} to ${en[o]}?`});if(al(i)||!i){l.info("No changes.");return}}}}fl()}function fl(){let e=ml();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}"`;il(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function ml(){let e=x(process.cwd());return ee("cli-upgrade",e?.domain)}async function pt(e={}){let t=E,n=await hl();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(He(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Sn()){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 yl()){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 gl()||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 gl(){return new Promise(e=>{try{let t=Qo("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function hl(e=fetch){try{let t=await e(cl,{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 yl(){return new Promise(e=>{let t=Qo("npm",["install","-g",`${se}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as wl}from"child_process";import{randomBytes as kl}from"crypto";import{isCancel as bl,spinner as $l,text as Sl}from"@clack/prompts";import me from"picocolors";function Xo(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 vl=1500,xl=300*1e3;function _l(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;wl(t,()=>{})}function Cl(){return kl(16).toString("hex")}function El(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Zo(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 Rl(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 Xo(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Al(e){return new Promise(t=>setTimeout(t,e))}async function ft(e={}){let t=process.cwd(),n=x(t),r=(e.apiBase||T.BASE||et).replace(/\/$/,"");if(j()){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 Sl({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(!Zo(String(g)))return"Please enter a valid domain like `example.com`."}});if(bl(p)){l.warn("Login cancelled.");return}let m=Zo(String(p));if(m){o=m;try{J(t,{domain:m}),l.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=Cl(),s=El(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}`),_l(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?$l():null;c?.start(me.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+xl,d=!0;for(;Date.now()<u;){d||await Al(vl),d=!1;let p=await Rl(r,i);if(p.status==="ready"){zr({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 ${me.bold(p.email)} (${me.cyan(p.domain)}).`:p.email?`Logged in as ${me.bold(p.email)}.`:"Logged in.";b(c,"success",m,me.green(g)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){b(c,"warn",`Session expired. Run \`${f("login")}\` again.`,me.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){b(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,me.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}b(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,me.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function mt(){Vr()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as ed}from"@clack/prompts";import Q from"picocolors";import{existsSync as Zn,mkdirSync as Su,readFileSync as Ei,readdirSync as vu,writeFileSync as xu}from"fs";import{createHash as _u}from"crypto";import{join as er,relative as Cu,sep as Eu}from"path";import{existsSync as Pl,mkdirSync as Il,readdirSync as ei,readFileSync as ti,writeFileSync as Tl}from"fs";import{dirname as Ol,join as Ke,relative as Ll}from"path";var Ce=e=>typeof e=="string"&&e?e:void 0;function Gn(e,t){let n=Ke(e,t),r;try{r=ei(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=Ke(n,i),a;try{a=de(ti(s,"utf-8")).data}catch{continue}let c=Ce(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:c,title:Ce(a.title)??c,draft:a.draft===!0,page_type:Ce(a.page_type)??Ce(a.type),path:Ll(e,s)})}return o}function Wn(e){let t;try{t=ei(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Ke(e,r),i;try{i=de(ti(o,"utf-8")).data}catch{continue}n.push({slug:Ce(i.slug)??r.replace(/\.md$/,""),source:Ce(i.source)??"external",repo_path:Ce(i.repo_path)??null,file:o})}return n}function Hn(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 Kn(e){return t=>Pl(Ke(e,t))}function qn(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ni(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function gt(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 ht(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 Qo(e,t){let n=Be(e,k,"content"),r=Nn(n),o=new Set;for(let c of r)c.source==="repo"&&c.repo_path&&o.add(Cl(c.repo_path));if(o.size===0)return{tracked:[]};let i=[...o].flatMap(c=>jn(e,c)),s=Dn(i,r,Fn(e));if(s.toTrack.length===0)return{tracked:[]};xl(n,{recursive:!0});let a=[];for(let c of s.toTrack){let u=ut({slug:c.slug,title:c.title,canonical:lt(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()});_l(Be(n,`${c.slug}.md`),u,"utf-8"),a.push(c.slug)}return{tracked:a}}import{existsSync as Bn,mkdirSync as Rl,readdirSync as Xo,readFileSync as Al,unlinkSync as Pl,writeFileSync as Mn}from"fs";import{join as We}from"path";import F from"picocolors";function oe(e){return We(e,k,"inbox")}function Zo(e){return`${e.action_type}-${e.id}.md`}function Il(e,t){let n=0;if(!Bn(e))return 0;for(let r of Xo(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{Pl(We(e,r)),n++}catch{}}return n}function Tl(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 ri(e,t){let n=Ke(e,k,"content"),r=Wn(n),o=new Set;for(let c of r)c.source==="repo"&&c.repo_path&&o.add(Ol(c.repo_path));if(o.size===0)return{tracked:[]};let i=[...o].flatMap(c=>Gn(e,c)),s=Hn(i,r,Kn(e));if(s.toTrack.length===0)return{tracked:[]};Il(n,{recursive:!0});let a=[];for(let c of s.toTrack){let u=ht({slug:c.slug,title:c.title,canonical:gt(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()});Tl(Ke(n,`${c.slug}.md`),u,"utf-8"),a.push(c.slug)}return{tracked:a}}import{existsSync as zn,mkdirSync as jl,readdirSync as oi,readFileSync as Nl,unlinkSync as Dl,writeFileSync as Yn}from"fs";import{join as Ye}from"path";import F from"picocolors";function ae(e){return Ye(e,k,"inbox")}function ii(e){return`${e.action_type}-${e.id}.md`}function Fl(e,t){let n=0;if(!zn(e))return 0;for(let r of oi(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{Dl(Ye(e,r)),n++}catch{}}return n}function Ul(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 Ol(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 Ll(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 jl(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 Ml(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 Bl(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 Gl(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. ${Ll(r,o,n)}
112
- 2. ${Ol(r)}
111
+ 1. ${Bl(r,o,n)}
112
+ 2. ${Ml(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 ei(e){return e.capture_screenshots!==!0?"":`
129
+ `}function si(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 Nl(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 Wl(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
- ${ei(t)}
166
+ ${si(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 Dl(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 Hl(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 Fl(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 Kl(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 Ul(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 ql(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
- ${ei(t)}
312
+ ${si(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 Ml(e){switch(e.action_type){case"cli_prune_pending":return Tl(e);case"cli_technical_fix":return jl(e);case"cli_new_content":return Nl(e);case"cli_content_update":return Dl(e);case"cli_sitemap_update":return Fl(e);case"cli_new_landing_page":return Ul(e);default:return null}}function Bl(e){if(e.length===0)return`# SEOAgent Inbox
343
+ `}function Yl(e){switch(e.action_type){case"cli_prune_pending":return Ul(e);case"cli_technical_fix":return Gl(e);case"cli_new_content":return Wl(e);case"cli_content_update":return Hl(e);case"cli_sitemap_update":return Kl(e);case"cli_new_landing_page":return ql(e);default:return null}}function zl(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 \`${Zo(n)}\``);return`# SEOAgent Inbox
346
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${ii(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 xe(e){let t=oe(e);if(!Bn(t))return[];let n=[];for(let r of Xo(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 $=Al(We(t,r),"utf-8"),w=$.match(/^---\n([\s\S]*?)\n---/);if(w){let I=w[1];c=Ge(I,"severity"),u=Ge(I,"issue"),d=Ge(I,"page_url");let z=Ge(I,"priority");(z==="high"||z==="medium"||z==="low")&&(p=z),m=Ge(I,"impact_estimate"),g=Ge(I,"effort_estimate")}let S=$.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);S&&(a=S[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 He(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Gl[e.severity??""]??F.dim,r=e.severity??"unknown",o=[F.dim("\u25B8"),F.bold(`id ${e.id}`),F.dim("\xB7"),F.cyan(t),n(r)];if(e.priority){let i=Wl[e.priority];o.push(F.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(F.dim("\xB7"),F.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(F.dim("\xB7"),F.dim(`\u23F1 ${e.effort_estimate}`)),o.push(F.dim("\u2014"),e.title),o.join(" ")}var Gl={critical:e=>F.red(F.bold(e)),high:e=>F.red(e),medium:e=>F.yellow(e),low:e=>F.dim(e)},Wl={high:e=>F.red(F.bold(e)),medium:e=>F.yellow(e),low:e=>F.dim(e)};function Ge(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 Yt(e){let t=oe(e);if(!Bn(t))return;let n=xe(e),r=n.length===0?`# SEOAgent Inbox
358
+ `}function Ee(e){let t=ae(e);if(!zn(t))return[];let n=[];for(let r of oi(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 $=Nl(Ye(t,r),"utf-8"),w=$.match(/^---\n([\s\S]*?)\n---/);if(w){let R=w[1];c=qe(R,"severity"),u=qe(R,"issue"),d=qe(R,"page_url");let U=qe(R,"priority");(U==="high"||U==="medium"||U==="low")&&(p=U),m=qe(R,"impact_estimate"),g=qe(R,"effort_estimate")}let A=$.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);A&&(a=A[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 ze(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Vl[e.severity??""]??F.dim,r=e.severity??"unknown",o=[F.dim("\u25B8"),F.bold(`id ${e.id}`),F.dim("\xB7"),F.cyan(t),n(r)];if(e.priority){let i=Jl[e.priority];o.push(F.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(F.dim("\xB7"),F.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(F.dim("\xB7"),F.dim(`\u23F1 ${e.effort_estimate}`)),o.push(F.dim("\u2014"),e.title),o.join(" ")}var Vl={critical:e=>F.red(F.bold(e)),high:e=>F.red(e),medium:e=>F.yellow(e),low:e=>F.dim(e)},Jl={high:e=>F.red(F.bold(e)),medium:e=>F.yellow(e),low:e=>F.dim(e)};function qe(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 tn(e){let t=ae(e);if(!zn(t))return;let n=Ee(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,35 +370,35 @@ 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
- `;Mn(We(t,"README.md"),r,"utf-8")}function ti(e,t){let n=oe(e);Rl(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Il(n,r),i=0;for(let s of t){let a=Ml(s);a!==null&&(Mn(We(n,Zo(s)),a,"utf-8"),i++)}return Mn(We(n,"README.md"),Bl(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as ql}from"crypto";import{existsSync as oi,mkdirSync as Yl,readFileSync as zl,statSync as ii,writeFileSync as ri,rmSync as Vl}from"fs";import{dirname as Jl,join as Gn,sep as Ql}from"path";function Hl(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Kl=[{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 ni(e,t){let n=Hl(e);for(let{cls:r,test:o}of Kl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Xl(e){return"sha256:"+ql("sha256").update(e).digest("hex")}function Zl(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 eu(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:ni(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 si(e){let t=await ci({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 ai(e,t){return Gn(e,t.split("/").join(Ql))}function tu(e,t,n){let r={};for(let o of t){let i=ai(e,o);if(!oi(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=ii(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Xl(zl(i,"utf-8")),locallyEdited:c}}return r}async function ci(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 li(e){let t=Gn(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!oi(t))return{...n,ok:!0};let r=await ci({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=tu(t,i,e.stateFiles),a=Zl(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=ai(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{Yl(Jl(p),{recursive:!0}),ri(p,d.body??"","utf-8");let m=ii(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":Vl(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=eu(a,o,c.cursor,new Date().toISOString());if(u)try{ri(Gn(t,Et),JSON.stringify(u,null,2)+`
374
- `,"utf-8")}catch{}return c}import{existsSync as di,mkdirSync as pi,readFileSync as nu,writeFileSync as Wn}from"fs";import{dirname as fi,join as ru}from"path";var Hn=1,ui=500;function Kn(e){return ru(e,k,Ar)}function zt(e){let t=Kn(e);if(!di(t))return[];try{let n=nu(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==Hn||!Array.isArray(o.entries)?[]:o.entries.filter(ou)}catch{return[]}}function mi(e,t){let n=Kn(e),o=zt(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:Hn,entries:i};try{pi(fi(n),{recursive:!0}),Wn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function gi(e,t){if(t.length===0)return;let n=Kn(e),r=zt(e).filter(i=>!t.includes(i.action_id)),o={version:Hn,entries:r};try{if(r.length===0&&di(n)){Wn(n,JSON.stringify(o,null,2),"utf-8");return}pi(fi(n),{recursive:!0}),Wn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function ou(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 hi,readFileSync as iu,unlinkSync as su,writeFileSync as au,openSync as cu,closeSync as lu,mkdirSync as uu}from"fs";import{dirname as du,join as pu}from"path";var fu=6e4;function yi(e){return pu(e,k,Pr)}function wi(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??fu,i=yi(e);if(!hi(i))return Vt(i,r,n());let s=bi(i);return!s||n()-s.started_at>o||!mu(s.pid)?Vt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function ki(e,t={}){let n=t.pid??process.pid,r=yi(e);if(!hi(r))return;let o=bi(r);if(!(o&&o.pid!==n))try{su(r)}catch{}}function Vt(e,t,n){let r={pid:t,started_at:n};try{uu(du(e),{recursive:!0});let o=cu(e,"w");try{au(o,JSON.stringify(r))}finally{lu(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function bi(e){try{let t=iu(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 mu(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var $u=new Set([".md"]),Su=new Set(["inbox"]);function vu(e){let t=[];function n(r,o){if(qn(r))for(let i of hu(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Su.has(i.name))continue;let s=Yn(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);$u.has(c)&&t.push(s)}}}return n(e,""),t}function Si(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Yn(fn,`${t}.json`)}function xu(e){return wu("sha256").update(e,"utf-8").digest("hex")}function _u(e){let t=Si(e);if(!qn(t))return{files:{},last_synced_at:null};try{return JSON.parse($i(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Cu(e,t){gu(fn,{recursive:!0}),yu(Si(e),JSON.stringify(t,null,2)+`
375
- `,"utf-8")}function Eu(e,t){return ku(e,t).split(bu).join("/")}async function Ru(e,t){try{let n=await O(`${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 Au(e,t,n){try{let r=await O(`${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 vi(e,t={}){let n=U();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=C(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=Yn(e,k);if(!qn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!wi(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Pu(e,t,n,r,o)}finally{ki(e)}}async function Pu(e,t,n,r,o){let i=_u(r.domain);try{Qo(e,r)}catch{}let s=vu(o),a=n.api_base||R.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],m=0,g=await Iu(e,a,c);if(!t.pullOnly)for(let T of s){let se=Eu(o,T);if(t.pathFilter&&!se.endsWith(t.pathFilter))continue;let xr=$i(T,"utf-8"),_r=xu(xr),Cr=i.files[se];if(!(!Cr||Cr.hash!==_r)&&!t.force)continue;m++;let pn=await Au(a,{path:se,contents:xr,domain:r.domain},c);pn.ok?(i.files[se]={hash:_r},u++):(d++,p.push(`${se}: ${pn.status} ${pn.error??""}`.trim()))}let $=await Ru(a,c),w=0,_=0;if($.ok){let T=ti(e,$.actions);w=T.wrote,_=T.removed}else $.error&&p.push(`pull actions: ${$.error}`);let S,I=!1,z=i.last_synced_at;if(!t.pushOnly){let T=await li({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});T.ok?z=T.cursor:(I=!0,T.error&&p.push(`pull: ${T.error}`)),S={written:T.written,overwritten:T.overwritten,skipped:T.skipped,conflicts:T.conflicts,deleted:T.deleted,warnings:T.warnings}}let D=!!S&&S.written+S.overwritten+S.deleted+S.conflicts>0;if(i.last_synced_at=z,Cu(r.domain,i),m===0&&w===0&&_===0&&!D&&g.flushed===0&&g.dropped===0&&!I&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:S};let Re=d===0&&!I;return{ok:Re,reason:Re?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:w,actionsRemoved:_,acksFlushed:g.flushed,acksDropped:g.dropped,pull:S}}async function Iu(e,t,n){let r=zt(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Tu(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&gi(e,s),{flushed:o,dropped:i}}async function Tu(e,t,n){try{let r=await O(`${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 xi(e){let t;try{t=C(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(Me(A,n)<=0){if(!t.skill_version)try{V(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return Te(e),V(e,{skill_version:A}),{refreshed:!0,from:n,to:A,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function zn(e){let t;try{t=C(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 Te(e),V(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 Ou,mkdirSync as Lu,readFileSync as ju,writeFileSync as Nu}from"fs";var Du="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Fu=1440*60*1e3,Uu=720*60*1e3,Mu=2e3;function Bu(e,t,n=Fu){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Gu(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Uu;if(!n||Me(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 Wu(e){let t=e.readCache();if(Bu(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Gu({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 Hu(){try{return Ou(Rt)?JSON.parse(ju(Rt,"utf-8")):{}}catch{return{}}}function Ku(e){try{Lu(G,{recursive:!0}),Nu(Rt,JSON.stringify(e,null,2)+`
376
- `,"utf-8")}catch{}}async function qu(){try{let e=await fetch(Du,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Mu)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function _i(e){try{return await Wu({current:e,now:new Date,fetchLatest:qu,readCache:Hu,writeCache:Ku})}catch{return null}}async function K(e={}){let t=xi(process.cwd());if(t.refreshed){try{ye(process.cwd())}catch{}e.silent||l.info(pe.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}we(process.cwd());let n=await _i(A);n&&l.message(pe.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?Yu():null;i?.start(`${o} ${pe.dim(".seoagent/")} with your dashboard\u2026`);let s=await vi(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){b(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,pe.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){b(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,pe.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="no-changes"){b(i,"info","Already in sync.",pe.green("Already in sync."));return}if(s.reason==="busy"){b(i,"info","Another sync is in progress \u2014 skipping this run.",pe.dim("Another sync is in progress \u2014 skipping this run."));return}let a=zu(s);b(i,"success",a??"Sync complete.",pe.green(a??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let c=s.pull;if(c){let u=c.written+c.overwritten;u>0&&l.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(c.overwritten>0?` (${c.overwritten} updated)`:"")),c.deleted>0&&l.info(`Removed ${c.deleted} file${c.deleted===1?"":"s"} deleted in the cloud.`),c.conflicts>0&&l.warn(`${c.conflicts} conflict${c.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of c.warnings.slice(0,5))l.info(` \u2022 ${d}`)}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 u of s.errors.slice(0,3))l.info(` \u2022 ${u}`)}}function zu(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=C(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function _e(e={}){if(e.print){let t=U();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let n=t.api_base||R.BASE,r=await si({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){l.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
373
+ `;Yn(Ye(t,"README.md"),r,"utf-8")}function ai(e,t){let n=ae(e);jl(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Fl(n,r),i=0;for(let s of t){let a=Yl(s);a!==null&&(Yn(Ye(n,ii(s)),a,"utf-8"),i++)}return Yn(Ye(n,"README.md"),zl(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Zl}from"crypto";import{existsSync as ui,mkdirSync as eu,readFileSync as tu,statSync as di,writeFileSync as li,rmSync as nu}from"fs";import{dirname as ru,join as Vn,sep as ou}from"path";function Ql(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Xl=[{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 ci(e,t){let n=Ql(e);for(let{cls:r,test:o}of Xl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function iu(e){return"sha256:"+Zl("sha256").update(e).digest("hex")}function su(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 au(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:ci(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 pi(e){let t=await mi({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 fi(e,t){return Vn(e,t.split("/").join(ou))}function cu(e,t,n){let r={};for(let o of t){let i=fi(e,o);if(!ui(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=di(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:iu(tu(i,"utf-8")),locallyEdited:c}}return r}async function mi(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 gi(e){let t=Vn(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!ui(t))return{...n,ok:!0};let r=await mi({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=cu(t,i,e.stateFiles),a=su(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=fi(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{eu(ru(p),{recursive:!0}),li(p,d.body??"","utf-8");let m=di(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=au(a,o,c.cursor,new Date().toISOString());if(u)try{li(Vn(t,Ot),JSON.stringify(u,null,2)+`
374
+ `,"utf-8")}catch{}return c}import{existsSync as yi,mkdirSync as wi,readFileSync as lu,writeFileSync as Jn}from"fs";import{dirname as ki,join as uu}from"path";var Qn=1,hi=500;function Xn(e){return uu(e,k,Lr)}function nn(e){let t=Xn(e);if(!yi(t))return[];try{let n=lu(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==Qn||!Array.isArray(o.entries)?[]:o.entries.filter(du)}catch{return[]}}function bi(e,t){let n=Xn(e),o=nn(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>hi?o.slice(-hi):o,s={version:Qn,entries:i};try{wi(ki(n),{recursive:!0}),Jn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function $i(e,t){if(t.length===0)return;let n=Xn(e),r=nn(e).filter(i=>!t.includes(i.action_id)),o={version:Qn,entries:r};try{if(r.length===0&&yi(n)){Jn(n,JSON.stringify(o,null,2),"utf-8");return}wi(ki(n),{recursive:!0}),Jn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function du(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 Si,readFileSync as pu,unlinkSync as fu,writeFileSync as mu,openSync as gu,closeSync as hu,mkdirSync as yu}from"fs";import{dirname as wu,join as ku}from"path";var bu=6e4;function vi(e){return ku(e,k,jr)}function xi(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??bu,i=vi(e);if(!Si(i))return rn(i,r,n());let s=Ci(i);return!s||n()-s.started_at>o||!$u(s.pid)?rn(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function _i(e,t={}){let n=t.pid??process.pid,r=vi(e);if(!Si(r))return;let o=Ci(r);if(!(o&&o.pid!==n))try{fu(r)}catch{}}function rn(e,t,n){let r={pid:t,started_at:n};try{yu(wu(e),{recursive:!0});let o=gu(e,"w");try{mu(o,JSON.stringify(r))}finally{hu(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Ci(e){try{let t=pu(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 $u(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ru=new Set([".md"]),Au=new Set(["inbox"]);function Pu(e){let t=[];function n(r,o){if(Zn(r))for(let i of vu(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Au.has(i.name))continue;let s=er(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);Ru.has(c)&&t.push(s)}}}return n(e,""),t}function Ri(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return er($n,`${t}.json`)}function Iu(e){return _u("sha256").update(e,"utf-8").digest("hex")}function Tu(e){let t=Ri(e);if(!Zn(t))return{files:{},last_synced_at:null};try{return JSON.parse(Ei(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Ou(e,t){Su($n,{recursive:!0}),xu(Ri(e),JSON.stringify(t,null,2)+`
375
+ `,"utf-8")}function Lu(e,t){return Cu(e,t).split(Eu).join("/")}async function ju(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 Nu(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 Ai(e,t={}){let n=j();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=x(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(r.domain===Le)return{ok:!0,reason:"domain-unknown",synced:0,failed:0,errors:[]};let o=er(e,k);if(!Zn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!xi(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Du(e,t,n,r,o)}finally{_i(e)}}async function Du(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=Tu(r.domain);try{ri(e,r)}catch{}let u=Pu(o),d=0,p=0,m=[],g=0,$=await Fu(e,i,s);if(!t.pullOnly)for(let M of u){let we=Lu(o,M);if(t.pathFilter&&!we.endsWith(t.pathFilter))continue;let le=Ei(M,"utf-8"),Ze=Iu(le),Ir=c.files[we];if(!(!Ir||Ir.hash!==Ze)&&!t.force)continue;g++;let bn=await Nu(i,{path:we,contents:le,domain:r.domain},s);bn.ok?(c.files[we]={hash:Ze},d++):(p++,m.push(`${we}: ${bn.status} ${bn.error??""}`.trim()))}let w=await ju(i,s),C=0,A=0;if(w.ok){let M=ai(e,w.actions);C=M.wrote,A=M.removed}else w.error&&m.push(`pull actions: ${w.error}`);let R,U=!1,L=c.last_synced_at;if(!t.pushOnly){let M=await gi({projectDir:e,apiBase:i,authHeader:s,since:c.last_synced_at,stateFiles:c.files,force:t.force});M.ok?L=M.cursor:(U=!0,M.error&&m.push(`pull: ${M.error}`)),R={written:M.written,overwritten:M.overwritten,skipped:M.skipped,conflicts:M.conflicts,deleted:M.deleted,warnings:M.warnings}}let V=!!R&&R.written+R.overwritten+R.deleted+R.conflicts>0;if(c.last_synced_at=L,Ou(r.domain,c),g===0&&C===0&&A===0&&!V&&$.flushed===0&&$.dropped===0&&!U&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:m,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:R};let Xe=p===0&&!U;return{ok:Xe,reason:Xe?void 0:"error",synced:d,failed:p,errors:m,actionsPulled:C,actionsRemoved:A,acksFlushed:$.flushed,acksDropped:$.dropped,pull:R}}async function Fu(e,t,n){let r=nn(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Uu(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&$i(e,s),{flushed:o,dropped:i}}async function Uu(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 Pi(e){let t;try{t=x(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(He(E,n)<=0){if(!t.skill_version)try{J(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return Ne(e),J(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function tr(e){let t;try{t=x(e)}catch{return{refreshed:!1,from:null,to:E,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:E,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return Ne(e),J(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:E,reason:"error"}}}import{existsSync as Mu,mkdirSync as Bu,readFileSync as Gu,writeFileSync as Wu}from"fs";var Hu="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Ku=1440*60*1e3,qu=720*60*1e3,Yu=2e3;function zu(e,t,n=Ku){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Vu(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??qu;if(!n||He(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 Ju(e){let t=e.readCache();if(zu(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Vu({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 Qu(){try{return Mu(Lt)?JSON.parse(Gu(Lt,"utf-8")):{}}catch{return{}}}function Xu(e){try{Bu(W,{recursive:!0}),Wu(Lt,JSON.stringify(e,null,2)+`
376
+ `,"utf-8")}catch{}}async function Zu(){try{let e=await fetch(Hu,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Yu)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function Ii(e){try{return await Ju({current:e,now:new Date,fetchLatest:Zu,readCache:Qu,writeCache:Xu})}catch{return null}}async function q(e={}){let t=Pi(process.cwd());if(t.refreshed){try{be(process.cwd())}catch{}e.silent||l.info(Q.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}$e(process.cwd());let n=await Ii(E);n&&l.message(Q.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?ed():null;i?.start(`${o} ${Q.dim(".seoagent/")} with your dashboard\u2026`);let s=await Ai(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){b(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,Q.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){b(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,Q.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="domain-unknown"){b(i,"info","`.seoagent/project.md` has `domain: unknown` \u2014 cloud sync skipped until you set your site's domain.",Q.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 u=`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.`;b(i,"warn",u,Q.yellow(u));return}if(s.reason==="unverified"){b(i,"info","Could not verify which cloud site this login is connected to \u2014 sync skipped (nothing pushed or pulled).",Q.dim("Cloud binding unverified \u2014 sync skipped.")),i&&s.errors[0]&&l.info(` \u2022 ${s.errors[0]}`);return}if(s.reason==="no-changes"){b(i,"info","Already in sync.",Q.green("Already in sync."));return}if(s.reason==="busy"){b(i,"info","Another sync is in progress \u2014 skipping this run.",Q.dim("Another sync is in progress \u2014 skipping this run."));return}let a=td(s);b(i,"success",a??"Sync complete.",Q.green(a??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let c=s.pull;if(c){let u=c.written+c.overwritten;u>0&&l.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(c.overwritten>0?` (${c.overwritten} updated)`:"")),c.deleted>0&&l.info(`Removed ${c.deleted} file${c.deleted===1?"":"s"} deleted in the cloud.`),c.conflicts>0&&l.warn(`${c.conflicts} conflict${c.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of c.warnings.slice(0,5))l.info(` \u2022 ${d}`)}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 u of s.errors.slice(0,3))l.info(` \u2022 ${u}`)}}function td(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 O(e){let t=x(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function Re(e={}){if(e.print){let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=O(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(Qr(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 pi({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(`
377
377
  `)||process.stdout.write(`
378
- `);return}await K({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Vu,readdirSync as Ju,unlinkSync as Qu}from"fs";import{join as Ci}from"path";import{isCancel as Xu,select as Zu}from"@clack/prompts";async function fe(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 ed(),n===null)return;let r=n,o=U();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||R.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await O(`${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{mi(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),Vn(r),Yt(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"){Vn(r),Yt(process.cwd());let $=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${$}.`);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}Vn(r),Yt(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: ${Ci(k,"inbox")}`))}function Vn(e){let t=oe(process.cwd());if(Vu(t)){for(let n of Ju(t))if(n.endsWith(`-${e}.md`))try{Qu(Ci(t,n))}catch{}}}async function ed(){let e=process.cwd(),t=xe(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 Zu({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:He(r)}))});return Xu(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import Jt from"picocolors";async function Jn(e={}){let t=process.cwd();if(!e.json&&!L(t))return;let n=xe(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:oe(t),actions:n})+`
379
- `);return}if(n.length===0){l.info(Jt.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(`${Jt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(He(r));l.message(""),l.message(`Apply one: ${Jt.bold(f("ack <id>"))} \xB7 Interactive picker: ${Jt.bold(f("ack"))} (no id)`)}import{readFileSync as ud}from"fs";import{join as dd,relative as pd}from"path";import{confirm as Ii,isCancel as Xt,multiselect as fd,note as Li,select as md}from"@clack/prompts";import h from"picocolors";import{query as gd}from"@anthropic-ai/claude-agent-sdk";import{existsSync as td,readdirSync as nd}from"fs";import{homedir as rd}from"os";import{join as od}from"path";import{execSync as Qn}from"child_process";function dt(){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":id()?sd()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function id(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Qn(e,{stdio:"ignore"}),!0}catch{return!1}}function sd(){let e=od(rd(),".claude");if(!td(e))return!1;try{return nd(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Ei(){try{return Qn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Ri(){try{return Qn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var ie={"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 Pi}from"marked";import{markedTerminal as ad}from"marked-terminal";import Xn from"picocolors";var Ai=!1;function cd(){Ai||(Pi.use(ad({reflowText:!1,width:100})),Ai=!0)}function Qt(e){if(!e)return e;cd();try{let t=Pi.parse(e);return typeof t=="string"?ld(t):e}catch{return e}}function ld(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Xn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Xn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Xn.italic(r))}async function er(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 $d(e.yes)){process.exitCode=1;return}if(e.yes)await K({embedded:!0});else{let u=await md({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(Xt(u)){l.info("Cancelled.");return}u==="sync"?await K({embedded:!0}):u==="pull"&&await _e({embedded:!0})}let r=xe(t);if(r.length===0){l.info(h.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 fd({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(g=>({value:g.id,label:He(g)})),initialValues:d,required:!1});if(Xt(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(S=>S.id===d);if(!p)continue;hd({index:u+1,total:o.length,entry:p});let m=dd(oe(t),p.filename),g;try{g=ud(m,"utf-8")}catch(S){l.error(` Could not read ${p.filename}: ${S.message}`),a++;continue}let $=Date.now(),w=await bd({cwd:t,entry:p,actionContent:g,model:e.model}),_=Ti(Date.now()-$);if(w.kind==="applied")try{await fe(String(d),{silent:!0}),i++,l.message("");let S=w.summary?`
380
- `+h.dim(" "+w.summary):"";l.message(` ${h.green("\u2713")} id ${d} ${h.dim("\u2014 applied in "+_)}${S}`)}catch(S){l.warn(` Applied but ack failed: ${S.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(w.kind==="declined")try{await fe(String(d),{silent:!0,failed:!0,reason:w.reason}),s++,l.message(""),l.message(` ${h.yellow("\u2298")} id ${d} ${h.dim("\u2014 declined: "+J(w.reason,100))}`)}catch(S){l.warn(` Could not ack decline: ${S.message}. Run \`seoagent ack ${d} --failed --reason "${w.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${h.red("\u2717")} id ${d} ${h.dim("\u2014 agent did not converge after "+_)}`)}wd({applied:i,declined:s,failed:a,total:o.length,elapsed:Ti(Date.now()-c)})}function hd(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=yd[i]??h.dim,a=[h.bold(`[${t}/${n}]`),h.dim("\xB7"),h.bold(`id ${r.id}`),h.dim("\xB7"),h.cyan(o),s(i)].join(" ");Li(r.title,a)}var yd={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function wd(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?h.green(`\u2713 ${t}/${o} applied`):h.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=h.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=h.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Li(`${a}
381
- ${h.dim("elapsed: "+i)}`,h.bold("Done"))}function Ti(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 kd(e){if(typeof e!="string"||!e)return null;let t=e.split(`
382
- `);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 bd(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Id(n,r);try{let s=gd({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)vd(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Cd(d,a)}else if(c.type==="result"){if(process.stdout.write(`
383
- `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=kd(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(`
384
- `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function $d(e){let t=dt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(h.dim(ie[t].summary)),!0;if(l.warn(ie[t].summary),l.message(` ${ie[t].next}`),e)return!1;if(t==="not-installed"){let n=await Ii({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Xt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(h.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Ei();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=dt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Ii({message:"Run `claude login` now to sign in?",initialValue:!0});if(Xt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(h.dim("Launching `claude login`\u2026"));let r=Ri();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Sd(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function vd(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Sd(e)){process.stdout.write(Qt(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=_d[o]??h.cyan,a=Pd(o,i);process.stdout.write(s(xd)+" "+h.bold(o)+h.dim("(")+a+h.dim(")")+`
385
- `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(h.dim(h.italic(" "+J(r,200)))+`
386
- `)}}var xd="\u23FA",Oi="\u23BF",_d={Read:h.blue,Glob:h.cyan,Grep:h.cyan,Edit:h.yellow,Write:h.magenta,Bash:h.green,WebFetch:h.magenta,WebSearch:h.magenta};function Cd(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=Ed(s);if(n){process.stdout.write(h.red(` ${Oi} Error`)+`
387
- `),a&&process.stdout.write(Ad(J(a,500)," ",h.red)+`
388
- `);return}let c=Rd(i,a,o?.input);c&&process.stdout.write(h.dim(` ${Oi} `)+c+`
389
- `)}function Ed(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 Rd(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
378
+ `);return}await q({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as nd,readdirSync as rd,unlinkSync as od}from"fs";import{join as Ti}from"path";import{isCancel as id,select as sd}from"@clack/prompts";async function ge(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 ad(),n===null)return;let r=n,o=j();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!O(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{bi(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),nr(r),tn(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"){nr(r),tn(process.cwd());let $=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${$}.`);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}nr(r),tn(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: ${Ti(k,"inbox")}`))}function nr(e){let t=ae(process.cwd());if(nd(t)){for(let n of rd(t))if(n.endsWith(`-${e}.md`))try{od(Ti(t,n))}catch{}}}async function ad(){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 sd({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:ze(r)}))});return id(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import on from"picocolors";async function rr(e={}){let t=process.cwd();if(!e.json&&!O(t))return;let n=Ee(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:ae(t),actions:n})+`
379
+ `);return}if(n.length===0){l.info(on.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(`${on.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(ze(r));l.message(""),l.message(`Apply one: ${on.bold(f("ack <id>"))} \xB7 Interactive picker: ${on.bold(f("ack"))} (no id)`)}import{readFileSync as yd}from"fs";import{join as wd,relative as kd}from"path";import{confirm as Di,isCancel as an,multiselect as bd,note as Mi,select as $d}from"@clack/prompts";import h from"picocolors";import{query as Sd}from"@anthropic-ai/claude-agent-sdk";import{existsSync as cd,readdirSync as ld}from"fs";import{homedir as ud}from"os";import{join as dd}from"path";import{execSync as or}from"child_process";function yt(){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":pd()?fd()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function pd(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return or(e,{stdio:"ignore"}),!0}catch{return!1}}function fd(){let e=dd(ud(),".claude");if(!cd(e))return!1;try{return ld(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Oi(){try{return or("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Li(){try{return or("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 Ni}from"marked";import{markedTerminal as md}from"marked-terminal";import ir from"picocolors";var ji=!1;function gd(){ji||(Ni.use(md({reflowText:!1,width:100})),ji=!0)}function sn(e){if(!e)return e;gd();try{let t=Ni.parse(e);return typeof t=="string"?hd(t):e}catch{return e}}function hd(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>ir.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>ir.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+ir.italic(r))}async function ar(e={}){let t=process.cwd();if(!O(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 Rd(e.yes)){process.exitCode=1;return}if(e.yes)await q({embedded:!0});else{let u=await $d({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(an(u)){l.info("Cancelled.");return}u==="sync"?await q({embedded:!0}):u==="pull"&&await Re({embedded:!0})}let r=Ee(t);if(r.length===0){l.info(h.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 bd({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(g=>({value:g.id,label:ze(g)})),initialValues:d,required:!1});if(an(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(A=>A.id===d);if(!p)continue;vd({index:u+1,total:o.length,entry:p});let m=wd(ae(t),p.filename),g;try{g=yd(m,"utf-8")}catch(A){l.error(` Could not read ${p.filename}: ${A.message}`),a++;continue}let $=Date.now(),w=await Ed({cwd:t,entry:p,actionContent:g,model:e.model}),C=Fi(Date.now()-$);if(w.kind==="applied")try{await ge(String(d),{silent:!0}),i++,l.message("");let A=w.summary?`
380
+ `+h.dim(" "+w.summary):"";l.message(` ${h.green("\u2713")} id ${d} ${h.dim("\u2014 applied in "+C)}${A}`)}catch(A){l.warn(` Applied but ack failed: ${A.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(w.kind==="declined")try{await ge(String(d),{silent:!0,failed:!0,reason:w.reason}),s++,l.message(""),l.message(` ${h.yellow("\u2298")} id ${d} ${h.dim("\u2014 declined: "+X(w.reason,100))}`)}catch(A){l.warn(` Could not ack decline: ${A.message}. Run \`seoagent ack ${d} --failed --reason "${w.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${h.red("\u2717")} id ${d} ${h.dim("\u2014 agent did not converge after "+C)}`)}_d({applied:i,declined:s,failed:a,total:o.length,elapsed:Fi(Date.now()-c)})}function vd(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=xd[i]??h.dim,a=[h.bold(`[${t}/${n}]`),h.dim("\xB7"),h.bold(`id ${r.id}`),h.dim("\xB7"),h.cyan(o),s(i)].join(" ");Mi(r.title,a)}var xd={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function _d(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?h.green(`\u2713 ${t}/${o} applied`):h.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=h.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=h.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Mi(`${a}
381
+ ${h.dim("elapsed: "+i)}`,h.bold("Done"))}function Fi(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 Cd(e){if(typeof e!="string"||!e)return null;let t=e.split(`
382
+ `);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 Ed(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Fd(n,r);try{let s=Sd({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)Pd(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Od(d,a)}else if(c.type==="result"){if(process.stdout.write(`
383
+ `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=Cd(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(`
384
+ `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Rd(e){let t=yt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(h.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 Di({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(an(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(h.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Oi();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=yt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Di({message:"Run `claude login` now to sign in?",initialValue:!0});if(an(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(h.dim("Launching `claude login`\u2026"));let r=Li();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Ad(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Pd(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Ad(e)){process.stdout.write(sn(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=Td[o]??h.cyan,a=Dd(o,i);process.stdout.write(s(Id)+" "+h.bold(o)+h.dim("(")+a+h.dim(")")+`
385
+ `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(h.dim(h.italic(" "+X(r,200)))+`
386
+ `)}}var Id="\u23FA",Ui="\u23BF",Td={Read:h.blue,Glob:h.cyan,Grep:h.cyan,Edit:h.yellow,Write:h.magenta,Bash:h.green,WebFetch:h.magenta,WebSearch:h.magenta};function Od(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=Ld(s);if(n){process.stdout.write(h.red(` ${Ui} Error`)+`
387
+ `),a&&process.stdout.write(Nd(X(a,500)," ",h.red)+`
388
+ `);return}let c=jd(i,a,o?.input);c&&process.stdout.write(h.dim(` ${Ui} `)+c+`
389
+ `)}function Ld(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 jd(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
390
390
  `).filter(Boolean).length;return h.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
391
391
  `).filter(o=>o.trim().length>0).length;return h.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
392
392
  `)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return h.dim(r);let o=t.split(`
393
- `).filter(i=>i.trim()).length;return h.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return h.dim(r?`${o} ${Zn(String(r))}`:o)}case"Bash":{let r=t.split(`
394
- `),o=r.slice(0,5).map(u=>J(u.trimEnd(),100)),i=r.length-5,s=o.join(`
393
+ `).filter(i=>i.trim()).length;return h.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return h.dim(r?`${o} ${sr(String(r))}`:o)}case"Bash":{let r=t.split(`
394
+ `),o=r.slice(0,5).map(u=>X(u.trimEnd(),100)),i=r.length-5,s=o.join(`
395
395
  `)+(i>0?`
396
396
  \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...c]=s.split(`
397
397
  `);return c.length===0?h.dim(a):h.dim(a)+`
398
398
  `+h.dim(c.map(u=>" "+u).join(`
399
- `))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${J(t.replace(/\s+/g," "),80)}`);default:return""}}function Ad(e,t,n){return e.split(`
399
+ `))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${X(t.replace(/\s+/g," "),80)}`);default:return""}}function Nd(e,t,n){return e.split(`
400
400
  `).map(r=>n(t+r)).join(`
401
- `)}function Pd(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(J(Zn(String(n.file_path??"")),80));case"Bash":return h.dim(J(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${Zn(String(n.path))}`:"";return h.dim(J(r+o,80))}case"Glob":return h.dim(J(String(n.pattern??""),80));case"WebFetch":return h.dim(J(String(n.url??""),80));case"WebSearch":return h.dim(J(String(n.query??""),80));default:return""}}function Zn(e){if(!e)return e;let t=process.cwd(),n=pd(t,e);return n.startsWith("..")?e:n||e}function J(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Id(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
401
+ `)}function Dd(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(X(sr(String(n.file_path??"")),80));case"Bash":return h.dim(X(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${sr(String(n.path))}`:"";return h.dim(X(r+o,80))}case"Glob":return h.dim(X(String(n.pattern??""),80));case"WebFetch":return h.dim(X(String(n.url??""),80));case"WebSearch":return h.dim(X(String(n.query??""),80));default:return""}}function sr(e){if(!e)return e;let t=process.cwd(),n=kd(t,e);return n.startsWith("..")?e:n||e}function X(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Fd(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
402
402
 
403
403
  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.
404
404
 
@@ -418,19 +418,19 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
418
418
  \`\`\`
419
419
  ${t}
420
420
  \`\`\`
421
- `}import{spinner as Td}from"@clack/prompts";import v from"picocolors";var Od=new Set(["on","off","status"]);async function pt(e,t={}){let n=(e||"").toLowerCase();if(!Od.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=U();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||R.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Td():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){b(a,"error",`Network error: ${g.message}`,v.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 $=C(process.cwd())?.domain??"",w=`${R.PRICING}?ref=cli${$?`&domain=${encodeURIComponent($)}`:""}`;b(a,"warn","CLI autopilot is a paid feature.",v.yellow("Autopilot is a paid feature.")),l.message(Ld(w)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){b(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,v.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:m}=d.autopilot;if(n==="on"){a?.stop(v.green("Autopilot enabled.")),l.message(tr({enabled:!0,deliveryMode:m,action:n}));return}if(n==="off"){a?.stop(v.dim("Autopilot disabled.")),l.message(tr({enabled:!1,deliveryMode:m,action:n}));return}a?.stop(v.dim("Status:")),l.message(tr({enabled:p,deliveryMode:m,action:n}))}function tr(e){let n=s=>v.dim(s.padEnd(11)),r=e.enabled?`${v.bold(v.green("\u25CF ON"))} ${v.dim("(queueing fixes for your coding agent)")}`:`${v.dim("\u25CB OFF")} ${v.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${v.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${v.dim("Apply queued fixes:")} ${v.cyan(f("sync"))}`}),o.push({content:`${v.dim("Turn off any time:")} ${v.cyan(f("autopilot off"))}`})):(o.push({content:`${v.dim("Enable (paid):")} ${v.cyan(f("autopilot on"))}`}),o.push({content:v.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.dim("autopilot")}`;return j(o,{width:78,title:i})}function Ld(e){let t=[{content:v.bold(v.yellow("Autopilot is a paid feature."))},{sep:!0},{content:v.dim("SEOAgent continuously audits your site and queues fixes for")},{content:v.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:v.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${v.dim("Upgrade:")} ${v.cyan(e)}`}],n=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.dim("autopilot")}`;return j(t,{width:78,title:n})}import{mkdirSync as qd,writeFileSync as Yd}from"fs";import{join as nr}from"path";import{readdirSync as jd,readFileSync as Nd,statSync as ji}from"fs";import{join as Dd}from"path";var Fd=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Ud=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"]),Md=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Bd=5e3,Gd=512*1024;function Mi(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Ni(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&&Ud.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Di=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Fi=/\]\(\s*([^)\s]+)/g;function Wd(e,t){if(!e)return[];let n=Mi(t),r=[],o;for(Di.lastIndex=0;(o=Di.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=Ni(i,n);s&&r.push(s)}for(Fi.lastIndex=0;(o=Fi.exec(e))!==null;){let i=Ni(o[1],n);i&&r.push(i)}return r}function Hd(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 Bi(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(`
422
- `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Mi(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(`
421
+ `}import{spinner as Ud}from"@clack/prompts";import S from"picocolors";var Md=new Set(["on","off","status"]);async function wt(e,t={}){let n=(e||"").toLowerCase();if(!Md.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=j();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?Ud():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){b(a,"error",`Network error: ${g.message}`,S.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=x(process.cwd()),$=ee("cli-autopilot",g?.domain);b(a,"warn","CLI autopilot is a paid feature.",S.yellow("Autopilot is a paid feature.")),l.message(Bd($)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){b(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,S.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:m}=d.autopilot;if(n==="on"){a?.stop(S.green("Autopilot enabled.")),l.message(cr({enabled:!0,deliveryMode:m,action:n}));return}if(n==="off"){a?.stop(S.dim("Autopilot disabled.")),l.message(cr({enabled:!1,deliveryMode:m,action:n}));return}a?.stop(S.dim("Status:")),l.message(cr({enabled:p,deliveryMode:m,action:n}))}function cr(e){let n=s=>S.dim(s.padEnd(11)),r=e.enabled?`${S.bold(S.green("\u25CF ON"))} ${S.dim("(queueing fixes for your coding agent)")}`:`${S.dim("\u25CB OFF")} ${S.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${S.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${S.dim("Apply queued fixes:")} ${S.cyan(f("sync"))}`}),o.push({content:`${S.dim("Turn off any time:")} ${S.cyan(f("autopilot off"))}`})):(o.push({content:`${S.dim("Enable (paid):")} ${S.cyan(f("autopilot on"))}`}),o.push({content:S.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${S.bold(S.cyan("SEOAgent"))} ${S.dim("\xB7")} ${S.dim("autopilot")}`;return N(o,{width:78,title:i})}function Bd(e){let t=[{content:S.bold(S.yellow("Autopilot is a paid feature."))},{sep:!0},{content:S.dim("SEOAgent continuously audits your site and queues fixes for")},{content:S.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:S.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${S.dim("Upgrade:")} ${S.cyan(e)}`}],n=`${S.bold(S.cyan("SEOAgent"))} ${S.dim("\xB7")} ${S.dim("autopilot")}`;return N(t,{width:78,title:n})}import{mkdirSync as Zd,writeFileSync as ep}from"fs";import{join as lr}from"path";import{readdirSync as Gd,readFileSync as Wd,statSync as Bi}from"fs";import{join as Hd}from"path";var Kd=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),qd=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"]),Yd=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),zd=5e3,Vd=512*1024;function qi(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Gi(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&&qd.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Wi=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Hi=/\]\(\s*([^)\s]+)/g;function Jd(e,t){if(!e)return[];let n=qi(t),r=[],o;for(Wi.lastIndex=0;(o=Wi.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=Gi(i,n);s&&r.push(s)}for(Hi.lastIndex=0;(o=Hi.exec(e))!==null;){let i=Gi(o[1],n);i&&r.push(i)}return r}function Qd(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 Yi(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(`
422
+ `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${qi(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(`
423
423
  `),i=e.orphans.length===0?`## Orphan pages
424
424
 
425
- 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=>`| ${Ui(a.url)} | \u2014 |`)].join(`
426
- `),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=>`| ${Ui(a.url)} | ${a.inbound} |`)].join(`
425
+ 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=>`| ${Ki(a.url)} | \u2014 |`)].join(`
426
+ `),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=>`| ${Ki(a.url)} | ${a.inbound} |`)].join(`
427
427
  `);return[r,"",o,"",i,s,""].join(`
428
- `)}function Ui(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Kd(e){let t=0;function*n(r){let o;try{o=jd(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Bd)return;if(i.name.startsWith("."))continue;let s=Dd(r,i.name);if(i.isDirectory()){if(Md.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(!Fd.has(c))continue;t++,yield s}}}yield*n(e)}function Gi(e,t){let{pages:n}=Z(e,t),r=[],o=0,i=!1;try{i=ji(e).isDirectory()}catch{i=!1}if(i)for(let s of Kd(e)){let a;try{if(ji(s).size>Gd)continue;a=Nd(s,"utf-8")}catch{continue}o++;for(let c of Wd(a,t))r.push(c)}return Hd(n,r,o)}function ft(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Gi(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
429
- `);return}let i=nr(t,k);qd(i,{recursive:!0});let s=nr(i,"internal-links.md");if(Yd(s,Bi(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 ${nr(k,"internal-links.md")}`)}import{existsSync as zd,mkdirSync as Vd,rmSync as Jd,writeFileSync as Wi}from"fs";import{dirname as Qd,join as Zt}from"path";import ee from"picocolors";async function rr(e,t={}){if(e!=="track"&&e!=="reconcile"){l.message(`Usage:
428
+ `)}function Ki(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Xd(e){let t=0;function*n(r){let o;try{o=Gd(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=zd)return;if(i.name.startsWith("."))continue;let s=Hd(r,i.name);if(i.isDirectory()){if(Yd.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(!Kd.has(c))continue;t++,yield s}}}yield*n(e)}function zi(e,t){let{pages:n}=ne(e,t),r=[],o=0,i=!1;try{i=Bi(e).isDirectory()}catch{i=!1}if(i)for(let s of Xd(e)){let a;try{if(Bi(s).size>Vd)continue;a=Wd(s,"utf-8")}catch{continue}o++;for(let c of Jd(a,t))r.push(c)}return Qd(n,r,o)}function kt(e={}){let t=process.cwd(),n=O(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=zi(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
429
+ `);return}let i=lr(t,k);Zd(i,{recursive:!0});let s=lr(i,"internal-links.md");if(ep(s,Yi(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 ${lr(k,"internal-links.md")}`)}import{existsSync as tp,mkdirSync as np,rmSync as rp,writeFileSync as Vi}from"fs";import{dirname as op,join as cn}from"path";import re from"picocolors";async function ur(e,t={}){if(e!=="track"&&e!=="reconcile"){l.message(`Usage:
430
430
  ${f("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft]
431
- ${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=C(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await Xd(n,r,t);return}let o=t.slug??(t.file?t.file:""),i=Un(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=lt(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()||Jo(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=ut({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=Zt(n,k,"content");Vd(d,{recursive:!0});let p=Zt(d,`${i}.md`),m=zd(p);Wi(p,u,"utf-8"),l.success(`${m?"Updated":"Tracked"} ${ee.bold(i)}${s?` \u2192 ${ee.cyan(s)}`:""} in .seoagent/content/.`);try{await K({silent:!0,pushOnly:!0})}catch{}l.message(ee.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}async function Xd(e,t,n){let r=Zt(e,k,"content"),o=Nn(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(Qd(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=>jn(e,c)),a=Dn(s,o,Fn(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=lt(c.slug,{domain:t.domain,blogPath:t.blog_path}),d=ut({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()});Wi(Zt(r,`${c.slug}.md`),d,"utf-8"),l.message(`${ee.green("+")} tracked ${ee.bold(c.slug)}${u?ee.dim(` \u2192 ${u}`):""}`)}for(let c of a.stale)n.prune?(Jd(c.file,{force:!0}),l.message(`${ee.red("-")} pruned stale pointer ${ee.bold(c.slug)} (source ${c.repo_path} is gone)`)):l.message(`${ee.yellow("!")} stale pointer ${ee.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 K({silent:!0,pushOnly:!0})}catch{}}import{existsSync as Zd,readFileSync as ep}from"fs";import{join as tp}from"path";import or from"picocolors";function np(e){let t=[];return 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.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 rp(e){let t=tp(e,k,Et);if(!Zd(t))return null;try{let n=JSON.parse(ep(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function ir(e={}){let t=process.cwd(),n=C(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
432
- `);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=le(t),o=np({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:rp(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
433
- `);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(or.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${or.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${or.dim("\u2192 "+s.fix)}`)}import te from"picocolors";import{existsSync as Ke,mkdirSync as en,readdirSync as op,readFileSync as ip,statSync as vk,writeFileSync as Hi}from"fs";import{dirname as sp,join as me,relative as ap,resolve as cp}from"path";var qe="okf";function tn(e){return me(e,k,qe)}var lp=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function sr(e){let t=[];for(let n of op(e,{withFileTypes:!0})){let r=me(e,n.name);n.isDirectory()?t.push(...sr(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function up(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 Ki(e){let t=[],n=[];if(!Ke(e))return{ok:!1,fileCount:0,errors:[{file:qe,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=sr(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:qe,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ke(me(e,"index.md"))||n.push({file:qe,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=ap(e,i),a;try{a=ce(ip(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!==""&&!lp.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 up(a.body)){let m=p.split("#")[0];if(!m)continue;let g=cp(sp(i),m);Ke(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 nn(e){let t=tn(e);if(!Ke(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:sr(t).length}}catch{return{exists:!0,fileCount:0}}}function qi(e,t){let n=tn(e);en(n,{recursive:!0}),en(me(n,"concepts"),{recursive:!0}),en(me(n,"faqs"),{recursive:!0}),en(me(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=me(n,"index.md");Ke(i)||(Hi(i,`---
431
+ ${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=x(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await ip(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=gt(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()||ni(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=ht({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=cn(n,k,"content");np(d,{recursive:!0});let p=cn(d,`${i}.md`),m=tp(p);Vi(p,u,"utf-8"),l.success(`${m?"Updated":"Tracked"} ${re.bold(i)}${s?` \u2192 ${re.cyan(s)}`:""} in .seoagent/content/.`);try{await q({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 ip(e,t,n){let r=cn(e,k,"content"),o=Wn(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(op(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=>Gn(e,c)),a=Hn(s,o,Kn(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=gt(c.slug,{domain:t.domain,blogPath:t.blog_path}),d=ht({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()});Vi(cn(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?(rp(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 q({silent:!0,pushOnly:!0})}catch{}}import{existsSync as sp,readFileSync as ap}from"fs";import{join as cp}from"path";import dr from"picocolors";function lp(e){let t=[];return 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.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 up(e){let t=cp(e,k,Ot);if(!sp(t))return null;try{let n=JSON.parse(ap(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function pr(e={}){let t=process.cwd(),n=x(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
432
+ `);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=pe(t),o=lp({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:up(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
433
+ `);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(dr.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${dr.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${dr.dim("\u2192 "+s.fix)}`)}import oe from"picocolors";import{existsSync as Ve,mkdirSync as ln,readdirSync as dp,readFileSync as pp,statSync as Nk,writeFileSync as Ji}from"fs";import{dirname as fp,join as he,relative as mp,resolve as gp}from"path";var Je="okf";function un(e){return he(e,k,Je)}var hp=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function fr(e){let t=[];for(let n of dp(e,{withFileTypes:!0})){let r=he(e,n.name);n.isDirectory()?t.push(...fr(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function yp(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 Qi(e){let t=[],n=[];if(!Ve(e))return{ok:!1,fileCount:0,errors:[{file:Je,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=fr(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Je,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ve(he(e,"index.md"))||n.push({file:Je,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=mp(e,i),a;try{a=de(pp(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!==""&&!hp.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 yp(a.body)){let m=p.split("#")[0];if(!m)continue;let g=gp(fp(i),m);Ve(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 dn(e){let t=un(e);if(!Ve(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:fr(t).length}}catch{return{exists:!0,fileCount:0}}}function Xi(e,t){let n=un(e);ln(n,{recursive:!0}),ln(he(n,"concepts"),{recursive:!0}),ln(he(n,"faqs"),{recursive:!0}),ln(he(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=he(n,"index.md");Ve(i)||(Ji(i,`---
434
434
  type: Organization
435
435
  title: ${o}
436
436
  description: Knowledge bundle describing ${o} for AI agents and answer engines.
@@ -457,7 +457,7 @@ _Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`
457
457
  ## Published articles
458
458
 
459
459
  - _Link article files here, e.g._ \`articles/guide-to-x.md\`
460
- `,"utf-8"),r.push("index.md"));let s=me(n,"log.md");return Ke(s)||(Hi(s,`---
460
+ `,"utf-8"),r.push("index.md"));let s=he(n,"log.md");return Ve(s)||(Ji(s,`---
461
461
  type: Log
462
462
  title: Change log
463
463
  description: Chronological history of changes to this OKF bundle.
@@ -466,15 +466,15 @@ description: Chronological history of changes to this OKF bundle.
466
466
  # Change log
467
467
 
468
468
  - Bundle scaffolded.
469
- `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var ar=`${k}/${qe}`;function mt(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}=qi(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=Ki(tn(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
470
- `);return}for(let c of a.errors)l.message(`${te.red("\u2717")} ${te.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${te.yellow("!")} ${te.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=nn(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
471
- `);return}l.message(j([{content:te.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?te.green(ar+"/"):te.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?te.dim("Run `seoagent okf validate` to check it."):te.dim("Run `seoagent okf scaffold` to start one.")}],{title:te.cyan("OKF")}))}import W from"picocolors";async function cr(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?Z(t,r).pages.map(s=>s.url||s.route):[],i=await So({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
472
- `),i.ok||(process.exitCode=1);return}dp(i),i.ok||(process.exitCode=1)}function dp(e){let t=e.fetched?e.status===200?W.green(`200 \xB7 ${e.urls.length} URL${e.urls.length===1?"":"s"}`):W.red(String(e.status)):W.red("unreachable");l.message(j([{content:W.bold("Sitemap check")},{sep:!0},{content:`URL: ${W.dim(e.sitemapUrl)}`},{content:`Status: ${t}`},...e.fetched&&e.status===200?[{content:`Private leaked: ${e.privateUrls.length===0?W.green("none"):W.yellow(String(e.privateUrls.length))}`},{content:`Missing public: ${e.missing.length===0?W.green("none"):W.yellow(String(e.missing.length))}`},{content:`<lastmod>: ${e.hasLastmod?W.green("present"):W.dim("absent")}`}]:[]],{title:e.ok?W.cyan("Sitemap"):W.red("Sitemap")}));for(let n of e.issues){let r=n.level==="error"?W.red("\u2717"):n.level==="warning"?W.yellow("!"):W.dim("\xB7");l.message(`${r} ${n.message}`)}e.ok?l.success("Sitemap looks healthy."):l.error("Sitemap has errors (see above).")}import{mkdirSync as Ip,writeFileSync as Tp}from"fs";import{join as is}from"path";import Ee from"picocolors";var ur=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi,Yi=30;function rn(e){let t=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(e);return t?t[1]:e}function gt(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 Ce(e,t){let n=new RegExp(`\\b${t}\\s*=\\s*"([^"]*)"`,"i").exec(e);if(n)return gt(n[1]).trim();let r=new RegExp(`\\b${t}\\s*=\\s*'([^']*)'`,"i").exec(e);if(r)return gt(r[1]).trim();let o=new RegExp(`\\b${t}\\s*=\\s*([^\\s>]+)`,"i").exec(e);return o?gt(o[1]).trim():null}function pp(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);return t&&gt(t[1].replace(/\s+/g," ")).trim()||null}function fp(e){let t=e.match(/<meta\b[^>]*>/gi)??[];for(let n of t){let r=Ce(n,"name");if(r&&r.toLowerCase()==="description"){let o=Ce(n,"content");return o&&o.trim()?o.trim():null}}return null}function mp(e){let t=rn(e),n=[],r=/<h1\b[^>]*>([\s\S]*?)<\/h1>/gi,o;for(;(o=r.exec(t))!==null;){let i=gt(o[1].replace(/<[^>]+>/g," ").replace(/\s+/g," ")).trim();i&&n.push(i)}return n}function gp(e){let t=e.match(/<link\b[^>]*>/gi)??[];for(let n of t){let r=Ce(n,"rel");if(r&&r.toLowerCase().split(/\s+/).includes("canonical")){let o=Ce(n,"href");return o&&o.trim()?o.trim():null}}return null}function hp(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:lr(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 lr(e,t=[]){if(Array.isArray(e)){for(let n of e)lr(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"])&&lr(n["@graph"],t)}return t}function zi(e,t){let n={},r=e.match(/<meta\b[^>]*>/gi)??[];for(let o of r){let i=(Ce(o,"property")||Ce(o,"name")||"").toLowerCase();if(i.startsWith(t)){let s=Ce(o,"content");s!==null&&(n[i.slice(t.length)]=s)}}return n}function yp(e){return zi(e,"og:")}function wp(e){return zi(e,"twitter:")}function Vi(e){return(rn(e).replace(ur," ").match(/<a\b[^>]*\bhref\s*=/gi)??[]).length}function Ji(e){let t=rn(e).replace(ur," ").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 kp=/\b(loading|please wait|just a moment|redirecting)\b[\s.…]*/i;function bp(e){let t=Ji(e),n=Vi(e),r=rn(e).replace(ur," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),o=t<Yi&&kp.test(r),i=t<Yi&&n===0;return o||i}function $p(e,t,n=200){let r=hp(t),o=Array.from(new Set(r.flatMap(s=>s.types))),i=gp(t);return{url:e,status:n,fetched:!0,title:pp(t),metaDescription:fp(t),h1s:mp(t),canonical:i,canonicalServerRendered:i===null?null:!0,jsonLd:r,jsonLdTypes:o,openGraph:yp(t),twitter:wp(t),wordCount:Ji(t),clientRenderedShell:bp(t),bodyLinkCount:Vi(t)}}async function Qi(e,t){let n={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};try{let r=await O(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{...n,status:r.status};let o=await r.text();return $p(e,o,r.status)}catch{return n}}function Sp(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}}async function Xi(e,t){let r=`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/robots.txt`,o={fetched:!1,status:null,raw:"",groups:[],sitemaps:[]};try{let i=await O(r,{headers:{"user-agent":"SEOAgent-CLI/robots-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!i.ok)return{...o,status:i.status};let s=await i.text();return/^\s*</.test(s)?{...o,status:i.status,raw:""}:{fetched:!0,status:i.status,raw:s,...Sp(s)}}catch{return o}}var vp=/\/(blog|posts?|articles?|news)\//i;function xp(e){return e.filter(t=>vp.test(t)).length}async function Zi(e,t){let r=`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`,o={fetched:!1,status:null,urls:[],count:0,blogUrlCount:0};try{let i=await O(r,{headers:{"user-agent":"SEOAgent-CLI/sitemap-facts"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!i.ok)return{...o,status:i.status};let s=await i.text();if(!/<urlset|<sitemapindex/i.test(s))return{...o,status:i.status};let a=Xe(s);return{fetched:!0,status:i.status,urls:a,count:a.length,blogUrlCount:xp(a)}}catch{return o}}function _p(e){return Object.keys(e.twitter).length>0}function Cp(e){return Object.keys(e.openGraph).length>0}function Ep(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 Cp(e);case"twitter_card":return _p(e);case"json_ld":return e.jsonLdTypes.length>0}}var Rp=["title","meta_description","canonical","open_graph","twitter_card","json_ld"];function Ap(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 Pp(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=Ep(e,t);return{kind:t,present:n,safeToRecommendAdding:!n,reason:n?Ap(e,t):`${t} genuinely absent in the server HTML \u2014 safe to recommend adding`}}function es(e){return Rp.map(t=>Pp(e,t))}var ts={title:"<title>",meta_description:"meta description",canonical:"canonical",open_graph:"Open Graph tags",twitter_card:"Twitter card",json_ld:"JSON-LD schema"};function ns(e){return e===null||e===""?"_(none)_":e}function rs(e){let{domain:t,capturedAt:n,pages:r,robots:o,sitemap:i}=e,s=[];if(s.push("---"),s.push(`domain: ${t}`),s.push(`captured_at: ${n}`),s.push(`pages_crawled: ${r.length}`),s.push("note: >-"),s.push(" Live-crawl evidence base. Every fact here was fetched from the live site."),s.push(" The audit must ground all Confirmed claims on THIS file, never on repo"),s.push(" source or priors. Do NOT recommend adding schema / robots rules /"),s.push(" canonical tags that already appear below."),s.push("---"),s.push(""),s.push(`# Live-Crawl Evidence \u2014 ${t}`),s.push(""),s.push("## robots.txt (Confirmed)"),!o.fetched)s.push(`- Not fetched (HTTP ${o.status??"network error"}). Do NOT assert any robots.txt rule \u2014 it is unverified (Hypothesis).`);else{let a=o.groups.flatMap(c=>c.disallow).filter(Boolean);s.push(`- Fetched: HTTP ${o.status}`),s.push(`- Disallow rules present: ${a.length===0?"**none** (do NOT claim any path is blocked)":a.map(c=>`\`${c}\``).join(", ")}`),s.push(`- Sitemap declarations: ${o.sitemaps.length===0?"_(none)_":o.sitemaps.join(", ")}`),s.push("- Raw contents:"),s.push("```"),s.push(o.raw.trim()),s.push("```")}s.push(""),s.push("## sitemap.xml (Confirmed)"),i.fetched?(s.push(`- **${i.count} URL${i.count===1?"":"s"}**, ${i.blogUrlCount} blog/article post${i.blogUrlCount===1?"":"s"}`),i.blogUrlCount===0&&s.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).")):s.push(`- Not fetched (HTTP ${i.status??"network error"}). Do NOT assert a sitemap URL count.`),s.push("");for(let a of r){if(s.push(`## ${a.url}`),!a.fetched){s.push(`- Not fetched (HTTP ${a.status??"network error"}). No claims about this page are Confirmed.`),s.push("");continue}s.push(`- HTTP ${a.status} \xB7 ${a.wordCount} body words`),s.push(`- **title:** ${ns(a.title)}`),s.push(`- **meta description:** ${ns(a.metaDescription)}`),s.push(`- **h1(s):** ${a.h1s.length===0?"_(none \u2014 missing H1, Confirmed)_":a.h1s.map(p=>`\`${p}\``).join(" | ")}${a.h1s.length>1?` **(\u26A0 ${a.h1s.length} H1s \u2014 conflicting)**`:""}`),s.push(`- **canonical:** ${a.canonical===null?"_(none in server HTML)_":`\`${a.canonical}\` (${a.canonicalServerRendered?"server-rendered":"client-rendered"})`}`),s.push(`- **JSON-LD @types present:** ${a.jsonLdTypes.length===0?"_(none \u2014 safe to recommend adding schema)_":a.jsonLdTypes.map(p=>`\`${p}\``).join(", ")+" \u2014 **already present; do NOT recommend adding these**"}`);let c=Object.keys(a.openGraph),u=Object.keys(a.twitter);s.push(`- **Open Graph:** ${c.length===0?"_(none)_":c.map(p=>`og:${p}`).join(", ")}`),s.push(`- **Twitter:** ${u.length===0?"_(none)_":u.map(p=>`twitter:${p}`).join(", ")}`),a.clientRenderedShell&&s.push(`- **\u26A0 client-rendered shell:** server HTML has ${a.wordCount} words and ${a.bodyLinkCount} in-body links \u2014 crawlers can't see the content (Confirmed). Any on-page data (counts, listings) is Likely/Hypothesis, not Confirmed.`);let d=es(a).filter(p=>p.present).map(p=>ts[p.kind]);d.length>0&&s.push(`- **Already present (do NOT recommend adding):** ${d.join(", ")} \u2014 verified in the server \`<head>\`.`),s.push("")}return s.join(`
473
- `)}function os(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 Op=25;async function dr(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 I know which site to crawl for evidence."),process.exitCode=1;return}let o=Math.min(Math.max(1,e.max??10),Op),i=Lp(t,r,o);l.info(`Capturing live-crawl evidence for ${r} (${i.length} page${i.length===1?"":"s"} + robots + sitemap)\u2026`);let[s,a,c]=await Promise.all([Promise.all(i.map(m=>Qi(m))),Xi(r),Zi(r)]),u={domain:r,capturedAt:new Date().toISOString(),pages:s,robots:a,sitemap:c},d=is(t,k,"audit");Ip(d,{recursive:!0});let p=is(d,"evidence.md");if(Tp(p,rs(u),"utf-8"),e.json){process.stdout.write(JSON.stringify(u,null,2)+`
474
- `);return}jp(u,p)}function Lp(e,t,n){let r=`https://${t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/`,o=new Set([r]),i=[r];try{let{pages:s}=Z(e,t);for(let a of s){let c=a.url;if(!(!/^https?:\/\//.test(c)||o.has(c))&&(o.add(c),i.push(c),i.length>=n))break}}catch{}return i.slice(0,n)}function jp(e,t){let n=os(e);l.success(`Captured evidence for ${n.fetched}/${n.pages} page${n.pages===1?"":"s"} \u2192 ${Ee.dim(t)}`),l.message(` robots.txt: ${n.robotsFetched?Ee.green("fetched"):Ee.yellow("not reachable")} \xB7 sitemap: ${n.sitemapCount===null?Ee.yellow("not reachable"):Ee.green(`${n.sitemapCount} URLs`)}`),n.multiH1>0&&l.message(` ${Ee.yellow("!")} ${n.multiH1} page(s) have multiple/conflicting H1s`),n.shells>0&&l.message(` ${Ee.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{existsSync as Bp,mkdirSync as Gp,readFileSync as Wp,writeFileSync as Hp}from"fs";import{join as pr}from"path";import ht from"picocolors";var cs={minImpressionsToPreserve:50,onTopicRelevance:.34},Np=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 ls(e){return e.toLowerCase().replace(/https?:\/\/[^/]+/g," ").replace(/[^a-z0-9]+/g," ").split(" ").filter(t=>t.length>2&&!Np.has(t)&&!/^\d+$/.test(t))}function us(e){let t=new Set;for(let n of e)for(let r of ls(n))t.add(r);return t}function Dp(e,t){let n=ls(e);return n.length===0||t.size===0?0:n.filter(o=>t.has(o)).length/n.length}function Fp(e,t,n=cs){let r=Dp(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 ds(e,t,n=cs){return e.map(r=>Fp(r,t,n)).sort((r,o)=>o.row.impressions-r.row.impressions)}function ss(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 on(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 ps(e){let t=e.split(/\r?\n/).filter(p=>p.trim()!=="");if(t.length<2)return[];let n=ss(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=ss(t[p]),g=(m[0]??"").trim();if(!g)continue;let $=c>=0?m[c]??"":"",w=on($);d.push({key:g,kind:o,clicks:s>=0?on(m[s]??"")??0:0,impressions:a>=0?on(m[a]??"")??0:0,position:u>=0?on(m[u]??""):null,ctr:w===null?null:/%/.test($)?w/100:w})}return d}var as=["harvest","redirect","sunset"],Up={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 Mp(e){return e.filter(t=>t.disposition==="redirect"&&t.row.kind==="page").map(t=>({from:t.row.key,note:t.action}))}function fs(e){let{domain:t,directionSummary:n,decisions:r,generatedAt:o}=e,i=as.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(`
475
- `);for(let c of as){let u=r.filter(d=>d.disposition===c);if(u.length!==0){s.push(`## ${Up[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=Mp(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(`
476
- `)}function ms(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 fr(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=Ft(t),i=[r,n.site_type],s=e.direction??"";if(o){let w=o.business;for(let _ of[w.type,w.audience,w.industry,w.description,w.name])_&&i.push(_);for(let _ of o.writingInstructions)i.push(_);s||(s=[w.description,w.type,w.audience].filter(Boolean).join(" \xB7 "))}s||(s=`${n.site_type} at ${r}`);let a=us(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 w=e.csv.startsWith("/")?e.csv:pr(t,e.csv);if(!Bp(w)){l.error(`GSC CSV not found: ${w}`),process.exitCode=1;return}let _=ps(Wp(w,"utf-8"));c.push(..._),u=`${_.length} row(s) from ${e.csv}`}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>`."),l.message(ht.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=ds(c,a),p=new Date().toISOString(),m=pr(t,k,"strategy");Gp(m,{recursive:!0});let g=pr(m,"migration-plan.md");Hp(g,fs({domain:r,directionSummary:s,decisions:d,generatedAt:p}),"utf-8");let $=ms(d);if(e.json){process.stdout.write(JSON.stringify({domain:r,directionSummary:s,source:u,summary:$,decisions:d},null,2)+`
477
- `);return}l.success(`Migration plan written \u2192 ${ht.dim(g)} (${u})`),l.message(` ${ht.green(`${$.harvest} harvest`)} \xB7 ${ht.cyan(`${$.redirect} redirect`)} \xB7 ${ht.yellow(`${$.sunset} sunset`)} across ${$.total} legacy asset${$.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 _s,writeFileSync as Cs,readFileSync as ef,readdirSync as tf,existsSync as nf}from"fs";import{join as Es}from"path";import P from"picocolors";import{query as rf}from"@anthropic-ai/claude-agent-sdk";import{join as mr}from"path";var gr="citations",hr="scorecard.md",Kp="history",qp=6,Yp=1,zp=12,Vp=5,sn="Claude (web-grounded)";function an(e){return mr(e,k,gr)}function hs(e){return mr(an(e),hr)}function ys(e){return mr(an(e),Kp)}function ws(e){return`${e.replace(/[:.]/g,"-")}.json`}function ks(e){return typeof e!="number"||!Number.isFinite(e)?qp:Math.max(Yp,Math.min(zp,Math.floor(e)))}function cn(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>=Vp))break}return n}function yt(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function yr(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 bs(e,t){let{cited:n,total:r}=yt(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function $s(e,t){if(!t)return null;let{cited:n}=yt(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 Ss(e,t){let n=cn(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(`
469
+ `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var mr=`${k}/${Je}`;function bt(e,t={}){let n=process.cwd(),r=O(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=Xi(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${mr}/.`):(l.success(`Scaffolded ${mr}/ \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=Qi(un(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
470
+ `);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=dn(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
471
+ `);return}l.message(N([{content:oe.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?oe.green(mr+"/"):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 gr(e={}){let t=process.cwd(),n=O(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 To({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
472
+ `),i.ok||(process.exitCode=1);return}wp(i),i.ok||(process.exitCode=1)}function wp(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(N([{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 Fp,writeFileSync as Up}from"fs";import{join as ds}from"path";import Pe from"picocolors";var yr=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi,Zi=30;function pn(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 Ae(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 kp(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);return t&&$t(t[1].replace(/\s+/g," ")).trim()||null}function bp(e){let t=e.match(/<meta\b[^>]*>/gi)??[];for(let n of t){let r=Ae(n,"name");if(r&&r.toLowerCase()==="description"){let o=Ae(n,"content");return o&&o.trim()?o.trim():null}}return null}function $p(e){let t=pn(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 Sp(e){let t=e.match(/<link\b[^>]*>/gi)??[];for(let n of t){let r=Ae(n,"rel");if(r&&r.toLowerCase().split(/\s+/).includes("canonical")){let o=Ae(n,"href");return o&&o.trim()?o.trim():null}}return null}function vp(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:hr(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 hr(e,t=[]){if(Array.isArray(e)){for(let n of e)hr(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"])&&hr(n["@graph"],t)}return t}function es(e,t){let n={},r=e.match(/<meta\b[^>]*>/gi)??[];for(let o of r){let i=(Ae(o,"property")||Ae(o,"name")||"").toLowerCase();if(i.startsWith(t)){let s=Ae(o,"content");s!==null&&(n[i.slice(t.length)]=s)}}return n}function xp(e){return es(e,"og:")}function _p(e){return es(e,"twitter:")}function ts(e){return(pn(e).replace(yr," ").match(/<a\b[^>]*\bhref\s*=/gi)??[]).length}function ns(e){let t=pn(e).replace(yr," ").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 Cp=/\b(loading|please wait|just a moment|redirecting)\b[\s.…]*/i;function Ep(e){let t=ns(e),n=ts(e),r=pn(e).replace(yr," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(),o=t<Zi&&Cp.test(r),i=t<Zi&&n===0;return o||i}function Rp(e,t,n=200){let r=vp(t),o=Array.from(new Set(r.flatMap(s=>s.types))),i=Sp(t);return{url:e,status:n,fetched:!0,title:kp(t),metaDescription:bp(t),h1s:$p(t),canonical:i,canonicalServerRendered:i===null?null:!0,jsonLd:r,jsonLdTypes:o,openGraph:xp(t),twitter:_p(t),wordCount:ns(t),clientRenderedShell:Ep(t),bodyLinkCount:ts(t)}}async function rs(e,t){let n={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};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{...n,status:r.status};let o=await r.text();return Rp(e,o,r.status)}catch{return n}}function Ap(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}}async function os(e,t){let r=`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/robots.txt`,o={fetched:!1,status:null,raw:"",groups:[],sitemaps:[]};try{let i=await P(r,{headers:{"user-agent":"SEOAgent-CLI/robots-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!i.ok)return{...o,status:i.status};let s=await i.text();return/^\s*</.test(s)?{...o,status:i.status,raw:""}:{fetched:!0,status:i.status,raw:s,...Ap(s)}}catch{return o}}var Pp=/\/(blog|posts?|articles?|news)\//i;function Ip(e){return e.filter(t=>Pp.test(t)).length}async function is(e,t){let r=`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`,o={fetched:!1,status:null,urls:[],count:0,blogUrlCount:0};try{let i=await P(r,{headers:{"user-agent":"SEOAgent-CLI/sitemap-facts"}},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!i.ok)return{...o,status:i.status};let s=await i.text();if(!/<urlset|<sitemapindex/i.test(s))return{...o,status:i.status};let a=ot(s);return{fetched:!0,status:i.status,urls:a,count:a.length,blogUrlCount:Ip(a)}}catch{return o}}function Tp(e){return Object.keys(e.twitter).length>0}function Op(e){return Object.keys(e.openGraph).length>0}function Lp(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 Op(e);case"twitter_card":return Tp(e);case"json_ld":return e.jsonLdTypes.length>0}}var jp=["title","meta_description","canonical","open_graph","twitter_card","json_ld"];function Np(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 Dp(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=Lp(e,t);return{kind:t,present:n,safeToRecommendAdding:!n,reason:n?Np(e,t):`${t} genuinely absent in the server HTML \u2014 safe to recommend adding`}}function ss(e){return jp.map(t=>Dp(e,t))}var as={title:"<title>",meta_description:"meta description",canonical:"canonical",open_graph:"Open Graph tags",twitter_card:"Twitter card",json_ld:"JSON-LD schema"};function cs(e){return e===null||e===""?"_(none)_":e}function ls(e){let{domain:t,capturedAt:n,pages:r,robots:o,sitemap:i}=e,s=[];if(s.push("---"),s.push(`domain: ${t}`),s.push(`captured_at: ${n}`),s.push(`pages_crawled: ${r.length}`),s.push("note: >-"),s.push(" Live-crawl evidence base. Every fact here was fetched from the live site."),s.push(" The audit must ground all Confirmed claims on THIS file, never on repo"),s.push(" source or priors. Do NOT recommend adding schema / robots rules /"),s.push(" canonical tags that already appear below."),s.push("---"),s.push(""),s.push(`# Live-Crawl Evidence \u2014 ${t}`),s.push(""),s.push("## robots.txt (Confirmed)"),!o.fetched)s.push(`- Not fetched (HTTP ${o.status??"network error"}). Do NOT assert any robots.txt rule \u2014 it is unverified (Hypothesis).`);else{let a=o.groups.flatMap(c=>c.disallow).filter(Boolean);s.push(`- Fetched: HTTP ${o.status}`),s.push(`- Disallow rules present: ${a.length===0?"**none** (do NOT claim any path is blocked)":a.map(c=>`\`${c}\``).join(", ")}`),s.push(`- Sitemap declarations: ${o.sitemaps.length===0?"_(none)_":o.sitemaps.join(", ")}`),s.push("- Raw contents:"),s.push("```"),s.push(o.raw.trim()),s.push("```")}s.push(""),s.push("## sitemap.xml (Confirmed)"),i.fetched?(s.push(`- **${i.count} URL${i.count===1?"":"s"}**, ${i.blogUrlCount} blog/article post${i.blogUrlCount===1?"":"s"}`),i.blogUrlCount===0&&s.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).")):s.push(`- Not fetched (HTTP ${i.status??"network error"}). Do NOT assert a sitemap URL count.`),s.push("");for(let a of r){if(s.push(`## ${a.url}`),!a.fetched){s.push(`- Not fetched (HTTP ${a.status??"network error"}). No claims about this page are Confirmed.`),s.push("");continue}s.push(`- HTTP ${a.status} \xB7 ${a.wordCount} body words`),s.push(`- **title:** ${cs(a.title)}`),s.push(`- **meta description:** ${cs(a.metaDescription)}`),s.push(`- **h1(s):** ${a.h1s.length===0?"_(none \u2014 missing H1, Confirmed)_":a.h1s.map(p=>`\`${p}\``).join(" | ")}${a.h1s.length>1?` **(\u26A0 ${a.h1s.length} H1s \u2014 conflicting)**`:""}`),s.push(`- **canonical:** ${a.canonical===null?"_(none in server HTML)_":`\`${a.canonical}\` (${a.canonicalServerRendered?"server-rendered":"client-rendered"})`}`),s.push(`- **JSON-LD @types present:** ${a.jsonLdTypes.length===0?"_(none \u2014 safe to recommend adding schema)_":a.jsonLdTypes.map(p=>`\`${p}\``).join(", ")+" \u2014 **already present; do NOT recommend adding these**"}`);let c=Object.keys(a.openGraph),u=Object.keys(a.twitter);s.push(`- **Open Graph:** ${c.length===0?"_(none)_":c.map(p=>`og:${p}`).join(", ")}`),s.push(`- **Twitter:** ${u.length===0?"_(none)_":u.map(p=>`twitter:${p}`).join(", ")}`),a.clientRenderedShell&&s.push(`- **\u26A0 client-rendered shell:** server HTML has ${a.wordCount} words and ${a.bodyLinkCount} in-body links \u2014 crawlers can't see the content (Confirmed). Any on-page data (counts, listings) is Likely/Hypothesis, not Confirmed.`);let d=ss(a).filter(p=>p.present).map(p=>as[p.kind]);d.length>0&&s.push(`- **Already present (do NOT recommend adding):** ${d.join(", ")} \u2014 verified in the server \`<head>\`.`),s.push("")}return s.join(`
473
+ `)}function us(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 Mp=25;async function wr(e={}){let t=process.cwd(),n=O(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 I know which site to crawl for evidence."),process.exitCode=1;return}let o=Math.min(Math.max(1,e.max??10),Mp),i=Bp(t,r,o);l.info(`Capturing live-crawl evidence for ${r} (${i.length} page${i.length===1?"":"s"} + robots + sitemap)\u2026`);let[s,a,c]=await Promise.all([Promise.all(i.map(m=>rs(m))),os(r),is(r)]),u={domain:r,capturedAt:new Date().toISOString(),pages:s,robots:a,sitemap:c},d=ds(t,k,"audit");Fp(d,{recursive:!0});let p=ds(d,"evidence.md");if(Up(p,ls(u),"utf-8"),e.json){process.stdout.write(JSON.stringify(u,null,2)+`
474
+ `);return}Gp(u,p)}function Bp(e,t,n){let r=`https://${t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/`,o=new Set([r]),i=[r];try{let{pages:s}=ne(e,t);for(let a of s){let c=a.url;if(!(!/^https?:\/\//.test(c)||o.has(c))&&(o.add(c),i.push(c),i.length>=n))break}}catch{}return i.slice(0,n)}function Gp(e,t){let n=us(e);l.success(`Captured evidence for ${n.fetched}/${n.pages} page${n.pages===1?"":"s"} \u2192 ${Pe.dim(t)}`),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`)}`),n.multiH1>0&&l.message(` ${Pe.yellow("!")} ${n.multiH1} page(s) have multiple/conflicting H1s`),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{existsSync as zp,mkdirSync as Vp,readFileSync as Jp,writeFileSync as Qp}from"fs";import{join as kr}from"path";import St from"picocolors";var ms={minImpressionsToPreserve:50,onTopicRelevance:.34},Wp=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 gs(e){return e.toLowerCase().replace(/https?:\/\/[^/]+/g," ").replace(/[^a-z0-9]+/g," ").split(" ").filter(t=>t.length>2&&!Wp.has(t)&&!/^\d+$/.test(t))}function hs(e){let t=new Set;for(let n of e)for(let r of gs(n))t.add(r);return t}function Hp(e,t){let n=gs(e);return n.length===0||t.size===0?0:n.filter(o=>t.has(o)).length/n.length}function Kp(e,t,n=ms){let r=Hp(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 ys(e,t,n=ms){return e.map(r=>Kp(r,t,n)).sort((r,o)=>o.row.impressions-r.row.impressions)}function ps(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 fn(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 ws(e){let t=e.split(/\r?\n/).filter(p=>p.trim()!=="");if(t.length<2)return[];let n=ps(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=ps(t[p]),g=(m[0]??"").trim();if(!g)continue;let $=c>=0?m[c]??"":"",w=fn($);d.push({key:g,kind:o,clicks:s>=0?fn(m[s]??"")??0:0,impressions:a>=0?fn(m[a]??"")??0:0,position:u>=0?fn(m[u]??""):null,ctr:w===null?null:/%/.test($)?w/100:w})}return d}var fs=["harvest","redirect","sunset"],qp={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 Yp(e){return e.filter(t=>t.disposition==="redirect"&&t.row.kind==="page").map(t=>({from:t.row.key,note:t.action}))}function ks(e){let{domain:t,directionSummary:n,decisions:r,generatedAt:o}=e,i=fs.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(`
475
+ `);for(let c of fs){let u=r.filter(d=>d.disposition===c);if(u.length!==0){s.push(`## ${qp[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=Yp(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(`
476
+ `)}function bs(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 br(e={}){let t=process.cwd(),n=O(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=Kt(t),i=[r,n.site_type],s=e.direction??"";if(o){let w=o.business;for(let C of[w.type,w.audience,w.industry,w.description,w.name])C&&i.push(C);for(let C of o.writingInstructions)i.push(C);s||(s=[w.description,w.type,w.audience].filter(Boolean).join(" \xB7 "))}s||(s=`${n.site_type} at ${r}`);let a=hs(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 w=e.csv.startsWith("/")?e.csv:kr(t,e.csv);if(!zp(w)){l.error(`GSC CSV not found: ${w}`),process.exitCode=1;return}let C=ws(Jp(w,"utf-8"));c.push(...C),u=`${C.length} row(s) from ${e.csv}`}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>`."),l.message(St.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=ys(c,a),p=new Date().toISOString(),m=kr(t,k,"strategy");Vp(m,{recursive:!0});let g=kr(m,"migration-plan.md");Qp(g,ks({domain:r,directionSummary:s,decisions:d,generatedAt:p}),"utf-8");let $=bs(d);if(e.json){process.stdout.write(JSON.stringify({domain:r,directionSummary:s,source:u,summary:$,decisions:d},null,2)+`
477
+ `);return}l.success(`Migration plan written \u2192 ${St.dim(g)} (${u})`),l.message(` ${St.green(`${$.harvest} harvest`)} \xB7 ${St.cyan(`${$.redirect} redirect`)} \xB7 ${St.yellow(`${$.sunset} sunset`)} across ${$.total} legacy asset${$.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 Is,writeFileSync as Ts,readFileSync as cf,readdirSync as lf,existsSync as uf}from"fs";import{join as Os}from"path";import I from"picocolors";import{query as df}from"@anthropic-ai/claude-agent-sdk";import{join as $r}from"path";var Sr="citations",vr="scorecard.md",Xp="history",Zp=6,ef=1,tf=12,nf=5,mn="Claude (web-grounded)";function gn(e){return $r(e,k,Sr)}function Ss(e){return $r(gn(e),vr)}function vs(e){return $r(gn(e),Xp)}function xs(e){return`${e.replace(/[:.]/g,"-")}.json`}function _s(e){return typeof e!="number"||!Number.isFinite(e)?Zp:Math.max(ef,Math.min(tf,Math.floor(e)))}function hn(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>=nf))break}return n}function vt(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function xr(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 Cs(e,t){let{cited:n,total:r}=vt(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function Es(e,t){if(!t)return null;let{cited:n}=vt(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 Rs(e,t){let n=hn(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(`
478
478
  `),o=n.length?`
479
479
  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?`,
480
480
  "competitorsSurfaced": [${JSON.stringify(n[0])}]`:`,
@@ -516,10 +516,10 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
516
516
  }
517
517
  \`\`\`
518
518
 
519
- \`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 vs(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=Jp(n[o]);if(i)return i}return null}function Jp(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=cn(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():"",$=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,w=Array.isArray(u.competitorsSurfaced)?Qp(u.competitorsSurfaced.map(_=>typeof _=="string"?_.trim():"").filter(_=>_&&s.has(_.toLowerCase()))):[];a.push({query:d,surfaced:p,rank:p?m:null,evidence:g,source:$,competitorsSurfaced:w})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function Qp(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 xs(e,t){let{cited:n,total:r}=yt(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",$=p.surfaced&&p.rank?`#${p.rank}`:"\u2014",w=ne(p.evidence||(p.surfaced?"surfaced":"not found")),_=p.source?ne(gs(p.source)):"\u2014";return i?`| ${m+1} | ${ne(p.query)} | ${g} | ${$} | ${_} | ${w} |`:`| ${m+1} | ${ne(p.query)} | ${g} | ${$} | ${w} |`}).join(`
519
+ \`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 As(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=rf(n[o]);if(i)return i}return null}function rf(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=hn(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():"",$=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,w=Array.isArray(u.competitorsSurfaced)?of(u.competitorsSurfaced.map(C=>typeof C=="string"?C.trim():"").filter(C=>C&&s.has(C.toLowerCase()))):[];a.push({query:d,surfaced:p,rank:p?m:null,evidence:g,source:$,competitorsSurfaced:w})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function of(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 Ps(e,t){let{cited:n,total:r}=vt(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",$=p.surfaced&&p.rank?`#${p.rank}`:"\u2014",w=ie(p.evidence||(p.surfaced?"surfaced":"not found")),C=p.source?ie($s(p.source)):"\u2014";return i?`| ${m+1} | ${ie(p.query)} | ${g} | ${$} | ${C} | ${w} |`:`| ${m+1} | ${ie(p.query)} | ${g} | ${$} | ${w} |`}).join(`
520
520
  `),a=i?`| # | Query | Cited? | ~Rank | Source cited | Evidence |
521
521
  |---|-------|--------|-------|--------------|----------|`:`| # | Query | Cited? | ~Rank | Evidence |
522
- |---|-------|--------|-------|----------|`,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: ${ne(gs(p.source))})_`:"";return`- **${ne(p.query)}** \u2014 ${p.evidence||"not surfaced"}${m}`}).join(`
522
+ |---|-------|--------|-------|----------|`,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($s(p.source))})_`:"";return`- **${ie(p.query)}** \u2014 ${p.evidence||"not surfaced"}${m}`}).join(`
523
523
  `),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`---
524
524
  type: Report
525
525
  title: AI Citation Scorecard \u2014 ${e.domain}
@@ -534,11 +534,11 @@ engine: claude-web-grounded
534
534
  > measurement half of the AEO/GEO loop \u2014 \`seoagent okf\` makes you citable, this
535
535
  > tells you whether it's working.
536
536
 
537
- **Cited: ${n} / ${r} queries** \xB7 engine: ${sn} \xB7 ${o}
538
- ${Xp(t.trend,n,r)}
537
+ **Cited: ${n} / ${r} queries** \xB7 engine: ${mn} \xB7 ${o}
538
+ ${sf(t.trend,n,r)}
539
539
  ${a}
540
540
  ${s}
541
- ${Zp(e)}
541
+ ${af(e)}
542
542
  ## Where you're not surfacing (opportunities)
543
543
 
544
544
  ${u}
@@ -562,13 +562,13 @@ This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
562
562
  rank and cite differently, and tracking them individually is a planned
563
563
  follow-up. Treat the score as directional \u2014 watch the trend rather than fixating
564
564
  on a single number.
565
- `}function Xp(e,t,n){if(!e)return`
565
+ `}function sf(e,t,n){if(!e)return`
566
566
  _First run \u2014 re-run on a cadence to start tracking the trend._
567
567
  `;let r=e.scoreDelta>0?`\u25B2 up ${e.scoreDelta}`:e.scoreDelta<0?`\u25BC down ${Math.abs(e.scoreDelta)}`:"\u25AA no change",o=`
568
568
  **Trend:** ${t}/${n} this run \u2014 ${r} from ${e.prevCited}/${e.prevTotal} on ${e.prevDate}.`;return e.newlyCited.length&&(o+=`
569
- - \u2705 Newly cited: ${e.newlyCited.map(i=>`_${ne(i)}_`).join("; ")}`),e.newlyDropped.length&&(o+=`
570
- - \u26A0\uFE0F Dropped: ${e.newlyDropped.map(i=>`_${ne(i)}_`).join("; ")}`),o+`
571
- `}function Zp(e){if(!e.competitors.length)return"";let t=yr(e).map(n=>{let r=n.isYou?`**${ne(n.brand)} (you)**`:ne(n.brand),o=n.total>0?`${Math.round(n.surfaced/n.total*100)}%`:"\u2014";return`| ${r} | ${n.surfaced} / ${n.total} | ${o} |`}).join(`
569
+ - \u2705 Newly cited: ${e.newlyCited.map(i=>`_${ie(i)}_`).join("; ")}`),e.newlyDropped.length&&(o+=`
570
+ - \u26A0\uFE0F Dropped: ${e.newlyDropped.map(i=>`_${ie(i)}_`).join("; ")}`),o+`
571
+ `}function af(e){if(!e.competitors.length)return"";let t=xr(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(`
572
572
  `);return`
573
573
  ## Share of voice
574
574
 
@@ -577,17 +577,17 @@ How often each brand surfaces across the same ${e.results.length} queries.
577
577
  | Brand | Surfaced | Rate |
578
578
  |-------|----------|------|
579
579
  ${t}
580
- `}function gs(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function ne(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function wt(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=dt();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(ie[r].summary),ie[r].next&&l.message(` ${ie[r].next}`),process.exitCode=1;return}l.info(P.dim(ie[r].summary));let o=Ft(t),i=nn(t),s=cn(e.competitors&&e.competitors.length?e.competitors:cf(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=ks(e.queries);l.message(`${P.cyan("\u25C7")} Auditing AI citations for ${P.bold(a.domain)} \u2014 ${c} web-grounded quer${c===1?"y":"ies"} via ${sn}.`),l.message(P.dim(` This runs live web searches and can take a minute\u2026
581
- `));let u=Ss(a,c),d=await of({cwd:t,prompt:u,model:e.model});if(d===null){process.exitCode=1;return}let p=vs(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=ys(t),$=lf(g),w=$s(p,$),_=xs(p,{generatedAt:m,trend:w});_s(an(t),{recursive:!0}),Cs(hs(t),_,"utf-8"),_s(g,{recursive:!0}),Cs(Es(g,ws(m)),JSON.stringify(bs(p,{generatedAt:m}),null,2)+`
582
- `,"utf-8");let{cited:S,total:I}=yt(p),z=S===0?P.red:S<I?P.yellow:P.green,D=[{content:P.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${P.cyan(p.domain)}`},{content:`Cited: ${z(`${S} / ${I}`)} ${P.dim("queries")}`}];if(w){let Q=w.scoreDelta>0?P.green(`\u25B2 +${w.scoreDelta}`):w.scoreDelta<0?P.red(`\u25BC ${w.scoreDelta}`):P.dim("\u25AA 0");D.push({content:`Trend: ${Q} ${P.dim(`vs ${w.prevCited}/${w.prevTotal} on ${w.prevDate}`)}`})}else D.push({content:P.dim("Trend: first run \u2014 re-run to start tracking")});if(D.push({content:`Engine: ${P.dim(sn)}`}),p.competitors.length){D.push({sep:!0}),D.push({content:P.dim("Share of voice:")});for(let Q of yr(p)){let Re=Q.isYou?P.bold(`${Q.brand} (you)`):Q.brand;D.push({content:` ${Re}: ${Q.surfaced}/${Q.total}`})}}D.push({sep:!0}),D.push({content:P.dim(`Saved \u2192 .seoagent/${gr}/${hr}`)}),D.push({content:S<I?P.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):P.dim("Surfacing across the board. Re-run periodically to catch drift.")}),l.message(j(D,{title:P.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(p,null,2)+`
583
- `)}async function of(e){let{cwd:t,prompt:n,model:r}=e;try{let o=rf({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)sf(c)}else if(s.type==="result"){if(process.stdout.write(`
580
+ `}function $s(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 xt(e={}){let t=process.cwd(),n=O(t);if(!n)return;let r=yt();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=Kt(t),i=dn(t),s=hn(e.competitors&&e.competitors.length?e.competitors:gf(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=_s(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 ${mn}.`),l.message(I.dim(` This runs live web searches and can take a minute\u2026
581
+ `));let u=Rs(a,c),d=await pf({cwd:t,prompt:u,model:e.model});if(d===null){process.exitCode=1;return}let p=As(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=vs(t),$=hf(g),w=Es(p,$),C=Ps(p,{generatedAt:m,trend:w});Is(gn(t),{recursive:!0}),Ts(Ss(t),C,"utf-8"),Is(g,{recursive:!0}),Ts(Os(g,xs(m)),JSON.stringify(Cs(p,{generatedAt:m}),null,2)+`
582
+ `,"utf-8");let{cited:A,total:R}=vt(p),U=A===0?I.red:A<R?I.yellow:I.green,L=[{content:I.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${I.cyan(p.domain)}`},{content:`Cited: ${U(`${A} / ${R}`)} ${I.dim("queries")}`}];if(w){let V=w.scoreDelta>0?I.green(`\u25B2 +${w.scoreDelta}`):w.scoreDelta<0?I.red(`\u25BC ${w.scoreDelta}`):I.dim("\u25AA 0");L.push({content:`Trend: ${V} ${I.dim(`vs ${w.prevCited}/${w.prevTotal} on ${w.prevDate}`)}`})}else L.push({content:I.dim("Trend: first run \u2014 re-run to start tracking")});if(L.push({content:`Engine: ${I.dim(mn)}`}),p.competitors.length){L.push({sep:!0}),L.push({content:I.dim("Share of voice:")});for(let V of xr(p)){let Z=V.isYou?I.bold(`${V.brand} (you)`):V.brand;L.push({content:` ${Z}: ${V.surfaced}/${V.total}`})}}L.push({sep:!0}),L.push({content:I.dim(`Saved \u2192 .seoagent/${Sr}/${vr}`)}),L.push({content:A<R?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(N(L,{title:I.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(p,null,2)+`
583
+ `)}async function pf(e){let{cwd:t,prompt:n,model:r}=e;try{let o=df({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)ff(c)}else if(s.type==="result"){if(process.stdout.write(`
584
584
  `),!(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(`
585
- `),l.error(` Agent error: ${o.message}`),null}}function sf(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(Qt(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(P.dim(` ${P.magenta("\u{1F50E}")} ${n}${o?` ${af(o,70)}`:""}
586
- `))}}function af(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function cf(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function lf(e){try{if(!nf(e))return null;let t=tf(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(ef(Es(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import Ye from"picocolors";var uf=30,df=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi;function pf(e){let t=e,n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t);n&&(t=n[1]),t=t.replace(df," ").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<uf?"empty":"yes"}}async function ff(e,t){try{let n=await O(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}=pf(r);return{status:n.status,rendered:i,wordCount:o}}catch{return{status:null,rendered:"error",wordCount:0}}}async function Rs(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 ff(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 wr=300;async function kt(e={}){if(e.all){await mf();return}let t=process.cwd();if(!L(t))return;we(t);let n=zn(t);Ps(t);let r=await As(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 As(e,t={}){try{let n=C(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=Z(e,r);t.enrichSitemap&&r&&await _o(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,wr);if(c.length>wr&&l.info(`Crawling the first ${wr} of ${c.length} pages (cap).`),u.length>0){l.info(`Crawling ${u.length} page${u.length===1?"":"s"}\u2026`),s=await Rs(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=Bt(e,o,s);return{added:a.added,total:a.total,crawl:i}}catch{return{added:0,total:0}}}async function mf(){let e=oo();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 ${Ye.bold(A)}\u2026`);let t=0,n=0;for(let r of e){let o=zn(r);Ps(r);let i=await As(r),s=i.added>0?Ye.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Ye.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${Ye.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${Ye.yellow("!")} ${r} ${Ye.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 Ps(e){try{ye(e)}catch{}}import{spinner as br,confirm as gf,isCancel as hf}from"@clack/prompts";import y from"picocolors";var Ts={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function yf(e){let t=process.cwd(),n=Ot(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=C(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||R.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?br():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await O(`${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){b(a,"error",`Network error: ${d.message}`,y.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})+`
587
- `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";b(a,"warn",`Daily peek quota reached for ${d}.`,y.yellow(`Daily peek quota reached for ${d}.`)),l.message(Is()),process.exitCode=1;return}if(!c.ok||!u){b(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){b(a,"warn","Real keyword data is temporarily unavailable. Try again later.",y.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(y.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){b(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){b(a,"warn",`No data returned for "${e.keyword}".`,y.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(y.green("Got it.")),l.message(wf(u.opportunity)),u.remaining&&l.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Is())}`)}function wf(e){let n=u=>y.dim(u.padEnd(14)),r=e.volume!=null?y.bold(String(e.volume)):y.dim("n/a"),o=e.difficulty!=null?`${y.bold(String(e.difficulty))} ${y.dim(kf(e.difficulty))}`:y.dim("n/a"),i=Ts[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?y.bold(y.green(i)):e.opportunity==="striking_distance"?y.bold(y.cyan(i)):e.opportunity==="competitor_gap"?y.bold(y.yellow(i)):y.dim(i),a=[{content:`${y.green("\u25CF")} ${y.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${y.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${y.bold(y.cyan("Keyword peek"))}`;return j(a,{width:55,title:c})}function kf(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Is(e=U()){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 kr(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 [${Ts[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function bf(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 $f(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await gf({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(hf(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||R.BASE,r=process.stdout.isTTY?br():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await O(`${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){b(r,"error",`Network error: ${a.message}`,y.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"){b(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",y.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){b(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,y.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;b(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,y.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(y.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 ge(e={}){if(e.peek&&e.peek.trim().length>0){await yf({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=U();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await $f({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||R.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?br():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await O(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(g){b(c,"error",`Network error: ${g.message}`,y.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"){b(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",y.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${y.cyan(R.PRICING)}`:`Upgrade to find new keywords to target: ${y.cyan(R.PRICING)}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){b(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,y.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){b(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.",y.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){b(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",y.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){b(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",y.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){b(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){b(c,"warn",`Skipped: ${p.skipped}`,y.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let g=p.gaps??0;b(c,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,y.green(`${g} competitor gap${g===1?"":"s"} found.`)),bf(p.topGaps??[]),l.message(`Review them in ${y.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;b(c,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,y.green(`${g} new keyword${g===1?"":"s"} discovered.`)),kr(p.opportunities??[]),l.message(`Review them in ${y.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;b(c,"success",`Seeded ${g} keyword${g===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,y.green(`${g} keyword${g===1?"":"s"} seeded from Search Console.`)),kr(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${y.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let m=p.enriched??0;b(c,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,y.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),kr(p.opportunities??[]),p.paid||l.message(`${y.dim("Free plan:")} enriched up to ${y.bold(String(p.cap??25))} keywords. ${y.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${y.cyan(R.PRICING)}`)}import N from"picocolors";function bt(e={}){let t=process.cwd(),n=C(t),r=le(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
588
- `);return}if(l.message(Sf(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}V(t,{image_provider:r.provider}),l.info(`Saved to ${N.cyan(".seoagent/project.md")} ${N.dim(`(image_provider: ${r.provider})`)}`)}function Sf(e){let n=i=>N.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${N.dim("\u25CB")} ${N.bold(N.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:N.dim("Set ONE of these to enable image generation:")});let i=wo();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${N.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:N.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${N.cyan(f("env-check"))}`})}else{r.push({content:`${N.green("\u2713")} ${N.dim("Image provider:")} ${N.bold(N.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${N.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${N.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${N.dim(i.join(", "))}`})}let o=`${N.bold(N.cyan("SEOAgent"))} ${N.dim("\xB7")} ${N.dim("env-check")}`;return j(r,{width:64,title:o})}import{existsSync as Sr,mkdirSync as js,writeFileSync as Ns}from"fs";import{dirname as un,isAbsolute as Ef,join as ln,resolve as Rf}from"path";import{tmpdir as Af}from"os";import{spinner as Pf}from"@clack/prompts";import M from"picocolors";import{Buffer as Os}from"buffer";async function $r(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 Os.from(n)}async function vf(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:Os.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await $r(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function xf(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 $r(o.url),contentType:o.content_type??"image/png"}}async function _f(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 Cf(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 _f(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 $r(o),contentType:"image/png",providerImageId:r.id}}async function Ls(e,t){switch(e){case"openai":return vf(t);case"fal":return xf(t);case"replicate":return Cf(t);default:throw new Error(`Unknown image provider: ${e}`)}}function If(e){return e==="openai"||e==="fal"||e==="replicate"}async function $t(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=C(t),r=null;if(e.provider){if(!If(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=le(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=yo(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=Ef(e.out)?e.out:Rf(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Pf():null;a?.start(`Generating image with ${M.bold(r)} ${M.dim(`(${o.envName})`)}\u2026`);try{let c=await Ls(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Sr(un(i))||js(un(i),{recursive:!0}),Ns(i,c.bytes),e.silent||b(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,M.green(`Wrote ${i} ${M.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(M.red("Image generation failed."));let u=Of(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Tf({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${M.dim("Full error log:")} ${M.cyan(u)}`),process.exitCode=1}}function Tf(e){let n=d=>M.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${M.red("\u2717")} ${M.bold(M.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${M.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${M.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:M.red(c)});let u=`${M.bold(M.cyan("SEOAgent"))} ${M.dim("\xB7")} ${M.dim("generate-image")}`;return j(i,{width:70,title:u})}function Of(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=ln(e,k),i=ln(o,".errors"),s=Sr(o)?ln(i,r):ln(Af(),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 Sr(un(s))||js(un(s),{recursive:!0}),Ns(s,a.join(`
589
- `)),s}catch{return null}}import H from"picocolors";async function St(e={}){let t=U();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
590
- `):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||R.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})}
585
+ `),l.error(` Agent error: ${o.message}`),null}}function ff(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(sn(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?` ${mf(o,70)}`:""}
586
+ `))}}function mf(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function gf(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function hf(e){try{if(!uf(e))return null;let t=lf(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(cf(Os(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import Qe from"picocolors";var yf=30,wf=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi;function kf(e){let t=e,n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t);n&&(t=n[1]),t=t.replace(wf," ").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<yf?"empty":"yes"}}async function bf(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}=kf(r);return{status:n.status,rendered:i,wordCount:o}}catch{return{status:null,rendered:"error",wordCount:0}}}async function Ls(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 bf(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 _r=300;async function _t(e={}){if(e.all){await $f();return}let t=process.cwd();if(!O(t))return;$e(t);let n=tr(t);Ns(t);let r=await js(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 js(e,t={}){try{let n=x(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,_r);if(c.length>_r&&l.info(`Crawling the first ${_r} of ${c.length} pages (cap).`),u.length>0){l.info(`Crawling ${u.length} page${u.length===1?"":"s"}\u2026`),s=await Ls(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=zt(e,o,s);return{added:a.added,total:a.total,crawl:i}}catch{return{added:0,total:0}}}async function $f(){let e=go();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 ${Qe.bold(E)}\u2026`);let t=0,n=0;for(let r of e){let o=tr(r);Ns(r);let i=await js(r),s=i.added>0?Qe.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Qe.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${Qe.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${Qe.yellow("!")} ${r} ${Qe.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${E}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Ns(e){try{be(e)}catch{}}import{spinner as Er,confirm as Sf,isCancel as vf}from"@clack/prompts";import y from"picocolors";var Fs={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function xf(e){let t=process.cwd(),n=Ut(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=x(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||T.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Er():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.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){b(a,"error",`Network error: ${d.message}`,y.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})+`
587
+ `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";b(a,"warn",`Daily peek quota reached for ${d}.`,y.yellow(`Daily peek quota reached for ${d}.`)),l.message(Ds()),process.exitCode=1;return}if(!c.ok||!u){b(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){b(a,"warn","Real keyword data is temporarily unavailable. Try again later.",y.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(y.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){b(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){b(a,"warn",`No data returned for "${e.keyword}".`,y.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(y.green("Got it.")),l.message(_f(u.opportunity)),u.remaining&&l.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Ds())}`)}function _f(e){let n=u=>y.dim(u.padEnd(14)),r=e.volume!=null?y.bold(String(e.volume)):y.dim("n/a"),o=e.difficulty!=null?`${y.bold(String(e.difficulty))} ${y.dim(Cf(e.difficulty))}`:y.dim("n/a"),i=Fs[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?y.bold(y.green(i)):e.opportunity==="striking_distance"?y.bold(y.cyan(i)):e.opportunity==="competitor_gap"?y.bold(y.yellow(i)):y.dim(i),a=[{content:`${y.green("\u25CF")} ${y.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${y.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${y.bold(y.cyan("Keyword peek"))}`;return N(a,{width:55,title:c})}function Cf(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Ds(e=j()){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 Cr(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 [${Fs[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Ef(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 Rf(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await Sf({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(vf(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||T.BASE,r=process.stdout.isTTY?Er():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){b(r,"error",`Network error: ${a.message}`,y.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"){b(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",y.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){b(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,y.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;b(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,y.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(y.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 ye(e={}){if(e.peek&&e.peek.trim().length>0){await xf({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await Rf({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?Er():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){b(c,"error",`Network error: ${g.message}`,y.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"){b(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",y.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${y.cyan(ee("cli-keywords-competitors"))}`:`Upgrade to find new keywords to target: ${y.cyan(ee("cli-keywords-discover"))}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){b(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,y.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){b(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.",y.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){b(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",y.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){b(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",y.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){b(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){b(c,"warn",`Skipped: ${p.skipped}`,y.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let g=p.gaps??0;b(c,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,y.green(`${g} competitor gap${g===1?"":"s"} found.`)),Ef(p.topGaps??[]),l.message(`Review them in ${y.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;b(c,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,y.green(`${g} new keyword${g===1?"":"s"} discovered.`)),Cr(p.opportunities??[]),l.message(`Review them in ${y.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;b(c,"success",`Seeded ${g} keyword${g===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,y.green(`${g} keyword${g===1?"":"s"} seeded from Search Console.`)),Cr(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${y.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let m=p.enriched??0;b(c,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,y.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),Cr(p.opportunities??[]),p.paid||l.message(`${y.dim("Free plan:")} enriched up to ${y.bold(String(p.cap??25))} keywords. ${y.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${y.cyan(ee("cli-keywords-cap"))}`)}import D from"picocolors";function Ct(e={}){let t=process.cwd(),n=x(t),r=pe(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
588
+ `);return}if(l.message(Af(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}J(t,{image_provider:r.provider}),l.info(`Saved to ${D.cyan(".seoagent/project.md")} ${D.dim(`(image_provider: ${r.provider})`)}`)}function Af(e){let n=i=>D.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${D.dim("\u25CB")} ${D.bold(D.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:D.dim("Set ONE of these to enable image generation:")});let i=Ro();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${D.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:D.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${D.cyan(f("env-check"))}`})}else{r.push({content:`${D.green("\u2713")} ${D.dim("Image provider:")} ${D.bold(D.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${D.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${D.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${D.dim(i.join(", "))}`})}let o=`${D.bold(D.cyan("SEOAgent"))} ${D.dim("\xB7")} ${D.dim("env-check")}`;return N(r,{width:64,title:o})}import{existsSync as Ar,mkdirSync as Bs,writeFileSync as Gs}from"fs";import{dirname as wn,isAbsolute as Lf,join as yn,resolve as jf}from"path";import{tmpdir as Nf}from"os";import{spinner as Df}from"@clack/prompts";import B from"picocolors";import{Buffer as Us}from"buffer";async function Rr(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 Us.from(n)}async function Pf(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:Us.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Rr(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function If(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 Rr(o.url),contentType:o.content_type??"image/png"}}async function Tf(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 Of(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 Tf(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 Rr(o),contentType:"image/png",providerImageId:r.id}}async function Ms(e,t){switch(e){case"openai":return Pf(t);case"fal":return If(t);case"replicate":return Of(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Ff(e){return e==="openai"||e==="fal"||e==="replicate"}async function Et(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=x(t),r=null;if(e.provider){if(!Ff(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=pe(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=Eo(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=Lf(e.out)?e.out:jf(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Df():null;a?.start(`Generating image with ${B.bold(r)} ${B.dim(`(${o.envName})`)}\u2026`);try{let c=await Ms(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Ar(wn(i))||Bs(wn(i),{recursive:!0}),Gs(i,c.bytes),e.silent||b(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=Mf(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Uf({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 Uf(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 N(i,{width:70,title:u})}function Mf(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=yn(e,k),i=yn(o,".errors"),s=Ar(o)?yn(i,r):yn(Nf(),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 Ar(wn(s))||Bs(wn(s),{recursive:!0}),Gs(s,a.join(`
589
+ `)),s}catch{return null}}import K from"picocolors";async function Rt(e={}){let t=j();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
590
+ `):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})}
591
591
  `);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}`})}
592
592
  `):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)}
593
- `);return}l.message(Lf(i)),i.paid===!1&&l.message(`${H.dim("Upgrade for autopilot:")} ${H.cyan(R.PRICING)}`)}function Lf(e){let n=i=>H.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${H.green("\u2713")} ${H.dim("Logged in as")} ${H.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${H.cyan(e.domain)}`}),e.plan){let i=e.paid?H.bold(H.green(e.plan)):H.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${H.dim(e.api_base)}`});let o=`${H.bold(H.cyan("SEOAgent"))} ${H.dim("\xB7")} ${H.dim("whoami")}`;return j(r,{width:55,title:o})}import{select as xt,text as vt,confirm as Us,isCancel as Y,intro as jf,outro as Nf}from"@clack/prompts";import dn from"picocolors";function Df(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>rt()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await K()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await et()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await at()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await St()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await xt({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(!Y(e))if(e==="peek"){let t=await vt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(Y(t))return;await ge({peek:String(t)})}else e==="discover"?await ge({discover:!0}):e==="competitors"?await ge({competitors:!0}):await ge()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>ft({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await xt({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"}]});Y(e)||mt(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 wt()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await vt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(Y(e))return;let t=await vt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});Y(t)||await $t({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>bt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await xt({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"}]});Y(e)||await pt(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await _e()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await vt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(Y(e))return;let t=await Us({message:"Mark as failed instead of completed?",initialValue:!1});if(Y(t))return;let n;if(t===!0){let r=await vt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(Y(r))return;String(r).trim()&&(n=String(r))}await fe(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 it()},{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 st({})},{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 xt({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"}]});Y(e)||kt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>ct()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await tt({})}]}var Ds="__exit__";async function Fs(e=Df()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:Ds,label:"Exit",hint:"Close the menu"});let n=await xt({message:"What would you like to do?",options:t});if(Y(n)||n===Ds)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 vr(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}jf(`${dn.bold(dn.cyan("SEOAgent"))} ${dn.dim("\xB7 menu")}`);let e=await Fs();for(;!e;){let t=await Us({message:"Do another?",initialValue:!0});if(Y(t)||t===!1){e=!0;break}e=await Fs()}Nf(dn.dim("See you next time."))}var E=new Ff;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=>{et({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=>{tt({yes:e.yes,global:e.global})});E.command("status").description("Show current SEO project state").action(rt);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=>{ir({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=>{at({apiBase:e.apiBase})});E.command("logout").description("Remove stored credentials for seoagent.com").action(ct);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=>{K({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=>{_e({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)=>{fe(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=>{Jn({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=>{er({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)=>{pt(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=>{ge({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=>{ft({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)=>{rr(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)=>{mt(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=>{cr({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, robots.txt, sitemap counts, client-render detection) \u2192 .seoagent/audit/evidence.md. Grounds every audit claim so nothing is invented.").option("--max <n>","Max pages to crawl (default 10, max 25)",e=>parseInt(e,10)).option("--json","Output the full evidence bundle as JSON").action(e=>{dr({max:e.max,json:e.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=>{fr({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=>{wt({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=>{bt({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=>{$t({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=>{St({json:e.json,apiBase:e.apiBase})});E.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(it);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=>{st({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=>{kt({all:e.all,crawl:e.crawl})});E.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{vr()});process.argv.length===2&&(E.outputHelp(),process.exit(0));E.parse();
593
+ `);return}l.message(Bf(i)),i.paid===!1&&l.message(`${K.dim("Upgrade for autopilot:")} ${K.cyan(ee("cli-whoami"))}`)}function Bf(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 N(r,{width:55,title:o})}import{select as Pt,text as At,confirm as Ks,isCancel as z,intro as Gf,outro as Wf}from"@clack/prompts";import kn from"picocolors";function Hf(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>lt()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await q()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await st()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await ft()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await Rt()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Pt({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(!z(e))if(e==="peek"){let t=await At({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(z(t))return;await ye({peek:String(t)})}else e==="discover"?await ye({discover:!0}):e==="competitors"?await ye({competitors:!0}):await ye()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>kt({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await Pt({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"}]});z(e)||bt(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 xt()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await At({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(z(e))return;let t=await At({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});z(t)||await Et({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Ct({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Pt({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"}]});z(e)||await wt(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await Re()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await At({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(z(e))return;let t=await Ks({message:"Mark as failed instead of completed?",initialValue:!1});if(z(t))return;let n;if(t===!0){let r=await At({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(z(r))return;String(r).trim()&&(n=String(r))}await ge(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 dt()},{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 pt({})},{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 Pt({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"}]});z(e)||_t({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>mt()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await at({})}]}var Ws="__exit__";async function Hs(e=Hf()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:Ws,label:"Exit",hint:"Close the menu"});let n=await Pt({message:"What would you like to do?",options:t});if(z(n)||n===Ws)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 Pr(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Gf(`${kn.bold(kn.cyan("SEOAgent"))} ${kn.dim("\xB7 menu")}`);let e=await Hs();for(;!e;){let t=await Ks({message:"Do another?",initialValue:!0});if(z(t)||t===!1){e=!0;break}e=await Hs()}Wf(kn.dim("See you next time."))}var _=new Kf;_.name("seoagent").description("AI SEO agent for Claude Code").version(E).showSuggestionAfterError(!0).showHelpAfterError(!0);_.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=>{st({yes:e.yes,domain:e.domain,siteType:e.siteType})});_.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=>{at({yes:e.yes,global:e.global})});_.command("status").description("Show current SEO project state").action(lt);_.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=>{pr({json:e.json})});_.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=>{ft({apiBase:e.apiBase})});_.command("logout").description("Remove stored credentials for seoagent.com").action(mt);_.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=>{q({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});_.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=>{Re({force:e.force,silent:e.silent,print:e.print})});_.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)=>{ge(e,{failed:t.failed,reason:t.reason})});_.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{rr({json:e.json})});_.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=>{ar({yes:e.yes,model:e.model})});_.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)=>{wt(e,{apiBase:t.apiBase})});_.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=>{ye({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});_.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=>{kt({json:e.json})});_.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)=>{ur(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})});_.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)=>{bt(e,{json:t.json})});_.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=>{gr({url:e.url,json:e.json})});_.command("crawl").description("Capture the live-crawl evidence base (title, meta, all H1s, canonical, JSON-LD @types, OG/Twitter, robots.txt, sitemap counts, client-render detection) \u2192 .seoagent/audit/evidence.md. Grounds every audit claim so nothing is invented.").option("--max <n>","Max pages to crawl (default 10, max 25)",e=>parseInt(e,10)).option("--json","Output the full evidence bundle as JSON").action(e=>{wr({max:e.max,json:e.json})});_.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=>{br({csv:e.csv,direction:e.direction,json:e.json})});_.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=>{xt({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})});_.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Ct({json:e.json})});_.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=>{Et({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});_.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=>{Rt({json:e.json,apiBase:e.apiBase})});_.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(dt);_.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=>{pt({dryRun:e.dryRun,projects:e.projects})});_.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=>{_t({all:e.all,crawl:e.crawl})});_.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Pr()});process.argv.length===2&&(_.outputHelp(),process.exit(0));_.parse();