cc-safety-net 2.6.3 → 2.6.5

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.
@@ -2,8 +2,8 @@ var ca="CC Safety Net could not analyze the command because it exceeds safe anal
2
2
 
3
3
  `)}function Ce(G,U){if(G.decision.kind!=="deny")return;let j=U.includeEvidence?G.decision.evidence:void 0;return{reason:G.decision.reason,ruleId:G.decision.ruleId,intent:G.decision.intent,command:j?.command,segment:j?.segment,toolName:U.toolName,...G.configFallback?{configWarning:G.configFallback.reason}:{},...G.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function O(G={}){return{reason:ko,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:G.command,segment:G.segment??G.command,toolName:G.toolName}}var rh={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop",ruleId:"cwd.session-unusable"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop",ruleId:"cwd.session-outside-workspace"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative",ruleId:"cwd.requested-unusable"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative",ruleId:"cwd.requested-outside-workspace"}}};function D(G,U={}){return{...rh[G.directory][G.problem],command:U.command,toolName:U.toolName,cwd:G.cwd}}function Y(G){return nh({...G,redact:J})}function rt(G){return J(G instanceof Error?G.message:String(G))}import{lstatSync as Gh,realpathSync as zh,statSync as $h}from"node:fs";import{homedir as Bh,tmpdir as Uh}from"node:os";import{statSync as Lh}from"node:fs";import{join as Wh}from"node:path";import{basename as eu,dirname as oh,isAbsolute as ih,join as sh,normalize as ah,resolve as Jc}from"node:path";var lh=256,Pi=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function an(G,U=process.platform){if(U!=="win32")return G;return G.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function sr(G,U=process.platform){if(U!=="win32")return!1;return(G[0]==="/"||G[0]==="\\")&&(G[1]==="/"||G[1]==="\\")}function fa(G,U){return ua(G,0,U)}function ua(G,U,j){let K="",re=0,oe=0;while(re<G.length){if(G[re]!=="$"){K+=G[re],re++;continue}if(G[re+1]==="{"){let Se=da(G,re+2),we=ch(G,re,U);if(we===null){if(Pi.has(Se))throw new s("pathEnvironmentExpansion");if(oe++,oe>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");K+="${",re+=2;continue}let We=G.slice(re,we+1);K+=uh(We,U,j),re=we+1;continue}let de=da(G,re+1);if(!de){K+="$",re++;continue}K+=ma(de,j)??`$${de}`,re+=de.length+1}return K}function ch(G,U,j){let K=1;for(let re=U+2;re<G.length;re++){if(G[re]==="\\"){re++;continue}if(G[re]==="$"&&G[re+1]==="{"){if(K++,j+K>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");re++;continue}if(G[re]!=="}")continue;if(K--,K===0)return re}return null}function uh(G,U,j){let K=G.slice(2,-1),re=da(K,0);if(!re)return G;let oe=K.slice(re.length);if(!oe)return ma(re,j)??G;let de=[":-",":+",":=",":?","-","+","=","?"].find((We)=>oe.startsWith(We));if(!de){if(Pi.has(re))throw new s("pathEnvironmentExpansion");return G}if(!Pi.has(re))return G;if(de.endsWith("="))throw new s("pathEnvironmentExpansion");let Se=ma(re,j),we=de.startsWith(":")?Se!==null&&Se!=="":Se!==null;if(de.endsWith("?")&&!we)throw new s("pathEnvironmentExpansion");if(de.endsWith("-")||de.endsWith("?"))return we?Se??"":ua(oe.slice(de.length),U+1,j);return we?ua(oe.slice(de.length),U+1,j):""}function da(G,U){if(!/[A-Za-z_]/.test(G[U]??""))return"";let j=U+1;while(/[A-Za-z0-9_]/.test(G[j]??""))j++;return G.slice(U,j)}function ma(G,U){if(!Pi.has(G))return null;if(G==="HOME")return U.env.get("HOME")??U.home;return U.env.get(G)??null}function Nt(G,U,j){if(!G)return G;let K=j.resolvedPaths.get(G);if(K!==void 0)return K;let re=[],oe=G;while(!0){tu(j,oe);let de=U.realpath(oe);if(de!==null)return Qc(j,G,de,re);let Se=oh(oe);if(Se===oe||re.length>=lh)return Qc(j,G,oe,re);re.push(eu(oe)),oe=Se}}function Qc(G,U,j,K){let re=K.length===0?j:sh(j,...K.reverse());return G.resolvedPaths.set(U,re),re}function dh(G,U,j){let K=j.resolvedPaths.get(G);if(K!==void 0)return K;tu(j,G);let re=U.realpath(G);if(re!==null)j.resolvedPaths.set(G,re);return re}function tu(G,U){G.charge("realpathAttempts"),G.charge("processedCandidateBytes",Buffer.byteLength(U))}function ln(G,U,j,K){let re=ru(G,U,j);if(!re)return"";return Nt(re,j.paths,K).replace(/\\/g,"/")}function nu(G,U,j,K,re){let oe=ru(G,U,j);if(!oe)return null;if(re(eu(oe)))return Nt(oe,j.paths,K).replace(/\\/g,"/");let de=dh(oe,j.paths,K);return de===null?null:de.replace(/\\/g,"/")}function ru(G,U,j){let K=j.home,re=fa(G.trim(),j).replace(/\\/g,"/");if(!re)return"";let oe=re==="~"?K:re.startsWith("~/")?Jc(K,re.slice(2)):re,de=an(oe);return ah(ih(de)?de:Jc(U,de))}import{spawnSync as mh}from"node:child_process";import{existsSync as Mo,lstatSync as fh,readFileSync as Do,realpathSync as qr,statSync as Oo}from"node:fs";import{dirname as pa,isAbsolute as ga,join as Kr,resolve as Ai}from"node:path";var ph=["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git","C:\\Program Files\\Git\\cmd\\git.exe","C:\\Program Files\\Git\\bin\\git.exe"],gh=5000;function iu(G,U=Oh(),j=gh){let K=hh(G),re=K===null?null:yh(K);if(K===null||re===null)return null;let oe=Ih(K,re,U,j);return oe===null?null:{recursiveSubmodules:oe}}function hh(G){try{let U=qr(Ai(G));return Oo(U).isDirectory()?U:null}catch{return null}}function yh(G){let U=Th(G);if(!U)return null;try{let j=fh(U);if(j.isSymbolicLink()||!j.isFile())return null;let K=ha(U);if(!K?.commonDir)return null;if(!Sh(K.gitDir,U))return null;return vh(K.gitDir,pa(U))?{gitDir:K.gitDir,commonDir:K.commonDir}:null}catch{return null}}function ha(G){try{let U=bh(G);if(!U)return null;let j=qr(ga(U)?U:Ai(pa(G),U));if(!Oo(j).isDirectory())return null;return{gitDir:j,commonDir:Ch(j)}}catch{return null}}function bh(G){let U=Do(G,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!U.startsWith("gitdir:"))return null;return U.slice(7).trim()||null}function Ch(G){try{let U=Do(Kr(G,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!U)return null;let j=qr(ga(U)?U:Ai(G,U));return Oo(j).isDirectory()?j:null}catch{return null}}function Sh(G,U){let j=Eh(G);return j===null?!1:su(G,j,U)}function vh(G,U){let j=Rh(G);return j===null?!0:su(G,j,U)}function Eh(G){let U=Kr(G,"gitdir");if(!Mo(U))return null;let j=Do(U,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return j===""?null:j}function Rh(G){let U=Kr(G,"config.worktree");return Mo(U)?_h(U):null}function su(G,U,j){try{return xh(ga(U)?U:Ai(G,U),j)}catch{return!1}}function xh(G,U){try{let j=Oo(G),K=Oo(U);if(j.ino!==0&&K.ino!==0&&j.dev===K.dev&&j.ino===K.ino)return!0}catch{}return ou(qr.native(G))===ou(qr.native(U))}function ou(G){let U=G.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),j=U.length>1&&U.endsWith("/")?U.slice(0,-1):U;return process.platform==="win32"?j.toLowerCase():j}function _h(G){let U=Do(G,"utf-8"),j=!1,K=null;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;if(oe.startsWith("[")){j=/^\[core\]$/i.test(oe);continue}if(!j)continue;let de=oe.match(/^worktree\s*=\s*(.*)$/i);if(de)K=wh(de[1]??"")}return K}function wh(G){let U=G.trim();if(!U.startsWith('"')||!U.endsWith('"'))return U;return Ah(U.slice(1,-1))}var Ph={"\\":"\\",'"':'"',n:`
4
4
  `,t:"\t",b:"\b"};function Ah(G){return G.replace(/\\(.?)/gs,(U,j)=>j===""?U:Ph[j]??U)}function Th(G){try{return ya(qr(G))}catch{return null}}function ya(G){let U=G;while(!0){let j=Kr(U,".git");if(Mo(j))return j;let K=pa(U);if(K===U)return null;U=K}}function Ih(G,U,j,K){if(kh(U))return!0;if(j===null)return!0;let re=mh(j,["config","--get","submodule.recurse"],{cwd:G,encoding:"utf8",env:Mh(process.env),stdio:["ignore","pipe","ignore"],timeout:K});if(re.error!==void 0||re.status!==0&&re.status!==1)return null;return re.status===0&&au(re.stdout.trim())}function kh(G){return[Kr(G.commonDir,"config"),Kr(G.gitDir,"config.worktree")].filter((U)=>Mo(U)).some((U)=>Dh(U))}function Oh(){return ph.find((G)=>Mo(G))??null}function No(G){return G==="GIT_CONFIG_COUNT"||G==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(G)}function Mh(G){return Object.fromEntries(Object.entries(G).filter(([U])=>!No(U)))}function Dh(G){let U;try{U=Do(G,"utf-8")}catch{return!0}let j="",K=!1;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;let de=oe.match(/^\[([^\]]+)\]$/);if(de){j=de[1]?.trim().toLowerCase()??"";continue}let Se=oe.indexOf("="),we=(Se===-1?oe:oe.slice(0,Se)).trim().toLowerCase(),We=Se===-1?"true":oe.slice(Se+1).trim();if(Nh(j)&&we==="path")return!0;if(j==="submodule"&&we==="recurse")K=au(We)}return K}function Nh(G){return G==="include"||G.startsWith("includeif ")}function au(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function lu(G,U){if(G==="")return null;let j=Pn(),K=ya(ln(G,G,U,j)),re=K?Fh(K,G,U,j):null;if(!re)return null;return Object.freeze({entries:Object.freeze([re.entry]),markerFiles:Object.freeze(re.markerFile?[re.markerFile]:[]),directories:Object.freeze(re.directories),hooksDirectories:Object.freeze(re.hooksDirectories)})}function Fh(G,U,j,K){try{let re=ln(G,U,j,K),oe=Lh(G),de=oe.isFile()?re:null,Se=oe.isFile()?ha(G):null,we=(oe.isDirectory()?[re]:[Se?.gitDir,Se?.commonDir]).flatMap((mt)=>mt?[Yr(ln(mt,U,j,K))]:[]),We=[...new Set(oe.isDirectory()?[Yr(G.replace(/\\/g,"/")),...we]:we)];return{entry:Yr(re),markerFile:de?Yr(de):null,directories:We,hooksDirectories:[...new Set(We.flatMap((mt)=>{let gt=Yr(Wh(mt,"hooks").replace(/\\/g,"/"));return[gt,Yr(ln(gt,U,j,K))]}))]}}catch{return null}}function Yr(G){return process.platform==="win32"?G.toLowerCase():G}var Hh={realpath:(G)=>{try{return zh(G)}catch{return null}},entryKind:(G)=>{try{let U=Gh(G,{throwIfNoEntry:!1});if(!U)return"missing";return U.isSymbolicLink()?"symlink":"present"}catch(U){if(U.code==="ENAMETOOLONG")return"missing";throw U}},isDirectory:(G)=>{try{return $h(G).isDirectory()}catch{return!1}}};function c(){return jh({env:new Map(Object.entries(process.env).flatMap(([G,U])=>U===void 0?[]:[[G,U]])),home:an(process.env.HOME||Bh()),tmpdir:Uh(),paths:Hh})}function jh(G,U={}){let j=new Map,K=new Map,re={...G,gitMetadata:(oe)=>cu(j,oe,()=>lu(oe,re)),worktreeFacts:(oe)=>cu(K,oe,()=>iu(oe)),...U};return re}function cu(G,U,j){let K=G.get(U);if(K!==void 0)return K;let re=j();return G.set(U,re),re}import{accessSync as py,constants as _u,statSync as gy}from"node:fs";import{isAbsolute as wu,relative as hy,resolve as yy,sep as by}from"node:path";import{types as Vh}from"node:util";var qh=new Set(["applypatch","patch"]),Kh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Yh=new Set(["grep","grepsearch","rg"]),Zh=new Set(["find","findbyname","glob"]),Xh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Jh=new Set(["command","diff","input","patch","patchtext"]),uu=new TextEncoder,Qh=new TextDecoder,ey=/\s/,ty=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Lo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function gu(G){return G.replace(/[-_\s]/g,"").toLowerCase()}function Ii(G){return Xh.has(gu(G))}function P(G){let U=gu(G);if(qh.has(U))return"patch";if(Yh.has(U))return"grep";if(Zh.has(U))return"glob";if(Kh.has(U))return"path";return"unknown"}function ie(G){if(!G||typeof G!=="object")return;Eu(G);let U=Object.getOwnPropertyDescriptor(G,"command");if(!U){if("command"in G)Un();return}if(U.get||U.set)Un();let j=U.value;return typeof j==="string"&&j!==""?j:void 0}function hu(G,U){return yu(G,U,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function yu(G,U,j,K,re){let oe=vu(G,K,re);if(typeof G==="string")return j?[G]:[];if(!oe)return[];let de=oe.entries.flatMap(([Se,we])=>yu(we,U,oe.array?j:U.has(bu(Se)),K,re+1));return K.ancestors.delete(oe.object),de}function bu(G){return G.replace(/-/g,"_").toLowerCase()}function Cu(G){return Su(G,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(ry)}function Su(G,U,j,K){let re=vu(G,j,K);if(typeof G==="string")return U?[G]:[];if(!re)return[];let oe=re.entries.flatMap(([de,Se])=>Su(Se,re.array?U:Jh.has(bu(de)),j,K+1));return j.ancestors.delete(re.object),oe}function ny(G,U,j){if(U.nodes++,G!==null&&typeof G==="object"&&j>Lo.maxDepth||U.nodes>Lo.maxNodes)Un();if(typeof G!=="string")return;let K=Buffer.byteLength(G);if(U.stringBytes+=K,K>Lo.maxStringBytes||U.stringBytes>Lo.maxAggregateStringBytes)Un()}function vu(G,U,j){if(ny(G,U,j),!G||typeof G!=="object")return null;let K=Eu(G);if(U.ancestors.has(G))Un();let re=Reflect.ownKeys(G);if(U.keys+=re.length,U.keys>Lo.maxKeys)Un();let oe=re.flatMap((de)=>{let Se=Object.getOwnPropertyDescriptor(G,de);if(!Se||Se.get||Se.set)Un();return typeof de==="string"&&Se.enumerable?[[de,Se.value]]:[]});return U.ancestors.add(G),{object:G,array:K,entries:oe}}function Eu(G){if(Vh.isProxy(G))Un();let U=Array.isArray(G),j=Object.getPrototypeOf(G);if(U&&j!==Array.prototype||!U&&j!==Object.prototype&&j!==null)Un();return U}function Un(){throw new f}function ry(G){let U=[],j=G.split(/\r?\n/),K=!1,re=!1,oe=null,de=null,Se=()=>{re=!1,oe=null,de=null};for(let we=0;we<j.length;we++){let We=j[we]??"";if(We==="*** Begin Patch"){K=!0,Se();continue}if(We==="*** End Patch"){K=!1,Se();continue}if(We.startsWith("@@")){let mt=oy(We);if(re=!0,oe=mt?.oldLines??null,de=mt?.newLines??null,oe===0&&de===0)Se();continue}if(re&&oe!==null&&de!==null){let mt=We.startsWith(" ")||We.startsWith("-")?1:0,gt=We.startsWith(" ")||We.startsWith("+")?1:0;if(oe=Math.max(0,oe-mt),de=Math.max(0,de-gt),oe===0&&de===0)Se();continue}if(We.startsWith("*** ")){Se(),U.push(...ba(We));continue}if(re)continue;if(We.startsWith("diff --git ")){U.push(...ba(We));continue}if(We.startsWith("--- ")){let mt=j[we+1]??"";if(!mt.startsWith("+++ "))continue;U.push(...Sa(Ti(We.slice(4),!0),Ti(mt.slice(4),!0))),we++;continue}if(!K)U.push(...ba(We))}return U}function oy(G){let U=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(G);if(!U)return null;return{oldLines:Number(U[1]??1),newLines:Number(U[2]??1)}}function ba(G){let U=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(G);if(U?.[1])return pu(U[1]);let j=/^\*\*\* Move to: (.+)$/.exec(G);if(j?.[1])return pu(j[1]);if(G.startsWith("diff --git "))return iy(G.slice(11));let K=/^--- (.+)$/.exec(G);if(K?.[1])return fu(K[1]);let re=/^\+\+\+ (.+)$/.exec(G);if(re?.[1])return fu(re[1]);let oe=/^(?:rename|copy) (?:from|to) (.+)$/.exec(G);if(oe?.[1])return my(oe[1]);return[]}function iy(G){let U=sy(G);if(U.length===2&&U[0]&&U[1])return Sa(U[0],U[1]);let j=ay(G);return j?Sa(G.slice(j.oldStart,j.oldEnd),G.slice(j.newStart,j.newEnd)):[]}function sy(G){let U=[],j=0;while(j<G.length&&U.length<2){while(Er(G[j]))j++;if(j>=G.length)break;let K=G[j]==='"'||G[j]==="'"?G[j]:void 0;if(!K){let oe=j;while(j<G.length&&!Er(G[j]))j++;U.push(G.slice(oe,j));continue}let re=Ru(G,j,K);if(!re)return[];U.push(re.value),j=re.end}while(Er(G[j]))j++;return j===G.length?U:[]}function ay(G){let U=0;while(U<G.length&&Er(G[U]))U++;let j=G.length;while(j>U&&Er(G[j-1]))j--;let K=0,re=U;while(re<j){if(!Er(G[re])){re++;continue}let oe=re;while(re<j&&Er(G[re]))re++;if(oe===U||re===j)continue;if(K++,K>ty)Un();if(ly(G,U,oe,re,j))return{oldStart:U,oldEnd:oe,newStart:re,newEnd:j}}return null}function ly(G,U,j,K,re){if(Ca(G,U,j,K,re))return!0;let oe=du(G,"/",U,j),de=du(G,"/",K,re);if(oe<=U||de<=K)return!1;if(Ca(G,U,oe,K,de))return!1;return Ca(G,oe+1,j,de+1,re)}function Ca(G,U,j,K,re){if(j-U!==re-K)return!1;for(let oe=0;oe<j-U;oe++)if(G[U+oe]!==G[K+oe])return!1;return!0}function du(G,U,j,K){for(let re=j;re<K;re++)if(G[re]===U)return re;return-1}function Er(G){return G!==void 0&&ey.test(G)}function Ru(G,U,j){let K=[],re=U+1;while(re<G.length){let oe=String.fromCodePoint(G.codePointAt(re)??0);if(oe===j)return{value:Qh.decode(Uint8Array.from(K)),end:re+1};if(oe!=="\\"||j==="'"){K.push(...uu.encode(oe)),re+=oe.length;continue}let de=G.slice(re+1),Se=/^[0-7]{1,3}/.exec(de)?.[0];if(Se){K.push(Number.parseInt(Se,8)),re+=Se.length+1;continue}K.push(...uu.encode(cy(de[0]??""))),re+=2}return null}function cy(G){return{a:"\x07",b:"\b",f:"\f",n:`
