@seoagent-official/seoagent 1.100.1 → 1.100.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +27 -27
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as lv}from"commander";import{dirname as If,relative as
|
|
2
|
+
import{Command as lv}from"commander";import{dirname as If,relative as Pt}from"path";var Xu={nl:"nl",be:"nl",de:"de",at:"de",ch:"de",fr:"fr",es:"es",it:"it",pt:"pt",br:"pt",dk:"da",se:"sv",no:"nb",fi:"fi",is:"is",gr:"el",pl:"pl",cz:"cs",sk:"sk",hu:"hu",ro:"ro",bg:"bg",hr:"hr",si:"sl",rs:"sr",lt:"lt",lv:"lv",ee:"et",ua:"uk",ru:"ru",tr:"tr",il:"he",sa:"ar",eg:"ar",mx:"es",ar:"es",cl:"es",co:"es",pe:"es",jp:"ja",kr:"ko",tw:"zh-TW",id:"id",vn:"vi",th:"th"},zi={"com.br":"pt","com.mx":"es","com.ar":"es","com.co":"es","co.jp":"ja","co.kr":"ko","com.tw":"zh-TW","co.id":"id","com.vn":"vi","co.th":"th","co.il":"he","com.tr":"tr"},Qr="en";function Qu(e){return e.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//,"").split(/[/?#]/)[0].split(":")[0].replace(/^www\./,"").replace(/\.$/,"")}function Yi(e){if(!e)return Qr;let t=Qu(e).split(".").filter(Boolean);if(t.length<2)return Qr;if(t.length>=3){let n=`${t[t.length-2]}.${t[t.length-1]}`;if(zi[n])return zi[n]}return Xu[t[t.length-1]]??Qr}import{intro as Ea,outro as Of,text as Ra,select as Io,spinner as Tf,isCancel as dt,cancel as pt,confirm as Aa}from"@clack/prompts";var bt=[".env.local",".env.production",".env"],Ji=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var Ae="@seoagent-official/seoagent",Kn=`${Ae}@latest`;import{homedir as Zu}from"os";import{join as kt}from"path";var k=".seoagent",Xi=["audit","strategy/clusters","briefs","content","content/images","performance"],Pe={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Wt=".claude/settings.json",qn=".pull-receipt.json",Qi=".ack-queue.json",Zi=".sync.lock",es=`# 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
|
-
`,ed=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:
|
|
9
|
+
`,ed=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:kt(Zu(),".config"),z=kt(ed,"seoagent"),Be=kt(z,"auth.json"),Zr=kt(z,"state"),Vn=kt(z,"update-check.json"),zn=kt(z,"projects.json");var Ie="https://seoagent.com",vt=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):Ie,O={BASE:vt,PRICING:`${vt}/pricing`,LEAD_API:`${vt}/api/cli/lead`,CLI_AUTH_PAGE:`${vt}/cli/auth`,CLI_AUTH_POLL:`${vt}/api/cli/auth/poll`,CLI_SYNC:`${vt}/api/cli/sync`};function be(e,t){let n=t&&t!=="unknown"?`&domain=${encodeURIComponent(t)}`:"";return`${O.PRICING}?ref=${encodeURIComponent(e)}${n}`}import{readFileSync as td}from"fs";import{fileURLToPath as nd}from"url";import{dirname as rd,join as od}from"path";var ts="0.0.0";function id(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return ts}function sd(e=t=>td(t,"utf-8")){try{let t=rd(nd(import.meta.url));return id(e(od(t,"package.json")))}catch{return ts}}var C=sd();function eo(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 m(e,t=eo()){return t?`seoagent ${e}`:`npx -y ${Kn} ${e}`}import{randomUUID as hd}from"crypto";import{existsSync as ls,mkdirSync as cs,readFileSync as yd,writeFileSync as us}from"fs";import{join as oo}from"path";import{existsSync as ad,readFileSync as ld}from"fs";var Yn="---";function cd(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 ud(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 ns(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,l]=ns(e,o+1,s.indent);r[i.key]=a,o=l}else r[i.key]="",o++}else r[i.key]=cd(i.valueRaw),o++}return[r,o]}function ue(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Yn)return{data:{},body:e};let n=-1;for(let l=1;l<t.length;l++)if(t[l].trim()===Yn){n=l;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
|
|
10
10
|
`),i=ud(r),s=i.length>0?i[0].indent:0,[a]=ns(i,0,s);return{data:a,body:o}}function Ge(e){if(!ad(e))return null;try{return ue(ld(e,"utf-8"))}catch{return null}}function dd(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 rs(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}:`),rs(i,t+1,n)):n.push(`${r}${o}: ${dd(i)}`))}function to(e,t=""){let n=[Yn];rs(e,0,n),n.push(Yn);let r=t.length===0?"":t.startsWith(`
|
|
11
11
|
`)?t:`
|
|
12
12
|
${t}`;return n.join(`
|
|
@@ -14,13 +14,13 @@ ${t}`;return n.join(`
|
|
|
14
14
|
`)?"":`
|
|
15
15
|
`)}import{existsSync as Xn,readdirSync as pd,statSync as fd}from"fs";import{join as Oe}from"path";var is=["svelte.config.js","svelte.config.ts","svelte.config.mjs","svelte.config.cjs","gatsby-config.js","gatsby-config.ts","gatsby-config.mjs","docusaurus.config.js","docusaurus.config.ts","docusaurus.config.mjs","hugo.toml","hugo.yaml","hugo.json"],ss=["next.config.js","next.config.ts","next.config.mjs","next.config.cjs","astro.config.js","astro.config.ts","astro.config.mjs","nuxt.config.js","nuxt.config.ts","nuxt.config.mjs","remix.config.js","remix.config.ts","vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs"],gd=["apps","packages"];function no(e){for(let t of is)if(Xn(Oe(e,t)))return"static";for(let t of ss)if(Xn(Oe(e,t)))return"public";return null}function os(e){for(let t of[...is,...ss])if(Xn(Oe(e,t)))return t;return null}function ro(e){let t=[];for(let n of gd){let r;try{r=pd(Oe(e,n),{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name).sort()}catch{continue}for(let o of r){let i=`${n}/${o}`;no(Oe(e,i))&&t.push(i)}}return t.length===1?t[0]:null}function Qn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^\.\//,"").replace(/\/+$/,"");return!t||t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)||t.split(/[\\/]/).some(n=>n==="..")?null:t.replace(/\\/g,"/")}function Jn(e,t){try{return fd(Oe(e,t)).isDirectory()}catch{return!1}}function Zn(e,t){let n=Qn(t);if(n)return{dir:n,source:"configured",evidence:"public_dir in .seoagent/project.md",exists:Jn(e,n)};let r=no(e);if(r)return{dir:r,source:"framework",evidence:os(e),exists:Jn(e,r)};let o=ro(e);if(o){let i=no(Oe(e,o));if(i){let s=`${o}/${i}`;return{dir:s,source:"framework",evidence:`${o}/${os(Oe(e,o))}`,exists:Jn(e,s)}}}for(let i of["public","static"])if(Jn(e,i))return{dir:i,source:"existing",evidence:`${i}/ exists`,exists:!0};return{dir:null,source:null,evidence:null,exists:!1}}var md=["app/llms.txt/route.ts","app/llms.txt/route.tsx","app/llms.txt/route.js","src/app/llms.txt/route.ts","src/app/llms.txt/route.tsx","src/app/llms.txt/route.js","pages/llms.txt.ts","pages/llms.txt.js","src/pages/llms.txt.ts","src/pages/llms.txt.js","src/routes/llms.txt/+server.ts","src/routes/llms.txt/+server.js","routes/llms.txt/+server.ts","routes/llms.txt/+server.js"];function as(e,t){let n=new Set([""]),r=Qn(t);if(r){let o=r.split("/").slice(0,-1).join("/");o&&n.add(o)}for(let o of n)for(let i of md){let s=o?`${o}/${i}`:i;if(Xn(Oe(e,s)))return s}return null}var wd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function io(){return hd()}var bd=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),kd="project.md";function Te(e){return oo(e,k)}function er(e){return oo(Te(e),kd)}function ds(e){return ls(er(e))}function _(e){let t=Ge(er(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&&bd.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0,a=typeof n.publishing=="object"&&n.publishing!==null?n.publishing:void 0,l=typeof n.content_dir=="string"&&n.content_dir?n.content_dir:a&&typeof a.content_dir=="string"&&a.content_dir?a.content_dir:void 0,c=typeof n.public_dir=="string"&&n.public_dir?n.public_dir:a&&typeof a.public_dir=="string"&&a.public_dir?a.public_dir: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,skill_hash:typeof n.skill_hash=="string"&&/^[0-9a-f]{64}$/.test(n.skill_hash)?n.skill_hash:void 0,install_id:s&&wd.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,content_dir:l?l.replace(/\/+$/,""):void 0,public_dir:Qn(c)??void 0,llms_owner:n.llms_owner==="route"?"route":void 0,live_url:typeof n.live_url=="string"&&n.live_url?n.live_url:void 0}}function Le(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=io();return Y(e,{install_id:n}),n}function vd(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
16
|
`)}function $d(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.skill_hash&&(t.skill_hash=e.skill_hash),e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),e.content_dir&&(t.content_dir=e.content_dir),e.public_dir&&(t.public_dir=e.public_dir),e.llms_owner&&(t.llms_owner=e.llms_owner),e.live_url&&(t.live_url=e.live_url),t}function ps(e,t){let n=Te(e);cs(n,{recursive:!0});let r=to($d(t),vd(t));us(er(e),r,"utf-8")}function Y(e,t){let n=er(e);if(!ls(n))return!1;let r=ue(yd(n,"utf-8")),o={...r.data,...t};return us(n,to(o,r.body),"utf-8"),!0}function fs(e){let t=Te(e);for(let n of Xi)cs(oo(t,n),{recursive:!0})}var so="Sent an anonymous install ping (random id + CLI version only \u2014 no domain, no paths). Opt out: SEOAGENT_TELEMETRY=0",Sd=2500;function ke(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 tt(e){let t=(e.apiBase||O.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??Sd)})).ok}catch{return!1}}import{existsSync as Ad,mkdirSync as hs,readFileSync as Pd,writeFileSync as Id,chmodSync as Od,unlinkSync as ys}from"fs";import{dirname as Td}from"path";var xd=new Set([502,503,504]),_d=1e4;async function I(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??_d,s=n.fetchImpl??fetch,a=n.sleep??Cd,l=n.transientStatuses??xd,c=null;for(let d=0;d<r;d++){let{init:p,cleanup:f}=Ed(t,i);try{let g=await s(e,p);if(l.has(g.status)&&d<r-1){await a(gs(o,d));continue}return g}catch(g){if(c=g,d<r-1){await a(gs(o,d));continue}}finally{f()}}throw c instanceof Error?c:new Error(String(c))}function gs(e,t){return e*Math.pow(3,t)}function Cd(e){return new Promise(t=>setTimeout(t,e))}function Ed(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 He="unknown";function We(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):""}function Rd(e,t){let n=We(e),r=We(t);return!n||!r||n===He||r===He?!1:n===r}async function Ke(e){let t;try{t=await I(`${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?Rd(r,e.localDomain)?{verdict:"match",cloudDomain:r}:{verdict:"mismatch",cloudDomain:r}:{verdict:"unverified",detail:"whoami did not return a bound domain"}}function ms(e,t){return`Cloud project is ${We(e)||e} but this workspace is ${We(t)||t} \u2014 not syncing. Run \`seoagent login\` from this directory to connect the right site \u2014 the CLI can stay logged into both sites at once, no need to log out first.`}var ws="SEOAGENT_AUTH";function Ld(e,t=Ie){let n=(e??"").trim();if(!n)return null;let r=n.indexOf(":");if(r<=0||r===n.length-1)return null;let o=n.slice(0,r).trim(),i=n.slice(r+1).trim();return!o||!i?null:{user_token:o,website_token:i,api_base:t}}function bs(e){return`${ws}=${e.user_token}:${e.website_token}`}function ks(e=process.env){return ao(e)?"env":"file"}function ao(e=process.env){let t=(e.SEOAGENT_API_BASE??"").trim()||Ie;return Ld(e[ws],t)}function tr(e){if(!e)return"";let t=We(e);return t&&t!==He?t:""}function Kt(){if(!Ad(Be))return null;try{return JSON.parse(Pd(Be,"utf-8"))}catch{return null}}function nt(e){return!e||!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||Ie}}function vs(e){hs(z,{recursive:!0}),hs(Td(Be),{recursive:!0}),Id(Be,JSON.stringify(e,null,2)+`
|
|
17
|
-
`,"utf-8");try{Od(Be,384)}catch{}}function N(e){let t=ao();if(t)return t;let n=Kt();if(!n)return null;if(!e)return nt(n);let r=tr(e);return r&&Object.keys(n.sites??{}).length>0?nt(n.sites?.[r]):nt(n)}function $s(e){if(ao())return!0;let t=Kt();if(!t)return!1;let n=tr(e);return n?nt(t.sites?.[n])!==null:!1}function lo(e,t){let n=Kt()??{},r=tr(t),o={...n.sites??{}};r&&(o[r]=e),vs({...e,sites:Object.keys(o).length>0?o:void 0})}function Ss(e){let t=Kt();if(!t)return!1;let n=tr(e),r=Object.keys(t.sites??{}).length>0;if(!n||!r)try{return ys(Be),!0}catch{return!1}let o=t.sites?.[n];if(!o)return!1;let i={...t.sites};delete i[n];let s=Object.keys(i),a=t.website_token===o.website_token,l=nt(a?i[s[0]]:t);if(!l&&s.length===0)try{return ys(Be),!0}catch{return!1}return vs({...l??{},sites:s.length>0?i:void 0}),!0}function qe(){let e=Kt();return e?.sites?Object.keys(e.sites).sort():[]}var Nd=new Set(["co","com","net","org","ac","gov","edu"]);function jd(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&&Nd.has(n[n.length-2])?n.length-3:n.length-2;return n[Math.max(0,r)]||null}async function xs(e){let t=jd(e.domain);if(!t)return{status:"unavailable"};let n=(e.apiBase||O.BASE).replace(/\/$/,"");try{let r=await I(`${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 rt,lstatSync as Dd,mkdirSync as ot,readFileSync as co,readdirSync as Md,rmSync as Fd,statSync as uo,symlinkSync as Ud,writeFileSync as qt}from"fs";import{dirname as
|
|
17
|
+
`,"utf-8");try{Od(Be,384)}catch{}}function N(e){let t=ao();if(t)return t;let n=Kt();if(!n)return null;if(!e)return nt(n);let r=tr(e);return r&&Object.keys(n.sites??{}).length>0?nt(n.sites?.[r]):nt(n)}function $s(e){if(ao())return!0;let t=Kt();if(!t)return!1;let n=tr(e);return n?nt(t.sites?.[n])!==null:!1}function lo(e,t){let n=Kt()??{},r=tr(t),o={...n.sites??{}};r&&(o[r]=e),vs({...e,sites:Object.keys(o).length>0?o:void 0})}function Ss(e){let t=Kt();if(!t)return!1;let n=tr(e),r=Object.keys(t.sites??{}).length>0;if(!n||!r)try{return ys(Be),!0}catch{return!1}let o=t.sites?.[n];if(!o)return!1;let i={...t.sites};delete i[n];let s=Object.keys(i),a=t.website_token===o.website_token,l=nt(a?i[s[0]]:t);if(!l&&s.length===0)try{return ys(Be),!0}catch{return!1}return vs({...l??{},sites:s.length>0?i:void 0}),!0}function qe(){let e=Kt();return e?.sites?Object.keys(e.sites).sort():[]}var Nd=new Set(["co","com","net","org","ac","gov","edu"]);function jd(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&&Nd.has(n[n.length-2])?n.length-3:n.length-2;return n[Math.max(0,r)]||null}async function xs(e){let t=jd(e.domain);if(!t)return{status:"unavailable"};let n=(e.apiBase||O.BASE).replace(/\/$/,"");try{let r=await I(`${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 rt,lstatSync as Dd,mkdirSync as ot,readFileSync as co,readdirSync as Md,rmSync as Fd,statSync as uo,symlinkSync as Ud,writeFileSync as qt}from"fs";import{dirname as $t,join as Q,relative as po,sep as Bd}from"path";import{fileURLToPath as Gd}from"url";var Hd=$t(Gd(import.meta.url));function _s(){return Q(Hd,"skills")}function Wd(){let e=Q(_s(),"seoagent.md");if(rt(e))return co(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Cs(e,t){let n=[];if(!rt(e))return n;for(let r of Md(e,{withFileTypes:!0})){let o=Q(e,r.name),i=Q(t,r.name);r.isDirectory()?(ot(i,{recursive:!0}),n.push(...Cs(o,i))):r.isFile()&&(ot($t(i),{recursive:!0}),qt(i,co(o)),n.push(i))}return n}function Kd(e){let t=rt(Q(e,".agents"));return Q(e,t?Pe.AGENTS:Pe.CLAUDE)}function Es(e,t){let n=Kd(e),r=[];for(let[o,i]of Object.entries(t)){let s=Q(n,o);ot($t(s),{recursive:!0}),qt(s,i,"utf-8"),r.push(s)}return r}function St(e,t){let n=rt(Q(e,".agents")),r=Q(e,n?Pe.AGENTS:Pe.CLAUDE),o=Q(r,"SKILL.md");ot(r,{recursive:!0}),qt(o,t??Wd(),"utf-8");let i=Q(_s(),"references"),s=Q(r,"references"),a=[];try{rt(i)&&uo(i).isDirectory()&&(ot(s,{recursive:!0}),a=Cs(i,s).map(p=>po(r,p)))}catch{}let l=n?qd(e,r):void 0,c=zd(e,o),d=Yd(e,o);return{skillFile:o,referenceFiles:a,claudeSymlink:l,agentsMdPath:c,cursorRulePath:d}}function qd(e,t){let n=Q(e,Pe.CLAUDE),r=null;try{r=Dd(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{Fd(n,{force:!0})}catch{return}}try{ot($t(n),{recursive:!0});let o=po($t(n),t);return Ud(o,n,"dir"),n}catch{return}}var Vd="<!-- seoagent:skill -->";function Rs(e,t){return po(e,t).split(Bd).join("/")}function zd(e,t){let n=Q(e,"AGENTS.md"),r=Rs(e,t);try{let o="";if(rt(n)&&(!uo(n).isFile()||(o=co(n,"utf-8"),/seoagent/i.test(o))))return;let i=[Vd,"","## SEOAgent","","This repo uses SEOAgent \u2014 a persistent AI SEO agent. Its state lives in `.seoagent/`.","",`- At session start, read \`${r}\` \u2014 the working contract for all SEO tasks.`,"- Each session: run `seoagent sync`, then triage `.seoagent/inbox/` for pending actions.","- Run `seoagent ack <id>` after completing each inbox action.",""].join(`
|
|
18
18
|
`),s=o.length===0?i:o.endsWith(`
|
|
19
19
|
`)?`${o}
|
|
20
20
|
${i}`:`${o}
|
|
21
21
|
|
|
22
22
|
${i}`;return qt(n,s,"utf-8"),n}catch{return}}function Yd(e,t){let n=Rs(e,t);try{let r=Q(e,".cursor");if(!rt(r)||!uo(r).isDirectory())return;let o=Q(r,"rules","seoagent.mdc"),i=["---","description: SEOAgent \u2014 persistent AI SEO agent for audits, keywords, content, and technical SEO; state in .seoagent/","alwaysApply: false","---","","# SEOAgent","","This repo uses SEOAgent. Its state lives in `.seoagent/`.","",`- For any SEO, content, or search-ranking task, first read \`${n}\` \u2014 it is the working contract.`,"- Each session: run `seoagent sync`, then triage `.seoagent/inbox/` for pending actions.","- Run `seoagent ack <id>` after completing each inbox action.",""].join(`
|
|
23
|
-
`);return ot(
|
|
23
|
+
`);return ot($t(o),{recursive:!0}),qt(o,i,"utf-8"),o}catch{return}}import{existsSync as Vt,mkdirSync as fo,readFileSync as Jd,writeFileSync as nr}from"fs";import{dirname as Ps,join as it}from"path";var go=`command -v seoagent >/dev/null 2>&1 && seoagent sync --silent || npx -y ${Kn} sync --silent`,Is=60;function Os(e){let t=it(e,k);fo(t,{recursive:!0});let n=it(t,".gitignore");nr(n,es,"utf-8");let r=it(t,"content","images",".gitkeep");return fo(Ps(r),{recursive:!0}),Vt(r)||nr(r,"","utf-8"),n}var rr=["PostToolUse","SessionStart"];function or(e){if(!Vt(e))return{};try{let t=Jd(e,"utf-8");return JSON.parse(t)}catch{return{}}}function zt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function As(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(zt)?!1:(r.hooks.push({type:"command",command:go,timeout:Is}),!0)}function Xd(e){let t=!1;for(let n of rr){let r=e[n];if(Array.isArray(r))for(let o of r)for(let i of o.hooks??[])zt(i)&&(i.command!==go&&(i.command=go,t=!0),typeof i.timeout!="number"&&(i.timeout=Is,t=!0))}return t}function st(e){let t=it(e,Wt);fo(Ps(t),{recursive:!0});let n=or(t);n.hooks=n.hooks??{};let r=Xd(n.hooks),o=n.hooks.PostToolUse=n.hooks.PostToolUse??[],i=As(o,l=>(l.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),s=n.hooks.SessionStart=n.hooks.SessionStart??[],a=As(s,l=>(l.matcher??"")==="",()=>({hooks:[]}));return nr(t,JSON.stringify(n,null,2)+`
|
|
24
24
|
`,"utf-8"),{file:t,added:i||a,migrated:r}}function Ts(e){let t=it(e,Wt);if(!Vt(t))return 0;let n=or(t).hooks;if(!n)return 0;let r=0;for(let o of rr){let i=n[o];if(Array.isArray(i))for(let s of i)for(let a of s.hooks??[])zt(a)&&typeof a.timeout!="number"&&r++}return r}function Ls(e){let t=it(e,Wt);if(!Vt(t))return!1;let n=or(t).hooks;return n?rr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(zt))}):!1}function Ns(e){let t=it(e,Wt);if(!Vt(t))return{file:t,removed:!1};let n=or(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of rr){let s=r[i];if(!Array.isArray(s))continue;for(let l of s){let c=l.hooks.length;l.hooks=l.hooks.filter(d=>!zt(d)),l.hooks.length!==c&&(o=!0)}let a=s.filter(l=>l.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,nr(t,JSON.stringify(n,null,2)+`
|
|
25
25
|
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as js,mkdirSync as Qd,readFileSync as Zd,writeFileSync as ep}from"fs";import{join as tp}from"path";function Ds(e){return js(tp(e,k,"project.md"))}function Ms(){try{if(!js(zn))return[];let e=JSON.parse(Zd(zn,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function Fs(e){try{Qd(z,{recursive:!0}),ep(zn,JSON.stringify({projects:e},null,2)+`
|
|
26
26
|
`,"utf-8")}catch{}}function at(e){try{if(!Ds(e))return;let t=Ms();if(t.includes(e))return;t.push(e),Fs(t)}catch{}}function Us(){let e=Ms(),t=e.filter(Ds);return t.length!==e.length&&Fs(t),t}import{readFileSync as Hs,writeFileSync as sp,existsSync as ho}from"fs";import{join as yo}from"path";function mo(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=np(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=rp(o):i==="writing instructions"?t.writingInstructions=Bs(o):i==="reference urls"?t.referenceUrls=op(o):i==="topics to avoid"?t.topicsToAvoid=Bs(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function Gs(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(`
|
|
@@ -44,10 +44,10 @@ page), fill in:
|
|
|
44
44
|
|
|
45
45
|
Then show the owner the draft for review, and delete this comment.
|
|
46
46
|
-->
|
|
47
|
-
`;function St(e){let t=yo(e,".seoagent",wo);if(!ho(t))return null;let n=Hs(t,"utf-8");return mo(n)}function Ws(e,t){let n=yo(e,".seoagent",wo);return ho(n)?!1:(sp(n,ap+Gs({business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null}),"utf-8"),!0)}function ir(e){let t=yo(e,".seoagent",wo);if(!ho(t))return!0;try{return ve(Hs(t,"utf-8"))}catch{return!1}}import{existsSync as Yt,readFileSync as Ks,readdirSync as lp,statSync as qs}from"fs";import{join as lt}from"path";var cp=[{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 up(e){let t=lt(e,"package.json");if(!Yt(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Ks(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function dp(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 pp(e){let t={};for(let n of wt){let r=lt(e,n);if(Yt(r))try{let o=Ks(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 l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function fp(e,t){let n=lt(e,t.replace(/\/$/,""));if(!Yt(n))return!1;if(t.endsWith("/"))try{return qs(n).isDirectory()}catch{return!1}return!0}function gp(e){let t=["content","_posts","posts",lt("src","content")];for(let n of t){let r=lt(e,n);if(Yt(r))try{if(!qs(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of lp(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(lt(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 mp(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"}],n=[""],r=ro(e);r&&n.push(r);for(let o of n)for(let i of t){let s=o?`${o}/${i.marker}`:i.marker;if(Yt(lt(e,s)))return i.path}return null}function Vs(e){let t=[],{deps:n}=up(e),r=pp(e),o="none";for(let s of cp){let a=[];for(let l of Object.keys(n))if(dp(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(fp(e,l)){let c=l.endsWith("/")?"directory":"file";a.push({type:c,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=gp(e);s&&(o="mdx-local",t.push(s))}let i=mp(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as hp,readFileSync as yp}from"fs";import{join as wp}from"path";var zs=["openai","fal","replicate"],xt={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function bp(e){let t={};if(!hp(e))return t;let n=yp(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 Ys(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 wt){let o=wp(e,r),i=bp(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 Ve(e){let t=[].concat(...zs.map(a=>xt[a])),n=Ys(e,t),r=[];for(let a of zs)xt[a].some(l=>n.found[l])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=xt[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 Js(e,t){let n=Ys(e,xt[t]);for(let r of xt[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Xs(){return xt}import{existsSync as ct,readFileSync as bo}from"fs";import{join as ut}from"path";function Qs(e){try{return new URL(e).hostname}catch{return e}}function Zs(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 kp(e){for(let t of wt){let n=ut(e,t);if(!ct(n))continue;let r=bo(n,"utf-8");for(let o of Ji){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Qs(s);if(Zs(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function vp(e){let t=ut(e,"package.json");if(!ct(t))return null;try{let n=JSON.parse(bo(t,"utf-8"));if(!n.homepage)return null;let r=Qs(n.homepage);return Zs(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function ea(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ct(ut(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=kp(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=vp(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=ut(e,"package.json"),s=null;if(ct(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(bo(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),c=(...d)=>d.some(p=>l.includes(p));if(c("@shopify/hydrogen","@shopify/polaris")||ct(ut(e,"shopify.config.js"))||ct(ut(e,"shopify.config.ts"))){s="product";let d=c("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ct(ut(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=c("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=c("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),f=c("next");d&&(f||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:f?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&c("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:c("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 Rp,readFileSync as $o,readdirSync as ra,statSync as Ap}from"fs";import{join as ae,sep as Pp}from"path";var $p=[/^\/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,/-(?:onboarding|login|logout|signin|sign-in|signup|sign-up|dashboard|checkout|account)$/i];function Ne(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,'"').trim();o&&t.push(o)}return t}function Sp(e){let t=[],n=/<lastmod>\s*([^<\s][^<]*?)\s*<\/lastmod>/gi,r;for(;(r=n.exec(e))!==null;)t.push(r[1].trim());return t}var xp=10,ta=.9;function _p(e,t){if(t<xp||e.length<t*ta)return null;let n=new Map;for(let r of e)n.set(r,(n.get(r)||0)+1);for(let[r,o]of n)if(o>=t*ta)return r;return null}function L(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 de(e){return $p.some(t=>t.test(e))}function Cp(e){return e.filter(t=>de(L(t)))}function Ep(e,t){let n=new Set(e.map(L)),r=[],o=new Set;for(let i of t){let s=L(i);de(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function Jt(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function na(e){let t=e.sitemapUrl||Jt(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,lastmods:[],uniformLastmod:null,issues:n},o="";try{let i=await I(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=Ne(o),r.lastmods=Sp(o),r.hasLastmod=r.lastmods.length>0,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=Cp(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(L).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.uniformLastmod=_p(r.lastmods,r.urls.length),r.uniformLastmod?n.push({level:"warning",message:`Every URL carries the same <lastmod> (${r.uniformLastmod}) \u2014 that is the sitemap's own build time, not a content date. Google discounts <lastmod> for the WHOLE sitemap when it looks generated, including pages whose dates are real. Emit a per-page date where you have one and omit <lastmod> everywhere else.`}):r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates. That is fine \u2014 omitting them is honest. Add a per-page date only where you have a real one (CMS updatedAt, file mtime); a single bulk date on every URL is worse than none."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=Ep(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 oa=["tsx","jsx","js","mdx","md"],Ip=["astro","md","mdx"],Op=5e3,Tp=2e3;function $e(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=sa(i);if(l===null){r++;return}let c=n.get(l);if(c){c.in_sitemap=c.in_sitemap||a,c.source.includes(s)||(c.source+=`, ${s}`);return}n.set(l,{route:l,url:la(t,l),in_sitemap:a,source:s})};for(let i of jp(e))Np(i,o);return{pages:[...n.values()].filter(i=>!de(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function ia(e,t,n){let r={checked:!1,liveCount:0,flipped:0,added:0},o=[];try{let c=await I(Jt(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!c.ok)return r;o=Ne(await c.text())}catch{return r}if(o.length===0)return r;let i=new Set(o.map(L)),s=0;for(let c of e)!c.in_sitemap&&i.has(L(c.url||c.route))&&(c.in_sitemap=!0,s++,c.source.includes("live-sitemap")||(c.source+=", live-sitemap"));let a=new Set(e.map(c=>L(c.url||c.route))),l=0;for(let c of o){if(l>=Tp)break;let d=Lp(c,t);d===null||a.has(d)||(a.add(d),e.push({route:d,url:la(t,d),in_sitemap:!0,source:"live-sitemap"}),l++)}return l>0&&e.sort((c,d)=>c.route.localeCompare(d.route)),{checked:!0,liveCount:o.length,flipped:s,added:l}}function Lp(e,t){let n=t.replace(/^https?:\/\//,"").replace(/\/.*$/,"").toLowerCase().replace(/^www\./,""),r;try{r=new URL(e)}catch{return null}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.toLowerCase().replace(/^www\./,"")!==n)return null;let o=L(e);return/\.xml$/i.test(o)||de(o)?null:sa(o)}function Np(e,t){for(let n of["app",ae("src","app")]){let r=ae(e,n);if(Xt(r))for(let o of ko(r)){let i=vo(r,o),s=i[i.length-1];Hp(s)&&(i.some(a=>a.startsWith("@"))||t(Fp(i.slice(0,-1)),"app router"))}}for(let n of["pages",ae("src","pages")]){let r=ae(e,n);if(Xt(r))for(let o of ko(r)){let i=vo(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=So(s),l=oa.includes(a),c=Ip.includes(a);if(!l&&!c)continue;let d=sr(s);Wp(d)||t(Up(i),c?"astro":"pages router")}}for(let n of[".","public"]){let r=ae(e,n);if(Xt(r))for(let o of ko(r,n==="."?1:1/0)){let i=vo(r,o),s=i[i.length-1];So(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Bp(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=ae(e,...n.split("/"));if(Rp(r)){for(let o of Kp(r)){let i=Gp(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function jp(e){let t=[e],n=new Set([e]);for(let r of Dp(e))for(let o of Mp(e,r))n.has(o)||(n.add(o),t.push(o));return t}function Dp(e){let t=[];try{let n=$o(ae(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($o(ae(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 Mp(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=ae(e,...n.split("/").filter(Boolean));return Xt(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=ae(e,...o.split("/").filter(Boolean));if(!Xt(i))return[];let s=[];try{for(let a of ra(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!aa.has(a.name)&&(s.push(ae(i,a.name)),s.length>=200))break}catch{}return s}function sa(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Fp(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Up(e){let t=[...e],n=sr(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Bp(e){let t=[...e],n=sr(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Gp(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Hp(e){return sr(e)==="page"&&oa.includes(So(e))}function Wp(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Kp(e){try{let t=$o(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 aa=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Xt(e){try{return Ap(e).isDirectory()}catch{return!1}}function*ko(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=ra(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Op)return;if(a.name.startsWith("."))continue;let l=ae(o,a.name);if(a.isDirectory()){if(aa.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function vo(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Pp).filter(Boolean)}function So(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function sr(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function la(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as qp,mkdirSync as Vp,readFileSync as zp,writeFileSync as Yp}from"fs";import{join as xo}from"path";var Qt="pages.md",ar="pages-discovered.md";function Jp(e){return Ge(xo(e,k,Qt))?.data?.generated===!0}function Xp(e){let t=Jp(e);return{rel:t?ar:Qt,cloudOwned:t}}function ca(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 lr(e,t,n){let r=Xp(e),o=xo(e,k,r.rel),i=qp(o),s=i?cr(o):new Map;if(t.length===0&&!i)return{wrote:!1,added:0,total:0,merged:!1,file:r.rel};let a=new Map(s),l=0,c=!1;for(let p of t){let f=da(p.url),g=n?.get(p.url),h=a.get(f);if(h)p.in_sitemap&&h.in_sitemap!=="yes"&&(h.in_sitemap="yes",c=!0),g&&ca(h,g)&&(c=!0);else{let y={url:f,in_sitemap:p.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:da(p.source)};g&&ca(y,g),a.set(f,y),l++,c=!0}}if(i&&!c)return{wrote:!1,added:0,total:a.size,merged:!0,file:r.rel};let d=[...a.values()];return Vp(xo(e,k),{recursive:!0}),Yp(o,Qp(d,r.cloudOwned),"utf-8"),{wrote:!0,added:l,total:d.length,merged:i,file:r.rel}}function Qp(e,t){let n=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
|
|
47
|
+
`;function xt(e){let t=yo(e,".seoagent",wo);if(!ho(t))return null;let n=Hs(t,"utf-8");return mo(n)}function Ws(e,t){let n=yo(e,".seoagent",wo);return ho(n)?!1:(sp(n,ap+Gs({business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null}),"utf-8"),!0)}function ir(e){let t=yo(e,".seoagent",wo);if(!ho(t))return!0;try{return ve(Hs(t,"utf-8"))}catch{return!1}}import{existsSync as Yt,readFileSync as Ks,readdirSync as lp,statSync as qs}from"fs";import{join as lt}from"path";var cp=[{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 up(e){let t=lt(e,"package.json");if(!Yt(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Ks(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function dp(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 pp(e){let t={};for(let n of bt){let r=lt(e,n);if(Yt(r))try{let o=Ks(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 l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function fp(e,t){let n=lt(e,t.replace(/\/$/,""));if(!Yt(n))return!1;if(t.endsWith("/"))try{return qs(n).isDirectory()}catch{return!1}return!0}function gp(e){let t=["content","_posts","posts",lt("src","content")];for(let n of t){let r=lt(e,n);if(Yt(r))try{if(!qs(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of lp(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(lt(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 mp(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"}],n=[""],r=ro(e);r&&n.push(r);for(let o of n)for(let i of t){let s=o?`${o}/${i.marker}`:i.marker;if(Yt(lt(e,s)))return i.path}return null}function Vs(e){let t=[],{deps:n}=up(e),r=pp(e),o="none";for(let s of cp){let a=[];for(let l of Object.keys(n))if(dp(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(fp(e,l)){let c=l.endsWith("/")?"directory":"file";a.push({type:c,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=gp(e);s&&(o="mdx-local",t.push(s))}let i=mp(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as hp,readFileSync as yp}from"fs";import{join as wp}from"path";var zs=["openai","fal","replicate"],_t={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function bp(e){let t={};if(!hp(e))return t;let n=yp(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 Ys(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 bt){let o=wp(e,r),i=bp(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 Ve(e){let t=[].concat(...zs.map(a=>_t[a])),n=Ys(e,t),r=[];for(let a of zs)_t[a].some(l=>n.found[l])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=_t[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 Js(e,t){let n=Ys(e,_t[t]);for(let r of _t[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Xs(){return _t}import{existsSync as ct,readFileSync as bo}from"fs";import{join as ut}from"path";function Qs(e){try{return new URL(e).hostname}catch{return e}}function Zs(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 kp(e){for(let t of bt){let n=ut(e,t);if(!ct(n))continue;let r=bo(n,"utf-8");for(let o of Ji){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Qs(s);if(Zs(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function vp(e){let t=ut(e,"package.json");if(!ct(t))return null;try{let n=JSON.parse(bo(t,"utf-8"));if(!n.homepage)return null;let r=Qs(n.homepage);return Zs(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function ea(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ct(ut(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=kp(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=vp(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=ut(e,"package.json"),s=null;if(ct(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(bo(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),c=(...d)=>d.some(p=>l.includes(p));if(c("@shopify/hydrogen","@shopify/polaris")||ct(ut(e,"shopify.config.js"))||ct(ut(e,"shopify.config.ts"))){s="product";let d=c("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ct(ut(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=c("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=c("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),f=c("next");d&&(f||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:f?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&c("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:c("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 Rp,readFileSync as $o,readdirSync as ra,statSync as Ap}from"fs";import{join as ae,sep as Pp}from"path";var $p=[/^\/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,/-(?:onboarding|login|logout|signin|sign-in|signup|sign-up|dashboard|checkout|account)$/i];function Ne(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,'"').trim();o&&t.push(o)}return t}function Sp(e){let t=[],n=/<lastmod>\s*([^<\s][^<]*?)\s*<\/lastmod>/gi,r;for(;(r=n.exec(e))!==null;)t.push(r[1].trim());return t}var xp=10,ta=.9;function _p(e,t){if(t<xp||e.length<t*ta)return null;let n=new Map;for(let r of e)n.set(r,(n.get(r)||0)+1);for(let[r,o]of n)if(o>=t*ta)return r;return null}function L(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 de(e){return $p.some(t=>t.test(e))}function Cp(e){return e.filter(t=>de(L(t)))}function Ep(e,t){let n=new Set(e.map(L)),r=[],o=new Set;for(let i of t){let s=L(i);de(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function Jt(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function na(e){let t=e.sitemapUrl||Jt(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,lastmods:[],uniformLastmod:null,issues:n},o="";try{let i=await I(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=Ne(o),r.lastmods=Sp(o),r.hasLastmod=r.lastmods.length>0,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=Cp(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(L).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.uniformLastmod=_p(r.lastmods,r.urls.length),r.uniformLastmod?n.push({level:"warning",message:`Every URL carries the same <lastmod> (${r.uniformLastmod}) \u2014 that is the sitemap's own build time, not a content date. Google discounts <lastmod> for the WHOLE sitemap when it looks generated, including pages whose dates are real. Emit a per-page date where you have one and omit <lastmod> everywhere else.`}):r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates. That is fine \u2014 omitting them is honest. Add a per-page date only where you have a real one (CMS updatedAt, file mtime); a single bulk date on every URL is worse than none."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=Ep(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 oa=["tsx","jsx","js","mdx","md"],Ip=["astro","md","mdx"],Op=5e3,Tp=2e3;function $e(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=sa(i);if(l===null){r++;return}let c=n.get(l);if(c){c.in_sitemap=c.in_sitemap||a,c.source.includes(s)||(c.source+=`, ${s}`);return}n.set(l,{route:l,url:la(t,l),in_sitemap:a,source:s})};for(let i of jp(e))Np(i,o);return{pages:[...n.values()].filter(i=>!de(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function ia(e,t,n){let r={checked:!1,liveCount:0,flipped:0,added:0},o=[];try{let c=await I(Jt(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!c.ok)return r;o=Ne(await c.text())}catch{return r}if(o.length===0)return r;let i=new Set(o.map(L)),s=0;for(let c of e)!c.in_sitemap&&i.has(L(c.url||c.route))&&(c.in_sitemap=!0,s++,c.source.includes("live-sitemap")||(c.source+=", live-sitemap"));let a=new Set(e.map(c=>L(c.url||c.route))),l=0;for(let c of o){if(l>=Tp)break;let d=Lp(c,t);d===null||a.has(d)||(a.add(d),e.push({route:d,url:la(t,d),in_sitemap:!0,source:"live-sitemap"}),l++)}return l>0&&e.sort((c,d)=>c.route.localeCompare(d.route)),{checked:!0,liveCount:o.length,flipped:s,added:l}}function Lp(e,t){let n=t.replace(/^https?:\/\//,"").replace(/\/.*$/,"").toLowerCase().replace(/^www\./,""),r;try{r=new URL(e)}catch{return null}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.toLowerCase().replace(/^www\./,"")!==n)return null;let o=L(e);return/\.xml$/i.test(o)||de(o)?null:sa(o)}function Np(e,t){for(let n of["app",ae("src","app")]){let r=ae(e,n);if(Xt(r))for(let o of ko(r)){let i=vo(r,o),s=i[i.length-1];Hp(s)&&(i.some(a=>a.startsWith("@"))||t(Fp(i.slice(0,-1)),"app router"))}}for(let n of["pages",ae("src","pages")]){let r=ae(e,n);if(Xt(r))for(let o of ko(r)){let i=vo(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=So(s),l=oa.includes(a),c=Ip.includes(a);if(!l&&!c)continue;let d=sr(s);Wp(d)||t(Up(i),c?"astro":"pages router")}}for(let n of[".","public"]){let r=ae(e,n);if(Xt(r))for(let o of ko(r,n==="."?1:1/0)){let i=vo(r,o),s=i[i.length-1];So(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Bp(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=ae(e,...n.split("/"));if(Rp(r)){for(let o of Kp(r)){let i=Gp(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function jp(e){let t=[e],n=new Set([e]);for(let r of Dp(e))for(let o of Mp(e,r))n.has(o)||(n.add(o),t.push(o));return t}function Dp(e){let t=[];try{let n=$o(ae(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($o(ae(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 Mp(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=ae(e,...n.split("/").filter(Boolean));return Xt(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=ae(e,...o.split("/").filter(Boolean));if(!Xt(i))return[];let s=[];try{for(let a of ra(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!aa.has(a.name)&&(s.push(ae(i,a.name)),s.length>=200))break}catch{}return s}function sa(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Fp(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Up(e){let t=[...e],n=sr(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Bp(e){let t=[...e],n=sr(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Gp(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Hp(e){return sr(e)==="page"&&oa.includes(So(e))}function Wp(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Kp(e){try{let t=$o(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 aa=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Xt(e){try{return Ap(e).isDirectory()}catch{return!1}}function*ko(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=ra(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Op)return;if(a.name.startsWith("."))continue;let l=ae(o,a.name);if(a.isDirectory()){if(aa.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function vo(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Pp).filter(Boolean)}function So(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function sr(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function la(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as qp,mkdirSync as Vp,readFileSync as zp,writeFileSync as Yp}from"fs";import{join as xo}from"path";var Qt="pages.md",ar="pages-discovered.md";function Jp(e){return Ge(xo(e,k,Qt))?.data?.generated===!0}function Xp(e){let t=Jp(e);return{rel:t?ar:Qt,cloudOwned:t}}function ca(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 lr(e,t,n){let r=Xp(e),o=xo(e,k,r.rel),i=qp(o),s=i?cr(o):new Map;if(t.length===0&&!i)return{wrote:!1,added:0,total:0,merged:!1,file:r.rel};let a=new Map(s),l=0,c=!1;for(let p of t){let f=da(p.url),g=n?.get(p.url),h=a.get(f);if(h)p.in_sitemap&&h.in_sitemap!=="yes"&&(h.in_sitemap="yes",c=!0),g&&ca(h,g)&&(c=!0);else{let y={url:f,in_sitemap:p.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:da(p.source)};g&&ca(y,g),a.set(f,y),l++,c=!0}}if(i&&!c)return{wrote:!1,added:0,total:a.size,merged:!0,file:r.rel};let d=[...a.values()];return Vp(xo(e,k),{recursive:!0}),Yp(o,Qp(d,r.cloudOwned),"utf-8"),{wrote:!0,added:l,total:d.length,merged:i,file:r.rel}}function Qp(e,t){let n=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
|
|
48
48
|
`),r=[t?"# Pages discovered in the codebase":"# Pages","",t?"Inventory of pages the codebase scan found. `pages.md` is now a cloud":"Inventory of pages discovered in your codebase. Every `seoagent sync`,",t?"projection (GSC traffic per page, edited in the dashboard), so the scan":"`seoagent init` and `seoagent refresh` re-scan and merge in newly-added",t?"writes here instead; every `seoagent sync` re-scans, merges in new pages":"pages without touching rows you or the audit have edited. `In sitemap` is",t?"and pushes them so the cloud inventory stays current. `In sitemap` is":"refreshed from the live sitemap; `Status` / `Rendered` / `Word count` are",t?"refreshed from the live sitemap; `Status` / `Rendered` / `Word count` are":"filled by `seoagent refresh --crawl` (a live fetch of each page). This file",t?"filled by `seoagent refresh --crawl` (a live fetch of each page).":"syncs to the cloud on login."].join(`
|
|
49
49
|
`),o="| URL | In sitemap | In nav | Status | Rendered | Word count | Notes |",i="|---|---|---|---|---|---|---|",s=e.map(a=>`| ${a.url} | ${a.in_sitemap} | ${a.in_nav} | ${a.status} | ${a.rendered} | ${a.word_count} | ${a.notes} |`);return[n,"",r,"",o,i,...s,""].join(`
|
|
50
|
-
`)}function cr(e){let t=new Map,n;try{n=zp(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!_o(r[o])||!Zp(r[o+1]))continue;let i=ua(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&&_o(r[a]);a++){let l=ua(r[a]),c=(l[s.url]??"").trim();!c||c==="\u2014"||c==="-"||t.set(c,{url:c,in_sitemap:
|
|
50
|
+
`)}function cr(e){let t=new Map,n;try{n=zp(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!_o(r[o])||!Zp(r[o+1]))continue;let i=ua(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&&_o(r[a]);a++){let l=ua(r[a]),c=(l[s.url]??"").trim();!c||c==="\u2014"||c==="-"||t.set(c,{url:c,in_sitemap:Ct(l,s.in_sitemap),in_nav:Ct(l,s.in_nav),status:Ct(l,s.status),rendered:Ct(l,s.rendered),word_count:Ct(l,s.word_count),notes:Ct(l,s.notes)})}break}return t}function Ct(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function _o(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function Zp(e){let t=e.trim();return _o(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function ua(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function da(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{existsSync as ef,readFileSync as tf,statSync as nf}from"fs";import{dirname as Co,isAbsolute as rf,join as of,resolve as Eo,sep as Zt}from"path";var sf={isWorktree:!1,mainRoot:null,reason:null};function pa(e){let t=of(e,".git");try{if(ef(t)&&nf(t).isFile()){let i=tf(t,"utf-8").match(/^gitdir:\s*(.+)\s*$/m),s=null;if(i){let a=rf(i[1])?i[1]:Eo(e,i[1]),l=Co(a),c=Co(l);l.endsWith(`${Zt}worktrees`)&&c.endsWith(`${Zt}.git`)&&(s=Co(c))}return{isWorktree:!0,mainRoot:s,reason:"gitfile"}}}catch{}let n=`${Zt}.claude${Zt}worktrees${Zt}`,r=Eo(e).indexOf(n);return r>=0?{isWorktree:!0,mainRoot:Eo(e).slice(0,r),reason:"agent-worktree-path"}:sf}import{existsSync as ze,mkdirSync as ur,readdirSync as af,readFileSync as ga,statSync as q$,writeFileSync as fa}from"fs";import{dirname as lf,join as je,relative as ma,resolve as cf,sep as uf}from"path";var Et="okf";function Rt(e){return je(e,k,Et)}var df=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function dr(e){let t=[];for(let n of af(e,{withFileTypes:!0})){let r=je(e,n.name);n.isDirectory()?t.push(...dr(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function pf(e){let t=[],n=/\[[^\]]*\]\(([^)]+)\)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim().split(/\s+/)[0];o&&(/^[a-z][a-z0-9+.-]*:/i.test(o)||o.startsWith("#")||t.push(o))}return t}function pr(e){let t=[],n=[];if(!ze(e))return{ok:!1,fileCount:0,errors:[{file:Et,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=dr(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Et,message:"OKF directory exists but contains no markdown files."}],warnings:[]};ze(je(e,"index.md"))||n.push({file:Et,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=ma(e,i),a;try{a=ue(ga(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let l=a.data.type;(l==null||String(l).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let c=a.data.timestamp;c!=null&&c!==""&&!df.test(String(c))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(c)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of pf(a.body)){let f=p.split("#")[0];if(!f)continue;let g=cf(lf(i),f);ze(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 fr(e){let t=Rt(e);if(!ze(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:dr(t).length}}catch{return{exists:!0,fileCount:0}}}var ff=["_Describe the business in","_Link concept files here","_Link FAQ files here","_Link article files here"];function ha(e){let t=je(e,"index.md");if(!ze(t))return!0;let n;try{n=ga(t,"utf-8")}catch{return!0}return ff.some(r=>n.includes(r))}function ya(e){if(!ze(e))return[];try{return dr(e).map(t=>ma(e,t).split(uf).join("/")).sort()}catch{return[]}}function gr(e,t){let n=Rt(e);ur(n,{recursive:!0}),ur(je(n,"concepts"),{recursive:!0}),ur(je(n,"faqs"),{recursive:!0}),ur(je(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=je(n,"index.md");ze(i)||(fa(i,`---
|
|
51
51
|
type: Organization
|
|
52
52
|
title: ${o}
|
|
53
53
|
description: Knowledge bundle describing ${o} for AI agents and answer engines.
|
|
@@ -83,14 +83,14 @@ description: Chronological history of changes to this OKF bundle.
|
|
|
83
83
|
# Change log
|
|
84
84
|
|
|
85
85
|
- Bundle scaffolded.
|
|
86
|
-
`,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}import{log as Rt}from"@clack/prompts";var u={info:e=>Rt.info(e),warn:e=>Rt.warn(e),error:e=>Rt.error(e),success:e=>Rt.success(e),step:e=>Rt.step(e),message:e=>Rt.message(e)};function S(e,t,n,r=n){e?e.stop(r):u[t](n)}import{randomBytes as mf}from"crypto";import{isCancel as hf,spinner as xa,text as yf}from"@clack/prompts";import pe from"picocolors";import{exec as gf}from"child_process";function mr(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;gf(t,()=>{})}function wa(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 ka=/^sa_[0-9a-f]{24}$/;function ba(e){switch(e){case"code_not_found":return"That setup code was not recognized: it was never issued. Codes cannot be guessed or retyped from memory; copy one exactly from seoagent.com/grok. A scheduled run on a fresh machine needs the SEOAGENT_AUTH secret (`seoagent whoami --env` on the bound machine), not a setup code.";case"code_already_used":return"That setup code has already been used \u2014 each code works exactly once. Generate a new one at seoagent.com/grok.";case"code_revoked":return"That setup code was replaced by a newer one. Use the latest code, or generate a new one at seoagent.com/grok.";case"code_expired":return"That setup code has expired. Generate a new one at seoagent.com/grok.";case"setup_codes_unavailable":return"Setup codes are not enabled on this server yet. Run `seoagent login` (browser flow) instead.";case"domain_required":return"This code has no site attached and the project has no domain. Run `seoagent init` first so the project knows its domain.";default:return typeof e=="string"&&e?`Login failed: ${e}`:"Login failed."}}function va(e,t){let n=t&&typeof t=="object"?t:null;if(e>=500)return e===503&&n?.error==="setup_codes_unavailable"?{status:"error",terminal:!0,message:ba(n.error)}:{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:ba(n?.error)};if(!n)return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof 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{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var wf=1500,bf=300*1e3,kf=3,vf=2e3;function hr(e,t){if(ke())return;let n=Le(e);n&&tt({installId:n,event:t,cliVersion:C})}function $f(){return mf(16).toString("hex")}function Sf(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function $a(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 xf(e,t,n){if(!e||e.website_token===t)return null;try{let r=await n(e);return r.verdict!=="unverified"?r.cloudDomain:null}catch{return null}}async function _f(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)}),o=null;try{o=await r.json()}catch{}return wa(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function _a(e){return new Promise(t=>setTimeout(t,e))}async function Ca(e,t,n,r){let o=N(),i=await xf(o,e.website_token,c=>Ke({apiBase:c.api_base,authHeader:`Bearer ${c.user_token}:${c.website_token}`,localDomain:""}));i&&o&&lo(o,i),lo({user_token:e.user_token,website_token:e.website_token,api_base:t},e.domain||n);let s=e.email&&e.domain?`Logged in as ${e.email} (${e.domain}). Future SEO work in this repo will sync to your dashboard.`:e.email?`Logged in as ${e.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.",a=e.email&&e.domain?`Logged in as ${pe.bold(e.email)} (${pe.cyan(e.domain)}).`:e.email?`Logged in as ${pe.bold(e.email)}.`:"Logged in.";S(r,"success",s,pe.green(a)),r&&u.info("Future SEO work in this repo will sync to your dashboard.");let l=qe().filter(c=>c!==We(e.domain||n));l.length>0&&u.info(`Also logged in to: ${l.join(", ")}. Each project auto-selects its own site \u2014 no need to log out first.`)}function Cf(e,t,n){return{code:e,...t&&t!=="unknown"?{domain:t}:{},...n?{install_id:n.installId,cli_version:n.cliVersion,platform:process.platform}:{}}}function Ro(e){if(ke())return null;let t=Le(e);return t?{installId:t,cliVersion:C}:null}async function Ef(e,t,n,r){try{let o=await fetch(`${e}/api/cli/auth/redeem`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(Cf(t,n,r)),signal:AbortSignal.timeout(1e4)}),i=null;try{i=await o.json()}catch{}return va(o.status,i)}catch(o){return{status:"error",terminal:!1,message:o.message||"network error"}}}var Rf="Scheduled runs on a fresh machine: store the output of `seoagent whoami --env` as the task's SEOAGENT_AUTH secret. A setup code works once and cannot be guessed; never reuse or invent one.";function Af(e){return e!=="ready"}function Pf(e,t,n){if(!e||!n||t&&t!=="unknown")return!1;try{if(!Y(e,{domain:n}))return!1}catch{return!1}return u.info(`Saved domain: ${n} \u2192 .seoagent/project.md (from the setup code).`),!0}async function Ao(e,t,n,r,o){if(!ka.test(e))return u.warn("That does not look like a setup code (expected `sa_` + 24 hex characters). Generate one at seoagent.com/grok."),"invalid";let s=!!process.stdout.isTTY?xa():null;s?.start(pe.dim("Redeeming setup code\u2026"));let a="network error";for(let l=0;l<kf;l++){l>0&&await _a(vf);let c=await Ef(t,e,n,r);if(c.status==="ready")return await Ca(c,t,n,s),Pf(o,n,c.domain),u.info(Rf),"ready";if(c.terminal)return S(s,"warn",c.message,pe.red(c.message)),"rejected";a=c.message}return S(s,"warn",`Could not reach the server (${a}). Check your connection and run \`${m("login")} --code <code>\` again.`,pe.yellow("Could not reach the server.")),s&&u.warn(`Run \`${m("login")} --code <code>\` again to retry.`),"unreachable"}function Po(e){return e&&e!=="unknown"?$s(e):!!N()}function Sa(){return`Next: run \`${m("sync")}\` in this repo \u2014 it pulls your strategy, briefs and inbox into .seoagent/. Nothing syncs until it runs.`}async function en(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||O.BASE||Ie).replace(/\/$/,""),o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let h=await yf({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(w){if(!String(w??"").trim())return"A site URL is required.";if(!$a(String(w)))return"Please enter a valid domain like `example.com`."}});if(hf(h)){u.warn("Login cancelled.");return}let y=$a(String(h));if(y){o=y;try{Y(t,{domain:y}),u.success(`Saved domain: ${y} \u2192 .seoagent/project.md`)}catch{}}}let i=(e.code??process.env.SEOAGENT_SETUP_CODE??"").trim(),s=o&&o!=="unknown";if(i&&!s?!1:Po(o)){let h=s?` for ${o}`:"";u.info(`Already logged in${h}. To switch accounts${h}, run \`${m("logout")}\` first.`);return}if(i){let h=await Ao(i,r,o,Ro(t),t);Af(h)?process.exitCode=1:u.info(Sa());return}let l=$f(),c=Sf(r,l,o);u.message("Opening seoagent.com to connect this CLI to your account..."),u.info(`If the browser does not open, visit: ${c}`),mr(c),u.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let p=!!process.stdout.isTTY?xa():null;p?.start(pe.dim("Waiting for browser confirmation\u2026"));let f=Date.now()+bf,g=!0;for(;Date.now()<f;){g||await _a(wf),g=!1;let h=await _f(r,l);if(h.status==="ready"){await Ca(h,r,o,p),hr(t,"login_browser_ok"),u.info(Sa());return}if(h.status==="expired"){hr(t,"login_browser_expired"),S(p,"warn",`Session expired. Run \`${m("login")}\` again.`,pe.red("Session expired.")),p&&u.warn(`Run \`${m("login")}\` again.`);return}if(h.status==="error"){if(h.terminal){S(p,"warn",`Login failed: ${h.message}. Run \`${m("login")}\` again.`,pe.red(`Login failed: ${h.message}.`)),p&&u.warn(`Run \`${m("login")}\` again.`),hr(t,"login_browser_failed");return}continue}}S(p,"warn",`Login timed out. Run \`${m("login")}\` again to retry.`,pe.yellow("Login timed out.")),p&&u.warn(`Run \`${m("login")}\` again to retry.`),hr(t,"login_browser_timeout")}function tn(e={}){let t=e.all?null:_(process.cwd()),n=!e.all&&t?.domain&&t.domain!=="unknown"?t.domain:null;if(!Ss(e.all?null:n)){u.info(n?`You were not logged in for ${n}.`:"You were not logged in.");return}u.success(n?`Logged out of ${n}.`:"Logged out.");let o=qe();o.length>0&&u.info(`Still logged in to: ${o.join(", ")}. Run \`${m("logout")} --all\` to log out of everything.`)}function yr(e,t=process.env){return(e.code??t.SEOAGENT_SETUP_CODE??"").trim()}function Lf(e,t=m("init")){return e?`${t} --code ${e}`:t}async function Oa(e,t,n){if(!n)return"none";let r=t!==De;if(r&&Po(t))return u.info(`Already logged in for ${t} \u2014 setup code not needed, skipping it.`),"already";let o=(O.BASE||Ie).replace(/\/$/,"");return Ao(n,o,r?t:null,Ro(e),e)}var Pa=[{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"}],De="unknown",Nf=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function jf(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 wr(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Nf.has(t)?t:null}function Ta(e,t){t.agentsMdPath&&u.info(`Added a SEOAgent section to ${At(e,t.agentsMdPath)} so agents that read it (Codex, others) find the skill.`),t.cursorRulePath&&u.info(`Wrote ${At(e,t.cursorRulePath)} so Cursor agents find the skill.`)}async function nn(e={}){let t=process.cwd();if(ds(t)){let l=_(t),c=$t(t);st(t),Y(t,{skill_version:C}),at(t);let d=At(t,c.skillFile),p=c.claudeSymlink?` (symlinked at ${At(t,c.claudeSymlink)})`:"",f=l?.skill_version&&l.skill_version!==C?`${l.skill_version} \u2192 ${C}`:C;if(u.success(`Refreshed the SEOAgent skill (${f}).`),u.info("Your `.seoagent/` knowledge was left untouched."),u.info(`Skill at ${d}${p} \u2014 agents read this file at session start.`),Ta(t,c),u.info(`Run \`${m("status")}\` to see your project, or \`${m("uninstall")}\` to start fresh.`),!ke()){let h=Le(t);h&&await tt({installId:h,event:"reinit",cliVersion:C})&&u.info(so)}let g=await Oa(t,l?.domain??De,yr(e));(g==="rejected"||g==="unreachable"||g==="invalid")&&u.warn(Df());return}let n=!!e.yes||!process.stdin.isTTY,r=pa(t);if(r.isWorktree&&!e.allowWorktree){let l=Lf(yr(e)),c=r.mainRoot?`cd ${r.mainRoot} && ${l}`:`run ${l} from the main repository root`;n&&(u.warn("This directory is a temporary git worktree \u2014 a `.seoagent/` created here is deleted with the worktree, and images/un-synced edits cannot be recovered from the cloud."),u.info(`Init at the main checkout instead: ${c}`),u.info("To init here anyway (not recommended), pass --allow-worktree."),process.exit(1)),Ea("SEOAgent \u2014 AI SEO Agent");let d=await Aa({message:"This looks like a temporary git worktree \u2014 .seoagent/ created here is lost when the worktree is removed. Create it here anyway?",initialValue:!1});(dt(d)||!d)&&(pt(`Good call. ${c}`),process.exit(0))}else n||Ea("SEOAgent \u2014 AI SEO Agent");let o=ea(t,l=>u.step(l)),i=()=>{if(o.evidence.length!==0){u.info("Inferred from your project:");for(let l of o.evidence)u.info(` \u2022 ${jf(l)}`)}},s=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||o.domain||null,a=wr(e.siteType)||wr(process.env.SEOAGENT_SITE_TYPE)||o.siteType||null;if(n){e.siteType?.trim()&&wr(e.siteType)===null&&(u.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&wr(process.env.SEOAGENT_SITE_TYPE)===null&&(u.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),i(),s||(u.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),s=De),a||(a="unknown"),await Ia(t,s,a,yr(e));return}if(i(),!s){let l=await Ra({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});dt(l)&&(pt("Cancelled"),process.exit(0)),s=String(l)}if(!a){let l=await Io({message:"What kind of site is this?",options:[...Pa]});dt(l)&&(pt("Cancelled"),process.exit(0)),a=l}for(;;){let l=await Aa({message:`Create .seoagent for ${s} (${a})?`});if(dt(l)&&(pt("Cancelled"),process.exit(0)),l)break;let c=await Io({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((dt(c)||c==="abort")&&(pt("Cancelled"),process.exit(0)),c==="domain"){let d=await Ra({message:"Website domain",placeholder:"example.com",validate:p=>p.trim()?void 0:"Domain is required"});dt(d)&&(pt("Cancelled"),process.exit(0)),s=String(d)}else{let d=await Io({message:"What kind of site is this?",options:[...Pa]});dt(d)&&(pt("Cancelled"),process.exit(0)),a=d}}await Ia(t,s,a,yr(e))}async function Ia(e,t,n,r){let o=Tf();o.start("Setting up your SEO project");let i=Vs(e),s=Ve(e),a=Zn(e),l=io(),c={domain:t,site_type:n,language:Yi(t),initialized_at:new Date().toISOString(),seoagent_version:C,skill_version:C,install_id:l,...i.cms!=="none"?{cms:i.cms}:{},...i.blog_path?{blog_path:i.blog_path}:{},...s.provider!=="none"?{image_provider:s.provider}:{},...a.dir?{public_dir:a.dir}:{}},d=ke(),p=d?Promise.resolve(!1):tt({installId:l,event:"init",cliVersion:C}),f=d||t===De?Promise.resolve(null):xs({domain:t,installId:l}),g=N(t),h=g&&t!==De?Ke({apiBase:g.api_base,authHeader:`Bearer ${g.user_token}:${g.website_token}`,localDomain:t}).catch(()=>null):Promise.resolve(null);fs(e),ps(e,c),at(e),Ws(e,n),Os(e);let y=gr(e,t!==De?t:null),w=$t(e),b=At(e,w.skillFile),E=If(b),H=`${E}/references/audit-checks.md`,T=w.claudeSymlink?At(e,w.claudeSymlink):void 0;st(e);let M=await Oa(e,t,r),se=M==="ready"||M==="already";if(M==="ready"&&t===De){let P=_(e)?.domain;P&&P!==De&&(t=P,c.domain=P)}let U=t!==De,K=M==="rejected"||M==="unreachable"||M==="invalid";K&&(process.exitCode=1);let G={pages:[],dynamicCount:0},te={wrote:!1,added:0,total:0,merged:!1,file:"pages.md"};try{G=$e(e,U?t:null),te=lr(e,G.pages)}catch{}if(o.stop(U?`Created .seoagent/ project for ${c.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),i.cms!=="none"){let P=i.evidence.map(q=>`${q.detail} (${q.source})`).slice(0,2).join(", ");u.info(`CMS detected: ${i.cms} \u2014 ${P}`)}if(i.blog_path&&u.info(`Blog route: ${i.blog_path}`),a.dir&&u.info(`Static files: ${a.dir}/ (${a.evidence}) \u2014 your llms.txt and OKF bundle publish there.`),y.created.length>0&&u.info("Scaffolded .seoagent/okf/ \u2014 the AI-readable knowledge bundle answer engines cite. The audit will offer to fill it."),s.provider!=="none"&&u.info(`Image generation: ${s.provider} (detected ${s.matched_key}) \u2014 articles can get AI hero images.`),G.pages.length>0){let P=te.merged?te.added>0?`Re-scanned your codebase: +${te.added} new page${te.added===1?"":"s"} merged into .seoagent/pages.md (${te.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${te.total} pages)`:`Found ${G.pages.length} page${G.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;u.info(P+(G.dynamicCount>0?` (plus ${G.dynamicCount} dynamic route template${G.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}Ta(e,w);let[Qe,we,Bn]=await Promise.all([p,f,h]);if(Bn?.verdict==="mismatch"&&u.warn(`Heads up: the credentials bound to ${t} are for a SEOAgent cloud project on ${Bn.cloudDomain} instead. This workspace stays LOCAL-ONLY \u2014 nothing will be pushed to or pulled from that project. To connect ${t} to the cloud, run \`${m("login")}\` from this directory and pick (or create) ${t} \u2014 the CLI can stay logged into both sites at once, no need to log out first.`),we?.status==="data"){let P=we.difficulty!=null?`, difficulty ${we.difficulty}/100`:"";u.info(`Free keyword peek \u2014 "${we.keyword}": ${we.volume.toLocaleString("en-US")} searches/mo${P}. You get ~10 free peeks/day: ${m('keywords --peek "<keyword>"')}`)}else we?.status==="no-data"&&u.info(`Free keyword peek is live \u2014 no search-volume data for "${we.keyword}" yet. Try a topic keyword (~10 free/day): ${m('keywords --peek "best <your category> tool"')}`);Qe&&u.info(so);let Vi=U?c.domain:"your site",Gn=U?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${c.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."];Of([U?`\u2713 SEOAgent installed for ${c.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${b} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...Gn,...ir(e)?[""," \u270D\uFE0F Before (or right after) the audit: DRAFT .seoagent/context.md \u2014 it"," is still the blank scaffold (instructions are inside the file)."," From this repo + the live homepage/pricing page, fill in the"," business name, type (LOCAL/physical vs ONLINE-only vs HYBRID),"," audience, location, and positioning \u2014 then show your human the"," draft to review. SEOAgent's keyword and strategy intelligence is"," context-blind until this file exists."]:[],"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${Vi}`," (homepage + sitemap + robots.txt; the checks live in",` ${H} \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.',"",...se?[" 3. This project is connected to the SEOAgent cloud. Each session: run",` ${m("sync")}, triage .seoagent/inbox/, do the work, and`,` ${m("ack <id>")} each completed action.`]:K?[" 3. \u26A0\uFE0F The setup code did NOT bind this project (see the error above)."," Do not continue without a successful login \u2014 nothing syncs unbound."," Get a fresh code at seoagent.com/grok, then run:",` ${m("login")} --code <code>`]:[" 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:",` ${m("login")}`],"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${b} is picked up automatically.`,...T?[` Symlinked at ${T} \u2192 ${E} so Claude Code finds it too.`]:[],"",...se?[" Cloud dashboard: connected. Pull your first work with:","",` ${m("sync")}`]:K?[" \u26A0\uFE0F The setup code did not bind this project. Get a fresh code at"," seoagent.com/grok, then run:","",` ${m("login")} --code <code>`]:[" Want the cloud dashboard now? Free account, ~30 seconds:","",` ${m("login")}`],""].join(`
|
|
86
|
+
`,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}import{log as At}from"@clack/prompts";var u={info:e=>At.info(e),warn:e=>At.warn(e),error:e=>At.error(e),success:e=>At.success(e),step:e=>At.step(e),message:e=>At.message(e)};function S(e,t,n,r=n){e?e.stop(r):u[t](n)}import{randomBytes as mf}from"crypto";import{isCancel as hf,spinner as xa,text as yf}from"@clack/prompts";import pe from"picocolors";import{exec as gf}from"child_process";function mr(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;gf(t,()=>{})}function wa(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 ka=/^sa_[0-9a-f]{24}$/;function ba(e){switch(e){case"code_not_found":return"That setup code was not recognized: it was never issued. Codes cannot be guessed or retyped from memory; copy one exactly from seoagent.com/grok. A scheduled run on a fresh machine needs the SEOAGENT_AUTH secret (`seoagent whoami --env` on the bound machine), not a setup code.";case"code_already_used":return"That setup code has already been used \u2014 each code works exactly once. Generate a new one at seoagent.com/grok.";case"code_revoked":return"That setup code was replaced by a newer one. Use the latest code, or generate a new one at seoagent.com/grok.";case"code_expired":return"That setup code has expired. Generate a new one at seoagent.com/grok.";case"setup_codes_unavailable":return"Setup codes are not enabled on this server yet. Run `seoagent login` (browser flow) instead.";case"domain_required":return"This code has no site attached and the project has no domain. Run `seoagent init` first so the project knows its domain.";default:return typeof e=="string"&&e?`Login failed: ${e}`:"Login failed."}}function va(e,t){let n=t&&typeof t=="object"?t:null;if(e>=500)return e===503&&n?.error==="setup_codes_unavailable"?{status:"error",terminal:!0,message:ba(n.error)}:{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:ba(n?.error)};if(!n)return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof 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{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var wf=1500,bf=300*1e3,kf=3,vf=2e3;function hr(e,t){if(ke())return;let n=Le(e);n&&tt({installId:n,event:t,cliVersion:C})}function $f(){return mf(16).toString("hex")}function Sf(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function $a(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 xf(e,t,n){if(!e||e.website_token===t)return null;try{let r=await n(e);return r.verdict!=="unverified"?r.cloudDomain:null}catch{return null}}async function _f(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)}),o=null;try{o=await r.json()}catch{}return wa(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function _a(e){return new Promise(t=>setTimeout(t,e))}async function Ca(e,t,n,r){let o=N(),i=await xf(o,e.website_token,c=>Ke({apiBase:c.api_base,authHeader:`Bearer ${c.user_token}:${c.website_token}`,localDomain:""}));i&&o&&lo(o,i),lo({user_token:e.user_token,website_token:e.website_token,api_base:t},e.domain||n);let s=e.email&&e.domain?`Logged in as ${e.email} (${e.domain}). Future SEO work in this repo will sync to your dashboard.`:e.email?`Logged in as ${e.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.",a=e.email&&e.domain?`Logged in as ${pe.bold(e.email)} (${pe.cyan(e.domain)}).`:e.email?`Logged in as ${pe.bold(e.email)}.`:"Logged in.";S(r,"success",s,pe.green(a)),r&&u.info("Future SEO work in this repo will sync to your dashboard.");let l=qe().filter(c=>c!==We(e.domain||n));l.length>0&&u.info(`Also logged in to: ${l.join(", ")}. Each project auto-selects its own site \u2014 no need to log out first.`)}function Cf(e,t,n){return{code:e,...t&&t!=="unknown"?{domain:t}:{},...n?{install_id:n.installId,cli_version:n.cliVersion,platform:process.platform}:{}}}function Ro(e){if(ke())return null;let t=Le(e);return t?{installId:t,cliVersion:C}:null}async function Ef(e,t,n,r){try{let o=await fetch(`${e}/api/cli/auth/redeem`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(Cf(t,n,r)),signal:AbortSignal.timeout(1e4)}),i=null;try{i=await o.json()}catch{}return va(o.status,i)}catch(o){return{status:"error",terminal:!1,message:o.message||"network error"}}}var Rf="Scheduled runs on a fresh machine: store the output of `seoagent whoami --env` as the task's SEOAGENT_AUTH secret. A setup code works once and cannot be guessed; never reuse or invent one.";function Af(e){return e!=="ready"}function Pf(e,t,n){if(!e||!n||t&&t!=="unknown")return!1;try{if(!Y(e,{domain:n}))return!1}catch{return!1}return u.info(`Saved domain: ${n} \u2192 .seoagent/project.md (from the setup code).`),!0}async function Ao(e,t,n,r,o){if(!ka.test(e))return u.warn("That does not look like a setup code (expected `sa_` + 24 hex characters). Generate one at seoagent.com/grok."),"invalid";let s=!!process.stdout.isTTY?xa():null;s?.start(pe.dim("Redeeming setup code\u2026"));let a="network error";for(let l=0;l<kf;l++){l>0&&await _a(vf);let c=await Ef(t,e,n,r);if(c.status==="ready")return await Ca(c,t,n,s),Pf(o,n,c.domain),u.info(Rf),"ready";if(c.terminal)return S(s,"warn",c.message,pe.red(c.message)),"rejected";a=c.message}return S(s,"warn",`Could not reach the server (${a}). Check your connection and run \`${m("login")} --code <code>\` again.`,pe.yellow("Could not reach the server.")),s&&u.warn(`Run \`${m("login")} --code <code>\` again to retry.`),"unreachable"}function Po(e){return e&&e!=="unknown"?$s(e):!!N()}function Sa(){return`Next: run \`${m("sync")}\` in this repo \u2014 it pulls your strategy, briefs and inbox into .seoagent/. Nothing syncs until it runs.`}async function en(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||O.BASE||Ie).replace(/\/$/,""),o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let h=await yf({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(w){if(!String(w??"").trim())return"A site URL is required.";if(!$a(String(w)))return"Please enter a valid domain like `example.com`."}});if(hf(h)){u.warn("Login cancelled.");return}let y=$a(String(h));if(y){o=y;try{Y(t,{domain:y}),u.success(`Saved domain: ${y} \u2192 .seoagent/project.md`)}catch{}}}let i=(e.code??process.env.SEOAGENT_SETUP_CODE??"").trim(),s=o&&o!=="unknown";if(i&&!s?!1:Po(o)){let h=s?` for ${o}`:"";u.info(`Already logged in${h}. To switch accounts${h}, run \`${m("logout")}\` first.`);return}if(i){let h=await Ao(i,r,o,Ro(t),t);Af(h)?process.exitCode=1:u.info(Sa());return}let l=$f(),c=Sf(r,l,o);u.message("Opening seoagent.com to connect this CLI to your account..."),u.info(`If the browser does not open, visit: ${c}`),mr(c),u.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let p=!!process.stdout.isTTY?xa():null;p?.start(pe.dim("Waiting for browser confirmation\u2026"));let f=Date.now()+bf,g=!0;for(;Date.now()<f;){g||await _a(wf),g=!1;let h=await _f(r,l);if(h.status==="ready"){await Ca(h,r,o,p),hr(t,"login_browser_ok"),u.info(Sa());return}if(h.status==="expired"){hr(t,"login_browser_expired"),S(p,"warn",`Session expired. Run \`${m("login")}\` again.`,pe.red("Session expired.")),p&&u.warn(`Run \`${m("login")}\` again.`);return}if(h.status==="error"){if(h.terminal){S(p,"warn",`Login failed: ${h.message}. Run \`${m("login")}\` again.`,pe.red(`Login failed: ${h.message}.`)),p&&u.warn(`Run \`${m("login")}\` again.`),hr(t,"login_browser_failed");return}continue}}S(p,"warn",`Login timed out. Run \`${m("login")}\` again to retry.`,pe.yellow("Login timed out.")),p&&u.warn(`Run \`${m("login")}\` again to retry.`),hr(t,"login_browser_timeout")}function tn(e={}){let t=e.all?null:_(process.cwd()),n=!e.all&&t?.domain&&t.domain!=="unknown"?t.domain:null;if(!Ss(e.all?null:n)){u.info(n?`You were not logged in for ${n}.`:"You were not logged in.");return}u.success(n?`Logged out of ${n}.`:"Logged out.");let o=qe();o.length>0&&u.info(`Still logged in to: ${o.join(", ")}. Run \`${m("logout")} --all\` to log out of everything.`)}function yr(e,t=process.env){return(e.code??t.SEOAGENT_SETUP_CODE??"").trim()}function Lf(e,t=m("init")){return e?`${t} --code ${e}`:t}async function Oa(e,t,n){if(!n)return"none";let r=t!==De;if(r&&Po(t))return u.info(`Already logged in for ${t} \u2014 setup code not needed, skipping it.`),"already";let o=(O.BASE||Ie).replace(/\/$/,"");return Ao(n,o,r?t:null,Ro(e),e)}var Pa=[{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"}],De="unknown",Nf=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function jf(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 wr(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Nf.has(t)?t:null}function Ta(e,t){t.agentsMdPath&&u.info(`Added a SEOAgent section to ${Pt(e,t.agentsMdPath)} so agents that read it (Codex, others) find the skill.`),t.cursorRulePath&&u.info(`Wrote ${Pt(e,t.cursorRulePath)} so Cursor agents find the skill.`)}async function nn(e={}){let t=process.cwd();if(ds(t)){let l=_(t),c=St(t);st(t),Y(t,{skill_version:C}),at(t);let d=Pt(t,c.skillFile),p=c.claudeSymlink?` (symlinked at ${Pt(t,c.claudeSymlink)})`:"",f=l?.skill_version&&l.skill_version!==C?`${l.skill_version} \u2192 ${C}`:C;if(u.success(`Refreshed the SEOAgent skill (${f}).`),u.info("Your `.seoagent/` knowledge was left untouched."),u.info(`Skill at ${d}${p} \u2014 agents read this file at session start.`),Ta(t,c),u.info(`Run \`${m("status")}\` to see your project, or \`${m("uninstall")}\` to start fresh.`),!ke()){let h=Le(t);h&&await tt({installId:h,event:"reinit",cliVersion:C})&&u.info(so)}let g=await Oa(t,l?.domain??De,yr(e));(g==="rejected"||g==="unreachable"||g==="invalid")&&u.warn(Df());return}let n=!!e.yes||!process.stdin.isTTY,r=pa(t);if(r.isWorktree&&!e.allowWorktree){let l=Lf(yr(e)),c=r.mainRoot?`cd ${r.mainRoot} && ${l}`:`run ${l} from the main repository root`;n&&(u.warn("This directory is a temporary git worktree \u2014 a `.seoagent/` created here is deleted with the worktree, and images/un-synced edits cannot be recovered from the cloud."),u.info(`Init at the main checkout instead: ${c}`),u.info("To init here anyway (not recommended), pass --allow-worktree."),process.exit(1)),Ea("SEOAgent \u2014 AI SEO Agent");let d=await Aa({message:"This looks like a temporary git worktree \u2014 .seoagent/ created here is lost when the worktree is removed. Create it here anyway?",initialValue:!1});(dt(d)||!d)&&(pt(`Good call. ${c}`),process.exit(0))}else n||Ea("SEOAgent \u2014 AI SEO Agent");let o=ea(t,l=>u.step(l)),i=()=>{if(o.evidence.length!==0){u.info("Inferred from your project:");for(let l of o.evidence)u.info(` \u2022 ${jf(l)}`)}},s=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||o.domain||null,a=wr(e.siteType)||wr(process.env.SEOAGENT_SITE_TYPE)||o.siteType||null;if(n){e.siteType?.trim()&&wr(e.siteType)===null&&(u.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&wr(process.env.SEOAGENT_SITE_TYPE)===null&&(u.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),i(),s||(u.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),s=De),a||(a="unknown"),await Ia(t,s,a,yr(e));return}if(i(),!s){let l=await Ra({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});dt(l)&&(pt("Cancelled"),process.exit(0)),s=String(l)}if(!a){let l=await Io({message:"What kind of site is this?",options:[...Pa]});dt(l)&&(pt("Cancelled"),process.exit(0)),a=l}for(;;){let l=await Aa({message:`Create .seoagent for ${s} (${a})?`});if(dt(l)&&(pt("Cancelled"),process.exit(0)),l)break;let c=await Io({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((dt(c)||c==="abort")&&(pt("Cancelled"),process.exit(0)),c==="domain"){let d=await Ra({message:"Website domain",placeholder:"example.com",validate:p=>p.trim()?void 0:"Domain is required"});dt(d)&&(pt("Cancelled"),process.exit(0)),s=String(d)}else{let d=await Io({message:"What kind of site is this?",options:[...Pa]});dt(d)&&(pt("Cancelled"),process.exit(0)),a=d}}await Ia(t,s,a,yr(e))}async function Ia(e,t,n,r){let o=Tf();o.start("Setting up your SEO project");let i=Vs(e),s=Ve(e),a=Zn(e),l=io(),c={domain:t,site_type:n,language:Yi(t),initialized_at:new Date().toISOString(),seoagent_version:C,skill_version:C,install_id:l,...i.cms!=="none"?{cms:i.cms}:{},...i.blog_path?{blog_path:i.blog_path}:{},...s.provider!=="none"?{image_provider:s.provider}:{},...a.dir?{public_dir:a.dir}:{}},d=ke(),p=d?Promise.resolve(!1):tt({installId:l,event:"init",cliVersion:C}),f=d||t===De?Promise.resolve(null):xs({domain:t,installId:l}),g=N(t),h=g&&t!==De?Ke({apiBase:g.api_base,authHeader:`Bearer ${g.user_token}:${g.website_token}`,localDomain:t}).catch(()=>null):Promise.resolve(null);fs(e),ps(e,c),at(e),Ws(e,n),Os(e);let y=gr(e,t!==De?t:null),w=St(e),b=Pt(e,w.skillFile),E=If(b),H=`${E}/references/audit-checks.md`,T=w.claudeSymlink?Pt(e,w.claudeSymlink):void 0;st(e);let M=await Oa(e,t,r),se=M==="ready"||M==="already";if(M==="ready"&&t===De){let P=_(e)?.domain;P&&P!==De&&(t=P,c.domain=P)}let U=t!==De,K=M==="rejected"||M==="unreachable"||M==="invalid";K&&(process.exitCode=1);let G={pages:[],dynamicCount:0},te={wrote:!1,added:0,total:0,merged:!1,file:"pages.md"};try{G=$e(e,U?t:null),te=lr(e,G.pages)}catch{}if(o.stop(U?`Created .seoagent/ project for ${c.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),i.cms!=="none"){let P=i.evidence.map(q=>`${q.detail} (${q.source})`).slice(0,2).join(", ");u.info(`CMS detected: ${i.cms} \u2014 ${P}`)}if(i.blog_path&&u.info(`Blog route: ${i.blog_path}`),a.dir&&u.info(`Static files: ${a.dir}/ (${a.evidence}) \u2014 your llms.txt and OKF bundle publish there.`),y.created.length>0&&u.info("Scaffolded .seoagent/okf/ \u2014 the AI-readable knowledge bundle answer engines cite. The audit will offer to fill it."),s.provider!=="none"&&u.info(`Image generation: ${s.provider} (detected ${s.matched_key}) \u2014 articles can get AI hero images.`),G.pages.length>0){let P=te.merged?te.added>0?`Re-scanned your codebase: +${te.added} new page${te.added===1?"":"s"} merged into .seoagent/pages.md (${te.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${te.total} pages)`:`Found ${G.pages.length} page${G.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;u.info(P+(G.dynamicCount>0?` (plus ${G.dynamicCount} dynamic route template${G.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}Ta(e,w);let[Qe,we,Bn]=await Promise.all([p,f,h]);if(Bn?.verdict==="mismatch"&&u.warn(`Heads up: the credentials bound to ${t} are for a SEOAgent cloud project on ${Bn.cloudDomain} instead. This workspace stays LOCAL-ONLY \u2014 nothing will be pushed to or pulled from that project. To connect ${t} to the cloud, run \`${m("login")}\` from this directory and pick (or create) ${t} \u2014 the CLI can stay logged into both sites at once, no need to log out first.`),we?.status==="data"){let P=we.difficulty!=null?`, difficulty ${we.difficulty}/100`:"";u.info(`Free keyword peek \u2014 "${we.keyword}": ${we.volume.toLocaleString("en-US")} searches/mo${P}. You get ~10 free peeks/day: ${m('keywords --peek "<keyword>"')}`)}else we?.status==="no-data"&&u.info(`Free keyword peek is live \u2014 no search-volume data for "${we.keyword}" yet. Try a topic keyword (~10 free/day): ${m('keywords --peek "best <your category> tool"')}`);Qe&&u.info(so);let Vi=U?c.domain:"your site",Gn=U?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${c.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."];Of([U?`\u2713 SEOAgent installed for ${c.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${b} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...Gn,...ir(e)?[""," \u270D\uFE0F Before (or right after) the audit: DRAFT .seoagent/context.md \u2014 it"," is still the blank scaffold (instructions are inside the file)."," From this repo + the live homepage/pricing page, fill in the"," business name, type (LOCAL/physical vs ONLINE-only vs HYBRID),"," audience, location, and positioning \u2014 then show your human the"," draft to review. SEOAgent's keyword and strategy intelligence is"," context-blind until this file exists."]:[],"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${Vi}`," (homepage + sitemap + robots.txt; the checks live in",` ${H} \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.',"",...se?[" 3. This project is connected to the SEOAgent cloud. Each session: run",` ${m("sync")}, triage .seoagent/inbox/, do the work, and`,` ${m("ack <id>")} each completed action.`]:K?[" 3. \u26A0\uFE0F The setup code did NOT bind this project (see the error above)."," Do not continue without a successful login \u2014 nothing syncs unbound."," Get a fresh code at seoagent.com/grok, then run:",` ${m("login")} --code <code>`]:[" 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:",` ${m("login")}`],"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${b} is picked up automatically.`,...T?[` Symlinked at ${T} \u2192 ${E} so Claude Code finds it too.`]:[],"",...se?[" Cloud dashboard: connected. Pull your first work with:","",` ${m("sync")}`]:K?[" \u26A0\uFE0F The setup code did not bind this project. Get a fresh code at"," seoagent.com/grok, then run:","",` ${m("login")} --code <code>`]:[" Want the cloud dashboard now? Free account, ~30 seconds:","",` ${m("login")}`],""].join(`
|
|
87
87
|
`))}function Df(){return`The setup code did not bind this project. Do not continue without a successful login \u2014 get a fresh code at seoagent.com/grok, then run \`${m("login")} --code <code>\`.`}import{existsSync as ja}from"fs";import{intro as Ff,outro as Uf,confirm as Bf,isCancel as Gf,cancel as Hf}from"@clack/prompts";import{existsSync as br,rmSync as Mf}from"fs";import{join as kr}from"path";function La(e,t={}){let n=[],r=kr(e,k);br(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=kr(e,Pe.CLAUDE);br(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=kr(e,Pe.AGENTS);return br(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),Ls(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:kr(e,".claude","settings.json"),kind:"hook"}),t.global&&br(z)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:z,kind:"global"}),n}function Na(e,t){for(let n of t)n.kind==="hook"?Ns(e):Mf(n.path,{recursive:!0,force:!0})}async function rn(e={}){let t=process.cwd(),n=La(t,{global:e.global});if(n.length===0){u.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&ja(z)&&u.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(`
|
|
88
88
|
`);if(!r){Ff("SEOAgent \u2014 uninstall"),u.message(`This will remove:
|
|
89
89
|
${o}`);let s=await Bf({message:"Remove these and start fresh?"});if(Gf(s)||!s){Hf("Cancelled \u2014 nothing was removed.");return}}Na(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
|
|
90
90
|
`);r?u.success(`Removed:
|
|
91
91
|
${i}`):Uf(`Removed:
|
|
92
|
-
${i}`),!e.global&&ja(z)&&u.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),u.info(`Re-install any time with \`${m("init")}\`.`)}import A from"picocolors";import{existsSync as on,readdirSync as Oo,statSync as Wf,readFileSync as Da}from"fs";import{join as
|
|
93
|
-
`)}function rg(e,t){if(!t)return Ye.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=sn(t),r=e-5-n;return r<1?Ye.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${Ye.dim("\u250C\u2500 ")}${t}${Ye.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function og(e,t){let n=sn(e),r=n<=t?e+" ".repeat(t-n):ng(e,t);return`${Ye.dim("\u2502")} ${r} ${Ye.dim("\u2502")}`}function To(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 an(){let e=Ma(process.cwd());if(!e){u.warn("No SEOAgent project found in this directory."),u.info(`Run \`${m("init")}\` to get started.`);return}u.message(ig(e))}function ig(e){if(!e)return"";let t=11,n=s=>A.dim(s.padEnd(t)),r=[];N(e.domain)?(r.push({content:`${A.green("\u2713")} ${A.dim("Logged in")}`}),r.push({content:A.dim(` Run \`${m("whoami")}\` for email / plan.`)})):(r.push({content:`${A.dim("\u25CB Not logged in")}`}),r.push({content:A.dim(` Run \`${m("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${A.green(`last run ${To(e.audit.date??"")}`)} ${A.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${A.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${A.bold(A.cyan(String(e.strategy.clusterCount??0)))} ${A.dim("clusters")} \xB7 ${A.bold(A.cyan(String(e.strategy.articleCount??0)))} ${A.dim("ideas")}`:`${n("Strategy:")}${A.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${A.bold(A.cyan(String(e.briefs.count??0)))} ${A.dim("ready")}`:`${n("Briefs:")}${A.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${A.green("\u2713")} ${A.bold(A.cyan(String(e.content.count??0)))} ${A.dim("articles written")}`:`${n("Content:")}${A.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${A.green("updated")} ${A.dim(To(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${A.dim("not yet created")}`});let i=`${A.bold(A.cyan("SEOAgent"))} ${A.dim("\xB7")} ${A.bold(e.domain)}`;return B(r,{width:78,title:i})}import{exec as sg,spawn as Ua}from"child_process";import{confirm as ag,isCancel as lg}from"@clack/prompts";import X from"picocolors";function Je(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 cg=`https://registry.npmjs.org/${Ae}/latest`,ln=["free","starter","pro","scale","enterprise"],vr={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ug(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return ln.includes(t)?t:null}function dg(e){let t=ln.indexOf(e);return t===-1||t===ln.length-1?null:ln[t+1]}async function pg(e,t=fetch){if(!e)return null;try{let n=(e.api_base||O.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 fg(e){let t=[],r=s=>X.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${X.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${X.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of ln){let a=vr[s];s===e.current?t.push({content:`${X.bold(X.green("\u25CF"))} ${X.bold(X.green(a.padEnd(11)))} ${X.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${X.yellow("\u25C6")} ${X.bold(X.yellow(a.padEnd(11)))} ${X.yellow("next tier")}`}):t.push({content:X.dim(` ${a}`)})}let i=`${X.bold(X.cyan("SEOAgent Cloud"))} ${X.dim("\xB7")} ${X.dim("your plan")}`;return B(t,{width:55,title:i})}async function cn(){let e=_(process.cwd()),t=N(e?.domain),n=!!process.stdin.isTTY;if(t&&n){let r=await pg(t);if(r){let o=ug(r.plan),i=o?dg(o):null;if(o&&u.message(fg({email:r.email,domain:r.domain,current:o,next:i})),o&&!i){u.success(`You're on ${vr[o]} (highest tier).`);return}if(o&&i){let s=await ag({message:`Upgrade from ${vr[o]} to ${vr[i]}?`});if(lg(s)||!s){u.info("No changes.");return}}}}gg()}function gg(){let e=mg();u.info("Opening SEOAgent Cloud pricing..."),u.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;sg(t,n=>{n&&u.warn("Could not open browser. Visit the URL above to upgrade.")})}function mg(){let e=_(process.cwd());return be("cli-upgrade",e?.domain)}async function un(e={}){let t=C,n=await yg();if(!n){u.warn("Couldn't reach the npm registry to check for a newer version."),u.message(`You're on ${t}. To force-update: npm install -g ${Ae}@latest`);return}if(Je(t,n)>=0){u.success(`You're on the latest CLI (${t}).`);return}if(!eo()){u.info(`A newer CLI is available: ${t} \u2192 ${n}.`),u.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),u.message(`Run the latest now by pinning the tag: npx -y ${Ae}@latest <cmd>`),u.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),u.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${Ae}@latest`);return}if(e.dryRun){u.info(`(dry-run) would run: npm install -g ${Ae}@latest`);return}if(u.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await wg()){u.error(`Update failed. Try manually: npm install -g ${Ae}@latest (you may need sudo on Linux/macOS).`);return}if(u.success(`Updated to ${n}.`),e.projects===!1){u.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}u.info("Refreshing your other projects to the new version\u2026"),await hg()||u.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 hg(){return new Promise(e=>{try{let t=Ua("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function yg(e=fetch){try{let t=await e(cg,{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 wg(){return new Promise(e=>{let t=Ua("npm",["install","-g",`${Ae}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{spinner as Sy}from"@clack/prompts";import F from"picocolors";import{existsSync as Zo,mkdirSync as _h,readFileSync as Zl,readdirSync as Ch,writeFileSync as Eh}from"fs";import{join as ei,relative as Rh,sep as Ah}from"path";var bg=["claude-code","cursor","codex","grok-bot","unknown"],kg="SEOAGENT_AGENT";function Ba(e=process.env){let t=(e[kg]??"").trim().toLowerCase();return bg.includes(t)?t:e.CLAUDECODE||e.CLAUDE_CODE||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":e.CURSOR_TRACE_ID||e.CURSOR_AGENT||e.CURSOR_SESSION_ID?"cursor":e.CODEX_SANDBOX||e.CODEX_THREAD_ID||e.OPENAI_CODEX?"codex":e.GROK_SANDBOX||e.XAI_SANDBOX?"grok-bot":"unknown"}import{existsSync as vg,mkdirSync as $g,readdirSync as Ha,readFileSync as No,writeFileSync as Ga}from"fs";import{dirname as Sg,join as It,relative as xg}from"path";var fe=e=>typeof e=="string"&&e?e:void 0;function jo(e,t){let n=It(e,t),r;try{r=Ha(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=It(n,i),a;try{a=ue(No(s,"utf-8")).data}catch{continue}let l=fe(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:l,title:fe(a.title)??l,draft:a.draft===!0,page_type:fe(a.page_type)??fe(a.type),path:xg(e,s)})}return o}function dn(e){let t;try{t=Ha(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=It(e,r),i;try{i=ue(No(o,"utf-8")).data}catch{continue}n.push({slug:fe(i.slug)??r.replace(/\.md$/,""),source:fe(i.source)??"external",repo_path:fe(i.repo_path)??null,status:fe(i.status)??null,file:o})}return n}function Do(e,t,n){let r=new Set(t.map(l=>l.slug)),o=e.filter(l=>!l.draft&&!r.has(l.slug)),i=new Map(e.filter(l=>!l.draft).map(l=>[l.slug,l])),s=[];for(let l of t){if((l.status??"")==="published")continue;let c=i.get(l.slug);c&&s.push({pointer:l,article:c})}let a=t.filter(l=>l.source==="repo"&&l.repo_path!==null&&!n(l.repo_path));return{toTrack:o,toPublish:s,stale:a,alreadyTracked:t.length-a.length}}function Mo(e){return t=>vg(It(e,t))}function $r(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Wa(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ot(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}`}var Lo="This is a pointer so the cloud dashboard can track it without duplicating";function Ka(e){if(!e.includes(Lo))return null;let t;try{t=ue(e)}catch{return null}return!fe(t.data.slug)||!t.body.includes(Lo)?null:{status:fe(t.data.status)??null,repo_path:fe(t.data.repo_path)??null}}function pn(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.brief&&t.push(`brief: ${JSON.stringify(e.brief)}`),e.supersedes&&t.push(`supersedes: ${e.supersedes}`),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?`
|
|
92
|
+
${i}`),!e.global&&ja(z)&&u.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),u.info(`Re-install any time with \`${m("init")}\`.`)}import A from"picocolors";import{existsSync as on,readdirSync as Oo,statSync as Wf,readFileSync as Da}from"fs";import{join as It}from"path";function Kf(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function qf(e){let t=It(e,"audit","latest.md");if(!on(t))return null;let n=Ge(t);if(!n)return null;let r=Da(t,"utf-8"),o=Kf(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Vf(e){try{let n=Da(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 zf(e){let t=It(e,"strategy","clusters");if(!on(t))return null;let n=Oo(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Vf(It(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Yf(e){let t=It(e,"briefs");if(!on(t))return null;let n=Oo(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Jf(e){let t=It(e,"content");if(!on(t))return null;let n=Oo(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Xf(e){let t=It(e,"roadmap.md");return on(t)?{exists:!0,updatedAt:Wf(t).mtime.toISOString()}:null}function Ma(e){let t=_(e);if(!t)return null;let n=Te(e);return{domain:t.domain,audit:qf(n),strategy:zf(n),briefs:Yf(n),content:Jf(n),roadmap:Xf(n)}}import Ye from"picocolors";var Fa=/\x1b\[[0-9;]*m/g;function sn(e){return e.replace(Fa,"").length}var Qf=51,Zf=24,eg=80;function tg(e,t,n=Qf){let r=0;for(let c of e)"sep"in c||(r=Math.max(r,sn(c.content)));let o=t?sn(t)+6:0,i=Math.max(n,r+4,o),s=process.stdout?.columns,a=(typeof s=="number"&&s>0?s:eg)-2,l=Math.max(Zf,a);return Math.min(i,l)}function ng(e,t){if(sn(e)<=t)return e;if(t<=0)return"";let n=t-1,r="",o=0,i=!1,s=d=>{for(let p of d){if(o+p.length>n)return;r+=p,o+=p.length}},a=new RegExp(Fa.source,"g"),l=0,c;for(;(c=a.exec(e))!==null;)s(e.slice(l,c.index)),r+=c[0],i=!0,l=c.index+c[0].length;return s(e.slice(l)),`${r}\u2026${i?"\x1B[0m":""}`}function B(e,t={}){let n=tg(e,t.title,t.width),r=n-4,o="\u2500".repeat(n-2),i=rg(n,t.title),s=Ye.dim(`\u251C${o}\u2524`),a=Ye.dim(`\u2514${o}\u2518`),l=[i];for(let c of e){if("sep"in c){l.push(s);continue}l.push(og(c.content,r))}return l.push(a),l.join(`
|
|
93
|
+
`)}function rg(e,t){if(!t)return Ye.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=sn(t),r=e-5-n;return r<1?Ye.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${Ye.dim("\u250C\u2500 ")}${t}${Ye.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function og(e,t){let n=sn(e),r=n<=t?e+" ".repeat(t-n):ng(e,t);return`${Ye.dim("\u2502")} ${r} ${Ye.dim("\u2502")}`}function To(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 an(){let e=Ma(process.cwd());if(!e){u.warn("No SEOAgent project found in this directory."),u.info(`Run \`${m("init")}\` to get started.`);return}u.message(ig(e))}function ig(e){if(!e)return"";let t=11,n=s=>A.dim(s.padEnd(t)),r=[];N(e.domain)?(r.push({content:`${A.green("\u2713")} ${A.dim("Logged in")}`}),r.push({content:A.dim(` Run \`${m("whoami")}\` for email / plan.`)})):(r.push({content:`${A.dim("\u25CB Not logged in")}`}),r.push({content:A.dim(` Run \`${m("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${A.green(`last run ${To(e.audit.date??"")}`)} ${A.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${A.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${A.bold(A.cyan(String(e.strategy.clusterCount??0)))} ${A.dim("clusters")} \xB7 ${A.bold(A.cyan(String(e.strategy.articleCount??0)))} ${A.dim("ideas")}`:`${n("Strategy:")}${A.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${A.bold(A.cyan(String(e.briefs.count??0)))} ${A.dim("ready")}`:`${n("Briefs:")}${A.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${A.green("\u2713")} ${A.bold(A.cyan(String(e.content.count??0)))} ${A.dim("articles written")}`:`${n("Content:")}${A.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${A.green("updated")} ${A.dim(To(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${A.dim("not yet created")}`});let i=`${A.bold(A.cyan("SEOAgent"))} ${A.dim("\xB7")} ${A.bold(e.domain)}`;return B(r,{width:78,title:i})}import{exec as sg,spawn as Ua}from"child_process";import{confirm as ag,isCancel as lg}from"@clack/prompts";import X from"picocolors";function Je(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 cg=`https://registry.npmjs.org/${Ae}/latest`,ln=["free","starter","pro","scale","enterprise"],vr={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ug(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return ln.includes(t)?t:null}function dg(e){let t=ln.indexOf(e);return t===-1||t===ln.length-1?null:ln[t+1]}async function pg(e,t=fetch){if(!e)return null;try{let n=(e.api_base||O.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 fg(e){let t=[],r=s=>X.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${X.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${X.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of ln){let a=vr[s];s===e.current?t.push({content:`${X.bold(X.green("\u25CF"))} ${X.bold(X.green(a.padEnd(11)))} ${X.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${X.yellow("\u25C6")} ${X.bold(X.yellow(a.padEnd(11)))} ${X.yellow("next tier")}`}):t.push({content:X.dim(` ${a}`)})}let i=`${X.bold(X.cyan("SEOAgent Cloud"))} ${X.dim("\xB7")} ${X.dim("your plan")}`;return B(t,{width:55,title:i})}async function cn(){let e=_(process.cwd()),t=N(e?.domain),n=!!process.stdin.isTTY;if(t&&n){let r=await pg(t);if(r){let o=ug(r.plan),i=o?dg(o):null;if(o&&u.message(fg({email:r.email,domain:r.domain,current:o,next:i})),o&&!i){u.success(`You're on ${vr[o]} (highest tier).`);return}if(o&&i){let s=await ag({message:`Upgrade from ${vr[o]} to ${vr[i]}?`});if(lg(s)||!s){u.info("No changes.");return}}}}gg()}function gg(){let e=mg();u.info("Opening SEOAgent Cloud pricing..."),u.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;sg(t,n=>{n&&u.warn("Could not open browser. Visit the URL above to upgrade.")})}function mg(){let e=_(process.cwd());return be("cli-upgrade",e?.domain)}async function un(e={}){let t=C,n=await yg();if(!n){u.warn("Couldn't reach the npm registry to check for a newer version."),u.message(`You're on ${t}. To force-update: npm install -g ${Ae}@latest`);return}if(Je(t,n)>=0){u.success(`You're on the latest CLI (${t}).`);return}if(!eo()){u.info(`A newer CLI is available: ${t} \u2192 ${n}.`),u.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),u.message(`Run the latest now by pinning the tag: npx -y ${Ae}@latest <cmd>`),u.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),u.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${Ae}@latest`);return}if(e.dryRun){u.info(`(dry-run) would run: npm install -g ${Ae}@latest`);return}if(u.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await wg()){u.error(`Update failed. Try manually: npm install -g ${Ae}@latest (you may need sudo on Linux/macOS).`);return}if(u.success(`Updated to ${n}.`),e.projects===!1){u.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}u.info("Refreshing your other projects to the new version\u2026"),await hg()||u.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 hg(){return new Promise(e=>{try{let t=Ua("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function yg(e=fetch){try{let t=await e(cg,{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 wg(){return new Promise(e=>{let t=Ua("npm",["install","-g",`${Ae}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{spinner as Sy}from"@clack/prompts";import F from"picocolors";import{existsSync as Zo,mkdirSync as _h,readFileSync as Zl,readdirSync as Ch,writeFileSync as Eh}from"fs";import{join as ei,relative as Rh,sep as Ah}from"path";var bg=["claude-code","cursor","codex","grok-bot","unknown"],kg="SEOAGENT_AGENT";function Ba(e=process.env){let t=(e[kg]??"").trim().toLowerCase();return bg.includes(t)?t:e.CLAUDECODE||e.CLAUDE_CODE||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":e.CURSOR_TRACE_ID||e.CURSOR_AGENT||e.CURSOR_SESSION_ID?"cursor":e.CODEX_SANDBOX||e.CODEX_THREAD_ID||e.OPENAI_CODEX?"codex":e.GROK_SANDBOX||e.XAI_SANDBOX?"grok-bot":"unknown"}import{existsSync as vg,mkdirSync as $g,readdirSync as Ha,readFileSync as No,writeFileSync as Ga}from"fs";import{dirname as Sg,join as Ot,relative as xg}from"path";var fe=e=>typeof e=="string"&&e?e:void 0;function jo(e,t){let n=Ot(e,t),r;try{r=Ha(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=Ot(n,i),a;try{a=ue(No(s,"utf-8")).data}catch{continue}let l=fe(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:l,title:fe(a.title)??l,draft:a.draft===!0,page_type:fe(a.page_type)??fe(a.type),path:xg(e,s)})}return o}function dn(e){let t;try{t=Ha(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Ot(e,r),i;try{i=ue(No(o,"utf-8")).data}catch{continue}n.push({slug:fe(i.slug)??r.replace(/\.md$/,""),source:fe(i.source)??"external",repo_path:fe(i.repo_path)??null,status:fe(i.status)??null,file:o})}return n}function Do(e,t,n){let r=new Set(t.map(l=>l.slug)),o=e.filter(l=>!l.draft&&!r.has(l.slug)),i=new Map(e.filter(l=>!l.draft).map(l=>[l.slug,l])),s=[];for(let l of t){if((l.status??"")==="published")continue;let c=i.get(l.slug);c&&s.push({pointer:l,article:c})}let a=t.filter(l=>l.source==="repo"&&l.repo_path!==null&&!n(l.repo_path));return{toTrack:o,toPublish:s,stale:a,alreadyTracked:t.length-a.length}}function Mo(e){return t=>vg(Ot(e,t))}function $r(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Wa(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Tt(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}`}var Lo="This is a pointer so the cloud dashboard can track it without duplicating";function Ka(e){if(!e.includes(Lo))return null;let t;try{t=ue(e)}catch{return null}return!fe(t.data.slug)||!t.body.includes(Lo)?null:{status:fe(t.data.status)??null,repo_path:fe(t.data.repo_path)??null}}function pn(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.brief&&t.push(`brief: ${JSON.stringify(e.brief)}`),e.supersedes&&t.push(`supersedes: ${e.supersedes}`),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?`
|
|
94
94
|
|
|
95
95
|
Live: ${e.canonical}`:"",o=[`# ${e.title}`,"",`Tracked record \u2014 this article is **${e.status}** and ${n}.`,Lo,"the body. Edit the source file to change the article."+r,""].join(`
|
|
96
96
|
`);return`${t.join(`
|
|
@@ -105,7 +105,7 @@ ${r.join(`
|
|
|
105
105
|
${r.join(`
|
|
106
106
|
`)}
|
|
107
107
|
---${n[2]??`
|
|
108
|
-
`}`}function Va(e,t){let n=
|
|
108
|
+
`}`}function Va(e,t){let n=Ot(e,k,"content"),r=dn(n),o=new Set;t.content_dir&&o.add(t.content_dir);for(let c of r)c.source==="repo"&&c.repo_path&&o.add(Sg(c.repo_path));if(o.size===0)return{tracked:[],published:[]};let i=[...o].flatMap(c=>jo(e,c)),s=Do(i,r,Mo(e)),a=[];for(let{pointer:c,article:d}of s.toPublish)try{let p=_g(No(c.file,"utf-8"),{repoPath:d.path,canonical:Tt(c.slug,{domain:t.domain,blogPath:t.blog_path})});Ga(c.file,p,"utf-8"),a.push(c.slug)}catch{}if(s.toTrack.length===0)return{tracked:[],published:a};$g(n,{recursive:!0});let l=[];for(let c of s.toTrack){let d=pn({slug:c.slug,title:c.title,canonical:Tt(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()});Ga(Ot(n,`${c.slug}.md`),d,"utf-8"),l.push(c.slug)}return{tracked:l,published:a}}import{existsSync as Uo,mkdirSync as Cg,readdirSync as za,readFileSync as Eg,unlinkSync as Rg,writeFileSync as Fo}from"fs";import{join as ft}from"path";import V from"picocolors";var Bo={};function Go(e){let t=new Map;try{for(let n of dn(ft(e,k,"content")))t.set(n.slug,{status:n.status,repo_path:n.repo_path})}catch{}return t}function Ya(e){let t=new Map;for(let n of e){if(n.action_type!=="cli_draft_ready")continue;let r=n.payload||{},o=r.article_slug??n.subject_id??null,i=r.path??(o?`content/${o}.md`:null);i&&t.set(i,[...t.get(i)??[],n.id])}return t}function Me(e){return ft(e,k,"inbox")}function Ja(e){return`${e.action_type}-${e.id}.md`}function Ag(e,t){let n=0;if(!Uo(e))return 0;for(let r of za(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{Rg(ft(e,r)),n++}catch{}}return n}function Pg(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`---
|
|
109
109
|
action_id: ${e.id}
|
|
110
110
|
action_type: ${e.action_type}
|
|
111
111
|
article_id: ${n}
|
|
@@ -810,7 +810,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
810
810
|
|
|
811
811
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
812
812
|
skill knows what to do.
|
|
813
|
-
`}function Fe(e){let t=Me(e);if(!Uo(t))return[];let n=[];for(let r of za(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",l=null,c=null,d=null,p=null,f=null,g=null;try{let h=Eg(ft(t,r),"utf-8"),y=h.match(/^---\n([\s\S]*?)\n---/);if(y){let E=y[1];l=
|
|
813
|
+
`}function Fe(e){let t=Me(e);if(!Uo(t))return[];let n=[];for(let r of za(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",l=null,c=null,d=null,p=null,f=null,g=null;try{let h=Eg(ft(t,r),"utf-8"),y=h.match(/^---\n([\s\S]*?)\n---/);if(y){let E=y[1];l=Lt(E,"severity"),c=Lt(E,"issue"),d=Lt(E,"page_url");let H=Lt(E,"priority");(H==="high"||H==="medium"||H==="low")&&(p=H),f=Lt(E,"impact_estimate"),g=Lt(E,"effort_estimate")}let b=h.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);b&&(a=b[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:l,issue:c,page_url:d,priority:p,impact_estimate:f,effort_estimate:g})}return n.sort((r,o)=>r.id-o.id)}function Nt(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Yg[e.severity??""]??V.dim,r=e.severity??"unknown",o=[V.dim("\u25B8"),V.bold(`id ${e.id}`),V.dim("\xB7"),V.cyan(t),n(r)];if(e.priority){let i=Jg[e.priority];o.push(V.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(V.dim("\xB7"),V.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(V.dim("\xB7"),V.dim(`\u23F1 ${e.effort_estimate}`)),o.push(V.dim("\u2014"),e.title),o.join(" ")}var Yg={critical:e=>V.red(V.bold(e)),high:e=>V.red(e),medium:e=>V.yellow(e),low:e=>V.dim(e)},Jg={high:e=>V.red(V.bold(e)),medium:e=>V.yellow(e),low:e=>V.dim(e)};function Lt(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 Sr(e){let t=Me(e);if(!Uo(t))return;let n=Fe(e),r=n.length===0?`# SEOAgent Inbox
|
|
814
814
|
|
|
815
815
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
816
816
|
`:`# SEOAgent Inbox
|
|
@@ -825,24 +825,24 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
825
825
|
|
|
826
826
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
827
827
|
skill knows what to do.
|
|
828
|
-
`;Fo(ft(t,"README.md"),r,"utf-8")}function Qa(e,t,n=Bo){let r=Me(e);Cg(r,{recursive:!0});let o=new Set(t.map(c=>c.id)),i=Ag(r,o),s={...n,localPointers:n.localPointers??Go(e)},a=[],l=0;for(let c of t){let d=Vg(c,s);if(d===null){l++;continue}Fo(ft(r,Ja(c)),d,"utf-8"),a.push(c)}return Fo(ft(r,"README.md"),zg(a,l),"utf-8"),{wrote:a.length,removed:i,inboxPath:r,skippedUnknown:l,pendingIds:t.map(c=>c.id),pending:a.map(c=>({id:c.id,action_type:c.action_type,title:c.title}))}}import{existsSync as Bm,readFileSync as Gm,writeFileSync as Hm}from"fs";import{join as Wm}from"path";import{createHash as kl}from"crypto";import{existsSync as vl,mkdirSync as Im,readFileSync as Om,writeFileSync as wl,rmSync as Tm}from"fs";import{dirname as Lm,join as Ko,sep as Nm}from"path";function Xg(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Qg=[{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"||e==="pages-discovered.md"||/^pages\/[^/]+\.md$/.test(e)},{cls:"competitors",test:e=>e==="competitors.md"},{cls:"changelog",test:e=>e==="changelog.md"}];function Za(e,t){let n=Xg(e);for(let{cls:r,test:o}of Qg)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}import{readdirSync as Zg,readFileSync as el,statSync as em,writeFileSync as tm,existsSync as tl}from"fs";import{join as Ho,relative as nl,resolve as rl,sep as fl,posix as
|
|
829
|
-
`,1)[0].trim();if(!/^https?:\/\//i.test(o))continue;let i=r.slice(o.length),s=!/^- Not fetched/m.test(i),a=
|
|
828
|
+
`;Fo(ft(t,"README.md"),r,"utf-8")}function Qa(e,t,n=Bo){let r=Me(e);Cg(r,{recursive:!0});let o=new Set(t.map(c=>c.id)),i=Ag(r,o),s={...n,localPointers:n.localPointers??Go(e)},a=[],l=0;for(let c of t){let d=Vg(c,s);if(d===null){l++;continue}Fo(ft(r,Ja(c)),d,"utf-8"),a.push(c)}return Fo(ft(r,"README.md"),zg(a,l),"utf-8"),{wrote:a.length,removed:i,inboxPath:r,skippedUnknown:l,pendingIds:t.map(c=>c.id),pending:a.map(c=>({id:c.id,action_type:c.action_type,title:c.title}))}}import{existsSync as Bm,readFileSync as Gm,writeFileSync as Hm}from"fs";import{join as Wm}from"path";import{createHash as kl}from"crypto";import{existsSync as vl,mkdirSync as Im,readFileSync as Om,writeFileSync as wl,rmSync as Tm}from"fs";import{dirname as Lm,join as Ko,sep as Nm}from"path";function Xg(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Qg=[{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"||e==="pages-discovered.md"||/^pages\/[^/]+\.md$/.test(e)},{cls:"competitors",test:e=>e==="competitors.md"},{cls:"changelog",test:e=>e==="changelog.md"}];function Za(e,t){let n=Xg(e);for(let{cls:r,test:o}of Qg)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}import{readdirSync as Zg,readFileSync as el,statSync as em,writeFileSync as tm,existsSync as tl}from"fs";import{join as Ho,relative as nl,resolve as rl,sep as fl,posix as gt}from"path";function jt(e,t){let n=new RegExp(`^- \\*\\*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\*\\* *:?\\s*(.*)$`,"mi"),o=new RegExp(`^- \\*\\*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}:\\*\\*\\s*(.*)$`,"mi").exec(e)??n.exec(e);return o?o[1].trim():null}function Dt(e){return e!==null&&!e.startsWith("_(none")}function nm(e){try{let t=new URL(e).pathname.replace(/\/+$/,"");return t===""?"/":t}catch{return"/"}}function _r(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);return t&&/^source_render:\s*true\s*$/m.test(t[1])?!0:/SOURCE RENDER \(local dev server\)/.test(e)}function rm(e){let t=[],n=e.split(/^## /m).slice(1);for(let r of n){let o=r.split(`
|
|
829
|
+
`,1)[0].trim();if(!/^https?:\/\//i.test(o))continue;let i=r.slice(o.length),s=!/^- Not fetched/m.test(i),a=jt(i,"JSON-LD @types present")??"",l=Dt(a)?Array.from(a.matchAll(/`([^`]+)`/g)).map(c=>c[1].toLowerCase()):[];t.push({url:o,pathname:nm(o),fetched:s,titlePresent:Dt(jt(i,"title")),metaDescriptionPresent:Dt(jt(i,"meta description")),canonicalPresent:Dt(jt(i,"canonical")),jsonLdTypes:l,openGraphPresent:Dt(jt(i,"Open Graph")),twitterPresent:Dt(jt(i,"Twitter"))})}return t}var xr="(\\d{4}-\\d{2}-\\d{2})";function om(e){let t=/^---\n([\s\S]*?)\n---/.exec(e),n=t?new RegExp(`^captured_at:\\s*["']?${xr}`,"m").exec(t[1]):null;if(n)return n[1];let r=new RegExp(`^\\*\\*Crawled origin:\\*\\*.*\\bat ${xr}`,"m").exec(e);return r?r[1]:null}var im=["audited_at","generated_at","updated_at","created_at","last_updated","updated","date"];function sm(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return null;let n=null;for(let r of im){let o=new RegExp(`^${r}:\\s*["']?${xr}`,"im").exec(t[1]);o&&(n===null||o[1]>n)&&(n=o[1])}return n}var ol=new RegExp(`^\\s*(?:(?:[-*+]|\\d+\\.)\\s+)?\\[?${xr}\\]?(?:$|[\\s:\u2014\u2013\\-)\\]])`);function am(e,t,n){let r=ol.exec(e);if(r)return r[1];for(let o=t.length-1;o>=0;o--){let i=ol.exec(t[o]);if(i)return i[1]}return n}var gn="CORRECTION (verify-recs)",lm=/\b(add(?:ed|ing|s)?|implement(?:ed|ing|s)?|inject(?:ed|ing|s)?|creat(?:e|ed|ing|es)|introduc(?:e|ed|ing|es))\b/i,cm=/\b(none existed|never existed|there (?:was|is|were|are) no|not present|missing|absent|lack(?:s|ed|ing)?|ha[sd] no|have no|did ?not (?:previously )?(?:have|exist|serve)|didn['’]?t (?:previously )?(?:have|exist|serve)|does ?not (?:have|exist|serve)|doesn['’]?t (?:have|exist|serve)|no existing)\b/i,um=/\b(pages|posts|articles|subpages|templates|blog posts|every page|all pages)\b/i,il=/\b(home ?page)\b/i,gl=["organization","softwareapplication","website","webpage","aboutpage","contactpage","collectionpage","profilepage","article","blogposting","newsarticle","faqpage","qapage","breadcrumblist","product","howto","itemlist","localbusiness","person","review","aggregaterating","videoobject","event","offer","service","recipe","course","jobposting"],dm=/\bjson[\s-]*ld\b|\bstructured\s+data\b|\bschema\b|@type|\bmarkup\b/i,pm=/\bjson[\s-]*ld\b|\bstructured\s+data\b|\bschema(?:\.org)?\b|@type|\bmarkup\b/.source,ml={faq:"faqpage",faqs:"faqpage",howto:"howto",breadcrumb:"breadcrumblist",breadcrumbs:"breadcrumblist"},fm=new Set(["a","an","the","any","no","not","its","our","your","their","this","that","these","those","some","all","more","extra","additional","further","other","new","net-new","existing","current","valid","proper","correct","appropriate","relevant","basic","full","complete","rich","minimal","page","page-level","site","site-wide","sitewide","global","homepage","structured","json","ld","json-ld","schema","and","or","of","with","without","has","have","had","is","are","was","were","serve","serves","served","serving","include","includes","including","add","adds","added","adding","implement","implemented","implementing","inject","injected","injecting","create","created","creating","introduce","introduced","introducing","missing","absent","lacks","lacking","plus","use","uses","using","need","needs","needed","ship","ships","shipped","emit","emits","render","renders","output","outputs","in","on","for","to","from","per","via","but","still","already","currently","never","previously","only","just","e.g","i.e","etc"]);function gm(e){let t=[],n=new RegExp(pm,"gi"),r;for(;(r=n.exec(e))!==null;){let o=/([A-Za-z][A-Za-z0-9'\u2019.-]*)\s+$/.exec(e.slice(0,r.index));if(!o)continue;let i=o[1].toLowerCase().replace(/['\u2019]s$/,"").replace(/\.+$/,"");!i||fm.has(i)||gl.includes(i)||ml[i]||t.push(i)}return t}function mm(e){let t=e.toLowerCase(),n=new Set;for(let r of gl)new RegExp(`\\b${r}\\b`,"i").test(t)&&n.add(r);for(let[r,o]of Object.entries(ml))new RegExp(`\\b${r}\\b`,"i").test(t)&&n.add(o);return Array.from(n)}var hm=[{id:"title",re:/\btitle\s+tag\b|<title>/i,present:e=>e.titlePresent,label:"a <title> tag"},{id:"meta_description",re:/\bmeta[\s-]*description\b/i,present:e=>e.metaDescriptionPresent,label:"a meta description"},{id:"canonical",re:/\bcanonical\b/i,present:e=>e.canonicalPresent,label:"a canonical tag"},{id:"open_graph",re:/\bopen[\s-]*graph\b|\bog:[a-z]+|\bog\s+tags?\b/i,present:e=>e.openGraphPresent,label:"Open Graph tags"},{id:"twitter_card",re:/\btwitter:[a-z_]+|\btwitter\s+(card|tags?)\b/i,present:e=>e.twitterPresent,label:"a Twitter card"}],ym=["page_url","target_url","page","url","resource","canonical","permalink","live_url"],wm=/^[ \t]*(?:[-*+]\s+)?\*\*(?:page(?:\s+to\s+update)?|target\s+page|url|canonical)\s*:?\*\*:?\s*<?([^\s<>)]+)/im;function bm(e){return/(^|[\\/])(briefs|content|articles|pages|posts)[\\/]/.test(e)}function fn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function km(e){let t="";try{t=new URL(e.url).host.replace(/^www\./,"")}catch{}let n=e.pathname==="/"?"":e.pathname;return(n?[fn(t+n),fn(n)]:[fn(t)]).filter(Boolean)}function sl(e,t){let n=fn(e);if(!n)return null;let r=null,o=0;for(let s of t)for(let a of km(s))n!==a&&!n.endsWith(`-${a}`)||a.length>o&&(r=s,o=a.length);if(r)return r;let i=t.filter(s=>{let a=s.pathname.split("/").filter(Boolean).pop();return a!==void 0&&fn(a)===n});return i.length===1?i[0]:null}function al(e,t){let n=e.trim().replace(/^[<("'`]+/,"").replace(/[>)"'`.,]+$/,"");if(!n)return null;let r=n.toLowerCase();for(let i of t)if(i.url.toLowerCase()===r)return i;let o=r;try{o=new URL(n).pathname.toLowerCase()}catch{}if(o=o.replace(/\/+$/,"")||"/",!o.startsWith("/"))return null;for(let i of t)if(i.pathname.toLowerCase()===o)return i;return null}function vm(e,t,n){let r=/^---\n([\s\S]*?)\n---/.exec(t);if(r)for(let i of ym){let s=new RegExp(`^${i}:\\s*["']?([^"'\\n]+)`,"im").exec(r[1]),a=s?al(s[1],n):null;if(a)return a}let o=wm.exec(t);if(o){let i=al(o[1],n);if(i)return i}if(e&&bm(e)){let i=(e.split(/[\\/]/).pop()??"").replace(/\.md$/i,""),s=sl(i,n);if(s)return s}if(r){let i=/^slug:\s*["']?([^"'\n]+)/im.exec(r[1]),s=i?sl(i[1],n):null;if(s)return s}return null}function Wo(e,t){let n=e.toLowerCase();return t.filter(r=>n.includes(r.url.toLowerCase())||r.pathname!=="/"&&n.includes(r.pathname.toLowerCase()))}function $m(e){let t=[],n=[];for(let r of e){let o=/^(#{1,6})\s+(.*)$/.exec(r);if(o){let i=o[1].length;for(;n.length>0&&n[n.length-1].level>=i;)n.pop();n.push({level:i,text:o[2]})}t.push(n.map(i=>i.text))}return t}function Sm(e,t,n,r){let o=Wo(e,n);if(o.length>0)return{targets:o,basis:"line"};if(il.test(e))return r.homepage?{targets:[r.homepage],basis:"line"}:null;for(let i=t.length-1;i>=0;i--){let s=Wo(t[i],n);if(s.length>0)return{targets:s,basis:"heading"};if(il.test(t[i]))return r.homepage?{targets:[r.homepage],basis:"heading"}:null}return r.fileBound?{targets:[r.fileBound],basis:"file"}:um.test(e)||r.namesOtherPages?null:r.homepage?{targets:[r.homepage],basis:"origin"}:null}function ll(e){return{organization:"Organization",softwareapplication:"SoftwareApplication",website:"WebSite",webpage:"WebPage",blogposting:"BlogPosting",newsarticle:"NewsArticle",faqpage:"FAQPage",breadcrumblist:"BreadcrumbList"}[e]??e.charAt(0).toUpperCase()+e.slice(1)}function xm(e){let t=/^(\s*(?:(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?|>\s+|#{1,6}\s+)?)(.*)$/.exec(e);return t?{prefix:t[1],content:t[2]}:{prefix:"",content:e}}function _m(e,t,n={}){if(_r(t))return{text:e,corrections:[],stale:[]};let r=rm(t).filter(f=>f.fetched);if(r.length===0)return{text:e,corrections:[],stale:[]};let o=r.find(f=>f.pathname==="/")??r[0],i=om(t),s=sm(e),a=e.split(`
|
|
830
830
|
`),l=$m(a),c=[],d=[],p={homepage:o,fileBound:vm(n.filePath,e,r),namesOtherPages:r.some(f=>f!==o&&Wo(e,[f]).length>0)};for(let f=0;f<a.length;f++){let g=a[f];if(g.includes(gn)||!lm.test(g)&&!cm.test(g)&&!/\bno\b/i.test(g))continue;let h=Sm(g,l[f],r,p);if(!h||h.targets.length===0)continue;let y=h.targets,w=[];for(let K of hm){let G=K.re.exec(g);G&&ul(g,G.index,G[0])&&y.every(te=>K.present(te))&&w.push(K.label)}let b=dm.exec(g);if(b&&ul(g,b.index,b[0])){let K=mm(g);if(K.length>0){let G=K.filter(te=>y.every(Qe=>Qe.jsonLdTypes.includes(te)));G.length>0&&w.push(`${G.map(ll).join(", ")} JSON-LD`)}else gm(g).length===0&&y.every(G=>G.jsonLdTypes.length>0)&&w.push(`JSON-LD (${Array.from(new Set(y.flatMap(G=>G.jsonLdTypes))).map(ll).join(", ")})`)}if(w.length===0)continue;let E=w.join(" + "),H=y.map(K=>K.url).join(", "),T=i?am(g,l[f],s):null;if(i&&T&&T<i){d.push({line:f+1,original:g,entityLabel:E,pageUrl:H,basis:h.basis,authoredAt:T,capturedAt:i});continue}let{prefix:M,content:se}=xm(g),U=`${M}~~${se}~~ \u2192 ${gn}: the live page (${H}) already serves ${E} per evidence.md \u2014 this was a repo-source reconciliation, not a net-new addition.`;a[f]=U,c.push({line:f+1,original:g,corrected:U,entityLabel:E,pageUrl:H,basis:h.basis})}return{text:a.join(`
|
|
831
831
|
`),corrections:c,stale:d}}var Cm=/^\s*(?:$|[()[\]{}.,;:!?'"’”…]|—|–|→|\btags?\b|\belements?\b|\bmeta\b|\bmarkup\b|\bstructured\b|\bdata\b|\bcards?\b|\blinks?\b|\burls?\b|\bdeclarations?\b|\bsnippets?\b|\battributes?\b|\bentr(?:y|ies)\b|\brel\b|\bhref\b|\bschema\b|\bjson[\s-]*ld\b|\bis\b|\bare\b|\bwas\b|\bwere\b|\bisn['’]?t\b|\baren['’]?t\b|\bwasn['’]?t\b|\bweren['’]?t\b|\bdid\b|\bdidn['’]?t\b|\bdoes\b|\bdoesn['’]?t\b|\bha[sd]\b|\bhasn['’]?t\b|\bhadn['’]?t\b|\bnot\b|\bnever\b|\bpresent\b|\bfound\b|\bexists?\b|\bexisted\b|\bset\b|\bdefined\b|\bconfigured\b|\bmissing\b|\babsent\b|\banywhere\b|\bat\s+all\b|\byet\b|\bto\b|\bon\b|\bfor\b|\bin\b|\binto\b|\bacross\b|\bat\b|\bvia\b|\bwith\b|\band\b|\bor\b|\bplus\b|\bper\b|https?:|\/|`)/i,Em=/\b(?:add(?:ed|ing|s)?|implement(?:ed|ing|s)?|inject(?:ed|ing|s)?|creat(?:e|ed|ing|es)|introduc(?:e|ed|ing|es))\s+(?:[\w`'’"/-]+\s+){0,3}$/i,Rm=/\b(?:no|not|missing|absent|without|zero|lack(?:s|ed|ing)?|ha[sd]\s+no|have\s+no|never\s+(?:had|served|shipped)|(?:do|does|did)\s*(?:n['’]t|\s+not)?\s+(?:have|serve|include|ship|set|emit|render|output)|don['’]t\s+(?:have|serve|include|ship|set|emit|render|output))\s+(?:(?:a|an|the|any|its|valid|proper|correct|self-referencing)\s+){0,2}$/i,cl=/^\s*[:,(]?\s*(?:tags?|elements?|meta|markup|data|cards?|links?|urls?|declarations?|snippets?|attributes?)?\s*(?:(?:is|are|was|were|ha[sd])\s+)?(?:still\s+)?(?:missing|absent|nowhere|not\s+(?:previously\s+)?(?:present|set|defined|found|served|rendered|emitted)|never\s+(?:previously\s+)?existed|did\s*n(?:ot|['’]?t)\s+(?:previously\s+)?(?:exist|have)|does\s*n(?:ot|['’]?t)\s+(?:currently\s+)?(?:exist|have)|no\s+longer\s+exists?)\b/i,Am=/^\s*[:,(]?\s*(?:tags?|elements?|meta|markup|data|cards?|links?|schema)?\s*(?:is|are|was|were|do|does|did|would|will|can|could|should|must)\s*n(?:ot|['’]t)\b/i;function ul(e,t,n){let r=e.slice(t+n.length),o=e.slice(Math.max(0,t-64),t);return!Cm.test(r)||!cl.test(r)&&Am.test(r)?!1:Em.test(o)||Rm.test(o)||cl.test(r)}function hl(e){let t=`~~ \u2192 ${gn}:`;if(!e.includes(t))return{text:e,stripped:0};let n=e.split(`
|
|
832
832
|
`),r=0;for(let o=0;o<n.length;o++){let i=n[o].indexOf(t);if(i===-1)continue;let s=n[o].slice(0,i),a=s.indexOf("~~");a!==-1&&(n[o]=s.slice(0,a)+s.slice(a+2),r++)}return{text:n.join(`
|
|
833
|
-
`),stripped:r}}var Pm=
|
|
833
|
+
`),stripped:r}}var Pm=gt.join(k,"audit","evidence.md");function dl(e){let t=e.split(fl).join("/");return t===Pm||t===gt.join(k,"audit","findings.md")||t===gt.join(k,"pages.md")||t===gt.join(k,"keywords.md")||t===gt.join(k,"llms.md")||t.startsWith(gt.join(k,"okf")+"/")||t.startsWith(gt.join(k,"inbox")+"/")}function pl(e){return e.split(fl).join("/").split("/").includes(".claude")}function yl(e,t=[]){let n;try{n=Zg(e)}catch{return t}for(let r of n){let o=Ho(e,r),i;try{i=em(o)}catch{continue}i.isDirectory()?yl(o,t):r.endsWith(".md")&&t.push(o)}return t}function Mt(e,t={}){let n=Ho(e,k,"audit","evidence.md"),r={evidenceFound:tl(n),evidencePath:n,sourceRender:!1,scanned:[],skipped:[],corrections:[],stale:[]};if(!r.evidenceFound)return r;let o=el(n,"utf-8");if(_r(o))return r.sourceRender=!0,r;let i=new Map;for(let s of yl(Ho(e,k))){let a=nl(e,s);dl(a)||pl(a)||i.set(rl(s),a)}for(let s of t.extraFiles??[]){let a=rl(e,s),l=nl(e,a);if(dl(l)||pl(l)){r.skipped.push(l);continue}tl(a)?i.set(a,l):r.skipped.push(l)}for(let[s,a]of i){let l;try{l=el(s,"utf-8")}catch{continue}r.scanned.push(a);let{text:c,corrections:d,stale:p}=_m(l,o,{filePath:a});if(d.length>0){tm(s,c,"utf-8");for(let f of d)r.corrections.push({...f,file:a})}for(let f of p)r.stale.push({...f,file:a})}return r}function jm(e){if(!e)return{};let t={"X-SEOAgent-Agent":e.agent,"X-SEOAgent-Auth-Source":e.authSource,"X-SEOAgent-Silent":e.silent?"1":"0"};return e.cliVersion&&(t["X-SEOAgent-CLI-Version"]=e.cliVersion),e.installId&&(t["X-SEOAgent-Install-Id"]=e.installId),t}function Dm(e){let t=e.directives;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let{key:o,text:i,tone:s}=r;typeof o!="string"||!o||typeof i!="string"||!i.trim()||n.push({key:o,text:i.trim(),tone:s==="upsell"||s==="action"?s:"info"})}return n}function $l(e){if(typeof e!="string")return{force:e===!0};let t=e.trim().replace(/\\/g,"/").replace(/^\.?\/+/,"").replace(/^\.seoagent\//,"").replace(/^\/+/,"");return t?{force:!1,forcePaths:[t]}:{force:!0}}function bl(e){return"sha256:"+kl("sha256").update(e).digest("hex")}function ge(e){return kl("sha256").update(e,"utf-8").digest("hex")}function Mm(e,t,n={}){let r=[],o=i=>n.force===!0||n.forcePaths?.includes(i)===!0;for(let i of e.artifacts){let s=t[i.path]??{exists:!1,locallyEdited:!1};if(!s.exists){r.push({path:i.path,kind:"write",body:i.body_md});continue}if(s.contentHash===i.content_hash){r.push({path:i.path,kind:"skip"});continue}if(s.verifyRecsStrippedHash===i.content_hash){r.push({path:i.path,kind:"skip",note:"local differs from cloud only by verify-recs corrections (written by the CLI, not by you)"});continue}if(i.generated){r.push({path:i.path,kind:"overwrite",body:i.body_md,note:s.locallyEdited?"discarded local edits \u2014 this is a cloud-generated file (edit it in the dashboard)":void 0});continue}if(s.trackingPointer&&s.locallyEdited){r.push({path:i.path,kind:"overwrite",body:i.body_md,note:"replaced the tracking-pointer stub with the cloud draft (the stub was written by `content track`, not by you)"});continue}if(i.path==="context.md"&&s.scaffoldContext&&!ve(i.body_md)){r.push({path:i.path,kind:"overwrite",body:i.body_md,note:"replaced the `seoagent init` scaffold with the owner-authored cloud context (the scaffold was written by `init`, not by you)"});continue}if(s.locallyEdited&&!o(i.path)){r.push({path:i.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}r.push({path:i.path,kind:"overwrite",body:i.body_md})}for(let i of e.deleted){let s=t[i];if(!(!s||!s.exists)){if(s.locallyEdited&&!o(i)){r.push({path:i,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}r.push({path:i,kind:"delete"})}}return r}function Fm(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:Za(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 Sl(e){let t=await qo(e);return t.ok?t.artifact?{ok:!0,body:t.artifact.body_md}:{ok:!1,error:`No cloud artifact found at "${e.path.replace(/^\/+/,"").replace(/\\/g,"/")}"`}:t}async function qo(e){let t=await _l({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,"/");return{ok:!0,artifact:t.manifest.artifacts.find(r=>r.path===n)??null}}function xl(e,t){return Ko(e,t.split("/").join(Nm))}function Um(e,t,n){let r={};for(let o of t){let i=xl(e,o);if(!vl(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=n[o],a=Om(i,"utf-8"),l=!s||s.hash!==ge(a),c=Ka(a),d=hl(a);r[o]={exists:!0,contentHash:bl(a),locallyEdited:l,...o==="context.md"&&ve(a)?{scaffoldContext:!0}:{},...c?{trackingPointer:c}:{},...d.stripped>0?{verifyRecsStrippedHash:bl(d.text)}:{}}}return r}async function _l(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",...jm(e.meta)}});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 Cl(e){let t=Ko(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,conflictPaths:[],pointerOverwrites:{},deleted:0,warnings:[],cursor:e.since};if(!vl(t))return{...n,ok:!0};let r=await _l({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl,meta:e.meta});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=Um(t,i,e.stateFiles),a=Mm(o,s,{force:e.force,forcePaths:e.forcePaths}),l={...n,pointerOverwrites:{},cursor:o.now,directives:Dm(o)};for(let d of a){let p=xl(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{Im(Lm(p),{recursive:!0});let f=d.body??"";wl(p,f,"utf-8"),e.stateFiles[d.path]={hash:ge(f)},d.kind==="write"?l.written++:l.overwritten++;let g=s[d.path]?.trackingPointer;d.kind==="overwrite"&&g&&(l.pointerOverwrites[d.path]=g),d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.conflictPaths.push(d.path),l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Tm(p,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.conflictPaths.push(d.path),l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(f){l.ok=!1,l.error=`${d.path}: ${f.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let c=Fm(a,o,l.cursor,new Date().toISOString());if(c)try{wl(Ko(t,qn),JSON.stringify(c,null,2)+`
|
|
834
834
|
`,"utf-8")}catch{}return l}var mn="context.md",Km="context.md: the cloud copy is owner-authored and your local version does not derive from it \u2014 NOT pushed, both copies kept. Compare with `seoagent pull --print context.md`, merge into the local file, then sync; or take the cloud copy with `seoagent sync --force context.md`.",qm="context.md: replaced the local `seoagent init` scaffold with the owner-authored cloud context (the scaffold was written by `init`, not by you).",Vm="context.md: took the cloud copy (`--force context.md`) \u2014 the local version was replaced.";function zm(e){return ve(e.localBody)?!0:!e.prevStateHash||e.prevStateHash!==ge(e.localBody)}function Ym(e){let{localBody:t,prevStateHash:n,cloudBody:r}=e;return r===null?{kind:"none"}:ge(t)===ge(r)?{kind:"none"}:ve(r)?{kind:"none"}:ve(t)?{kind:"restore",body:r,notice:qm}:n&&n===ge(r)?{kind:"none"}:e.forceTakeCloud?{kind:"restore",body:r,notice:Vm}:e.forcePushLocal?{kind:"none"}:{kind:"block-push",notice:Km}}var hn={restored:!1,blockPush:!1,notices:[]};async function El(e){let t=Wm(e.seoagentDir,mn);if(!Bm(t))return hn;let n;try{n=Gm(t,"utf-8")}catch{return hn}let r=e.stateFiles[mn]?.hash??null;if(!zm({localBody:n,prevStateHash:r}))return hn;let o=await qo({apiBase:e.apiBase,authHeader:e.authHeader,path:mn,fetchImpl:e.fetchImpl});if(!o.ok)return{restored:!1,blockPush:!ve(n)&&(!r||r!==ge(n)),notices:[]};let i=Ym({localBody:n,prevStateHash:r,cloudBody:o.artifact?.body_md??null,forceTakeCloud:e.forcePaths?.includes(mn)===!0,forcePushLocal:e.force===!0});switch(i.kind){case"none":return hn;case"restore":try{Hm(t,i.body,"utf-8")}catch{return hn}return e.stateFiles[mn]={hash:ge(i.body)},{restored:!0,blockPush:!1,notices:[i.notice]};case"block-push":return{restored:!1,blockPush:!0,notices:[i.notice]}}}import{existsSync as Al,mkdirSync as Pl,readFileSync as Jm,writeFileSync as Vo}from"fs";import{dirname as Il,join as Xm}from"path";var zo=1,Rl=500;function Yo(e){return Xm(e,k,Qi)}function Cr(e){let t=Yo(e);if(!Al(t))return[];try{let n=Jm(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==zo||!Array.isArray(o.entries)?[]:o.entries.filter(Qm)}catch{return[]}}function Ol(e,t){let n=Yo(e),o=Cr(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>Rl?o.slice(-Rl):o,s={version:zo,entries:i};try{Pl(Il(n),{recursive:!0}),Vo(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Tl(e,t){if(t.length===0)return;let n=Yo(e),r=Cr(e).filter(i=>!t.includes(i.action_id)),o={version:zo,entries:r};try{if(r.length===0&&Al(n)){Vo(n,JSON.stringify(o,null,2),"utf-8");return}Pl(Il(n),{recursive:!0}),Vo(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function Qm(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 Ll,readFileSync as Zm,unlinkSync as eh,writeFileSync as th,openSync as nh,closeSync as rh,mkdirSync as oh}from"fs";import{dirname as ih,join as sh}from"path";var ah=6e4;function Nl(e){return sh(e,k,Zi)}function jl(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??ah,i=Nl(e);if(!Ll(i))return Er(i,r,n());let s=Ml(i);return!s||n()-s.started_at>o||!lh(s.pid)?Er(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function Dl(e,t={}){let n=t.pid??process.pid,r=Nl(e);if(!Ll(r))return;let o=Ml(r);if(!(o&&o.pid!==n))try{eh(r)}catch{}}function Er(e,t,n){let r={pid:t,started_at:n};try{oh(ih(e),{recursive:!0});let o=nh(e,"w");try{th(o,JSON.stringify(r))}finally{rh(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Ml(e){try{let t=Zm(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 lh(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}import{existsSync as Yl,mkdirSync as wh,readFileSync as Jl,writeFileSync as bh}from"fs";import{dirname as kh,join as bn}from"path";import{existsSync as Ar,readFileSync as Hl,readdirSync as ch}from"fs";import{join as wn}from"path";var Pr="llms.md",uh=160,Fl=100;function Rr(e,t=uh){let n=e.replace(/\s+/g," ").replace(/[[\]]/g,"").trim();return n.length<=t?n:n.slice(0,t-1).trimEnd()+"\u2026"}function Jo(e){let t=L(e);if(t==="/")return"Home";let r=(t.split("/").filter(Boolean).pop()||"Home").replace(/[-_]+/g," ").replace(/\.(html?|md|php)$/i,"").trim();return r?r.split(" ").map(o=>o.length>0?o[0].toUpperCase()+o.slice(1):o).join(" "):"Home"}var dh=new Set(["readme","changelog","license","licence","contributing","contributors","code_of_conduct","code-of-conduct","security","authors","notice","agents","claude","cursorrules","codeowners","copying","maintainers"]);function ph(e){let t=Number.parseInt(String(e).trim(),10);return Number.isFinite(t)?t>=400&&t<=599:!1}function Wl(e){let t=L(e).split("/").filter(Boolean).pop();return t?dh.has(t.replace(/\.(md|mdx|txt|html?)$/i,"").toLowerCase()):!1}function Ul(e){let t=Rr(e.label,80)||Jo(e.url),n=e.description?Rr(e.description):"";return`- [${t}](${e.url})${n?`: ${n}`:""}`}function Kl(e){let t=[`# ${Rr(e.siteName,100)}`,""];if(e.summary&&t.push(`> ${Rr(e.summary,300)}`,""),e.pages.length>0){t.push("## Pages","");for(let n of e.pages)t.push(Ul(n));t.push("")}if(e.articles.length>0){t.push("## Articles","");for(let n of e.articles)t.push(Ul(n));t.push("")}return t.join(`
|
|
835
835
|
`).replace(/\n+$/,`
|
|
836
|
-
`)}function fh(e){let t=new Map,n=null;for(let r of e.split(/\r?\n/)){let o=/^##\s+(https?:\/\/\S+)\s*$/.exec(r);if(o){n=L(o[1]),t.has(n)||t.set(n,{});continue}if(!n)continue;if(/^##\s/.test(r)){n=null;continue}let i=/^-\s+\*\*title:\*\*\s+(.*)$/.exec(r);if(i&&i[1]!=="_(none)_"){t.get(n).title=i[1].trim();continue}let s=/^-\s+\*\*meta description:\*\*\s+(.*)$/.exec(r);s&&s[1]!=="_(none)_"&&(t.get(n).description=s[1].trim())}return t}function gh(e){let t=wn(e,k,"audit","evidence.md");if(!Ar(t))return new Map;try{return fh(Hl(t,"utf-8"))}catch{return new Map}}function mh(e,t,n){let r=wn(e,k,"content");if(!Ar(r))return[];let o=new Map,i;try{i=ch(r)}catch{return[]}for(let s of i.sort()){if(!s.toLowerCase().endsWith(".md"))continue;let a;try{a=ue(Hl(wn(r,s),"utf-8")).data}catch{continue}let l=typeof a.canonical=="string"?a.canonical.trim():"",c=typeof a.status=="string"?a.status.toLowerCase():"";if(!l||c==="draft"||Wl(l)||n?.has(L(l)))continue;let d=typeof a.title=="string"&&a.title.trim()?a.title.trim():Jo(l),p=t.get(L(l)),f={url:l,label:p?.title||d,...p?.description?{description:p.description}:{}},g=typeof a.slug=="string"?a.slug.trim():s.slice(0,-3),h=L(l).split("/").filter(Boolean).pop()??"",y=g===h,w=o.get(l);(!w||y&&!w.slugMatchesUrl)&&o.set(l,{link:f,slugMatchesUrl:y})}return Array.from(o.values(),s=>s.link)}function Bl(e){try{return new URL(e).host.toLowerCase().replace(/^www\./,"")}catch{return""}}function yn(e){return/^http:\/\//i.test(e)}function hh(e,t,n,r){let o=[Qt,ar].map(a=>wn(e,k,a)).filter(a=>Ar(a));if(o.length===0)return[];let i=t.toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,""),s=new Map;for(let a of o.flatMap(l=>[...cr(l).keys()])){if(!/^https?:\/\//i.test(a))continue;let l=L(a);if(de(l)||Wl(a)||r?.has(l))continue;let d=`${Bl(a)}${l}`,p=s.get(d);if(!p){s.set(d,a);continue}if(yn(p)!==yn(a)){yn(p)&&s.set(d,a);continue}let f="";try{f=new URL(a).hostname.toLowerCase()}catch{f=""}f===i&&s.set(d,a)}return n?Array.from(s.values()):Array.from(s.values(),a=>yn(a)&&Bl(a)===i.replace(/^www\./,"")?a.replace(/^http:\/\//i,"https://"):a)}function yh(e){let t=new Set;for(let n of[Qt,ar]){let r=wn(e,k,n);if(Ar(r))for(let o of cr(r).values())ph(o.status)&&t.add(L(o.url))}return t}function Gl(e){return[...e].sort((t,n)=>{let r=L(t.url),o=L(n.url);return r==="/"?o==="/"?0:-1:o==="/"?1:r.localeCompare(o)})}function ql(e,t){let n=t.domain.replace(/^https?:\/\//,"").replace(/\/+$/,""),r=(()=>{try{return
|
|
837
|
-
`,"utf-8")}function Dh(e,t){return Rh(e,t).split(Ah).join("/")}async function Mh(e,t){try{let n=await I(`${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 Fh(e,t,n){try{let r=await I(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:i.slice(0,200)}}let o=typeof r.json=="function"?await r.json().catch(()=>null):null;return{ok:!0,status:r.status,...o?.agent_notice?{agentNotice:o.agent_notice}:{}}}catch(r){return{ok:!1,status:0,error:r.message}}}async function tc(e,t={}){let n=Ph(e),r=d=>{let p=n?{...d,verifyRecs:n}:{...d};return s&&(p={...p,aiFiles:s}),i&&i.added>0&&(p={...p,pagesRescan:{added:i.added,total:i.total,file:i.file}}),p},o=_(e),i=null;if(o&&!t.pullOnly)try{i=await kn(e)}catch{}let s=null;if(o)try{s=Ft(e,o)}catch{}let a=N(o?.domain);if(!a)return r({ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]});if(!o)return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(o.domain===He)return r({ok:!0,reason:"domain-unknown",synced:0,failed:0,errors:[]});let l=ei(e,k);if(!Zo(l))return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(!jl(e).acquired)return r({ok:!0,reason:"busy",synced:0,failed:0,errors:[]});try{return r(await Uh(e,t,a,o,l))}finally{Dl(e)}}async function Uh(e,t,n,r,o){let i=n.api_base||O.BASE,s=`Bearer ${n.user_token}:${n.website_token}`,a=await Ke({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 l=Nh(r.domain);try{Va(e,r)}catch{}let c=Th(o),d=0,p=0,f=[],g=[],h=0,y=await Gh(e,i,s),w={restored:!1,blockPush:!1,notices:[]};if((!t.pathFilter||"context.md".endsWith(t.pathFilter))&&(w=await El({seoagentDir:o,apiBase:i,authHeader:s,stateFiles:l.files,force:t.force,forcePaths:t.forcePaths}),f.push(...w.notices)),!t.pullOnly)for(let P of c){let q=Dh(o,P);if(t.pathFilter&&!q.endsWith(t.pathFilter)||q==="context.md"&&w.blockPush)continue;let Ze=Zl(P,"utf-8"),ht=ge(Ze),Hn=l.files[q];if(!(!Hn||Hn.hash!==ht)&&!t.force)continue;h++;let et=await Fh(i,{path:q,contents:Ze,domain:r.domain},s);et.ok?(l.files[q]={hash:ht},d++,et.agentNotice&&f.push(`${q}: ${et.agentNotice}`)):(p++,g.push(`${q}: ${et.status} ${et.error??""}`.trim()))}let b=await Mh(i,s),E=0,H=0,T=[],M=0,se=0;!b.ok&&b.error&&g.push(`pull actions: ${b.error}`);let U,K=[],G=new Map,te=!1,Qe=[],we=l.last_synced_at;if(!t.pushOnly){let P=await Cl({projectDir:e,apiBase:i,authHeader:s,since:l.last_synced_at,stateFiles:l.files,force:t.force,forcePaths:t.forcePaths,meta:Bh(e,!!t.silent)});Qe=P.directives??[],P.ok?we=P.cursor:(te=!0,P.error&&g.push(`pull: ${P.error}`)),U={written:P.written,overwritten:P.overwritten,skipped:P.skipped,conflicts:P.conflicts,deleted:P.deleted,warnings:P.warnings},K=P.conflictPaths;for(let[q,Ze]of Object.entries(P.pointerOverwrites)){let ht=q.match(/^content\/(.+)\.md$/)?.[1];ht&&G.set(ht,Ze)}}if(b.ok){let P=Go(e);for(let[Re,yt]of G)P.set(Re,yt);let q=Qa(e,b.actions,{conflictedPaths:new Set(K),localPointers:P});E=q.wrote,H=q.removed,M=q.skippedUnknown;let Ze=l.announced_at?Date.parse(l.announced_at):NaN,Hn=q.pendingIds.length>0&&(Number.isNaN(Ze)||Date.now()-Ze>=Lh)?new Set:new Set(l.announced_action_ids??[]),Wn=new Set(q.pendingIds.filter(Re=>!Hn.has(Re)));T=q.pending.filter(Re=>Wn.has(Re.id)),se=Wn.size-T.length,l.announced_action_ids=q.pendingIds,Wn.size>0&&(l.announced_at=new Date().toISOString());let et=Ya(b.actions);U&&K.length>0&&(U.warnings=U.warnings.map(Re=>{let yt=K.find(Xr=>Re.startsWith(`${Xr}:`)),Jr=yt?et.get(yt):void 0;return!yt||!Jr?.length?Re:`${Re} \u2014 blocks inbox action${Jr.length===1?"":"s"} ${Jr.map(Xr=>`#${Xr}`).join(", ")}; take the cloud copy with \`seoagent sync --force ${yt}\``}))}let Bn=!!U&&U.written+U.overwritten+U.deleted+U.conflicts>0;if(l.last_synced_at=we,jh(r.domain,l),h===0&&E===0&&H===0&&!Bn&&!w.restored&&w.notices.length===0&&y.flushed===0&&y.dropped===0&&!te&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:g,actionsPulled:0,actionsRemoved:0,actionsNew:[],actionsUnknown:M,actionsUnknownNew:se,acksFlushed:0,acksDropped:0,pull:U,directives:Qe};let Gn=p===0&&!te;return{ok:Gn,reason:Gn?void 0:"error",synced:d,failed:p,errors:g,...f.length>0?{notices:f}:{},actionsPulled:E,actionsRemoved:H,actionsNew:T,actionsUnknown:M,actionsUnknownNew:se,acksFlushed:y.flushed,acksDropped:y.dropped,pull:U,directives:Qe}}function Bh(e,t){let n=ke(),r=n?null:_(e)?.install_id??null;return{cliVersion:n?null:C,agent:Ba(),authSource:ks(),installId:r||null,silent:t}}async function Gh(e,t,n){let r=Cr(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await Hh(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Tl(e,s),{flushed:o,dropped:i}}async function Hh(e,t,n){try{let r=await I(`${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 nc(e,t=3e4){let n=setTimeout(e,t);return n.unref?.(),{cancel:()=>clearTimeout(n)}}function rc(e){let t;try{t=_(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(Je(C,n)<=0){if(!t.skill_version)try{Y(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return $t(e),Y(e,{skill_version:C}),{refreshed:!0,from:n,to:C,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function ti(e){let t;try{t=_(e)}catch{return{refreshed:!1,from:null,to:C,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:C,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return $t(e),Y(e,{skill_version:C}),{refreshed:!0,from:n,to:C,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:C,reason:"error"}}}import{createHash as Wh}from"crypto";import{existsSync as mC,mkdirSync as Kh,readFileSync as qh,writeFileSync as Vh}from"fs";import{join as zh}from"path";var Yh="/cli-skill/manifest.json",Jh=360*60*1e3,Xh=4e3,Qh=64,Zh=4*1024*1024,oc=zh(z,"skill-check.json"),ey=e=>Wh("sha256").update(e).digest("hex");function ty(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.hash!="string"||!/^[0-9a-f]{64}$/.test(t.hash)||typeof t.min_cli!="string"||!/^\d+\.\d+\.\d+/.test(t.min_cli)||!Array.isArray(t.files)||t.files.length===0||t.files.length>Qh)return null;let n=[],r=0;for(let o of t.files){if(typeof o!="object"||o===null)return null;let i=o;if(typeof i.path!="string"||typeof i.sha256!="string"||!/^[A-Za-z0-9._/-]+$/.test(i.path)||i.path.startsWith("/")||i.path.split("/").includes("..")||!i.path.endsWith(".md")||!/^[0-9a-f]{64}$/.test(i.sha256))return null;let s=typeof i.bytes=="number"?i.bytes:0;r+=s,n.push({path:i.path,sha256:i.sha256,bytes:s})}return r>Zh||!n.some(o=>o.path==="SKILL.md")?null:{hash:t.hash,min_cli:t.min_cli,files:n}}function ny(e,t,n=Jh){if(!e)return!0;let r=Date.parse(e);return Number.isNaN(r)?!0:t.getTime()-r>=n}function ry(){try{return JSON.parse(qh(oc,"utf-8"))}catch{return{}}}function oy(e){try{Kh(z,{recursive:!0}),Vh(oc,JSON.stringify({checkedAt:e}),"utf-8")}catch{}}async function iy(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(Xh),headers:{"User-Agent":`seoagent-cli/${C}`}});return t.ok?await t.text():null}catch{return null}}async function ic(e,t={}){try{let n=_(e);if(!n)return{updated:!1,reason:"no-project"};let r=t.now??new Date,o=ry();if(!t.force&&!ny(o.checkedAt,r))return{updated:!1,reason:"throttled"};let i=(t.baseUrl??O.BASE).replace(/\/$/,""),s=t.fetchText??iy,a=await s(`${i}${Yh}`);if(oy(r.toISOString()),a===null)return{updated:!1,reason:"unreachable"};let l;try{l=ty(JSON.parse(a))}catch{l=null}if(!l)return{updated:!1,reason:"malformed"};if(n.skill_hash===l.hash)return{updated:!1,reason:"up-to-date"};if(Je(C,l.min_cli)<0)return{updated:!1,reason:"cli-too-old",minCli:l.min_cli};let c={};for(let d of l.files){let p=await s(`${i}/cli-skill/${d.path}`);if(p===null)return{updated:!1,reason:"unreachable"};if(ey(p)!==d.sha256)return{updated:!1,reason:"verify-failed"};c[d.path]=p}return Es(e,c),Y(e,{skill_hash:l.hash}),{updated:!0,reason:"updated",fileCount:l.files.length}}catch{return{updated:!1,reason:"error"}}}import{existsSync as sy,mkdirSync as ay,readFileSync as ly,writeFileSync as cy}from"fs";var uy="https://registry.npmjs.org/@seoagent-official/seoagent/latest",dy=1440*60*1e3,py=720*60*1e3,fy=2e3;function gy(e,t,n=dy){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function my(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??py;if(!n||Je(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 hy(e){let t=e.readCache();if(gy(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=my({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 yy(){try{return sy(Vn)?JSON.parse(ly(Vn,"utf-8")):{}}catch{return{}}}function wy(e){try{ay(z,{recursive:!0}),cy(Vn,JSON.stringify(e,null,2)+`
|
|
836
|
+
`)}function fh(e){let t=new Map,n=null;for(let r of e.split(/\r?\n/)){let o=/^##\s+(https?:\/\/\S+)\s*$/.exec(r);if(o){n=L(o[1]),t.has(n)||t.set(n,{});continue}if(!n)continue;if(/^##\s/.test(r)){n=null;continue}let i=/^-\s+\*\*title:\*\*\s+(.*)$/.exec(r);if(i&&i[1]!=="_(none)_"){t.get(n).title=i[1].trim();continue}let s=/^-\s+\*\*meta description:\*\*\s+(.*)$/.exec(r);s&&s[1]!=="_(none)_"&&(t.get(n).description=s[1].trim())}return t}function gh(e){let t=wn(e,k,"audit","evidence.md");if(!Ar(t))return new Map;try{return fh(Hl(t,"utf-8"))}catch{return new Map}}function mh(e,t,n){let r=wn(e,k,"content");if(!Ar(r))return[];let o=new Map,i;try{i=ch(r)}catch{return[]}for(let s of i.sort()){if(!s.toLowerCase().endsWith(".md"))continue;let a;try{a=ue(Hl(wn(r,s),"utf-8")).data}catch{continue}let l=typeof a.canonical=="string"?a.canonical.trim():"",c=typeof a.status=="string"?a.status.toLowerCase():"";if(!l||c==="draft"||Wl(l)||n?.has(L(l)))continue;let d=typeof a.title=="string"&&a.title.trim()?a.title.trim():Jo(l),p=t.get(L(l)),f={url:l,label:p?.title||d,...p?.description?{description:p.description}:{}},g=typeof a.slug=="string"?a.slug.trim():s.slice(0,-3),h=L(l).split("/").filter(Boolean).pop()??"",y=g===h,w=o.get(l);(!w||y&&!w.slugMatchesUrl)&&o.set(l,{link:f,slugMatchesUrl:y})}return Array.from(o.values(),s=>s.link)}function Bl(e){try{return new URL(e).host.toLowerCase().replace(/^www\./,"")}catch{return""}}function yn(e){return/^http:\/\//i.test(e)}function hh(e,t,n,r){let o=[Qt,ar].map(a=>wn(e,k,a)).filter(a=>Ar(a));if(o.length===0)return[];let i=t.toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,""),s=new Map;for(let a of o.flatMap(l=>[...cr(l).keys()])){if(!/^https?:\/\//i.test(a))continue;let l=L(a);if(de(l)||Wl(a)||r?.has(l))continue;let d=`${Bl(a)}${l}`,p=s.get(d);if(!p){s.set(d,a);continue}if(yn(p)!==yn(a)){yn(p)&&s.set(d,a);continue}let f="";try{f=new URL(a).hostname.toLowerCase()}catch{f=""}f===i&&s.set(d,a)}return n?Array.from(s.values()):Array.from(s.values(),a=>yn(a)&&Bl(a)===i.replace(/^www\./,"")?a.replace(/^http:\/\//i,"https://"):a)}function yh(e){let t=new Set;for(let n of[Qt,ar]){let r=wn(e,k,n);if(Ar(r))for(let o of cr(r).values())ph(o.status)&&t.add(L(o.url))}return t}function Gl(e){return[...e].sort((t,n)=>{let r=L(t.url),o=L(n.url);return r==="/"?o==="/"?0:-1:o==="/"?1:r.localeCompare(o)})}function ql(e,t){let n=t.domain.replace(/^https?:\/\//,"").replace(/\/+$/,""),r=(()=>{try{return xt(e)}catch{return null}})(),o=gh(e),i=yh(e),s=mh(e,o,i),a=new Set(s.map(p=>L(p.url))),l=[];for(let p of hh(e,n,yn(t.domain),i)){let f=L(p);if(a.has(f))continue;let g=o.get(f);l.push({url:p,label:g?.title||Jo(p),...g?.description?{description:g.description}:{}})}if(l.length===0&&s.length===0)return null;let c=r?.business?.name?.trim()||o.get("/")?.title||n,d=r?.business?.description?.trim()||o.get("/")?.description||null;return{siteName:c,summary:d,pages:Gl(l).slice(0,Fl),articles:Gl(s).slice(0,Fl)}}var Ir=".well-known/okf",Vl="llms.txt",zl={publicDir:null,publicDirSource:null,llmsSourceWritten:!1,llmsPublished:null,okfPublished:0,okfPublishedDir:null,llmsRoute:null,llmsRouteDrift:!1,skipped:[]};function Xo(e,t){try{return Yl(e)&&Jl(e,"utf-8")===t?!1:(wh(kh(e),{recursive:!0}),bh(e,t,"utf-8"),!0)}catch{return!1}}function Ft(e,t){if(!t.domain||t.domain==="unknown")return{...zl,skipped:["no-domain"]};let n=Zn(e,t.public_dir??null),r={...zl,publicDir:n.dir,publicDirSource:n.source,skipped:[]},o=null;try{let s=ql(e,t);o=s?Kl(s):null}catch{o=null}if(o===null)r.skipped.push("llms-no-content");else if(r.llmsSourceWritten=Xo(bn(e,k,Pr),o),r.llmsRoute=as(e,n.dir),r.llmsRoute)r.skipped.push("llms-route-owned"),r.llmsRouteDrift=r.llmsSourceWritten&&t.llms_owner!=="route";else if(n.dir){let s=bn(e,n.dir,Vl);Xo(s,o)&&(r.llmsPublished=`${n.dir}/${Vl}`)}let i=Rt(e);if(!Yl(i))r.skipped.push("okf-missing");else if(ha(i))r.skipped.push("okf-placeholder");else if(!pr(i).ok)r.skipped.push("okf-invalid");else if(n.dir){let s=bn(e,n.dir,Ir),a=0;for(let l of ya(i)){let c;try{c=Jl(bn(i,l),"utf-8")}catch{continue}Xo(bn(s,l),c)&&a++}a>0&&(r.okfPublished=a,r.okfPublishedDir=`${n.dir}/${Ir}`)}return n.dir||r.skipped.push("no-public-dir"),r}function Xl(e,t){if(!e)return[];let n=[],r=[];return e.llmsPublished&&r.push(e.llmsPublished),e.okfPublishedDir&&r.push(`${e.okfPublishedDir}/ (${e.okfPublished} file${e.okfPublished===1?"":"s"})`),r.length>0&&n.push({text:`ai-files: published ${r.join(" and ")} \u2014 commit these so answer engines can read them.`,tone:"dim",always:!0}),e.skipped.includes("okf-placeholder")&&n.push({text:"ai-files: .seoagent/okf/ is still the scaffold. Fill it (see references/open-knowledge-format.md) and it publishes itself on the next sync.",tone:"dim",always:!1}),e.skipped.includes("okf-invalid")&&n.push({text:`ai-files: .seoagent/okf/ has validation errors, so it was NOT published. Run \`${t("okf validate")}\` and fix them.`,tone:"warn",always:!1}),e.llmsRouteDrift&&n.push({text:`ai-files: .seoagent/llms.md changed, but ${e.llmsRoute} already serves /llms.txt, so nothing was published \u2014 a file in your static dir would shadow that route. Compare the two, or set \`llms_owner: route\` in .seoagent/project.md to own the file yourself and stop this notice.`,tone:"dim",always:!1}),e.skipped.includes("no-public-dir")&&n.push({text:"ai-files: couldn't tell which directory this project serves as static files. Set `public_dir:` in .seoagent/project.md (`public`, `static`, or a nested path like `apps/web/public` in a monorepo) so llms.txt and the OKF bundle actually get served.",tone:"dim",always:!1}),n}var vh=30,$h=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi;function Sh(e){let t=e,n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t);n&&(t=n[1]),t=t.replace($h," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&[a-z]+;/gi," ").replace(/\s+/g," ").trim();let r=t===""?0:t.split(" ").filter(Boolean).length;return{wordCount:r,rendered:r<vh?"empty":"yes"}}async function xh(e,t){try{let n=await I(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}=Sh(r);return{status:n.status,rendered:i,wordCount:o}}catch{return{status:null,rendered:"error",wordCount:0}}}async function Ql(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 xh(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 Qo=300;async function kn(e,t={}){try{let n=_(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=$e(e,r);t.enrichSitemap&&r&&await ia(o,r);let i,s;if(t.crawl&&r){let l=o.map(d=>d.url).filter(d=>/^https?:\/\//.test(d)),c=l.slice(0,Qo);if(l.length>Qo&&u.info(`Crawling the first ${Qo} of ${l.length} pages (cap).`),c.length>0){u.info(`Crawling ${c.length} page${c.length===1?"":"s"}\u2026`),s=await Ql(c);let d=0,p=0;for(let f of s.values())f.rendered==="empty"?d++:f.rendered==="error"&&p++;i={crawled:s.size,empty:d,errors:p}}}let a=lr(e,o,s);return{added:a.added,total:a.total,file:a.file,crawl:i}}catch{return{added:0,total:0,file:"pages.md"}}}function Ph(e){try{let t=Mt(e);return t.evidenceFound?t:void 0}catch{return}}var Ih=new Set([".md"]),Oh=new Set(["inbox"]);function Th(e){let t=[];function n(r,o){if(Zo(r))for(let i of Ch(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Oh.has(i.name))continue;let s=ei(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a);Ih.has(l)&&t.push(s)}}}return n(e,""),t}function ec(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ei(Zr,`${t}.json`)}var Lh=14400*1e3;function Nh(e){let t=ec(e);if(!Zo(t))return{files:{},last_synced_at:null};try{return JSON.parse(Zl(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function jh(e,t){_h(Zr,{recursive:!0}),Eh(ec(e),JSON.stringify(t,null,2)+`
|
|
837
|
+
`,"utf-8")}function Dh(e,t){return Rh(e,t).split(Ah).join("/")}async function Mh(e,t){try{let n=await I(`${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 Fh(e,t,n){try{let r=await I(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:i.slice(0,200)}}let o=typeof r.json=="function"?await r.json().catch(()=>null):null;return{ok:!0,status:r.status,...o?.agent_notice?{agentNotice:o.agent_notice}:{}}}catch(r){return{ok:!1,status:0,error:r.message}}}async function tc(e,t={}){let n=Ph(e),r=d=>{let p=n?{...d,verifyRecs:n}:{...d};return s&&(p={...p,aiFiles:s}),i&&i.added>0&&(p={...p,pagesRescan:{added:i.added,total:i.total,file:i.file}}),p},o=_(e),i=null;if(o&&!t.pullOnly)try{i=await kn(e)}catch{}let s=null;if(o)try{s=Ft(e,o)}catch{}let a=N(o?.domain);if(!a)return r({ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]});if(!o)return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(o.domain===He)return r({ok:!0,reason:"domain-unknown",synced:0,failed:0,errors:[]});let l=ei(e,k);if(!Zo(l))return r({ok:!0,reason:"no-project",synced:0,failed:0,errors:[]});if(!jl(e).acquired)return r({ok:!0,reason:"busy",synced:0,failed:0,errors:[]});try{return r(await Uh(e,t,a,o,l))}finally{Dl(e)}}async function Uh(e,t,n,r,o){let i=n.api_base||O.BASE,s=`Bearer ${n.user_token}:${n.website_token}`,a=await Ke({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 l=Nh(r.domain);try{Va(e,r)}catch{}let c=Th(o),d=0,p=0,f=[],g=[],h=0,y=await Gh(e,i,s),w={restored:!1,blockPush:!1,notices:[]};if((!t.pathFilter||"context.md".endsWith(t.pathFilter))&&(w=await El({seoagentDir:o,apiBase:i,authHeader:s,stateFiles:l.files,force:t.force,forcePaths:t.forcePaths}),f.push(...w.notices)),!t.pullOnly)for(let P of c){let q=Dh(o,P);if(t.pathFilter&&!q.endsWith(t.pathFilter)||q==="context.md"&&w.blockPush)continue;let Ze=Zl(P,"utf-8"),yt=ge(Ze),Hn=l.files[q];if(!(!Hn||Hn.hash!==yt)&&!t.force)continue;h++;let et=await Fh(i,{path:q,contents:Ze,domain:r.domain},s);et.ok?(l.files[q]={hash:yt},d++,et.agentNotice&&f.push(`${q}: ${et.agentNotice}`)):(p++,g.push(`${q}: ${et.status} ${et.error??""}`.trim()))}let b=await Mh(i,s),E=0,H=0,T=[],M=0,se=0;!b.ok&&b.error&&g.push(`pull actions: ${b.error}`);let U,K=[],G=new Map,te=!1,Qe=[],we=l.last_synced_at;if(!t.pushOnly){let P=await Cl({projectDir:e,apiBase:i,authHeader:s,since:l.last_synced_at,stateFiles:l.files,force:t.force,forcePaths:t.forcePaths,meta:Bh(e,!!t.silent)});Qe=P.directives??[],P.ok?we=P.cursor:(te=!0,P.error&&g.push(`pull: ${P.error}`)),U={written:P.written,overwritten:P.overwritten,skipped:P.skipped,conflicts:P.conflicts,deleted:P.deleted,warnings:P.warnings},K=P.conflictPaths;for(let[q,Ze]of Object.entries(P.pointerOverwrites)){let yt=q.match(/^content\/(.+)\.md$/)?.[1];yt&&G.set(yt,Ze)}}if(b.ok){let P=Go(e);for(let[Re,wt]of G)P.set(Re,wt);let q=Qa(e,b.actions,{conflictedPaths:new Set(K),localPointers:P});E=q.wrote,H=q.removed,M=q.skippedUnknown;let Ze=l.announced_at?Date.parse(l.announced_at):NaN,Hn=q.pendingIds.length>0&&(Number.isNaN(Ze)||Date.now()-Ze>=Lh)?new Set:new Set(l.announced_action_ids??[]),Wn=new Set(q.pendingIds.filter(Re=>!Hn.has(Re)));T=q.pending.filter(Re=>Wn.has(Re.id)),se=Wn.size-T.length,l.announced_action_ids=q.pendingIds,Wn.size>0&&(l.announced_at=new Date().toISOString());let et=Ya(b.actions);U&&K.length>0&&(U.warnings=U.warnings.map(Re=>{let wt=K.find(Xr=>Re.startsWith(`${Xr}:`)),Jr=wt?et.get(wt):void 0;return!wt||!Jr?.length?Re:`${Re} \u2014 blocks inbox action${Jr.length===1?"":"s"} ${Jr.map(Xr=>`#${Xr}`).join(", ")}; take the cloud copy with \`seoagent sync --force ${wt}\``}))}let Bn=!!U&&U.written+U.overwritten+U.deleted+U.conflicts>0;if(l.last_synced_at=we,jh(r.domain,l),h===0&&E===0&&H===0&&!Bn&&!w.restored&&w.notices.length===0&&y.flushed===0&&y.dropped===0&&!te&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:g,actionsPulled:0,actionsRemoved:0,actionsNew:[],actionsUnknown:M,actionsUnknownNew:se,acksFlushed:0,acksDropped:0,pull:U,directives:Qe};let Gn=p===0&&!te;return{ok:Gn,reason:Gn?void 0:"error",synced:d,failed:p,errors:g,...f.length>0?{notices:f}:{},actionsPulled:E,actionsRemoved:H,actionsNew:T,actionsUnknown:M,actionsUnknownNew:se,acksFlushed:y.flushed,acksDropped:y.dropped,pull:U,directives:Qe}}function Bh(e,t){let n=ke(),r=n?null:_(e)?.install_id??null;return{cliVersion:n?null:C,agent:Ba(),authSource:ks(),installId:r||null,silent:t}}async function Gh(e,t,n){let r=Cr(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await Hh(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Tl(e,s),{flushed:o,dropped:i}}async function Hh(e,t,n){try{let r=await I(`${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 nc(e,t=3e4){let n=setTimeout(e,t);return n.unref?.(),{cancel:()=>clearTimeout(n)}}function rc(e){let t;try{t=_(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(Je(C,n)<=0){if(!t.skill_version)try{Y(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return St(e),Y(e,{skill_version:C}),{refreshed:!0,from:n,to:C,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function ti(e){let t;try{t=_(e)}catch{return{refreshed:!1,from:null,to:C,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:C,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return St(e),Y(e,{skill_version:C}),{refreshed:!0,from:n,to:C,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:C,reason:"error"}}}import{createHash as Wh}from"crypto";import{existsSync as mC,mkdirSync as Kh,readFileSync as qh,writeFileSync as Vh}from"fs";import{join as zh}from"path";var Yh="/cli-skill/manifest.json",Jh=360*60*1e3,Xh=4e3,Qh=64,Zh=4*1024*1024,oc=zh(z,"skill-check.json"),ey=e=>Wh("sha256").update(e).digest("hex");function ty(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.hash!="string"||!/^[0-9a-f]{64}$/.test(t.hash)||typeof t.min_cli!="string"||!/^\d+\.\d+\.\d+/.test(t.min_cli)||!Array.isArray(t.files)||t.files.length===0||t.files.length>Qh)return null;let n=[],r=0;for(let o of t.files){if(typeof o!="object"||o===null)return null;let i=o;if(typeof i.path!="string"||typeof i.sha256!="string"||!/^[A-Za-z0-9._/-]+$/.test(i.path)||i.path.startsWith("/")||i.path.split("/").includes("..")||!i.path.endsWith(".md")||!/^[0-9a-f]{64}$/.test(i.sha256))return null;let s=typeof i.bytes=="number"?i.bytes:0;r+=s,n.push({path:i.path,sha256:i.sha256,bytes:s})}return r>Zh||!n.some(o=>o.path==="SKILL.md")?null:{hash:t.hash,min_cli:t.min_cli,files:n}}function ny(e,t,n=Jh){if(!e)return!0;let r=Date.parse(e);return Number.isNaN(r)?!0:t.getTime()-r>=n}function ry(){try{return JSON.parse(qh(oc,"utf-8"))}catch{return{}}}function oy(e){try{Kh(z,{recursive:!0}),Vh(oc,JSON.stringify({checkedAt:e}),"utf-8")}catch{}}async function iy(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(Xh),headers:{"User-Agent":`seoagent-cli/${C}`}});return t.ok?await t.text():null}catch{return null}}async function ic(e,t={}){try{let n=_(e);if(!n)return{updated:!1,reason:"no-project"};let r=t.now??new Date,o=ry();if(!t.force&&!ny(o.checkedAt,r))return{updated:!1,reason:"throttled"};let i=(t.baseUrl??O.BASE).replace(/\/$/,""),s=t.fetchText??iy,a=await s(`${i}${Yh}`);if(oy(r.toISOString()),a===null)return{updated:!1,reason:"unreachable"};let l;try{l=ty(JSON.parse(a))}catch{l=null}if(!l)return{updated:!1,reason:"malformed"};if(n.skill_hash===l.hash)return{updated:!1,reason:"up-to-date"};if(Je(C,l.min_cli)<0)return{updated:!1,reason:"cli-too-old",minCli:l.min_cli};let c={};for(let d of l.files){let p=await s(`${i}/cli-skill/${d.path}`);if(p===null)return{updated:!1,reason:"unreachable"};if(ey(p)!==d.sha256)return{updated:!1,reason:"verify-failed"};c[d.path]=p}return Es(e,c),Y(e,{skill_hash:l.hash}),{updated:!0,reason:"updated",fileCount:l.files.length}}catch{return{updated:!1,reason:"error"}}}import{existsSync as sy,mkdirSync as ay,readFileSync as ly,writeFileSync as cy}from"fs";var uy="https://registry.npmjs.org/@seoagent-official/seoagent/latest",dy=1440*60*1e3,py=720*60*1e3,fy=2e3;function gy(e,t,n=dy){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function my(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??py;if(!n||Je(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 hy(e){let t=e.readCache();if(gy(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=my({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 yy(){try{return sy(Vn)?JSON.parse(ly(Vn,"utf-8")):{}}catch{return{}}}function wy(e){try{ay(z,{recursive:!0}),cy(Vn,JSON.stringify(e,null,2)+`
|
|
838
838
|
`,"utf-8")}catch{}}async function by(){try{let e=await fetch(uy,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(fy)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function sc(e){try{return await hy({current:e,now:new Date,fetchLatest:by,readCache:yy,writeCache:wy})}catch{return null}}import{existsSync as ac,readdirSync as lc}from"fs";import{join as ni}from"path";var cc={PILLAR:0,SUB_PILLAR:1,LONG_TAIL:2},uc={high:0,medium:1,low:2},ky=new Set(["drafted","published","dismissed","superseded","done"]);function vy(e){let t=e.filter(n=>!ky.has((n.status??"").toLowerCase()));return t.length===0?null:[...t].sort((n,r)=>{let o=cc[(n.role??"").toUpperCase()]??3,i=cc[(r.role??"").toUpperCase()]??3;if(o!==i)return o-i;let s=uc[(n.priority??"").toLowerCase()]??3,a=uc[(r.priority??"").toLowerCase()]??3;return s!==a?s-a:n.slug.localeCompare(r.slug)})[0]}function dc(e,t,n){if(t>0)return null;let r=vy(e);if(!r)return null;let o=r.role?` (${r.role})`:"";return`Next: no article yet \u2014 write .seoagent/briefs/${r.slug}.md${o} first, then run \`${n("content track")} <path-to-article>\` so the board advances. ${e.length} brief${e.length===1?"":"s"} waiting.`}function pc(e){let t={briefs:[],articleCount:0};try{let n=ni(e,"briefs");if(ac(n))for(let o of lc(n).filter(i=>i.endsWith(".md"))){let s=Ge(ni(n,o))?.data??{};t.briefs.push({slug:o.replace(/\.md$/,""),role:typeof s.role=="string"?s.role:null,priority:typeof s.priority=="string"?s.priority:null,status:typeof s.status=="string"?s.status:null})}let r=ni(e,"content");ac(r)&&(t.articleCount=lc(r).filter(o=>o.endsWith(".md")).length)}catch{}return t}async function re(e={}){let t=nc(()=>{e.silent||u.warn(`Sync gave up after ${Math.round(3e4/1e3)}s (network too slow or stalled). Sync is best-effort \u2014 nothing is lost; it will retry on the next run.`),process.exit(0)});try{await xy(e)}finally{t.cancel()}}async function xy(e){let t=rc(process.cwd());if(t.refreshed){try{st(process.cwd())}catch{}e.silent||u.info(F.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}let n=await ic(process.cwd());n.updated&&!e.silent&&u.info(F.dim("\u21BB Updated the SEOAgent skill to the latest published version.")),n.reason==="cli-too-old"&&!e.silent&&u.message(F.yellow(`A newer SEOAgent skill is available but needs CLI ${n.minCli} or later (you have ${C}). Run \`${m("update-cli")}\` to get it.`)),at(process.cwd());let r=await sc(C);r&&u.message(F.yellow(r));let o=!e.silent&&!!process.stdout.isTTY,i=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",s=o?Sy():null;s?.start(`${i} ${F.dim(".seoagent/")} with your dashboard\u2026`);let{force:a,forcePaths:l}=$l(e.force),c=await tc(process.cwd(),{pathFilter:e.path,silent:!!e.silent,force:a,forcePaths:l,pushOnly:e.pushOnly,pullOnly:e.pullOnly}),d=c.verifyRecs;if(d){d.sourceRender&&u.message(F.yellow("verify-recs: evidence.md is a SOURCE RENDER (undesignated local dev-server crawl) \u2014 live-state claims cannot be verified. Re-run `seoagent crawl --url <live origin>`."));for(let h of d.corrections)u.message(F.yellow(`verify-recs: corrected ${h.file}:${h.line} \u2014 the live page (${h.pageUrl}) already serves ${h.entityLabel}; reflect this correction in your summary.`))}for(let h of Xl(c.aiFiles??null,m))!h.always&&e.silent||u.message(h.tone==="warn"?F.yellow(h.text):F.dim(h.text));let p=c.pagesRescan;if(p&&!e.silent&&u.message(F.dim(`+${p.added} page${p.added===1?"":"s"} discovered in the codebase \u2192 .seoagent/${p.file} (${p.total} total).`)),c.actionsNew&&c.actionsNew.length>0){let h=c.actionsNew.slice(0,5).map(w=>` - ${w.title??w.action_type} (id ${w.id})`).join(`
|
|
839
839
|
`),y=c.actionsNew.length>5?`
|
|
840
840
|
\u2026 and ${c.actionsNew.length-5} more`:"";u.message(F.yellow(`inbox: ${c.actionsNew.length} pending action${c.actionsNew.length===1?"":"s"} from your SEOAgent dashboard await processing:
|
|
841
841
|
${h}${y}
|
|
842
|
-
Read .seoagent/inbox/README.md and process them (see references/inbox.md), then \`seoagent ack\` each one.`))}c.actionsUnknownNew&&c.actionsUnknownNew>0&&u.message(F.yellow(`inbox: ${c.actionsUnknownNew} pending action${c.actionsUnknownNew===1?"":"s"} need a newer CLI to display \u2014 run \`${m("update-cli")}\` and sync again.`));for(let h of _y(c.directives??[]))u.message(h);if(e.silent){c.ok||(process.exitCode=0);return}if(c.reason==="no-auth"){S(s,"info",`Not logged in. Run \`${m("login")}\` to enable cloud sync.`,F.dim("Not logged in \u2014 cloud sync skipped.")),s&&u.info(`Run \`${m("login")}\` to enable cloud sync.`);return}if(c.reason==="no-project"){S(s,"info",`No SEOAgent project here. Run \`${m("init")}\` first.`,F.dim("No SEOAgent project \u2014 sync skipped.")),s&&u.info(`Run \`${m("init")}\` first.`);return}if(c.reason==="domain-unknown"){S(s,"info","`.seoagent/project.md` has `domain: unknown` \u2014 cloud sync skipped until you set your site's domain.",F.dim("domain: unknown \u2014 cloud sync skipped.")),s&&u.info("Set `domain:` in .seoagent/project.md, then re-run sync.");return}if(c.reason==="project-mismatch"){let h=`Cloud project is ${c.cloudDomain} but this workspace is ${c.localDomain} \u2014 not syncing. Run \`${m("login")}\` from this directory to connect ${c.localDomain} \u2014 the CLI can stay logged into both sites at once, no need to log out first.`;S(s,"warn",h,F.yellow(h));return}if(c.reason==="unverified"){S(s,"info","Could not verify which cloud site this login is connected to \u2014 sync skipped (nothing pushed or pulled).",F.dim("Cloud binding unverified \u2014 sync skipped.")),s&&c.errors[0]&&u.info(` \u2022 ${c.errors[0]}`);return}if(c.reason==="no-changes"){S(s,"info","Already in sync.",F.green("Already in sync."));return}if(c.reason==="busy"){S(s,"info","Another sync is in progress \u2014 skipping this run.",F.dim("Another sync is in progress \u2014 skipping this run."));return}let f=Cy(c);S(s,"success",f??"Sync complete.",F.green(f??"Sync complete.")),c.synced>0&&u.success(`Synced ${c.synced} file${c.synced===1?"":"s"} to your dashboard.`);for(let h of c.notices??[])u.warn(`\u270D\uFE0F ${h}`);let g=c.pull;if(g){let h=g.written+g.overwritten;h>0&&u.success(`Pulled ${h} file${h===1?"":"s"} from the cloud`+(g.overwritten>0?` (${g.overwritten} updated)`:"")),g.deleted>0&&u.info(`Removed ${g.deleted} file${g.deleted===1?"":"s"} deleted in the cloud.`),g.conflicts>0&&u.warn(`${g.conflicts} conflict${g.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let y of g.warnings.slice(0,5))u.info(` \u2022 ${y}`)}{let h=pc(Te(process.cwd())),y=dc(h.briefs,h.articleCount,m);y&&u.message(F.cyan(y))}if(c.acksFlushed&&c.acksFlushed>0&&u.success(`Flushed ${c.acksFlushed} offline ack${c.acksFlushed===1?"":"s"} from the queue.`),c.acksDropped&&c.acksDropped>0&&u.info(`Dropped ${c.acksDropped} stale ack${c.acksDropped===1?"":"s"} (already settled server-side).`),c.actionsPulled&&c.actionsPulled>0&&(u.success(`Pulled ${c.actionsPulled} pending action${c.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||u.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),c.actionsRemoved&&c.actionsRemoved>0&&u.info(`Cleaned up ${c.actionsRemoved} stale inbox file${c.actionsRemoved===1?"":"s"}.`),c.failed>0){u.warn(`${c.failed} file${c.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let h of c.errors.slice(0,3))u.info(` \u2022 ${h}`)}}function _y(e){return e.map(t=>{let n=t.tone==="upsell"?"SEOAgent Cloud":"SEOAgent";return(t.tone==="upsell"?F.magenta:t.tone==="action"?F.cyan:F.dim)(`${n} \u203A ${t.text}`)})}function Cy(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 j(e){let t=_(e);return t||(u.error(`No SEOAgent project here. Run \`${m("init")}\` first.`),process.exitCode=1,null)}async function
|
|
842
|
+
Read .seoagent/inbox/README.md and process them (see references/inbox.md), then \`seoagent ack\` each one.`))}c.actionsUnknownNew&&c.actionsUnknownNew>0&&u.message(F.yellow(`inbox: ${c.actionsUnknownNew} pending action${c.actionsUnknownNew===1?"":"s"} need a newer CLI to display \u2014 run \`${m("update-cli")}\` and sync again.`));for(let h of _y(c.directives??[]))u.message(h);if(e.silent){c.ok||(process.exitCode=0);return}if(c.reason==="no-auth"){S(s,"info",`Not logged in. Run \`${m("login")}\` to enable cloud sync.`,F.dim("Not logged in \u2014 cloud sync skipped.")),s&&u.info(`Run \`${m("login")}\` to enable cloud sync.`);return}if(c.reason==="no-project"){S(s,"info",`No SEOAgent project here. Run \`${m("init")}\` first.`,F.dim("No SEOAgent project \u2014 sync skipped.")),s&&u.info(`Run \`${m("init")}\` first.`);return}if(c.reason==="domain-unknown"){S(s,"info","`.seoagent/project.md` has `domain: unknown` \u2014 cloud sync skipped until you set your site's domain.",F.dim("domain: unknown \u2014 cloud sync skipped.")),s&&u.info("Set `domain:` in .seoagent/project.md, then re-run sync.");return}if(c.reason==="project-mismatch"){let h=`Cloud project is ${c.cloudDomain} but this workspace is ${c.localDomain} \u2014 not syncing. Run \`${m("login")}\` from this directory to connect ${c.localDomain} \u2014 the CLI can stay logged into both sites at once, no need to log out first.`;S(s,"warn",h,F.yellow(h));return}if(c.reason==="unverified"){S(s,"info","Could not verify which cloud site this login is connected to \u2014 sync skipped (nothing pushed or pulled).",F.dim("Cloud binding unverified \u2014 sync skipped.")),s&&c.errors[0]&&u.info(` \u2022 ${c.errors[0]}`);return}if(c.reason==="no-changes"){S(s,"info","Already in sync.",F.green("Already in sync."));return}if(c.reason==="busy"){S(s,"info","Another sync is in progress \u2014 skipping this run.",F.dim("Another sync is in progress \u2014 skipping this run."));return}let f=Cy(c);S(s,"success",f??"Sync complete.",F.green(f??"Sync complete.")),c.synced>0&&u.success(`Synced ${c.synced} file${c.synced===1?"":"s"} to your dashboard.`);for(let h of c.notices??[])u.warn(`\u270D\uFE0F ${h}`);let g=c.pull;if(g){let h=g.written+g.overwritten;h>0&&u.success(`Pulled ${h} file${h===1?"":"s"} from the cloud`+(g.overwritten>0?` (${g.overwritten} updated)`:"")),g.deleted>0&&u.info(`Removed ${g.deleted} file${g.deleted===1?"":"s"} deleted in the cloud.`),g.conflicts>0&&u.warn(`${g.conflicts} conflict${g.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let y of g.warnings.slice(0,5))u.info(` \u2022 ${y}`)}{let h=pc(Te(process.cwd())),y=dc(h.briefs,h.articleCount,m);y&&u.message(F.cyan(y))}if(c.acksFlushed&&c.acksFlushed>0&&u.success(`Flushed ${c.acksFlushed} offline ack${c.acksFlushed===1?"":"s"} from the queue.`),c.acksDropped&&c.acksDropped>0&&u.info(`Dropped ${c.acksDropped} stale ack${c.acksDropped===1?"":"s"} (already settled server-side).`),c.actionsPulled&&c.actionsPulled>0&&(u.success(`Pulled ${c.actionsPulled} pending action${c.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||u.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),c.actionsRemoved&&c.actionsRemoved>0&&u.info(`Cleaned up ${c.actionsRemoved} stale inbox file${c.actionsRemoved===1?"":"s"}.`),c.failed>0){u.warn(`${c.failed} file${c.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let h of c.errors.slice(0,3))u.info(` \u2022 ${h}`)}}function _y(e){return e.map(t=>{let n=t.tone==="upsell"?"SEOAgent Cloud":"SEOAgent";return(t.tone==="upsell"?F.magenta:t.tone==="action"?F.cyan:F.dim)(`${n} \u203A ${t.text}`)})}function Cy(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 j(e){let t=_(e);return t||(u.error(`No SEOAgent project here. Run \`${m("init")}\` first.`),process.exitCode=1,null)}async function mt(e={}){if(e.print){let t=_(process.cwd())?.domain,n=N(t);if(!n){u.error(`Not logged in. Run \`${m("login")}\` first.`),process.exitCode=1;return}let r=j(process.cwd());if(!r)return;let o=n.api_base||O.BASE,i=`Bearer ${n.user_token}:${n.website_token}`;if(r.domain===He){u.warn("`.seoagent/project.md` has `domain: unknown` \u2014 set your site's domain before pulling from the cloud."),process.exitCode=1;return}let s=await Ke({apiBase:o,authHeader:i,localDomain:r.domain});if(s.verdict==="mismatch"){u.warn(ms(s.cloudDomain,r.domain)),process.exitCode=1;return}if(s.verdict==="unverified"){u.warn(`Could not verify which cloud site this login is connected to (${s.detail}) \u2014 not pulling.`),process.exitCode=1;return}let a=await Sl({apiBase:o,authHeader:i,path:e.print});if(!a.ok){u.warn(a.error),process.exitCode=1;return}process.stdout.write(a.body),a.body.endsWith(`
|
|
843
843
|
`)||process.stdout.write(`
|
|
844
|
-
`);return}await re({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Ey,readdirSync as Ry,unlinkSync as Ay}from"fs";import{join as fc}from"path";import{isCancel as Py,select as Iy}from"@clack/prompts";async function Se(e,t={}){let n=null;if(e){let d=Number.parseInt(e,10);if(Number.isNaN(d)||d<=0)return u.error(`Invalid action id: "${e}"`),process.exitCode=1,!1;n=d}else if(n=await Oy(),n===null)return!1;let r=n,o=_(process.cwd()),i=N(o?.domain);if(!i)return u.error(`Not logged in. Run \`${m("login")}\` first.`),process.exitCode=1,!1;if(!j(process.cwd()))return!1;let s=i.api_base||O.BASE,a=`Bearer ${i.user_token}:${i.website_token}`,l=t.failed?"failed":"completed",c;try{c=await I(`${s}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:a},body:JSON.stringify({status:l,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{return Ol(process.cwd(),{action_id:r,status:l,reason:t.failed?t.reason??null:null}),ri(r),Sr(process.cwd()),t.silent||u.warn(`Network unavailable \u2014 ack queued locally. Run \`${m("sync")}\` when you're back online; it'll flush automatically.`),!0}if(!c.ok){let d=await c.text().catch(()=>""),p=null;try{p=JSON.parse(d)}catch{p=null}if(c.status===409&&p?.code==="already_acked"){ri(r),Sr(process.cwd());let y=typeof p.error=="string"?p.error.match(/'([^']+)'/)?.[1]??"settled":"settled";return t.silent||u.success(`Action ${r} was already ${y}.`),!0}let f=typeof p?.code=="string"?p.code:null,g=typeof p?.error=="string"?p.error:d,h=f?`, code: ${f}`:"";return u.error(`Server rejected ack (${c.status}${h}): ${g.slice(0,200)}`),process.exitCode=1,!1}return ri(r),Sr(process.cwd()),t.silent||(t.failed?u.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):u.success(`Action ${r} marked completed.`),u.info(` inbox location: ${fc(k,"inbox")}`)),!0}function ri(e){let t=Me(process.cwd());if(Ey(t)){for(let n of Ry(t))if(n.endsWith(`-${e}.md`))try{Ay(fc(t,n))}catch{}}}async function Oy(){let e=process.cwd(),t=Fe(e);if(t.length===0)return u.info("No pending actions in .seoagent/inbox/."),u.message(`Run \`${m("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return u.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${m("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Iy({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:
|
|
845
|
-
`);return}if(n.length===0){u.info(Or.dim("No pending actions.")),u.message(`Run \`${m("sync")}\` to pull anything autopilot has queued, or \`${m("autopilot status")}\` to check whether autopilot is on.`);return}u.message(`${Or.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),u.message("");for(let r of n)u.message(
|
|
844
|
+
`);return}await re({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Ey,readdirSync as Ry,unlinkSync as Ay}from"fs";import{join as fc}from"path";import{isCancel as Py,select as Iy}from"@clack/prompts";async function Se(e,t={}){let n=null;if(e){let d=Number.parseInt(e,10);if(Number.isNaN(d)||d<=0)return u.error(`Invalid action id: "${e}"`),process.exitCode=1,!1;n=d}else if(n=await Oy(),n===null)return!1;let r=n,o=_(process.cwd()),i=N(o?.domain);if(!i)return u.error(`Not logged in. Run \`${m("login")}\` first.`),process.exitCode=1,!1;if(!j(process.cwd()))return!1;let s=i.api_base||O.BASE,a=`Bearer ${i.user_token}:${i.website_token}`,l=t.failed?"failed":"completed",c;try{c=await I(`${s}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:a},body:JSON.stringify({status:l,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{return Ol(process.cwd(),{action_id:r,status:l,reason:t.failed?t.reason??null:null}),ri(r),Sr(process.cwd()),t.silent||u.warn(`Network unavailable \u2014 ack queued locally. Run \`${m("sync")}\` when you're back online; it'll flush automatically.`),!0}if(!c.ok){let d=await c.text().catch(()=>""),p=null;try{p=JSON.parse(d)}catch{p=null}if(c.status===409&&p?.code==="already_acked"){ri(r),Sr(process.cwd());let y=typeof p.error=="string"?p.error.match(/'([^']+)'/)?.[1]??"settled":"settled";return t.silent||u.success(`Action ${r} was already ${y}.`),!0}let f=typeof p?.code=="string"?p.code:null,g=typeof p?.error=="string"?p.error:d,h=f?`, code: ${f}`:"";return u.error(`Server rejected ack (${c.status}${h}): ${g.slice(0,200)}`),process.exitCode=1,!1}return ri(r),Sr(process.cwd()),t.silent||(t.failed?u.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):u.success(`Action ${r} marked completed.`),u.info(` inbox location: ${fc(k,"inbox")}`)),!0}function ri(e){let t=Me(process.cwd());if(Ey(t)){for(let n of Ry(t))if(n.endsWith(`-${e}.md`))try{Ay(fc(t,n))}catch{}}}async function Oy(){let e=process.cwd(),t=Fe(e);if(t.length===0)return u.info("No pending actions in .seoagent/inbox/."),u.message(`Run \`${m("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return u.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${m("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Iy({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Nt(r)}))});return Py(n)?(u.info("Cancelled \u2014 no action closed out."),null):n}import Or from"picocolors";async function oi(e={}){let t=process.cwd();if(!e.json&&!j(t))return;let n=Fe(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:Me(t),actions:n})+`
|
|
845
|
+
`);return}if(n.length===0){u.info(Or.dim("No pending actions.")),u.message(`Run \`${m("sync")}\` to pull anything autopilot has queued, or \`${m("autopilot status")}\` to check whether autopilot is on.`);return}u.message(`${Or.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),u.message("");for(let r of n)u.message(Nt(r));u.message(""),u.message(`Apply one: ${Or.bold(m("ack <id>"))} \xB7 Interactive picker: ${Or.bold(m("ack"))} (no id)`)}import{readFileSync as qy}from"fs";import{join as Vy,relative as zy}from"path";import{confirm as vc,isCancel as jr,multiselect as Yy,note as xc,select as Jy}from"@clack/prompts";import v from"picocolors";import{query as Xy}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Ty,readFileSync as Ly}from"fs";import{homedir as Ny}from"os";import{join as jy}from"path";import{execSync as Tr}from"child_process";var Dy="Claude Code-credentials",My=44;function vn(){if(process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN)return"env-key";if(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")return"enterprise";let e=Uy();return e==="valid"?"claude-session-verified":Fy()?e==="absent"?"claude-installed-no-session":"claude-session-unverified":"not-installed"}function Lr(e){return e==="env-key"||e==="enterprise"||e==="claude-session-verified"||e==="claude-session-unverified"}function Fy(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Tr(e,{stdio:"ignore"}),!0}catch{return!1}}function Uy(){if(process.env.CLAUDE_CODE_OAUTH_TOKEN)return"valid";let e=jy(Ny(),".claude",".credentials.json");if(Ty(e)){let t=gc(Gy(e));if(t==="valid")return"valid";if(t==="absent"&&process.platform!=="darwin")return"absent"}return process.platform==="darwin"?By():"absent"}function By(){try{let e=Tr(`security find-generic-password -s '${Dy}' -w`,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3});return gc(mc(e))}catch(e){return e.status===My?"absent":"unknown"}}function gc(e){if(!e||typeof e!="object")return"unknown";let t=e.claudeAiOauth;if(!t||typeof t!="object")return"absent";let{accessToken:n,refreshToken:r,expiresAt:o}=t,i=typeof n=="string"?n.trim():"",s=typeof r=="string"?r.trim():"";return!i||typeof o=="number"&&o>0&&o<=Date.now()&&!s?"absent":"valid"}function Gy(e){try{return mc(Ly(e,"utf-8"))}catch{return null}}function mc(e){try{return JSON.parse(e.trim())}catch{return null}}function hc(){try{return Tr("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function yc(){try{return Tr("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var wc=["The agent could not get model access. Fix it with ONE of:"," \u2022 `claude login` \u2014 sign in with your Claude.ai Pro/Max account"," \u2022 `claude setup-token` \u2014 long-lived token for non-interactive use"," \u2022 `export ANTHROPIC_API_KEY=\u2026` \u2014 bring your own key (https://console.anthropic.com/)","Then re-run this command.","Note: `/login` is a Claude Code slash command \u2014 it does nothing in a shell.","Note: `seoagent login` is SEOAgent cloud auth. It does NOT grant model access."],oe={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-verified":{summary:"Using your existing `claude login` session.",next:""},"claude-session-unverified":{summary:"Trying your existing `claude login` session\u2026",next:"Couldn't confirm a stored credential. If this fails with an auth error, run `claude login` (or `claude setup-token`), or set `ANTHROPIC_API_KEY`. `seoagent login` is SEOAgent cloud auth and will not help."},"claude-installed-no-session":{summary:"Claude Code is installed but has no usable login session.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, `claude setup-token` for a long-lived token, or set `ANTHROPIC_API_KEY` and re-run. (`seoagent login` is SEOAgent cloud auth \u2014 it does NOT grant model access.)"},"not-installed":{summary:"Claude Code is not installed and no model credential was found.",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. (`seoagent login` is SEOAgent cloud auth \u2014 it does NOT grant model access.)"}};import{marked as kc}from"marked";import{markedTerminal as Hy}from"marked-terminal";import ii from"picocolors";var bc=!1;function Wy(){bc||(kc.use(Hy({reflowText:!1,width:100})),bc=!0)}function Nr(e){if(!e)return e;Wy();try{let t=kc.parse(e);return typeof t=="string"?Ky(t):e}catch{return e}}function Ky(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>ii.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>ii.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+ii.italic(r))}async function ai(e={}){let t=process.cwd();if(!j(t))return;if(!process.stdout.isTTY&&!e.yes){u.error(`\`${m("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 rw(e.yes)){process.exitCode=1;return}if(e.yes)await re({embedded:!0});else{let c=await Jy({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(jr(c)){u.info("Cancelled.");return}c==="sync"?await re({embedded:!0}):c==="pull"&&await mt({embedded:!0})}let r=Fe(t);if(r.length===0){u.info(v.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(c=>c.id),u.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let c=r.some(g=>g.priority!==null),d=c?r.filter(g=>g.priority==="high").map(g=>g.id):r.map(g=>g.id),p=c&&d.length===0?" (no high-priority actions \u2014 toggle to select)":c?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",f=await Yy({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(g=>({value:g.id,label:Nt(g)})),initialValues:d,required:!1});if(jr(f)){u.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(f)||f.length===0){u.info("No actions selected. Nothing to do.");return}o=f}let i=0,s=0,a=0,l=Date.now();for(let c=0;c<o.length;c++){let d=o[c],p=r.find(b=>b.id===d);if(!p)continue;Qy({index:c+1,total:o.length,entry:p});let f=Vy(Me(t),p.filename),g;try{g=qy(f,"utf-8")}catch(b){u.error(` Could not read ${p.filename}: ${b.message}`),a++;continue}let h=Date.now(),y=await nw({cwd:t,entry:p,actionContent:g,model:e.model}),w=$c(Date.now()-h);if(y.kind==="applied")try{await Se(String(d),{silent:!0}),i++,u.message("");let b=y.summary?`
|
|
846
846
|
`+v.dim(" "+y.summary):"";u.message(` ${v.green("\u2713")} id ${d} ${v.dim("\u2014 applied in "+w)}${b}`)}catch(b){u.warn(` Applied but ack failed: ${b.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(y.kind==="declined")try{await Se(String(d),{silent:!0,failed:!0,reason:y.reason}),s++,u.message(""),u.message(` ${v.yellow("\u2298")} id ${d} ${v.dim("\u2014 declined: "+me(y.reason,100))}`)}catch(b){u.warn(` Could not ack decline: ${b.message}. Run \`seoagent ack ${d} --failed --reason "${y.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,u.message(""),u.message(` ${v.red("\u2717")} id ${d} ${v.dim("\u2014 agent did not converge after "+w)}`)}ew({applied:i,declined:s,failed:a,total:o.length,elapsed:$c(Date.now()-l)})}function Qy(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Zy[i]??v.dim,a=[v.bold(`[${t}/${n}]`),v.dim("\xB7"),v.bold(`id ${r.id}`),v.dim("\xB7"),v.cyan(o),s(i)].join(" ");xc(r.title,a)}var Zy={critical:e=>v.red(v.bold(e)),high:v.red,medium:v.yellow,low:v.dim};function ew(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?v.green(`\u2713 ${t}/${o} applied`):v.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=v.red(`\u2717 0/${o} applied`);else{let l=[`${t}/${o} applied`];n>0&&l.push(`${n} declined`),r>0&&l.push(`${r} failed`),a=v.yellow(`\u25D0 ${l.join(" \xB7 ")}`)}xc(`${a}
|
|
847
847
|
${v.dim("elapsed: "+i)}`,v.bold("Done"))}function $c(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 tw(e){if(typeof e!="string"||!e)return null;let t=e.split(`
|
|
848
848
|
`);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 nw(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=fw(n,r);try{let s=Xy({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let l of s)if(l.type==="assistant"){let c=l.message.content;if(Array.isArray(c))for(let d of c)iw(d,a)}else if(l.type==="user"){let c=l.message.content;if(Array.isArray(c))for(let d of c)lw(d,a)}else if(l.type==="result"){if(process.stdout.write(`
|
|
@@ -894,10 +894,10 @@ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## O
|
|
|
894
894
|
`)}function Rc(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Pw(e){let t=0;function*n(r){let o;try{o=ww(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=xw)return;if(i.name.startsWith("."))continue;let s=kw(r,i.name);if(i.isDirectory()){if(Sw.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a+1).toLowerCase();if(!vw.has(l))continue;t++,yield s}}}yield*n(e)}function Pc(e,t){let{pages:n}=$e(e,t),r=[],o=0,i=!1;try{i=_c(e).isDirectory()}catch{i=!1}if(i)for(let s of Pw(e)){let a;try{if(_c(s).size>_w)continue;a=bw(s,"utf-8")}catch{continue}o++;for(let l of Rw(a,t))r.push(l)}return Aw(n,r,o)}var Iw=30;function Ow(e){return e?(e.match(/<meta\b[^>]*>/gi)??[]).some(n=>/\bname\s*=\s*["']?\s*(robots|googlebot)\b/i.test(n)&&/\bnoindex\b/i.test(n)):!1}async function Ic(e,t,n){let r=Dr(t);if(!r||e.orphans.length===0)return{checked:0,excludedUrls:[],exclusionReasons:{}};let o=e.orphans.slice(0,Iw),i={};await Promise.all(o.map(async a=>{try{let l=await I(a.url,{redirect:"follow",headers:{"user-agent":"SEOAgent-CLI/internal-links-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n}),c=new URL(l.url||a.url).hostname.toLowerCase().replace(/^www\./,"");if(c&&c!==r){i[a.url]="off-domain-redirect";return}let d=l.headers?.get?.("x-robots-tag")??"";if(/\bnoindex\b/i.test(d)){i[a.url]="noindex";return}l.ok&&Ow(await l.text())&&(i[a.url]="noindex")}catch{}}));let s=new Set(Object.keys(i));return s.size>0&&(e.orphans=e.orphans.filter(a=>!s.has(a.url))),{checked:o.length,excludedUrls:[...s],exclusionReasons:i}}async function Oc(e,t,n){if(!Dr(t)||e.orphans.length===0)return{checked:!1,sitemapUrlCount:0,excludedUrls:[]};let r=[];try{let s=await I(Jt(t),{headers:{"user-agent":"SEOAgent-CLI/internal-links-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,sitemapUrlCount:0,excludedUrls:[]};r=Ne(await s.text())}catch{return{checked:!1,sitemapUrlCount:0,excludedUrls:[]}}if(r.length===0)return{checked:!1,sitemapUrlCount:0,excludedUrls:[]};let o=new Set(r.map(L)),i=e.orphans.filter(s=>!o.has(L(s.url||s.route))).map(s=>s.url);if(i.length>0){let s=new Set(i);e.orphans=e.orphans.filter(a=>!s.has(a.url))}return{checked:!0,sitemapUrlCount:r.length,excludedUrls:i}}async function xn(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Pc(t,r);if(r){let a=await Oc(o,r);for(let d of a.excludedUrls)u.info(`Skipping ${d} \u2014 excluded from the site's own sitemap, unlinked by design.`);let{excludedUrls:l,exclusionReasons:c}=await Ic(o,r);for(let d of l)u.info(c[d]==="noindex"?`Skipping ${d} \u2014 page is noindex, unlinked by design.`:`Skipping ${d} \u2014 redirects to a different domain, not an orphan here.`)}if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
|
|
895
895
|
`);return}let i=li(t,k);Tw(i,{recursive:!0});let s=li(i,"internal-links.md");if(Lw(s,Ac(o,r),"utf-8"),u.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)u.info("No orphan pages \u2014 every page has an inbound internal link.");else{u.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))u.message(` \u2022 ${a.url}`);o.orphans.length>10&&u.message(` \u2026and ${o.orphans.length-10} more`)}u.info(`Report written to ${li(k,"internal-links.md")}`)}import{existsSync as Nw,mkdirSync as jw,readFileSync as Dw,rmSync as Mw,writeFileSync as Tc}from"fs";import{dirname as Lc,join as Mr}from"path";import le from"picocolors";async function ci(e,t={}){if(e!=="track"&&e!=="reconcile"){u.message(`Usage:
|
|
896
896
|
${m("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft] [--brief <brief-slug>]
|
|
897
|
-
${m("content reconcile")} [--dir <content-dir>] [--prune] # backfill pointers for published articles missing one`),e&&(u.error(`Unknown content action: ${e}. Actions: \`track\`, \`reconcile\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){u.error(`No .seoagent/project.md found. Run \`${m("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await Fw(n,r,t);return}let o=t.slug??(t.file?t.file:""),i=$r(o);if(!i){u.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=
|
|
897
|
+
${m("content reconcile")} [--dir <content-dir>] [--prune] # backfill pointers for published articles missing one`),e&&(u.error(`Unknown content action: ${e}. Actions: \`track\`, \`reconcile\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){u.error(`No .seoagent/project.md found. Run \`${m("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await Fw(n,r,t);return}let o=t.slug??(t.file?t.file:""),i=$r(o);if(!i){u.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=Tt(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||u.warn("No live URL \u2014 pass --url, or set domain + blog_path in project.md. Tracking without a canonical URL.");let a=$r(t.supersedes??"")||void 0,l=a&&a!==i?a:void 0;a&&!l&&u.warn("--supersedes names this same article \u2014 ignoring it (nothing was renamed).");let c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",d=t.status?.trim()||"published",p=new Date().toISOString(),f=Mr(n,k,"content");jw(f,{recursive:!0});let g=Mr(f,`${i}.md`),h=Nw(g),y=null;if(h)try{y=qa(Dw(g,"utf-8"),{slug:i,status:d,source:c,tracked_at:p,canonical:s,canonicalExplicit:!!t.url?.trim(),title:t.title?.trim()||void 0,page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,repo_path:t.file?.trim()||void 0,brief:t.brief?.trim()||void 0,supersedes:l})}catch{y=null}if(y===null&&(y=pn({slug:i,title:t.title?.trim()||Wa(i),canonical:s,status:d,page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,source:c,repo_path:t.file?.trim()||void 0,brief:t.brief?.trim()||void 0,supersedes:l,tracked_at:p})),Tc(g,y,"utf-8"),c==="repo"&&t.file?.trim()&&!r.content_dir)try{Y(n,{content_dir:Lc(t.file.trim())})}catch{}u.success(`${h?"Updated":"Tracked"} ${le.bold(i)}${s?` \u2192 ${le.cyan(s)}`:""} in .seoagent/content/.`);try{await re({silent:!0,pushOnly:!0})}catch{}l&&u.message(le.dim(`Reported as a rename of \`${l}\` \u2014 the cloud marks that draft superseded instead of re-delivering it.`));let w=(t.action??"").trim();if(w){let b=!1;try{b=await Se(w,{silent:!0})}catch{}b?u.message(le.dim(`Closed out inbox action ${w}.`)):u.warn(`Could not close it out \u2014 the action is still pending. Run \`${m(`ack ${w}`)}\` once the cause is clear.`)}u.message(le.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}async function Fw(e,t,n){let r=Mr(e,k,"content"),o=dn(r),i=new Set;for(let l of(n.dir??"").split(",").map(c=>c.trim()).filter(Boolean))i.add(l);t.content_dir&&i.add(t.content_dir);for(let l of o)l.source==="repo"&&l.repo_path&&i.add(Lc(l.repo_path));if(i.size===0){u.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(l=>jo(e,l)),a=Do(s,o,Mo(e));if(a.toTrack.length===0&&a.stale.length===0){u.success(`Content tracking is in sync \u2014 ${a.alreadyTracked} pointer${a.alreadyTracked===1?"":"s"} cover every published article in ${[...i].join(", ")}.`);return}for(let l of a.toTrack){let c=Tt(l.slug,{domain:t.domain,blogPath:t.blog_path}),d=pn({slug:l.slug,title:l.title,canonical:c,status:"published",page_type:l.page_type,source:"repo",repo_path:l.path,tracked_at:new Date().toISOString()});Tc(Mr(r,`${l.slug}.md`),d,"utf-8"),u.message(`${le.green("+")} tracked ${le.bold(l.slug)}${c?le.dim(` \u2192 ${c}`):""}`)}for(let l of a.stale)n.prune?(Mw(l.file,{force:!0}),u.message(`${le.red("-")} pruned stale pointer ${le.bold(l.slug)} (source ${l.repo_path} is gone)`)):u.message(`${le.yellow("!")} stale pointer ${le.bold(l.slug)} \u2192 ${l.repo_path} no longer exists (re-run with --prune to delete)`);u.success(`Reconciled content: +${a.toTrack.length} tracked, ${a.stale.length} stale${n.prune?" (pruned)":""}.`);try{await re({silent:!0,pushOnly:!0})}catch{}}import{existsSync as di,readFileSync as jc,statSync as Uw}from"fs";import{join as pi}from"path";import ui from"picocolors";var Nc=24;function Bw(e){let t=[];if(e.pullReceiptCount!=null&&t.push({level:"action",code:"pull_receipt",message:`${e.pullReceiptCount} cloud change${e.pullReceiptCount===1?"":"s"} pulled but not triaged yet.`,fix:"Read references/pull-receipt.md (next to the skill) and triage them, then delete .seoagent/.pull-receipt.json."}),(e.inboxPendingCount??0)>0){let r=e.inboxPendingCount;t.push({level:"action",code:"inbox_pending",message:`${r} pending inbox action${r===1?"":"s"} from autopilot await${r===1?"s":""} local apply.`,fix:"Run `seoagent inbox` to list them, then Read references/inbox.md (next to the skill) for the per-type procedure."})}if((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.contextNeedsDrafting&&t.push({level:"action",code:"context_scaffold",message:".seoagent/context.md is still the blank init scaffold \u2014 keyword, strategy, and content decisions are context-blind until it is drafted.",fix:"Draft it now from the repo + live homepage (business name, type incl. LOCAL/ONLINE-only/HYBRID, audience, industry, location, positioning), then show the owner. See the skill\u2019s Session start step 3."}),e.auditExists){let r=e.evidenceAgeHours===null,o=!r&&e.evidenceAgeHours>Nc;(r||o)&&t.push({level:"action",code:"evidence_stale",message:r?"An audit exists but there is NO live-crawl evidence base (.seoagent/audit/evidence.md) \u2014 its live-state claims are ungrounded.":`The live-crawl evidence base is ${Math.round(e.evidenceAgeHours)}h old (> ${Nc}h) \u2014 the live site may have changed since.`,fix:"Run `seoagent crawl` to refresh .seoagent/audit/evidence.md before asserting any live-state finding \u2014 findings must cite the evidence."})}if((e.hookTimeoutMissingCount??0)>0){let r=e.hookTimeoutMissingCount;t.push({level:"action",code:"hook_timeout_missing",message:`${r} SEOAgent hook entr${r===1?"y":"ies"} in .claude/settings.json ha${r===1?"s":"ve"} no timeout \u2014 a stalled sync could wedge the session.`,fix:"Run `seoagent init` (safe re-run) \u2014 it rewrites the hook entries with an explicit 60s timeout."})}return!(e.imageProvider&&e.imageProvider!=="none")&&e.detectedImageProvider!=="none"&&t.push({level:"action",code:"image_provider_unset",message:`Image generation is available (${e.detectedImageKey} found) but not enabled.`,fix:`Run \`${m("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 Gw(e,t=Date.now()){let n=pi(e,k,"audit","evidence.md");if(!di(n))return null;try{let r=jc(n,"utf-8").slice(0,2e3),o=/^captured_at:\s*(\S+)\s*$/m.exec(r);if(o){let i=Date.parse(o[1]);if(!Number.isNaN(i))return(t-i)/36e5}return(t-Uw(n).mtimeMs)/36e5}catch{return null}}function Hw(e){let t=pi(e,k,qn);if(!di(t))return null;try{let n=JSON.parse(jc(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function fi(e={}){let t=process.cwd(),n=_(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
|
|
898
898
|
`);return}u.error(`No .seoagent/project.md found. Run \`${m("init")}\` first.`),process.exitCode=1;return}let r=Ve(t),o=Bw({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:Hw(t),contextNeedsDrafting:ir(t),inboxPendingCount:Fe(t).length,auditExists:di(pi(t,k,"audit","latest.md")),evidenceAgeHours:Gw(t),hookTimeoutMissingCount:Ts(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
|
|
899
|
-
`);return}let i=o.filter(s=>s.level==="action");if(i.length===0){u.success("SEOAgent health: everything looks good.");return}u.message(ui.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)u.message(` ${ui.yellow("\u25CF")} ${s.message}`),s.fix&&u.message(` ${ui.dim("\u2192 "+s.fix)}`)}import xe from"picocolors";var Ut=`${k}/${
|
|
900
|
-
`);return}if(a.skipped.includes("okf-missing")){u.error(`No bundle at ${Ut}/. Run \`seoagent okf scaffold\` first.`),process.exitCode=1;return}if(a.skipped.includes("okf-placeholder")){u.error(`${Ut}/ is still the scaffold \u2014 publishing placeholder text to answer engines is worse than publishing nothing.`),u.info("Fill the bundle first (see references/open-knowledge-format.md), then re-run."),process.exitCode=1;return}if(a.skipped.includes("okf-invalid")){u.error(`${Ut}/ has validation errors, so it was not published. Run \`seoagent okf validate\` and fix them.`),process.exitCode=1;return}if(!a.publicDir){u.error("Couldn't tell which directory this project serves as static files."),u.info("Set `public_dir:` in .seoagent/project.md (`public` for Next.js/Vite/Astro, `static` for SvelteKit/Gatsby/Hugo, or a nested path like `apps/web/public` in a monorepo) and re-run."),process.exitCode=1;return}let l=a.okfPublishedDir??`${a.publicDir}/${Ir}`;a.okfPublished>0?u.success(`Published ${a.okfPublished} file${a.okfPublished===1?"":"s"} \u2192 ${l}/ \u2014 commit them so /.well-known/okf/index.md is served.`):u.info(`${l}/ is already current \u2014 nothing to copy.`);return}if(o==="validate"){let a=pr(
|
|
899
|
+
`);return}let i=o.filter(s=>s.level==="action");if(i.length===0){u.success("SEOAgent health: everything looks good.");return}u.message(ui.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)u.message(` ${ui.yellow("\u25CF")} ${s.message}`),s.fix&&u.message(` ${ui.dim("\u2192 "+s.fix)}`)}import xe from"picocolors";var Ut=`${k}/${Et}`;function _n(e,t={}){let n=process.cwd(),r=j(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=gr(n,i);a.length===0?u.info(`OKF bundle already scaffolded at ${Ut}/.`):(u.success(`Scaffolded ${Ut}/ \u2014 created ${a.join(", ")}.`),u.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="publish"){let a=Ft(n,r);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
|
|
900
|
+
`);return}if(a.skipped.includes("okf-missing")){u.error(`No bundle at ${Ut}/. Run \`seoagent okf scaffold\` first.`),process.exitCode=1;return}if(a.skipped.includes("okf-placeholder")){u.error(`${Ut}/ is still the scaffold \u2014 publishing placeholder text to answer engines is worse than publishing nothing.`),u.info("Fill the bundle first (see references/open-knowledge-format.md), then re-run."),process.exitCode=1;return}if(a.skipped.includes("okf-invalid")){u.error(`${Ut}/ has validation errors, so it was not published. Run \`seoagent okf validate\` and fix them.`),process.exitCode=1;return}if(!a.publicDir){u.error("Couldn't tell which directory this project serves as static files."),u.info("Set `public_dir:` in .seoagent/project.md (`public` for Next.js/Vite/Astro, `static` for SvelteKit/Gatsby/Hugo, or a nested path like `apps/web/public` in a monorepo) and re-run."),process.exitCode=1;return}let l=a.okfPublishedDir??`${a.publicDir}/${Ir}`;a.okfPublished>0?u.success(`Published ${a.okfPublished} file${a.okfPublished===1?"":"s"} \u2192 ${l}/ \u2014 commit them so /.well-known/okf/index.md is served.`):u.info(`${l}/ is already current \u2014 nothing to copy.`);return}if(o==="validate"){let a=pr(Rt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
|
|
901
901
|
`);return}for(let l of a.errors)u.message(`${xe.red("\u2717")} ${xe.dim(l.file)} \u2014 ${l.message}`);for(let l of a.warnings)u.message(`${xe.yellow("!")} ${xe.dim(l.file)} \u2014 ${l.message}`);a.ok?u.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(u.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=fr(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
|
|
902
902
|
`);return}u.message(B([{content:xe.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?xe.green(Ut+"/"):xe.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?xe.dim("Run `seoagent okf validate` to check it, `okf publish` to serve it."):xe.dim("Run `seoagent okf scaffold` to start one.")}],{title:xe.cyan("OKF")}))}import he from"picocolors";function gi(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=Ft(t,n);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
903
903
|
`);return}if(r.skipped.includes("no-domain")){u.error("No domain set in .seoagent/project.md \u2014 llms.txt links need absolute URLs. Set `domain:` first."),process.exitCode=1;return}let o=`${k}/${Pr}`;if(r.skipped.includes("llms-no-content")){u.warn("Nothing to describe yet \u2014 no pages in .seoagent/pages.md and no published articles in .seoagent/content/."),u.info("Run `seoagent refresh` (or an audit) to inventory the site, then re-run this.");return}if(u.message(B([{content:he.bold("llms.txt")},{sep:!0},{content:`Source: ${he.green(o)}${r.llmsSourceWritten?he.dim(" (updated)"):he.dim(" (unchanged)")}`},{content:`Published: ${r.llmsRoute?he.dim(`skipped \u2014 ${r.llmsRoute} serves it`):r.llmsPublished?he.green(r.llmsPublished):r.publicDir?he.dim(`${r.publicDir}/llms.txt (already current)`):he.yellow("nowhere \u2014 no static dir found")}`}],{title:he.cyan("llms.txt")})),r.llmsRoute){u.info(`Your project already serves /llms.txt from ${r.llmsRoute}, so nothing was published \u2014 a file in your static dir would shadow that route.`),u.info(`The generated version is in ${o} if you want to compare. To hand the file to SEOAgent instead, delete the route and re-run.`),n.llms_owner==="route"?u.info(he.dim("`llms_owner: route` is set, so sync stays quiet about this.")):u.info(he.dim("Sync mentions this only when the generated source changes. Set `llms_owner: route` in .seoagent/project.md to silence it for good."));return}if(!r.publicDir){u.warn("Couldn't tell which directory this project serves as static files, so llms.txt is not being served."),u.info("Set `public_dir:` in .seoagent/project.md (`public` for Next.js/Vite/Astro, `static` for SvelteKit/Gatsby/Hugo, or a nested path like `apps/web/public` in a monorepo) and re-run.");return}r.llmsPublished&&u.info("Commit the published file so it reaches your live site.")}import Z from"picocolors";async function mi(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r&&!e.url){u.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?$e(t,r).pages.map(s=>s.url||s.route):[],i=await na({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
|
|
@@ -905,9 +905,9 @@ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## O
|
|
|
905
905
|
`)}function Yc(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 Jc={Critical:0,High:1,Medium:2,Low:3};var gb=/^\*\*Check:\*\*\s*`([a-z][a-z0-9_]*)`\s*$/;function Xc(e){try{let t=new URL(e);return t.hash="",t.pathname==="/"?`${t.origin}/${t.search}`:`${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`}catch{return null}}function ie(e,t,n){return e===1?t:n??`${t}s`}function vi(e){let{pages:t,robots:n,sitemap:r}=e,o=t.filter(c=>c.fetched),i=An(t),s=[],a=o.filter(c=>c.clientRenderedShell);a.length>0&&s.push({severity:"Critical",checkId:"client_rendered_shell",title:`${a.length} ${ie(a.length,"page serves","pages serve")} a client-rendered shell \u2014 crawlers see no content`,what:'The server HTML for these pages is (near-)empty \u2014 a "Loading\u2026" placeholder or a body with no in-body links. Search engines index what the initial HTML contains, so these pages look blank to crawlers.',urls:a.map(c=>c.url),why:"A 200 OK with an empty body is treated as a soft 404 and gets deindexed; a content listing rendered this way also hides every page it links to from crawl discovery.",fix:"Server-render or pre-render these routes (SSR/SSG/ISR) so the content and links are present in the initial HTML.",evidence:a.map(c=>`evidence.md \xA7 ${c.url} \u2014 client-rendered shell`).join("; ")});let l=t.filter(c=>!c.fetched);if(l.length>0&&s.push({severity:"High",checkId:"crawl_incomplete",title:`${l.length} discovered ${ie(l.length,"page","pages")} could not be crawled \u2014 evidence is incomplete`,what:"These URLs were discovered by the crawl (sitemap, nav links, or repo routes) but did not return a usable 2xx response even after retries and a sequential re-fetch. The crawl is INCOMPLETE: every other finding in this report is a lower bound, and no check result exists for these pages \u2014 an uncaptured page must never be treated as passing.",urls:l.map(c=>`${c.url} (${c.failureReason??(c.status===null?"network error":`HTTP ${c.status}`)})`),why:"Linked or sitemap-listed URLs that error waste crawl budget, break user journeys, and (if they used to rank) bleed accumulated authority \u2014 and every page the crawl could not capture is a blind spot in this audit.",fix:"Fix or 301-redirect each URL (remove permanently dead ones from the sitemap and internal links); if the failure was network/timeout, re-run `seoagent crawl` to complete the evidence before treating the audit as final.",evidence:"evidence.md \xA7 Pages NOT captured"}),n.fetched||s.push({severity:"High",checkId:"robots_txt_missing",title:"robots.txt is missing or unreachable",what:`Fetching /robots.txt returned ${n.status===null?"a network error":`HTTP ${n.status}`} \u2014 crawlers get no crawl directives and no sitemap pointer from it.`,urls:[],why:"Without a robots.txt, crawlers apply defaults and never discover the sitemap from it; a misconfigured server may even be blocking the fetch.",fix:"Serve a robots.txt at the site root \u2014 at minimum `User-agent: *`, `Allow: /`, and a `Sitemap:` line pointing at the live sitemap.xml.",evidence:"evidence.md \xA7 robots.txt \u2014 Not fetched"}),!r.fetched)s.push({severity:"High",checkId:"sitemap_missing",title:"sitemap.xml is missing or unreachable",what:`Fetching /sitemap.xml returned ${r.status===null?"a network error":`HTTP ${r.status}`} (or the response was not valid sitemap XML).`,urls:[],why:"Without a sitemap, search engines rely purely on link discovery \u2014 new and deep pages get found late or never.",fix:"Generate and serve a sitemap.xml listing every canonical public URL, and submit it to Google Search Console.",evidence:"evidence.md \xA7 sitemap.xml \u2014 Not fetched"});else{let c=new Set(r.urls.map(p=>Xc(p)).filter(Boolean)),d=o.filter(p=>{let f=Xc(p.url);return f!==null&&!c.has(f)});d.length>0&&s.push({severity:"Medium",checkId:"sitemap_coverage_gap",title:`${d.length} crawled ${ie(d.length,"page is","pages are")} missing from sitemap.xml (${r.count} ${ie(r.count,"URL")} listed vs ${o.length} ${ie(o.length,"page")} discovered live)`,what:"These pages are live and reachable (the crawl fetched them via nav links or discovery) but sitemap.xml does not list them.",urls:d.map(p=>p.url),why:"Pages absent from the sitemap depend entirely on link discovery, get crawled less often, and signal an unmaintained sitemap to search engines.",fix:"Regenerate the sitemap to include every canonical public URL (prefer a framework-generated sitemap so it stays current), then resubmit it to Search Console.",evidence:`evidence.md \xA7 sitemap.xml \u2014 ${r.count} ${ie(r.count,"URL")}`})}if(n.fetched&&r.fetched&&n.sitemaps.length===0&&s.push({severity:"Medium",checkId:"sitemap_not_in_robots",title:"robots.txt has no Sitemap: declaration",what:"The live robots.txt was fetched successfully but declares no `Sitemap:` line, even though a sitemap.xml exists.",urls:[],why:"Crawlers that read robots.txt first (all of them) never learn where the sitemap lives without a GSC submission.",fix:"Add `Sitemap: <origin>/sitemap.xml` to robots.txt.",evidence:"evidence.md \xA7 robots.txt \u2014 Sitemap declarations: _(none)_"}),i.pagesMissingCanonical.length>0&&s.push({severity:"Medium",checkId:"canonical_missing",title:`${i.pagesMissingCanonical.length} ${ie(i.pagesMissingCanonical.length,"page has","pages have")} no canonical tag in the server HTML`,what:'The server HTML of these pages contains no `<link rel="canonical">`.',urls:i.pagesMissingCanonical,why:"Without a self-referencing canonical, URL variants (query strings, trailing slashes, http/https, www) can split ranking signals across duplicates.",fix:'Add a self-referencing `<link rel="canonical" href="{full URL}">` to each listed page.',evidence:"evidence.md \xA7 Site-wide rollup \u2014 Pages missing canonical"}),i.pagesMissingMetaDescription.length>0&&s.push({severity:"Medium",checkId:"meta_description_missing",title:`${i.pagesMissingMetaDescription.length} ${ie(i.pagesMissingMetaDescription.length,"page is","pages are")} missing a meta description`,what:'These pages serve no `<meta name="description">` in the server HTML.',urls:i.pagesMissingMetaDescription,why:"Google writes its own snippet for these results \u2014 usually worse copy than yours \u2014 which depresses click-through rate.",fix:"Add a unique 150\u2013160 character meta description (primary keyword + a soft CTA) to each listed page.",evidence:"evidence.md \xA7 Site-wide rollup \u2014 Pages missing meta description"}),i.pagesWithMultipleH1s.length>0&&s.push({severity:"Medium",checkId:"h1_multiple",title:`${i.pagesWithMultipleH1s.length} ${ie(i.pagesWithMultipleH1s.length,"page has","pages have")} multiple H1s`,what:"These pages serve more than one `<h1>` in the document, sending conflicting topic signals.",urls:i.pagesWithMultipleH1s,why:"A single clear H1 tells crawlers (and AI answer engines) what the page is about; multiple H1s dilute that signal.",fix:"Keep exactly one `<h1>` per page and demote the others to `<h2>`/`<h3>`.",evidence:"evidence.md \xA7 Site-wide rollup \u2014 Pages with multiple H1s"}),i.pagesWithNoStructuredData.length>0&&s.push({severity:"Medium",checkId:"json_ld_missing",title:`${i.pagesWithNoStructuredData.length} ${ie(i.pagesWithNoStructuredData.length,"page serves","pages serve")} no structured data (zero JSON-LD)`,what:'The server HTML of these pages contains no `<script type="application/ld+json">` block at all.',urls:i.pagesWithNoStructuredData,why:"Structured data powers rich results and gives AI search engines an unambiguous machine-readable summary of the page; pages without it compete on prose alone.",fix:"Add the JSON-LD type matching each page (Organization/WebSite on the homepage, Article/BlogPosting on posts, etc.) \u2014 only on the pages listed here; other crawled pages already serve schema.",evidence:"evidence.md \xA7 Site-wide rollup \u2014 Pages with no structured data (zero JSON-LD)"}),i.totalImgsMissingAlt>0){let c=i.pagesWithImgsMissingAlt.map(d=>{let f=o.find(g=>g.url===d.url)?.imgsMissingAltSrcs??[];return`${d.url} \u2014 ${d.count} ${ie(d.count,"image")}${f.length>0?` (${f.join(", ")}${d.count>f.length?", \u2026":""})`:""}`});s.push({severity:"Medium",checkId:"images_without_alt",title:`${i.totalImgsMissingAlt} ${ie(i.totalImgsMissingAlt,"image is","images are")} missing alt text across ${i.pagesWithImgsMissingAlt.length} ${ie(i.pagesWithImgsMissingAlt.length,"page")}`,what:'These `<img>` tags carry no `alt` attribute at all (decorative `alt=""` counts as present and is not flagged).',urls:c,why:"Missing alt text costs image-search visibility and accessibility, and is one of the most common automated-audit dings.",fix:"Add descriptive alt text to each listed image (start with the srcs shown).",evidence:"evidence.md \xA7 Site-wide rollup \u2014 Images missing alt"})}return s.sort((c,d)=>Jc[c.severity]-Jc[d.severity])}function mb(e){let t=[];for(let n of e.filter(r=>r.fetched)){let r=Fr(n).filter(o=>o.present).map(o=>o.kind==="json_ld"?`${Rn[o.kind]} (${n.jsonLdTypes.join(", ")})`:Rn[o.kind]);r.length>0&&t.push(`- ${n.url} \u2014 ${r.join(", ")}`)}return t}function Qc(e){let t=vi(e),n=e.origin??`https://${e.domain.replace(/^https?:\/\//,"").replace(/\/+$/,"")}`,r=e.sourceRender===!0,o=[];o.push("---"),o.push(`domain: ${e.domain}`),o.push(`origin: ${n}`),o.push(`source_render: ${r}`),o.push(`generated_at: ${e.capturedAt}`),o.push(`findings: ${t.length}`),o.push("source_evidence: .seoagent/audit/evidence.md"),o.push("note: >-"),o.push(" MACHINE-GENERATED findings report derived from the live-crawl evidence."),o.push(" The audit (audit/latest.md) BUILDS ON this file \u2014 it must carry every"),o.push(" finding below forward (adding GSC context and prioritization on top),"),o.push(" never re-derive or truncate the list. Do not hand-edit; re-run"),o.push(" `seoagent crawl` to regenerate."),o.push("---"),o.push(""),o.push(`# Technical findings \u2014 ${e.domain} (from the live crawl)`),o.push(""),o.push(`Derived by code from \`.seoagent/audit/evidence.md\` (crawled ${n} at ${e.capturedAt}). Every finding below is **Confirmed** against that evidence. Reporting every one of these is non-negotiable \u2014 session economy trims bookkeeping, never findings.`),o.push(""),r&&(o.push(`> **\u26A0 ${ki}.**`),o.push("> These findings describe the LOCAL render only \u2014 the crawl hit an undesignated loopback origin. Do not present them as live-site facts; re-run `seoagent crawl --url <live origin>` for live findings."),o.push("")),t.length===0&&(o.push("## No confirmed technical findings"),o.push(""),o.push("Every crawled page passed the rollup checks (canonical, meta description, single H1, structured data, image alt, server-rendered content), and robots.txt + sitemap.xml were fetched successfully with no coverage gaps."),o.push("")),t.forEach((s,a)=>{if(o.push(`## [${s.severity}] ${s.title}`),o.push(""),o.push(`**Confirmed** \xB7 Evidence: ${s.evidence}`),o.push(""),o.push(`**Check:** \`${s.checkId}\``),o.push(""),o.push(s.what),s.urls.length>0){o.push(""),o.push("Affected URLs:");for(let l of s.urls)o.push(`- ${l}`)}o.push(""),o.push(`**Why it matters:** ${s.why}`),o.push(""),o.push(`**Suggested fix:** ${s.fix}`),a<t.length-1&&o.push("")}),o.push("");let i=mb(e.pages);return o.push("## Already present on the live site \u2014 never recommend adding these"),o.push(""),o.push('The crawl confirms the following already exist in the live server HTML. If the repo source lacks any of them, the **repo source is stale \u2014 the live page already serves it; reconcile the source** with what is live. Never phrase these as "add X".'),o.push(""),i.length===0?o.push("_(no fetched page serves any head-level entity \u2014 nothing to guard)_"):o.push(...i),o.push(""),o.join(`
|
|
906
906
|
`)}function Zc(e){let t=[],n=/^## \[(Critical|High|Medium|Low)\] (.+)$/,r=null;for(let o of e.split(/\r?\n/)){let i=o.match(n);if(i){r={severity:i[1],title:i[2].trim()},t.push(r);continue}if(/^##\s/.test(o)){r=null;continue}let s=r?o.match(gb):null;s&&r&&(r.checkId=s[1])}return t}var Si=500,yb=5,wb=18e4,bb=9e5,kb=6e4,vb=3e3,$b=15e3,Sb=2;function xb(e){let t=kb+vb*Math.max(0,e);return Math.min(bb,Math.max(wb,t))}function nu(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="0.0.0.0"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}function _b(e){let t=e.trim().replace(/\/+$/,"");if(!t)return null;let n=t;if(!/^https?:\/\//i.test(n)){let r=n.split("/")[0].split(":")[0];n=`${nu(r)?"http":"https"}://${n}`}try{let r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.origin}catch{return null}}function xi(e){let t=[];e.urlFlag&&t.push({raw:e.urlFlag,source:"flag"}),e.liveUrl&&t.push({raw:e.liveUrl,source:"live_url"}),e.domain&&e.domain!=="unknown"&&t.push({raw:e.domain,source:"domain"});for(let n of t){let r=_b(n.raw);if(!r){if(n.source==="flag")return{ok:!1,error:`Invalid --url value: ${JSON.stringify(n.raw)} \u2014 pass a full origin like https://example.com or http://127.0.0.1:3000.`};continue}let o=n.source==="flag"||n.source==="live_url",i=nu(new URL(r).hostname);return{ok:!0,origin:r,source:n.source,designated:o,loopback:i,sourceRender:i&&!o}}return{ok:!1,error:"No crawl origin \u2014 pass --url <live site origin> or set live_url: (or domain:) in .seoagent/project.md. The crawl never guesses which site is live, and starting a local dev server does NOT count as the live site."}}async function _i(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=xi({urlFlag:e.url,liveUrl:n.live_url,domain:n.domain});if(!r.ok){u.error(r.error),process.exitCode=1;return}if(r.source==="flag")try{Y(t,{live_url:r.origin})}catch{}let o=n.domain&&n.domain!=="unknown"?n.domain:new URL(r.origin).host,i=Math.min(Math.max(1,e.max??Si),Si),s=`${r.origin}/`;u.info(`Capturing live-crawl evidence from ${r.origin} (every discovered page up to ${i} + robots + sitemap)\u2026`),r.sourceRender&&u.warn("Loopback origin without a --url/live_url designation \u2014 evidence will be labeled SOURCE RENDER (local dev server), NOT the public live site.");let[a,l,c]=await Promise.all([wi(s,e.fetchImpl),Kc(r.origin,e.fetchImpl),qc(r.origin,e.fetchImpl)]),d=a.html?Fc(a.html,s):[],p=Eb({home:s,sitemapUrls:tu(c.urls,r.origin),navLinks:d,repoUrls:tu(Rb(t,o),r.origin),max:i}),f=p.urls;p.truncated>0&&u.warn(`CRAWL CAPPED: discovered ${p.discovered} pages but will fetch only ${f.length} (${e.max!==void 0?`--max ${i}`:`safety cap ${Si}`}). ${p.truncated} discovered page${p.truncated===1?"":"s"} will NOT be audited \u2014 evidence is a LOWER BOUND.`);let g=Date.now()+xb(f.length),h=f.filter(M=>M!==s),y=await Hc(h,{concurrency:yb,fetchImpl:e.fetchImpl,deadlineMs:g}),w=[a.evidence,...y];await Ab(w,g,e.fetchImpl);let b={domain:o,origin:r.origin,originSource:r.source,sourceRender:r.sourceRender,capturedAt:new Date().toISOString(),pages:w,robots:l,sitemap:c},E=$i(t,k,"audit");hb(E,{recursive:!0});let H=$i(E,"evidence.md");eu(H,zc(b),"utf-8");let T=$i(E,"findings.md");if(eu(T,Qc(b),"utf-8"),e.json){process.stdout.write(JSON.stringify(b,null,2)+`
|
|
907
907
|
`);return}Pb(b,H,T)}function Cb(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.pathname==="/"?`${t.origin}/${t.search}`:`${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`)}catch{return null}}function Eb(e){let t=new Set,n=[],r=o=>{let i=Cb(o);!i||t.has(i)||(t.add(i),n.length<e.max&&n.push(i))};r(e.home);for(let o of e.sitemapUrls??[])r(o);for(let o of e.navLinks??[])r(o);for(let o of e.repoUrls??[])r(o);return{urls:n,discovered:t.size,truncated:t.size-n.length}}function Rb(e,t){try{return $e(e,t).pages.map(n=>n.url).filter(n=>/^https?:\/\//.test(n))}catch{return[]}}async function Ab(e,t,n){for(let r=0;r<e.length;r++){let o=e[r];if(o.fetched)continue;if(Date.now()>=t){let s="crawl time budget exhausted before sequential retry";e[r]={...o,failureReason:o.failureReason?`${o.failureReason}; ${s}`:s};continue}let i=await bi(o.url,{attempts:Sb,timeoutMs:$b,fetchImpl:n});e[r]=i.fetched?i:{...i,failureReason:i.failureReason??o.failureReason??null}}}function tu(e,t){let n=[];for(let r of e)try{let o=new URL(r);n.push(`${t}${o.pathname}${o.search}`)}catch{}return n}function Pb(e,t,n){let r=Yc(e),o=An(e.pages);u.success(`Captured evidence for ${r.fetched}/${r.pages} page${r.pages===1?"":"s"} from ${e.origin??e.domain} \u2192 ${ye.dim(t)}`);let i=e.pages.filter(a=>!a.fetched);if(i.length>0){u.warn(`CRAWL INCOMPLETE: ${i.length} discovered page${i.length===1?"":"s"} could NOT be captured \u2014 evidence is a LOWER BOUND, not a complete picture. See "Pages NOT captured" in evidence.md.`);for(let a of i)u.message(` ${ye.red("\u2717")} ${a.url} \u2014 ${a.failureReason??(a.status===null?"network error":`HTTP ${a.status}`)}`)}e.sourceRender&&u.warn("SOURCE RENDER (local dev server) \u2014 this evidence describes the local render, NOT the public live site. Re-run with --url <live origin> for live evidence."),u.message(` robots.txt: ${r.robotsFetched?ye.green("fetched"):ye.yellow("not reachable")} \xB7 sitemap: ${r.sitemapCount===null?ye.yellow("not reachable"):ye.green(`${r.sitemapCount} URLs`)}`);let s=[];if(o.pagesMissingCanonical.length>0&&s.push(`${o.pagesMissingCanonical.length} missing canonical`),o.pagesMissingMetaDescription.length>0&&s.push(`${o.pagesMissingMetaDescription.length} missing meta description`),o.pagesWithMultipleH1s.length>0&&s.push(`${o.pagesWithMultipleH1s.length} with multiple H1s`),o.pagesWithNoStructuredData.length>0&&s.push(`${o.pagesWithNoStructuredData.length} with no structured data`),o.totalImgsMissingAlt>0&&s.push(`${o.totalImgsMissingAlt} image${o.totalImgsMissingAlt===1?"":"s"} missing alt`),s.length>0&&u.message(` ${ye.yellow("!")} rollup: ${s.join(" \xB7 ")}`),r.shells>0&&u.message(` ${ye.yellow("!")} ${r.shells} page(s) render as a client-side shell \u2014 crawlers can't see the content`),n){let a=vi(e).length;u.message(` findings report: ${a===0?ye.green("no confirmed findings"):ye.yellow(`${a} confirmed finding${a===1?"":"s"}`)} \u2192 ${ye.dim(n)}`)}u.info("The audit will ground its Confirmed findings on this evidence \u2014 and must carry EVERY finding from findings.md into audit/latest.md and the final summary. No invented robots rules, no recommending schema that already exists.")}import{existsSync as Lb,mkdirSync as Nb,writeFileSync as jb}from"fs";import{dirname as cu,join as Db}from"path";import _e from"picocolors";var Ib=10,ou=30,Ci=200;function iu(e,t,n){let r=new URL(t).host,o=new Set,i=[];for(let l of e){let c;try{c=new URL(l)}catch{continue}if(c.host!==r){let p=f=>f.replace(/^www\./,"");if(p(c.host)!==p(r))continue}let d=c.href.split("#")[0];o.has(d)||(o.add(d),!de(L(d))&&(/\.(md|txt)$/i.test(c.pathname)||i.push(d)))}let s=`${t.replace(/\/$/,"")}/`,a=i.findIndex(l=>l===s||l===s.slice(0,-1));if(a>0){let[l]=i.splice(a,1);i.unshift(l)}return{selected:i.slice(0,n),skipped:i.slice(n)}}function Ob(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ei(e){let t=0,n=0;for(let r of e)r.error||r.indexStatus==="ERROR"?n+=1:r.indexStatus==="PASS"&&(t+=1);return{inspected:e.length,indexed:t,notIndexed:e.length-t-n,errors:n}}function Br(e){return e.replace(/\|/g,"\\|")}function ru(e){return e.error?e.error:e.coverageState||e.indexStatus}function su(e,t){let n=Ei(e),r=e.filter(l=>!l.error&&l.indexStatus==="PASS"),o=e.filter(l=>l.error||l.indexStatus==="ERROR"),i=e.filter(l=>!r.includes(l)&&!o.includes(l)),s=t.notInspected.length===0,a=["---",`origin: ${t.origin}`,`gsc_property: ${t.siteUrl}`,`generated: ${t.generatedAt}`,`sitemap: ${t.sitemapUrl??"(none found \u2014 homepage only)"}`,`sitemap_urls: ${t.sitemapUrlCount}`,`inspected: ${n.inspected}`,`indexed: ${n.indexed}`,`not_indexed: ${n.notIndexed}`,`errors: ${n.errors}`,`capture_complete: ${s}`,"---","",`# GSC Indexing Coverage \u2014 ${t.origin}`,"","Verdicts are authoritative Google Search Console URL Inspection results",`fetched ${t.generatedAt} for property \`${t.siteUrl}\`. A finding derived`,'from a row below is `Confirmed`. URLs in the "Not inspected" section have',"NO verdict \u2014 never claim they are indexed or not indexed.",""];if(i.length>0){a.push(`## Not indexed (${i.length})`,""),a.push("| URL | Verdict | Coverage state | Last crawl | Robots | Fetch |"),a.push("| --- | --- | --- | --- | --- | --- |");for(let l of i)a.push(`| ${Br(l.url)} | ${l.indexStatus} | ${Br(ru(l))} | ${l.lastCrawlTime??"\u2014"} | ${l.robotsTxtState??"\u2014"} | ${l.fetchStatus??"\u2014"} |`);a.push("")}if(r.length>0){a.push(`## Indexed (${r.length})`,""),a.push("| URL | Coverage state | Google canonical | Last crawl |"),a.push("| --- | --- | --- | --- |");for(let l of r)a.push(`| ${Br(l.url)} | ${Br(ru(l))} | ${l.googleCanonical??"\u2014"} | ${l.lastCrawlTime??"\u2014"} |`);a.push("")}if(o.length>0){a.push(`## Inspection errors (${o.length})`,"");for(let l of o)a.push(`- ${l.url} \u2014 ${l.error??"unknown error"}`);a.push("")}if(!s){a.push(`## Not inspected (${t.notInspected.length} sitemap URLs beyond the cap)`,"","No verdict exists for these \u2014 raise the cap with `--max <n>` to inspect them.","");let l=t.notInspected.slice(0,100);for(let c of l)a.push(`- ${c}`);t.notInspected.length>l.length&&a.push(`- \u2026and ${t.notInspected.length-l.length} more`),a.push("")}return a.join(`
|
|
908
|
-
`)}var
|
|
908
|
+
`)}var ht=class extends Error{constructor(n,r){super(r);this.code=n}};async function au(e){let t=(e.apiBase||e.auth.api_base).replace(/\/$/,""),n=Ob(e.urls,Ib),r=[],o="";for(let[i,s]of n.entries()){let a;try{a=await I(`${t}/api/cli/indexing`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.auth.user_token}:${e.auth.website_token}`},body:JSON.stringify({urls:s})},{timeoutMs:11e4,fetchImpl:e.fetchImpl})}catch(c){throw new ht("http_error",`Network error calling ${t}/api/cli/indexing: ${c instanceof Error?c.message:String(c)}`)}let l=await a.json().catch(()=>({}));if(!a.ok||l.status!=="ok"){let c=l.code;throw c==="gsc_not_connected"||c==="gsc_property_not_found"||c==="gsc_token_error"||c==="invalid_credentials"||c==="url_domain_mismatch"?new ht(c,l.error||c):new ht("http_error",l.error||`HTTP ${a.status} from /api/cli/indexing`)}o=l.site_url||o,r.push(...l.results??[]),e.onProgress?.(r.length,e.urls.length)}return{siteUrl:o,results:r}}var Tb=5;async function lu(e,t=fetch){let n=`${e.replace(/\/$/,"")}/sitemap.xml`,r=async a=>{try{let l=await I(a,{},{fetchImpl:t,timeoutMs:15e3});return l.ok?Ne(await l.text()):null}catch{return null}},o=await r(n);if(!o||o.length===0)return null;let i=o.filter(a=>/\.xml(\?.*)?$/i.test(a)),s=o.filter(a=>!/\.xml(\?.*)?$/i.test(a));if(i.length>0)for(let a of i.slice(0,Tb)){let l=await r(a);l&&s.push(...l.filter(c=>!/\.xml(\?.*)?$/i.test(c)))}return s.length===0?null:{sitemapUrl:n,urls:s}}async function Ri(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=N(n.domain);if(!r){let b=qe();u.error(`Not logged in for ${n.domain}. Indexing coverage needs Google Search Console, which comes with the FREE cloud account.
|
|
909
909
|
Run ${_e.cyan("seoagent login")} (connects GSC), then re-run ${_e.cyan("seoagent indexing")}.`+(b.length>0?`
|
|
910
|
-
(This machine is logged in to: ${b.join(", ")} \u2014 not this project's site.)`:"")),process.exitCode=1;return}let o=xi({urlFlag:e.url,liveUrl:n.live_url,domain:n.domain});if(!o.ok){u.error(o.error),process.exitCode=1;return}let i=o.origin,s=Math.min(Math.max(1,e.max??ou),Ci);u.info(`Reading live sitemap from ${i}/sitemap.xml\u2026`);let a=await lu(i,e.fetchImpl),l=a?.urls??[`${i.replace(/\/$/,"")}/`];a||u.warn("No parseable sitemap found \u2014 inspecting the homepage only.");let{selected:c,skipped:d}=iu(l,i,s);if(c.length===0){u.error(`The sitemap at ${i}/sitemap.xml lists no inspectable same-origin URLs.`),process.exitCode=1;return}u.info(`Inspecting ${c.length} URL${c.length===1?"":"s"} with Google Search Console (this takes a few seconds per URL)\u2026`);let p;try{p=await au({urls:c,auth:r,apiBase:e.apiBase,fetchImpl:e.fetchImpl,onProgress:(b,E)=>{b<E&&u.info(` \u2026${b}/${E} inspected`)}})}catch(b){if(b instanceof
|
|
910
|
+
(This machine is logged in to: ${b.join(", ")} \u2014 not this project's site.)`:"")),process.exitCode=1;return}let o=xi({urlFlag:e.url,liveUrl:n.live_url,domain:n.domain});if(!o.ok){u.error(o.error),process.exitCode=1;return}let i=o.origin,s=Math.min(Math.max(1,e.max??ou),Ci);u.info(`Reading live sitemap from ${i}/sitemap.xml\u2026`);let a=await lu(i,e.fetchImpl),l=a?.urls??[`${i.replace(/\/$/,"")}/`];a||u.warn("No parseable sitemap found \u2014 inspecting the homepage only.");let{selected:c,skipped:d}=iu(l,i,s);if(c.length===0){u.error(`The sitemap at ${i}/sitemap.xml lists no inspectable same-origin URLs.`),process.exitCode=1;return}u.info(`Inspecting ${c.length} URL${c.length===1?"":"s"} with Google Search Console (this takes a few seconds per URL)\u2026`);let p;try{p=await au({urls:c,auth:r,apiBase:e.apiBase,fetchImpl:e.fetchImpl,onProgress:(b,E)=>{b<E&&u.info(` \u2026${b}/${E} inspected`)}})}catch(b){if(b instanceof ht){let E={invalid_credentials:`Stored credentials were rejected \u2014 run ${_e.cyan("seoagent login")} again.`,gsc_not_connected:"Connect Google Search Console from the SEOAgent dashboard, then re-run.",gsc_property_not_found:`Verify the site in Search Console (property matching ${n.domain}) and re-run.`,url_domain_mismatch:`These credentials belong to a different site. Run ${_e.cyan("seoagent login")} for ${n.domain}, then re-run.`,gsc_token_error:"Search Console token expired \u2014 reconnect GSC from the dashboard.",http_error:"Transient network/server error \u2014 re-run in a minute."};u.error(`${b.message}
|
|
911
911
|
${E[b.code]}`)}else u.error(`Indexing lookup failed: ${b instanceof Error?b.message:String(b)}`);process.exitCode=1;return}let f=(e.now?.()??new Date).toISOString(),g=su(p.results,{origin:i,siteUrl:p.siteUrl,generatedAt:f,sitemapUrl:a?.sitemapUrl??null,sitemapUrlCount:l.length,notInspected:d}),h=Db(Te(t),"audit","indexing.md");Lb(cu(h))||Nb(cu(h),{recursive:!0}),jb(h,g,"utf-8");let y=Ei(p.results);if(e.json){process.stdout.write(JSON.stringify({origin:i,site_url:p.siteUrl,summary:y,results:p.results,not_inspected:d},null,2)+`
|
|
912
912
|
`);return}let w=y.inspected>0?Math.round(y.indexed/y.inspected*100):0;u.info(""),u.info(`${_e.bold("Indexing coverage")} for ${i} (GSC property ${p.siteUrl}):`),u.info(` ${_e.green(`${y.indexed} indexed`)} \xB7 ${y.notIndexed>0?_e.yellow(`${y.notIndexed} not indexed`):"0 not indexed"} \xB7 ${y.errors>0?_e.red(`${y.errors} errors`):"0 errors"} \u2014 ${w}% of the ${y.inspected} inspected sitemap URLs`),d.length>0&&u.info(` ${d.length} sitemap URLs not inspected (cap ${s}) \u2014 raise with ${_e.cyan(`--max ${Math.min(l.length,Ci)}`)}`),u.info(` Report: ${_e.cyan(".seoagent/audit/indexing.md")}`)}import Pn from"picocolors";async function Ai(e={}){let t=process.cwd(),n=Mt(t,{extraFiles:e.files});if(e.json){process.stdout.write(JSON.stringify(n,null,2)+`
|
|
913
913
|
`);return}if(!n.evidenceFound){if(e.quiet)return;u.info(`No crawl evidence found (.seoagent/audit/evidence.md) \u2014 run \`${m("crawl")}\` first, then re-run verify-recs. Nothing was verified.`);return}if(n.sourceRender){u.warn(`evidence.md is a SOURCE RENDER (undesignated local dev-server crawl) \u2014 verify-recs CANNOT verify live-state claims against it. No corrections were applied. Re-run \`${m("crawl")} --url <live origin>\` to capture live evidence, then re-run verify-recs.`);return}if(n.corrections.length===0){if(e.quiet)return;u.success(`Verified ${n.scanned.length} authored file${n.scanned.length===1?"":"s"} against the crawl evidence \u2014 no false absence/add claims found.`)}else{u.warn(`Corrected ${n.corrections.length} claim${n.corrections.length===1?"":"s"} that contradicted the live-crawl evidence:`);for(let r of n.corrections)u.message(` ${Pn.dim(`${r.file}:${r.line}`)} \u2014 the live page already serves ${Pn.bold(r.entityLabel)} (${r.pageUrl})`);u.info("Each line was rewritten in place with a CORRECTION annotation. Reflect these corrections in your final summary \u2014 the original claims were wrong.")}if(n.stale.length>0&&!e.quiet){let r=n.stale.length;u.message(` ${Pn.dim(`${r} earlier claim${r===1?"":"s"} predate${r===1?"s":""} the crawl (captured ${n.stale[0].capturedAt}) and ${r===1?"was":"were"} left as history \u2014 the live page now serves what ${r===1?"it":"they"} reported missing. Mark ${r===1?"it":"them"} fixed in a re-audit; do not rewrite the record.`)}`);for(let o of n.stale)u.message(` ${Pn.dim(`${o.file}:${o.line} (authored ${o.authoredAt}) \u2014 ${o.entityLabel} (${o.pageUrl})`)}`)}n.skipped.length>0&&u.message(` ${Pn.dim(`skipped (protected): ${n.skipped.join(", ")}`)}`)}import{existsSync as uu,readFileSync as du,readdirSync as Mb,statSync as Fb}from"fs";import{join as Ce,relative as Ub,sep as Bb}from"path";var Gb=["Critical","High","Medium","Low"],Hb={Critical:5,High:3,Medium:2,Low:1},Wb=8;function Kb(e){let t=[],n=e.split(/^## /m).slice(1);for(let r of n){let o=r.split(`
|
|
@@ -921,7 +921,7 @@ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## O
|
|
|
921
921
|
`);return}process.stdout.write(t.markdown.trimEnd()+`
|
|
922
922
|
`)}import{existsSync as ck,mkdirSync as uk,readFileSync as $u,writeFileSync as dk}from"fs";import{join as Ti}from"path";import Gt from"picocolors";import{readdirSync as Qb,readFileSync as Zb,statSync as ek}from"fs";import{join as Hr}from"path";var mu={minImpressionsToPreserve:50,onTopicRelevance:.34},tk=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 hu(e){return e.toLowerCase().replace(/https?:\/\/[^/]+/g," ").replace(/[^a-z0-9]+/g," ").split(" ").filter(t=>t.length>2&&!tk.has(t)&&!/^\d+$/.test(t))}function yu(e){let t=new Set;for(let n of e)for(let r of hu(n))t.add(r);return t}function nk(e,t){let n=hu(e);return n.length===0||t.size===0?0:n.filter(o=>t.has(o)).length/n.length}function rk(e,t,n=mu){let r=nk(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}`,l,c,d;return o&&i?(l="harvest",c=`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?(l="redirect",c=`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.`):(l="sunset",c=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:l,onTopic:o,relevance:r,rationale:c,action:d}}function wu(e,t,n=mu){return e.map(r=>rk(r,t,n)).sort((r,o)=>o.row.impressions-r.row.impressions)}function Ii(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 Gr(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 Oi(e){let t=e.split(/\r?\n/).filter(p=>p.trim()!=="");if(t.length<2)return[];let n=Ii(t[0]).map(p=>p.toLowerCase()),r=n[0]??"",o=/quer/i.test(r)?"query":"page",i=p=>n.findIndex(f=>p.some(g=>f.includes(g))),s=i(["click"]),a=i(["impression"]),l=i(["ctr"]),c=i(["position"]),d=[];for(let p=1;p<t.length;p++){let f=Ii(t[p]),g=(f[0]??"").trim();if(!g)continue;let h=l>=0?f[l]??"":"",y=Gr(h);d.push({key:g,kind:o,clicks:s>=0?Gr(f[s]??"")??0:0,impressions:a>=0?Gr(f[a]??"")??0:0,position:c>=0?Gr(f[c]??""):null,ctr:y===null?null:/%/.test(h)?y/100:y})}return d}function ok(e){let t=e.split(/\r?\n/).find(s=>s.trim()!=="");if(!t)return!1;let n=Ii(t).map(s=>s.toLowerCase()),r=n[0]??"",o=/page|url|quer/.test(r),i=n.some(s=>s.includes("impression"));return o&&i}var ik=[".","gsc",Hr(".seoagent","gsc"),Hr("data","gsc")],sk=4096;function bu(e){let t=[];for(let n of ik){let r=Hr(e,n),o;try{o=Qb(r)}catch{continue}for(let i of o){if(!/\.csv$/i.test(i))continue;let s=Hr(r,i);try{if(!ek(s).isFile())continue;let a=Zb(s,"utf-8").slice(0,sk);ok(a)&&t.push(s)}catch{}}}return t}var gu=["harvest","redirect","sunset"],ak={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 lk(e){return e.filter(t=>t.disposition==="redirect"&&t.row.kind==="page").map(t=>({from:t.row.key,note:t.action}))}function ku(e){let{domain:t,directionSummary:n,decisions:r,generatedAt:o}=e,i=gu.reduce((l,c)=>(l[c]=r.filter(d=>d.disposition===c).length,l),{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(`
|
|
923
923
|
`);for(let l of gu){let c=r.filter(d=>d.disposition===l);if(c.length!==0){s.push(`## ${ak[l]}`),s.push("");for(let d of c)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=lk(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 l of a)s.push(`${l.from} -> <choose the closest new page>`);s.push("```"),s.push("")}return s.join(`
|
|
924
|
-
`)}function vu(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 Li(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r){u.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=
|
|
924
|
+
`)}function vu(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 Li(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r){u.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=xt(t),i=[r,n.site_type],s=e.direction??"";if(o){let y=o.business;for(let w of[y.type,y.audience,y.industry,y.description,y.name])w&&i.push(w);for(let w of o.writingInstructions)i.push(w);s||(s=[y.description,y.type,y.audience].filter(Boolean).join(" \xB7 "))}s||(s=`${n.site_type} at ${r}`);let a=yu(i);if(a.size===0){u.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 l=[],c="";if(e.csv){let y=e.csv.startsWith("/")?e.csv:Ti(t,e.csv);if(!ck(y)){u.error(`GSC CSV not found: ${y}`),process.exitCode=1;return}let w=Oi($u(y,"utf-8"));l.push(...w),c=`${w.length} row(s) from ${e.csv}`}else{let y=bu(t);if(y.length>0){let w=null;for(let b of y)try{let E=Oi($u(b,"utf-8"));(!w||E.length>w.rows.length)&&(w={path:b,rows:E})}catch{}w&&w.rows.length>0&&(l.push(...w.rows),c=`${w.rows.length} row(s) auto-detected from ${w.path}`,u.info(`Auto-detected GSC export: ${Gt.dim(w.path)}`))}}if(l.length===0){u.error("No GSC performance rows to plan from. Export Search Console \u2192 Performance \u2192 Pages (or Queries) as CSV and pass it with `--csv <path>` (or drop it in the repo \u2014 `gsc/*.csv` and root *.csv exports are auto-detected)."),u.message(Gt.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=wu(l,a),p=new Date().toISOString(),f=Ti(t,k,"strategy");uk(f,{recursive:!0});let g=Ti(f,"migration-plan.md");dk(g,ku({domain:r,directionSummary:s,decisions:d,generatedAt:p}),"utf-8");let h=vu(d);if(e.json){process.stdout.write(JSON.stringify({domain:r,directionSummary:s,source:c,summary:h,decisions:d},null,2)+`
|
|
925
925
|
`);return}u.success(`Migration plan written \u2192 ${Gt.dim(g)} (${c})`),u.message(` ${Gt.green(`${h.harvest} harvest`)} \xB7 ${Gt.cyan(`${h.redirect} redirect`)} \xB7 ${Gt.yellow(`${h.sunset} sunset`)} across ${h.total} legacy asset${h.total===1?"":"s"}`),u.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 Tu,writeFileSync as Lu,readFileSync as vk,readdirSync as $k,existsSync as Sk}from"fs";import{join as ju}from"path";import D from"picocolors";import{query as xk}from"@anthropic-ai/claude-agent-sdk";import{join as Ni}from"path";var ji="citations",Di="scorecard.md",pk="history",fk=6,gk=1,mk=12,hk=5,Wr="Claude (web-grounded)";function Kr(e){return Ni(e,k,ji)}function xu(e){return Ni(Kr(e),Di)}function _u(e){return Ni(Kr(e),pk)}function Cu(e){return`${e.replace(/[:.]/g,"-")}.json`}function Eu(e){return typeof e!="number"||!Number.isFinite(e)?fk:Math.max(gk,Math.min(mk,Math.floor(e)))}function qr(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>=hk))break}return n}function In(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Mi(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 Ru(e,t){let{cited:n,total:r}=In(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function Au(e,t){if(!t)return null;let{cited:n}=In(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 Pu(e,t){let n=qr(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(`
|
|
926
926
|
`),o=n.length?`
|
|
927
927
|
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?`,
|
|
@@ -1025,7 +1025,7 @@ How often each brand surfaces across the same ${e.results.length} queries.
|
|
|
1025
1025
|
| Brand | Surfaced | Rate |
|
|
1026
1026
|
|-------|----------|------|
|
|
1027
1027
|
${t}
|
|
1028
|
-
`}function Su(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function Ee(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function On(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=vn();if(!Lr(r)){u.warn(oe[r].summary),oe[r].next&&u.message(` ${oe[r].next}`),process.exitCode=1;return}u.info(D.dim(oe[r].summary)),r==="claude-session-unverified"&&oe[r].next&&u.message(D.dim(` ${oe[r].next}`));let o=
|
|
1028
|
+
`}function Su(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function Ee(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function On(e={}){let t=process.cwd(),n=j(t);if(!n)return;let r=vn();if(!Lr(r)){u.warn(oe[r].summary),oe[r].next&&u.message(` ${oe[r].next}`),process.exitCode=1;return}u.info(D.dim(oe[r].summary)),r==="claude-session-unverified"&&oe[r].next&&u.message(D.dim(` ${oe[r].next}`));let o=xt(t),i=fr(t),s=qr(e.competitors&&e.competitors.length?e.competitors:Rk(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},l=Eu(e.queries);u.message(`${D.cyan("\u25C7")} Auditing AI citations for ${D.bold(a.domain)} \u2014 ${l} web-grounded quer${l===1?"y":"ies"} via ${Wr}.`),u.message(D.dim(` This runs live web searches and can take a minute\u2026
|
|
1029
1029
|
`));let c=Pu(a,l),d=await _k({cwd:t,prompt:c,model:e.model});if(d===null){process.exitCode=1;return}let p=Iu(d);if(!p){u.error(`Couldn't read a citation report from the agent's reply. Re-run \`${m("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let f=new Date().toISOString(),g=_u(t),h=Ak(g),y=Au(p,h),w=Ou(p,{generatedAt:f,trend:y});Tu(Kr(t),{recursive:!0}),Lu(xu(t),w,"utf-8"),Tu(g,{recursive:!0}),Lu(ju(g,Cu(f)),JSON.stringify(Ru(p,{generatedAt:f}),null,2)+`
|
|
1030
1030
|
`,"utf-8");let{cited:b,total:E}=In(p),H=b===0?D.red:b<E?D.yellow:D.green,T=[{content:D.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${D.cyan(p.domain)}`},{content:`Cited: ${H(`${b} / ${E}`)} ${D.dim("queries")}`}];if(y){let M=y.scoreDelta>0?D.green(`\u25B2 +${y.scoreDelta}`):y.scoreDelta<0?D.red(`\u25BC ${y.scoreDelta}`):D.dim("\u25AA 0");T.push({content:`Trend: ${M} ${D.dim(`vs ${y.prevCited}/${y.prevTotal} on ${y.prevDate}`)}`})}else T.push({content:D.dim("Trend: first run \u2014 re-run to start tracking")});if(T.push({content:`Engine: ${D.dim(Wr)}`}),p.competitors.length){T.push({sep:!0}),T.push({content:D.dim("Share of voice:")});for(let M of Mi(p)){let se=M.isYou?D.bold(`${M.brand} (you)`):M.brand;T.push({content:` ${se}: ${M.surfaced}/${M.total}`})}}T.push({sep:!0}),T.push({content:D.dim(`Saved \u2192 .seoagent/${ji}/${Di}`)}),T.push({content:b<E?D.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):D.dim("Surfacing across the board. Re-run periodically to catch drift.")}),u.message(B(T,{title:D.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(p,null,2)+`
|
|
1031
1031
|
`)}async function _k(e){let{cwd:t,prompt:n,model:r}=e;try{let o=xk({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 l of a)Ck(l)}else if(s.type==="result"){if(process.stdout.write(`
|
|
@@ -1043,4 +1043,4 @@ ${t}
|
|
|
1043
1043
|
`);return}u.message(ev(s)),a.length>0&&u.message(ee.dim(`Also logged in to: ${a.join(", ")}.`)),s.paid===!1&&u.message(`${ee.dim("Upgrade for autopilot:")} ${ee.cyan(be("cli-whoami"))}`)}function ev(e){let n=i=>ee.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${ee.green("\u2713")} ${ee.dim("Logged in as")} ${ee.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${ee.cyan(e.domain)}`}),e.plan){let i=e.paid?ee.bold(ee.green(e.plan)):ee.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${ee.dim(e.api_base)}`});let o=`${ee.bold(ee.cyan("SEOAgent"))} ${ee.dim("\xB7")} ${ee.dim("whoami")}`;return B(r,{width:55,title:o})}import{spinner as tv}from"@clack/prompts";import Dn from"picocolors";function Wu(e,t){switch(e){case"missing_header":case"malformed_header":case"invalid_credentials":return"Not logged in for this site. Run `seoagent login` first.";case"oauth_not_configured":return"Google sign-in is not configured on this server. Connect Search Console from the dashboard instead.";default:return typeof e=="string"&&e?`Search Console request failed: ${e}`:`HTTP ${t} (client error)`}}function Ku(e,t){let n=t&&typeof t=="object"?t:null;return e===404?{status:"error",terminal:!0,message:"This server does not support `seoagent gsc connect` yet. Connect Search Console from the dashboard, or update the CLI."}:e>=500?{status:"error",terminal:!1,message:`HTTP ${e} (server error)`}:e>=400?{status:"error",terminal:!0,message:Wu(n?.code,e)}:n?.status==="ok"&&typeof n.auth_url=="string"&&typeof n.since=="string"?{status:"ok",auth_url:n.auth_url,since:n.since}:{status:"error",terminal:!0,message:'Malformed response: expected { status: "ok", auth_url, since }'}}function qu(e,t){let n=t&&typeof t=="object"?t:null;if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e===404)return{status:"error",terminal:!0,message:"This server does not support `seoagent gsc status` yet. Update the CLI or check the dashboard."};if(e>=400)return{status:"error",terminal:!0,message:Wu(n?.code,e)};if(!n)return{status:"error",terminal:!0,message:"Malformed response: expected an object"};if(n.status==="none"||n.status==="pending")return{status:n.status};if(n.status==="ready"){let r=n.property&&typeof n.property=="object"?n.property:null;return{status:"ready",email:typeof n.email=="string"?n.email:null,property:r&&typeof r.site_url=="string"?{site_url:r.site_url,permission_level:typeof r.permission_level=="string"?r.permission_level:null,verified:r.verified!==!1}:null,properties_count:typeof n.properties_count=="number"?n.properties_count:0}}return{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}function Wi(e,t){let n=e.email?` as ${e.email}`:"";if(e.property)return`Search Console connected${n}. Property for ${t??"this site"}: ${e.property.site_url} (${e.property.permission_level??"verified"}).`;let r=t??"this site",o=e.properties_count;return`Search Console connected${n}, but that Google account has no verified property for ${r} (${o} propert${o===1?"y":"ies"} found). Add and verify ${r} at search.google.com/search-console, then run \`seoagent gsc connect\` again.`}var nv=2e3,rv=300*1e3;function ov(e){return new Promise(t=>setTimeout(t,e))}async function Vu(e,t,n){try{let r=`${e}/api/cli/gsc/status${n?`?since=${encodeURIComponent(n)}`:""}`,o=await fetch(r,{headers:{Authorization:t,Accept:"application/json"},signal:AbortSignal.timeout(3e4)}),i=null;try{i=await o.json()}catch{}return qu(o.status,i)}catch(r){return{status:"error",terminal:!1,message:r.message||"network error"}}}function Mn(e,t){if(ke())return;let n=Le(e);n&&tt({installId:n,event:t,cliVersion:C})}async function Ki(e,t={}){if(e!=="connect"&&e!=="status"){u.error(`Unknown action "${e}". Use \`${m("gsc")} connect\` or \`${m("gsc")} status\`.`),process.exitCode=1;return}let n=process.cwd(),r=_(n),o=r?.domain&&r.domain!=="unknown"?r.domain:null,i=N(o);if(!i){t.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
|
|
1044
1044
|
`):u.error(`Not logged in${o?` for ${o}`:""}. Run \`${m("login")}\` first \u2014 Search Console connects to the account the CLI is bound to.`),process.exitCode=1;return}let s=(t.apiBase||i.api_base||O.BASE).replace(/\/$/,""),a=`Bearer ${i.user_token}:${i.website_token}`;if(e==="status"){let g=await Vu(s,a,null);if(t.json){process.stdout.write(`${JSON.stringify({logged_in:!0,...g})}
|
|
1045
1045
|
`),g.status==="error"&&(process.exitCode=1);return}if(g.status==="ready"){let h=Wi(g,o);g.property?u.success(h):u.warn(h);return}if(g.status==="error"){u.error(g.message),process.exitCode=1;return}u.info(`Search Console is not connected. Run \`${m("gsc")} connect\` to sign in with Google \u2014 takes about 30 seconds.`);return}let l;try{let g=await fetch(`${s}/api/cli/gsc/connect/start`,{method:"POST",headers:{Authorization:a,Accept:"application/json"},signal:AbortSignal.timeout(15e3)}),h=null;try{h=await g.json()}catch{}l=Ku(g.status,h)}catch(g){l={status:"error",terminal:!1,message:g.message||"network error"}}if(l.status==="error"){u.error(l.message),Mn(n,"gsc_connect_failed"),process.exitCode=1;return}u.message("Opening Google to connect Search Console to your SEOAgent account..."),u.info(`If the browser does not open, visit: ${l.auth_url}`),mr(l.auth_url),u.info("In your browser: choose the Google account that owns the Search Console property, then click Allow.");let d=!!process.stdout.isTTY?tv():null;d?.start(Dn.dim("Waiting for Google\u2026"));let p=Date.now()+rv,f=!0;for(;Date.now()<p;){f||await ov(nv),f=!1;let g=await Vu(s,a,l.since);if(g.status==="ready"){let h=Wi(g,o);g.property?(S(d,"success",h,Dn.green(h)),u.info(`Real queries and indexing verdicts now flow to this site. Next: \`${m("keywords")} --seed\`.`),Mn(n,"gsc_connect_ok")):(S(d,"warn",h,Dn.yellow(h)),Mn(n,"gsc_connect_no_property")),t.json&&process.stdout.write(`${JSON.stringify(g)}
|
|
1046
|
-
`);return}if(g.status==="error"&&g.terminal){S(d,"warn",g.message,Dn.red(g.message)),Mn(n,"gsc_connect_failed"),process.exitCode=1;return}}S(d,"warn",`Timed out waiting for Google. Run \`${m("gsc")} connect\` again to retry.`,Dn.yellow("Timed out waiting for Google.")),d&&u.warn(`Run \`${m("gsc")} connect\` again to retry.`),Mn(n,"gsc_connect_timeout"),process.exitCode=1}import{select as Un,text as Fn,confirm as Ju,isCancel as ce,intro as iv,outro as sv}from"@clack/prompts";import Yr from"picocolors";function av(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>an()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await re()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await nn()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await en()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await jn()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Un({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(!ce(e))if(e==="peek"){let t=await Fn({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(ce(t))return;await Xe({peek:String(t)})}else e==="discover"?await Xe({discover:!0}):e==="competitors"?await Xe({competitors:!0}):await Xe()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>xn({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await Un({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"}]});ce(e)||_n(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 On()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Fn({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(ce(e))return;let t=await Fn({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});ce(t)||await Nn({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Ln({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Un({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"}]});ce(e)||await Sn(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await gt()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Fn({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(ce(e))return;let t=await Ju({message:"Mark as failed instead of completed?",initialValue:!1});if(ce(t))return;let n;if(t===!0){let r=await Fn({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(ce(r))return;String(r).trim()&&(n=String(r))}await Se(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 cn()},{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 un({})},{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 Un({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"}]});ce(e)||Tn({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>tn()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await rn({})}]}var zu="__exit__";async function Yu(e=av()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:zu,label:"Exit",hint:"Close the menu"});let n=await Un({message:"What would you like to do?",options:t});if(ce(n)||n===zu)return!0;let r=e.find(o=>o.command===n);if(!r)return u.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){u.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function qi(){if(!process.stdin.isTTY){u.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}iv(`${Yr.bold(Yr.cyan("SEOAgent"))} ${Yr.dim("\xB7 menu")}`);let e=await Yu();for(;!e;){let t=await Ju({message:"Do another?",initialValue:!0});if(ce(t)||t===!1){e=!0;break}e=await Yu()}sv(Yr.dim("See you next time."))}var R=new lv;R.name("seoagent").description("AI SEO agent for Claude Code").version(C).showSuggestionAfterError(!0).showHelpAfterError(!0);R.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").option("--allow-worktree","Scaffold .seoagent/ inside a temporary git worktree anyway (not recommended \u2014 it is deleted with the worktree)").option("--code <code>","One-time setup code from seoagent.com/grok \u2014 scaffolds AND binds this project in one command, no browser (also read from SEOAGENT_SETUP_CODE)").action(e=>{nn({yes:e.yes,domain:e.domain,siteType:e.siteType,allowWorktree:e.allowWorktree,code:e.code})});R.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{rn({yes:e.yes,global:e.global})});R.command("status").description("Show current SEO project state").action(an);R.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{fi({json:e.json})});R.command("login").description("Connect this CLI to your seoagent.com account (browser flow, or --code for headless setup)").option("--api-base <url>","Override API base URL (for testing)").option("--code <code>","One-time setup code from seoagent.com/grok \u2014 binds headlessly, no browser (also read from SEOAGENT_SETUP_CODE)").action(e=>{en({apiBase:e.apiBase,code:e.code})});R.command("logout").description("Remove stored credentials for this project's site (--all for every logged-in site)").option("--all","Log out of every stored site, not just this project's").action(e=>{tn({all:e.all})});R.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force [relpath]","Re-send every artifact on push; take cloud on every pull conflict. Give a path (`--force content/x.md`) to take cloud for that ONE artifact and leave the other conflicts alone.").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=>{re({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});R.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force [relpath]","Take the cloud version on every conflict (discards local edits). Give a path to force that ONE artifact.").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{gt({force:e.force,silent:e.silent,print:e.print})});R.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{Se(e,{failed:t.failed,reason:t.reason})});R.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{oi({json:e.json})});R.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{ai({yes:e.yes,model:e.model})});R.command("autopilot <action> [value]").description("Turn CLI autopilot on|off, show status, toggle `auto-approve on|off`, or set `draft-mode cloud|agent` (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t,n)=>{Sn(e,t,{apiBase:n.apiBase})});R.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Xe({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});R.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{xn({json:e.json})});R.command("content [action]").description("Track published articles so the dashboard sees them \u2014 `content track` (one) or `content reconcile` (backfill all)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").option("--brief <brief-slug>","Brief this article was generated from (preserved automatically if the record already has one)").option("--supersedes <slug>","The cloud-delivered draft slug this article shipped as, when you renamed it \u2014 marks that draft superseded instead of leaving a duplicate").option("--action <id>","The cli_draft_ready action this track closes out (acks it for you)").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)=>{ci(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword,brief:t.brief,supersedes:t.supersedes,action:t.action,dir:t.dir,prune:t.prune})});R.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold|publish] \u2192 .seoagent/okf/ (publish copies it into your static dir so /.well-known/okf/ is actually served)").option("--json","Output result as JSON").action((e,t)=>{_n(e,{json:t.json})});R.command("llms").description("Generate and publish llms.txt \u2014 the markdown map answer engines read. Built from .seoagent/pages.md, content/, evidence.md and context.md, written to .seoagent/llms.md and published to <public_dir>/llms.txt. Runs automatically on every `seoagent sync`.").option("--json","Output result as JSON").action(e=>{gi({json:e.json})});R.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{mi({url:e.url,json:e.json})});R.command("crawl").description("Capture the live-crawl evidence base (title, meta, all H1s, canonical, JSON-LD @types, OG/Twitter, img-alt gaps, robots.txt, sitemap counts, client-render detection) for the homepage + subpages discovered from the live sitemap + nav links, with a site-wide rollup \u2192 .seoagent/audit/evidence.md. Grounds every audit claim so nothing is invented. The crawled origin is EXPLICIT: --url wins (and is persisted as live_url: in project.md), else live_url:/domain: from project.md, else it errors \u2014 never a guess. An undesignated loopback origin is labeled SOURCE RENDER, not live evidence.").option("--url <origin>","The live site origin to crawl (e.g. https://example.com or http://127.0.0.1:3000) \u2014 persisted as live_url: in project.md for later runs").option("--max <n>","Max pages to crawl (default: every discovered page, up to 500)",e=>parseInt(e,10)).option("--json","Output the full evidence bundle as JSON").action(e=>{_i({url:e.url,max:e.max,json:e.json})});R.command("indexing").description("GSC indexing coverage: which sitemap URLs Google has actually indexed (authoritative URL Inspection verdicts) \u2192 .seoagent/audit/indexing.md. Requires the free `seoagent login` (connects Search Console). Origin resolution mirrors crawl: --url wins, else live_url:/domain: from project.md, else it errors \u2014 never a guess.").option("--url <origin>","The live site origin (e.g. https://example.com)").option("--max <n>","Max sitemap URLs to inspect (default 30, max 200 \u2014 URL Inspection has a daily quota)",e=>parseInt(e,10)).option("--json","Output the results as JSON").action(e=>{Ri({url:e.url,max:e.max,json:e.json})});R.command("verify-recs [files...]").description('Mechanically verify authored recommendations against the crawl evidence (.seoagent/audit/evidence.md) \u2014 rewrites false "added X / none existed / missing X" claims about head-level entities (title, meta description, canonical, OG, twitter:card, JSON-LD) the live page already serves, across .seoagent/**/*.md plus any files passed. Mandatory final step of an audit/optimization session. Always exits 0.').option("--json","Output the machine-readable correction report as JSON").option("--quiet","Print only actionable output (corrections / source-render warning) \u2014 for hooks").action((e,t)=>{Ai({files:e??[],json:t.json,quiet:t.quiet})});R.command("summary [files...]").description("Compose the ready-to-deliver session summary FROM the corrected on-disk .seoagent state \u2014 top audit findings quoted verbatim (confidence labels + Evidence citations), every verify-recs CORRECTION (so corrected framing is what gets relayed), the migration-plan harvest/redirect/sunset table, and top roadmap items. Runs the verify-recs pass first. The final message of an audit/optimization session must be built from this output, not from memory. Flags live-state claims as UNVERIFIED when the crawl evidence is missing or a source render. Plain markdown to stdout; always exits 0.").option("--json","Output the structured summary as JSON").action((e,t)=>{Pi({files:e??[],json:t.json})});R.command("migrate").description("Plan the migration of legacy Google Search Console authority when the site has repositioned \u2014 classifies each URL/query as harvest | redirect | sunset \u2192 .seoagent/strategy/migration-plan.md").option("--csv <path>","Search Console Pages/Queries CSV export to plan from (no login required)").option("--direction <text>","Override the new-direction summary (else inferred from project.md + context.md)").option("--json","Output the full plan + decisions as JSON").action(e=>{Li({csv:e.csv,direction:e.direction,json:e.json})});R.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{On({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});R.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Ln({json:e.json})});R.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{Nn({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});R.command("gsc <action>").description("Google Search Console: `connect` opens Google sign-in and stores the connection in the cloud; `status` shows the connection and the property for this site").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Ki(e,{json:t.json,apiBase:t.apiBase})});R.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--env","Print `SEOAGENT_AUTH=<user>:<site>` for scheduled runs on a fresh machine (store it as the task secret)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{jn({json:e.json,env:e.env,apiBase:e.apiBase})});R.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(cn);R.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{un({dryRun:e.dryRun,projects:e.projects})});R.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").option("--crawl","Also fetch each page to fill Status / Rendered / Word count in pages.md (slower)").action(e=>{Tn({all:e.all,crawl:e.crawl})});R.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{qi()});process.argv.length===2&&(R.outputHelp(),process.exit(0));R.parse();
|
|
1046
|
+
`);return}if(g.status==="error"&&g.terminal){S(d,"warn",g.message,Dn.red(g.message)),Mn(n,"gsc_connect_failed"),process.exitCode=1;return}}S(d,"warn",`Timed out waiting for Google. Run \`${m("gsc")} connect\` again to retry.`,Dn.yellow("Timed out waiting for Google.")),d&&u.warn(`Run \`${m("gsc")} connect\` again to retry.`),Mn(n,"gsc_connect_timeout"),process.exitCode=1}import{select as Un,text as Fn,confirm as Ju,isCancel as ce,intro as iv,outro as sv}from"@clack/prompts";import Yr from"picocolors";function av(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>an()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await re()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await nn()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await en()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await jn()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Un({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(!ce(e))if(e==="peek"){let t=await Fn({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(ce(t))return;await Xe({peek:String(t)})}else e==="discover"?await Xe({discover:!0}):e==="competitors"?await Xe({competitors:!0}):await Xe()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>xn({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await Un({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"}]});ce(e)||_n(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 On()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Fn({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(ce(e))return;let t=await Fn({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});ce(t)||await Nn({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Ln({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Un({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"}]});ce(e)||await Sn(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await mt()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Fn({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(ce(e))return;let t=await Ju({message:"Mark as failed instead of completed?",initialValue:!1});if(ce(t))return;let n;if(t===!0){let r=await Fn({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(ce(r))return;String(r).trim()&&(n=String(r))}await Se(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 cn()},{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 un({})},{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 Un({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"}]});ce(e)||Tn({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>tn()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await rn({})}]}var zu="__exit__";async function Yu(e=av()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:zu,label:"Exit",hint:"Close the menu"});let n=await Un({message:"What would you like to do?",options:t});if(ce(n)||n===zu)return!0;let r=e.find(o=>o.command===n);if(!r)return u.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){u.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function qi(){if(!process.stdin.isTTY){u.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}iv(`${Yr.bold(Yr.cyan("SEOAgent"))} ${Yr.dim("\xB7 menu")}`);let e=await Yu();for(;!e;){let t=await Ju({message:"Do another?",initialValue:!0});if(ce(t)||t===!1){e=!0;break}e=await Yu()}sv(Yr.dim("See you next time."))}var R=new lv;R.name("seoagent").description("AI SEO agent for Claude Code").version(C).showSuggestionAfterError(!0).showHelpAfterError(!0);R.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").option("--allow-worktree","Scaffold .seoagent/ inside a temporary git worktree anyway (not recommended \u2014 it is deleted with the worktree)").option("--code <code>","One-time setup code from seoagent.com/grok \u2014 scaffolds AND binds this project in one command, no browser (also read from SEOAGENT_SETUP_CODE)").action(e=>{nn({yes:e.yes,domain:e.domain,siteType:e.siteType,allowWorktree:e.allowWorktree,code:e.code})});R.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{rn({yes:e.yes,global:e.global})});R.command("status").description("Show current SEO project state").action(an);R.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{fi({json:e.json})});R.command("login").description("Connect this CLI to your seoagent.com account (browser flow, or --code for headless setup)").option("--api-base <url>","Override API base URL (for testing)").option("--code <code>","One-time setup code from seoagent.com/grok \u2014 binds headlessly, no browser (also read from SEOAGENT_SETUP_CODE)").action(e=>{en({apiBase:e.apiBase,code:e.code})});R.command("logout").description("Remove stored credentials for this project's site (--all for every logged-in site)").option("--all","Log out of every stored site, not just this project's").action(e=>{tn({all:e.all})});R.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force [relpath]","Re-send every artifact on push; take cloud on every pull conflict. Give a path (`--force content/x.md`) to take cloud for that ONE artifact and leave the other conflicts alone.").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=>{re({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});R.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force [relpath]","Take the cloud version on every conflict (discards local edits). Give a path to force that ONE artifact.").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{mt({force:e.force,silent:e.silent,print:e.print})});R.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{Se(e,{failed:t.failed,reason:t.reason})});R.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{oi({json:e.json})});R.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{ai({yes:e.yes,model:e.model})});R.command("autopilot <action> [value]").description("Turn CLI autopilot on|off, show status, toggle `auto-approve on|off`, or set `draft-mode cloud|agent` (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t,n)=>{Sn(e,t,{apiBase:n.apiBase})});R.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Xe({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});R.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{xn({json:e.json})});R.command("content [action]").description("Track published articles so the dashboard sees them \u2014 `content track` (one) or `content reconcile` (backfill all)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").option("--brief <brief-slug>","Brief this article was generated from (preserved automatically if the record already has one)").option("--supersedes <slug>","The cloud-delivered draft slug this article shipped as, when you renamed it \u2014 marks that draft superseded instead of leaving a duplicate").option("--action <id>","The cli_draft_ready action this track closes out (acks it for you)").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)=>{ci(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword,brief:t.brief,supersedes:t.supersedes,action:t.action,dir:t.dir,prune:t.prune})});R.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold|publish] \u2192 .seoagent/okf/ (publish copies it into your static dir so /.well-known/okf/ is actually served)").option("--json","Output result as JSON").action((e,t)=>{_n(e,{json:t.json})});R.command("llms").description("Generate and publish llms.txt \u2014 the markdown map answer engines read. Built from .seoagent/pages.md, content/, evidence.md and context.md, written to .seoagent/llms.md and published to <public_dir>/llms.txt. Runs automatically on every `seoagent sync`.").option("--json","Output result as JSON").action(e=>{gi({json:e.json})});R.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{mi({url:e.url,json:e.json})});R.command("crawl").description("Capture the live-crawl evidence base (title, meta, all H1s, canonical, JSON-LD @types, OG/Twitter, img-alt gaps, robots.txt, sitemap counts, client-render detection) for the homepage + subpages discovered from the live sitemap + nav links, with a site-wide rollup \u2192 .seoagent/audit/evidence.md. Grounds every audit claim so nothing is invented. The crawled origin is EXPLICIT: --url wins (and is persisted as live_url: in project.md), else live_url:/domain: from project.md, else it errors \u2014 never a guess. An undesignated loopback origin is labeled SOURCE RENDER, not live evidence.").option("--url <origin>","The live site origin to crawl (e.g. https://example.com or http://127.0.0.1:3000) \u2014 persisted as live_url: in project.md for later runs").option("--max <n>","Max pages to crawl (default: every discovered page, up to 500)",e=>parseInt(e,10)).option("--json","Output the full evidence bundle as JSON").action(e=>{_i({url:e.url,max:e.max,json:e.json})});R.command("indexing").description("GSC indexing coverage: which sitemap URLs Google has actually indexed (authoritative URL Inspection verdicts) \u2192 .seoagent/audit/indexing.md. Requires the free `seoagent login` (connects Search Console). Origin resolution mirrors crawl: --url wins, else live_url:/domain: from project.md, else it errors \u2014 never a guess.").option("--url <origin>","The live site origin (e.g. https://example.com)").option("--max <n>","Max sitemap URLs to inspect (default 30, max 200 \u2014 URL Inspection has a daily quota)",e=>parseInt(e,10)).option("--json","Output the results as JSON").action(e=>{Ri({url:e.url,max:e.max,json:e.json})});R.command("verify-recs [files...]").description('Mechanically verify authored recommendations against the crawl evidence (.seoagent/audit/evidence.md) \u2014 rewrites false "added X / none existed / missing X" claims about head-level entities (title, meta description, canonical, OG, twitter:card, JSON-LD) the live page already serves, across .seoagent/**/*.md plus any files passed. Mandatory final step of an audit/optimization session. Always exits 0.').option("--json","Output the machine-readable correction report as JSON").option("--quiet","Print only actionable output (corrections / source-render warning) \u2014 for hooks").action((e,t)=>{Ai({files:e??[],json:t.json,quiet:t.quiet})});R.command("summary [files...]").description("Compose the ready-to-deliver session summary FROM the corrected on-disk .seoagent state \u2014 top audit findings quoted verbatim (confidence labels + Evidence citations), every verify-recs CORRECTION (so corrected framing is what gets relayed), the migration-plan harvest/redirect/sunset table, and top roadmap items. Runs the verify-recs pass first. The final message of an audit/optimization session must be built from this output, not from memory. Flags live-state claims as UNVERIFIED when the crawl evidence is missing or a source render. Plain markdown to stdout; always exits 0.").option("--json","Output the structured summary as JSON").action((e,t)=>{Pi({files:e??[],json:t.json})});R.command("migrate").description("Plan the migration of legacy Google Search Console authority when the site has repositioned \u2014 classifies each URL/query as harvest | redirect | sunset \u2192 .seoagent/strategy/migration-plan.md").option("--csv <path>","Search Console Pages/Queries CSV export to plan from (no login required)").option("--direction <text>","Override the new-direction summary (else inferred from project.md + context.md)").option("--json","Output the full plan + decisions as JSON").action(e=>{Li({csv:e.csv,direction:e.direction,json:e.json})});R.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{On({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});R.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Ln({json:e.json})});R.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{Nn({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});R.command("gsc <action>").description("Google Search Console: `connect` opens Google sign-in and stores the connection in the cloud; `status` shows the connection and the property for this site").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Ki(e,{json:t.json,apiBase:t.apiBase})});R.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--env","Print `SEOAGENT_AUTH=<user>:<site>` for scheduled runs on a fresh machine (store it as the task secret)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{jn({json:e.json,env:e.env,apiBase:e.apiBase})});R.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(cn);R.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{un({dryRun:e.dryRun,projects:e.projects})});R.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").option("--crawl","Also fetch each page to fill Status / Rendered / Word count in pages.md (slower)").action(e=>{Tn({all:e.all,crawl:e.crawl})});R.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{qi()});process.argv.length===2&&(R.outputHelp(),process.exit(0));R.parse();
|