5
- `,r:"\r",t:"\t",v:"\v"}[G]??G}function uy(G){return Wo(fy(G))}function Sa(G,U){if(G==="/dev/null")return mu(U);if(U==="/dev/null")return mu(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(Wo);let j=dy(G,U)??(G===U?xu(G):null);return[G,U,...j?[j]:[]].flatMap(Wo)}function mu(G){let U=xu(G);return[G,...U?[U]:[]].flatMap(Wo)}function xu(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function dy(G,U){let j=G.indexOf("/"),K=U.indexOf("/");if(j<1||K<1)return null;if(G.slice(0,j)===U.slice(0,K))return null;let re=G.slice(j+1);return re===U.slice(K+1)?re:null}function fu(G){return uy(Ti(G,!0))}function my(G){return Wo(Ti(G,!1))}function Ti(G,U){let j=G.trim(),K=j[0]==='"'||j[0]==="'"?j[0]:void 0;if(K){let re=Ru(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function fy(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function Wo(G){return G===""||G==="/dev/null"?[]:[G]}function pu(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!gy(G).isDirectory())return!1;return py(G,_u.R_OK|_u.X_OK),!0}catch{return!1}}function it(G,U,j){if(sr(G))return;let K=U.flatMap((oe)=>va(oe,j));if(!K[0])return;let re=va(wu(G)?G:yy(K[0],G),j)[0];if(!re)return;return K.some((oe)=>Cy(re,oe))?re:void 0}function Ve(G,U){return G.flatMap((j)=>va(j,U))[0]}function va(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function Cy(G,U){let j=hy(U,G);return j===""||j!==".."&&!j.startsWith(`..${by}`)&&!wu(j)}var Sy=8388608;async function Ke(G){let U=[],j=0;for await(let K of G){let re=typeof K==="string"?Buffer.from(K,"utf-8"):Buffer.from(K.buffer,K.byteOffset,K.byteLength);if(j+=re.byteLength,j>Sy)throw vy(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function vy(G){let U=G.destroy??G.cancel;if(!U)return;try{Promise.resolve(U.call(G)).catch(()=>{})}catch{}}function u(G,U,j,K,re){if(j.kind!=="command")return{toolName:G,input:U,route:j,context:K};return{toolName:G,input:U,route:j,context:K,command:re}}var Zr=["fail_closed","paranoid_rm","paranoid_interpreters"],ki={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var n={level:{name:"CC_SAFETY_NET_LEVEL"},strict:{name:"CC_SAFETY_NET_STRICT",legacyName:"SAFETY_NET_STRICT"},paranoid:{name:"CC_SAFETY_NET_PARANOID",legacyName:"SAFETY_NET_PARANOID"},paranoidRm:{name:"CC_SAFETY_NET_PARANOID_RM",legacyName:"SAFETY_NET_PARANOID_RM"},paranoidInterpreters:{name:"CC_SAFETY_NET_PARANOID_INTERPRETERS",legacyName:"SAFETY_NET_PARANOID_INTERPRETERS"},worktree:{name:"CC_SAFETY_NET_WORKTREE",legacyName:"SAFETY_NET_WORKTREE"},debug:{name:"CC_SAFETY_NET_DEBUG"},auditScope:{name:"CC_SAFETY_NET_AUDIT_SCOPE"},projectTightenOnly:{name:"CC_SAFETY_NET_PROJECT_TIGHTEN_ONLY"}},Oi=["standard","strict","paranoid"];function Pu(G,U){if(!U)return G;return Oi.indexOf(U)>Oi.indexOf(G)?U:G}function Au(G){let U=pe(n.level,G);return Oi.find((j)=>j===U)}function Tu(G,U){return Pu(G,Au(U))}function Ey(G){let U=pe(n.level,G);if(!U)return;let j=Au(G);if(j)return j;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(U.slice(0,40))}. Use ${Oi.join(", ")}.`);return}function qe(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Ee(G){return qe(pe(n.auditScope,G))==="all"}function Ea(G){if(G.failClosed&&G.paranoidRm&&G.paranoidInterpreters)return"paranoid";if(G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"strict";if(!G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"standard";return"custom"}function T(G={},U){let j=G.safety?.level??"standard",K=Ey(U),re=Pu(j,K),oe=ki[re],de={failClosed:oe.fail_closed,paranoidRm:oe.paranoid_rm,paranoidInterpreters:oe.paranoid_interpreters},Se={failClosed:re===j?"preset":"environment",paranoidRm:re===j?"preset":"environment",paranoidInterpreters:re===j?"preset":"environment"},we={failClosed:[`policy safety.level=${j}`],paranoidRm:[`policy safety.level=${j}`],paranoidInterpreters:[`policy safety.level=${j}`]};if(re!==j)we.failClosed.push(`env ${n.level.name}=${K}`),we.paranoidRm.push(`env ${n.level.name}=${K}`),we.paranoidInterpreters.push(`env ${n.level.name}=${K}`);if(G.safety?.overrides?.failClosed!==void 0)de.failClosed=G.safety.overrides.failClosed,Se.failClosed="capability_override",we.failClosed.push("policy safety.overrides.fail_closed");if(G.safety?.overrides?.paranoidRm!==void 0)de.paranoidRm=G.safety.overrides.paranoidRm,Se.paranoidRm="capability_override",we.paranoidRm.push("policy safety.overrides.paranoid_rm");if(G.safety?.overrides?.paranoidInterpreters!==void 0)de.paranoidInterpreters=G.safety.overrides.paranoidInterpreters,Se.paranoidInterpreters="capability_override",we.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(v(n.strict,U))de.failClosed=!0,Se.failClosed="environment",we.failClosed.push(`env ${n.strict.name}`);if(v(n.paranoid,U))de.paranoidRm=!0,de.paranoidInterpreters=!0,Se.paranoidRm="environment",Se.paranoidInterpreters="environment",we.paranoidRm.push(`env ${n.paranoid.name}`),we.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(v(n.paranoidRm,U))de.paranoidRm=!0,Se.paranoidRm="environment",we.paranoidRm.push(`env ${n.paranoidRm.name}`);if(v(n.paranoidInterpreters,U))de.paranoidInterpreters=!0,Se.paranoidInterpreters="environment",we.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let We=!!G.worktreeMode||v(n.worktree,U);return{strict:de.failClosed,paranoidRm:de.paranoidRm,paranoidInterpreters:de.paranoidInterpreters,worktreeMode:We,effectiveLevel:Ea(de),capabilities:{fail_closed:{enabled:de.failClosed,source:Se.failClosed,sources:we.failClosed},paranoid_rm:{enabled:de.paranoidRm,source:Se.paranoidRm,sources:we.paranoidRm},paranoid_interpreters:{enabled:de.paranoidInterpreters,source:Se.paranoidInterpreters,sources:we.paranoidInterpreters}}}}function v(G,U){let j=typeof G==="string"?Fo(G,U):pe(G,U);return j==="1"||j?.toLowerCase()==="true"}function Fo(G,U){return U.get(G)}function pe(G,U){let j=Fo(G.name,U);if(j!==void 0)return j;if(G.legacyName)return Fo(G.legacyName,U);return}function ot(G,U){return Fo(G.name,U)!==void 0||!!G.legacyName&&Fo(G.legacyName,U)!==void 0}import{dirname as wr}from"node:path";import{closeSync as Ry,constants as Go,fstatSync as Ra,fsyncSync as xy,lstatSync as An,mkdirSync as Iu,openSync as ku,readdirSync as _a,readFileSync as _y,realpathSync as Xr,renameSync as wy,rmdirSync as Ou,statSync as xa,unlinkSync as wa,writeFileSync as Py}from"node:fs";import{isAbsolute as Mu,join as Rr,normalize as Ay,parse as Mi,relative as Pa,resolve as Aa,sep as Di}from"node:path";function Ie(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var Ty=Symbol("PolicyFilesystemScope"),Iy=Symbol("PolicyFilesystemTarget"),Du=Go.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function S(G,U){return{[Ty]:!0,root:Aa(G),label:U}}function zo(G,U){let j=Ay(U);if(U===""||Mu(U)||j===".."||j.startsWith(`..${Di}`))throw new o(G.label);return{[Iy]:!0,scope:G,relativePath:j,path:Rr(G.root,j)}}function i(G,U){return zo(G,Pa(G.root,Aa(U)))}function se(G,U="rules policy"){let j=Aa(G),K=Mi(j).dir;return zo(S(K,U),Pa(K,j))}function r(G){return Zn(G.scope.label,()=>{if(!en(G))return null;let U=ku(G.path,Go.O_RDONLY|Du);return Lu(U,()=>{let j=Ra(U);if(!j.isFile())throw new o(G.scope.label);let K=_y(U,"utf-8"),re=An(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return en(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ie()}.tmp`;Zn(G.scope.label,()=>{Oy(G),en(G);let oe=ku(re,Go.O_CREAT|Go.O_EXCL|Go.O_WRONLY|Du,j),de=Lu(oe,()=>{let Se=Ra(oe);if(!Se.isFile())throw new o(G.scope.label);Py(oe,U,"utf-8"),xy(oe);let we=Ra(oe);if(!we.isFile()||we.dev!==Se.dev||we.ino!==Se.ino)throw new o(G.scope.label);return we});en(G),Dy(G,re,de.dev,de.ino),wy(re,G.path),K?.(G.path),en(G)},()=>Ny(re))}function Nu(G,U){if(G.path===U.path)return!0;return Zn(G.scope.label,()=>{if(!en(G)||!en(U))return!1;let j=(K)=>Rr(Xr(Mi(K).dir),Mi(K).base);return j(G.path)===j(U.path)})}function me(G){let U=Zn(G.scope.label,()=>{if(!en(G,"directory"))return null;let j=_a(G.path);return en(G,"directory"),j});if(!U)return null;return Zn(G.scope.label,()=>{let j=U.map((K)=>{let re=zo(G.scope,Rr(G.relativePath,K)),oe=An(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Ni(Ta(G.scope),Xr(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return en(G,"directory"),j})}function H(G){Zn(G.scope.label,()=>{if(!en(G))return;wa(G.path),en(G)})}function st(G){Zn(G.scope.label,()=>{if(!ky(G))return;Fu(G),en(G,"directory")})}function at(G){Zn(G.scope.label,()=>{if(!en(G,"directory"))return;Ou(G.path),en(G,"directory")})}function ky(G){return Zn(G.scope.label,()=>{if(!en(G,"directory"))return!1;return Wu(G),!0})}function Zn(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Lu(G,U){try{return U()}finally{Ry(G)}}function en(G,U="file"){let j=Gu(G.scope);if(!j)return!1;let K=G.relativePath.split(Di);for(let re of K.keys()){let oe=Rr(G.scope.root,...K.slice(0,re+1)),de=An(oe,{throwIfNoEntry:!1});if(!de)return!1;if(de.isSymbolicLink())throw new o(G.scope.label);if(re<K.length-1&&!de.isDirectory())throw new o(G.scope.label);if(re===K.length-1&&(U==="file"?!de.isFile():!de.isDirectory()))throw new o(G.scope.label);Ni(j,Xr(oe),G.scope.label)}return!0}function Wu(G){for(let U of _a(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=An(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Wu(j)}en(G,"directory")}function Fu(G){for(let U of _a(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=An(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Fu(j);continue}if(!K.isFile())throw new o(G.scope.label);wa(j.path)}Ou(G.path)}function Oy(G){My(G.scope);let U=Ta(G.scope),j=G.relativePath.split(Di).slice(0,-1);for(let K of j.keys()){let re=Rr(G.scope.root,...j.slice(0,K+1));if(!An(re,{throwIfNoEntry:!1}))Iu(re,{mode:448});let oe=An(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Ni(U,Xr(re),G.scope.label)}}function My(G){if(An(G.root,{throwIfNoEntry:!1})){if(!xa(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!An(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Mi(j).dir;if(K===j)throw new o(G.label);j=K}if(!xa(j).isDirectory())throw new o(G.label);for(let K of U){Iu(K,{mode:448});let re=An(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function Gu(G){if(!An(G.root,{throwIfNoEntry:!1}))return null;if(!xa(G.root).isDirectory())throw new o(G.label);return Xr(G.root)}function Ta(G){let U=Gu(G);if(!U)throw new o(G.label);return U}function Dy(G,U,j,K){let re=An(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Ni(Ta(G.scope),Xr(U),G.scope.label)}function Ni(G,U,j){let K=Pa(G,U);if(K===".."||K.startsWith(`..${Di}`)||Mu(K))throw new o(j)}function Ny(G){try{wa(G)}catch{}}import{dirname as xr,isAbsolute as zy,join as _r,relative as $y,resolve as ar,sep as By}from"node:path";var d=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var zu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Ly=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,$u=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Wy=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^${Wy}/(${d.source.slice(1,-1)})/${Fy}$`);function Gy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function Bu(G){if(w(G))try{return N(G),null}catch(U){return U instanceof Error?U.message:String(U)}return d.test(G)?null:`Local rulebook sources must be bare names matching ${d}: ${G}`}function N(G){if(G.startsWith("github:"))throw Error(`Invalid rulebook source: ${G}`);let U=G.match(zu);if(!U?.[1]||!U[2]||!U[3])throw Error(`Invalid GitHub rulebook source: ${G}`);let j=U[3].lastIndexOf("/");if(j<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);let K=U[3].slice(0,j),re=U[3].slice(j+1);if(!K||!$u.test(K))throw Error(`GitHub rulebook refs must use valid path segments: ${G}`);if(!re||!d.test(re))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);return{owner:U[1],repo:U[2],ref:K,path:Gy(re),name:re}}function Z(G){return Ly.test(G)}function ae(G){return $u.test(G)}function w(G){return zu.test(G)}function lt(G){if(!d.test(G))throw Error(`Local rulebook sources must be bare names matching ${d}: ${G}`)}var Uu="rule.json",Li="policy.json",Hu=".cc-safety-net",Uy="rules",Hy="CC_SAFETY_NET_HOME",ju="`cc-safety-net rule update`";function jy(G){return ar(G,he)}function _(G){return _r(jy(G),Uu)}function h(G){return _r(ar(G),Hu,Li)}function ke(G,U={}){return U.userConfigDir??(U.userConfigPath?xr(U.userConfigPath):_r(Vy(G),Uy))}function Vy(G){let U=G.env.get(Hy);return U?ar(an(U)):_r(G.home,Hu)}function W(G,U={}){return _r(ke(G,U),Uu)}function l(G,U={}){return _r(xr(ke(G,U)),Li)}function L(G,U){let j=Pn();return Nt(h(U.cwd),G.paths,j)===Nt(ar(l(G,U)),G.paths,j)}function X(G,U){let j=U.userConfigPath??W(G,U),K=U.projectConfigPath??_(U.cwd),re=Je(G,U),oe=Ye(K,U.cwd);return{userConfigPath:j,projectConfigPath:K,userScope:re,projectScope:oe,userConfigTarget:i(re,j),projectConfigTarget:i(oe,K)}}function Je(G,U){let j=U.userConfigPath?xr(xr(ar(U.userConfigPath))):xr(ar(U.userConfigDir??ke(G,U)));return S(j,"user policy")}function Ye(G,U){let j=ar(U),K=ar(G),re=$y(j,K);if(re!==".."&&!re.startsWith(`..${By}`)&&!zy(re))return S(j,"project policy");return S(xr(xr(K)),"project policy")}function M(G,U){return _r(G,U,ge)}var Sn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),C=/^[a-zA-Z][a-zA-Z0-9_-]*$/,I=256,Vt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Vu=new Set(["python","python3","python2","node","ruby","perl"]),Wi=/^python(?:[23](?:\.\d+)*)?$/,Tn=new Set(["awk","gawk","nawk","mawk"]),Fi=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var qu="Rulebook exceeds CC Safety Net's safe validation limits.",Ku="Additional rulebook validation errors were omitted.",Dn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Yu(G){if(Ia(G.allowed_commands,Dn.maxAllowedCommands)||Ia(G.rules,Dn.maxRules)||Ia(G.tests,Dn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Dn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Dn.maxStringCodeUnits||oe&&re.length>Dn.maxFixtureCommandCodeUnits||re.length>U)return!1;return U-=re.length,!0};if(!K(G.name)||!K(G.version)||!K(G.description)||!K(G.author)||!K(G.migrated_from))return!1;if(Array.isArray(G.allowed_commands)){for(let re of G.allowed_commands)if(!K(re))return!1}if(Array.isArray(G.rules))for(let re of G.rules){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.name)||!K(oe.command)||!K(oe.subcommand)||!K(oe.reason)||!K(oe.intent))return!1;let de=oe.match&&typeof oe.match==="object"?oe.match:{};for(let Se of[oe.block_args,de.command_path,de.any_args,de.exclude_args]){if(!Array.isArray(Se))continue;if(Se.length>Dn.maxBlockArgsPerRule||Se.length>j)return!1;j-=Se.length;for(let we of Se)if(!K(we))return!1}}if(Array.isArray(G.tests))for(let re of G.tests){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.command,!0)||!K(oe.expect)||!K(oe.rule))return!1}return!0}function Ia(G,U){return Array.isArray(G)&&G.length>U}var ka=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ye=64,be="Rule config exceeds CC Safety Net's safe source limit.";function Mt(G){return kt(G).toLowerCase()}function kt(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}function dn(G,U){let j=new Set,K=!1;for(let re of G){if(re==="--"){K=!0;continue}if(K)continue;if(re.startsWith("-")&&!re.startsWith("--")&&re.length>1)for(let oe=1;oe<re.length;oe++){let de=re[oe];if(!de||!/[a-zA-Z]/.test(de))break;let Se=`-${de}`;if(j.add(Se),U?.shortOptsWithValue?.has(Se))break}}return j}var qy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Oa=new Set(["--init-file","--rcfile"]);function Ma(G,U,j,K){let re=!1,oe=0,de=!1,Se=!1,we=!1;for(let We=1;We<U.length;We++){let mt=U[We];if(mt===void 0)break;if(G==="ksh"&&mt==="o"&&We+1<U.length){if(K==="argv"){let gt=U.slice(We+1);if(U[0]==="-"&&(gt==="c"||gt[0]==="-"&&gt.endsWith("c")))de=!0}break}if(G==="ksh"&&mt==="o"&&We+1===U.length&&(j?.startsWith("-")||j?.startsWith("+")))break;if(G==="zsh"&&mt==="o"&&We+1<U.length)break;if(K==="startup"&&mt==="i")re=U[0]==="-";if(K==="argv"&&U[0]==="-"&&mt==="c")de=!0;if(K==="argv"&&mt==="n")we=U[0]==="-";if(K==="argv"&&mt==="s")Se=U[0]==="-";if(!qy[G]?.includes(mt))continue;if(We+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Se,syntaxCheck:we}}function vn(G){let U=kt(G[0]??"").toLowerCase(),j=!1,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--"){let we=j&&G[oe+1]!==void 0?oe+1:null;return{command:we===null?null:G[we]??null,commandIndex:we,scriptIndex:!j&&!K&&G[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!j&&(K||G[oe+1]===void 0),syntaxCheck:re}}if(de==="-"||de[0]!=="-"&&de[0]!=="+")return{command:j?de:null,commandIndex:j?oe:null,scriptIndex:!j&&!K&&de!=="-"?oe:null,readsStdinAsCommands:!j&&(K||de==="-"),syntaxCheck:re};if(de.startsWith("--")){let we=de.split("=",1)[0]??de;if(U==="bash"&&Oa.has(we)&&!de.includes("="))oe++;continue}let Se=Ma(U,de,G[oe+1],"argv");if(Se.commandSelected)j=!0;if(Se.syntaxCheck)re=!0;if(Se.stdinMode)K=!0;oe+=Se.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!j,syntaxCheck:re}}function $o(G,U){if(U.escaped)return U.escaped=!1,!0;if(G==="\\"&&!U.inSingle)return U.escaped=!0,!0;if(G==="'"&&!U.inDouble)return U.inSingle=!U.inSingle,!0;if(G==='"'&&!U.inSingle)return U.inDouble=!U.inDouble,!0;return!1}function Gi(G){let U={inSingle:!1,inDouble:!1,escaped:!1};for(let j of Ky(G))$o(j,U);return U.inSingle||U.inDouble}function Ky(G){let U="",j={inSingle:!1,inDouble:!1,escaped:!1},K=!1,re=!0;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(!de)break;if(K){if(de===`
6
- `||de==="\r")U+=de,K=!1,j.escaped=!1;continue}if(de==="#"&&!j.inSingle&&!j.inDouble&&re){K=!0;continue}if(U+=de,!j.inSingle&&!j.inDouble&&!j.escaped)re=/[\s;&|()<>]/.test(de);$o(de,j)}return U}var Da=new Set(["rm","find","xargs","parallel"]),Yy=new Set(["git","busybox",...Da,...Vt,...Vu,...Tn]),Zy=new Set(["python","node","ruby","perl"]);function Ae(G){let U=Mt(G);return Yy.has(U)||Nn(U)}function Nn(G){return Zy.has(Xy(G))}function Xy(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}var ut={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(G){try{let U=r(Jy(G));if(U===null)return{config:null,errors:[]};if(!U.trim())return{config:null,errors:["Config file is empty"]};let j=JSON.parse(U),K=Ze(j);if(K.errors.length>0)return{config:null,errors:K.errors};return{config:{version:1,rules:j.rules??[],overrides:j.overrides??{},transparent_wrappers:j.transparent_wrappers??[]},errors:[]}}catch(U){if(U instanceof o)return{config:null,errors:[U.message]};let j=U instanceof Error?U.message:String(U);return{config:null,errors:[U instanceof SyntaxError?"Invalid JSON":j]}}}function Jy(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),tn=(G,U)=>({path:G,message:U,kind:"custom"});function Oe(G){let U=new Set;return G.flatMap((j,K)=>{let re=Jr(j)?j.name:void 0;if(typeof re!=="string")return[];if(U.has(re.toLowerCase()))return[tn(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Re=`must be one of ${ka.join(", ")}`,Qy=/^[^/]+\/[^/]+$/,eb=["version","rules","overrides","transparent_wrappers"];function Ze(G){let U=tb(G);return{errors:ce(Xe(U,eb,(j)=>j.kind==="custom"),": "," "),sources:cb(G,U)}}function tb(G){if(!Jr(G))return[e([],"Config must be an object")];let U=Array.isArray(G.rules)&&G.rules.length>ye;return[...G.version===1?[]:[e(["version"],"must be 1")],...nb(G.rules,U),...ib(G.overrides),...ab(G.transparent_wrappers),...U?[]:ob(G.rules),...Jr(G.overrides)?Object.keys(G.overrides).filter((j)=>!Qy.test(j)).map((j)=>tn(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...lb(G.transparent_wrappers)]}function nb(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...Zu(G,ye)?[e(["rules"],be)]:[]];if(U)return[{path:["rules"],message:be,kind:"limit"}];return G.flatMap((j,K)=>{if(typeof j!=="string")return[e(["rules",K],"must be a rulebook source string"),...rb(j,1)?[e(["rules",K],"must be a non-empty rulebook source string")]:[]];return j===""?[e(["rules",K],"must be a non-empty rulebook source string")]:[]})}function Zu(G,U){let j=Xu(G);return j!==void 0&&!(j<=U)}function rb(G,U){let j=Xu(G);return j!==void 0&&!(j>=U)}function Xu(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function ob(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||j==="")return[];if(j.trim()==="")return[tn(["rules",K],"must be a non-empty rulebook source string")];let re=Bu(j);if(re)return[tn(["rules",K],re)];if(U.has(j))return[tn(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function ib(G){if(G===void 0)return[];if(!Jr(G))return[e(["overrides"],"must be an object if provided")];return Object.keys(G).flatMap((U)=>{let j=G[U];if(j==="off")return[];if(!Jr(j))return[e(["overrides",U],'must be "off" or an object')];return[...sb(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Te(j.intent)?[]:[e(["overrides",U,"intent"],Re)]]})}function sb(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...Zu(G,I)?[e(U,`must be at most ${I} characters`)]:[]];if(G==="")return[e(U,"required non-empty string")];return G.length>I?[e(U,`must be at most ${I} characters`)]:[]}function ab(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["transparent_wrappers"],"must be an array of command strings")];return G.flatMap((U,j)=>{if(typeof U!=="string")return[e(["transparent_wrappers",j],"must be a command string")];return C.test(U)?[]:[e(["transparent_wrappers",j],"must match command pattern")]})}function lb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[tn(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Ae(j))return[tn(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function cb(G,U){let j=Jr(G)?G.rules:void 0;if(!Array.isArray(j))return new Set;if(U.some((re)=>re.path.length===1&&re.path[0]==="rules"))return new Set;let K=new Set(U.filter((re)=>re.path[0]==="rules"&&typeof re.path[1]==="number").map((re)=>re.path[1]));return new Set(j.filter((re,oe)=>typeof re==="string"&&!K.has(oe)))}function Xe(G,U,j){let K=G.map((de)=>de.path[1]),re=[...new Set(K.filter((de)=>typeof de==="string"))],oe=(de,Se)=>[de.path.length===0?-1:U.indexOf(String(de.path[0])),typeof Se==="number"?Se:re.indexOf(String(Se)),j(de)?0:1];return G.map((de,Se)=>({issue:de,rank:oe(de,K[Se])})).sort((de,Se)=>de.rank[0]-Se.rank[0]||de.rank[1]-Se.rank[1]||de.rank[2]-Se.rank[2]).map((de)=>de.issue)}function ce(G,U,j){return[...new Set(G.map((K)=>{let re=Na(K.path);if(K.kind==="unknownKeys")return`${re?`${re}.`:""}unknown field "${K.message}"`;if(K.kind==="key"||K.kind==="limit"||K.path.length===0)return K.message;return`${re}${K.path.length===1?j:U}${K.message}`}))]}function Na(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Te(G){return ka.includes(G)}function Jr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=mb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var ub=`required non-empty string up to ${I} characters`,Ju="must be a non-empty array of unique non-empty strings",db="required non-empty array of non-empty strings";function mb(G){if(!lr(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Yu(G))return{errors:[qu],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(fb(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Dn.maxValidationErrors?[...U.slice(0,Dn.maxValidationErrors),Ku]:U,ruleNames:new Set(De(G).map((j)=>j.toLowerCase()))}}function De(G){let U=lr(G)?G.rules:void 0;return(Array.isArray(U)?U:[]).flatMap((j)=>{let K=lr(j)?j.name:void 0;return typeof K==="string"?[K]:[]})}function fb(G,U){return[...typeof G.name==="string"&&d.test(G.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof G.version==="string"&&G.version!==""?[]:[e(["version"],"required non-empty string")],...pb(G.allowed_commands),...gb(G.rules,U),...Cb(G.tests),...Sb(G),...vb(G)]}function pb(G){if(!Array.isArray(G))return[e(["allowed_commands"],"required array")];let U=new Set;return[...G.flatMap((j,K)=>typeof j==="string"&&C.test(j)?[]:[e(["allowed_commands",K],"must match command pattern")]),...G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[tn(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function gb(G,U){if(!Array.isArray(G))return[e(["rules"],"required array")];return[...G.flatMap((j,K)=>{if(!lr(j))return[e(["rules",K],"must be an object")];return U?yb(j,["rules",K]):hb(j,["rules",K])}),...Oe(G)]}function hb(G,U){return[...Qu(G.name,U),...ed(G.command,U),...G.subcommand===void 0||typeof G.subcommand==="string"&&C.test(G.subcommand)?[]:[e([...U,"subcommand"],"must match command pattern")],...zi(G.block_args,[...U,"block_args"],"required non-empty array",!1),...td(G.reason,U),...nd(G.intent,U)]}function yb(G,U){return[...Qu(G.name,U),...ed(G.command,U),...td(G.reason,U),...nd(G.intent,U),...bb(G.match,[...U,"match"]),...G.subcommand===void 0?[]:[e([...U,"subcommand"],"not supported in rulebook_version 2")],...G.block_args===void 0?[]:[e([...U,"block_args"],"not supported in rulebook_version 2")]]}function Qu(G,U){if(typeof G!=="string")return[e([...U,"name"],"required string")];return d.test(G)?[]:[e([...U,"name"],"must match rule name pattern")]}function ed(G,U){return typeof G==="string"&&C.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function td(G,U){return typeof G==="string"&&G!==""&&G.length<=I?[]:[e([...U,"reason"],ub)]}function nd(G,U){return G===void 0||Te(G)?[]:[e([...U,"intent"],Re)]}function bb(G,U){if(!lr(G))return[e(U,"required object")];return[...zi(G.command_path,[...U,"command_path"],db,!1),...G.any_args===void 0?[]:zi(G.any_args,[...U,"any_args"],Ju,!0),...G.exclude_args===void 0?[]:zi(G.exclude_args,[...U,"exclude_args"],Ju,!0)]}function zi(G,U,j,K){if(!Array.isArray(G))return[e(U,j)];let re=G.flatMap((oe,de)=>{if(typeof oe!=="string")return[e([...U,de],"must be a non-empty string")];return oe===""?[tn([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[tn(U,j)]:[],...K&&new Set(G).size!==G.length?[tn(U,"must not contain duplicate values")]:[]]}function Cb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["tests"],"must be an array if provided")];return G.flatMap((U,j)=>{if(!lr(U))return[e(["tests",j],"must be an object")];return[...typeof U.command==="string"&&U.command.trim()!==""?[]:[e(["tests",j,"command"],"required non-empty string")],...U.expect==="blocked"||U.expect==="allowed"?[]:[e(["tests",j,"expect"],'must be "blocked" or "allowed"')],...U.rule===void 0||typeof U.rule==="string"?[]:[e(["tests",j,"rule"],"must be a string if provided")],...U.expect==="blocked"&&typeof U.rule!=="string"?[tn(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function Sb(G){if(!Array.isArray(G.tests))return[];let U=new Set(De(G));return[...new Set(G.tests.flatMap((j)=>lr(j)&&j.expect==="blocked"&&typeof j.rule==="string"?[j.rule]:[]))].filter((j)=>!U.has(j)).map((j)=>tn(["tests"],`blocked fixture references unknown rule "${j}"`))}function vb(G){if(!Array.isArray(G.allowed_commands)||!Array.isArray(G.rules))return[];let U=new Set(G.allowed_commands.filter((j)=>typeof j==="string"));return G.rules.flatMap((j,K)=>{let re=lr(j)?j.command:void 0;if(typeof re!=="string"||U.has(re))return[];return[tn(["rules",K,"command"],`"${re}" must be listed in allowed_commands`)]})}function lr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function Q(G,U){let j=X(G,U),K;try{K=Nu(j.userConfigTarget,j.projectConfigTarget)}catch(pt){if(pt instanceof o)return Ib(j,pt.message);throw pt}let re=m(j.userConfigTarget),oe=K?{config:null,errors:[]}:m(j.projectConfigTarget),de=od(j.userConfigPath,re.errors),Se=od(j.projectConfigPath,oe.errors),we=new Set,We=re.config?La(re.config,wr(j.userConfigPath),"user",j.userScope,we):id(),mt=oe.config?La(oe.config,wr(j.projectConfigPath),"project",j.projectScope,we):id(),gt=re.config?.overrides??{},ft=oe.config?.overrides??{};return{rules:[...rd(We.rules,gt),...rd(mt.rules,ft)],transparent_wrappers:Ab(re.config,oe.config),rulebooks:[...We.rulebooks,...mt.rulebooks],errors:[...de,...Se,...We.errors,...mt.errors],warnings:[...We.warnings,...mt.warnings,...We.canValidateOverrides?Wa(gt,We.knownRuleIds,j.userConfigPath):[],...We.canValidateOverrides?Tb(ft,We.knownRuleIds,j.projectConfigPath):[],...mt.canValidateOverrides?Wa(ft,mt.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=Eb(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...Rb(j.config,j.scope,G)]}function Eb(G,U){let j=U??S(wr(wr(G)),"rules policy"),K=m(i(j,G)).config;if(!K)return null;return{config:K,scope:La(K,wr(G),"project",j)}}function Rb(G,U,j){return U.canValidateOverrides?Wa(G.overrides??{},U.knownRuleIds,j):[]}function La(G,U,j,K=S(wr(wr(U)),j==="user"?"user policy":"project policy"),re=new Set){let oe=[],de=[],Se=G.rules.flatMap((We)=>{let mt=_b(We,U,K);if(mt.errors.length>0||!mt.rulebook)return oe.push(...mt.errors),[];let gt=mt.rulebook;if(re.has(gt.name))return de.push(`duplicate active rulebook name "${gt.name}" for ${We}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return re.add(gt.name),[{rules:xb(gt),rulebook:{source:j,spec:We,name:gt.name,version:gt.version,rules:gt.rules.map((ft)=>`${gt.name}/${ft.name}`)}}]}),we=Se.flatMap((We)=>We.rules);return{rules:we,rulebooks:Se.map((We)=>We.rulebook),knownRuleIds:new Set(we.map((We)=>We.name)),errors:oe,warnings:de,canValidateOverrides:oe.length===0}}function xb(G){if(G.rulebook_version===2)return G.rules.map((U)=>({name:`${G.name}/${U.name}`,command:U.command,block_args:[],match:U.match,reason:U.reason,intent:U.intent}));return G.rules.map((U)=>({...U,name:`${G.name}/${U.name}`,match:void 0}))}function _b(G,U,j){let K=Ne(G),re=M(U,K),oe=Pb(re,j);if("error"in oe)return{rulebook:null,errors:[oe.error]};if(oe.content===null)return{rulebook:null,errors:[`missing rulebook file ${re} for ${G}; ${wb(G)}`]};let de=xe(oe.content);if("problem"in de)return{rulebook:null,errors:[`invalid rulebook ${re}: ${de.problem}; fix that file`]};if(de.rulebook.name!==K)return{rulebook:null,errors:[`rulebook name "${de.rulebook.name}" in ${re} must match source "${G}"; fix that file`]};return{rulebook:de.rulebook,errors:[]}}function Ne(G){return w(G)?N(G).name:G}function wb(G){return w(G)?`run ${ju} to vendor ${G}`:"create that file or remove that source from the rules config"}function Pb(G,U){try{return{content:r(i(U,G))}}catch(j){if(j instanceof o)return{error:j.message};throw j}}function xe(G){let U;try{U=JSON.parse(G)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:le(U)}}catch(j){return{problem:j instanceof Error?j.message:"invalid rulebook"}}}function Ab(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function rd(G,U){return G.flatMap((j)=>{let K=U[j.name];if(K==="off")return[];if(K&&typeof K==="object")return[{...j,intent:K.intent??j.intent,reason:K.reason}];return[j]})}function Wa(G,U,j){return Object.keys(G).filter((K)=>!U.has(K)).map((K)=>`unknown override key "${K}" in ${j}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Tb(G,U,j){return Object.keys(G).filter((K)=>U.has(K)).map((K)=>`project override cannot target user-scoped rule "${K}" in ${j}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function od(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function Ib(G,U){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function id(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as $b,readFileSync as Bb}from"node:fs";var sd=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Fa=new Set(sd.map((G)=>G.id)),z=sd,kb=new Map(z.map((G)=>[G.id,G.intent]));function _t(G,U){return{id:G,reason:U,intent:kb.get(G)??"manual_only"}}var Ga=[{id:"secret.basename.env",category:"Basename",label:".env",description:"Blocks exact .env files.",basename:".env"},{id:"secret.basename.npmrc",category:"Basename",label:".npmrc",description:"Blocks npm credential config files.",basename:".npmrc"},{id:"secret.basename.pypirc",category:"Basename",label:".pypirc",description:"Blocks Python package index credential files.",basename:".pypirc"},{id:"secret.basename.netrc",category:"Basename",label:".netrc",description:"Blocks machine login credential files.",basename:".netrc"},{id:"secret.basename.git-credentials",category:"Basename",label:".git-credentials",description:"Blocks Git credential storage files.",basename:".git-credentials"},{id:"secret.basename.id-rsa",category:"Basename",label:"id_rsa",description:"Blocks RSA private key basenames.",basename:"id_rsa"},{id:"secret.basename.id-ed25519",category:"Basename",label:"id_ed25519",description:"Blocks Ed25519 private key basenames.",basename:"id_ed25519"},{id:"secret.basename.id-ecdsa",category:"Basename",label:"id_ecdsa",description:"Blocks ECDSA private key basenames.",basename:"id_ecdsa"},{id:"secret.basename.credentials",category:"Basename",label:"credentials",description:"Blocks generic credentials file basenames.",basename:"credentials"}],$i={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Ob=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Mb=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],za=[{id:"secret.home.ssh",category:"Home path",label:"~/.ssh",description:"Blocks home SSH configuration and key paths.",suffixParts:[".ssh"]},{id:"secret.home.aws",category:"Home path",label:"~/.aws",description:"Blocks home AWS credential and config paths.",suffixParts:[".aws"]},{id:"secret.home.gcp",category:"Home path",label:"~/.gcp",description:"Blocks home GCP credential paths.",suffixParts:[".gcp"]},{id:"secret.home.gcloud-config",category:"Home path",label:"~/.config/gcloud",description:"Blocks home Google Cloud SDK credential paths.",suffixParts:[".config","gcloud"]},{id:"secret.home.kube-config",category:"Home path",label:"~/.kube/config",description:"Blocks home Kubernetes config files.",suffixParts:[".kube","config"]},{id:"secret.home.docker-config",category:"Home path",label:"~/.docker/config.json",description:"Blocks home Docker credential config files.",suffixParts:[".docker","config.json"]},...Mb.flatMap((G)=>Ob.map((U)=>({id:["secret.home",G.idSlug,U.slice(1)].join("."),category:"Home path",label:[G.label,U].join(""),description:["Blocks home ",G.label,U," credential backup files."].join(""),suffixParts:[...G.directoryParts,[G.basename,U].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Bi=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],ad=[{prefix:"id_rsa",slug:"id-rsa",label:"id_rsa"},{prefix:"id_dsa",slug:"id-dsa",label:"id_dsa"},{prefix:"id_ed25519",slug:"id-ed25519",label:"id_ed25519"},{prefix:"id_ecdsa",slug:"id-ecdsa",label:"id_ecdsa"},{prefix:"credentials",slug:"credentials",label:"credentials"}],Db=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],$a=ad.map((G)=>({id:`secret.variant.${G.slug}.separator`,category:"Variant",label:`${G.label}-* / ${G.label}_*`,description:`Blocks ${G.label} variants with dash or underscore suffixes.`,prefix:G.prefix})),Ba=ad.flatMap((G)=>Db.map((U)=>({id:`secret.variant.${G.slug}.${U.slice(1)}`,category:"Variant",label:`${G.label}${U}`,description:`Blocks ${G.label}${U} private credential variants.`,prefix:G.prefix,suffix:U}))),Bo={id:"secret.pattern.ssh-key-basename",category:"Pattern",label:"*_(rsa|dsa|ed25519|ecdsa)",description:"Blocks extensionless SSH private key-like basenames.",pattern:/^.*_(rsa|dsa|ed25519|ecdsa)$/},Ua=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((G)=>({id:`secret.ext.${G}`,category:"Extension",label:`.${G}`,description:`Blocks files with the .${G} extension.`,extension:G})),Ha=[{id:"secret.ext-pattern.key",category:"Extension pattern",label:".key / .keypair",description:"Blocks key and keypair extension patterns.",pattern:/^key(pair)?$/},{id:"secret.ext-pattern.keystore",category:"Extension pattern",label:".keystore / .keyring",description:"Blocks keystore and keyring extension patterns.",pattern:/^key(store|ring)$/},{id:"secret.ext-pattern.kdbx",category:"Extension pattern",label:".kdb / .kdbx",description:"Blocks KeePass database extension patterns.",pattern:/^kdbx?$/}],Qe=[...Ga,$i,...za,...$a,...Ba,Bo,...Ua,...Ha,...Bi].map((G)=>({id:G.id,category:G.category,label:G.label,...G.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in G?{paths:G.paths}:{description:G.description}})),Ui=new Set(Bi.flatMap((G)=>G.category==="Coding CLI config"?[G.id]:[])),ja=new Set(Qe.map((G)=>G.id));import{isAbsolute as Va,join as Nb,normalize as Lb,sep as Hi}from"node:path";var ji=process.platform==="win32",ld=/[*?]/;function qa(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ji?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(ld.test(K)||re==="."||re==="..")return null;return{root:K||"/",name:re}}function Uo(G,U){if(G==="~")return U;if(G.startsWith("~/"))return`${U}${G.slice(1)}`;return G}function Ka(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Uo(G.trim(),U);if(!Va(j))return"must be an absolute path or start with ~/";return Ho(j,U)}function Ya(G,U){let j=cd(G,U);if(j===null)return"must be a non-empty path string";if(!Va(j))return null;if(Ho(j,U)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var Wb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Fb="cannot cover the guard's own configuration";function cd(G,U){if(typeof G!=="string"||G.trim()==="")return null;let j=G.trim(),K=ji?j.replaceAll("\\","/"):j;return Uo(K.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),U)}function Za(G,U){let j=cd(G,U);if(j===null)return"must be a non-empty path string";let K=qa(j)?.root??j;if(ld.test(K))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Va(K))return null;if(Ho(K,U)!==null)return Wb;return Gb(K,U)?Fb:null}function Gb(G,U){let j=Vi(G),K=Vi(Nb(U,".cc-safety-net"));return j===K||j.startsWith(`${K}${Hi}`)}function Ho(G,U){let j=Vi(G),K=Vi(U);if(j===K)return"cannot be the home directory";let re=j.endsWith(Hi)?j:`${j}${Hi}`;if(K.startsWith(re))return"cannot contain the home directory";return null}function Vi(G){let U=Lb(G);if(ji)U=U.replace(/\//g,"\\").toLowerCase();if(U.length>(ji?3:1)&&U.endsWith(Hi))U=U.slice(0,-1);return U}var ud=30,qi=1,Ki=365;function dd(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var md=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function Tt(G,U){if(!G)return null;if(md.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function Xt(G,U,j){if(md.has(U))return!0;if(G?.destructiveCommandProtectionEnabled===!1)return!1;return G?.effectiveDestructiveCommandRules[U]?.enabled??j}function q(G,U){return Object.freeze(Object.fromEntries(z.map((j)=>{let K=j.activationCapability?U[j.activationCapability]:void 0,re=K?.enabled??!0,oe=G.destructiveCommandRuleOverrides[j.id],de=j.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...oe?{override:oe}:{}}:G.destructiveCommandProtectionEnabled?oe?{enabled:oe==="on",inheritedEnabled:re,changesInherited:oe==="on"!==re,source:"rule_override",...j.activationCapability?{activationCapability:j.activationCapability}:{},override:oe}:{enabled:re,inheritedEnabled:re,changesInherited:!1,source:K?.source??"built_in_default",...j.activationCapability?{activationCapability:j.activationCapability}:{}}:{enabled:!1,inheritedEnabled:re,changesInherited:!1,source:"master_disabled",...j.activationCapability?{activationCapability:j.activationCapability}:{},...oe?{override:oe}:{}};return[j.id,Object.freeze(de)]})))}function fd(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:q(G,U)})}var pd={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=zb(G,U,K),oe=new Set(j?re.map((mt)=>mt.field):[]),de=(mt,gt)=>oe.has(mt)?void 0:gt,Se=(mt,gt)=>Object.fromEntries(Object.entries(gt??{}).filter(([ft])=>!oe.has(`${mt}.${ft}`))),we=(mt,gt)=>gt?.filter((ft)=>!oe.has(`${mt}.${ft}`));return{policy:{version:1,safety:{level:de("safety.level",U.safety?.level)??G.safety.level,overrides:{...G.safety.overrides,...Se("safety.overrides",U.safety?.overrides)}},workflow:{worktree_mode:de("workflow.worktree_mode",U.workflow?.worktree_mode)??G.workflow.worktree_mode},destructive_command_protection:{enabled:de("destructive_command_protection.enabled",U.destructive_command_protection?.enabled)??G.destructive_command_protection.enabled,overrides:{...G.destructive_command_protection.overrides,...Se("destructive_command_protection.overrides",U.destructive_command_protection?.overrides)},allow_paths:Xa(G.destructive_command_protection.allow_paths,we("destructive_command_protection.allow_paths",U.destructive_command_protection?.allow_paths))},secret_protection:{enabled:de("secret_protection.enabled",U.secret_protection?.enabled)??G.secret_protection.enabled,overrides:{...G.secret_protection.overrides,...Se("secret_protection.overrides",U.secret_protection?.overrides)},deny_paths:Xa(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:Xa(G.secret_protection.allow_paths,we("secret_protection.allow_paths",U.secret_protection?.allow_paths))},audit:G.audit},weakenings:re.map((mt)=>mt.message)}}function Xa(G,U){return[...new Set([...G,...U??[]])]}function zb(G,U,j){let K=U.safety?.level,re=ki[j];return[...K&&pd[K]<pd[G.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${G.safety.level} -> ${K}`}]:[],...Zr.flatMap((oe)=>U.safety?.overrides?.[oe]===!1&&(G.safety.overrides[oe]??re[oe])?[{field:`safety.overrides.${oe}`,message:`project policy disables ${oe}`}]:[]),...U.workflow?.worktree_mode===!0&&!G.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...U.destructive_command_protection?.enabled===!1&&G.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...U.secret_protection?.enabled===!1&&G.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...gd("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...gd("secret_protection.overrides",U.secret_protection?.overrides,(oe)=>G.secret_protection.enabled&&(G.secret_protection.overrides[oe]==="on"?!0:G.secret_protection.overrides[oe]!=="off"&&!Ui.has(oe))),...G.destructive_command_protection.enabled?hd(G.destructive_command_protection.allow_paths,U.destructive_command_protection?.allow_paths).map((oe)=>({field:`destructive_command_protection.allow_paths.${oe}`,message:`project policy adds destructive allow path: ${oe}`})):[],...G.secret_protection.enabled?hd(G.secret_protection.allow_paths,U.secret_protection?.allow_paths).map((oe)=>({field:`secret_protection.allow_paths.${oe}`,message:`project policy adds secret allow path: ${oe}`})):[]]}function gd(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function hd(G,U){return(U??[]).filter((j)=>!G.includes(j))}var el=new Set(["standard","strict","paranoid"]),te={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:ud}};function Sd(G,U){let j=Kb(l(G,U),G.home),K=L(G,U)?{exists:!1,policy:F(),errors:[]}:Me(h(U.cwd),G.home),re=ue(K.parsed,G.home),oe=v(n.projectTightenOnly,G.env),de=j.gui??te,Se=Object.keys(re.policy).length>0?ee(de,re.policy,oe,Tu(de.safety.level,G.env)):void 0,we=[...j.errors,...K.errors,...re.diagnostics],We=(j.fallback==="defaults"&&Se?"salvaged":j.fallback)??(j.gui?void 0:K.fallback)??(we.length>0?"salvaged":void 0),mt=re.policy.safety?.level&&Se?.policy.safety.level===re.policy.safety.level?"project":j.levelPresent?"user":"default";return{...Se?Qa(Se.policy):j.policy,errors:we,...We?{fallback:We}:{},...K.exists?{policyScopes:{levelScope:mt,weakenings:Se?.weakenings??[],weakeningsIgnored:oe}}:{}}}var Ub="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!En(G))return{policy:{},diagnostics:[]};let j=En(G.safety)?G.safety:{},K=En(G.workflow)?G.workflow:{},re=En(G.destructive_command_protection)?G.destructive_command_protection:{},oe=En(G.secret_protection)?G.secret_protection:{},de={...el.has(j.level)?{level:j.level}:{},...En(j.overrides)?yd({overrides:vd(j.overrides,Zr,["safety","overrides"],Pr)}):{}},Se={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Yi(re.overrides,Fa,Rd,Pr)}:{},...re.allow_paths!==void 0?{allow_paths:eo(re.allow_paths,Ka,U,["destructive_command_protection","allow_paths"],Pr)}:{}},we={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Yi(oe.overrides,ja,xd,Pr)}:{},...oe.deny_paths!==void 0?{deny_paths:eo(oe.deny_paths,Ya,U,["secret_protection","deny_paths"],Pr)}:{},...oe.allow_paths!==void 0?{allow_paths:eo(oe.allow_paths,Za,U,["secret_protection","allow_paths"],Pr)}:{}};return{policy:yd({safety:de,workflow:typeof K.worktree_mode==="boolean"?{worktree_mode:K.worktree_mode}:{},destructive_command_protection:Se,secret_protection:we}),diagnostics:G.audit===void 0?[]:[Ub]}}function vd(G,U,j,K){return Object.fromEntries(U.flatMap((re)=>{let oe=G[re];if(typeof oe==="boolean")return[[re,oe]];if(oe!==void 0)K(e([...j,re],tl));return[]}))}function yd(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var Pr=()=>{return},tl="must be a boolean",nl="must be an object if provided",Ed=`must be an integer between ${qi} and ${Ki}`,Rd={path:["destructive_command_protection","overrides"],label:"destructive command"},xd={path:["secret_protection","overrides"],label:"secret protection"},et=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function tt(G,U){let j=[];return{policy:_d(G,U,(re)=>{j.push(re)}),issues:j}}function E(G,U){return _d(G,U,Pr)}function _d(G,U,j){if(!En(G))return j(e([],"Config must be an object")),F();if(G.version!==1)j(e(["version"],"must be 1"));let K=Qr(G.safety,["safety"],["level","overrides"],j),re=Qr(K.overrides,["safety","overrides"],Zr,j),oe=Qr(G.workflow,["workflow"],["worktree_mode"],j),de=Qr(G.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],j),Se=Qr(G.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],j),we=Qr(G.audit,["audit"],["retention_days"],j);return wd(G,et,[],j),{version:1,safety:{level:Hb(K.level,j),overrides:vd(re,Zr,["safety","overrides"],j)},workflow:{worktree_mode:Ja(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:Ja(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Yi(de.overrides,Fa,Rd,j),allow_paths:eo(de.allow_paths,Ka,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:Ja(Se.enabled,["secret_protection","enabled"],!0,j),overrides:Yi(Se.overrides,ja,xd,j),deny_paths:eo(Se.deny_paths,Ya,U,["secret_protection","deny_paths"],j),allow_paths:eo(Se.allow_paths,Za,U,["secret_protection","allow_paths"],j)},audit:{retention_days:jb(we.retention_days,j)}}}function Qr(G,U,j,K){if(G===void 0)return{};if(!En(G))return K(e(U,nl)),{};return wd(G,j,U,K),G}function wd(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function Hb(G,U){if(G===void 0)return"standard";if(el.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Ja(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,tl));return j}function jb(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=qi&&G<=Ki))U(e(["audit","retention_days"],Ed));return dd(G)}function Yi(G,U,j,K){if(G===void 0)return{};if(!En(G))return K(e(j.path,nl)),{};return Object.fromEntries(Object.entries(G).flatMap(([re,oe])=>{if(!U.has(re))return K({path:[...j.path,re],message:`unknown ${j.label} rule id "${re}"`,kind:"key"}),[];if(oe==="on"||oe==="off")return[[re,oe]];return K(e([...j.path,re],'must be "on" or "off"')),[]}))}function eo(G,U,j,K,re){if(G===void 0)return[];if(!Array.isArray(G))return re(e(K,"must be an array of paths")),[];return G.flatMap((oe,de)=>{let Se=U(oe,j);if(Se===null)return[oe];return re(typeof oe==="string"?tn([...K,de],Se):e([...K,de],Se)),[]})}function En(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function F(){return structuredClone(te)}function Le(G,U){let j=T({safety:$e(G.safety)},U),K=q({destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides},j.capabilities),re=Object.values(K),oe=re.filter((de)=>de.source!=="catastrophic");return{selectedPreset:G.safety.level,effectiveLevel:j.effectiveLevel,capabilities:j.capabilities,rules:K,counts:{enabled:oe.filter((de)=>de.enabled).length,disabled:oe.filter((de)=>!de.enabled).length,effectiveCustomizations:re.filter((de)=>de.changesInherited).length}}}function Me(G,U){if(!$b(G))return{exists:!1,policy:F(),errors:[]};try{let j=Bb(G,"utf-8");if(!j.trim())return{exists:!0,policy:F(),errors:[`${G}: Config file is empty`],fallback:"defaults"};let K=JSON.parse(j),re=tt(K,U);if(re.issues.length===0)return{exists:!0,parsed:K,policy:re.policy,errors:[]};return{exists:!0,parsed:K,policy:re.policy,errors:re.issues.map((oe)=>`${G}: ${qb(oe)}`),fallback:En(K)?"salvaged":"defaults"}}catch(j){let K=j instanceof Error?j.message:String(j);return{exists:!0,policy:F(),errors:[`${G}: ${j instanceof SyntaxError?"Invalid JSON":K}`],fallback:"defaults"}}}var Vb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[nl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[tl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Ed,`not an integer between ${qi} and ${Ki}`]]);function qb(G){let U=Na(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=Vb.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function Kb(G,U){let j=Me(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!En(K))return{policy:Cd(),errors:[]};let re=E(K,U);return{policy:Qa(re),gui:re,errors:[],levelPresent:bd(K)}}if(j.parsed===void 0)return{policy:Cd(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:Qa(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:bd(j.parsed)}}function bd(G){let U=En(G)&&En(G.safety)?G.safety:{};return el.has(U.level)}function Fe(G){let U=Object.entries(G),j=new Set(U.flatMap(([K,re])=>re==="on"?[K]:[]));return[...new Set([...[...Ui].filter((K)=>!j.has(K)),...U.flatMap(([K,re])=>re==="off"?[K]:[])])]}function Cd(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function Qa(G){return{safety:$e(G.safety),worktreeMode:G.workflow.worktree_mode,destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides,destructiveCommandAllowPaths:G.destructive_command_protection.allow_paths,secretProtection:{enabled:G.secret_protection.enabled,disabledRules:Fe(G.secret_protection.overrides),denyPaths:G.secret_protection.deny_paths,allowPaths:G.secret_protection.allow_paths}}}function $e(G){let U={...G.overrides.fail_closed!==void 0?{failClosed:G.overrides.fail_closed}:{},...G.overrides.paranoid_rm!==void 0?{paranoidRm:G.overrides.paranoid_rm}:{},...G.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:G.overrides.paranoid_interpreters}:{}};return{level:G.level,...Object.keys(U).length>0?{overrides:U}:{}}}function k(G,U){let j=Q(G,U),K=Sd(G,U),re={rules:j.rules,transparentWrappers:j.transparent_wrappers,safety:K.safety,worktreeMode:K.worktreeMode,destructiveCommandProtectionEnabled:K.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:K.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:K.destructiveCommandAllowPaths,secretProtection:{enabled:K.secretProtection.enabled??!0,disabledRules:K.secretProtection.disabledRules??[],denyPaths:K.secretProtection.denyPaths,allowPaths:K.secretProtection.allowPaths??[]}},oe={...j.userConfig?.overrides,...j.projectConfig?.overrides},de=Object.freeze(Object.fromEntries(re.rules.map((Se)=>{let we=j.rulebooks.find((mt)=>mt.rules.includes(Se.name)),We=oe[Se.name];return[Se.name,Object.freeze({id:Se.name,...we?{rulebook:Object.freeze({name:we.name,version:we.version}),...Jb(we.spec)?{source:we.spec}:{}}:{},...We&&typeof We==="object"?{override:Object.freeze({type:"reason",reason:We.reason})}:{}})]})));return _e(re,Yb(j,K),de,K.policyScopes)}function je(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function Yb(G,U){let j=Xb(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:Qb(G.errors.length>0?Zb(G.errors):void 0,G.warnings.length>0?ol(G.warnings.join("; ")):void 0,j)}}function Zb(G){return`${ol(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Xb(G){if(G.errors.length===0)return;let U=G.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${G.errors.join("; ")}. Enforcing ${U}; the invalid values are not active. Fix the policy file manually`}function Jb(G){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(G)}function _e(G,U,j=Object.freeze({}),K){let re=rl(structuredClone(G)),oe=K?{policyScopes:rl(structuredClone(K))}:{};if(!U)return Object.freeze({state:"ready",policy:re,diagnostics:Object.freeze([]),ruleMetadata:j,...oe});return Object.freeze({state:"degraded",policy:re,diagnostics:Object.freeze([...U.diagnostics]),reason:U.reason,ruleMetadata:j,...oe})}function rl(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))rl(U);return Object.freeze(G)}function Qb(...G){return ol(G.filter((U)=>!!U).join("; "))}function ol(G){return/[.!?]$/.test(G)?G:`${G}.`}function Ue(G){let U=G.effectiveCapabilities,j=G.strict??U.fail_closed.enabled,K=G.paranoidRm??U.paranoid_rm.enabled,re=G.paranoidInterpreters??U.paranoid_interpreters.enabled,oe={fail_closed:il(U.fail_closed,G.strict,"strict"),paranoid_rm:il(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:il(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:fd(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Ea({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function il(G,U,j){if(U===void 0||U===G.enabled)return G;return{enabled:U,source:"capability_override",sources:[...G.sources,`analysis options.${j}`]}}import{dirname as zw,isAbsolute as $w,join as Bw,parse as Uw,resolve as Hw,sep as jw}from"node:path";function jo(G,U){if(G!=="powershell")return U[0]?.provenance==="command-substitution";let j=U[0]?.text==="&"||U[0]?.text==="."?1:0,K=U[j]?.provenance;return K!==void 0&&K!=="literal"}var eC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Zi(G,U){return G?.provenance==="literal"&&!G.quoted&&G.raw===U&&G.text===U}function Vo(G){let U=Zi(G.words[0],"time")?1:0,j=U===1&&Zi(G.words[U],"-p")?U+1:U,K=U===1&&Zi(G.words[j],"--")?j+1:j,re=Zi(G.words[K],"!")?K+1:K,oe=G.words.slice(re).find((de)=>!eC.test(de.text));return oe?.provenance==="literal"?oe.text:void 0}var cr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Xi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function tC(G){return Object.freeze({...G,span:Object.freeze(G.span),words:Object.freeze(G.words),redirections:Object.freeze(G.redirections.map((U)=>Object.freeze({...U,span:Object.freeze(U.span),...U.heredoc?{heredoc:Object.freeze({...U.heredoc,bodySpan:Object.freeze(U.heredoc.bodySpan),terminatorSpan:Object.freeze(U.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(G.nested.map((U)=>mn(U)))})}function Ji(G,U,j){G.push(j),U.reset()}function Qi(G){let U=[];return{parts:U,push:(j,K,re)=>{if(K<=j)return;U.push({raw:G.slice(j,K),span:{start:j,end:K},provenance:re})}}}function sl(G){let U=G.parts??[{raw:G.raw,span:G.span,provenance:G.provenance}];return Object.freeze({kind:"word",...G,span:Object.freeze(G.span),parts:Object.freeze(U.map((j)=>Object.freeze({...j,span:Object.freeze(j.span)})))})}function to(G,U,j,K,re,oe,de){return sl({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function mn(G){return Object.freeze({...G,span:Object.freeze(G.span),issues:Object.freeze(G.issues.map((U)=>Object.freeze({...U}))),nodes:Object.freeze(G.nodes.map((U)=>{if(U.kind==="command")return tC(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:mn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function al(G,U,j){if(U>=j||Ad(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Ad(G[de]??"")){let Se=G[de]??"";if(Se==="'"){re=!0;let we=Pd(G,de+1,j,"'");K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==='"'){re=!0;let we=Pd(G,de+1,j,'"');K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==="\\"){re=!0;let we=G[de+1];if(!we||we===`
5
+ `,r:"\r",t:"\t",v:"\v"}[G]??G}function uy(G){return Wo(fy(G))}function Sa(G,U){if(G==="/dev/null")return mu(U);if(U==="/dev/null")return mu(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(Wo);let j=dy(G,U)??(G===U?xu(G):null);return[G,U,...j?[j]:[]].flatMap(Wo)}function mu(G){let U=xu(G);return[G,...U?[U]:[]].flatMap(Wo)}function xu(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function dy(G,U){let j=G.indexOf("/"),K=U.indexOf("/");if(j<1||K<1)return null;if(G.slice(0,j)===U.slice(0,K))return null;let re=G.slice(j+1);return re===U.slice(K+1)?re:null}function fu(G){return uy(Ti(G,!0))}function my(G){return Wo(Ti(G,!1))}function Ti(G,U){let j=G.trim(),K=j[0]==='"'||j[0]==="'"?j[0]:void 0;if(K){let re=Ru(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function fy(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function Wo(G){return G===""||G==="/dev/null"?[]:[G]}function pu(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!gy(G).isDirectory())return!1;return py(G,_u.R_OK|_u.X_OK),!0}catch{return!1}}function it(G,U,j){if(sr(G))return;let K=U.flatMap((oe)=>va(oe,j));if(!K[0])return;let re=va(wu(G)?G:yy(K[0],G),j)[0];if(!re)return;return K.some((oe)=>Cy(re,oe))?re:void 0}function qe(G,U){return G.flatMap((j)=>va(j,U))[0]}function va(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function Cy(G,U){let j=hy(U,G);return j===""||j!==".."&&!j.startsWith(`..${by}`)&&!wu(j)}var Sy=8388608;async function Ke(G){let U=[],j=0;for await(let K of G){let re=typeof K==="string"?Buffer.from(K,"utf-8"):Buffer.from(K.buffer,K.byteOffset,K.byteLength);if(j+=re.byteLength,j>Sy)throw vy(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function vy(G){let U=G.destroy??G.cancel;if(!U)return;try{Promise.resolve(U.call(G)).catch(()=>{})}catch{}}function u(G,U,j,K,re){if(j.kind!=="command")return{toolName:G,input:U,route:j,context:K};return{toolName:G,input:U,route:j,context:K,command:re}}var Zr=["fail_closed","paranoid_rm","paranoid_interpreters"],ki={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var n={level:{name:"CC_SAFETY_NET_LEVEL"},strict:{name:"CC_SAFETY_NET_STRICT",legacyName:"SAFETY_NET_STRICT"},paranoid:{name:"CC_SAFETY_NET_PARANOID",legacyName:"SAFETY_NET_PARANOID"},paranoidRm:{name:"CC_SAFETY_NET_PARANOID_RM",legacyName:"SAFETY_NET_PARANOID_RM"},paranoidInterpreters:{name:"CC_SAFETY_NET_PARANOID_INTERPRETERS",legacyName:"SAFETY_NET_PARANOID_INTERPRETERS"},worktree:{name:"CC_SAFETY_NET_WORKTREE",legacyName:"SAFETY_NET_WORKTREE"},debug:{name:"CC_SAFETY_NET_DEBUG"},auditScope:{name:"CC_SAFETY_NET_AUDIT_SCOPE"},projectTightenOnly:{name:"CC_SAFETY_NET_PROJECT_TIGHTEN_ONLY"}},Oi=["standard","strict","paranoid"];function Pu(G,U){if(!U)return G;return Oi.indexOf(U)>Oi.indexOf(G)?U:G}function Au(G){let U=pe(n.level,G);return Oi.find((j)=>j===U)}function Tu(G,U){return Pu(G,Au(U))}function Ey(G){let U=pe(n.level,G);if(!U)return;let j=Au(G);if(j)return j;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(U.slice(0,40))}. Use ${Oi.join(", ")}.`);return}function Ve(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Ee(G){return Ve(pe(n.auditScope,G))==="all"}function Ea(G){if(G.failClosed&&G.paranoidRm&&G.paranoidInterpreters)return"paranoid";if(G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"strict";if(!G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"standard";return"custom"}function T(G={},U){let j=G.safety?.level??"standard",K=Ey(U),re=Pu(j,K),oe=ki[re],de={failClosed:oe.fail_closed,paranoidRm:oe.paranoid_rm,paranoidInterpreters:oe.paranoid_interpreters},Se={failClosed:re===j?"preset":"environment",paranoidRm:re===j?"preset":"environment",paranoidInterpreters:re===j?"preset":"environment"},we={failClosed:[`policy safety.level=${j}`],paranoidRm:[`policy safety.level=${j}`],paranoidInterpreters:[`policy safety.level=${j}`]};if(re!==j)we.failClosed.push(`env ${n.level.name}=${K}`),we.paranoidRm.push(`env ${n.level.name}=${K}`),we.paranoidInterpreters.push(`env ${n.level.name}=${K}`);if(G.safety?.overrides?.failClosed!==void 0)de.failClosed=G.safety.overrides.failClosed,Se.failClosed="capability_override",we.failClosed.push("policy safety.overrides.fail_closed");if(G.safety?.overrides?.paranoidRm!==void 0)de.paranoidRm=G.safety.overrides.paranoidRm,Se.paranoidRm="capability_override",we.paranoidRm.push("policy safety.overrides.paranoid_rm");if(G.safety?.overrides?.paranoidInterpreters!==void 0)de.paranoidInterpreters=G.safety.overrides.paranoidInterpreters,Se.paranoidInterpreters="capability_override",we.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(v(n.strict,U))de.failClosed=!0,Se.failClosed="environment",we.failClosed.push(`env ${n.strict.name}`);if(v(n.paranoid,U))de.paranoidRm=!0,de.paranoidInterpreters=!0,Se.paranoidRm="environment",Se.paranoidInterpreters="environment",we.paranoidRm.push(`env ${n.paranoid.name}`),we.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(v(n.paranoidRm,U))de.paranoidRm=!0,Se.paranoidRm="environment",we.paranoidRm.push(`env ${n.paranoidRm.name}`);if(v(n.paranoidInterpreters,U))de.paranoidInterpreters=!0,Se.paranoidInterpreters="environment",we.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let We=!!G.worktreeMode||v(n.worktree,U);return{strict:de.failClosed,paranoidRm:de.paranoidRm,paranoidInterpreters:de.paranoidInterpreters,worktreeMode:We,effectiveLevel:Ea(de),capabilities:{fail_closed:{enabled:de.failClosed,source:Se.failClosed,sources:we.failClosed},paranoid_rm:{enabled:de.paranoidRm,source:Se.paranoidRm,sources:we.paranoidRm},paranoid_interpreters:{enabled:de.paranoidInterpreters,source:Se.paranoidInterpreters,sources:we.paranoidInterpreters}}}}function v(G,U){let j=typeof G==="string"?Fo(G,U):pe(G,U);return j==="1"||j?.toLowerCase()==="true"}function Fo(G,U){return U.get(G)}function pe(G,U){let j=Fo(G.name,U);if(j!==void 0)return j;if(G.legacyName)return Fo(G.legacyName,U);return}function ot(G,U){return Fo(G.name,U)!==void 0||!!G.legacyName&&Fo(G.legacyName,U)!==void 0}import{dirname as wr}from"node:path";import{closeSync as Ry,constants as Go,fstatSync as Ra,fsyncSync as xy,lstatSync as An,mkdirSync as Iu,openSync as ku,readdirSync as _a,readFileSync as _y,realpathSync as Xr,renameSync as wy,rmdirSync as Ou,statSync as xa,unlinkSync as wa,writeFileSync as Py}from"node:fs";import{isAbsolute as Mu,join as Rr,normalize as Ay,parse as Mi,relative as Pa,resolve as Aa,sep as Di}from"node:path";function Ie(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var Ty=Symbol("PolicyFilesystemScope"),Iy=Symbol("PolicyFilesystemTarget"),Du=Go.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function S(G,U){return{[Ty]:!0,root:Aa(G),label:U}}function zo(G,U){let j=Ay(U);if(U===""||Mu(U)||j===".."||j.startsWith(`..${Di}`))throw new o(G.label);return{[Iy]:!0,scope:G,relativePath:j,path:Rr(G.root,j)}}function i(G,U){return zo(G,Pa(G.root,Aa(U)))}function se(G,U="rules policy"){let j=Aa(G),K=Mi(j).dir;return zo(S(K,U),Pa(K,j))}function r(G){return Zn(G.scope.label,()=>{if(!en(G))return null;let U=ku(G.path,Go.O_RDONLY|Du);return Lu(U,()=>{let j=Ra(U);if(!j.isFile())throw new o(G.scope.label);let K=_y(U,"utf-8"),re=An(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return en(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ie()}.tmp`;Zn(G.scope.label,()=>{Oy(G),en(G);let oe=ku(re,Go.O_CREAT|Go.O_EXCL|Go.O_WRONLY|Du,j),de=Lu(oe,()=>{let Se=Ra(oe);if(!Se.isFile())throw new o(G.scope.label);Py(oe,U,"utf-8"),xy(oe);let we=Ra(oe);if(!we.isFile()||we.dev!==Se.dev||we.ino!==Se.ino)throw new o(G.scope.label);return we});en(G),Dy(G,re,de.dev,de.ino),wy(re,G.path),K?.(G.path),en(G)},()=>Ny(re))}function Nu(G,U){if(G.path===U.path)return!0;return Zn(G.scope.label,()=>{if(!en(G)||!en(U))return!1;let j=(K)=>Rr(Xr(Mi(K).dir),Mi(K).base);return j(G.path)===j(U.path)})}function me(G){let U=Zn(G.scope.label,()=>{if(!en(G,"directory"))return null;let j=_a(G.path);return en(G,"directory"),j});if(!U)return null;return Zn(G.scope.label,()=>{let j=U.map((K)=>{let re=zo(G.scope,Rr(G.relativePath,K)),oe=An(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Ni(Ta(G.scope),Xr(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return en(G,"directory"),j})}function H(G){Zn(G.scope.label,()=>{if(!en(G))return;wa(G.path),en(G)})}function st(G){Zn(G.scope.label,()=>{if(!ky(G))return;Fu(G),en(G,"directory")})}function at(G){Zn(G.scope.label,()=>{if(!en(G,"directory"))return;Ou(G.path),en(G,"directory")})}function ky(G){return Zn(G.scope.label,()=>{if(!en(G,"directory"))return!1;return Wu(G),!0})}function Zn(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Lu(G,U){try{return U()}finally{Ry(G)}}function en(G,U="file"){let j=Gu(G.scope);if(!j)return!1;let K=G.relativePath.split(Di);for(let re of K.keys()){let oe=Rr(G.scope.root,...K.slice(0,re+1)),de=An(oe,{throwIfNoEntry:!1});if(!de)return!1;if(de.isSymbolicLink())throw new o(G.scope.label);if(re<K.length-1&&!de.isDirectory())throw new o(G.scope.label);if(re===K.length-1&&(U==="file"?!de.isFile():!de.isDirectory()))throw new o(G.scope.label);Ni(j,Xr(oe),G.scope.label)}return!0}function Wu(G){for(let U of _a(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=An(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Wu(j)}en(G,"directory")}function Fu(G){for(let U of _a(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=An(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Fu(j);continue}if(!K.isFile())throw new o(G.scope.label);wa(j.path)}Ou(G.path)}function Oy(G){My(G.scope);let U=Ta(G.scope),j=G.relativePath.split(Di).slice(0,-1);for(let K of j.keys()){let re=Rr(G.scope.root,...j.slice(0,K+1));if(!An(re,{throwIfNoEntry:!1}))Iu(re,{mode:448});let oe=An(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Ni(U,Xr(re),G.scope.label)}}function My(G){if(An(G.root,{throwIfNoEntry:!1})){if(!xa(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!An(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Mi(j).dir;if(K===j)throw new o(G.label);j=K}if(!xa(j).isDirectory())throw new o(G.label);for(let K of U){Iu(K,{mode:448});let re=An(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function Gu(G){if(!An(G.root,{throwIfNoEntry:!1}))return null;if(!xa(G.root).isDirectory())throw new o(G.label);return Xr(G.root)}function Ta(G){let U=Gu(G);if(!U)throw new o(G.label);return U}function Dy(G,U,j,K){let re=An(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Ni(Ta(G.scope),Xr(U),G.scope.label)}function Ni(G,U,j){let K=Pa(G,U);if(K===".."||K.startsWith(`..${Di}`)||Mu(K))throw new o(j)}function Ny(G){try{wa(G)}catch{}}import{dirname as xr,isAbsolute as zy,join as _r,relative as $y,resolve as ar,sep as By}from"node:path";var d=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var zu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Ly=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,$u=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Wy=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^${Wy}/(${d.source.slice(1,-1)})/${Fy}$`);function Gy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function Bu(G){if(w(G))try{return N(G),null}catch(U){return U instanceof Error?U.message:String(U)}return d.test(G)?null:`Local rulebook sources must be bare names matching ${d}: ${G}`}function N(G){if(G.startsWith("github:"))throw Error(`Invalid rulebook source: ${G}`);let U=G.match(zu);if(!U?.[1]||!U[2]||!U[3])throw Error(`Invalid GitHub rulebook source: ${G}`);let j=U[3].lastIndexOf("/");if(j<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);let K=U[3].slice(0,j),re=U[3].slice(j+1);if(!K||!$u.test(K))throw Error(`GitHub rulebook refs must use valid path segments: ${G}`);if(!re||!d.test(re))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);return{owner:U[1],repo:U[2],ref:K,path:Gy(re),name:re}}function Z(G){return Ly.test(G)}function ae(G){return $u.test(G)}function w(G){return zu.test(G)}function lt(G){if(!d.test(G))throw Error(`Local rulebook sources must be bare names matching ${d}: ${G}`)}var Uu="rule.json",Li="policy.json",Hu=".cc-safety-net",Uy="rules",Hy="CC_SAFETY_NET_HOME",ju="`cc-safety-net rule update`";function jy(G){return ar(G,he)}function _(G){return _r(jy(G),Uu)}function h(G){return _r(ar(G),Hu,Li)}function ke(G,U={}){return U.userConfigDir??(U.userConfigPath?xr(U.userConfigPath):_r(Vy(G),Uy))}function Vy(G){let U=G.env.get(Hy);return U?ar(an(U)):_r(G.home,Hu)}function W(G,U={}){return _r(ke(G,U),Uu)}function l(G,U={}){return _r(xr(ke(G,U)),Li)}function L(G,U){let j=Pn();return Nt(h(U.cwd),G.paths,j)===Nt(ar(l(G,U)),G.paths,j)}function X(G,U){let j=U.userConfigPath??W(G,U),K=U.projectConfigPath??_(U.cwd),re=Je(G,U),oe=Ye(K,U.cwd);return{userConfigPath:j,projectConfigPath:K,userScope:re,projectScope:oe,userConfigTarget:i(re,j),projectConfigTarget:i(oe,K)}}function Je(G,U){let j=U.userConfigPath?xr(xr(ar(U.userConfigPath))):xr(ar(U.userConfigDir??ke(G,U)));return S(j,"user policy")}function Ye(G,U){let j=ar(U),K=ar(G),re=$y(j,K);if(re!==".."&&!re.startsWith(`..${By}`)&&!zy(re))return S(j,"project policy");return S(xr(xr(K)),"project policy")}function M(G,U){return _r(G,U,ge)}var Sn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),C=/^[a-zA-Z][a-zA-Z0-9_-]*$/,I=256,Vt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Vu=new Set(["python","python3","python2","node","ruby","perl"]),Wi=/^python(?:[23](?:\.\d+)*)?$/,Tn=new Set(["awk","gawk","nawk","mawk"]),Fi=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var qu="Rulebook exceeds CC Safety Net's safe validation limits.",Ku="Additional rulebook validation errors were omitted.",Dn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Yu(G){if(Ia(G.allowed_commands,Dn.maxAllowedCommands)||Ia(G.rules,Dn.maxRules)||Ia(G.tests,Dn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Dn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Dn.maxStringCodeUnits||oe&&re.length>Dn.maxFixtureCommandCodeUnits||re.length>U)return!1;return U-=re.length,!0};if(!K(G.name)||!K(G.version)||!K(G.description)||!K(G.author)||!K(G.migrated_from))return!1;if(Array.isArray(G.allowed_commands)){for(let re of G.allowed_commands)if(!K(re))return!1}if(Array.isArray(G.rules))for(let re of G.rules){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.name)||!K(oe.command)||!K(oe.subcommand)||!K(oe.reason)||!K(oe.intent))return!1;let de=oe.match&&typeof oe.match==="object"?oe.match:{};for(let Se of[oe.block_args,de.command_path,de.any_args,de.exclude_args]){if(!Array.isArray(Se))continue;if(Se.length>Dn.maxBlockArgsPerRule||Se.length>j)return!1;j-=Se.length;for(let we of Se)if(!K(we))return!1}}if(Array.isArray(G.tests))for(let re of G.tests){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.command,!0)||!K(oe.expect)||!K(oe.rule))return!1}return!0}function Ia(G,U){return Array.isArray(G)&&G.length>U}var ka=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ye=64,be="Rule config exceeds CC Safety Net's safe source limit.";function Mt(G){return kt(G).toLowerCase()}function kt(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}function dn(G,U){let j=new Set,K=!1;for(let re of G){if(re==="--"){K=!0;continue}if(K)continue;if(re.startsWith("-")&&!re.startsWith("--")&&re.length>1)for(let oe=1;oe<re.length;oe++){let de=re[oe];if(!de||!/[a-zA-Z]/.test(de))break;let Se=`-${de}`;if(j.add(Se),U?.shortOptsWithValue?.has(Se))break}}return j}var qy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Oa=new Set(["--init-file","--rcfile"]);function Ma(G,U,j,K){let re=!1,oe=0,de=!1,Se=!1,we=!1;for(let We=1;We<U.length;We++){let mt=U[We];if(mt===void 0)break;if(G==="ksh"&&mt==="o"&&We+1<U.length){if(K==="argv"){let gt=U.slice(We+1);if(U[0]==="-"&&(gt==="c"||gt[0]==="-"&&gt.endsWith("c")))de=!0}break}if(G==="ksh"&&mt==="o"&&We+1===U.length&&(j?.startsWith("-")||j?.startsWith("+")))break;if(G==="zsh"&&mt==="o"&&We+1<U.length)break;if(K==="startup"&&mt==="i")re=U[0]==="-";if(K==="argv"&&U[0]==="-"&&mt==="c")de=!0;if(K==="argv"&&mt==="n")we=U[0]==="-";if(K==="argv"&&mt==="s")Se=U[0]==="-";if(!qy[G]?.includes(mt))continue;if(We+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Se,syntaxCheck:we}}function vn(G){let U=kt(G[0]??"").toLowerCase(),j=!1,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--"){let we=j&&G[oe+1]!==void 0?oe+1:null;return{command:we===null?null:G[we]??null,commandIndex:we,scriptIndex:!j&&!K&&G[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!j&&(K||G[oe+1]===void 0),syntaxCheck:re}}if(de==="-"||de[0]!=="-"&&de[0]!=="+")return{command:j?de:null,commandIndex:j?oe:null,scriptIndex:!j&&!K&&de!=="-"?oe:null,readsStdinAsCommands:!j&&(K||de==="-"),syntaxCheck:re};if(de.startsWith("--")){let we=de.split("=",1)[0]??de;if(U==="bash"&&Oa.has(we)&&!de.includes("="))oe++;continue}let Se=Ma(U,de,G[oe+1],"argv");if(Se.commandSelected)j=!0;if(Se.syntaxCheck)re=!0;if(Se.stdinMode)K=!0;oe+=Se.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!j,syntaxCheck:re}}function $o(G,U){if(U.escaped)return U.escaped=!1,!0;if(G==="\\"&&!U.inSingle)return U.escaped=!0,!0;if(G==="'"&&!U.inDouble)return U.inSingle=!U.inSingle,!0;if(G==='"'&&!U.inSingle)return U.inDouble=!U.inDouble,!0;return!1}function Gi(G){let U={inSingle:!1,inDouble:!1,escaped:!1};for(let j of Ky(G))$o(j,U);return U.inSingle||U.inDouble}function Ky(G){let U="",j={inSingle:!1,inDouble:!1,escaped:!1},K=!1,re=!0;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(!de)break;if(K){if(de===`
6
+ `||de==="\r")U+=de,K=!1,j.escaped=!1;continue}if(de==="#"&&!j.inSingle&&!j.inDouble&&re){K=!0;continue}if(U+=de,!j.inSingle&&!j.inDouble&&!j.escaped)re=/[\s;&|()<>]/.test(de);$o(de,j)}return U}var Da=new Set(["rm","find","xargs","parallel"]),Yy=new Set(["git","busybox",...Da,...Vt,...Vu,...Tn]),Zy=new Set(["python","node","ruby","perl"]);function Ae(G){let U=Mt(G);return Yy.has(U)||Nn(U)}function Nn(G){return Zy.has(Xy(G))}function Xy(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}var ut={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(G){try{let U=r(Jy(G));if(U===null)return{config:null,errors:[]};if(!U.trim())return{config:null,errors:["Config file is empty"]};let j=JSON.parse(U),K=Ze(j);if(K.errors.length>0)return{config:null,errors:K.errors};return{config:{version:1,rules:j.rules??[],overrides:j.overrides??{},transparent_wrappers:j.transparent_wrappers??[]},errors:[]}}catch(U){if(U instanceof o)return{config:null,errors:[U.message]};let j=U instanceof Error?U.message:String(U);return{config:null,errors:[U instanceof SyntaxError?"Invalid JSON":j]}}}function Jy(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),tn=(G,U)=>({path:G,message:U,kind:"custom"});function Oe(G){let U=new Set;return G.flatMap((j,K)=>{let re=Jr(j)?j.name:void 0;if(typeof re!=="string")return[];if(U.has(re.toLowerCase()))return[tn(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Re=`must be one of ${ka.join(", ")}`,Qy=/^[^/]+\/[^/]+$/,eb=["version","rules","overrides","transparent_wrappers"];function Ze(G){let U=tb(G);return{errors:ce(Xe(U,eb,(j)=>j.kind==="custom"),": "," "),sources:cb(G,U)}}function tb(G){if(!Jr(G))return[e([],"Config must be an object")];let U=Array.isArray(G.rules)&&G.rules.length>ye;return[...G.version===1?[]:[e(["version"],"must be 1")],...nb(G.rules,U),...ib(G.overrides),...ab(G.transparent_wrappers),...U?[]:ob(G.rules),...Jr(G.overrides)?Object.keys(G.overrides).filter((j)=>!Qy.test(j)).map((j)=>tn(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...lb(G.transparent_wrappers)]}function nb(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...Zu(G,ye)?[e(["rules"],be)]:[]];if(U)return[{path:["rules"],message:be,kind:"limit"}];return G.flatMap((j,K)=>{if(typeof j!=="string")return[e(["rules",K],"must be a rulebook source string"),...rb(j,1)?[e(["rules",K],"must be a non-empty rulebook source string")]:[]];return j===""?[e(["rules",K],"must be a non-empty rulebook source string")]:[]})}function Zu(G,U){let j=Xu(G);return j!==void 0&&!(j<=U)}function rb(G,U){let j=Xu(G);return j!==void 0&&!(j>=U)}function Xu(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function ob(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||j==="")return[];if(j.trim()==="")return[tn(["rules",K],"must be a non-empty rulebook source string")];let re=Bu(j);if(re)return[tn(["rules",K],re)];if(U.has(j))return[tn(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function ib(G){if(G===void 0)return[];if(!Jr(G))return[e(["overrides"],"must be an object if provided")];return Object.keys(G).flatMap((U)=>{let j=G[U];if(j==="off")return[];if(!Jr(j))return[e(["overrides",U],'must be "off" or an object')];return[...sb(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Te(j.intent)?[]:[e(["overrides",U,"intent"],Re)]]})}function sb(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...Zu(G,I)?[e(U,`must be at most ${I} characters`)]:[]];if(G==="")return[e(U,"required non-empty string")];return G.length>I?[e(U,`must be at most ${I} characters`)]:[]}function ab(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["transparent_wrappers"],"must be an array of command strings")];return G.flatMap((U,j)=>{if(typeof U!=="string")return[e(["transparent_wrappers",j],"must be a command string")];return C.test(U)?[]:[e(["transparent_wrappers",j],"must match command pattern")]})}function lb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[tn(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Ae(j))return[tn(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function cb(G,U){let j=Jr(G)?G.rules:void 0;if(!Array.isArray(j))return new Set;if(U.some((re)=>re.path.length===1&&re.path[0]==="rules"))return new Set;let K=new Set(U.filter((re)=>re.path[0]==="rules"&&typeof re.path[1]==="number").map((re)=>re.path[1]));return new Set(j.filter((re,oe)=>typeof re==="string"&&!K.has(oe)))}function Xe(G,U,j){let K=G.map((de)=>de.path[1]),re=[...new Set(K.filter((de)=>typeof de==="string"))],oe=(de,Se)=>[de.path.length===0?-1:U.indexOf(String(de.path[0])),typeof Se==="number"?Se:re.indexOf(String(Se)),j(de)?0:1];return G.map((de,Se)=>({issue:de,rank:oe(de,K[Se])})).sort((de,Se)=>de.rank[0]-Se.rank[0]||de.rank[1]-Se.rank[1]||de.rank[2]-Se.rank[2]).map((de)=>de.issue)}function ce(G,U,j){return[...new Set(G.map((K)=>{let re=Na(K.path);if(K.kind==="unknownKeys")return`${re?`${re}.`:""}unknown field "${K.message}"`;if(K.kind==="key"||K.kind==="limit"||K.path.length===0)return K.message;return`${re}${K.path.length===1?j:U}${K.message}`}))]}function Na(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Te(G){return ka.includes(G)}function Jr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=mb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var ub=`required non-empty string up to ${I} characters`,Ju="must be a non-empty array of unique non-empty strings",db="required non-empty array of non-empty strings";function mb(G){if(!lr(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Yu(G))return{errors:[qu],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(fb(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Dn.maxValidationErrors?[...U.slice(0,Dn.maxValidationErrors),Ku]:U,ruleNames:new Set(De(G).map((j)=>j.toLowerCase()))}}function De(G){let U=lr(G)?G.rules:void 0;return(Array.isArray(U)?U:[]).flatMap((j)=>{let K=lr(j)?j.name:void 0;return typeof K==="string"?[K]:[]})}function fb(G,U){return[...typeof G.name==="string"&&d.test(G.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof G.version==="string"&&G.version!==""?[]:[e(["version"],"required non-empty string")],...pb(G.allowed_commands),...gb(G.rules,U),...Cb(G.tests),...Sb(G),...vb(G)]}function pb(G){if(!Array.isArray(G))return[e(["allowed_commands"],"required array")];let U=new Set;return[...G.flatMap((j,K)=>typeof j==="string"&&C.test(j)?[]:[e(["allowed_commands",K],"must match command pattern")]),...G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[tn(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function gb(G,U){if(!Array.isArray(G))return[e(["rules"],"required array")];return[...G.flatMap((j,K)=>{if(!lr(j))return[e(["rules",K],"must be an object")];return U?yb(j,["rules",K]):hb(j,["rules",K])}),...Oe(G)]}function hb(G,U){return[...Qu(G.name,U),...ed(G.command,U),...G.subcommand===void 0||typeof G.subcommand==="string"&&C.test(G.subcommand)?[]:[e([...U,"subcommand"],"must match command pattern")],...zi(G.block_args,[...U,"block_args"],"required non-empty array",!1),...td(G.reason,U),...nd(G.intent,U)]}function yb(G,U){return[...Qu(G.name,U),...ed(G.command,U),...td(G.reason,U),...nd(G.intent,U),...bb(G.match,[...U,"match"]),...G.subcommand===void 0?[]:[e([...U,"subcommand"],"not supported in rulebook_version 2")],...G.block_args===void 0?[]:[e([...U,"block_args"],"not supported in rulebook_version 2")]]}function Qu(G,U){if(typeof G!=="string")return[e([...U,"name"],"required string")];return d.test(G)?[]:[e([...U,"name"],"must match rule name pattern")]}function ed(G,U){return typeof G==="string"&&C.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function td(G,U){return typeof G==="string"&&G!==""&&G.length<=I?[]:[e([...U,"reason"],ub)]}function nd(G,U){return G===void 0||Te(G)?[]:[e([...U,"intent"],Re)]}function bb(G,U){if(!lr(G))return[e(U,"required object")];return[...zi(G.command_path,[...U,"command_path"],db,!1),...G.any_args===void 0?[]:zi(G.any_args,[...U,"any_args"],Ju,!0),...G.exclude_args===void 0?[]:zi(G.exclude_args,[...U,"exclude_args"],Ju,!0)]}function zi(G,U,j,K){if(!Array.isArray(G))return[e(U,j)];let re=G.flatMap((oe,de)=>{if(typeof oe!=="string")return[e([...U,de],"must be a non-empty string")];return oe===""?[tn([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[tn(U,j)]:[],...K&&new Set(G).size!==G.length?[tn(U,"must not contain duplicate values")]:[]]}function Cb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["tests"],"must be an array if provided")];return G.flatMap((U,j)=>{if(!lr(U))return[e(["tests",j],"must be an object")];return[...typeof U.command==="string"&&U.command.trim()!==""?[]:[e(["tests",j,"command"],"required non-empty string")],...U.expect==="blocked"||U.expect==="allowed"?[]:[e(["tests",j,"expect"],'must be "blocked" or "allowed"')],...U.rule===void 0||typeof U.rule==="string"?[]:[e(["tests",j,"rule"],"must be a string if provided")],...U.expect==="blocked"&&typeof U.rule!=="string"?[tn(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function Sb(G){if(!Array.isArray(G.tests))return[];let U=new Set(De(G));return[...new Set(G.tests.flatMap((j)=>lr(j)&&j.expect==="blocked"&&typeof j.rule==="string"?[j.rule]:[]))].filter((j)=>!U.has(j)).map((j)=>tn(["tests"],`blocked fixture references unknown rule "${j}"`))}function vb(G){if(!Array.isArray(G.allowed_commands)||!Array.isArray(G.rules))return[];let U=new Set(G.allowed_commands.filter((j)=>typeof j==="string"));return G.rules.flatMap((j,K)=>{let re=lr(j)?j.command:void 0;if(typeof re!=="string"||U.has(re))return[];return[tn(["rules",K,"command"],`"${re}" must be listed in allowed_commands`)]})}function lr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function Q(G,U){let j=X(G,U),K;try{K=Nu(j.userConfigTarget,j.projectConfigTarget)}catch(pt){if(pt instanceof o)return Ib(j,pt.message);throw pt}let re=m(j.userConfigTarget),oe=K?{config:null,errors:[]}:m(j.projectConfigTarget),de=od(j.userConfigPath,re.errors),Se=od(j.projectConfigPath,oe.errors),we=new Set,We=re.config?La(re.config,wr(j.userConfigPath),"user",j.userScope,we):id(),mt=oe.config?La(oe.config,wr(j.projectConfigPath),"project",j.projectScope,we):id(),gt=re.config?.overrides??{},ft=oe.config?.overrides??{};return{rules:[...rd(We.rules,gt),...rd(mt.rules,ft)],transparent_wrappers:Ab(re.config,oe.config),rulebooks:[...We.rulebooks,...mt.rulebooks],errors:[...de,...Se,...We.errors,...mt.errors],warnings:[...We.warnings,...mt.warnings,...We.canValidateOverrides?Wa(gt,We.knownRuleIds,j.userConfigPath):[],...We.canValidateOverrides?Tb(ft,We.knownRuleIds,j.projectConfigPath):[],...mt.canValidateOverrides?Wa(ft,mt.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=Eb(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...Rb(j.config,j.scope,G)]}function Eb(G,U){let j=U??S(wr(wr(G)),"rules policy"),K=m(i(j,G)).config;if(!K)return null;return{config:K,scope:La(K,wr(G),"project",j)}}function Rb(G,U,j){return U.canValidateOverrides?Wa(G.overrides??{},U.knownRuleIds,j):[]}function La(G,U,j,K=S(wr(wr(U)),j==="user"?"user policy":"project policy"),re=new Set){let oe=[],de=[],Se=G.rules.flatMap((We)=>{let mt=_b(We,U,K);if(mt.errors.length>0||!mt.rulebook)return oe.push(...mt.errors),[];let gt=mt.rulebook;if(re.has(gt.name))return de.push(`duplicate active rulebook name "${gt.name}" for ${We}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return re.add(gt.name),[{rules:xb(gt),rulebook:{source:j,spec:We,name:gt.name,version:gt.version,rules:gt.rules.map((ft)=>`${gt.name}/${ft.name}`)}}]}),we=Se.flatMap((We)=>We.rules);return{rules:we,rulebooks:Se.map((We)=>We.rulebook),knownRuleIds:new Set(we.map((We)=>We.name)),errors:oe,warnings:de,canValidateOverrides:oe.length===0}}function xb(G){if(G.rulebook_version===2)return G.rules.map((U)=>({name:`${G.name}/${U.name}`,command:U.command,block_args:[],match:U.match,reason:U.reason,intent:U.intent}));return G.rules.map((U)=>({...U,name:`${G.name}/${U.name}`,match:void 0}))}function _b(G,U,j){let K=Ne(G),re=M(U,K),oe=Pb(re,j);if("error"in oe)return{rulebook:null,errors:[oe.error]};if(oe.content===null)return{rulebook:null,errors:[`missing rulebook file ${re} for ${G}; ${wb(G)}`]};let de=xe(oe.content);if("problem"in de)return{rulebook:null,errors:[`invalid rulebook ${re}: ${de.problem}; fix that file`]};if(de.rulebook.name!==K)return{rulebook:null,errors:[`rulebook name "${de.rulebook.name}" in ${re} must match source "${G}"; fix that file`]};return{rulebook:de.rulebook,errors:[]}}function Ne(G){return w(G)?N(G).name:G}function wb(G){return w(G)?`run ${ju} to vendor ${G}`:"create that file or remove that source from the rules config"}function Pb(G,U){try{return{content:r(i(U,G))}}catch(j){if(j instanceof o)return{error:j.message};throw j}}function xe(G){let U;try{U=JSON.parse(G)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:le(U)}}catch(j){return{problem:j instanceof Error?j.message:"invalid rulebook"}}}function Ab(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function rd(G,U){return G.flatMap((j)=>{let K=U[j.name];if(K==="off")return[];if(K&&typeof K==="object")return[{...j,intent:K.intent??j.intent,reason:K.reason}];return[j]})}function Wa(G,U,j){return Object.keys(G).filter((K)=>!U.has(K)).map((K)=>`unknown override key "${K}" in ${j}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Tb(G,U,j){return Object.keys(G).filter((K)=>U.has(K)).map((K)=>`project override cannot target user-scoped rule "${K}" in ${j}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function od(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function Ib(G,U){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function id(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as $b,readFileSync as Bb}from"node:fs";var sd=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Fa=new Set(sd.map((G)=>G.id)),z=sd,kb=new Map(z.map((G)=>[G.id,G.intent]));function _t(G,U){return{id:G,reason:U,intent:kb.get(G)??"manual_only"}}var Ga=[{id:"secret.basename.env",category:"Basename",label:".env",description:"Blocks exact .env files.",basename:".env"},{id:"secret.basename.npmrc",category:"Basename",label:".npmrc",description:"Blocks npm credential config files.",basename:".npmrc"},{id:"secret.basename.pypirc",category:"Basename",label:".pypirc",description:"Blocks Python package index credential files.",basename:".pypirc"},{id:"secret.basename.netrc",category:"Basename",label:".netrc",description:"Blocks machine login credential files.",basename:".netrc"},{id:"secret.basename.git-credentials",category:"Basename",label:".git-credentials",description:"Blocks Git credential storage files.",basename:".git-credentials"},{id:"secret.basename.id-rsa",category:"Basename",label:"id_rsa",description:"Blocks RSA private key basenames.",basename:"id_rsa"},{id:"secret.basename.id-ed25519",category:"Basename",label:"id_ed25519",description:"Blocks Ed25519 private key basenames.",basename:"id_ed25519"},{id:"secret.basename.id-ecdsa",category:"Basename",label:"id_ecdsa",description:"Blocks ECDSA private key basenames.",basename:"id_ecdsa"},{id:"secret.basename.credentials",category:"Basename",label:"credentials",description:"Blocks generic credentials file basenames.",basename:"credentials"}],$i={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Ob=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Mb=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],za=[{id:"secret.home.ssh",category:"Home path",label:"~/.ssh",description:"Blocks home SSH configuration and key paths.",suffixParts:[".ssh"]},{id:"secret.home.aws",category:"Home path",label:"~/.aws",description:"Blocks home AWS credential and config paths.",suffixParts:[".aws"]},{id:"secret.home.gcp",category:"Home path",label:"~/.gcp",description:"Blocks home GCP credential paths.",suffixParts:[".gcp"]},{id:"secret.home.gcloud-config",category:"Home path",label:"~/.config/gcloud",description:"Blocks home Google Cloud SDK credential paths.",suffixParts:[".config","gcloud"]},{id:"secret.home.kube-config",category:"Home path",label:"~/.kube/config",description:"Blocks home Kubernetes config files.",suffixParts:[".kube","config"]},{id:"secret.home.docker-config",category:"Home path",label:"~/.docker/config.json",description:"Blocks home Docker credential config files.",suffixParts:[".docker","config.json"]},...Mb.flatMap((G)=>Ob.map((U)=>({id:["secret.home",G.idSlug,U.slice(1)].join("."),category:"Home path",label:[G.label,U].join(""),description:["Blocks home ",G.label,U," credential backup files."].join(""),suffixParts:[...G.directoryParts,[G.basename,U].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Bi=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],ad=[{prefix:"id_rsa",slug:"id-rsa",label:"id_rsa"},{prefix:"id_dsa",slug:"id-dsa",label:"id_dsa"},{prefix:"id_ed25519",slug:"id-ed25519",label:"id_ed25519"},{prefix:"id_ecdsa",slug:"id-ecdsa",label:"id_ecdsa"},{prefix:"credentials",slug:"credentials",label:"credentials"}],Db=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],$a=ad.map((G)=>({id:`secret.variant.${G.slug}.separator`,category:"Variant",label:`${G.label}-* / ${G.label}_*`,description:`Blocks ${G.label} variants with dash or underscore suffixes.`,prefix:G.prefix})),Ba=ad.flatMap((G)=>Db.map((U)=>({id:`secret.variant.${G.slug}.${U.slice(1)}`,category:"Variant",label:`${G.label}${U}`,description:`Blocks ${G.label}${U} private credential variants.`,prefix:G.prefix,suffix:U}))),Bo={id:"secret.pattern.ssh-key-basename",category:"Pattern",label:"*_(rsa|dsa|ed25519|ecdsa)",description:"Blocks extensionless SSH private key-like basenames.",pattern:/^.*_(rsa|dsa|ed25519|ecdsa)$/},Ua=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((G)=>({id:`secret.ext.${G}`,category:"Extension",label:`.${G}`,description:`Blocks files with the .${G} extension.`,extension:G})),Ha=[{id:"secret.ext-pattern.key",category:"Extension pattern",label:".key / .keypair",description:"Blocks key and keypair extension patterns.",pattern:/^key(pair)?$/},{id:"secret.ext-pattern.keystore",category:"Extension pattern",label:".keystore / .keyring",description:"Blocks keystore and keyring extension patterns.",pattern:/^key(store|ring)$/},{id:"secret.ext-pattern.kdbx",category:"Extension pattern",label:".kdb / .kdbx",description:"Blocks KeePass database extension patterns.",pattern:/^kdbx?$/}],Qe=[...Ga,$i,...za,...$a,...Ba,Bo,...Ua,...Ha,...Bi].map((G)=>({id:G.id,category:G.category,label:G.label,...G.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in G?{paths:G.paths}:{description:G.description}})),Ui=new Set(Bi.flatMap((G)=>G.category==="Coding CLI config"?[G.id]:[])),ja=new Set(Qe.map((G)=>G.id));import{isAbsolute as Va,join as Nb,normalize as Lb,sep as Hi}from"node:path";var ji=process.platform==="win32",ld=/[*?]/;function qa(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ji?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(ld.test(K)||re==="."||re==="..")return null;return{root:K||"/",name:re}}function Uo(G,U){if(G==="~")return U;if(G.startsWith("~/"))return`${U}${G.slice(1)}`;return G}function Ka(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Uo(G.trim(),U);if(!Va(j))return"must be an absolute path or start with ~/";return Ho(j,U)}function Ya(G,U){let j=cd(G,U);if(j===null)return"must be a non-empty path string";if(!Va(j))return null;if(Ho(j,U)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var Wb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Fb="cannot cover the guard's own configuration";function cd(G,U){if(typeof G!=="string"||G.trim()==="")return null;let j=G.trim(),K=ji?j.replaceAll("\\","/"):j;return Uo(K.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),U)}function Za(G,U){let j=cd(G,U);if(j===null)return"must be a non-empty path string";let K=qa(j)?.root??j;if(ld.test(K))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Va(K))return null;if(Ho(K,U)!==null)return Wb;return Gb(K,U)?Fb:null}function Gb(G,U){let j=Vi(G),K=Vi(Nb(U,".cc-safety-net"));return j===K||j.startsWith(`${K}${Hi}`)}function Ho(G,U){let j=Vi(G),K=Vi(U);if(j===K)return"cannot be the home directory";let re=j.endsWith(Hi)?j:`${j}${Hi}`;if(K.startsWith(re))return"cannot contain the home directory";return null}function Vi(G){let U=Lb(G);if(ji)U=U.replace(/\//g,"\\").toLowerCase();if(U.length>(ji?3:1)&&U.endsWith(Hi))U=U.slice(0,-1);return U}var ud=30,qi=1,Ki=365;function dd(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var md=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function Tt(G,U){if(!G)return null;if(md.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function Xt(G,U,j){if(md.has(U))return!0;if(G?.destructiveCommandProtectionEnabled===!1)return!1;return G?.effectiveDestructiveCommandRules[U]?.enabled??j}function V(G,U){return Object.freeze(Object.fromEntries(z.map((j)=>{let K=j.activationCapability?U[j.activationCapability]:void 0,re=K?.enabled??!0,oe=G.destructiveCommandRuleOverrides[j.id],de=j.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...oe?{override:oe}:{}}:G.destructiveCommandProtectionEnabled?oe?{enabled:oe==="on",inheritedEnabled:re,changesInherited:oe==="on"!==re,source:"rule_override",...j.activationCapability?{activationCapability:j.activationCapability}:{},override:oe}:{enabled:re,inheritedEnabled:re,changesInherited:!1,source:K?.source??"built_in_default",...j.activationCapability?{activationCapability:j.activationCapability}:{}}:{enabled:!1,inheritedEnabled:re,changesInherited:!1,source:"master_disabled",...j.activationCapability?{activationCapability:j.activationCapability}:{},...oe?{override:oe}:{}};return[j.id,Object.freeze(de)]})))}function fd(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:V(G,U)})}var pd={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=zb(G,U,K),oe=new Set(j?re.map((mt)=>mt.field):[]),de=(mt,gt)=>oe.has(mt)?void 0:gt,Se=(mt,gt)=>Object.fromEntries(Object.entries(gt??{}).filter(([ft])=>!oe.has(`${mt}.${ft}`))),we=(mt,gt)=>gt?.filter((ft)=>!oe.has(`${mt}.${ft}`));return{policy:{version:1,safety:{level:de("safety.level",U.safety?.level)??G.safety.level,overrides:{...G.safety.overrides,...Se("safety.overrides",U.safety?.overrides)}},workflow:{worktree_mode:de("workflow.worktree_mode",U.workflow?.worktree_mode)??G.workflow.worktree_mode},destructive_command_protection:{enabled:de("destructive_command_protection.enabled",U.destructive_command_protection?.enabled)??G.destructive_command_protection.enabled,overrides:{...G.destructive_command_protection.overrides,...Se("destructive_command_protection.overrides",U.destructive_command_protection?.overrides)},allow_paths:Xa(G.destructive_command_protection.allow_paths,we("destructive_command_protection.allow_paths",U.destructive_command_protection?.allow_paths))},secret_protection:{enabled:de("secret_protection.enabled",U.secret_protection?.enabled)??G.secret_protection.enabled,overrides:{...G.secret_protection.overrides,...Se("secret_protection.overrides",U.secret_protection?.overrides)},deny_paths:Xa(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:Xa(G.secret_protection.allow_paths,we("secret_protection.allow_paths",U.secret_protection?.allow_paths))},audit:G.audit},weakenings:re.map((mt)=>mt.message)}}function Xa(G,U){return[...new Set([...G,...U??[]])]}function zb(G,U,j){let K=U.safety?.level,re=ki[j];return[...K&&pd[K]<pd[G.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${G.safety.level} -> ${K}`}]:[],...Zr.flatMap((oe)=>U.safety?.overrides?.[oe]===!1&&(G.safety.overrides[oe]??re[oe])?[{field:`safety.overrides.${oe}`,message:`project policy disables ${oe}`}]:[]),...U.workflow?.worktree_mode===!0&&!G.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...U.destructive_command_protection?.enabled===!1&&G.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...U.secret_protection?.enabled===!1&&G.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...gd("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...gd("secret_protection.overrides",U.secret_protection?.overrides,(oe)=>G.secret_protection.enabled&&(G.secret_protection.overrides[oe]==="on"?!0:G.secret_protection.overrides[oe]!=="off"&&!Ui.has(oe))),...G.destructive_command_protection.enabled?hd(G.destructive_command_protection.allow_paths,U.destructive_command_protection?.allow_paths).map((oe)=>({field:`destructive_command_protection.allow_paths.${oe}`,message:`project policy adds destructive allow path: ${oe}`})):[],...G.secret_protection.enabled?hd(G.secret_protection.allow_paths,U.secret_protection?.allow_paths).map((oe)=>({field:`secret_protection.allow_paths.${oe}`,message:`project policy adds secret allow path: ${oe}`})):[]]}function gd(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function hd(G,U){return(U??[]).filter((j)=>!G.includes(j))}var el=new Set(["standard","strict","paranoid"]),te={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:ud}};function Sd(G,U){let j=Kb(l(G,U),G.home),K=L(G,U)?{exists:!1,policy:F(),errors:[]}:Me(h(U.cwd),G.home),re=ue(K.parsed,G.home),oe=v(n.projectTightenOnly,G.env),de=j.gui??te,Se=Object.keys(re.policy).length>0?ee(de,re.policy,oe,Tu(de.safety.level,G.env)):void 0,we=[...j.errors,...K.errors,...re.diagnostics],We=(j.fallback==="defaults"&&Se?"salvaged":j.fallback)??(j.gui?void 0:K.fallback)??(we.length>0?"salvaged":void 0),mt=re.policy.safety?.level&&Se?.policy.safety.level===re.policy.safety.level?"project":j.levelPresent?"user":"default";return{...Se?Qa(Se.policy):j.policy,errors:we,...We?{fallback:We}:{},...K.exists?{policyScopes:{levelScope:mt,weakenings:Se?.weakenings??[],weakeningsIgnored:oe}}:{}}}var Ub="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!En(G))return{policy:{},diagnostics:[]};let j=En(G.safety)?G.safety:{},K=En(G.workflow)?G.workflow:{},re=En(G.destructive_command_protection)?G.destructive_command_protection:{},oe=En(G.secret_protection)?G.secret_protection:{},de={...el.has(j.level)?{level:j.level}:{},...En(j.overrides)?yd({overrides:vd(j.overrides,Zr,["safety","overrides"],Pr)}):{}},Se={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Yi(re.overrides,Fa,Rd,Pr)}:{},...re.allow_paths!==void 0?{allow_paths:eo(re.allow_paths,Ka,U,["destructive_command_protection","allow_paths"],Pr)}:{}},we={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Yi(oe.overrides,ja,xd,Pr)}:{},...oe.deny_paths!==void 0?{deny_paths:eo(oe.deny_paths,Ya,U,["secret_protection","deny_paths"],Pr)}:{},...oe.allow_paths!==void 0?{allow_paths:eo(oe.allow_paths,Za,U,["secret_protection","allow_paths"],Pr)}:{}};return{policy:yd({safety:de,workflow:typeof K.worktree_mode==="boolean"?{worktree_mode:K.worktree_mode}:{},destructive_command_protection:Se,secret_protection:we}),diagnostics:G.audit===void 0?[]:[Ub]}}function vd(G,U,j,K){return Object.fromEntries(U.flatMap((re)=>{let oe=G[re];if(typeof oe==="boolean")return[[re,oe]];if(oe!==void 0)K(e([...j,re],tl));return[]}))}function yd(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var Pr=()=>{return},tl="must be a boolean",nl="must be an object if provided",Ed=`must be an integer between ${qi} and ${Ki}`,Rd={path:["destructive_command_protection","overrides"],label:"destructive command"},xd={path:["secret_protection","overrides"],label:"secret protection"},et=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function tt(G,U){let j=[];return{policy:_d(G,U,(re)=>{j.push(re)}),issues:j}}function E(G,U){return _d(G,U,Pr)}function _d(G,U,j){if(!En(G))return j(e([],"Config must be an object")),F();if(G.version!==1)j(e(["version"],"must be 1"));let K=Qr(G.safety,["safety"],["level","overrides"],j),re=Qr(K.overrides,["safety","overrides"],Zr,j),oe=Qr(G.workflow,["workflow"],["worktree_mode"],j),de=Qr(G.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],j),Se=Qr(G.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],j),we=Qr(G.audit,["audit"],["retention_days"],j);return wd(G,et,[],j),{version:1,safety:{level:Hb(K.level,j),overrides:vd(re,Zr,["safety","overrides"],j)},workflow:{worktree_mode:Ja(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:Ja(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Yi(de.overrides,Fa,Rd,j),allow_paths:eo(de.allow_paths,Ka,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:Ja(Se.enabled,["secret_protection","enabled"],!0,j),overrides:Yi(Se.overrides,ja,xd,j),deny_paths:eo(Se.deny_paths,Ya,U,["secret_protection","deny_paths"],j),allow_paths:eo(Se.allow_paths,Za,U,["secret_protection","allow_paths"],j)},audit:{retention_days:jb(we.retention_days,j)}}}function Qr(G,U,j,K){if(G===void 0)return{};if(!En(G))return K(e(U,nl)),{};return wd(G,j,U,K),G}function wd(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function Hb(G,U){if(G===void 0)return"standard";if(el.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Ja(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,tl));return j}function jb(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=qi&&G<=Ki))U(e(["audit","retention_days"],Ed));return dd(G)}function Yi(G,U,j,K){if(G===void 0)return{};if(!En(G))return K(e(j.path,nl)),{};return Object.fromEntries(Object.entries(G).flatMap(([re,oe])=>{if(!U.has(re))return K({path:[...j.path,re],message:`unknown ${j.label} rule id "${re}"`,kind:"key"}),[];if(oe==="on"||oe==="off")return[[re,oe]];return K(e([...j.path,re],'must be "on" or "off"')),[]}))}function eo(G,U,j,K,re){if(G===void 0)return[];if(!Array.isArray(G))return re(e(K,"must be an array of paths")),[];return G.flatMap((oe,de)=>{let Se=U(oe,j);if(Se===null)return[oe];return re(typeof oe==="string"?tn([...K,de],Se):e([...K,de],Se)),[]})}function En(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function F(){return structuredClone(te)}function Le(G,U){let j=T({safety:$e(G.safety)},U),K=V({destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides},j.capabilities),re=Object.values(K),oe=re.filter((de)=>de.source!=="catastrophic");return{selectedPreset:G.safety.level,effectiveLevel:j.effectiveLevel,capabilities:j.capabilities,rules:K,counts:{enabled:oe.filter((de)=>de.enabled).length,disabled:oe.filter((de)=>!de.enabled).length,effectiveCustomizations:re.filter((de)=>de.changesInherited).length}}}function Me(G,U){if(!$b(G))return{exists:!1,policy:F(),errors:[]};try{let j=Bb(G,"utf-8");if(!j.trim())return{exists:!0,policy:F(),errors:[`${G}: Config file is empty`],fallback:"defaults"};let K=JSON.parse(j),re=tt(K,U);if(re.issues.length===0)return{exists:!0,parsed:K,policy:re.policy,errors:[]};return{exists:!0,parsed:K,policy:re.policy,errors:re.issues.map((oe)=>`${G}: ${qb(oe)}`),fallback:En(K)?"salvaged":"defaults"}}catch(j){let K=j instanceof Error?j.message:String(j);return{exists:!0,policy:F(),errors:[`${G}: ${j instanceof SyntaxError?"Invalid JSON":K}`],fallback:"defaults"}}}var Vb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[nl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[tl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Ed,`not an integer between ${qi} and ${Ki}`]]);function qb(G){let U=Na(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=Vb.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function Kb(G,U){let j=Me(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!En(K))return{policy:Cd(),errors:[]};let re=E(K,U);return{policy:Qa(re),gui:re,errors:[],levelPresent:bd(K)}}if(j.parsed===void 0)return{policy:Cd(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:Qa(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:bd(j.parsed)}}function bd(G){let U=En(G)&&En(G.safety)?G.safety:{};return el.has(U.level)}function Fe(G){let U=Object.entries(G),j=new Set(U.flatMap(([K,re])=>re==="on"?[K]:[]));return[...new Set([...[...Ui].filter((K)=>!j.has(K)),...U.flatMap(([K,re])=>re==="off"?[K]:[])])]}function Cd(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function Qa(G){return{safety:$e(G.safety),worktreeMode:G.workflow.worktree_mode,destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides,destructiveCommandAllowPaths:G.destructive_command_protection.allow_paths,secretProtection:{enabled:G.secret_protection.enabled,disabledRules:Fe(G.secret_protection.overrides),denyPaths:G.secret_protection.deny_paths,allowPaths:G.secret_protection.allow_paths}}}function $e(G){let U={...G.overrides.fail_closed!==void 0?{failClosed:G.overrides.fail_closed}:{},...G.overrides.paranoid_rm!==void 0?{paranoidRm:G.overrides.paranoid_rm}:{},...G.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:G.overrides.paranoid_interpreters}:{}};return{level:G.level,...Object.keys(U).length>0?{overrides:U}:{}}}function k(G,U){let j=Q(G,U),K=Sd(G,U),re={rules:j.rules,transparentWrappers:j.transparent_wrappers,safety:K.safety,worktreeMode:K.worktreeMode,destructiveCommandProtectionEnabled:K.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:K.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:K.destructiveCommandAllowPaths,secretProtection:{enabled:K.secretProtection.enabled??!0,disabledRules:K.secretProtection.disabledRules??[],denyPaths:K.secretProtection.denyPaths,allowPaths:K.secretProtection.allowPaths??[]}},oe={...j.userConfig?.overrides,...j.projectConfig?.overrides},de=Object.freeze(Object.fromEntries(re.rules.map((Se)=>{let we=j.rulebooks.find((mt)=>mt.rules.includes(Se.name)),We=oe[Se.name];return[Se.name,Object.freeze({id:Se.name,...we?{rulebook:Object.freeze({name:we.name,version:we.version}),...Jb(we.spec)?{source:we.spec}:{}}:{},...We&&typeof We==="object"?{override:Object.freeze({type:"reason",reason:We.reason})}:{}})]})));return _e(re,Yb(j,K),de,K.policyScopes)}function je(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function Yb(G,U){let j=Xb(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:Qb(G.errors.length>0?Zb(G.errors):void 0,G.warnings.length>0?ol(G.warnings.join("; ")):void 0,j)}}function Zb(G){return`${ol(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Xb(G){if(G.errors.length===0)return;let U=G.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${G.errors.join("; ")}. Enforcing ${U}; the invalid values are not active. Fix the policy file manually`}function Jb(G){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(G)}function _e(G,U,j=Object.freeze({}),K){let re=rl(structuredClone(G)),oe=K?{policyScopes:rl(structuredClone(K))}:{};if(!U)return Object.freeze({state:"ready",policy:re,diagnostics:Object.freeze([]),ruleMetadata:j,...oe});return Object.freeze({state:"degraded",policy:re,diagnostics:Object.freeze([...U.diagnostics]),reason:U.reason,ruleMetadata:j,...oe})}function rl(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))rl(U);return Object.freeze(G)}function Qb(...G){return ol(G.filter((U)=>!!U).join("; "))}function ol(G){return/[.!?]$/.test(G)?G:`${G}.`}function Ue(G){let U=G.effectiveCapabilities,j=G.strict??U.fail_closed.enabled,K=G.paranoidRm??U.paranoid_rm.enabled,re=G.paranoidInterpreters??U.paranoid_interpreters.enabled,oe={fail_closed:il(U.fail_closed,G.strict,"strict"),paranoid_rm:il(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:il(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:fd(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Ea({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function il(G,U,j){if(U===void 0||U===G.enabled)return G;return{enabled:U,source:"capability_override",sources:[...G.sources,`analysis options.${j}`]}}import{dirname as zw,isAbsolute as $w,join as Bw,parse as Uw,resolve as Hw,sep as jw}from"node:path";function jo(G,U){if(G!=="powershell")return U[0]?.provenance==="command-substitution";let j=U[0]?.text==="&"||U[0]?.text==="."?1:0,K=U[j]?.provenance;return K!==void 0&&K!=="literal"}var eC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Zi(G,U){return G?.provenance==="literal"&&!G.quoted&&G.raw===U&&G.text===U}function Vo(G){let U=Zi(G.words[0],"time")?1:0,j=U===1&&Zi(G.words[U],"-p")?U+1:U,K=U===1&&Zi(G.words[j],"--")?j+1:j,re=Zi(G.words[K],"!")?K+1:K,oe=G.words.slice(re).find((de)=>!eC.test(de.text));return oe?.provenance==="literal"?oe.text:void 0}var cr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Xi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function tC(G){return Object.freeze({...G,span:Object.freeze(G.span),words:Object.freeze(G.words),redirections:Object.freeze(G.redirections.map((U)=>Object.freeze({...U,span:Object.freeze(U.span),...U.heredoc?{heredoc:Object.freeze({...U.heredoc,bodySpan:Object.freeze(U.heredoc.bodySpan),terminatorSpan:Object.freeze(U.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(G.nested.map((U)=>mn(U)))})}function Ji(G,U,j){G.push(j),U.reset()}function Qi(G){let U=[];return{parts:U,push:(j,K,re)=>{if(K<=j)return;U.push({raw:G.slice(j,K),span:{start:j,end:K},provenance:re})}}}function sl(G){let U=G.parts??[{raw:G.raw,span:G.span,provenance:G.provenance}];return Object.freeze({kind:"word",...G,span:Object.freeze(G.span),parts:Object.freeze(U.map((j)=>Object.freeze({...j,span:Object.freeze(j.span)})))})}function to(G,U,j,K,re,oe,de){return sl({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function mn(G){return Object.freeze({...G,span:Object.freeze(G.span),issues:Object.freeze(G.issues.map((U)=>Object.freeze({...U}))),nodes:Object.freeze(G.nodes.map((U)=>{if(U.kind==="command")return tC(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:mn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function al(G,U,j){if(U>=j||Ad(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Ad(G[de]??"")){let Se=G[de]??"";if(Se==="'"){re=!0;let we=Pd(G,de+1,j,"'");K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==='"'){re=!0;let we=Pd(G,de+1,j,'"');K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==="\\"){re=!0;let we=G[de+1];if(!we||we===`
7
7
  `||we==="\r"){oe=!0;break}K+=we,de+=2;continue}if(Se==="`"||G.startsWith("$(",de)||G.startsWith("${",de)||G.startsWith("<(",de)||G.startsWith(">(",de))oe=!0;K+=Se,de++}return{delimiter:K,quoted:re,next:de,ambiguous:oe}}function ll(G,U,j,K){let re=[],oe=U;for(let de of K){let Se=oe,we=!1;while(oe<j){let We=nC(G,oe,j);if((de.stripTabs?We.text.replace(/^\t+/,""):We.text)===de.delimiter){de.attach({body:de.stripTabs?rC(G.slice(Se,oe)):G.slice(Se,oe),delimiter:de.delimiter,quotedDelimiter:de.quotedDelimiter,bodySpan:{start:Se,end:oe},terminatorSpan:{start:oe,end:We.contentEnd}}),oe=We.next,we=!0;break}if(We.next<=oe)break;oe=We.next}if(we)continue;return re.push({code:"unterminated-heredoc",message:`heredoc delimiter ${de.delimiter} was not found`}),{next:j,issues:re,terminated:!1}}return{next:oe,issues:re,terminated:!0}}function Pd(G,U,j,K){let re="",oe=U;while(oe<j&&G[oe]!==`
8
8
  `&&G[oe]!=="\r"){let de=G[oe]??"";if(de===K)return{text:re,next:oe+1,closed:!0};if(K==='"'&&de==="\\"&&G[oe+1]){let Se=G[oe+1]??"";re+=["$","`",'"',"\\"].includes(Se)?Se:`\\${Se}`,oe+=2;continue}re+=de,oe++}return{text:re,next:oe,closed:!1}}function Ad(G){return G!=="\r"&&(/[\s;&|<>)]/u.test(G)||G==="`")}function nC(G,U,j){let K=U;while(K<j&&G[K]!==`
9
9
  `)K++;let re=K>=j?j:K+1;return{text:G.slice(U,K),contentEnd:K,next:re}}function rC(G){return G.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Md=new Set(["&&","||","|","|&"]),oC=new Set(["!","do","elif","else","if","then","until","while"]);function Dd(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return mn({kind:"program",dialect:"posix",source:G,span:j,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${U.maxInputLength} UTF-16 code units`}],nodes:[]});let K={wordsUsed:0,maxWords:U.maxWords,quotedExpansionEnd:1/0},re=ns(G,0,G.length,U,K,0),oe=fC(G,K.quotedExpansionEnd,re.nodes)?[...re.issues,Wd]:re.issues;return mn({kind:"program",dialect:"posix",source:G,span:j,status:os(oe,re.limited),issues:oe,nodes:re.nodes})}function ns(G,U,j,K,re,oe,de){let Se=[],we=[],We=Xi(),mt=[],gt=()=>{if(We.words.length===0&&We.redirections.length===0)return;let pt={start:We.start,end:We.end},ht=We.words.map((yt)=>yt.text);Ji(Se,We,{kind:"command",dialect:"posix",source:G.slice(pt.start,pt.end),span:pt,words:We.words,redirections:We.redirections,nested:We.nested,displayText:we.length>0&&Se.length===0?G.slice(U,j):ht.join(" ")})},ft=U;while(ft<j){let pt=G[ft];if(!pt)break;if(de&&pt===de)return gt(),Od(Se,we),{nodes:Se,issues:we,next:ft+1,closed:!0,limited:!1,pendingHeredocs:mt};if(Ko(pt)){if(pt===`
@@ -45,5 +45,5 @@ var ca="CC Safety Net could not analyze the command because it exceeds safe anal
45
45
  `:At),j,K,re,oe,de)):[],...pt?[]:(We.masked.match(Lc)??[]).map(Se),...ft?(U.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Se):[]]}var Hc={"(":")","[":"]","{":"}"},jg="and|elif|else|if|in|is|not|of|or|return|while|yield",$A=new RegExp(`(?:^|[^\\w$])(?:${jg})$`),BA=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${jg})\\s*\\(|/\\*`),UA=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function HA(G,U){return BA.test(G)||G.split(`
46
46
  `).some((j)=>{let K=j.indexOf(U);return K>=0&&/[()[\]{}]/.test(j.slice(K))})}function jA(G){return Array.from(G.matchAll(/[A-Za-z_$][\w$]*/g),(U)=>qg(U[0])).some((U)=>U.some((j)=>UA.test(j)))}var VA=new Set(["cmd","powershell","pwsh"]);function qA(G,U){let j=Po(G.masked,U),K=Hc[G.masked[j]??""];if(K===void 0||K==="}")return!1;let re=G.masked.indexOf(K,j+1),oe=G.masked.slice(j+1,re);return re!==-1&&/^\s*,[\w\s,]*$/.test(oe)&&/^[,)]/.test(G.masked.slice(Po(G.masked,re+1)))&&!G.literals.some((de)=>de.tokenStart>j&&de.tokenStart<re&&(Fc.has(de.text)||lo(un(de.text).toLowerCase())||VA.has(un(de.text).toLowerCase().replace(/\.exe$/,""))))}function KA(G){let U=[];return G.split("").map((j,K)=>{let re=U.at(-1)??-1;if(j in Hc)U.push(K);if(j===")"||j==="]"||j==="}")U.pop();return re})}function YA(G,U,j,K){let re=j[U.tokenStart]??-1,oe=G[re]??"",de=wo(G,U.tokenStart),Se=Po(G,U.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(G.slice(Math.max(0,de-3),de+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(G.slice(Se,Se+8)))return!0;if(K&&(oe==="["||oe==="("))return!1;let we=G[de],We=G[Se];if(oe==="{"&&we===":")return nT(G,de);let mt=(we===oe||we===",")&&(We===","||We===Hc[oe]||oe==="{"&&We===":");if(oe!=="(")return mt&&oe!=="";return mt&&(we===","||We===",")&&rT(G,re)}var ZA=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,XA=/^\s*\.\s*write_(?:text|bytes)\s*\(/,JA=/(?:^|[^\w$.])open\s*$/,QA=/^[bt]*[awx][abtwx]*$/,eT=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function tT(G,U,j){let K=j[U.tokenStart]??-1;if(G.masked[K]!=="(")return!1;let re=wo(G.masked,U.tokenStart),oe=Po(G.masked,U.tokenEnd),de=G.masked[oe],Se=G.masked.slice(Math.max(0,K-40),K);if(ZA.test(Se))return(re===K||G.masked[re]===",")&&(de===","||de===")")&&!G.literals.some((We)=>We.tokenStart>K&&We.tokenStart<U.tokenStart)&&XA.test(G.masked.slice(ds(G.masked,K+1)+1));if(re!==K||de!==",")return!1;if(eT.test(Se))return!0;if(!JA.test(Se))return!1;let we=G.literals.find((We)=>/^,\s*(?:mode\s*=\s*)?$/.test(G.masked.slice(oe,We.tokenStart)));return we!==void 0&&QA.test(we.text)&&/^[,)]/.test(G.masked.slice(Po(G.masked,we.tokenEnd)))}function nT(G,U){let j=wo(G,U),K=/[\w$]*$/.exec(G.slice(Math.max(0,j-63),j+1))?.[0]??"",re=G[wo(G,j+1-K.length)];return re==="{"||re===","}function rT(G,U){let j=wo(G,U),K=G.slice(Math.max(0,j-7),j+1);return!/[\w$)\]]$/.test(K)||$A.test(K)}function oT(G){let U=Uc(G);if(U==="python")return"python";if(U==="osascript")return"opaque";return U==="node"||U==="bun"||U==="deno"?"javascript":"simple"}var iT={python:"#",javascript:"/"};function sT(G,U){if(U==="opaque")return{kind:"unmaskable"};let j={masked:G.split(""),literals:[]};return Vg(G,0,U,j,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:j.masked.join(""),literals:j.literals}}function Vg(G,U,j,K,re){let oe=0;for(let de=U;de<G.length;de++){let Se=G[de]??"";if(re&&Se==="}"&&oe===0)return de;if(re&&Se===iT[j])return null;if(Se==="{")oe++;if(Se==="}")oe--;if(j==="simple"&&(Se==="`"||Se==="%"||Se==="<")){if(fA.test(G.slice(de)))return null}let we=Se==="'"||Se==='"'||j==="javascript"&&Se==="`"?Se:null;if(we===null)continue;if(we==="`"&&uT(G,de))return null;let We=j==="python"?lT(G,de):"",mt=j==="python"&&G.startsWith(we.repeat(3),de)?we.repeat(3):we,gt=de+mt.length,ft=we==="`"||/[fF]/.test(We),pt=de-We.length,ht=ft?aT(G,pt,gt,mt,j,K):cT(G,gt,mt);if(ht===null)return null;if(!ft){let yt=G.slice(gt,ht);if(j==="simple"&&we==='"'&&pA.test(yt))return null;K.literals.push({start:gt,text:yt,tokenStart:pt,tokenEnd:ht+mt.length}),K.masked.fill(" ",gt,ht)}K.masked.fill(" ",de,gt),K.masked.fill(" ",ht,ht+mt.length),de=ht+mt.length-1}return re?null:G.length}function aT(G,U,j,K,re,oe){let de=re==="python"?"{":"${",Se=K==="`"||K.length===3,we="";for(let We=j;We<G.length;We++){let mt=G[We]??"";if(G.startsWith(K,We))return oe.literals.push({start:j,text:we,tokenStart:U,tokenEnd:We+K.length}),We;if(!Se&&(mt===`
47
47
  `||mt==="\r"))return null;let gt=re==="python"&&(mt==="{"||mt==="}")&&G[We+1]===mt;if(!gt&&G.startsWith(de,We)){let ht=Vg(G,We+de.length,re,oe,!0);if(ht===null)return null;we+=`${de}}`,oe.masked.fill(" ",We,We+de.length),oe.masked[ht]=" ",We=ht;continue}let pt=mt==="\\"&&!(re==="python"&&G[We+1]==="{")||gt?2:1;we+=G.slice(We,We+pt),oe.masked.fill(" ",We,We+pt),We+=pt-1}return null}function lT(G,U){return mA.exec(G.slice(Math.max(0,U-3),U))?.[1]??""}function cT(G,U,j){let K=j.length===3;for(let re=U;re<G.length;re++){let oe=G[re];if(oe==="\\"){re++;continue}if(!K&&(oe===`
48
- `||oe==="\r"))return null;if(G.startsWith(j,re))return re}return null}function uT(G,U){for(let j=U-1;j>=0;j--){let K=G[j];if(!K||/\s/.test(K))continue;return/[\w$\])]/.test(K)}return!1}function dT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(ZP.has(j.toLowerCase()))return!0;let re=qg(j);if(!re.some((oe)=>XP.has(oe)))continue;if(re.length>1)return!0;if(G[wo(G,K)]===".")return!0;if(G[Po(G,K+j.length)]==="(")return!0}return!1}function qg(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((U)=>U.toLowerCase())}function wo(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function Po(G,U){for(let j=U;j<G.length;j++)if(!/\s/.test(G[j]??""))return j;return G.length}function mT(G,U,j,K,re,oe){return yT(G).flatMap((de)=>{let Se=U.getShellSyntax(de);if(Se.status==="invalid")return[];return[...Ao(Se,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...fT(Se,K)?pT(Se,K).map((we)=>({target:we,cwd:re})):[]]})}function fT(G,U){let j=Ss(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||un(er(re.text,U)).toLowerCase()!=="base64")continue;for(let oe=K+1;oe<j.length;oe++){let de=j[oe];if(de?.kind==="operator")break;if(de?.kind!=="word")continue;let Se=er(de.text,U);if(Se==="--decode"||!Se.startsWith("--")&&Se.startsWith("-")&&/[dD]/.test(Se))return!0}}return!1}function pT(G,U){return Ss(G).flatMap((j)=>j.kind==="word"?[er(j.text,U)]:j.kind==="redirection"&&j.target?[er(j.target,U)]:[]).flatMap(jc)}function jc(G){let U=hT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||gT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function gT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function hT(G){if(G.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(G))return null;if(/=/.test(G.replace(/=+$/g,"")))return null;let U=G.replace(/=+$/g,"");if(U.length%4===1)return null;return`${U.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-U.length%4)%4)}`}function yT(G){let U=[],j={inSingle:!1,inDouble:!1,escaped:!1};for(let K=0;K<G.length;K++){let re=G[K];if(!re)break;if($o(re,j))continue;if(Kg(G,K,j)){let oe=bT(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=CT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function bT(G,U){let j={inSingle:!1,inDouble:!1,escaped:!1},K=1;for(let re=U+1;re<G.length;re++){let oe=G[re];if(!oe)break;if($o(oe,j))continue;if(Kg(G,re,j)){K++,re++;continue}if(!j.inSingle&&!j.inDouble&&oe===")"){if(K--,K===0)return{body:G.slice(U+1,re),endIndex:re}}}return null}function CT(G,U){let j=!1;for(let K=U+1;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="`")return{body:G.slice(U+1,K),endIndex:K}}return null}function Kg(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function ST(G){let U=[],j=[],K=!1,re=!1,oe=!1;for(let we=0;we<G.length;we++){let We=G[we];if(We===void 0)break;if(!oe&&We==="--"){oe=!0;continue}if(oe){j.push(We);continue}let mt=/^--([^=]+)(?:=(.*))?$/.exec(We);if(mt!==null){let gt=mt[1]??"",ft=mt[2];if(gt===aA)re=!0;if(cA.has(gt))K=!0;if(ft!==void 0){if(gt===Rg)U.push(ft);continue}if(dA.has(gt)){let pt=G[we+1];if(gt===Rg&&pt!==void 0)U.push(pt);we++}continue}if(We.startsWith("-")&&We.length>1){let gt=We.slice(1),ft="",pt="";for(let yt=0;yt<gt.length;yt++){let bt=gt[yt]??"";if(lA.has(bt))K=!0;if(uA.has(bt)){ft=bt,pt=gt.slice(yt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===Eg)U.push(pt);continue}let ht=G[we+1];if(ft===Eg&&ht!==void 0)U.push(ht);we++;continue}j.push(We)}let Se=!K&&!re?j.slice(1):j;return[...U,...Se]}function qn(G){let U=G.findIndex((j)=>!Yg(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function Yg(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var vT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),ET=".env.",RT=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),xT=[".env.example.",".env.sample."];function _T(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function wT(G){return G.length>0&&!/\s/.test(G)}function ia(G,U,j,K){let re=Zg(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function Zg(G,U,j,K){try{return _i(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var PT=/[?&][^?&=/]+=/,AT=new Set(["node_modules","__pycache__"]),TT=[["vendor","bundle"],["vendor","cache"]];function IT(G,U,j,K,re){if(_T(G))return null;let oe=yn(G,U,K,re);if(!oe)return null;let de=zt(oe.split("/").pop()??""),Se=zt(oe),we=()=>wT(de)||ia(G,U,K,re),We=zt(LT(G,U,K,re));for(let ft of za){let pt=`~/${ft.suffixParts.join("/")}`;if((kg(Se,pt)||kg(We,pt))&&ir(ft.id,j))return ft.id}if(RT.has(de)||xT.some((ft)=>de.startsWith(ft)))return null;let mt=kT(oe,U,j,K,re);if(mt)return mt;if(vT.has(de))return null;for(let ft of Ga)if(de===ft.basename&&ir(ft.id,j))return ft.id;if(de.startsWith(ET)&&ir($i.id,j)&&we())return $i.id;for(let ft of $a)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){let pt=de.slice(ft.prefix.length)[0];if((pt==="-"||pt==="_")&&ir(ft.id,j)&&we())return ft.id}for(let ft of Ba)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){if(de.slice(ft.prefix.length)===ft.suffix&&ir(ft.id,j))return ft.id}if(DT(Se))return null;if(!de.includes(".")&&Bo.pattern.test(de)&&ir(Bo.id,j))return Bo.id;if(PT.test(G)&&!ia(G,U,K,re))return null;let gt=NT(de,j);if(gt)return gt;return null}function kT(G,U,j,K,re){return Bi.find((oe)=>{if(!ir(oe.id,j))return!1;switch(oe.id){case"secret.cli.claude-code":return Lt(G,Bt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=zt(G).split("/");return Lt(G,Bt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),["settings.json","settings.local.json"])||Ri(G,"~/.claude.json",U,K,re)||de.at(-1)==="settings.local.json"&&de.at(-2)===".claude"||de.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Lt(G,yn("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Bt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return Lt(G,de,["auth.json",".credentials.json"])||_o(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Bt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Se=zt(G).split("/").at(-1)??"";return Lt(G,de,["config.toml"])||Se.endsWith(".config.toml")&&Lt(G,de,[Se])}case"secret.cli.gemini":return Lt(G,Jt(Bt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let de=zt(G).split("/"),Se=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),we=K.env.get("ProgramData")?[Jt(Bt(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return Lt(G,Jt(Bt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["settings.json","google_accounts.json"])||de.at(-1)==="settings.json"&&de.at(-2)===".gemini"||(Se?.trim()?Ri(G,Se,U,K,re):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...we].some((We)=>Lt(G,yn(We,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Bt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return Lt(G,de,["config.json"])||_o(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Lt(G,Bt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Bt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Se=Bt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return Lt(G,de,["server.token"])||_o(G,de,["credentials"])||_o(G,Se,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let de=["config.toml","mcp.json"],Se=zt(G).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Lt(G,Bt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||Lt(G,Bt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=Jt(Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Se=zt(G).split("/").at(-1)??"",we=K.env.get("OPENCODE_DB")?.trim(),We=we&&we!==":memory:"?[we,`${we}-wal`,`${we}-shm`]:[];return Lt(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Lt(G,de,[Se])||We.some((mt)=>Ri(G,mt,U,K,re))}case"secret.cli.opencode.config":{let de=Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Se=K.env.get("ProgramData")?[Jt(Bt(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],we=["opencode.json","opencode.jsonc"],We=K.env.get("OPENCODE_CONFIG");return we.includes(zt(G).split("/").at(-1)??"")||Lt(G,de,["config.json"])||(We?.trim()?Ri(G,We,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((mt)=>Lt(G,yn(mt,U,K,re),we))}case"secret.cli.pi":return Lt(G,Bt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return Lt(G,Bt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=yn("~",U,K,re);return[Jt(Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),Jt(de,".local","share","amp")].some((we)=>Lt(G,we,["secrets.json"]))||_o(G,Jt(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Se=[Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),Jt(yn("~",U,K,re),".config","amp")],we=zt(G).split("/"),We=K.env.get("AMP_SETTINGS_FILE");return Se.some((mt)=>Lt(G,mt,de))||we.at(-2)===".amp"&&de.includes(we.at(-1)??"")||(We?.trim()?Ri(G,We,U,K,re):!1)}case"secret.cli.cursor":{let de=Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Se=Jt(Bt(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return Lt(G,yn("~/.cursor",U,K,re),["auth.json"])||Lt(G,de,["auth.json"])||zt(G).split("/").at(-1)==="mcp-auth.json"&&jr(zt(G),zt(Se))}case"secret.cli.cursor.config":{let de=zt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return Lt(G,Bt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=zt(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||Lt(G,Bt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||Lt(G,yn("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Lt(G,yn("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=zt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||Lt(G,yn("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),yn("~/.local/share",U,K,re)].some((de)=>Lt(G,Jt(de,"devin"),["credentials.toml"])||_o(G,Jt(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),yn("~/.config",U,K,re)].some((de)=>Lt(G,Jt(de,"devin"),["config.json"]));default:return!1}})?.id??null}var Ig=new WeakMap;function Bt(G,U,j,K,re){let oe=Ig.get(re)??new Map;Ig.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Se=oe.get(de);if(Se!==void 0)return Se;let we=yn(G?.trim()?G:U,j,K,re);return oe.set(de,we),we}function Lt(G,U,j){return j.some((K)=>Xg(G,Jt(U,K)))}function _o(G,U,j){return j.some((K)=>jr(zt(G),zt(Jt(U,K))))}function Ri(G,U,j,K,re){return Xg(G,yn(U,j,K,re))}function Xg(G,U){return zt(G)===zt(U)}function Jt(G,...U){return $n([G,...U].filter(Boolean).join("/"))}function OT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=zt(_i(G,U,re,oe));return j.some((Se)=>jr(de,zt(_i(Se,K,re,oe))))}function MT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=zt(_i(G,U,re,oe));if(!de)return!1;let Se=re.env.get("HOME")??re.home,we=Se?$n(Nt(an(Se),re.paths,oe)):"",We=zt(we),mt=re.env.get("CC_SAFETY_NET_HOME"),gt=zt(mt?$n(Nt(sa(an(mt)),re.paths,oe)):we&&$n(Nt(`${we}/.cc-safety-net`,re.paths,oe)));if(gt&&jr(de,gt))return!1;return j.some((ft)=>{let pt=qa(ft);if(pt&&Og.basename(de)!==zt(pt.name))return!1;let ht=zt(_i(pt?.root??ft,K,re,oe));if(!ht)return!1;if(We&&(We===ht||We.startsWith(ht.endsWith("/")?ht:`${ht}/`)))return!1;return jr(de,ht)&&!(pt&&de===ht)})}function DT(G){let U=G.split("/");return U.some((j)=>AT.has(j))||TT.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function NT(G,U){let j=G.lastIndexOf("."),K=j>0&&j<G.length-1?G.slice(j+1):"";if(K==="")return null;for(let re of Ua)if(K===re.extension&&ir(re.id,U))return re.id;for(let re of Ha)if(re.pattern.test(K)&&ir(re.id,U))return re.id;return null}function zt(G){return G.toLowerCase()}function ir(G,U){return!U?.disabledRules?.includes(G)}function yn(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe)return"";if(!re)return oe;let de=qc(oe,re),Se=ra(de)?de:$n(sa(U,de)),we=$n(Nt(Se,j.paths,K));if(!jr(we,re)){if(ra(de))return we;return we===Se?oe:we}let We=we.slice(re.length);return We?`~${We}`:"~"}function kg(G,U){return G===U||G.startsWith(`${U}/`)}function LT(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe||!re)return"";let de=qc(oe,re),Se=Og.normalize(ra(de)?de:$n(sa(U,de))),we=$n(an(j.env.get("HOME")??j.home)),We=(ft)=>process.platform==="win32"?ft.toLowerCase():ft,mt=[re,we].find((ft)=>ft!==""&&jr(We(Se),We(ft)));if(mt===void 0)return"";let gt=Se.slice(mt.length);return gt?`~${gt}`:"~"}function _i(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe)return"";let de=re?qc(oe,re):oe;return $n(Nt(ra(de)?de:sa(U,de),j.paths,K))}function Vc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?$n(Nt(an(K),U.paths,j)):"",oe=$n(an(WT(er(G,U))));return{home:re,normalized:oe}}function WT(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return UP(G)}catch{return G}}function qc(G,U){if(G==="~")return U;if(G.startsWith("~/"))return Jt(U,G.slice(2));return G}function FT(G){if(process.platform==="win32")return!0;return BP.parse(G).root.length>1}function $n(G){let U=G.trim(),j=(U.includes("\\")&&FT(U)?U.replace(/\\/g,"/"):U).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(j==="/")return j;return j.replace(/\/+$/g,"")}function jr(G,U){return G===U||G.startsWith(U.endsWith("/")?U:`${U}/`)}function un(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(G,U,j){super(`CC Safety Net ${G} dependency failed`,{cause:j});this.stage=G;this.evaluation=U}}var GT={findPolicyMutation:Cg,findGitMetadataMutation:Um,resolveGitMetadata:$T,loadPolicySnapshot:k,findSensitiveTarget:Wg,analyzeCommand:mg,getModes:T},zT=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function V(G,U){let j={...GT,...U.dependencies},K=HT(G),re=wi(G)?G.command:K,oe=Cr("policy-protection",re,()=>Gm(G)),de=pn(oe,"input-candidate"),Se=pn(oe,"declared-command");if(wi(G)&&G.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Bn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:G.command,segment:G.command}}};if(de?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:uf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let we=Pn(),We=Cr("policy-protection",re,()=>j.resolveGitMetadata([G.context.executionCwd,G.context.configCwd],U.environment)),mt=Cr("policy-protection",re,()=>j.findPolicyMutation(oe,U.environment,we));if(mt){let St=re??mt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:He,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:St,segment:mt.target}}}}let gt=Cr("policy-protection",re,()=>gg(oe,U.environment,we));if(gt){let St=re??gt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:St,segment:gt.target}}}}let ft=Cr("policy-protection",re,()=>j.findGitMetadataMutation(oe,We,U.environment,we));if(ft){let St=re??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:St,segment:ft.target}}}}let pt=Cr("config-load",re,()=>j.loadPolicySnapshot(U.environment,{...U.policyOptions,cwd:G.context.configCwd})),ht=pt.policy,yt=j.getModes(ht,U.environment.env),bt={level:yt.effectiveLevel,...BT(pt)},Ct=ht.secretProtection.enabled===!1?null:Cr("secret-protection",re,()=>j.findSensitiveTarget(oe,ht.secretProtection,U.environment,we,{strict:wi(G)||de?.program.dialect==="powershell"?yt.strict:void 0}));if(Ct){let St=re??Ct.target;return{stage:"secret-protection",...bt,decision:{kind:"deny",reason:Mg,intent:"hard_stop",ruleId:Ct.ruleId,evidence:{command:St,segment:Ct.target}}}}if(!wi(G))return{stage:"non-command",...bt,decision:{kind:"allow"}};if(!G.command||G.command.trim()==="")return{...Kc("command-validation",re),...bt};let vt=Cr("command-analysis",re,()=>fg(()=>j.analyzeCommand(G.command,{cwd:G.context.executionCwd,shell:G.route.shell,policySnapshot:pt,environment:U.environment,protectedGitMetadata:We,effectiveCapabilities:yt.capabilities,strict:yt.strict,paranoidRm:yt.paranoidRm,paranoidInterpreters:yt.paranoidInterpreters,worktreeMode:yt.worktreeMode,budget:we,...U.trace?{trace:U.trace}:{}},UT(oe),oe.store),G.command,U.trace));if(vt.decision){let St=!yt.strict&&(vt.decision.ruleId==="raw-text.dangerous-command"||vt.decision.reason===di&&!zT.test(vt.decision.evidence?.segment??"")&&In(G.command)===null);return{stage:"command-analysis",...bt,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:St?{...vt.decision,unverifiedByStandardMode:!0}:vt.decision}}return{stage:"command-analysis",...bt,decision:{kind:"allow"}}}function $T(G,U){let j=[...new Set(G.filter((K)=>typeof K==="string"&&K!==""))].flatMap((K)=>U.gitMetadata(K)??[]);if(j.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(j.flatMap((K)=>K.entries))]),markerFiles:Object.freeze([...new Set(j.flatMap((K)=>K.markerFiles))]),directories:Object.freeze([...new Set(j.flatMap((K)=>K.directories))]),hooksDirectories:Object.freeze([...new Set(j.flatMap((K)=>K.hooksDirectories))])})}function BT(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function UT(G){return pn(G,"declared-command")?.program}function HT(G){try{return ie(G.input)}catch(U){let j=wi(G)?G.command:void 0;throw new p("policy-protection",Kc("policy-protection",U instanceof f?void 0:j,U),U)}}function Cr(G,U,j){try{return j()}catch(K){throw new p(G,Kc(G,K instanceof f?void 0:U,K),K)}}function Kc(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?ca:ko,ruleId:K?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...U?{evidence:{command:U,segment:U}}:{}}}}function wi(G){return G.route.kind==="command"}
49
- export{a,s,J,Pe,Be,R,nt,ze,Ce,O,D,Y,rt,c,n,qe,Ee,T,v,pe,ot,f,P,ie,fe,it,Ve,Ke,u,Ie,o,S,i,se,r,g,me,H,st,at,d,ge,he,ct,N,Z,ae,w,lt,_,h,ke,W,l,L,X,Je,Ye,M,C,I,ye,be,Ae,ut,m,e,Oe,Re,Ze,Xe,ce,Te,le,De,Q,B,Ne,xe,z,Qe,q,ee,te,ue,et,tt,E,F,Le,Me,Fe,$e,k,je,_e,Ue,y,t,ne,ve,b,x,A,dt,Ge,He,p,V};
48
+ `||oe==="\r"))return null;if(G.startsWith(j,re))return re}return null}function uT(G,U){for(let j=U-1;j>=0;j--){let K=G[j];if(!K||/\s/.test(K))continue;return/[\w$\])]/.test(K)}return!1}function dT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(ZP.has(j.toLowerCase()))return!0;let re=qg(j);if(!re.some((oe)=>XP.has(oe)))continue;if(re.length>1)return!0;if(G[wo(G,K)]===".")return!0;if(G[Po(G,K+j.length)]==="(")return!0}return!1}function qg(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((U)=>U.toLowerCase())}function wo(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function Po(G,U){for(let j=U;j<G.length;j++)if(!/\s/.test(G[j]??""))return j;return G.length}function mT(G,U,j,K,re,oe){return yT(G).flatMap((de)=>{let Se=U.getShellSyntax(de);if(Se.status==="invalid")return[];return[...Ao(Se,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...fT(Se,K)?pT(Se,K).map((we)=>({target:we,cwd:re})):[]]})}function fT(G,U){let j=Ss(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||un(er(re.text,U)).toLowerCase()!=="base64")continue;for(let oe=K+1;oe<j.length;oe++){let de=j[oe];if(de?.kind==="operator")break;if(de?.kind!=="word")continue;let Se=er(de.text,U);if(Se==="--decode"||!Se.startsWith("--")&&Se.startsWith("-")&&/[dD]/.test(Se))return!0}}return!1}function pT(G,U){return Ss(G).flatMap((j)=>j.kind==="word"?[er(j.text,U)]:j.kind==="redirection"&&j.target?[er(j.target,U)]:[]).flatMap(jc)}function jc(G){let U=hT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||gT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function gT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function hT(G){if(G.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(G))return null;if(/=/.test(G.replace(/=+$/g,"")))return null;let U=G.replace(/=+$/g,"");if(U.length%4===1)return null;return`${U.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-U.length%4)%4)}`}function yT(G){let U=[],j={inSingle:!1,inDouble:!1,escaped:!1};for(let K=0;K<G.length;K++){let re=G[K];if(!re)break;if($o(re,j))continue;if(Kg(G,K,j)){let oe=bT(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=CT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function bT(G,U){let j={inSingle:!1,inDouble:!1,escaped:!1},K=1;for(let re=U+1;re<G.length;re++){let oe=G[re];if(!oe)break;if($o(oe,j))continue;if(Kg(G,re,j)){K++,re++;continue}if(!j.inSingle&&!j.inDouble&&oe===")"){if(K--,K===0)return{body:G.slice(U+1,re),endIndex:re}}}return null}function CT(G,U){let j=!1;for(let K=U+1;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="`")return{body:G.slice(U+1,K),endIndex:K}}return null}function Kg(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function ST(G){let U=[],j=[],K=!1,re=!1,oe=!1;for(let we=0;we<G.length;we++){let We=G[we];if(We===void 0)break;if(!oe&&We==="--"){oe=!0;continue}if(oe){j.push(We);continue}let mt=/^--([^=]+)(?:=(.*))?$/.exec(We);if(mt!==null){let gt=mt[1]??"",ft=mt[2];if(gt===aA)re=!0;if(cA.has(gt))K=!0;if(ft!==void 0){if(gt===Rg)U.push(ft);continue}if(dA.has(gt)){let pt=G[we+1];if(gt===Rg&&pt!==void 0)U.push(pt);we++}continue}if(We.startsWith("-")&&We.length>1){let gt=We.slice(1),ft="",pt="";for(let yt=0;yt<gt.length;yt++){let bt=gt[yt]??"";if(lA.has(bt))K=!0;if(uA.has(bt)){ft=bt,pt=gt.slice(yt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===Eg)U.push(pt);continue}let ht=G[we+1];if(ft===Eg&&ht!==void 0)U.push(ht);we++;continue}j.push(We)}let Se=!K&&!re?j.slice(1):j;return[...U,...Se]}function qn(G){let U=G.findIndex((j)=>!Yg(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function Yg(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var vT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),ET=".env.",RT=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),xT=[".env.example.",".env.sample."];function _T(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function wT(G){return G.length>0&&!/\s/.test(G)}function ia(G,U,j,K){let re=Zg(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function Zg(G,U,j,K){try{return _i(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var PT=/[?&][^?&=/]+=/,AT=new Set(["node_modules","__pycache__"]),TT=[["vendor","bundle"],["vendor","cache"]];function IT(G,U,j,K,re){if(_T(G))return null;let oe=yn(G,U,K,re);if(!oe)return null;let de=zt(oe.split("/").pop()??""),Se=zt(oe),we=()=>wT(de)||ia(G,U,K,re),We=zt(LT(G,U,K,re));for(let ft of za){let pt=`~/${ft.suffixParts.join("/")}`;if((kg(Se,pt)||kg(We,pt))&&ir(ft.id,j))return ft.id}if(RT.has(de)||xT.some((ft)=>de.startsWith(ft)))return null;let mt=kT(oe,U,j,K,re);if(mt)return mt;if(vT.has(de))return null;for(let ft of Ga)if(de===ft.basename&&ir(ft.id,j))return ft.id;if(de.startsWith(ET)&&ir($i.id,j)&&we())return $i.id;for(let ft of $a)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){let pt=de.slice(ft.prefix.length)[0];if((pt==="-"||pt==="_")&&ir(ft.id,j)&&we())return ft.id}for(let ft of Ba)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){if(de.slice(ft.prefix.length)===ft.suffix&&ir(ft.id,j))return ft.id}if(DT(Se))return null;if(!de.includes(".")&&Bo.pattern.test(de)&&ir(Bo.id,j))return Bo.id;if(PT.test(G)&&!ia(G,U,K,re))return null;let gt=NT(de,j);if(gt)return gt;return null}function kT(G,U,j,K,re){return Bi.find((oe)=>{if(!ir(oe.id,j))return!1;switch(oe.id){case"secret.cli.claude-code":return Lt(G,Bt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=zt(G).split("/");return Lt(G,Bt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),["settings.json","settings.local.json"])||Ri(G,"~/.claude.json",U,K,re)||de.at(-1)==="settings.local.json"&&de.at(-2)===".claude"||de.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Lt(G,yn("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Bt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return Lt(G,de,["auth.json",".credentials.json"])||_o(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Bt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Se=zt(G).split("/").at(-1)??"";return Lt(G,de,["config.toml"])||Se.endsWith(".config.toml")&&Lt(G,de,[Se])}case"secret.cli.gemini":return Lt(G,Jt(Bt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let de=zt(G).split("/"),Se=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),we=K.env.get("ProgramData")?[Jt(Bt(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return Lt(G,Jt(Bt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["settings.json","google_accounts.json"])||de.at(-1)==="settings.json"&&de.at(-2)===".gemini"||(Se?.trim()?Ri(G,Se,U,K,re):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...we].some((We)=>Lt(G,yn(We,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Bt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return Lt(G,de,["config.json"])||_o(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Lt(G,Bt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Bt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Se=Bt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return Lt(G,de,["server.token"])||_o(G,de,["credentials"])||_o(G,Se,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let de=["config.toml","mcp.json"],Se=zt(G).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Lt(G,Bt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||Lt(G,Bt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=Jt(Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Se=zt(G).split("/").at(-1)??"",we=K.env.get("OPENCODE_DB")?.trim(),We=we&&we!==":memory:"?[we,`${we}-wal`,`${we}-shm`]:[];return Lt(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Lt(G,de,[Se])||We.some((mt)=>Ri(G,mt,U,K,re))}case"secret.cli.opencode.config":{let de=Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Se=K.env.get("ProgramData")?[Jt(Bt(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],we=["opencode.json","opencode.jsonc"],We=K.env.get("OPENCODE_CONFIG");return we.includes(zt(G).split("/").at(-1)??"")||Lt(G,de,["config.json"])||(We?.trim()?Ri(G,We,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((mt)=>Lt(G,yn(mt,U,K,re),we))}case"secret.cli.pi":return Lt(G,Bt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return Lt(G,Bt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=yn("~",U,K,re);return[Jt(Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),Jt(de,".local","share","amp")].some((we)=>Lt(G,we,["secrets.json"]))||_o(G,Jt(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Se=[Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),Jt(yn("~",U,K,re),".config","amp")],we=zt(G).split("/"),We=K.env.get("AMP_SETTINGS_FILE");return Se.some((mt)=>Lt(G,mt,de))||we.at(-2)===".amp"&&de.includes(we.at(-1)??"")||(We?.trim()?Ri(G,We,U,K,re):!1)}case"secret.cli.cursor":{let de=Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Se=Jt(Bt(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return Lt(G,yn("~/.cursor",U,K,re),["auth.json"])||Lt(G,de,["auth.json"])||zt(G).split("/").at(-1)==="mcp-auth.json"&&jr(zt(G),zt(Se))}case"secret.cli.cursor.config":{let de=zt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return Lt(G,Bt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=zt(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||Lt(G,Bt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||Lt(G,yn("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Lt(G,yn("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=zt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||Lt(G,yn("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),yn("~/.local/share",U,K,re)].some((de)=>Lt(G,Jt(de,"devin"),["credentials.toml"])||_o(G,Jt(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),yn("~/.config",U,K,re)].some((de)=>Lt(G,Jt(de,"devin"),["config.json"]));default:return!1}})?.id??null}var Ig=new WeakMap;function Bt(G,U,j,K,re){let oe=Ig.get(re)??new Map;Ig.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Se=oe.get(de);if(Se!==void 0)return Se;let we=yn(G?.trim()?G:U,j,K,re);return oe.set(de,we),we}function Lt(G,U,j){return j.some((K)=>Xg(G,Jt(U,K)))}function _o(G,U,j){return j.some((K)=>jr(zt(G),zt(Jt(U,K))))}function Ri(G,U,j,K,re){return Xg(G,yn(U,j,K,re))}function Xg(G,U){return zt(G)===zt(U)}function Jt(G,...U){return $n([G,...U].filter(Boolean).join("/"))}function OT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=zt(_i(G,U,re,oe));return j.some((Se)=>jr(de,zt(_i(Se,K,re,oe))))}function MT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=zt(_i(G,U,re,oe));if(!de)return!1;let Se=re.env.get("HOME")??re.home,we=Se?$n(Nt(an(Se),re.paths,oe)):"",We=zt(we),mt=re.env.get("CC_SAFETY_NET_HOME"),gt=zt(mt?$n(Nt(sa(an(mt)),re.paths,oe)):we&&$n(Nt(`${we}/.cc-safety-net`,re.paths,oe)));if(gt&&jr(de,gt))return!1;return j.some((ft)=>{let pt=qa(ft);if(pt&&Og.basename(de)!==zt(pt.name))return!1;let ht=zt(_i(pt?.root??ft,K,re,oe));if(!ht)return!1;if(We&&(We===ht||We.startsWith(ht.endsWith("/")?ht:`${ht}/`)))return!1;return jr(de,ht)&&!(pt&&de===ht)})}function DT(G){let U=G.split("/");return U.some((j)=>AT.has(j))||TT.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function NT(G,U){let j=G.lastIndexOf("."),K=j>0&&j<G.length-1?G.slice(j+1):"";if(K==="")return null;for(let re of Ua)if(K===re.extension&&ir(re.id,U))return re.id;for(let re of Ha)if(re.pattern.test(K)&&ir(re.id,U))return re.id;return null}function zt(G){return G.toLowerCase()}function ir(G,U){return!U?.disabledRules?.includes(G)}function yn(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe)return"";if(!re)return oe;let de=qc(oe,re),Se=ra(de)?de:$n(sa(U,de)),we=$n(Nt(Se,j.paths,K));if(!jr(we,re)){if(ra(de))return we;return we===Se?oe:we}let We=we.slice(re.length);return We?`~${We}`:"~"}function kg(G,U){return G===U||G.startsWith(`${U}/`)}function LT(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe||!re)return"";let de=qc(oe,re),Se=Og.normalize(ra(de)?de:$n(sa(U,de))),we=$n(an(j.env.get("HOME")??j.home)),We=(ft)=>process.platform==="win32"?ft.toLowerCase():ft,mt=[re,we].find((ft)=>ft!==""&&jr(We(Se),We(ft)));if(mt===void 0)return"";let gt=Se.slice(mt.length);return gt?`~${gt}`:"~"}function _i(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe)return"";let de=re?qc(oe,re):oe;return $n(Nt(ra(de)?de:sa(U,de),j.paths,K))}function Vc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?$n(Nt(an(K),U.paths,j)):"",oe=$n(an(WT(er(G,U))));return{home:re,normalized:oe}}function WT(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return UP(G)}catch{return G}}function qc(G,U){if(G==="~")return U;if(G.startsWith("~/"))return Jt(U,G.slice(2));return G}function FT(G){if(process.platform==="win32")return!0;return BP.parse(G).root.length>1}function $n(G){let U=G.trim(),j=(U.includes("\\")&&FT(U)?U.replace(/\\/g,"/"):U).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(j==="/")return j;return j.replace(/\/+$/g,"")}function jr(G,U){return G===U||G.startsWith(U.endsWith("/")?U:`${U}/`)}function un(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(G,U,j){super(`CC Safety Net ${G} dependency failed`,{cause:j});this.stage=G;this.evaluation=U}}var GT={findPolicyMutation:Cg,findGitMetadataMutation:Um,resolveGitMetadata:$T,loadPolicySnapshot:k,findSensitiveTarget:Wg,analyzeCommand:mg,getModes:T},zT=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function q(G,U){let j={...GT,...U.dependencies},K=HT(G),re=wi(G)?G.command:K,oe=Cr("policy-protection",re,()=>Gm(G)),de=pn(oe,"input-candidate"),Se=pn(oe,"declared-command");if(wi(G)&&G.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Bn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:G.command,segment:G.command}}};if(de?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:uf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let we=Pn(),We=Cr("policy-protection",re,()=>j.resolveGitMetadata([G.context.executionCwd,G.context.configCwd],U.environment)),mt=Cr("policy-protection",re,()=>j.findPolicyMutation(oe,U.environment,we));if(mt){let St=re??mt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:He,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:St,segment:mt.target}}}}let gt=Cr("policy-protection",re,()=>gg(oe,U.environment,we));if(gt){let St=re??gt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:St,segment:gt.target}}}}let ft=Cr("policy-protection",re,()=>j.findGitMetadataMutation(oe,We,U.environment,we));if(ft){let St=re??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:St,segment:ft.target}}}}let pt=Cr("config-load",re,()=>j.loadPolicySnapshot(U.environment,{...U.policyOptions,cwd:G.context.configCwd})),ht=pt.policy,yt=j.getModes(ht,U.environment.env),bt={level:yt.effectiveLevel,...BT(pt)},Ct=ht.secretProtection.enabled===!1?null:Cr("secret-protection",re,()=>j.findSensitiveTarget(oe,ht.secretProtection,U.environment,we,{strict:wi(G)||de?.program.dialect==="powershell"?yt.strict:void 0}));if(Ct){let St=re??Ct.target;return{stage:"secret-protection",...bt,decision:{kind:"deny",reason:Mg,intent:"hard_stop",ruleId:Ct.ruleId,evidence:{command:St,segment:Ct.target}}}}if(!wi(G))return{stage:"non-command",...bt,decision:{kind:"allow"}};if(!G.command||G.command.trim()==="")return{...Kc("command-validation",re),...bt};let vt=Cr("command-analysis",re,()=>fg(()=>j.analyzeCommand(G.command,{cwd:G.context.executionCwd,shell:G.route.shell,policySnapshot:pt,environment:U.environment,protectedGitMetadata:We,effectiveCapabilities:yt.capabilities,strict:yt.strict,paranoidRm:yt.paranoidRm,paranoidInterpreters:yt.paranoidInterpreters,worktreeMode:yt.worktreeMode,budget:we,...U.trace?{trace:U.trace}:{}},UT(oe),oe.store),G.command,U.trace));if(vt.decision){let St=!yt.strict&&(vt.decision.ruleId==="raw-text.dangerous-command"||vt.decision.reason===di&&!zT.test(vt.decision.evidence?.segment??"")&&In(G.command)===null);return{stage:"command-analysis",...bt,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:St?{...vt.decision,unverifiedByStandardMode:!0}:vt.decision}}return{stage:"command-analysis",...bt,decision:{kind:"allow"}}}function $T(G,U){let j=[...new Set(G.filter((K)=>typeof K==="string"&&K!==""))].flatMap((K)=>U.gitMetadata(K)??[]);if(j.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(j.flatMap((K)=>K.entries))]),markerFiles:Object.freeze([...new Set(j.flatMap((K)=>K.markerFiles))]),directories:Object.freeze([...new Set(j.flatMap((K)=>K.directories))]),hooksDirectories:Object.freeze([...new Set(j.flatMap((K)=>K.hooksDirectories))])})}function BT(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function UT(G){return pn(G,"declared-command")?.program}function HT(G){try{return ie(G.input)}catch(U){let j=wi(G)?G.command:void 0;throw new p("policy-protection",Kc("policy-protection",U instanceof f?void 0:j,U),U)}}function Cr(G,U,j){try{return j()}catch(K){throw new p(G,Kc(G,K instanceof f?void 0:U,K),K)}}function Kc(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?ca:ko,ruleId:K?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...U?{evidence:{command:U,segment:U}}:{}}}}function wi(G){return G.route.kind==="command"}
49
+ export{a,s,J,Pe,Be,R,nt,ze,Ce,O,D,Y,rt,c,n,Ve,Ee,T,v,pe,ot,f,P,ie,fe,it,qe,Ke,u,Ie,o,S,i,se,r,g,me,H,st,at,d,ge,he,ct,N,Z,ae,w,lt,_,h,ke,W,l,L,X,Je,Ye,M,C,I,ye,be,Ae,ut,m,e,Oe,Re,Ze,Xe,ce,Te,le,De,Q,B,Ne,xe,z,Qe,V,ee,te,ue,et,tt,E,F,Le,Me,Fe,$e,k,je,_e,Ue,y,t,ne,ve,b,x,A,dt,Ge,He,p,q};